From 375e84d663a8f4ce07999ecf1eca75504b7edb0d Mon Sep 17 00:00:00 2001 From: Christ Date: Sun, 16 Aug 2026 23:51:06 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=EF=BC=9A=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E6=9C=8D=E5=8A=A1=E4=B8=8E=E5=9F=BA=E7=A1=80?= =?UTF-8?q?=E8=AE=BE=E6=96=BD=E9=80=82=E9=85=8D=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将账号、认证、管理员、分析、自动化、卡券、聊天、商品、关键词、设置和订单能力迁移到 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_*。 --- cmd/server/main.go | 10 +- docs/architecture/lifecycle-inventory.md | 27 + docs/architecture/refactoring-master-plan.md | 1344 +++++++---------- frontend/services/api.test.ts | 7 + frontend/services/api.ts | 2 +- internal/adapter/account_login_audit.go | 84 ++ internal/adapter/account_login_audit_test.go | 76 + internal/adapter/account_login_repository.go | 316 ++++ .../adapter/account_login_repository_test.go | 152 ++ internal/adapter/account_long_login.go | 186 +++ internal/adapter/account_profile.go | 165 ++ internal/adapter/account_settings.go | 179 +++ internal/adapter/account_settings_test.go | 145 ++ internal/adapter/account_summary.go | 164 ++ internal/adapter/account_summary_test.go | 129 ++ internal/adapter/account_tasks.go | 113 ++ internal/adapter/account_tasks_test.go | 16 + internal/adapter/admin_repository.go | 62 + internal/adapter/admin_repository_test.go | 46 + internal/adapter/ai_model_client.go | 163 ++ internal/adapter/ai_model_client_test.go | 42 + internal/adapter/analytics_repository.go | 319 ++++ internal/adapter/authentication_repository.go | 151 ++ .../adapter/authentication_repository_test.go | 117 ++ .../adapter/automation_credential_wake.go | 31 + .../automation_credential_wake_test.go | 16 + internal/adapter/automation_repository.go | 221 +++ .../adapter/automation_repository_test.go | 104 ++ internal/adapter/cards_repository.go | 127 ++ internal/adapter/cards_repository_test.go | 121 ++ internal/adapter/chat_contract_conversion.go | 24 + .../adapter/chat_contract_conversion_test.go | 47 + internal/adapter/chat_repository.go | 134 ++ internal/adapter/chat_repository_test.go | 145 ++ internal/adapter/chat_sending.go | 221 +++ internal/adapter/cookie_identity.go | 42 + internal/adapter/cookie_identity_test.go | 15 + internal/adapter/cookie_session.go | 79 + internal/adapter/cookie_session_test.go | 75 + internal/adapter/database_health.go | 31 + internal/adapter/database_health_test.go | 42 + internal/adapter/default_reply_repository.go | 133 ++ .../adapter/default_reply_repository_test.go | 117 ++ internal/adapter/item_batch_preview.go | 97 ++ internal/adapter/item_batch_preview_test.go | 60 + internal/adapter/item_batch_publish.go | 382 +++++ internal/adapter/item_batch_publish_test.go | 116 ++ internal/adapter/item_batch_repository.go | 414 +++++ .../adapter/item_batch_repository_test.go | 165 ++ internal/adapter/item_catalog.go | 124 ++ internal/adapter/item_catalog_test.go | 92 ++ internal/adapter/item_publish.go | 300 ++++ internal/adapter/item_publish_images.go | 75 + internal/adapter/item_publish_images_test.go | 67 + internal/adapter/item_publish_test.go | 199 +++ internal/adapter/item_sync.go | 478 ++++++ internal/adapter/item_sync_test.go | 105 ++ internal/adapter/keyword_repository.go | 234 +++ internal/adapter/keyword_repository_test.go | 132 ++ internal/adapter/notification_repository.go | 198 +++ .../adapter/notification_repository_test.go | 90 ++ internal/adapter/order_boundary.go | 38 + internal/adapter/order_boundary_test.go | 41 + internal/adapter/order_reconciliation.go | 36 + internal/adapter/order_reconciliation_test.go | 57 + .../{server => adapter}/order_repository.go | 84 +- internal/adapter/order_repository_test.go | 48 + internal/adapter/order_runtime.go | 388 +++++ internal/adapter/order_runtime_test.go | 137 ++ internal/adapter/server_dependencies.go | 216 +++ internal/adapter/settings_repository.go | 247 +++ internal/adapter/transaction.go | 52 + internal/adapter/transaction_test.go | 33 + .../account/authentication_service.go | 123 ++ .../account/authentication_service_test.go | 182 +++ .../account/credential_repository.go | 45 + .../application/account/delete_service.go | 8 +- internal/application/account/login_audit.go | 162 ++ .../application/account/login_audit_test.go | 121 ++ internal/application/account/login_service.go | 18 +- .../application/account/long_login_service.go | 68 + .../account/long_login_service_test.go | 72 + .../application/account/profile_service.go | 26 +- .../account/profile_service_test.go | 2 +- .../application/account/qr_login_service.go | 3 + .../application/account/settings_service.go | 228 +++ .../account/settings_service_test.go | 176 +++ .../application/account/summary_service.go | 200 +++ .../account/summary_service_test.go | 174 +++ internal/application/admin/service.go | 98 ++ internal/application/admin/service_test.go | 117 ++ internal/application/analytics/models.go | 246 +++ internal/application/analytics/service.go | 375 +++++ .../application/analytics/service_test.go | 335 ++++ .../application/automation/account_tasks.go | 175 +++ .../automation/account_tasks_test.go | 134 ++ .../application/automation/credential_wake.go | 40 + .../automation/credential_wake_test.go | 59 + .../application/automation/publish_rules.go | 28 + .../automation/publish_rules_test.go | 64 + internal/application/automation/rules.go | 441 ++++++ internal/application/automation/rules_test.go | 184 +++ internal/application/automation/service.go | 107 ++ .../application/automation/service_test.go | 140 ++ internal/application/cards/service.go | 300 ++++ internal/application/cards/service_test.go | 301 ++++ internal/application/chat/send.go | 9 +- internal/application/chat/service.go | 214 +++ internal/application/chat/service_test.go | 152 +- internal/application/defaultreply/service.go | 154 ++ .../application/defaultreply/service_test.go | 180 +++ .../application/items/batch_local_publish.go | 228 +++ .../items/batch_local_publish_test.go | 133 ++ .../application/items/batch_management.go | 331 ++++ .../items/batch_management_test.go | 314 ++++ internal/application/items/batch_preview.go | 881 +++++++++++ .../items/batch_preview_persistence.go | 94 ++ .../application/items/batch_preview_test.go | 160 ++ internal/application/items/batch_publish.go | 129 +- .../application/items/batch_publish_test.go | 6 +- internal/application/items/batch_recovery.go | 149 ++ .../application/items/batch_recovery_test.go | 204 +++ internal/application/items/catalog.go | 81 + .../application/items/catalog_mutation.go | 144 ++ .../items/catalog_mutation_test.go | 109 ++ internal/application/items/catalog_test.go | 72 + .../items/category_recommendation.go | 53 + .../items/category_recommendation_test.go | 99 ++ internal/application/items/single_publish.go | 52 + .../application/items/single_publish_test.go | 22 + internal/application/items/sync.go | 155 ++ internal/application/items/sync_test.go | 129 ++ internal/application/keywords/service.go | 295 ++++ internal/application/keywords/service_test.go | 197 +++ .../application/notifications/channels.go | 8 + .../notifications/channels_test.go | 37 + .../application/orders/manual_ship_service.go | 11 +- internal/application/settings/service.go | 405 +++++ internal/application/settings/service_test.go | 238 +++ internal/auth/auth.go | 16 + internal/auth/auth_test.go | 20 + internal/automation/account_tasks.go | 19 +- internal/automation/account_tasks_test.go | 66 + .../mysql/00019_deferred_automation_tasks.sql | 2 +- internal/renewal/scheduler.go | 25 + internal/renewal/scheduler_test.go | 45 + internal/server/account_login_repository.go | 270 ---- .../account_login_repository_boundary_test.go | 22 + internal/server/account_login_service.go | 75 +- .../server/account_summary_handlers_test.go | 87 ++ .../account_task_application_adapter.go | 36 + internal/server/account_task_handlers.go | 41 +- internal/server/admin_auth_test.go | 4 +- internal/server/admin_handlers.go | 30 +- internal/server/analytics_handlers.go | 224 +-- internal/server/analytics_repository.go | 57 - internal/server/analytics_service.go | 397 ----- internal/server/api_contract.go | 4 +- internal/server/api_contract_test.go | 4 +- internal/server/application_services.go | 352 ++++- internal/server/application_services_test.go | 4 +- internal/server/auth_handlers.go | 42 +- internal/server/automation_handlers.go | 439 +----- internal/server/automation_issue_port_test.go | 49 + internal/server/automation_rule_handlers.go | 295 ++++ .../server/card_application_handlers_test.go | 135 ++ internal/server/card_batch_handlers.go | 79 +- internal/server/card_handlers.go | 283 ++-- internal/server/chat_application.go | 14 + internal/server/chat_handlers.go | 248 +-- internal/server/communication_repository.go | 154 -- internal/server/communication_service.go | 381 ----- internal/server/communication_service_test.go | 19 +- internal/server/cookie_handlers.go | 546 ++----- internal/server/cookie_handlers_test.go | 17 + internal/server/default_reply_application.go | 9 + internal/server/default_reply_handlers.go | 135 +- internal/server/extras_test.go | 4 +- internal/server/handler_errors_test.go | 4 +- internal/server/handlers_extra_test.go | 7 +- internal/server/http_client_test.go | 14 - .../server/item_batch_local_application.go | 26 + .../item_batch_management_application.go | 23 + internal/server/item_handlers.go | 893 +++-------- internal/server/item_handlers_test.go | 159 +- .../server/item_publish_batch_handlers.go | 1158 +++----------- internal/server/item_publish_images.go | 41 - internal/server/item_publish_images_test.go | 14 + internal/server/item_publish_repository.go | 257 ---- internal/server/item_publish_service.go | 431 ------ internal/server/item_publish_service_test.go | 42 +- internal/server/item_sync_application_test.go | 59 + internal/server/keyword_handlers.go | 559 +++---- internal/server/login_audit.go | 105 +- internal/server/login_audit_test.go | 47 + internal/server/mtop_cookie_session.go | 65 +- internal/server/mtop_cookie_session_test.go | 13 +- internal/server/notification_handlers.go | 195 +-- internal/server/order_handlers.go | 75 +- internal/server/order_handlers_extra_test.go | 6 +- .../server/order_model_conversion_test.go | 84 +- internal/server/order_refresh_job_handlers.go | 120 +- .../order_refresh_job_lifecycle_test.go | 260 ++++ internal/server/order_service.go | 274 ++-- .../order_service_reconciliation_test.go | 79 + internal/server/ownership_helpers.go | 91 +- .../server/ownership_secret_scope_test.go | 35 + internal/server/parser_test.go | 43 +- internal/server/platform_runtime.go | 61 +- .../server/platform_runtime_boundary_test.go | 36 + .../server/platform_runtime_scope_test.go | 2 +- internal/server/publish_batch_run_test.go | 32 +- internal/server/publish_batch_test.go | 84 ++ internal/server/qrlogin_handlers.go | 21 - internal/server/qrlogin_keyword_test.go | 3 +- internal/server/run_test.go | 20 +- internal/server/server.go | 199 ++- internal/server/server_test.go | 22 +- internal/server/settings_extra_test.go | 20 +- internal/server/settings_handlers.go | 360 ++--- .../server/settings_models_compat_test.go | 26 + internal/server/success_contract.go | 213 +-- internal/server/task_registry_test.go | 29 + internal/server/transaction_repository.go | 63 - internal/server/unit_of_work_test.go | 6 +- ...st-CMeDGrpw.js => AccountList-Bpj-f-W3.js} | 2 +- ...dList-CV-IXa79.js => CardList-D5uSws-z.js} | 2 +- .../{Chat-ChmGl-XK.js => Chat-BLyP9Pyt.js} | 2 +- ...oard-BjrV0BPa.js => Dashboard-sUNU2Eg5.js} | 2 +- ...mList-DX-qMjnd.js => ItemList-kyCurZV6.js} | 2 +- ...-D65tIfCl.js => Notifications-CyWpiVXa.js} | 2 +- ...List-DCxOUz7n.js => OrderList-Bb5NffV_.js} | 2 +- .../{Rules-D884-CgU.js => Rules-MPWRzM5C.js} | 2 +- ...tings-j3SwRFCx.js => Settings-5xhSVKHU.js} | 2 +- .../webui/static/assets/index-CYPNW7Ux.js | 2 + .../webui/static/assets/index-DK02p8DH.js | 2 - internal/webui/static/index.html | 2 +- tools/architecturecheck/main.go | 42 +- tools/architecturecheck/main_test.go | 8 +- 239 files changed, 23870 insertions(+), 7871 deletions(-) create mode 100644 docs/architecture/lifecycle-inventory.md create mode 100644 internal/adapter/account_login_audit.go create mode 100644 internal/adapter/account_login_audit_test.go create mode 100644 internal/adapter/account_login_repository.go create mode 100644 internal/adapter/account_login_repository_test.go create mode 100644 internal/adapter/account_long_login.go create mode 100644 internal/adapter/account_profile.go create mode 100644 internal/adapter/account_settings.go create mode 100644 internal/adapter/account_settings_test.go create mode 100644 internal/adapter/account_summary.go create mode 100644 internal/adapter/account_summary_test.go create mode 100644 internal/adapter/account_tasks.go create mode 100644 internal/adapter/account_tasks_test.go create mode 100644 internal/adapter/admin_repository.go create mode 100644 internal/adapter/admin_repository_test.go create mode 100644 internal/adapter/ai_model_client.go create mode 100644 internal/adapter/ai_model_client_test.go create mode 100644 internal/adapter/analytics_repository.go create mode 100644 internal/adapter/authentication_repository.go create mode 100644 internal/adapter/authentication_repository_test.go create mode 100644 internal/adapter/automation_credential_wake.go create mode 100644 internal/adapter/automation_credential_wake_test.go create mode 100644 internal/adapter/automation_repository.go create mode 100644 internal/adapter/automation_repository_test.go create mode 100644 internal/adapter/cards_repository.go create mode 100644 internal/adapter/cards_repository_test.go create mode 100644 internal/adapter/chat_contract_conversion.go create mode 100644 internal/adapter/chat_contract_conversion_test.go create mode 100644 internal/adapter/chat_repository.go create mode 100644 internal/adapter/chat_repository_test.go create mode 100644 internal/adapter/chat_sending.go create mode 100644 internal/adapter/cookie_identity.go create mode 100644 internal/adapter/cookie_identity_test.go create mode 100644 internal/adapter/cookie_session.go create mode 100644 internal/adapter/cookie_session_test.go create mode 100644 internal/adapter/database_health.go create mode 100644 internal/adapter/database_health_test.go create mode 100644 internal/adapter/default_reply_repository.go create mode 100644 internal/adapter/default_reply_repository_test.go create mode 100644 internal/adapter/item_batch_preview.go create mode 100644 internal/adapter/item_batch_preview_test.go create mode 100644 internal/adapter/item_batch_publish.go create mode 100644 internal/adapter/item_batch_publish_test.go create mode 100644 internal/adapter/item_batch_repository.go create mode 100644 internal/adapter/item_batch_repository_test.go create mode 100644 internal/adapter/item_catalog.go create mode 100644 internal/adapter/item_catalog_test.go create mode 100644 internal/adapter/item_publish.go create mode 100644 internal/adapter/item_publish_images.go create mode 100644 internal/adapter/item_publish_images_test.go create mode 100644 internal/adapter/item_publish_test.go create mode 100644 internal/adapter/item_sync.go create mode 100644 internal/adapter/item_sync_test.go create mode 100644 internal/adapter/keyword_repository.go create mode 100644 internal/adapter/keyword_repository_test.go create mode 100644 internal/adapter/notification_repository.go create mode 100644 internal/adapter/notification_repository_test.go create mode 100644 internal/adapter/order_boundary.go create mode 100644 internal/adapter/order_boundary_test.go create mode 100644 internal/adapter/order_reconciliation.go create mode 100644 internal/adapter/order_reconciliation_test.go rename internal/{server => adapter}/order_repository.go (77%) create mode 100644 internal/adapter/order_repository_test.go create mode 100644 internal/adapter/order_runtime.go create mode 100644 internal/adapter/order_runtime_test.go create mode 100644 internal/adapter/server_dependencies.go create mode 100644 internal/adapter/settings_repository.go create mode 100644 internal/adapter/transaction.go create mode 100644 internal/adapter/transaction_test.go create mode 100644 internal/application/account/authentication_service.go create mode 100644 internal/application/account/authentication_service_test.go create mode 100644 internal/application/account/credential_repository.go create mode 100644 internal/application/account/login_audit.go create mode 100644 internal/application/account/login_audit_test.go create mode 100644 internal/application/account/long_login_service.go create mode 100644 internal/application/account/long_login_service_test.go create mode 100644 internal/application/account/settings_service.go create mode 100644 internal/application/account/settings_service_test.go create mode 100644 internal/application/account/summary_service.go create mode 100644 internal/application/account/summary_service_test.go create mode 100644 internal/application/admin/service.go create mode 100644 internal/application/admin/service_test.go create mode 100644 internal/application/analytics/models.go create mode 100644 internal/application/analytics/service.go create mode 100644 internal/application/analytics/service_test.go create mode 100644 internal/application/automation/account_tasks.go create mode 100644 internal/application/automation/account_tasks_test.go create mode 100644 internal/application/automation/credential_wake.go create mode 100644 internal/application/automation/credential_wake_test.go create mode 100644 internal/application/automation/publish_rules.go create mode 100644 internal/application/automation/publish_rules_test.go create mode 100644 internal/application/automation/rules.go create mode 100644 internal/application/automation/rules_test.go create mode 100644 internal/application/automation/service.go create mode 100644 internal/application/automation/service_test.go create mode 100644 internal/application/cards/service.go create mode 100644 internal/application/cards/service_test.go create mode 100644 internal/application/defaultreply/service.go create mode 100644 internal/application/defaultreply/service_test.go create mode 100644 internal/application/items/batch_local_publish.go create mode 100644 internal/application/items/batch_local_publish_test.go create mode 100644 internal/application/items/batch_management.go create mode 100644 internal/application/items/batch_management_test.go create mode 100644 internal/application/items/batch_preview.go create mode 100644 internal/application/items/batch_preview_persistence.go create mode 100644 internal/application/items/batch_preview_test.go create mode 100644 internal/application/items/batch_recovery.go create mode 100644 internal/application/items/batch_recovery_test.go create mode 100644 internal/application/items/catalog.go create mode 100644 internal/application/items/catalog_mutation.go create mode 100644 internal/application/items/catalog_mutation_test.go create mode 100644 internal/application/items/catalog_test.go create mode 100644 internal/application/items/category_recommendation.go create mode 100644 internal/application/items/category_recommendation_test.go create mode 100644 internal/application/items/sync.go create mode 100644 internal/application/items/sync_test.go create mode 100644 internal/application/keywords/service.go create mode 100644 internal/application/keywords/service_test.go create mode 100644 internal/application/settings/service.go create mode 100644 internal/application/settings/service_test.go delete mode 100644 internal/server/account_login_repository.go create mode 100644 internal/server/account_login_repository_boundary_test.go create mode 100644 internal/server/account_summary_handlers_test.go create mode 100644 internal/server/account_task_application_adapter.go delete mode 100644 internal/server/analytics_repository.go delete mode 100644 internal/server/analytics_service.go create mode 100644 internal/server/automation_issue_port_test.go create mode 100644 internal/server/automation_rule_handlers.go create mode 100644 internal/server/card_application_handlers_test.go create mode 100644 internal/server/chat_application.go delete mode 100644 internal/server/communication_repository.go delete mode 100644 internal/server/communication_service.go create mode 100644 internal/server/default_reply_application.go delete mode 100644 internal/server/http_client_test.go create mode 100644 internal/server/item_batch_local_application.go create mode 100644 internal/server/item_batch_management_application.go create mode 100644 internal/server/item_publish_images_test.go delete mode 100644 internal/server/item_publish_repository.go delete mode 100644 internal/server/item_publish_service.go create mode 100644 internal/server/item_sync_application_test.go create mode 100644 internal/server/login_audit_test.go create mode 100644 internal/server/order_refresh_job_lifecycle_test.go create mode 100644 internal/server/order_service_reconciliation_test.go create mode 100644 internal/server/ownership_secret_scope_test.go create mode 100644 internal/server/platform_runtime_boundary_test.go create mode 100644 internal/server/settings_models_compat_test.go delete mode 100644 internal/server/transaction_repository.go rename internal/webui/static/assets/{AccountList-CMeDGrpw.js => AccountList-Bpj-f-W3.js} (99%) rename internal/webui/static/assets/{CardList-CV-IXa79.js => CardList-D5uSws-z.js} (99%) rename internal/webui/static/assets/{Chat-ChmGl-XK.js => Chat-BLyP9Pyt.js} (99%) rename internal/webui/static/assets/{Dashboard-BjrV0BPa.js => Dashboard-sUNU2Eg5.js} (99%) rename internal/webui/static/assets/{ItemList-DX-qMjnd.js => ItemList-kyCurZV6.js} (99%) rename internal/webui/static/assets/{Notifications-D65tIfCl.js => Notifications-CyWpiVXa.js} (99%) rename internal/webui/static/assets/{OrderList-DCxOUz7n.js => OrderList-Bb5NffV_.js} (99%) rename internal/webui/static/assets/{Rules-D884-CgU.js => Rules-MPWRzM5C.js} (99%) rename internal/webui/static/assets/{Settings-j3SwRFCx.js => Settings-5xhSVKHU.js} (99%) create mode 100644 internal/webui/static/assets/index-CYPNW7Ux.js delete mode 100644 internal/webui/static/assets/index-DK02p8DH.js diff --git a/cmd/server/main.go b/cmd/server/main.go index 7fe7470..20fd3c9 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -329,7 +329,15 @@ func runServer(parent context.Context, opts serverOptions) error { go renewalScheduler.Run(ctx) // srv 是完成依赖校验并注入聊天服务后的 HTTP 应用实例。 - srv, err := server.New(store, mgr, opts.secure, opts.webDir, opts.addr, logger, autoCenter, notifier, server.WithChatService(chatService)) + // serverDependencies 封装 HTTP 服务需要的持久化适配器,避免 Server 直接持有 Store。 + serverDependencies, dependencyErr := adapter.NewDependencies(store) + if dependencyErr != nil { + return fmt.Errorf("构造 HTTP 基础设施依赖失败: %w", dependencyErr) + } + // authentication 保存 HTTP 会话中间件所需的认证实现;会话 Cookie 的 Secure 策略由启动参数决定。 + authentication := &auth.Service{Store: store, Logger: logger, Secure: opts.secure} + // srv、err 保存 HTTP 服务构造结果及失败原因。 + srv, err := server.New(serverDependencies, authentication, mgr, opts.webDir, opts.addr, logger, autoCenter, notifier, server.WithChatService(chatService)) if err != nil { return fmt.Errorf("构造 HTTP 服务失败: %w", err) } diff --git a/docs/architecture/lifecycle-inventory.md b/docs/architecture/lifecycle-inventory.md new file mode 100644 index 0000000..d05d8a6 --- /dev/null +++ b/docs/architecture/lifecycle-inventory.md @@ -0,0 +1,27 @@ +# 生命周期与后台任务清单 + +本文是重构计划阶段 5 的持续审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界, +用于逐项关闭“生命周期与删除 fencing”父切片;清单本身不代表对应组件已经满足完成条件。 + +## 组件清单 + +| 组件/入口 | 所有者 | Context 来源 | 停止/关闭 | 等待/观测 | 当前证据 | 剩余风险 | +| --- | --- | --- | --- | --- | --- | --- | +| `server.Server` HTTP 与后台任务 | `cmd/server` | `Server.Start` 接收的进程 Context;后台任务继承生命周期 Context | `Server.Stop(ctx)`,关闭 HTTP、恢复任务和后台计数 | `Wait`、`WaitForBackground`、任务注册表状态查询 | Server 生命周期、超时等待和任务注册表测试 | 仍需把所有新后台入口统一登记并审计启动顺序 | +| 订单刷新 worker/recovery | `server.Server` | Server 生命周期 Context;恢复扫描使用调用方 Context | worker 终止、租约 fencing、终态写入使用受控 Context | 任务注册表记录 running/succeeded/failed/canceled/timed_out | 订单刷新生命周期与租约测试 | 取消端点和统一运维查询仍待收口 | +| 商品批量发布 worker/recovery | `server.Server` | Server 生命周期 Context;取消后的本地收口使用独立补偿 Context | worker cancel、租约 token、批次终态补偿写入 | 任务注册表与批次状态 | 批量取消 race、应用 BatchRunner 测试 | 单行平台适配仍在 Server,恢复指标和统一查询待补齐 | +| 订单 reconciliation worker | `server.Server` | Server 生命周期 Context | 扫描器停止时取消当前扫描 | 后台任务注册表和补偿记录状态 | reconciliation 成功/失败重试测试 | 指数退避和更完整运维操作待补齐 | +| `account.Manager` 账号运行时集合 | `cmd/server` | `StartAll`/`Start` 调用方 Context | `StopContext`、`StopAllContext`,全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing 和 race 测试 | 运行时内部任务仍需纳入统一清单 | +| `engine.Account` 单账号运行时 | `account.Manager` | `Account.Run(parent)` | `StopContext` 取消运行 Context 并等待连接/任务退出 | `StopContext` 返回错误;运行状态可查询 | Engine lifecycle 与 credential coordinator 测试 | 消息发送、重连和 recorder 子任务需要逐一核对 Join 边界 | +| 浏览器 `Manager` | `cmd/server`/账号流程 | 每次调用的 Context;关闭使用 `CloseContext` | 关闭 fencing,等待活动调用归零,再关闭 Playwright | `CloseContext` 返回超时并可重试 | Browser lifecycle 与 race 测试 | 底层同步 Playwright Close 无法被 Context 中断 | +| 续期 `renewal.Scheduler` | `cmd/server` | `Run(ctx)` 调用方 Context | `StopContext` 幂等并阻止 Stop 后 Run | `WaitContext` | 先 Stop、重复 Stop、零值和 race 测试 | 迟到 Cookie 合并调用方仍需统一审计 | +| 自动化 `automation.Scheduler` | `cmd/server` | `Run(ctx)` 调用方 Context | Context 取消后停止调度 | `WaitContext` | scheduler 与结果收口测试 | 自动化准备和外部动作旁路仍需完整盘点 | +| 通知 outbox worker | `cmd/server` | `Start(ctx)` 调用方 Context | Context 取消后停止拉取与发送 | `WaitContext`、uncertain 状态查询 | notify worker、uncertain 状态和三库测试 | 运维重试与人工核对流程仍待补齐 | +| WebSocket/聊天后台发送任务 | `server.Server`/`chat.Service` | 请求或服务生命周期 Context | 请求取消、连接关闭或服务停止;handler 清理阶段先取消并关闭连接 | handler 等待读取 goroutine 退出,发送结果和连接状态仍由连接生命周期观测 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 其他实时连接的统一 owner/Join 证据仍待完善 | + +## 使用规则 + +1. 新增 goroutine 必须在本表增加一行,注明启动者、Context 来源、取消责任和等待方式。 +2. 每个组件完成生命周期迁移后,必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动完成。 +3. 删除账号前必须先建立账号级 stopping fence,再在受限 Context 内停止运行时,最后重新校验归属并删除持久化记录。 +4. 本表中标记为“剩余风险”的项目未满足父切片关闭条件前,阶段 5 必须保持“进行中”。 diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index c4aaad1..bca5520 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -1,835 +1,543 @@ -# Ydisks 闲鱼助手渐进式重构总计划 +# Ydisks 闲鱼助手重构总计划 -## 1. 文档目的 +## 1. 计划目标 -本文是仓库后续结构治理的唯一长期路线图。任何涉及 Go 包边界、HTTP API、数据库访问、 -账号凭证、React 页面结构、测试基础设施或依赖装配的修改,都必须先阅读本文、 -`docs/architecture/dependency-rules.md` 与 `docs/architecture/comment-standard.md`。 +本文是仓库重构的唯一阶段路线图,只记录目标架构、十个正式迭代、阶段验收条件和强制约束。 +本文不记录开发日期、提交列表、阶段内进度、完成日志、人员记录或临时工作说明。 -本计划采用小步、可回滚的纵向切片,不允许建立一个长期脱离主分支的大型重构分支, -也不允许在一个变更中同时完成大规模移动、行为修改、数据库迁移和兼容清理。 +阶段 0 是执行重构前的治理前置条件,不计入正式迭代。阶段 1 至阶段 10 各自对应一个完整 +迭代和一个 PR,最多执行十轮。阶段内部可以连续完成多项实现和测试,但不得拆成额外轮次、 +额外 PR 或额外提交。 -滑块 CAPTCHA 逻辑继续受 `docs/slider-captcha-frozen-spec.md` 保护;本计划不构成修改授权。 +滑块 CAPTCHA 行为继续由 `docs/slider-captcha-frozen-spec.md` 保护。本文不是修改冻结行为的授权。 -## 2. 当前问题基线 +### 1.1 最终成功标准 -截至计划建立时,仓库具有良好的测试和工程化基础,但存在以下主要维护风险: +1. `cmd` 只负责配置、依赖构造、信号和进程生命周期。 +2. `internal/server` 只负责 HTTP/WebSocket transport、鉴权、中间件、具名 DTO 和 SPA。 +3. 应用服务负责完整用例、所有权校验和事务边界,且不依赖 HTTP、数据库或平台实现类型。 +4. `internal/db` 独占 SQL、迁移、方言、加密持久化和 repository 实现。 +5. 账号摘要、平台凭证、密码登录秘密和运行配置使用不同模型和最小查询。 +6. Engine 与 Automation 的并发状态、凭证协调、外部动作和生命周期由明确组件拥有。 +7. React 遵守 `app -> features -> shared`,业务请求、状态和 DTO 转换归属对应 feature。 +8. SQLite、MySQL、PostgreSQL 的迁移、事务和核心业务行为一致。 +9. 旧 API 和兼容字段只在有调用方、遥测和删除条件时保留,最终按明确 Sunset 退场。 +10. 架构、注释、race、多数据库、前端类型和构建均成为自动门禁,无历史豁免。 -- `internal/server` 同时承担 HTTP、业务编排、MTOP 调用、事务、QR 会话和批量发布 worker 生命周期; -- `internal/engine/account.go` 集中管理连接、凭证、重试、运行状态、去重、防抖和任务生命周期; -- `internal/automation/center.go` 同时管理规则、运行、外部动作、卡密分配、凭证恢复和通知; -- `internal/db.Store` 向上层暴露全部 repository 与裸 `*sql.DB`; -- 账号列表和所有权检查会读取或解密超过实际需要的敏感字段; -- HTTP 响应大量使用动态 map,错误结构和 API 路径不统一; -- 前端存在多个 900 至 1800 行的页面组件,API 与类型集中在单文件; -- 部分前端测试依赖源码字符串断言,难以保护真实交互; -- CI 主要依附发布 workflow,尚未形成独立 PR 质量门禁; -- server 测试重复执行全量 SQLite 迁移,使完整 race 测试耗时过高; -- 历史代码尚未满足全函数、全变量准确中文注释要求。 - -审计重开基线(2026-08-15):此前将测试覆盖率收口误判为目标架构完成,现已撤销该判断。当前仍存在敏感设置明文进入前端、Server 持有基础设施编排、Port 泄露 `sql.Tx`/`db.*`、凭证锁覆盖慢速外部 I/O、外部成功后本地状态缺少统一补偿、N+1 同步、关闭游离 goroutine、大型页面同步加载和模板化注释假阴性等问题。覆盖率、lint、race 通过只能证明当前行为可验证,不能替代分层和状态正确性完成条件。 - -## 3. 不变量与成功标准 - -重构期间必须持续满足以下不变量: - -1. 每个合并点都能编译、启动并通过适用测试。 -2. 未经当前任务明确授权,不改变业务行为、API 兼容语义或冻结滑块行为。 -3. 敏感凭证不得扩大读取、传递、序列化或日志记录范围。 -4. SQLite、MySQL 和 PostgreSQL 的行为保持一致。 -5. 前端源码变化后必须重建并校验 `internal/webui/static`。 -6. 新增或修改的函数、变量、字段、参数和返回值必须符合中文注释规范。 -7. 每次完成一个计划步骤,都必须更新本文的状态、验证结果和后续入口。 -8. 不通过删除、跳过或放宽测试来完成重构。 - -最终成功标准: - -- `internal/server` 只负责 HTTP、鉴权、中间件、DTO 映射和静态资源; -- 应用服务负责业务用例和事务边界,不依赖 `net/http`; -- handler 不直接访问 `Store.DB`、MTOP 或 browser; -- 账号摘要、平台凭证、密码登录秘密和运行配置使用不同模型与查询; -- HTTP API 使用具名 DTO、统一错误结构和统一版本前缀; -- React 按 feature 组织,页面容器、数据 Hook、表单和视图组件职责分离; -- `Account` 与 `Center` 成为 facade,内部状态由独立组件拥有; -- PR CI、目标 race、多数据库和架构规则均为自动门禁; -- Go 与 TypeScript/TSX 源码的中文注释基线清零。 - -## 4. 目标依赖方向 +## 2. 目标架构 ```text -cmd/server - ├── application lifecycle - └── HTTP server +cmd + -> application services / lifecycle + -> consumer-defined ports + <- adapter implementations + -> db / xianyu / browser / notify HTTP server - └── application services + -> application services -application services - ├── domain/runtime services - └── consumer-defined ports - -db / xianyu / browser / notify - └── implement consumer-defined ports +React app shell + -> feature page + -> feature hooks / state / API adapter / UI model + -> shared HTTP client and shared UI ``` -前端目标方向: - -```text -app shell / routes - └── feature pages - ├── feature hooks - ├── feature components - └── feature API adapters - └── shared HTTP client -``` - -详细的允许与禁止依赖见 `docs/architecture/dependency-rules.md`。 - -## 5. 阶段状态总表 - -状态只允许使用:`未开始`、`进行中`、`已完成`、`阻塞`。 - -| 阶段 | 状态 | 目标 | 完成证据 | -| --- | --- | --- | --- | -| 0. 治理文档与强约束 | 已完成 | 总计划、依赖规则、注释规范、AGENTS 门禁、注释检查器 | 文档、门禁规则、Go/TypeScript 检查器和历史基线已落盘 | -| 1. PR CI 与测试基础 | 已完成 | 独立 CI、测试 DB 模板、可执行 race | CI、独立模板、server smoke race 和完整 race 均有验证 | -| 2. 敏感数据访问边界 | 已完成 | 摘要、凭证、登录秘密和系统设置分离 | Cookie/平台运行视图、系统设置脱敏读写、已知生产敏感设置调用方审计和运维诊断输出脱敏已收口;SQLite、MySQL 8.4、PostgreSQL 17 的真实多库迁移与 CRUD 回归均通过;高频运行时仅读取窄视图、不逐次写审计,管理/一次性敏感读取均有审计和 fail-closed 测试 | -| 3. HTTP API 契约 | 已完成 | 统一错误、具名 DTO、版本化路径 | 统一错误 DTO、具名成功 DTO、所有前端业务调用方版本化、旧路径兼容和最终审计均已完成 | -| 4. Server 应用服务 | 进行中 | 订单、发布、登录、聊天纵向抽取 | 订单、单/批量商品发布、账号资料刷新、手动/扫码登录、普通 Cookie 更新、账号删除、聊天历史/写入和通知渠道/绑定/uncertain 查询已通过应用 Port 接入;密码登录关闭策略已由应用 Port 统一承载,但浏览器密码登录仍明确禁用,其他账号操作、部分商品辅助流程和 handler 低层依赖仍待收口 | -| 5. 应用生命周期装配 | 进行中 | 消除必需依赖 setter 回填并统一关闭边界 | Server、续期调度器、浏览器 Manager、Engine watcher、账号 Manager 的 Stop/Close 已具备 Context/fencing 与回归;账号删除已由应用服务统一执行 fencing、最多五秒停止等待和锁内二次归属复核;Server 后台/恢复任务已有进程内 ID、状态和 Context 超时查询,统一跨组件清单仍待补齐 | -| 6. Engine 与 Automation | 已完成 | facade + 独立状态组件 | Engine/Automation 组件边界、race、生命周期与冻结规范测试均已通过 | -| 7. React Feature 化 | 进行中 | 页面、Hook、API、类型按领域拆分 | Rules、Items、Accounts、Cards、Orders、Notifications、Dashboard、Settings、Chat 和 AccountAutomation 的 feature/API/Hook 已拆分,App 路由懒加载和入口包体预算已收口;Provider/路由壳、完整页面行为覆盖和剩余大型页面边界仍待完成 | -| 8. DB 与事务治理 | 进行中 | 窄接口、事务执行器、方言门禁 | 订单/商品/通知应用 Port、非敏感通知渠道摘要查询、批量 worker、订单 reconciliation、通知渠道/绑定与 uncertain 状态和三库迁移证据已补齐;自动化准备阶段订单事实失败不再被吞;任务状态明确为非持久化进程内元数据;仍有 Server 低层适配集中、`sql.Tx`/`db.*` 旧边界、更多批量读写与补偿查询待收口 | -| 9. 架构门禁与兼容清理 | 进行中 | 允许依赖图、临时例外、兼容路径退场 | `architecturecheck` 已覆盖应用 Port AST 类型和 Server 新增低层依赖;聊天写入、通知渠道/绑定、普通 Cookie 更新和账号删除已接入 Port,密码登录关闭策略也已接入应用层,但仍保留历史 Server 临时白名单,旧 API 遥测、Sunset 条件和其他领域迁移尚未完成 | -| 10. 注释基线清零 | 进行中 | 全仓准确中文注释检查 | 已有字符级/AST 门禁;待完成模板短语黑名单、业务语义抽查、复杂度门禁和冻结文件精确例外 | - -### 当前执行入口 - -- 当前阶段:审计重开后的过渡架构治理;不得使用“全部完成”表述。P0 敏感数据父切片已按完成条件关闭;当前按顺序推进 P1 应用 Port、生命周期和外部动作补偿父切片,之后才处理 P2 批量同步、HTTP 兼容退场和 React 页面边界;在 P1 父切片关闭前继续暂停新的 React 页面细粒度子切片;每个 PR 必须同时更新完成证据和剩余风险; -- 已完成:总计划、依赖规则、中文注释规范、`AGENTS.md` 强约束,以及 Go/TypeScript AST 注释检查器和历史基线; -- 阶段 1 已完成:server 测试模板预置管理员和账号 cookie,普通测试约 21.3 秒,完整 server race 约 194.3 秒通过; -- 已完成阶段 2 逻辑切片一“Repository 敏感数据边界”:建立 `CookieSummary`、`ListOwnedIDs`、`ExistsOwned`、`GetOwnerID`、`GetSummaryOwned` 和原子 `GetValueOwned`,覆盖跨用户、无效 user ID 及无效密文回归; -- 已完成阶段 2 逻辑切片二“Server 非敏感消费方”:账号列表、运行状态、账号详情、聊天、商品、关键词回复、卡券关联和管理员账号停止流程均迁移到窄查询,纯所有权流程不再解密完整凭证; -- 已完成阶段 2 逻辑切片三“订单消费方”:订单刷新、手动发货和订单导入使用账号 ID 列表与所有权判断,凭证流程按需读取单账号详情; -- 已完成阶段 2 后续切片:`internal/chat/service.go` 的订阅账号集合已迁移到 `ListOwnedIDs`,聊天订阅不再批量解密账号 Cookie; -- 已完成阶段 2 后续切片:`internal/account/manager.go` 已改用受控的 `ListEnabledRuntimeCredentials` 启动账号,只解密启用账号 Cookie,不再使用 `AllForUser(ctx, 0)` 加逐账号状态查询; -- 已完成阶段 2 后续切片:`internal/renewal/scheduler.go` 已改用 `RenewalRuntimeAccount` 窄模型及按账号重读接口,只解密 Cookie、续期 metadata 和启用状态,不再把登录密码/用户名带入续期调度器; -- 已完成阶段 2 后续切片:`internal/automation/account_tasks.go` 的 Session 阻断指纹已改用 `GetCookieRuntimeData`,只读取 Cookie 与 metadata,不再解密完整账号详情; -- 已完成阶段 2 后续切片:`internal/automation/center.go` 的确认发货流程已改用 `GetCookieRuntimeData`,只读取 Cookie 与 metadata,保留凭证锁、Cookie Jar 和重试行为; -- 已完成阶段 2 后续切片:`internal/automation/center.go` 的通用 `cookieValue` 回退读取已迁移到 `GetValue`,Automation 生产代码不再直接读取完整账号详情; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `tryLoginStatusCheck` 已改用 `GetCookieRuntimeData`,只读取 Cookie 与 metadata,保持重试、Cookie Jar 和锁语义; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `tryAPIRenewUsing` 已改用 `GetCookieRuntimeData`,只读取接口续期所需的 Cookie 与 metadata,保持续期、快照持久化、锁和 token 清理语义,并补充损坏登录密码回归测试; -- 已完成阶段 2 后续切片:新增 `GetCookieMetadata` 单字段接口,并将 `internal/engine/account.go` 的 `persistRenewFlatCookie` 迁移到该接口,只读取 metadata,保持扁平 Cookie 更新和 metadata 快照清理行为; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `handleMaxFailures` 已改用 `GetValue`,只读取恢复回调所需的 Cookie 明文,保持失败计数和重连行为,并补充损坏登录密码回归测试; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `persistPendingRenewCookies` 已改用 `GetCookieRuntimeData`,只读取异步续期所需的 Cookie 与 metadata,保持迟到 Cookie 合并、凭证锁和通知行为,并补充损坏登录密码回归测试; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `refreshTokenWithMinGap` metadata 读取已迁移到 `GetCookieMetadata`,只读取 token 请求所需的 Cookie 快照信息,保持 Cookie 快照请求上下文和 token 刷新行为,并补充损坏登录密码回归测试; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `adoptTokenResponseCookies` metadata 读取已迁移到 `GetCookieMetadata`,只读取 token 响应 Cookie 合并所需的快照信息,保持响应合并、快照持久化和错误语义,并补充损坏登录密码回归测试; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `databaseCredentialFingerprint` 已改用 `GetCookieRuntimeData`,只读取 token 凭证一致性校验所需的 Cookie 与 metadata,保持空值、指纹不一致和错误语义,并补充损坏登录密码回归测试; -- 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `reloadCookieFromDB` 已改用 `GetCookieRuntimeData`,只读取外部 Cookie 更新检测所需的 Cookie 与 metadata,保持运行时替换、token 清理和错误行为,并补充损坏登录密码回归测试; -- 已完成阶段 2 当前 PR 切片四“Engine/账号运行时凭证边界”:`cookieSnapshotMatchesDB`、`UpdateCookie` 和账号管理器 `Restart` 已分别改用 `GetCookieRuntimeData` 或 `GetValue`,只读取运行实例所需的 Cookie 数据;损坏登录密码回归测试覆盖 WS 注册前校验、运行时同步和重启路径,且三项修改合并为一个可回滚提交; -- 已完成阶段 2 当前 PR 切片五“平台凭证流程统一窄查询”:新增不含用户名和登录密码的 `CookiePlatformRuntimeData`,并将 `internal/adapter` 的 token 风控、订单详情、协议续期以及 `internal/renewal` 的迟到 Cookie 合并统一迁移到该视图;损坏登录密码回归测试覆盖四条平台流程,且整批修改合并为一个可回滚提交; -- 已完成阶段 2 当前 PR 切片六“Server 平台凭证流程审计”:Server 的订单、发布、商品同步、二维码登录、长登录、资料刷新和账号生命周期路径已改用平台运行视图或非敏感摘要;完整 `CookieDetail` 仅保留给账号设置和登录信息更新这两个确实需要登录秘密的流程,新增 Server 窄查询回归测试并通过全量门禁,整批修改合并为一个可回滚提交; -- 已完成阶段 2 最终审计:生产代码中的 `GetDetails` 仅保留登录设置和登录信息更新两条完整详情白名单;平台流程统一使用 `GetCookiePlatformRuntimeData`,所有权流程统一使用摘要查询,凭证读取继续由 `LockAccountCredentials` 保护;新增 `TestMultiDB_CookieCredentialScope` 覆盖 SQLite,并在提供环境变量时覆盖 MySQL/Postgres,验证三种方言的 Cookie、metadata、平台视图和所有权摘要一致;阶段 2 全量门禁通过并合并为一个可回滚提交; -- 已完成阶段 3 第一个 PR 切片“HTTP 错误结构盘点与第一批契约测试”:新增共享 `httpapi.ErrorResponse`,统一 `code`/`message`/`request_id` 错误边界;认证失败改用 401 和稳定 `authentication_failed`,健康检查和账号列表改用具名 DTO;React 请求层移除 `detail/msg` 错误依赖并为账号列表补充具名类型;新增健康检查、认证失败和账号列表契约测试,Go/React 全量门禁通过并合并为一个可回滚提交; -- 已完成阶段 3 第二个 PR 切片“剩余认证与公共 API 错误迁移”:初始化冲突、管理员/用户密码修改、登录凭据校验、用户名冲突、公开设置故障和 SPA API 404 均返回统一错误 DTO 与正确状态码;新增状态码/错误码契约测试,Go 全量门禁通过并合并为一个可回滚提交; -- 已完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移”:订单刷新、手动发货和订单导入不再返回顶层 HTTP 200 + `success:false`,批量结果改用 `partial_failure`,刷新明细错误统一使用 `message`;账号任务的 502 错误改用统一错误 DTO;新增订单/账号契约测试并通过全量门禁,逐项结果中的 `success` 仅保留为批处理行状态; -- 已完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移”:聊天发送失败和商品发布失败均改用统一 `code`/`message`/`request_id` 错误 DTO,商品远端已成功但本地保存失败的恢复信息迁移到可选 `details`;React 错误类型同步支持 `details`,新增 HTTP DTO、聊天/自动化/商品契约测试并通过前端门禁; -- 已完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移”:二维码生成、扫码状态持久化、风控验证失败和账号不匹配均改用正确的非 2xx 状态码与统一错误 DTO;历史密码登录入口返回明确的 `password_login_disabled` 未实现错误;新增二维码/密码登录契约测试并通过全量门禁; -- 已完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备”:认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO,新增响应契约测试,并记录 `/api/v1` 兼容迁移边界;未提前切换旧路径,保持可回滚; -- 已完成阶段 3 第七个 PR 切片“剩余业务成功响应 DTO 与客户端契约收口”:账号详情/设置、商品核心发布与同步、自动化规则/异常、订单详情/刷新/批量外层响应改用具名 DTO;React 客户端同步使用具名契约类型;新增跨领域成功响应契约测试;旧字段、旧路径和批处理逐行兼容字段保留;全量门禁通过并合并为一个可回滚提交; -- 已完成阶段 3 第八个 PR 切片“剩余商品批量操作与设置/卡券/通知成功响应收口”:商品类目推荐、批量发布预检/任务、系统与用户设置、账号 AI 设置、卡券 CRUD/批量、通知渠道与账号绑定均改用具名 DTO;React 客户端同步具名契约类型;补充跨领域契约测试;保留动态设置键、旧路径和批量逐行字段;全量门禁通过并合并为一个可回滚提交; -- 已完成阶段 3 第九个 PR 切片“剩余关键词回复、默认回复与账号任务成功响应收口”:关键词基础/商品/类型规则、指定商品回复、默认回复、账号任务设置与运行记录均改用具名 DTO;React 客户端同步具名契约类型;新增跨领域契约测试;保留旧路径和兼容字段;全量门禁通过并合并为一个可回滚提交; -- 已完成阶段 3 第十个 PR 切片“分析统计、管理员与剩余公共成功响应收口”:管理员用户/账号/统计、用户仪表盘、订单分析、有效订单分页和二维码生成均改用具名 DTO;React 客户端同步统计和二维码契约类型;新增跨领域契约测试;保留动态设置和二维码状态的兼容边界;全量门禁通过并合并为一个可回滚提交; -- 已完成阶段 3 第十二个 PR 切片“HTTP API 版本化兼容入口与会话调用方迁移”:新增 `/api/v1/session/login`、`/api/v1/session/initialize`、`/api/v1/session` 与 `/api/v1/session/logout` 薄适配入口,复用旧 handler;React 登录、初始化、会话校验和登出已迁移,旧路径保留;新增 Go/React 契约测试并保持独立可回滚提交; -- 已完成阶段 3 第十三个 PR 切片“账号 API 版本化兼容入口与调用方迁移”:新增 `/api/v1/accounts`、详情、运行状态、单账号详情和启停状态薄适配入口,复用旧 handler;React 账号摘要、详情、运行状态和启停状态调用已迁移,旧路径保留;新增 Go/React 契约测试并保持独立可回滚提交; -- 已完成阶段 3 第十四个 PR 切片“账号设置与资料 API 版本化兼容入口迁移”:新增账号聚合设置、备注、暂停、自动确认、长登录和资料刷新 `/api/v1/accounts/{cid}/...` 薄适配入口,复用旧 handler;React 相关调用已迁移,旧路径保留;新增 Go/React 契约测试并保持独立可回滚提交; -- 已完成阶段 3 第十五个 PR 切片“账号凭证与登录信息 API 版本化兼容入口迁移”:新增账号新增、Cookie 更新和登录信息设置 `/api/v1/accounts...` 薄适配入口,复用既有凭证锁与权限 handler;React 对应调用已迁移,旧路径保留;新增敏感字段边界契约测试并保持独立可回滚提交; -- 已完成阶段 3 第十六个 PR 切片“订单 API 版本化兼容入口与调用方迁移”:新增订单列表、详情和更新 `/api/v1/orders...` 薄适配入口,复用既有订单归属校验与 handler;React 对应调用已迁移,旧路径保留;新增订单契约测试并保持独立可回滚提交; -- 已完成阶段 3 第十七个 PR 切片“订单刷新与批量操作 API 版本化兼容入口迁移”:新增订单刷新、单订单刷新、手动发货和导入 `/api/v1/orders...` 薄适配入口,复用既有订单 handler;React 对应调用已迁移,旧路径保留;新增刷新/批量契约测试并保持独立可回滚提交; -- 已完成阶段 3 第十八个 PR 切片“商品 API 版本化兼容入口与调用方迁移”:新增商品列表、详情、发布、更新和删除 `/api/v1/items...` 薄适配入口,复用既有商品所有权校验与 handler;React 对应调用已迁移,旧路径保留;新增商品契约测试并保持独立可回滚提交; -- 已完成阶段 3 第十九个 PR 切片“商品同步与批量发布 API 版本化兼容入口迁移”:新增商品同步、类目推荐、批量发布预检、任务、详情、取消、重试和结果下载 `/api/v1/items...` 薄适配入口,复用既有商品 handler;React 对应同步/批量发布调用已迁移,旧路径保留;新增商品批量契约测试并保持独立可回滚提交; -- 已完成阶段 3 第二十个 PR 切片“设置、卡券与通知 API 版本化兼容入口迁移”:新增系统/用户/AI 设置、卡券和通知渠道/消息/账号绑定 `/api/v1/settings`、`/api/v1/cards`、`/api/v1/notifications` 薄适配入口,复用既有权限边界与 handler;React 系统设置、AI 设置、卡券和通知调用已迁移,旧路径保留;新增三领域契约测试并保持独立可回滚提交; -- 已完成阶段 3 第二十一个 PR 切片“聊天与账号任务 API 版本化兼容入口迁移”:新增聊天 REST/WebSocket 和账号任务设置/运行记录/执行 `/api/v1/chat...`、`/api/v1/account-tasks...` 薄适配入口,复用既有权限边界与 handler;React REST/WebSocket、账号任务设置和执行调用已迁移,旧路径保留;新增聊天/账号任务契约测试并保持独立可回滚提交; -- 已完成阶段 3 第二十二个 PR 切片“关键词回复与默认回复 API 版本化兼容入口迁移”:新增关键词基础/商品/类型规则、指定商品回复和默认回复 `/api/v1/reply-rules...`、`/api/v1/default-replies...` 薄适配入口,复用既有权限校验与 handler;React 关键词类型规则、指定商品回复和默认回复调用已迁移,旧路径保留;新增回复规则契约测试并保持独立可回滚提交; -- 已完成阶段 3 第二十三个 PR 切片“管理员、仪表盘与订单分析 API 版本化兼容入口迁移”:新增管理员用户/账号/统计、仪表盘统计、订单分析和有效订单 `/api/v1/admin...`、`/api/v1/analytics...` 薄适配入口,复用既有管理员权限与统计 handler;React 管理员统计、仪表盘和订单分析调用已迁移,旧路径保留;新增管理员/统计契约测试并保持独立可回滚提交; -- 已完成阶段 3 第二十四个 PR 切片“二维码登录 API 版本化兼容入口迁移”:新增二维码生成、状态查询、状态持久化和验证完成 `/api/v1/qr-login...` 薄适配入口,复用既有认证、会话所有权和敏感字段过滤 handler;React 二维码生成、轮询和验证完成调用已迁移,旧路径保留;新增二维码新旧入口契约测试并保持独立可回滚提交; -- 已完成阶段 3 第二十五个 PR 切片“密码登录及剩余公共调用方 API 版本化兼容入口迁移”:新增会话密码/凭证、账号删除、密码登录禁用、自动化规则/异常处理、订单删除和商品创建 `/api/v1/...` 薄适配入口,复用既有认证、权限和业务 handler;React 对应调用已迁移,旧路径保留;新增剩余公共调用方 Go/React 契约测试并保持独立可回滚提交; -- 已完成阶段 3 第二十六个 PR 切片“版本化入口最终审计与旧调用方清零”:前端生产调用和批量结果下载已无业务旧路径;Vite 代理收敛为 `/api` 与健康检查;服务端剩余商品兼容入口已补齐;新增旧代理别名和商品遗漏入口审计证据,阶段 3 完成条件满足并保持独立可回滚提交; -- 已完成阶段 4 第一个 PR 切片“订单应用服务边界提取”:订单列表、详情、更新、删除、批量导入、手动发货和批量刷新已由不依赖 `net/http` 的 `orderApplicationService` 编排;handler 仅保留 HTTP 解析、鉴权上下文和 DTO 编码;保留订单所有权、事务回滚、MTOP 凭证锁、Cookie Jar 持久化、Session 续期和逐单部分失败语义;新增服务层直接调用测试并通过 Go 全量门禁与 server race; -- 已完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口”:订单列表状态/图片映射、详情商品补全、单订单刷新和批量刷新响应均由应用服务返回稳定视图;更新校验改用业务错误分类,HTTP 层不再依赖错误文本判断状态码;旧/版本化入口契约测试和全量门禁通过; -- 已完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取”:新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;HTTP 层仅保留请求解析、鉴权和契约映射,保留 worker、锁、cancel map、租约和远端发布顺序;新增服务层直接调用测试并通过全量门禁,合并为一个可回滚提交; -- 已完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取”:新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;HTTP handler 仅保留请求解析、所有权校验和契约映射,保留扫码会话锁与账号凭证锁不变量;新增服务层测试并通过全量门禁,合并为一个可回滚提交; -- 已完成阶段 4 第五个 PR 切片“聊天与通知应用服务边界提取”:新增不依赖 `net/http` 的通信应用服务,覆盖账号任务设置/执行/记录、聊天文字与图片发送、聊天历史读取/已读、通知渠道 CRUD、账号绑定和删除;保留 WebSocket 订阅、聊天事件广播、通知 outbox 与失败状态语义;新增服务层测试并通过全量门禁,合并为一个可回滚提交; -- 已完成阶段 4 第六个 PR 切片“Server 事务与生命周期边界收口”:新增 Server 统一 Unit of Work,订单更新与导入不再直接管理事务;新增后台任务生命周期登记入口,HTTP 优雅关闭与批量发布恢复扫描器统一纳入等待流程;修复服务不可用时 handler 先做资源归属校验导致状态码变化的问题;新增事务提交/回滚测试并通过全量门禁,合并为一个可回滚提交; -- 已完成阶段 4 第七个 PR 切片“Server 直接依赖清理与应用服务装配收口”:统一装配订单、发布、登录、通信和分析应用服务;默认回复、账号设置、AI 设置、通知绑定、管理员查询及订单分析查询均迁移到 repository 或应用服务边界;handler 不再直接访问 `Store.DB`,新增装配一致性测试并通过全量门禁,合并为一个可回滚提交; -- 已完成阶段 5 PR 切片“应用构造依赖验证与生命周期接口”:`Server.New` 在构造阶段校验 `Store/Manager`,聊天服务通过 option 注入并移除生产运行时 setter;新增幂等 `Start/Wait/Stop`,`Stop` 统一等待 HTTP、后台扫描器和批量 worker;`cmd/server` 迁移到显式生命周期入口;新增构造失败、重复启动/停止和 worker 等待测试,并通过全量门禁,合并为一个可回滚提交; -- 已完成阶段 6 第一个 PR 切片“Engine 账号 facade 与运行状态边界”:将连接状态、失败计数、离线告警和业务任务生命周期分别提取为独立锁组件;`Account` 保留 facade,`Stop` 对并发调用保持幂等并等待已登记任务;新增生命周期并发回归测试,未改变 WebSocket、凭证、自动化和冻结风控逻辑;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交; -- 已完成阶段 6 第二个 PR 切片“Engine WebSocket 连接循环边界”:`registerConnection` 在凭证锁内统一快照复核与 WebSocket 注册,`runConnectionSession` 统一心跳、接收、Token 轮换 goroutine 的创建/取消/等待;`Account` 继续负责凭证错误、风控和重连结果解释;新增会话收束测试,未改变冻结风控行为;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交; -- 已完成阶段 6 第三个 PR 切片“Engine WebSocket 记录与消息分发边界”:将 WS 记录 worker、消息去重、防抖和并发信号量分别收口到独立组件;`Account` 保留兼容 facade,系统事件背压、聊天洪峰限流、消息顺序、自动化事件优先级和 Stop 等待语义保持不变;全量 Go 测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交; -- 已完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界”:将 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态收口到独立 `credentialState`;运行状态锁改为显式 `runtimeMu`,避免匿名组件锁冲突;保留风控恢复、刷新锁、Cookie/Token 绑定和 WebSocket 注册前快照复核语义;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交; -- 已完成阶段 6 第五个 PR 切片“Automation 事件事实与规则匹配边界”:新增事件事实记录器、无动作副作用的规则匹配器和纯动作计划器;`Center` 与 `Scheduler` 统一通过组件查询规则和生成动作计划,规则匹配不执行外部动作,付款发货动作顺序、规格匹配、延迟快照和恢复语义保持不变;Automation/Server race、全量测试、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交; -- 已完成阶段 6 第六个 PR 切片“Automation 运行协调与动作执行边界”:新增 `automationRunCoordinator`,统一运行创建/恢复、动作前后检查点、延迟任务续租、账号门禁和不确定结果隔离;`Center` 保留兼容调用入口,外部动作已执行/未执行/结果未知三态语义、人工核对状态机和恢复游标保持不变;Automation 测试、注释和 diff 门禁通过,整批修改合并为一个可回滚提交; -- 已完成阶段 6 第七个 PR 切片“Automation 发货、卡密与通知动作边界”:新增 `automationActionExecutor` 与 `deliveryNotifier`,统一确认发货、Cookie/Jar 合并、卡券锁与库存消费、消息错误三态分类和结果通知;`Center` 保留兼容入口,凭证锁、卡券库存、恢复唤醒和通知文案语义保持不变;新增动作执行器回归测试,Automation 测试、注释和 diff 门禁通过,整批修改合并为一个可回滚提交; -- 已完成阶段 6 第八个 PR 切片“Automation 账号任务与凭证门禁边界”:新增 `accountTaskCoordinator`,统一账号状态门禁、自动评价/商品擦亮调度、任务租约、Session 指纹阻断、凭证恢复和 Cookie 同步;`Center` 保留公开任务入口,Session 失效恢复、任务幂等、失败重试和账号暂停语义保持不变;Automation 测试、注释和 diff 门禁通过,整批修改合并为一个可回滚提交;阶段 6 完成; -- 已完成阶段 7 第一个 PR 切片“React Rules feature 化与 API/行为测试边界”:按 `app/features/rules` 提取 Rules API 适配层、领域类型、数据 Hook、异常面板和交互状态模型;规则页通过 Hook 管理服务端数据与请求代次,保留旧组件入口和现有 API 路径;行为测试覆盖成功、失败、重复提交、过期响应和页签切换;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交; -- 已完成阶段 7 第二个 PR 切片“React ItemList feature 化与批量发布行为边界”:按 `app/features/items` 提取商品/批量 API 适配层、批量任务类型、批量 Hook 和阶段指示器组件;批量预检、任务恢复、轮询取消、失败重试和过期响应均由 feature 状态边界负责;行为测试覆盖预检门禁、取消状态、失败重试、历史任务筛选和过期轮询响应;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交; -- 已完成阶段 7 第三个 PR 切片“React AccountList feature 化与账号运行状态行为边界”:按 `app/features/accounts` 提取账号 API 适配层、账号数据与运行状态 Hook、运行状态展示模型、账号编辑弹窗和登录/暂停状态模型;账号加载与运行状态轮询支持取消和请求代次门禁,密码登录响应按账号与代次隔离,旧组件入口保留兼容转发;行为测试覆盖账号切换、暂停/恢复、凭证失败、风控验证和过期响应;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交; -- 已完成阶段 7 第四个 PR 切片“React CardList feature 化与卡密库存/批量追加行为边界”:按 `app/features/cards` 提取卡密 API 适配层、库存数据 Hook、批量导入/追加状态 Hook 和弹窗组件;卡密筛选、追加预览、提交取消、失败重试与账号切换过期响应均由 feature 状态边界负责,保留旧组件入口和 API 路径;新增状态模型测试并通过前端类型检查、全量测试、注释检查和构建门禁,合并为一个可回滚提交; -- 已完成阶段 7 第五个 PR 切片“React OrderList feature 化与订单导入/刷新行为边界”:按 `app/features/orders` 提取订单 API 适配层、查询/分页 Hook、导入 Hook、筛选栏和导入弹窗;订单查询与辅助数据支持并行加载、取消和代次门禁,导入支持文件预检、取消、失败重试和导入后刷新;新增筛选、导入归一化、API 取消信号和过期响应测试,保留旧组件入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交; -- 已完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界”:按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交; -- 已完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界”:按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交; -- 已完成阶段 7 第八个 PR 切片“React Settings feature 化与系统配置校验边界”:按 `app/features/settings` 提取系统配置/模型/凭据 API 适配层、配置常量、表单状态和敏感字段校验;配置读取与保存支持并行加载、请求取消、失败重试和过期响应保护,登录凭据提交保留现有校验与重登录语义;新增配置裁剪、凭据校验、API 取消信号和请求代次测试,保留旧页面入口和 API 路径; -- 已完成阶段 7 第九个 PR 切片“React Chat feature 化与会话消息行为边界”:按 `app/features/chat` 提取聊天 API、会话筛选/消息合并状态、账号/会话/消息分页 Hook;会话切换、联系人分页和消息加载支持取消与请求代次保护,文本/图片发送支持失败重试,WebSocket 和滚动语义保持不变;新增会话筛选、消息去重、分页过期响应、发送取消与 API 取消信号测试,保留旧页面入口和 API 路径; -- 已完成阶段 7 第十个 PR 切片“React AccountAutomation feature 化与任务设置行为边界”:按 `app/features/accountAutomation` 提取账号任务 API、默认设置与重复执行状态模型、任务设置 Hook;账号切换支持取消和请求代次保护,保存/立即执行支持重复提交阻断、失败重试和结果刷新;新增默认值、动作门禁、API 取消信号测试,保留旧弹窗入口和 API 路径; -- 已完成阶段 7 当前 PR 切片“React AccountList 子模块收口与页面组合边界”:账号卡片、删除确认、二维码授权和 AI 设置弹窗已迁入 `app/features/accounts/components`,根页面只负责列表状态、请求代次和子模块组合;新增展示/交互边界测试,前端 322 个测试、类型检查、注释门禁和生产构建通过。路由懒加载、Provider 边界、AccountList 完整页面行为测试和首屏包体预算仍待完成; -- 已完成阶段 7 当前 PR 切片“React 路由懒加载与首屏入口包体边界”:认证根组件保留会话与导航状态,9 个业务页面在 `app/shell/AuthenticatedShell.tsx` 中按路由使用 `React.lazy` 加载,统一 `Suspense` 页面占位,保留权限回退、历史导航和页面参数语义;新增生产 bundle 边界测试,验证入口脚本小于 100KB、图表依赖不被首屏预加载且 9 个页面均有独立 chunk;前端 325 个测试、类型检查、注释门禁和生产构建通过。Provider/路由壳的更细粒度状态边界、完整页面行为覆盖、动态 chunk 独立预算和大型页面进一步拆分仍待完成; -- 已完成阶段 7 当前 PR 切片“认证后路由壳与页面组合边界”:新增 `AuthenticatedShell` 与 `AppContent`,将侧边栏、主内容布局、权限回退、商品到规则页联动和动态页面组合从 `App.tsx` 移出;更新响应式布局与路由静态契约测试,前端 326 个测试、类型检查、注释门禁、生产构建和仓库 `make check` 通过。Provider 状态边界、完整页面行为覆盖、动态 chunk 独立预算和大型页面进一步拆分仍待完成; -- 已完成阶段 7 当前 PR 切片“认证会话 Provider 状态边界”:新增 `SessionProvider`/`useSession`,集中会话校验、AbortController 生命周期、首次管理员初始化、登录、注销和 `auth:logout` 全局事件;`App.tsx` 只保留认证表单输入、导航状态和页面展示协调,不再直接调用会话 API 或维护全局认证状态;新增 Provider 行为测试覆盖已认证、未初始化、登录/初始化成功、全局注销及注销失败清理,前端 330 个测试、类型检查、注释门禁、生产构建和仓库 `make check` 通过。页面级 Provider 组合、完整页面行为覆盖、动态 chunk 独立预算和大型页面进一步拆分仍待完成; -- 已完成阶段 7 当前 PR 切片“React 路由组合行为与动态 chunk 独立预算”:`bundleBoundary.test.ts` 新增九个业务页面的独立原始字节预算门禁;`AuthenticatedShell.test.tsx` 新增非管理员设置回退、管理员设置加载、商品→规则目标传递及规则目标消费行为测试;前端路由组合与生产资源边界均有运行时/产物证据,页面行为和动态分片治理继续保持可回归。完整页面行为覆盖、更多大型页面边界和全局 Provider 组合仍待完成; -- 已完成阶段 7 当前 PR 切片“React AccountList 完整页面行为边界”:新增真实挂载 `AccountList` 的组合行为测试,覆盖搜索过滤与计数提示、删除确认后的 API/本地状态更新、启用状态切换、资料刷新、二维码生成与轮询成功、二维码关闭时停止轮询和取消请求;通过替身隔离真实账号、二维码和浏览器数据,不跳过页面协调逻辑。AccountList 内部 QR 协调器进一步 feature 化、其他大型页面完整行为覆盖和全局 Provider 组合仍待完成; -- 已完成阶段 7 当前 PR 切片“React AccountList 二维码登录协调器 feature 化”:新增 `app/features/accounts/qrLogin.ts` 与 `qrPolling.ts`,将二维码生成、轮询、风控验证、持久化、延迟关闭和异步清理从根页面迁入账号 feature;旧 `components/qrPolling.ts` 仅保留兼容导出,AccountList 根组件不再持有二维码请求/轮询实现;新增 Hook 分支测试覆盖成功、风控、生成失败、持久化失败和取消,AccountList 组合测试同步验证 feature 轮询边界。其他大型页面完整行为覆盖、页面级 Provider 组合和全局架构收口仍待完成; -- 已完成阶段 7 当前 PR 切片“React OrderList 完整页面行为边界”:新增真实挂载 `OrderList` 的组合测试,覆盖筛选栏状态转发、同步与导入入口、详情弹窗、编辑字段映射、状态发货、单笔同步、删除分页分支和上一页/下一页函数式更新;分页按钮补充稳定的无障碍名称,测试隔离订单查询 Hook、导入状态、API 和筛选子组件,不跳过页面协调逻辑。OrderList 动作协调器进一步 feature 化、Rules/ItemList/CardList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; -- 已完成阶段 7 当前 PR 切片“React OrderList 动作协调器 feature 化”:新增 `app/features/orders/orderActions.ts` 与对应 Hook 测试,将订单同步、发货、详情、编辑草稿、单笔同步、删除分页回退和弹窗生命周期从 `OrderList` 根组件迁入 feature;根组件只保留查询、筛选、页面组合和展示字段更新,编辑字段通过函数式补丁进入协调器;成功、失败、取消和异常结果均有 Hook/页面回归证据。Rules/ItemList/CardList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; -- 已完成阶段 7 当前 PR 切片“React CardList 动作协调器 feature 化”:新增 `app/features/cards/cardActions.ts`,将卡密新增、编辑、删除、启停、筛选、复制和模板下载从 `CardList` 根组件迁入 cards feature;批量导入仍复用既有批量 Hook,页面根组件只负责状态组合和表单展示;新增动作 Hook 与真实页面组合测试,覆盖筛选、批量入口、新增/编辑字段映射、启停、复制和删除。Rules/ItemList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; -- 已完成阶段 7 当前 PR 切片“React Rules 动作协调器 feature 化”:新增 `app/features/rules/ruleActions.ts`,将自动化规则草稿、触发类型/规格编辑、保存删除、异常恢复、关键词回复和默认回复动作,以及商品页联动加载从 `Rules` 根组件迁入 rules feature;同步更新路由静态契约测试,新增 Hook 测试覆盖自动化规则归一化保存、三类回复保存、触发/规格编辑、删除和异常恢复;前端全量 366 个测试、类型检查、中文注释门禁和生产构建通过。ItemList 其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; -- 已完成阶段 7 当前 PR 切片“React ItemList 普通商品动作协调器 feature 化”:新增 `app/features/items/itemActions.ts`,将商品同步、编辑、删除、手动添加、普通发布、模板下载、图片预览和发货地定位从 `ItemList` 根组件迁入 items feature;批量发布仍复用既有 `useItemPublishBatch` 状态机,页面根组件只负责列表、批量流程和视图组合;新增 Hook 测试覆盖 CRUD、普通发布成功、定位成功/失败边界,并更新图片预览契约测试;前端全量 62 个测试文件/369 个用例、类型检查、中文注释门禁、生产构建和仓库 `make check` 通过。ItemList 真实页面组合覆盖、页面级 Provider 组合和阶段 7 总体验收仍待完成; -- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。 - -## 6. 阶段 0:治理文档与强约束 - -### 工作项 - -- 创建本总计划; -- 创建依赖边界规则; -- 创建全函数、全变量中文注释规范; -- 在 `AGENTS.md` 中加入必须阅读、必须更新和禁止绕过的规则; -- 增加 Go AST 与 TypeScript AST 注释检查器和历史基线。 - -### 完成条件 - -- 所有长期约束均能从 `AGENTS.md` 链接到权威文档; -- 后续任务可以明确指出所处阶段、工作项和适用验证; -- 文档不与冻结滑块规范、打包规则或数据库规则冲突; -- `make comments` 与 `npm --prefix frontend run comments:check` 能阻止不在历史基线中的新增声明缺少中文注释。 - -### 6.1 注释检查器落地说明 - -- `tools/commentlint` 使用 Go AST 检查函数、类型、常量、变量、结构体/接口字段、短变量和范围变量; -- `frontend/scripts/check-comments.mjs` 使用 TypeScript Compiler API 检查变量、函数、方法、属性和函数表达式; -- `.commentlint/go-baseline.json` 与 `.commentlint/frontend-baseline.json` 只记录当前历史债务,新增或修改声明不得通过追加基线绕过; -- 基线使用文件、行号、类别和名称作为审查键。移动或重构文件时,必须清理对应文件的历史问题并重新生成基线; -- 检查器只验证“邻近注释 + 至少一个汉字”,注释准确性、参数语义、并发和敏感数据说明仍由人工审查负责; -- 注释债务按阶段逐文件清理,阶段 10 完成时删除两个基线文件并启用全仓零问题门禁。 - -## 7. 阶段 1:PR CI 与测试基础 - -### 1.1 独立 PR CI - -新增 `.github/workflows/ci.yml`,在 pull request 以及 `main`、`dev` push 时执行: - -- Go 格式只读检查; -- `go vet ./...`; -- `golangci-lint run ./...`; -- `go test ./...`; -- 中文注释检查; -- `npm ci`、typecheck、test、build; -- 嵌入式前端产物一致性检查。 - -发布 workflow 保持发布职责,不再作为唯一质量门禁。 - -### 1.2 Server 测试数据库模板 - -- 在测试入口迁移一次 SQLite 模板; -- 每个测试复制模板到独立临时目录; -- 测试之间不得共享可写数据库连接; -- 关闭无必要的 Goose 测试日志; -- 记录优化前后的普通测试和 race 时间。 - -当前实现:`internal/server/test_database_test.go` 在进程内只执行一次 Goose 迁移,并预置普通测试共同需要的 -管理员和账号 cookie,随后按测试复制 SQLite 文件并直接打开副本。普通 `internal/server` 测试从约 48.2 秒 -降至约 21.3 秒;完整 server race 从 267 秒未完成改善为约 194.3 秒通过。 - -### 1.3 Race 分层 - -普通 PR 先运行并发敏感包的目标 race;server fixture 优化后加入稳定的 server race 子集; -全仓 race 可以进入 nightly。任何 race 报告都必须修复,不得加入忽略名单。 - -当前 PR 门禁使用 `make test-server-race`,覆盖 server 启停、发布 worker、凭证状态转换和锁内所有权复核 -等已验证的并发场景,实测约 12.4 秒通过;完整 `go test -race ./internal/server` 已在预置测试夹具后约 194.3 秒通过, -可作为 nightly 或手工发布前验证,不用 smoke race 代替完整覆盖。 - -### 完成条件 - -- PR 在合并前获得稳定、独立的质量结果; -- `internal/server` race 不再因重复迁移和重复密码哈希触发长时间超时; -- CI 不修改工作区后假装通过格式检查。 - -## 8. 阶段 2:敏感数据访问边界 - -### 2.1 模型拆分 - -建立互不混用的账号摘要、平台凭证、密码登录秘密和运行设置模型。 - -### 2.2 Repository 查询 - -增加用途明确的查询: - -- `ListSummaries`; -- `ListOwnedIDs`; -- `ExistsOwned`; -- `GetCredential`; -- `GetLoginSecret`; -- `GetRuntimeSettings`。 - -当前实现先落地了 Cookie 领域的窄查询:`CookieSummary` 不包含 `Value`、`Password` 或 `MetadataJSON`; -`ListOwnedIDs` 只返回账号 ID;`ExistsOwned` 只返回布尔存在性,并拒绝 `userID=0` 的隐式管理员查询。 -`GetOwnerID` 只返回所有者 ID;`GetSummaryOwned` 返回指定用户的单个非敏感摘要;`GetValueOwned` 在同一条带 user_id 过滤的查询中读取并解密单个 Cookie,避免 -所有权检查与凭证读取之间的竞态窗口。测试使用故意无效的密文值验证摘要查询和所有权检查不会触发解密, -并使用正常加密值覆盖单值凭证读取。账号列表与详情 handler 已不再通过 `AllForUser` 或完整 `GetDetails` 读取敏感字段, -目前 server 生产代码和聊天订阅服务已不再调用 `Cookies.AllForUser`。账号管理器还保留一处管理员视角的全账号凭证加载, -该调用不能简单替换为 ID 列表,将通过受控的启用账号凭证接口单独治理。 - -逐步替换使用 `AllForUser` 进行所有权检查以及使用 `GetDetails` 获取非敏感字段的调用。最终审计已确认生产代码的完整详情读取白名单仅为登录设置和登录信息更新;平台调用、账号生命周期、订单、发布、二维码登录和资料流程均不再需要解密登录秘密。 - -### 2.3 安全不变量 - -- 列表和所有权检查不解密 Cookie、密码或 metadata; -- 只有平台调用流程读取平台凭证; -- 只有密码登录或续期流程读取登录秘密; -- 敏感模型不得用作 HTTP DTO; -- 敏感值不得写入普通日志、错误体或测试失败信息。 - -### 完成条件 - -- 账号列表没有 N+1 敏感查询; -- 用户 ID `0` 不再表示隐式管理员查询; -- 三种数据库的查询和并发测试通过; -- 完整详情读取白名单、所有权过滤和凭证锁不变量均有可复核证据。 - -## 9. 阶段 3:HTTP API 契约 - -### 3.1 统一错误结构 - -所有失败响应逐步统一为 `code`、`message` 和可选 `request_id`,并使用正确 HTTP 状态码。 -禁止新增 HTTP 200 + `success:false`,禁止新增 `detail`、`msg`、`error` 等新的错误别名。 - -### 3.2 具名 DTO - -- handler 不新增匿名请求结构或动态 map 响应; -- DB model 不直接作为 HTTP 响应; -- API DTO 与领域模型显式转换; -- 前端不新增 `Promise` 或无边界 `Record`。 - -### 3.3 版本化路径 - -新接口使用 `/api/v1`。旧接口以兼容别名保留,必须记录调用方、迁移步骤和删除条件。 -只有在前端和外部调用方全部迁移、契约测试覆盖后才能删除兼容路由。 - -### 3.4 类型生成 - -账号和订单 DTO 稳定后再引入 OpenAPI。生成文件不得手工修改;历史兼容归一只存在于边界 adapter。 - -## 10. 阶段 4:Server 应用服务 - -按订单、发布、账号登录、聊天/通知顺序纵向提取应用服务。每次只处理一个业务切片。 - -### 4.1 订单服务 - -应用服务负责列表、详情、更新、导入、同步、手工发货、所有权和事务;handler 只负责 DTO。 - -### 4.2 发布服务 - -应用服务负责单商品发布、预检、批量任务、恢复、取消、重试和关联自动化规则。 -完成后发布 worker、锁和 cancel map 不再属于 HTTP Server。 - -### 4.3 账号登录服务 - -应用服务负责 QR 会话所有权、结果持久化、资料刷新、Cookie 合并、账号重启和登录审计。 -完成后 QR 状态和持久化锁不再属于 HTTP Server。 - -### 4.4 聊天与通知 - -继续收紧已有服务的接口,使 handler 不再直接查询 Store 或调用平台客户端。 - -### 4.5 事务 - -跨 repository 事务由应用服务通过明确的 Unit of Work 执行。禁止 handler 调用 `BeginTx`。 - -### 完成条件 - -- `internal/server` 不直接访问 `Store.DB`; -- handler 不直接调用 MTOP 或 browser; -- 应用服务不依赖 `net/http`; -- 业务分支由应用服务单元测试保护,HTTP 测试集中验证契约与鉴权。 - -## 11. 阶段 5:应用生命周期装配 - -应用服务边界稳定后建立应用装配与生命周期层: - -- 构造所有服务并验证必需依赖; -- 按明确顺序启动,按逆序关闭; -- `Start` 前不得隐式启动 goroutine; -- `Stop` 必须幂等并等待其拥有的 worker; -- 必需依赖不得通过运行时 setter 回填; -- 测试替换通过构造参数或 option 提供。 - -`cmd/server` 最终只处理配置、环境、日志、信号和应用启动。 - -## 12. 阶段 6:Engine 与 Automation - -### 6.1 Engine - -保留 `Account` facade,按纯策略、运行状态、WS 记录、去重、防抖、任务生命周期、凭证状态、 -连接循环的顺序提取。每个组件必须拥有自己的状态和锁,禁止只移动方法却继续共享整个 Account。 - -每个并发组件必须在中文注释中写明: - -- 锁保护的字段; -- 是否允许嵌套持锁; -- 持锁时能否执行 I/O; -- goroutine 的创建、取消和等待责任; -- Stop 的幂等与等待语义。 - -### 6.2 Automation - -逐步提取事件事实记录、规则匹配、运行协调、动作执行、发货、卡密分配、凭证门禁和结果通知。 -规则匹配不得隐式执行外部动作;外部动作必须区分未执行、已执行和结果不确定。 - -### 6.3 冻结边界 - -本阶段默认不修改任何冻结滑块文件,也不得通过调用方重构改变冻结行为。 -涉及凭证、连接或风控恢复时必须执行冻结规范规定的测试。 - -## 13. 阶段 7:React Feature 化 - -### 7.1 目标结构 - -按 `app`、`features`、`shared` 和 `generated` 分层。每个 feature 自有 API、类型、Hook、组件、页面和测试。 -禁止使用会隐藏依赖来源的大型 barrel export。 - -### 7.2 拆分顺序 - -按 `Rules`、`ItemList`、`AccountList`、`CardList`、`OrderList`、`Notifications`、 -`Dashboard`、`Settings`、`Chat` 的顺序拆分。 - -### 7.3 React 强约束 - -- 可由 props/state 计算的值不得重复存入 state; -- 用户操作副作用放在事件处理器中,不使用 state + effect 间接触发; -- 依赖不同的副作用拆成不同 effect; -- 基于旧值更新必须使用函数式 setState; -- 异步请求必须支持取消或 generation gate; -- 独立请求应并行启动; -- memo 只用于实际昂贵计算或稳定子组件输入; -- 不在组件内部声明子组件; -- 服务端数据、表单状态和短暂 UI 状态必须分开; -- 重页面和重依赖使用 `lazy`/`Suspense` 按页面加载; -- 组件不得直接调用 `fetch` 或 `axios`。 - -### 7.4 测试 - -关键流程使用行为测试覆盖成功、失败、取消、切换、过期响应和重复提交。 -源码字符串测试只保留真正的静态架构规则。 - -## 14. 阶段 8:DB 与事务治理 - -- 上层逐步改为持有窄 repository 接口,而不是完整 Store; -- 上层不得访问裸 `*sql.DB`; -- SQL 行结构、持久化模型、领域模型和 HTTP DTO 分离; -- 是否拆物理 package 由稳定后的事务与依赖方向决定,不以目录数量为目标; -- 三套迁移编号和关键 schema 自动校验; -- 新迁移必须在 SQLite、MySQL、Postgres 上验证; -- Credential 锁最终迁移到职责明确的凭证协调组件。 - -## 15. 阶段 9:架构门禁与兼容清理 - -目标结构稳定后加入自动检查: - -- `internal/server` 禁止导入 `internal/db` 和 `internal/xianyu`; -- `internal/db`、`internal/xianyu`、`internal/browser` 禁止导入上层应用包; -- 前端 feature 禁止跨 feature 导入内部文件; -- React 组件禁止直接调用网络客户端; -- 到期兼容字段和路由必须先确认调用方为零,再删除; -- 架构门禁只能约束目标结构,不得把过渡期错误依赖永久合法化。 - -## 16. 阶段 10:注释基线清零 - -注释治理贯穿所有阶段。最终阶段负责: - -- 清理所有历史基线豁免; -- 检查 Go 与 TypeScript/TSX 生产和测试源码; -- 抽样审查注释准确性; -- 确认注释描述的是职责、语义、单位、敏感性和并发约束,而非复述语法; -- 将全仓严格检查加入 PR CI。 - -## 17. 推荐变更序列 - -1. 治理文档、AGENTS 强约束和注释基线工具; -2. 独立 PR CI; -3. server SQLite 测试模板与 race 优化; -4. 前端行为测试基础; -5. AccountSummary 与所有权查询; -6. AccountCredential 与 AccountLoginSecret; -7. 统一 API 错误; -8. 账号 DTO 与版本化接口; -9. 订单 DTO 与版本化接口; -10. 前端 shared client 与 feature API; -11. Rules 页面; -12. ItemList 页面; -13. 订单应用服务; -14. 发布应用服务与 worker; -15. 账号登录与 QR 服务; -16. 应用生命周期装配; -17. Automation 内部组件; -18. Engine 纯策略与状态组件; -19. Engine 连接与凭证组件; -20. DB Store 与事务边界; -21. 旧 API 和旧字段清理; -22. 架构门禁与注释基线清零。 - -## 18. 每个变更的执行模板 - -开始前: - -1. 在本文状态表中确认所属阶段; -2. 写明本次改动的行为不变量; -3. 列出涉及文件、风险、回滚方式和验证命令; -4. 检查是否触及敏感凭证、多数据库、并发、前端产物或冻结滑块边界。 - -实施时: - -1. 先补足或建立保护行为的测试; -2. 一次只移动一个职责; -3. 不顺手清理无关代码; -4. 为所有新增或修改声明补准确中文注释; -5. 保留兼容 adapter,直到调用方迁移完成。 - -完成时: - -1. 执行适用验证矩阵; -2. 检查工作区没有意外生成物; -3. 更新本计划状态和完成证据; -4. 记录下一步最小安全入口; -5. 确认未放宽测试或安全边界。 - -## 19. 验证矩阵 - -所有 Go 修改至少执行: - -```bash -go vet ./... -golangci-lint run ./... -go test ./... -``` - -并发和生命周期修改增加: - -```bash -go test -race ./internal/engine ./internal/account ./internal/automation ./internal/renewal ./internal/notify -``` - -数据库修改增加: - -```bash -go test ./internal/db -go run ./cmd/dbverify "sqlite:///tmp/xianyu-verify.db" -``` - -并在可用环境执行 MySQL/Postgres 多数据库回归。 - -前端修改执行: - -```bash -npm --prefix frontend run typecheck -npm --prefix frontend test -npm --prefix frontend run build -``` - -涉及凭证、登录、engine、account、server 或 browser 调用关系时,额外执行 -`docs/slider-captcha-frozen-spec.md` 中规定的测试,即使未直接修改受保护文件。 - -## 20. 计划更新记录 - -| 日期 | 变更 | 结果 | 下一步 | -| --- | --- | --- | --- | -| 2026-08-14 | 建立长期重构计划、依赖规则和中文注释规范 | 阶段 0 开始 | 将强约束接入 AGENTS,随后实现注释基线工具与独立 CI | -| 2026-08-14 | 将计划治理、注释、依赖、敏感数据、API、React、数据库和并发规则接入 AGENTS | 后续任务已有强制入口 | 实现注释检查器和历史基线 | -| 2026-08-14 | 落地 Go/TypeScript AST 注释检查器、Make 目标、npm 脚本和历史基线 | 阶段 0 完成;`make comments`、前端注释检查和 typecheck 通过 | 阶段 1.1:新增独立 PR CI | -| 2026-08-14 | 新增独立 Go/React PR CI,加入格式、注释、vet、lint、测试和嵌入产物一致性门禁 | 阶段 1 进行中;本地 Go/前端测试、构建和 YAML 解析通过 | 优化 server 测试数据库模板并记录 race 分层结果 | -| 2026-08-14 | server 测试改为一次迁移模板 + 每测独立副本 | 普通 server 测试约 48.2s 降至约 36.5s;稳定 server race 子集约 12.4s 通过;完整 race 运行 267s 后仍未完成,未发现 race 报告 | 定位完整 race 慢点,再进入敏感数据访问边界 | -| 2026-08-14 | 将稳定 server race 子集固化为 `make test-server-race` 并接入 PR CI | 启停、发布 worker、凭证状态转换和锁内所有权复核场景纳入合并前 smoke race | 定位完整 race 慢点 | -| 2026-08-14 | 将管理员与账号 cookie 预置到 server 测试模板 | 普通 server 测试约 21.3s;完整 `go test -race ./internal/server` 约 194.3s 通过;阶段 1 完成 | 阶段 2:盘点敏感数据查询调用方 | -| 2026-08-14 | 新增 `CookieSummary`、`ListOwnedIDs`、`ExistsOwned` 及跨用户/无效 user ID 回归测试 | 阶段 2 第一个数据边界切片完成;故意无效密文摘要查询通过 | 迁移 server ownership helper,移除 `AllForUser` 所有权读取 | -| 2026-08-14 | Engine 登录态检查与接口续期改用 `GetCookieRuntimeData` | 只解密 Cookie 与 metadata;接口续期窄查询回归测试通过,未改变锁、token 清理和快照持久化语义 | 迁移 `persistRenewFlatCookie` 的 metadata 窄查询 | -| 2026-08-14 | 新增 `GetCookieMetadata` 并收窄 `persistRenewFlatCookie` | 扁平 Cookie 写回不再读取旧 Cookie、用户名或登录密码;损坏旧凭证回归测试通过 | 迁移 `handleMaxFailures` 的单值 Cookie 读取 | -| 2026-08-14 | `handleMaxFailures` 改用 `GetValue` | 恢复回调只读取 Cookie 明文;损坏登录密码回归测试通过,失败计数和重连行为保持不变 | 迁移 `persistPendingRenewCookies` 的异步续期读取 | -| 2026-08-14 | `persistPendingRenewCookies` 改用 `GetCookieRuntimeData` | 迟到 Cookie 合并只解密 Cookie 与 metadata;锁、并发重放和通知行为保持不变,回归测试通过 | 迁移 `refreshTokenWithMinGap` 的 metadata 读取 | -| 2026-08-14 | `refreshTokenWithMinGap` 改用 `GetCookieMetadata` | token 请求只解密 Cookie 快照 metadata;快照上下文和 token 刷新行为保持不变,回归测试通过 | 迁移 `adoptTokenResponseCookies` 的 metadata 读取 | -| 2026-08-14 | `adoptTokenResponseCookies` 改用 `GetCookieMetadata` | token 响应合并只解密 metadata;快照持久化和错误语义保持不变,回归测试通过 | 迁移 `databaseCredentialFingerprint` 的运行时凭证读取 | -| 2026-08-14 | `databaseCredentialFingerprint` 改用 `GetCookieRuntimeData` | token 凭证一致性校验只解密 Cookie 与 metadata;空值、指纹和错误语义保持不变,回归测试通过 | 迁移 `reloadCookieFromDB` 的运行时凭证读取 | -| 2026-08-14 | 完成阶段 2 当前 PR 切片“Server 平台凭证流程审计” | Server 平台、订单、发布、二维码和资料流程均不再读取完整账号详情;完整详情仅保留给登录设置与登录信息更新;窄查询回归测试、全量测试、race、vet、lint 和注释门禁通过 | 进行敏感数据边界最终审计,确认阶段 2 完成证据后进入阶段 3 | -| 2026-08-14 | 完成阶段 2 最终审计 PR 切片 | 生产 `GetDetails` 白名单仅保留登录设置与登录信息更新;新增跨数据库 Cookie/metadata/平台视图/所有权窄查询回归;全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:HTTP 错误结构盘点与第一批契约测试 | -| 2026-08-14 | 完成阶段 3 第一个 PR 切片“HTTP 错误结构盘点与第一批契约测试” | 共享错误 DTO、认证 401、健康检查和账号列表具名 DTO 已落地;React 请求层完成错误契约迁移;Go/React 全量测试、vet、lint、注释和前端构建通过 | 阶段 3:剩余认证与公共 API 错误迁移 | -| 2026-08-14 | 完成阶段 3 第二个 PR 切片“剩余认证与公共 API 错误迁移” | 初始化、密码修改、凭据校验、用户名冲突、公开设置故障和 SPA API 404 的状态码/错误码契约已统一;契约测试、全量测试、vet、lint、注释和 diff 门禁通过 | 阶段 3:订单与账号业务 API 错误响应迁移 | -| 2026-08-14 | 完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移” | 订单批量接口移除顶层 HTTP 200 + `success:false`,逐项失败保留行级状态并统一为 `message`;账号任务 502 改用统一错误 DTO;订单/账号契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:聊天、商品与自动化业务 API 错误响应迁移 | -| 2026-08-14 | 完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移” | 聊天发送和商品发布失败统一为 `code`/`message`/`request_id`,远端发布后的商品核对信息迁移到 `details`;React 错误类型、HTTP DTO 测试和业务契约测试已更新;前端类型检查、测试、构建及 Go 注释门禁通过 | 阶段 3:二维码登录、密码登录和剩余公共业务错误响应迁移 | -| 2026-08-14 | 完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移” | 二维码与密码登录遗留 HTTP 200 + `success:false` 已迁移为非 2xx 错误;账号不匹配保留 `scanned_account_id` 到 `details`;二维码/密码登录契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:统一业务成功响应具名 DTO 与版本化路径准备 | -| 2026-08-14 | 完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备” | 认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO;新增响应契约测试和 `/api/v1` 迁移边界文档;全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:剩余业务成功响应 DTO 与客户端契约收口 | -| 2026-08-14 | 完成阶段 3 第七个 PR 切片“剩余业务成功响应 DTO 与客户端契约收口” | 账号详情/设置、商品发布/同步、自动化规则/异常、订单详情/刷新/批量外层响应已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:剩余商品批量操作与设置/卡券/通知成功响应收口 | -| 2026-08-14 | 完成阶段 3 第八个 PR 切片“剩余商品批量操作与设置/卡券/通知成功响应收口” | 商品类目推荐、批量发布预检/任务、系统与用户设置、账号 AI 设置、卡券 CRUD/批量、通知渠道与账号绑定已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:剩余关键词回复、默认回复与账号任务成功响应收口 | -| 2026-08-14 | 完成阶段 3 第九个 PR 切片“剩余关键词回复、默认回复与账号任务成功响应收口” | 关键词基础/商品/类型规则、指定商品回复、默认回复、账号任务设置与运行记录已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:分析统计、管理员与剩余公共成功响应收口 | -| 2026-08-14 | 完成阶段 3 第十个 PR 切片“分析统计、管理员与剩余公共成功响应收口” | 管理员用户/账号/统计、用户仪表盘、订单分析、有效订单分页和二维码生成已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:公共成功响应兼容收尾与版本化迁移入口审计 | -| 2026-08-14 | 完成阶段 3 第十一个 PR 切片“公共成功响应兼容收尾与版本化迁移入口审计” | 系统、管理员和用户动态设置统一通过具名 map 边界类型;二维码状态保留非敏感扩展字段并过滤 Cookie,验证完成使用具名 DTO;React API 清理剩余 `Promise`/`get` 成功响应并补齐兼容类型;新增动态设置与二维码契约测试,明确旧路径仍保留、尚未宣称 `/api/v1` 可用;所有修改合并为一个可回滚提交 | 阶段 3:HTTP API 版本化兼容入口落地与调用方迁移 | -| 2026-08-14 | 完成阶段 3 第十二个 PR 切片“HTTP API 版本化兼容入口与会话调用方迁移” | 新增 `/api/v1/session/login`、`/api/v1/session/initialize`、`/api/v1/session` 与 `/api/v1/session/logout` 薄适配入口,全部复用既有认证 handler;React 登录、初始化、会话校验和登出调用已迁移;Go/React 契约测试确认新旧路径兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:账号 API 版本化兼容入口与调用方迁移 | -| 2026-08-14 | 完成阶段 3 第十三个 PR 切片“账号 API 版本化兼容入口与调用方迁移” | 新增 `/api/v1/accounts`、`/api/v1/accounts/details`、`/api/v1/accounts/runtime-status`、`/api/v1/accounts/{cid}` 与启停状态薄适配入口,全部复用既有账号 handler;React 账号摘要、详情、运行状态和启停状态调用已迁移;Go/React 契约测试确认新旧路径兼容且详情不泄露凭证;全量门禁通过并合并为一个可回滚提交 | 阶段 3:账号设置与资料 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第十四个 PR 切片“账号设置与资料 API 版本化兼容入口迁移” | 新增 `/api/v1/accounts/{cid}/settings`、`remark`、`pause-duration`、`auto-confirm`、`long-login` 和 `refresh-profile` 薄适配入口,全部复用既有账号 handler;React 账号设置、备注、暂停、自动确认、长登录和资料刷新调用已迁移;Go/React 契约测试确认新旧路径兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:账号凭证与登录信息 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第十五个 PR 切片“账号凭证与登录信息 API 版本化兼容入口迁移” | 新增 `/api/v1/accounts`、`/api/v1/accounts/{cid}`、`/api/v1/accounts/{cid}/login-info` 薄适配入口,复用既有 handler 和凭证锁;React 新增/更新 Cookie 与登录信息调用已迁移;Go/React 契约测试确认敏感字段不回传且旧路径兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:订单 API 版本化兼容入口与调用方迁移 | -| 2026-08-14 | 完成阶段 3 第十六个 PR 切片“订单 API 版本化兼容入口与调用方迁移” | 新增 `/api/v1/orders`、`/api/v1/orders/{order_id}` 的列表、详情和更新薄适配入口,复用既有订单 handler 与归属校验;React 列表、详情和更新调用已迁移;Go/React 契约测试确认新旧路径兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:订单刷新与批量操作 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第十七个 PR 切片“订单刷新与批量操作 API 版本化兼容入口迁移” | 新增订单刷新、单订单刷新、手动发货和导入 `/api/v1/orders...` 薄适配入口,复用既有订单 handler;React 刷新、单订单刷新、手动发货和导入调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:商品 API 版本化兼容入口与调用方迁移 | -| 2026-08-14 | 完成阶段 3 第十八个 PR 切片“商品 API 版本化兼容入口与调用方迁移” | 新增商品列表、详情、发布、更新和删除 `/api/v1/items...` 薄适配入口,复用既有商品 handler 与所有权校验;React 列表、详情、发布、更新和删除调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:商品同步与批量发布 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第十九个 PR 切片“商品同步与批量发布 API 版本化兼容入口迁移” | 新增商品同步、类目推荐、批量发布预检/任务/详情、取消、重试和结果下载 `/api/v1/items...` 薄适配入口,复用既有商品 handler;React 同步和批量发布调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:设置、卡券与通知 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第二十个 PR 切片“设置、卡券与通知 API 版本化兼容入口迁移” | 新增系统/用户/AI 设置、卡券和通知渠道/消息/账号绑定 `/api/v1/settings`、`/api/v1/cards`、`/api/v1/notifications` 薄适配入口,复用既有权限边界与 handler;React 设置、卡券和通知调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:聊天与账号任务 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第二十一个 PR 切片“聊天与账号任务 API 版本化兼容入口迁移” | 新增聊天 REST/WebSocket、账号任务设置/运行记录/执行 `/api/v1/chat...`、`/api/v1/account-tasks...` 薄适配入口,复用既有 handler 与权限校验;React 聊天 REST/WebSocket 和账号任务调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:关键词回复与默认回复 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第二十二个 PR 切片“关键词回复与默认回复 API 版本化兼容入口迁移” | 新增关键词基础/商品/类型规则、指定商品回复和默认回复 `/api/v1/reply-rules...`、`/api/v1/default-replies...` 薄适配入口,复用既有 handler 与权限校验;React 关键词、指定商品回复和默认回复调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:管理员、仪表盘与订单分析 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第二十三个 PR 切片“管理员、仪表盘与订单分析 API 版本化兼容入口迁移” | 新增管理员用户/账号/统计、仪表盘统计、订单分析和有效订单 `/api/v1/admin...`、`/api/v1/analytics...` 薄适配入口,复用既有权限边界与 handler;React 管理员统计、仪表盘和订单分析调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:二维码登录 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第二十四个 PR 切片“二维码登录 API 版本化兼容入口迁移” | 新增二维码生成、状态查询、状态持久化和验证完成 `/api/v1/qr-login...` 薄适配入口,复用既有认证、会话所有权和敏感字段过滤 handler;React 二维码生成、轮询和验证完成调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:密码登录及剩余公共调用方 API 版本化兼容入口迁移 | -| 2026-08-14 | 完成阶段 3 第二十五个 PR 切片“密码登录及剩余公共调用方 API 版本化兼容入口迁移” | 新增会话密码/凭证、账号删除、密码登录禁用、自动化规则/异常处理、订单删除和商品创建 `/api/v1/...` 薄适配入口,复用既有认证、权限和业务 handler;React 对应调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:版本化入口最终审计与旧调用方清零 | -| 2026-08-14 | 完成阶段 3 第二十六个 PR 切片“版本化入口最终审计与旧调用方清零” | 前端生产调用和批量结果下载已无业务旧路径;Vite 代理收敛为 `/api` 与健康检查;服务端补齐商品按账号列表、多规格和多数量兼容入口;Go/React/Vite 审计测试、全量测试、race、vet、lint、注释和构建门禁通过并合并为一个可回滚提交 | 阶段 4:订单应用服务边界提取 | -| 2026-08-14 | 完成阶段 4 第一个 PR 切片“订单应用服务边界提取” | 新增不依赖 `net/http` 的订单应用服务,覆盖列表、详情、更新、删除、导入、手动发货、批量刷新和单订单刷新;保留权限、事务、凭证锁、Cookie Jar 和 Session 续期语义;服务层测试、全量测试、race、vet、lint、注释门禁通过并合并为一个可回滚提交 | 阶段 4:订单响应 DTO 映射收口 | -| 2026-08-14 | 完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口” | 列表/详情/刷新响应视图由应用服务统一生成;错误分类模型替代 HTTP handler 中的错误文本判断;旧/版本化订单契约、全量测试、race、vet、lint、注释和 diff 门禁通过,合并为一个可回滚提交 | 阶段 4:商品发布应用服务边界提取 | -| 2026-08-14 | 完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取” | 新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;保留 worker、凭证锁、cancel map、租约、远端发布与自动化规则时序;新增服务层测试,Go 全量测试、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:账号登录应用服务边界提取 | -| 2026-08-14 | 完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取” | 新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;保留扫码会话锁、账号凭证锁和旧/版本化 HTTP 契约;新增服务层测试,Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:聊天与通知应用服务边界提取 | -| 2026-08-14 | 完成阶段 4 第五个 PR 切片“聊天与通知应用服务边界提取” | 新增不依赖 `net/http` 的通信应用服务,覆盖账号任务设置/执行/记录、聊天文字与图片发送、聊天历史读取/已读、通知渠道 CRUD、账号绑定和删除;保留 WebSocket 订阅、聊天事件广播、通知 outbox 与失败状态语义;新增服务层测试,Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:Server 事务与生命周期边界收口 | -| 2026-08-14 | 完成阶段 4 第六个 PR 切片“Server 事务与生命周期边界收口” | 新增 Server 统一 Unit of Work,订单更新与导入不再直接管理事务;新增后台任务生命周期登记入口,HTTP 优雅关闭与批量发布恢复扫描器统一纳入等待流程;修复服务不可用时 handler 先做资源归属校验导致状态码变化的问题;事务测试、Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:Server 直接依赖清理与应用服务装配收口 | -| 2026-08-14 | 完成阶段 4 第七个 PR 切片“Server 直接依赖清理与应用服务装配收口” | 统一装配订单、发布、登录、通信和分析应用服务;默认回复、账号设置、AI 设置、通知绑定、管理员查询及订单分析查询迁移到 repository 或应用服务边界;handler 不再直接访问 `Store.DB`;装配测试、Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 5:应用构造依赖验证与生命周期接口 | -| 2026-08-14 | 完成阶段 5 PR 切片“应用构造依赖验证与生命周期接口” | `Server.New` 在构造阶段校验 `Store/Manager`,聊天服务改用 option 注入并移除生产运行时 setter;新增幂等 `Start/Wait/Stop`,`Stop` 统一等待 HTTP、后台扫描器和批量 worker;`cmd/server` 迁移到显式生命周期入口;构造失败、重复启动/停止和 worker 等待测试、全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Engine 账号 facade 与运行状态边界 | -| 2026-08-14 | 完成阶段 6 第一个 PR 切片“Engine 账号 facade 与运行状态边界” | 将连接状态、失败计数、离线告警和业务任务生命周期分别提取为独立锁组件;`Account` 保留 facade,`Stop` 对并发调用保持幂等并等待已登记任务;新增生命周期并发回归测试,未改变 WebSocket、凭证、自动化和冻结风控逻辑;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Engine WebSocket 连接循环边界 | -| 2026-08-14 | 完成阶段 6 第二个 PR 切片“Engine WebSocket 连接循环边界” | `registerConnection` 在凭证锁内统一快照复核与 WebSocket 注册,`runConnectionSession` 统一心跳、接收、Token 轮换 goroutine 的创建/取消/等待;`Account` 继续负责凭证错误、风控和重连结果解释;新增会话收束测试,未改变冻结风控行为;全量测试、Engine race、Server race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Engine WebSocket 记录与消息分发边界 | -| 2026-08-14 | 完成阶段 6 第三个 PR 切片“Engine WebSocket 记录与消息分发边界” | 新增 `messageDispatcher` 与 `wsRecorder`,分别管理消息去重/防抖/并发投递和 WebSocket 诊断记录队列/worker;`Account` 仅保留 facade 与生命周期接线,动态 Handler、系统事件背压、聊天洪峰限流和 Stop 等待语义保持兼容;Engine 全量回归与并发测试、后续门禁通过并合并为一个可回滚提交 | 阶段 6:Engine 凭证状态与 Token 生命周期边界 | -| 2026-08-14 | 完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界” | 新增 `credentialState`,集中 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态;运行状态组件锁改名为 `runtimeMu`,保持 `Account` facade 字段访问兼容;Cookie 更新、Token 清理、风控恢复和 WS 注册前凭证快照复核语义保持不变;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 事件事实与规则匹配边界 | -| 2026-08-14 | 完成阶段 6 第五个 PR 切片“Automation 事件事实与规则匹配边界” | 新增 `eventFactRecorder`、`ruleMatcher` 和 `actionPlanner`;事件事实写入、规则查询和动作计划生成职责分离,`Center`/`Scheduler` 不再直接散落调用规则匹配;动作计划保持付款发卡优先、规格过滤和延迟快照语义,新增纯计划与无订单事实回归测试;Automation/Server race、全量测试、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 运行协调与动作执行边界 | -| 2026-08-14 | 完成阶段 6 第六个 PR 切片“Automation 运行协调与动作执行边界” | 新增 `automationRunCoordinator`,统一运行创建/恢复、动作前后检查点、延迟任务续租、账号门禁和不确定结果隔离;`Center` 保留兼容调用入口,外部动作三态语义、人工核对状态机和恢复游标保持不变;Automation 测试、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 发货、卡密与通知动作边界 | -| 2026-08-14 | 完成阶段 6 第七个 PR 切片“Automation 发货、卡密与通知动作边界” | 新增 `automationActionExecutor` 与 `deliveryNotifier`,统一确认发货、Cookie/Jar 合并、卡券锁与库存消费、消息错误三态分类和结果通知;`Center` 保留兼容入口,凭证锁、卡券库存、恢复唤醒和通知文案语义保持不变;新增动作执行器回归测试;Automation 测试、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 账号任务与凭证门禁边界 | -| 2026-08-14 | 完成阶段 6 第八个 PR 切片“Automation 账号任务与凭证门禁边界” | 新增 `accountTaskCoordinator`,统一账号状态门禁、自动评价/商品擦亮调度、任务租约、Session 指纹阻断、凭证恢复和 Cookie 同步;`Center` 保留公开任务入口,Session 失效恢复、任务幂等、失败重试和账号暂停语义保持不变;Automation 测试、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 7:React Rules feature 化与 API/行为测试边界 | -| 2026-08-14 | 完成阶段 7 第一个 PR 切片“React Rules feature 化与 API/行为测试边界” | 新增 `app/features/rules` 的 API 适配层、领域类型、数据 Hook、异常面板和交互状态模型;规则请求支持并行加载与请求代次门禁,保存动作阻断重复提交;行为测试覆盖成功、失败、重复提交、过期响应和页签切换;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React ItemList feature 化与批量发布行为边界 | -| 2026-08-14 | 完成阶段 7 第二个 PR 切片“React ItemList feature 化与批量发布行为边界” | 新增 `app/features/items` 的 API 适配层、批量任务类型、批量 Hook、批量状态模型和阶段指示器组件;批量预检、任务恢复、轮询过期响应、安全取消和失败重试均有独立状态边界;行为测试覆盖预检门禁、取消状态、失败重试、历史任务筛选和过期轮询响应;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React AccountList feature 化与账号运行状态行为边界 | -| 2026-08-15 | 完成阶段 7 第三个 PR 切片“React AccountList feature 化与账号运行状态行为边界” | 新增 `app/features/accounts` 的 API 适配层、账号数据与运行状态 Hook、账号编辑弹窗、登录/暂停状态模型;账号加载和运行状态轮询具备取消与代次门禁,密码登录响应按账号与代次隔离,兼容入口保留;行为测试覆盖账号切换、暂停/恢复、凭证失败、风控验证和过期响应;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React CardList feature 化与卡密库存/批量追加行为边界 | -| 2026-08-15 | 完成阶段 7 第四个 PR 切片“React CardList feature 化与卡密库存/批量追加行为边界” | 按 `app/features/cards` 提取卡密 API 适配层、库存数据 Hook、批量导入/追加状态 Hook 和弹窗组件;卡密筛选、追加预览、提交取消、失败重试与账号切换过期响应均由 feature 状态边界负责,保留旧组件入口和 API 路径;新增状态模型测试并通过前端类型检查、全量测试、注释检查和构建门禁,合并为一个可回滚提交 | 阶段 7:React OrderList feature 化与订单导入/刷新行为边界 | -| 2026-08-15 | 完成阶段 7 第五个 PR 切片“React OrderList feature 化与订单导入/刷新行为边界” | 按 `app/features/orders` 提取订单 API 适配层、查询/分页 Hook、导入 Hook、筛选栏和导入弹窗;订单查询与辅助数据支持并行加载、取消和代次门禁,导入支持文件预检、取消、失败重试和导入后刷新;新增筛选、导入归一化、API 取消信号和过期响应测试,保留旧组件入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Notifications feature 化与渠道/事件绑定行为边界 | -| 2026-08-15 | 完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界” | 按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Dashboard feature 化与统计/趋势查询行为边界 | -| 2026-08-15 | 完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界” | 按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Settings feature 化与系统配置校验边界 | -| 2026-08-15 | 完成阶段 7 第八个 PR 切片“React Settings feature 化与系统配置校验边界” | 按 `app/features/settings` 提取系统配置/模型/凭据 API 适配层、配置常量、表单状态和敏感字段校验;配置读取与保存支持并行加载、请求取消、失败重试和过期响应保护,登录凭据提交保留现有校验与重登录语义;新增配置裁剪、凭据校验、API 取消信号和请求代次测试,保留旧页面入口和 API 路径 | 阶段 7:React Chat feature 化与会话消息行为边界 | -| 2026-08-15 | 完成阶段 7 第九个 PR 切片“React Chat feature 化与会话消息行为边界” | 按 `app/features/chat` 提取聊天 API、会话筛选/消息合并状态、账号/会话/消息分页 Hook;会话切换、联系人分页和消息加载支持取消与请求代次保护,文本/图片发送支持失败重试,WebSocket 和滚动语义保持不变;新增会话筛选、消息去重、分页过期响应、发送取消与 API 取消信号测试,保留旧页面入口和 API 路径 | 阶段 7:React AccountAutomation feature 化与任务设置行为边界 | -| 2026-08-15 | 完成阶段 7 第十个 PR 切片“React AccountAutomation feature 化与任务设置行为边界” | 按 `app/features/accountAutomation` 提取账号任务 API、默认设置与重复执行状态模型、任务设置 Hook;账号切换支持取消和请求代次保护,保存/立即执行支持重复提交阻断、失败重试和结果刷新;新增默认值、动作门禁、API 取消信号测试,保留旧弹窗入口和 API 路径 | 阶段 7:React AccountList 子模块收口与页面组合边界 | -| 2026-08-15 | 完成阶段 7 第十一个 PR 切片“React AccountList 子模块收口与页面组合边界” | 新增 `useAccountSubmodules`,集中管理账号编辑、长登录、通知绑定、AI 设置和密码登录状态;编辑弹窗仅保留页面组合与二维码/删除职责,子模块请求支持并行加载、取消和账号/代次隔离;新增跨子模块过期响应、密码登录取消信号和路由边界测试;前端类型检查、全量测试和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React feature 依赖门禁与旧页面入口瘦身 | -| 2026-08-15 | 完成阶段 7 第十二个 PR 切片“React feature 依赖门禁与旧页面入口瘦身” | 新增 feature 依赖架构测试,禁止生产页面绕过 API 适配层直接使用共享网络客户端或 `fetch`;会话与健康检查纳入 `session/system` feature API,Sidebar 和 App 不再直接访问共享网络层;账号、卡密、订单和规则的旧 `components/*State` 转发入口及其测试迁移/删除,状态测试归属各自 feature;前端类型检查、184 个测试、注释门禁和构建门禁通过 | 阶段 8:DB 与事务治理第一批窄 repository 边界 | -| 2026-08-15 | 完成阶段 8 第一个 PR 切片“Chat 窄 repository 接口与服务依赖收口” | 新增 `chat.Repository`,聊天服务只持有会话、消息和账号归属所需的最小持久化接口;完整 `db.Store` 仅在构造适配器时出现,新增 `NewWithRepository` 和内存替身测试,保持聊天消息幂等、会话归属与订阅语义不变;Chat 全量测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:通知与账号任务窄 repository 边界 | -| 2026-08-15 | 完成阶段 8 第二个 PR 切片“账号任务窄 repository 与凭证门禁收口” | 新增 `automation.AccountTaskRepository`,账号任务协调器只持有账号启停/暂停、任务设置/租约、运行凭证和 Cookie 更新所需的最小接口;自动化中心保留 Store 装配适配器,Session 指纹阻断、续期恢复、任务幂等和 Cookie 同步语义保持不变;Automation 全量测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:通知与应用服务 repository 边界 | -| 2026-08-15 | 完成阶段 8 第三个 PR 切片“通知与通信应用服务 repository 边界” | 新增 `notify.Repository`,通知器仅持有渠道、SMTP 系统设置和 outbox 所需的最小接口,保留同步发送、异步租约、重试和测试发送语义;新增通信应用服务窄 repository,账号任务、通知渠道/绑定和聊天历史持久化不再直接访问完整 `db.Store`,实时账号、MTOP 和聊天服务仍由 Server 装配;通知/Server 定向测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:剩余应用服务与事务 repository 边界 | -| 2026-08-15 | 完成阶段 8 第四个 PR 切片“分析应用服务只读 repository 边界” | 新增分析服务窄 repository,统一封装 Dashboard 固定统计、订单分析聚合、有效订单分页、卡密库存读取和数据库方言;应用服务不再持有完整 `Server` 或直接访问 `Store.Analytics/Cards`,查询阶段错误、金额表达式和响应聚合语义保持不变;Server 全量测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:订单与发布应用服务 repository 边界 | -| 2026-08-15 | 完成阶段 8 第五个 PR 切片“订单应用服务 repository 与事务边界” | 新增 `orderRepository`,订单应用服务的订单/商品读写、用户归属、事务、凭证锁、续期 Cookie 和远端缺失清理均通过窄接口;平台 MTOP、运行时 Cookie 更新、自动化发货和通知编排仍由 Server 负责;订单列表、详情、导入、手动发货、单笔/批量刷新语义保持不变;Server 全量测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:发布应用服务 repository 与 worker 事务边界 | -| 2026-08-15 | 完成阶段 8 第六个 PR 切片“发布应用服务 repository 边界” | 新增 `itemPublishRepository`,单商品发布、类目推荐、预检批次创建、批次查询/取消/删除/失败重试及凭证 Cookie 持久化不再直接访问完整 `db.Store`;批量 worker 的租约状态机和后台生命周期暂保持原有 Server 接线,下一片整体迁移;单商品/批量发布测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:发布 worker 租约状态机 repository 边界 | -| 2026-08-15 | 完成阶段 8 第七个 PR 切片“发布 worker 租约状态机 repository 边界” | 发布恢复扫描、批次租约续期、明细抢占、远端发布检查点、结果落库、取消/中断收口和过期上传清理统一通过 `itemPublishRepository`;worker 不再直接访问 `PublishBatches`、Cookies 或 Items,平台 MTOP、自动化规则和生命周期等待语义保持不变;Server 全量测试、Server race、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:账号登录应用服务 repository 边界 | -| 2026-08-15 | 完成阶段 8 第八个 PR 切片“账号登录凭证与 Token repository 边界” | 新增 `accountLoginRepository`,账号登录服务的凭证创建/更新、Cookie Jar 元数据写回、凭证锁、Token 清理和运行状态读取统一通过窄接口;保留登录服务对资料刷新、登录审计和运行时重启的既有编排,未改变扫码幂等、Cookie 合并与凭证锁时序;Server 全量测试、Server race、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:登录审计与资料刷新共享 repository 边界 | -| 2026-08-15 | 完成阶段 8 第九个 PR 切片“登录审计与资料刷新共享 repository 边界” | 登录方式/状态、登录审计日志、账号资料更新、资料刷新凭证锁与平台视图读取统一通过 `accountLoginRepository`;运行时 Cookie 更新复用同一账号状态边界,移除无调用方的旧扁平 Cookie helper,保持 MTOP Cookie Jar 合并、资料刷新失败恢复和运行时唤醒语义不变;Server 全量测试、Server race、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:数据库直连与事务边界最终审计 | -| 2026-08-15 | 完成阶段 8 第十个 PR 切片“统一事务执行 repository 边界” | Server 统一事务入口不再直接持有 `Store.DB`,改由 `transactionRepository` 负责创建、提交和回滚事务;事务初始化失败、业务错误和提交失败均保持回滚语义,Server 依赖装配与事务回归测试已覆盖;Server 全量测试、Server race、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 9:架构依赖门禁与数据库直连最终审计 | -| 2026-08-15 | 完成阶段 9 第一个 PR 切片“Go/React 架构依赖门禁与数据库直连审计” | 新增 `tools/architecturecheck`,阻止 `internal/db`、`internal/xianyu`、`internal/browser` 反向依赖上层应用包,并阻止 Server 业务层直接创建事务;门禁接入 Makefile、CI 和 `make check`,同步更新阶段状态;架构检查、Go 全量测试、vet、lint、注释和前端注释门禁通过并合并为一个可回滚提交 | 阶段 9:兼容路由/字段调用方最终清理 | -| 2026-08-15 | 完成阶段 9 第二个 PR 切片“前端泛化兼容响应类型清理” | 移除未被调用方使用的 `ApiResponse` 和含义不清的 `LoginResponse`,认证初始化/登录统一使用 `SessionResponse`,登出、密码修改、账号、聊天、订单等操作统一使用 `OperationResponse`;未改变 HTTP 路径和业务状态字段;前端类型检查、184 个测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 9:账号 `cookie`/`note` 兼容字段调用方清理 | -| 2026-08-15 | 完成阶段 9 第三个 PR 切片“账号 cookie/note 兼容字段调用方清理” | `AccountDetail` 移除历史 `cookie`/`note` 别名,账号详情归一化、搜索/展示、编辑回填和运行状态测试统一使用 `value`/`remark`;编辑表单的 `cookie` 保留为真实用户输入字段;前端类型检查、184 个测试、注释检查、仓库 `make check` 和生产构建通过,嵌入式 bundle 已同步并合并为一个可回滚提交 | 阶段 9:旧路由与剩余兼容字段最终审计 | -| 2026-08-15 | 完成阶段 9 第四个 PR 切片“旧路由与剩余兼容字段最终审计” | 新增 API 兼容边界清单,明确旧服务端入口的保留条件、复用 handler 约束和删除证据要求;新增 React 架构测试,禁止生产 API 适配层重新调用未版本化 `/api/...` 路径;服务端新旧入口契约测试继续覆盖兼容行为,前端 185 个测试、类型检查和注释门禁通过并合并为一个可回滚提交 | 阶段 10:注释基线清零与严格门禁 | -| 2026-08-15 | 完成阶段 10 第一个 PR 切片“前端共享 types.ts 注释基线清零” | 为分页、会话、账号、聊天、订单、卡券、商品、自动化规则、统计、设置、AI、默认回复和通知 DTO 的全部字段补齐准确中文注释,解释字段职责、敏感性、状态和时间/数量单位;`frontend/types.ts` 历史注释基线清零,前端注释门禁、类型检查、185 个测试和生产构建通过并合并为一个可回滚提交 | 阶段 10:前端 services/api.ts 注释基线清零 | -| 2026-08-15 | 完成阶段 10 第二个 PR 切片“前端 services/api.ts 注释基线清零” | 为 API 适配层全部导出函数、局部变量、请求参数和内联响应字段补齐中文注释,明确认证、账号、聊天、订单、商品、卡密、自动化、设置和通知接口的数据职责;增强注释检查器对调用参数、类型字面量和循环变量内联注释的识别能力,`services/api.ts` 注释基线清零;前端注释门禁、类型检查和 185 个测试通过并合并为一个可回滚提交 | 阶段 10:前端 components/hooks 注释基线按领域清零 | -| 2026-08-15 | 完成阶段 10 第三个 PR 切片“前端 components/hooks 注释基线按领域清零” | 为账号、聊天、仪表盘、设置、规则、商品、卡密、订单、通知和二维码等组件、Hook、状态模块及其测试补齐函数、变量、回调和字段中文注释;补强注释检查器对箭头函数主体内联注释的识别,保持路由源码断言和 JSX 行为不变;目标目录注释基线清零,前端注释门禁、类型检查、185 个测试和生产构建通过并合并为一个可回滚提交 | 阶段 10:Go 核心领域注释基线按领域清零 | -| 2026-08-15 | 完成阶段 10 第四个 PR 切片“Go internal/server 注释基线按领域清零” | 为 HTTP handlers、应用服务、事务边界、批量发布、登录/二维码、请求解析、测试辅助和错误处理代码补齐函数、变量、字段及常量中文注释;增强 Go 注释检查器对多行文档块与分组 const/var 注释的识别;`internal/server` 注释基线清零,Server 定向测试和 Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/db 与 internal/xianyu 领域注释基线 | -| 2026-08-15 | 完成阶段 10 第五个 PR 切片“Go internal/db 注释基线按领域清零” | 为数据库 Store、repository、迁移/方言、多数据库适配、凭证与订单数据访问及其测试补齐函数、变量、字段和常量中文注释;`internal/db` 注释基线清零;数据库定向测试、SQLite 迁移与 CRUD 验证、Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/xianyu 领域注释基线 | -| 2026-08-15 | 完成阶段 10 第六个 PR 切片“Go internal/xianyu 注释基线按领域清零” | 为 MTOP 请求、协议编解码与签名、二维码登录、续期、WebSocket、Cookie 刷新和用户代理代码及其测试补齐函数、变量、字段和常量中文注释;`internal/xianyu` 及子包注释基线清零;平台协议定向测试和 Go 注释门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/engine、internal/automation 与其他领域注释基线 | -| 2026-08-15 | 完成阶段 10 第七个 PR 切片“Go internal/engine 注释基线按领域清零” | 为账号运行时、连接循环、凭证作用域、消息分发、回复策略、AI、令牌缓存和生命周期测试补齐函数、变量、字段及常量中文注释;`internal/engine` 注释基线清零;Engine 定向测试、`go test -race ./internal/engine`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/automation、internal/account、internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 | -| 2026-08-15 | 完成阶段 10 第八个 PR 切片“Go internal/automation 注释基线按领域清零” | 为自动化中心、账号任务、动作执行器、事件流水线、运行协调器、调度器、通知器及其测试补齐函数、变量、字段和常量中文注释;`internal/automation` 注释基线清零;Automation 定向测试、`go test -race ./internal/automation`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/account、internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 | -| 2026-08-15 | 完成阶段 10 第九个 PR 切片“Go internal/account 注释基线按领域清零” | 为账号管理器、凭证作用域、运行时启动/停止和生命周期测试补齐函数、变量、字段及常量中文注释;`internal/account` 注释基线清零;Account 定向测试、`go test -race ./internal/account`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 | -| 2026-08-15 | 完成阶段 10 第十个 PR 切片“Go internal/adapter 注释基线按领域清零” | 为 adapter 装配、平台运行视图、远端 Token CAPTCHA 流程及其测试补齐函数、变量、字段和常量中文注释;`internal/adapter` 注释基线清零;Adapter 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/renewal、internal/notify、internal/chat 等领域注释基线 | -| 2026-08-15 | 完成阶段 10 第十一个 PR 切片“Go internal/renewal 注释基线按领域清零” | 为续期冷却、调度器、平台运行凭证范围和相关测试补齐函数、变量、字段及常量中文注释;`internal/renewal` 注释基线清零;Renewal 定向测试、`go test -race ./internal/renewal`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/notify、internal/chat 等领域注释基线 | -| 2026-08-15 | 完成阶段 10 第十二个 PR 切片“Go internal/notify 注释基线按领域清零” | 为通知器、渠道与账号绑定、通知 outbox、SMTP 守卫及其测试补齐函数、变量、字段和常量中文注释;`internal/notify` 注释基线清零;Notify 定向测试、`go test -race ./internal/notify`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/chat 领域注释基线 | -| 2026-08-15 | 完成阶段 10 第十三个 PR 切片“Go internal/chat 注释基线按领域清零” | 为聊天 repository、消息服务、账号订阅、已读状态、事件广播及其测试补齐函数、变量、字段和常量中文注释;`internal/chat` 注释基线清零;Chat 定向测试、`go test -race ./internal/chat`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:进入非冻结 browser、cmd 与 tools 注释基线清理 | -| 2026-08-15 | 完成阶段 10 第十四个 PR 切片“Go 非冻结 internal/browser 注释基线按领域清零” | 为 Cookie、订单、密码登录、二维码刷新、生命周期、用户数据目录和浏览器辅助测试补齐函数、变量、字段及常量中文注释;严格跳过冻结的 slider/CAPTCHA 实现与测试;非冻结 browser 注释基线清零,冻结文件保留 664 项原有基线;Browser 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 cmd 与 tools 注释基线,并保留冻结基线边界 | -| 2026-08-15 | 完成阶段 10 第十五个 PR 切片“Go cmd 与 tools 注释基线按领域清零” | 为 server、tray、dbseed、dbverify、init-admin、browser-install、spike 命令及 iconconv 工具补齐函数、变量、字段和常量中文注释;`cmd` 与 `tools` 注释基线清零;命令/工具定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理剩余基础内部包并保留冻结 browser 基线 | -| 2026-08-15 | 完成阶段 10 第十六个 PR 切片“Go 基础内部包注释基线按领域清零” | 为 `internal/auth`、`internal/netguard`、`internal/logging`、`internal/version`、`internal/logsafe` 和 `internal/webui` 补齐函数、变量、字段及常量中文注释;这些基础包注释基线清零;定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交;当前 Go 基线仅保留冻结 browser CAPTCHA 文件 | 阶段 10:冻结基线边界审计、删除可清理基线并完成最终验收 | -| 2026-08-15 | 完成阶段 10 最终 PR 切片“冻结边界固化与全仓零基线验收” | Go/前端注释检查器显式识别冻结 CAPTCHA 文件并支持无基线严格模式;前端剩余注释债务清零;删除 `.commentlint/go-baseline.json` 与 `.commentlint/frontend-baseline.json`;无基线 Go/React 注释门禁、全量测试、类型检查和生产构建通过,冻结实现保持原样 | 阶段 10 完成:进入全仓重构计划最终审计 | -| 2026-08-15 | 完成测试覆盖率提升切片“确定性 Browser/命令入口覆盖与前端覆盖率采集” | 新增 Cookie 快照、浏览器池/持久化上下文、登录页、订单 DOM、滑块页面辅助、命令行入口测试;修复 Playwright 数值类型导致的登录成功误判;新增 Go `cover-browser`、前端 V8 `test:coverage` 与 Makefile 入口;普通 Go 全量覆盖率 70.9%,本地 Chromium 覆盖 Browser 约 60.0%,前端当前全源覆盖率为语句 19.22%;真实账号/外部平台流程仍明确不触网 | 下一步:按覆盖率报告继续补齐前端页面行为与 Browser 非账号错误分支,不降低门禁或伪造 100% | -| 2026-08-15 | 完成测试覆盖率提升切片“前端规则与领域状态边界补测” | 新增规则工具、账号运行态、批量任务、仪表盘、通知和聊天状态的确定性边界测试,覆盖默认值、空值、状态映射、过期响应、错误消息、SMTP 校验和时间格式化;前端 196 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 22.02%;页面组件与真实平台账号流程仍按覆盖率报告列为后续切片,不降低门禁或伪造 100% | 下一步:补齐 React 页面/Hook 行为测试,并继续覆盖 Browser 非账号错误分支 | -| 2026-08-15 | 完成测试覆盖率提升切片“React 纯展示组件静态渲染覆盖” | 新增无需浏览器环境的静态渲染测试,覆盖卡密图标类型、批量阶段高亮、通知事件选中状态和订单筛选栏结构;前端 200 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 22.53%;交互回调和页面 Hook 仍需后续使用可控测试替身继续补齐,不降低门禁或伪造 100% | 下一步:补齐 React 页面/Hook 行为测试,并继续覆盖 Browser 非账号错误分支 | -| 2026-08-15 | 完成测试覆盖率提升切片“React 通知与自动化异常组件分支覆盖” | 扩展静态渲染测试覆盖通知渠道空状态/停用/测试中状态,以及自动化运行异常和延迟任务的人工处理按钮;前端 202 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 23.00%;复杂表单交互与页面 Hook 仍需后续使用可控测试替身继续补齐,不降低门禁或伪造 100% | 下一步:补齐 React 页面/Hook 行为测试,并继续覆盖 Browser 非账号错误分支 | -| 2026-08-15 | 完成测试覆盖率提升切片“React SMTP 设置组件展示分支覆盖” | 新增 SMTP 设置面板静态渲染测试,覆盖密码显隐、保存中禁用状态、TLS/SSL 配置及发件人字段回填;前端 203 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 23.18%;表单事件回调和页面 Hook 仍需后续使用可控测试替身继续补齐,不降低门禁或伪造 100% | 下一步:补齐 React 页面/Hook 行为测试,并继续覆盖 Browser 非账号错误分支 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Hook 可控运行时与请求分支覆盖” | 引入 `@testing-library/react` 与 `jsdom` 测试运行时;新增账号任务 Hook 的加载、保存、执行、失败重试和禁用账号门禁测试;新增仪表盘 Hook 的并行加载、刷新、概览失败和非法日期范围测试;前端 209 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 26.45%;真实账号、外部平台和未注入的生产页面组合仍列为后续切片,不降低门禁或伪造 100% | 下一步:继续补齐 Accounts/Cards/Chat/Items/Notifications/Orders/Settings/Rules Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Settings Hook 请求与凭据行为覆盖” | 新增系统设置 Hook 的成功加载/保存、模型发现失败、凭据前端校验、后端拒绝和初始读取失败测试;前端 213 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 28.96%;真实重新登录和浏览器页面重载仍只验证可控响应与调度,不伪造真实会话 | 下一步:继续补齐 Accounts/Cards/Chat/Items/Notifications/Orders/Rules Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Orders Hook 查询与导入行为覆盖” | 新增订单查询 Hook 的分页加载、辅助数据映射、账号/商品名称解析测试;新增订单导入 Hook 的成功刷新关闭、文件格式校验和服务失败状态测试;前端 216 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 31.69%;真实订单平台数据仍不触网,仅验证可控接口契约与状态机 | 下一步:继续补齐 Accounts/Cards/Chat/Notifications/Rules Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Notifications Hook 渠道与 SMTP 行为覆盖” | 新增通知 Hook 的管理员/普通用户加载、渠道新建、启用切换、测试通知、SMTP 保存、表单校验、删除和失败提示测试;前端 219 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 34.81%;真实推送服务和账号绑定数据仍不触网,仅验证可控接口契约与状态机 | 下一步:继续补齐 Accounts/Cards/Chat/Rules Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Accounts Hook 账号与运行状态覆盖” | 新增账号数据 Hook 的账号详情/AI 配置并行加载、AI 失败隔离、账号详情失败和运行状态轮询测试;前端 221 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 36.02%;真实账号凭证、远端资料和平台运行状态仍不触网,仅验证可控接口契约与生命周期清理 | 下一步:继续补齐 Cards/Chat/Items/Rules Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Cards Hook 库存与批量操作覆盖” | 新增卡密库存 Hook 的成功/失败加载测试;新增批量操作 Hook 的追加预览、追加成功、批量创建成功和追加失败测试;前端 223 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 38.19%;真实卡密库存和外部 API 卡密仍不触网,仅验证可控接口契约与状态机 | 下一步:继续补齐 Chat/Items/Rules Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Chat Hook 加载、分页与发送覆盖” | 新增聊天 Hook 的账号/运行状态加载、会话与消息分页、已读标记、文字/图片发送、发送失败重试和 WebSocket 清理测试;前端 225 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 44.11%;真实聊天账号、外部平台消息和 WebSocket 服务仍不触网,仅验证可控接口契约与状态机 | 下一步:继续补齐 Items/Rules Hook、账号子模块 Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Items 批量发布 Hook 行为覆盖” | 新增批量发布 Hook 的任务恢复、类目推荐、文件预检、任务启动、取消、最近结果、失败重试、关闭清理及表单守卫测试;修复批量状态变化后重试回调捕获旧状态的依赖问题;前端 227 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 46.88%;真实商品文件、账号凭证和外部发布平台仍不触网,仅验证可控接口契约与状态机 | 下一步:继续补齐 Rules Hook、账号子模块 Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Rules 数据 Hook 页签与异常隔离覆盖” | 新增规则数据 Hook 的参考数据并行加载、自动化规则分页/筛选、服务端页码修正、异常列表失败隔离、关键词规则、默认回复和无账号守卫测试;前端 229 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 48.38%;真实账号规则和外部平台数据仍不触网,仅验证可控接口契约、请求代次和页签状态机 | 下一步:继续补齐账号子模块 Hook 与页面行为测试 | -| 2026-08-15 | 完成测试覆盖率提升切片“React Accounts 子模块编辑、AI 与密码登录覆盖” | 新增账号子模块 Hook 的编辑弹窗初始化、通知渠道加载/切换、长期登录保存、AI 设置保存、暂停重启、密码登录成功/取消以及绑定/长登录/AI 请求失败隔离测试;前端 232 个测试、类型检查、注释门禁通过,全源语句覆盖率提升至 52.59%;真实账号凭证、密码和平台登录流程仍不触网,仅验证可控接口契约、请求取消和生命周期状态机 | 下一步:继续补齐页面组件行为与剩余非账号外部错误分支 | -| 2026-08-15 | 调整测试覆盖率目标为业务代码边界 | 根据最新要求移除本轮新增的纯 UI 页面组件测试,不再把 Sidebar、页面空状态、页面结构和展示分支作为覆盖率目标;保留账号、聊天、商品批量、通知、订单、设置、规则等 Hook、状态机、请求编排和领域工具测试;后续覆盖率统计以业务模块为主,真实账号/外部平台流程仍仅在确实无法确定性模拟时跳过 | 下一步:继续补齐业务 Hook、请求编排与领域状态的未覆盖分支 | -| 2026-08-15 | 完成业务测试覆盖切片“AMap 地点查询适配边界” | 新增高德地点查询的无效坐标、无数据、失败响应、POI 字段校验和结果映射测试;仅使用浏览器全局与 PlaceSearch 可控替身,不触发真实地图网络请求;前端测试、类型和注释门禁通过,纯 UI 组件不纳入覆盖率目标 | 下一步:补齐请求层与业务 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“AMap 脚本加载错误边界” | 新增高德脚本首次注入、已有脚本节点、加载完成但对象缺失、脚本错误和超时测试;通过 jsdom 与动态模块隔离验证加载器生命周期,不访问真实地图网络;前端测试、类型和注释门禁通过 | 下一步:补齐业务 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“请求层方法与取消/错误边界” | 新增 PUT/DELETE 请求、纯文本错误、损坏 JSON 错误体、外部 AbortSignal 及上传取消测试;验证统一错误消息、认证失败通知和超时/取消区分;前端请求测试、类型和注释门禁通过,纯 UI 组件不纳入覆盖率目标 | 下一步:补齐业务 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“请求层网络异常与上传载荷” | 补充普通请求/上传请求网络异常透传、上传失败响应和原始错误载荷保留测试;覆盖请求层非业务网络分支,不依赖真实服务;前端请求测试、类型和注释门禁通过 | 下一步:补齐业务 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“账号自动化 Hook 失败与重试” | 补充任务设置读取失败、任务执行失败和失败重试测试,覆盖业务错误提示、重试动作和状态清理;不触发真实账号任务;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Accounts/Items/Notifications 等 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“商品批量发布 Hook 异常与轮询” | 补充类目推荐、批量预检、启动、取消、重试、最近结果和预检清理失败测试,并覆盖轮询完成后刷新商品/发货规则列表;使用 API 替身验证状态机,不触发真实商品文件或外部平台;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Accounts 子模块与 Notifications Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“账号子模块保存与密码登录异常” | 补充长期登录、AI、账号编辑、暂停保存失败,以及密码登录启动失败和状态查询失败测试;覆盖错误提示、状态收口和重试前置条件,不触发真实账号凭证或平台登录;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Notifications/Chat/Settings 等 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Notifications Hook 渠道与 SMTP 错误” | 补充通知渠道加载、编辑保存、启用切换和系统 SMTP 保存失败测试;验证错误提示、请求状态收口和管理员边界,不触发真实推送服务或邮件服务器;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Chat/Settings/Orders 等 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Chat Hook 实时连接与请求错误” | 新增 WebSocket 开关/消息/非法帧处理、联系人刷新、消息加载、历史分页和图片发送失败重试测试;仅使用 WebSocket 与 API 替身验证聊天状态机,不触发真实账号会话或平台消息;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Settings/Orders/Cards 等 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Orders Hook 部分失败导入与查询边界” | 补充订单账号回退名称、部分失败导入结果、导入重试、弹窗关闭清理测试;验证导入状态机和分页查询派生逻辑,不依赖真实订单文件或平台数据;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Settings/Cards/Rules 等 Hook 的未覆盖错误分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Settings Hook 保存与凭据异常” | 补充系统配置保存失败、登录凭据网络异常、成功提示和重载调度测试;验证错误状态、成功消息和表单请求边界,不触发真实会话或账号凭据;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Cards/Rules 与剩余可控业务分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Cards Hook 批量创建与追加重试” | 补充批量创建失败、追加失败重试和切换目标后阻止旧任务重试测试;验证库存加载、批量状态和目标隔离,不依赖真实卡密库存或外部服务;前端 Hook 测试、类型和注释门禁通过 | 下一步:补齐 Rules 与剩余可控业务分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Rules Hook 参考数据与异常筛选” | 补充空账号参考数据默认选择、异常面板空筛选和延迟任务账号过滤测试;验证规则页数据边界,不触发真实规则或账号数据;前端 Hook/领域状态测试、类型和注释门禁通过 | 下一步:继续补齐剩余可控业务分支并分类外部依赖分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Cards/Chat Hook 关闭、重试与滚动边界” | 补充卡密批量创建重试/关闭、聊天联系人分页失败、滚动距离策略和实时发送边界测试;验证请求清理与交互状态机,不触发真实卡密、账号或消息服务;前端 Hook 测试、类型和注释门禁通过 | 下一步:继续补齐剩余可控业务分支并分类外部依赖分支 | -| 2026-08-15 | 完成业务测试覆盖切片“通知/日期/SMTP 领域工具边界” | 补充邮件通知自定义 SMTP 开关解析、默认字段回填、日期自定义/昨天范围和 SMTP 布尔值归一化测试;覆盖纯业务工具的默认与异常分支,不依赖外部服务或 UI;前端测试、类型和注释门禁通过 | 下一步:继续补齐剩余可控业务分支并分类外部依赖分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Accounts Hook 运行状态轮询错误” | 补充账号运行状态轮询失败测试,验证账号列表保留、错误记录和轮询生命周期清理;不触发真实账号运行时;前端 Hook 测试、类型和注释门禁通过 | 下一步:继续补齐剩余可控业务分支并分类外部依赖分支 | -| 2026-08-15 | 完成业务测试覆盖切片“账号子模块通知与密码登录中间状态” | 补充通知渠道独立失败、AI 弹窗关闭、密码登录处理中和编辑弹窗关闭取消测试;覆盖子模块请求隔离与生命周期清理,不触发真实账号凭证或平台登录;前端 Hook 测试、类型和注释门禁通过 | 下一步:继续补齐剩余可控业务分支并分类外部依赖分支 | -| 2026-08-15 | 完成阶段性业务覆盖率审计 | 前端全量测试 50 个文件、268 个用例通过;业务代码 V8 覆盖率达到语句 92.47%、分支 73.48%、函数 93.41%、行 96.46%;纯 UI 组件按用户要求排除,剩余未覆盖项集中在 API 适配器未调用接口、请求取消/过期保护和真实平台生命周期分支,下一轮继续按可控性补测并保留外部依赖跳过说明 | 下一步:继续补齐剩余可控业务分支,最终形成业务覆盖率验收清单 | -| 2026-08-15 | 完成业务测试覆盖切片“通知 API 序列化与绑定响应” | 补充通知渠道更新配置/事件序列化和消息通知数组展开、非法绑定值忽略测试;覆盖 API 适配层确定性响应归一化,不触发推送服务;前端 API 测试、类型和注释门禁通过 | 下一步:继续补齐剩余 API 适配器与请求取消分支 | -| 2026-08-15 | 完成业务测试覆盖切片“商品发布与通知事件 API 归一化” | 补充商品发布 multipart 图片/地点字段序列化,以及通知事件 JSON/分隔符兼容解析测试;覆盖 API 适配层剩余确定性分支,不触发真实商品发布或推送服务;前端 API 测试、类型和注释门禁通过 | 下一步:继续补齐剩余 API 适配器与请求取消分支 | -| 2026-08-15 | 完成业务测试覆盖切片“AMap 地点映射与并发加载边界” | 补充 POI 缺失标识、成功空结果和并发查询共享脚本 Promise 测试;覆盖地图适配器剩余确定性分支,不访问真实地图网络;前端测试、类型和注释门禁通过 | 下一步:继续补齐剩余 API 适配器与请求取消分支 | -| 2026-08-15 | 完成业务测试覆盖切片“请求层成功文本响应” | 补充普通请求成功返回非 JSON 文本的确定性测试,覆盖共享请求层文本分支,不依赖真实服务;前端请求测试、类型和注释门禁通过 | 下一步:继续补齐剩余 API 适配器与请求取消分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Dashboard Hook 经营数据错误” | 补充趋势/有效订单并行请求失败和范围错误状态测试;验证错误信息收口,不触发真实统计或订单数据;前端 Hook 测试、类型和注释门禁通过 | 下一步:继续补齐剩余 API 适配器与请求取消分支 | -| 2026-08-15 | 完成业务测试覆盖切片“API 头像、订单分析、批量预检与卡密归一化” | 补充头像 URL 缓存参数/非法地址、数字天数分析、批量预检可选字段、无账号规则守卫和卡密 JSON 配置归一化测试;覆盖 API 适配层确定性分支,不依赖真实账号或平台数据;前端 API 测试、类型和注释门禁通过 | 下一步:继续补齐剩余 API 适配器与请求取消分支 | -| 2026-08-15 | 完成业务测试覆盖切片“订单筛选、通知数组与默认回复归一化” | 补充订单账号/状态筛选参数、通知事件数组格式和默认回复空字段保存载荷测试;覆盖 API 适配层剩余确定性分支,不依赖真实订单或推送服务;前端 API 测试、类型和注释门禁通过 | 下一步:继续补齐剩余 API 适配器与请求取消分支 | -| 2026-08-15 | 完成业务测试覆盖切片“请求层认证并发与预取消边界” | 补充并发认证失败去重、上传认证失败、非 JSON 上传错误读取失败和请求开始前已取消测试;验证统一请求层的认证事件、状态码兜底和取消错误收口,不依赖真实服务;前端请求测试、类型和注释门禁通过 | 下一步:继续补齐 Chat/Notifications/Orders 等 Hook 的可控生命周期分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Chat Hook 初始化、轮询与实时生命周期” | 补充聊天初始化失败、运行状态轮询失败重调度、历史消息成功滚动恢复、未知实时会话刷新、空消息帧和 WebSocket 错误关闭测试;仅使用 API、定时器、WebSocket 与 DOM 替身,不触发真实账号会话;前端 Chat Hook 测试、类型和注释门禁通过 | 下一步:继续补齐 Notifications/Orders/Items 等 Hook 的可控生命周期分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Notifications Hook 定时器、SMTP 与删除边界” | 补充 SMTP 初始加载失败、提示自动消失、弹窗关闭、用户拒绝删除和删除请求失败测试;验证通知状态清理和错误收口,不触发真实推送或邮件服务;前端 Notifications Hook 测试、类型和注释门禁通过 | 下一步:继续补齐 Orders/Items/Settings 等 Hook 的可控生命周期分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Orders Hook 查询防抖与辅助错误” | 补充订单主查询失败、搜索文本防抖标准化和账号/商品辅助数据失败测试;验证订单分页状态、请求参数和辅助数据隔离,不依赖真实订单文件或平台数据;前端 Orders Hook 测试、类型和注释门禁通过 | 下一步:继续补齐 Items/Settings 等 Hook 的可控生命周期分支 | -| 2026-08-15 | 完成业务测试覆盖切片“Items Hook 批量任务守卫与轮询错误” | 补充无最近任务、无预检、无有效行、用户拒绝取消、不可重试任务和轮询失败测试;验证批量发布状态机前置条件与错误收口,不触发真实商品文件或外部发布平台;前端 Items Hook 测试、类型和注释门禁通过 | 下一步:继续补齐 Settings/Accounts 等 Hook 的可控生命周期分支 | -| 2026-08-15 | 完成阶段性业务覆盖收口切片“请求、账户、卡密、订单与设置边界” | 补充上传超时、批量发布空输入、卡密批量操作空守卫、订单无文件导入、设置外部点击与重载调度、账户绑定移除/AI 默认值/密码终态,以及仪表盘和聊天领域排序时间边界;前端全量 50 个文件、301 个用例通过,语句覆盖率提升至 96.58%、函数 97.25%、行 99.63%;纯 UI 和真实账号/平台流程仍按边界排除 | 下一步:继续处理剩余可控的过期响应、取消清理和领域分支,形成最终业务覆盖率验收清单 | -| 2026-08-15 | 完成业务测试覆盖切片“账号任务、账号轮询与聊天实时边界” | 补充账号任务保存并发门禁、账号运行状态下一轮定时轮询、通知绑定移除/暂停状态更新、密码登录处理中轮询与关闭清理、聊天空发送/滚动守卫/未知会话排序,以及规则分页兼容入口测试;前端注释门禁、定向测试和类型检查通过,阶段覆盖率提升至语句 97.49%、函数 99.08%、行 99.86%;过期响应保护仍按真实取消时序分类保留 | 下一步:继续评估通知、卡密、设置与请求层过期响应是否能在不引入不稳定时序的前提下补测 | -| 2026-08-15 | 完成业务测试覆盖切片“通知与批量任务过期响应并发” | 补充通知渠道刷新丢弃旧响应、批量轮询防并发和关闭后旧响应失效,以及普通请求纯文本错误读取失败测试;验证请求代次和轮询保护,不触发真实推送、商品或平台服务;前端注释门禁、定向测试和类型检查通过 | 下一步:执行全量回归、覆盖率终审并记录仍需真实取消时序或不可达代码分支 | -| 2026-08-15 | 完成业务测试覆盖切片“卡密、仪表盘、设置与订单过期响应” | 补充卡密库存刷新、仪表盘经营数据、系统设置和订单查询的重复请求旧响应隔离测试;前端全量覆盖率达到语句 98.00%、函数 100%、行 99.86%,分支 79.82%;剩余未覆盖主要为取消/卸载时序保护、订单相似标题不可达分支和防御性条件组合 | 下一步:执行最终全量回归并形成业务覆盖率验收与跳过项清单 | -| 2026-08-15 | 完成阶段性业务覆盖率终审 | 前端 50 个测试文件、312 个用例通过;业务代码覆盖率为语句 98.00%(2500/2551)、函数 100%(547/547)、行 99.86%(2178/2181)、分支 79.82%(1385/1735);所有业务函数均有测试入口。剩余分支集中在请求取消/卸载后旧响应保护的极端时序、真实账号或外部平台会话生命周期,以及订单相似标题判断中被前置标题返回遮蔽的不可达路径;纯 UI 组件按约束排除 | 下一步:后续新增业务函数必须同步测试与中文注释,若改变取消时序或外部依赖契约需重新审计覆盖率 | - -## 11. 审计重开后的执行切片 - -以下切片是当前唯一有效的后续入口。每个切片完成后必须:更新本表、补齐针对性测试、运行适用门禁,并创建一个中文提交;未满足“完成条件”不得标记为已完成。 - -| 优先级 | PR 切片 | 主要范围 | 完成条件 | -| --- | --- | --- | --- | -| P0 | 敏感系统设置与运维输出脱敏 | `SystemSettings.Redacted`、敏感值 retain/replace/clear、管理端响应、dbverify 指纹输出、前端敏感字段状态 | HTTP 响应和 React 状态不出现秘密;空值显式清除、缺省值保留;Go/React 回归覆盖;三库迁移测试通过;显式 `values` 不得携带敏感键 | -| P1 | 应用 Port 与架构允许边 | `internal/application/orders`、订单命令/结果 DTO、基础设施适配器、`architecturecheck` | Server 不再创建或持有订单应用实现;Port 不出现 `sql.Tx`、`db.*`、HTTP 类型;架构门禁能主动拒绝违规 | -| P1 | 凭证快照与账号操作协调器 | 凭证版本、短锁快照、外部调用重试/合并、每账号有界协调、锁指标和锁 Map 回收 | 慢速外部调用不持有共享凭证锁;并发更新有版本冲突测试;锁等待和队列可观测 | -| P1 | 生命周期与删除 fencing | `Server.Stop(ctx)`、`Manager.Stop(ctx)`、StopAll 并发收束、账号删除任务登记和状态 fencing | 所有等待受关闭 Context 限制;删除接口不会产生游离 Stop goroutine;超时有明确错误和可追踪任务 | -| P1 | 外部动作补偿与 reconciliation | 手动发货、本地订单状态、自动化准备检查点、reconciliation/outbox 表和重试 worker | 外部成功/本地失败统一返回三态结果;不会重复执行不可逆动作;补偿记录可恢复、可审计 | -| P2 | 商品/订单批量同步 | 用户范围 Join、游标分页、批量 Upsert、规格探测缓存和受限并发 | 消除逐账号/逐订单 N+1;错误不再被忽略;SQLite/MySQL/Postgres 查询计划和大数据量测试有证据 | -| P2 | HTTP 契约与兼容退场 | 批量 DTO、错误字段统一、旧路由使用量、Deprecation/Sunset 和删除版本 | 新增接口不使用匿名动态结果;旧入口有遥测、期限和兼容测试 | -| P2 | React 页面边界与初始包体 | 页面迁移到 feature、路由懒加载、Provider/路由壳、bundle budget | App 不同步加载全部页面;首屏预算门禁通过;遵循并行请求、动态导入和避免重复渲染规范 | -| P2 | 复杂度与注释真实性 | 长函数拆分、复杂度门禁、模板注释黑名单、冻结文件精确例外 | 新增/修改函数和变量有准确中文语义注释;模板注释不得通过门禁;冻结 CAPTCHA 仅按文件例外 | - -### 11.1 当前切片完成记录 - -| 日期 | 切片 | 状态 | 证据 | -| --- | --- | --- | --- | -| 2026-08-15 | 审计重开与完成条件纠偏 | 已完成 | 已将阶段 2、4、5、8、9、10 从“已完成”改为“进行中”,建立九个可回滚 PR 切片,并明确“测试通过不等于架构完成”的新验收规则 | -| 2026-08-15 | P0 敏感系统设置与运维输出脱敏 | 已完成 | `SystemSettings.Redacted`、敏感值 retain/replace/clear、管理端脱敏、已知敏感调用方审计、集中式日志属性脱敏和 dbverify 指纹输出均已收口;真实执行 SQLite、MySQL 8.4、PostgreSQL 17 的 `make test-multidb` 全部 `TestMultiDB_*` 通过,Go/React 回归、类型/构建、架构和中文注释门禁通过;高频运行时窄视图不逐次写审计的边界已记录并有测试,不再把 SQLite 单库结果误判为三库证据 | -| 2026-08-15 | P1 订单读模型 Port 与架构依赖门禁 | 已完成 | 新增 `internal/application/orders` 纯业务 `OrderRow`/`ListFilter`/`Reader`;订单列表适配器负责 `db.*` 到应用模型的转换;架构门禁统一模块路径、禁止应用层依赖 `db/server/xianyu/browser/sql/http`,并对 Server 新增低层依赖要求临时白名单;新增门禁测试,`make check` 通过。订单写入事务 Port、其他应用服务和既有白名单仍未完成,阶段 4/8/9 继续保持“进行中” | -| 2026-08-15 | P1 订单事务 Writer Port | 已完成 | 新增 `orders.OrderPatch`、`ItemWrite`、`UpsertOptions`、`Writer` 和 `UnitOfWork`;订单更新、导入、手动发货和刷新统一通过应用 Writer,`*sql.Tx` 仅存在于 Server 基础设施适配器;保留现有提交/回滚语义并通过订单回归与 `make check`。订单实体读取、凭证 Port、其他应用服务和 Server 白名单仍未完成,阶段 4/8/9 继续保持“进行中” | -| 2026-08-15 | P1 订单实体读取与平台运行视图 Port | 已完成 | 新增纯应用层 `Order`、`ItemInfo`、`PlatformRuntimeData`;订单详情、商品读取、订单分页和刷新凭证读取不再通过 repository 暴露 `db.Order`、`db.ItemInfo`、`db.OrderRow` 或 `db.CookieDetail`;Server 到现有自动化/会话辅助函数保留显式边界适配;新增字段完整性转换测试,`make check` 和注释门禁通过。该三切片仅收口订单 Port,凭证协调器、生命周期、补偿、批量同步和其他领域依赖仍未完成,阶段 4/8/9 继续保持“进行中” | -| 2026-08-15 | P1 凭证快照与账号操作协调器(订单详情切片) | 已完成 | `Store.LockAccountCredentials` 增加引用计数和空闲 entry 回收,并保持同账号互斥与重复释放幂等;订单详情流程改为锁内读取、锁外执行慢速 MTOP、锁内重读提交,检测到期间凭证变化时丢弃旧响应;新增锁回收、并发互斥、慢速 I/O 不占锁和 race 回归测试,`make check`、注释门禁及聚焦 race 通过。其他凭证调用方仍待迁移,版本化持久化冲突控制和协调指标仍未完成,阶段 2/4/5/8/9 继续保持“进行中” | -| 2026-08-15 | P1 凭证快照与账号操作协调器(API 续期切片) | 已完成 | `apiCookieRenewOne` 改为锁内读取、锁外执行 `renewAPI`、锁内重读提交;外部调用期间凭证变化时使用 `RebaseResponseCookies` 基于最新 Cookie/metadata 重放 `Set-Cookie`,无可重放数据则拒绝旧快照写回;新增慢 I/O 不占锁和并发更新保留测试,续期全量测试、聚焦 race 与注释门禁通过。登录续期、Engine、Automation 和版本化持久化冲突控制仍未完成,阶段 2/4/5/8/9 继续保持“进行中” | -| 2026-08-15 | P1 凭证快照与账号操作协调器(登录态检查切片) | 已完成 | `loginRenewOne` 改为锁内读取、锁外执行 `loginuser.get`、锁内重读提交;检查期间凭证发生变化时丢弃基于旧快照的响应 Cookie,避免覆盖并发更新;保留完整 Cookie Jar 权威持久化、Session 过期恢复和禁用账号语义;新增慢 I/O 不占锁及旧响应拒绝测试,续期全量测试、聚焦 race、注释门禁通过。Engine、Automation、剩余 Server 调用方和版本化持久化冲突控制仍未完成,阶段 2/4/5/8/9 继续保持“进行中” | -| 2026-08-15 | P1 凭证快照与账号操作协调器(Engine 登录态检查切片) | 已完成 | `Account.tryLoginStatusCheck` 改为锁内读取、锁外执行登录态检查、锁内重读提交;检查期间数据库 Cookie/metadata 发生变化时丢弃旧会话响应,避免更新运行时和数据库为过期状态;新增 Engine 慢 I/O 不占锁及并发旧响应拒绝测试,Engine 全量测试、聚焦 race 和注释门禁通过。Engine 其他 token/续期路径、Automation、Server 其他调用方和版本化持久化冲突控制仍未完成,阶段 2/4/5/8/9 继续保持“进行中” | -| 2026-08-15 | P1 凭证快照与账号操作协调器(Engine API 续期切片) | 已完成 | `Account.tryAPIRenewUsing` 保留 `refreshMu` 的同账号刷新串行语义,但改为锁内读取、锁外执行续期回调、锁内重读提交;外部期间凭证变化时用 `RebaseResponseCookies` 基于最新状态合并 `Set-Cookie`,无可重放数据则拒绝旧状态;新增慢 I/O、并发锁获取和 Cookie 合并测试,Engine 全量测试、聚焦 race、注释门禁通过。Engine Token 刷新、Automation、Server 其他调用方和版本化持久化冲突控制仍未完成,阶段 2/4/5/8/9 继续保持“进行中” | -| 2026-08-15 | P1 凭证快照与账号操作协调器(Engine Token 刷新切片) | 已完成 | `refreshTokenWithMinGap` 保留 `refreshMu` 的同账号 Token 刷新和风控重试串行语义,但网络请求、风控恢复均在共享凭证锁外执行;每次响应提交前重读最新 Cookie/metadata,检测到并发变化时丢弃旧 Token 响应并使用最新快照重试;新增慢 I/O、锁可获取和并发 Cookie 变化重试测试,Engine 全量测试、聚焦 race、注释门禁通过。Automation、Server 其他调用方和版本化持久化冲突控制仍未完成,阶段 2/4/5/8/9 继续保持“进行中” | -| 2026-08-15 | P0 敏感系统设置命令语义切片 | 已完成 | 管理端系统设置更新新增 `values`/`secrets` 分离 DTO;敏感设置仅接受 `retain`、`replace`、`clear` 命令,普通 `values` 和旧版顶层字段均拒绝敏感键;数据库原子应用普通设置与敏感命令;补充 Go 数据库/HTTP 回归和 React API 请求体测试,定向 Go/React 测试与前端类型检查通过。P0 三库迁移回归、所有运维输出和敏感访问审计仍待完成 | -| 2026-08-15 | P1 订单运行时 Port 边界切片 | 已完成 | 订单应用服务不再持有 `*Server`,改由 `orderRuntimePort` 接收平台、自动化、通知和运行时 Cookie 能力;`serverOrderRuntimeAdapter` 仅在 Server 装配边界桥接现有实现;订单行为、凭证锁和错误语义保持不变;Server 全量测试、架构门禁和中文注释门禁通过。订单 Port 仍位于 `internal/server`,repository 仍有基础设施适配职责,其他应用服务和 `sql.Tx`/`db.*` 全面隔离尚未完成 | -| 2026-08-15 | P1 订单 Repository Port 迁移切片 | 已完成 | 将 `orderRepository` 从 `internal/server` 迁移为 `internal/application/orders.Repository`;应用 Port 只暴露领域模型、`Writer`/`UnitOfWork`、凭证协调和平台运行视图,不出现 `sql.Tx`、`db.*`、HTTP 或 Server 类型;Server 仅保留 `storeOrderRepository` 基础设施适配器;订单全量测试、架构门禁和中文注释门禁通过。订单运行时 Port 仍依赖 Server 适配边界,其他应用服务及事务/批量治理仍未完成 | -| 2026-08-15 | P0 敏感设置跨方言回归补强 | 已完成 | `TestMultiDB_SettingsQuoteKey` 新增敏感设置 `replace/retain/clear`、脱敏读取和密文解密回归;SQLite 在当前环境执行通过,MySQL/Postgres 仅在 `TEST_MYSQL_URL`/`TEST_POSTGRES_URL` 提供时自动加入,当前环境未提供外部数据库,因此不宣称三库实测完成。P0 的运维输出和敏感访问审计仍待完成 | -| 2026-08-15 | P1 应用 Port 类型架构门禁切片 | 已完成 | `architecturecheck` 改用完整 AST 扫描 `internal/application` 类型声明,主动拒绝 `db.*`、`sql.Tx` 和 `*Server` 泄露;新增正反例门禁测试;现有订单 Port 通过扫描,架构门禁与中文注释门禁通过。Server 允许边、订单平台 Port 和其他应用服务仍需继续迁移,不能据此宣称目标架构完成 | -| 2026-08-15 | P1 生命周期上下文边界切片 | 已完成 | `Account.StopContext`、`Manager.StopContext/StopAllContext` 和 `Server.Stop` 的 HTTP、后台任务及 worker 等待均受调用方 Context 限制;超时后未完成账号仍保留在管理表,避免误报已清理;`cmd/server` 使用关闭上下文停止账号;新增账号与 Server 超时回归及聚焦 race 测试通过。账号删除游离 goroutine、调度器等待和删除 fencing 仍未完成,阶段 5 继续保持“进行中” | -| 2026-08-15 | P1 账号删除停止任务登记切片 | 已完成 | 删除账号后的 `Manager.StopContext` 不再通过游离 goroutine 调用,而是登记到 Server `backgroundWG`;Server 关闭会等待或按 Context 收束该任务;新增删除 handler 等待后台任务回归。删除状态 fencing、任务 ID 和调度器 Context-aware 等待仍未完成,阶段 5 继续保持“进行中” | -| 2026-08-15 | P1 手动发货补偿记录与三态结果切片 | 已完成 | 新增跨方言 `order_reconciliations` 表及 `OrderReconciliations` 存储;手动确认发货在远端成功、本地订单写入失败时记录 pending 补偿任务,响应状态改为 `reconciliation_required`,不再误报凭证保存失败;React 批量结果类型同步补偿字段,SQLite 补偿生命周期回归和全量门禁通过。补偿 worker、自动化准备阶段的所有忽略错误和其他外部动作仍待治理,阶段 8 继续保持“进行中” | -| 2026-08-15 | P2 商品列表用户范围批量查询切片 | 已完成 | 新增 `Items.ListForUser`,通过 `cookies` JOIN 一次读取用户范围商品,按账号筛选仍保留归属校验;`listItems` 删除逐账号循环和被忽略的查询错误,数据库失败统一返回错误;新增跨用户/账号筛选回归,Go/前端门禁通过。商品规格远端 N+1、批量 Upsert 和订单同步仍待治理,阶段 8 继续保持“进行中” | -| 2026-08-15 | P1 商品全量同步凭证锁边界切片 | 已完成 | 商品全量同步和规格探测改为锁外执行远端 I/O,返回后重读凭证快照;检测到并发凭证更新时跳过旧响应 Cookie 写回,避免覆盖新状态;新增远端阻塞期间同账号锁可获取回归;同时将迁移回滚测试改为按当前 Goose 版本动态回滚,避免新增迁移导致旧字段误判。Server/DB 定向测试、注释门禁和 `make check` 通过。商品分页同步、规格探测缓存和订单同步仍待治理,阶段 2/5/8 继续保持“进行中” | -| 2026-08-15 | P1 订单刷新凭证锁边界切片 | 已完成 | 订单发现和详情 chunk 的远端 MTOP 请求改为锁外执行;完成后重读平台凭证快照,检测并发更新时跳过旧 Cookie 写回并保留明确结果;新增订单发现阻塞期间同账号锁可获取回归,订单/Server 定向测试和中文注释门禁通过。订单刷新仍需继续治理批量订单读取、批量 Upsert、游标分页和后台 Job 化,阶段 2/5/8 继续保持“进行中” | -| 2026-08-15 | P2 订单缺失状态批量写入切片 | 已完成 | `SoftDeleteMissingForCookie` 改为单条 `NOT IN` 批量 UPDATE,消除逐订单读取与逐条写入;空线上订单集合和保留订单回归均覆盖,数据库注释门禁与定向测试通过。订单详情逐单 Upsert、刷新后台 Job、游标分页和三库大数据量查询计划仍待治理,阶段 8 继续保持“进行中” | -| 2026-08-15 | P1 订单补偿恢复 worker 切片 | 已完成 | 新增 `internal/reconciliation` 服务和受 Server `backgroundWG` 管理的扫描器;pending 手动发货补偿会重试本地订单状态写入,成功后标记 resolved,失败保留 pending 并递增 attempts;新增成功恢复/失败重试测试,定向测试与中文注释门禁通过。更广泛自动化动作补偿、指数退避和运维查询接口仍待治理,阶段 5/8 继续保持“进行中” | -| 2026-08-15 | P1 账号删除生命周期 fencing 切片 | 已完成 | 删除流程新增账号级 `BeginStopping/EndStopping` fencing,停止窗口内拒绝新的 runtime 启动;删除前停止 runtime 改为受 5 秒请求 Context 约束的同步收束,超时返回明确冲突,不再创建游离 Stop goroutine;重新取得凭证锁后复核账号归属再删除,避免停止窗口内误删被替换账号;新增 Manager fencing 回归测试,Go/Server 定向测试、`make check` 和 Go/React 注释门禁通过。调度器 Context-aware 等待、删除任务 ID/状态查询、其他生命周期任务统一清单仍待治理,阶段 5 继续保持“进行中” | -| 2026-08-15 | P2 订单详情分片事务写入切片 | 已完成 | 订单详情远端请求仍在锁外执行;每个详情分片先收集成功结果,再通过订单应用 `UnitOfWork` 在单事务内提交,避免逐订单独立事务和分片内部分提交;事务失败时整片结果统一失败并保留远端会话收束逻辑;订单刷新定向测试、`make check`、架构和中文注释门禁通过。尚未实现真正单 SQL 多行 UPSERT、游标分页和后台 Job 化,P2 批量同步仍保持“进行中” | -| 2026-08-15 | P2 订单刷新复合游标扫描切片 | 已完成 | 订单刷新应用 Port 移除 OFFSET 分页入口,数据库新增 `created_at + order_id` 复合游标查询并统一扫描模型;刷新流程按游标读取每个账号订单,加入游标不推进保护;1001 条订单无重复扫描、订单/Server 定向测试和中文注释门禁通过。用户订单列表 HTTP 分页仍是页码语义;真正单 SQL 多行 UPSERT、后台 Job 化、SQLite/MySQL/Postgres 查询计划证据仍待完成,P2 批量同步保持“进行中” | -| 2026-08-15 | P2 商品多规格探测批量与并发边界切片 | 已完成 | 商品同步先用 `MultiSpecFlags` 一次读取本地多规格标记,消除逐商品数据库查询;剩余远端详情探测使用 4 路有界并发,Session 过期可取消同批次探测,普通单项失败保留告警并继续;新增批量标记和并发上限回归测试,定向测试与中文注释门禁通过。跨请求缓存、跨批次去重、平台限流指标和 MySQL/Postgres 查询计划仍待完成,P2 批量同步保持“进行中” | -| 2026-08-15 | P2 商品多规格跨请求缓存切片 | 已完成 | Server 新增按账号/商品隔离的 10 分钟 TTL 多规格缓存;同步成功结果(含 false)均缓存,后续同步命中缓存时跳过远端探测,过期项自动清理;新增缓存命中、过期和并发探测回归测试,注释门禁通过。跨实例共享缓存、主动失效通知、平台限流指标和 MySQL/Postgres 查询计划仍待完成,P2 批量同步保持“进行中” | -| 2026-08-15 | P2 订单复合游标索引与查询计划切片 | 已完成 | SQLite/MySQL/Postgres 新增 `idx_orders_cursor(cookie_id, deleted_at, created_at, order_id)` 复合索引;新增 SQLite `EXPLAIN QUERY PLAN` 回归,确认订单游标查询使用该索引;迁移、订单扫描和中文注释门禁通过。MySQL/Postgres 实际执行计划仍需外部数据库环境验证,P2 批量同步保持“进行中” | -| 2026-08-15 | P1 订单刷新持久化后台任务切片 | 已完成 | 新增 SQLite/MySQL/Postgres `order_refresh_jobs` 迁移及应用层 `RefreshJobRepository` Port;订单刷新 HTTP 端点改为 202 + 用户隔离的状态查询,后台 worker 受 Server 生命周期管理,使用 worker token/lease fencing,并提供过期任务恢复扫描;React 客户端改为可取消的状态轮询;新增任务生命周期、跨用户隔离、旧 worker 拒绝写入、成功/失败/取消和 HTTP/前端契约回归;Go 全量测试、架构/中文注释门禁、前端 317 测试、类型检查和生产构建通过。仍待补充取消端点、进度事件、MySQL/Postgres 实际任务迁移回归与统一运维查询,阶段 4/5/8/9 继续保持“进行中” | -| 2026-08-15 | P1 订单运行时 Port 基础设施类型收口切片 | 已完成 | `orderRuntimePort` 的完整自动化发货参数改为应用层 `orders.Order`,Cookie 会话持久化参数改为 `orders.PlatformRuntimeData`;`db.Order`/`db.CookieDetail` 转换下沉到 Server 装配适配器,业务服务不再通过运行时 Port 接触数据库模型;补充订单与平台视图边界转换回归,架构门禁、中文注释门禁和订单定向测试通过。订单应用服务实现仍位于 `internal/server`,Port 仍含平台协议接口,其他应用服务和基础设施适配器继续按后续切片迁移,阶段 4/8/9 保持“进行中” | -| 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 保持“进行中” | -| 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 保持“进行中” | -| 2026-08-15 | P1 订单刷新应用服务迁移切片 | 已完成本切片 | 新增 `internal/application/orders.RefreshService`、刷新 Port 和具名结果模型;单笔刷新、订单发现、缺失清理、复合游标筛选、详情分片事务写入、Cookie 会话收束和会话过期恢复从 `internal/server/order_service.go` 迁入应用层,Server 仅保留运行时/存储适配与兼容 DTO 转换;删除旧单笔/批量刷新实现,新增刷新应用层成功、拒绝和批量发现/详情测试;`go test ./...`、订单/Server race、`architecturecheck`、Go 中文注释门禁和 `git diff --check` 通过。刷新应用层当前定向语句覆盖约 60%–82%,订单应用包整体约 77.1%,仍需继续补齐凭证变化、平台错误、事务失败和多页边界测试;刷新取消/进度事件、三库任务回归、其他领域迁移和阶段 4/5/8/9 仍未完成,不能据此宣称目标架构完成 | -| 2026-08-15 | P1 订单刷新任务取消与状态 fencing 切片 | 已完成本切片 | 新增按用户归属的 `Cancel` 持久化命令,仅允许 `queued/running` 任务转为 `cancelled` 并清理旧 worker 租约;Server 在 worker 启动前登记可取消 Context,取消端点同时收束内存 worker,旧 worker 的 `Complete` 无法覆盖取消终态;新增 legacy/versioned DELETE 路由、前端 `cancelOrderRefreshJob`,`syncOrders` 在轮询取消时通知后端;覆盖 SQLite 任务生命周期、跨用户隔离、旧 worker fencing、HTTP 和前端 API 回归;`make check`、Go/React 注释门禁、Go 全量测试、前端 318 测试、类型检查和生产构建通过。刷新进度事件、三库任务迁移实测、后台运维查询、批量 UPSERT 和其他领域迁移仍未完成,阶段 4/5/8/9 保持“进行中” | -| 2026-08-15 | P2 订单详情分片单条多值 UPSERT 切片 | 已完成本切片 | 新增应用层 `RefreshOrderWrite` 与 `BatchUpsertOrders` Port;详情分片先收集成功结果,再由 Server 适配器在单事务内调用数据库 `UpsertManyTx`,数据库以一条多值 UPSERT 写入整片订单,保留状态防倒退、空字段不覆盖、软删除恢复和跨账号归属检查;新增批量订单 SQLite 回归(状态、版本、金额、跨账号、重复订单)及应用层“单次批量调用”断言;定向 Go 测试、`make check`、架构门禁、中文注释门禁和 `git diff --check` 通过。当前环境未提供 `TEST_MYSQL_URL`/`TEST_POSTGRES_URL`,因此未宣称外部数据库实测完成;订单发现仍为逐账号游标、商品批量同步和其他批量写入仍未完成,阶段 4/5/8/9 保持“进行中” | -| 2026-08-15 | P2 订单发现批量读写切片 | 已完成本切片 | 订单发现不再对远端订单逐条 `FindOrder` + `UpsertOrder`;新增 `FindOrdersByIDs`(按 500 个标识分片,兼容 SQLite 参数上限),远端列表先去重/归一化,再一次批量读取和一次多值 UPSERT,补齐 `is_bargain` 写入且保留已有砍价标记;未知状态不会覆盖已有进阶状态,批量失败不返回虚假发现统计;新增去重、批量调用次数、未知状态防倒退、批量读写失败和 SQLite 回归;`make check`、订单/Server 聚焦 race、架构门禁、中文注释门禁、`git diff --check` 通过。当前未配置 MySQL/Postgres 外部实例,三库 SQL 仅完成代码路径兼容设计,后续仍需外部查询计划/大数据量实测;跨账号账号级平台请求、商品/其他领域批量同步和阶段 4/5/8/9 仍未完成 | -| 2026-08-15 | P1 订单应用服务集合装配下沉切片 | 已完成本切片 | 新增 `internal/application/orders.ServiceSet` 与 `NewServiceSet`,统一构造订单列表、详情、删除、更新、导入、手动发货、刷新和刷新任务服务;`internal/server` 的订单对象重命名为 `orderHTTPAdapter`,只负责兼容 HTTP DTO/错误映射与归属适配,Server 不再分别创建订单业务服务;刷新任务 handler 改为通过应用层 ServiceSet 的任务 Port;新增应用集合构造测试与 Server 装配断言,订单/Server 定向测试和中文注释门禁通过。商品发布、登录、聊天等其他 Server 应用服务仍未迁移,低层 handler 依赖、生命周期统一清单、旧 API 兼容退场和整体阶段 4/5/8/9 仍保持“进行中” | -| 2026-08-15 | P0 敏感设置访问审计切片 | 已完成本切片 | 新增 SQLite/MySQL/Postgres `security_audit_logs` 迁移、`SecurityAuditLogs` repository 和 Store 装配;系统设置读取、敏感设置写入及 AI 模型密钥使用均记录用户、动作、资源和键名,审计记录不保存秘密值;审计存储不可用时管理端敏感操作 fail closed;新增数据库防泄露、HTTP 访问审计、审计存储缺失和迁移字段回归,定向测试、`make check`、架构/中文注释门禁通过。该历史子切片当时仅有 SQLite 实测,外部三库证据、运维输出脱敏和其他秘密调用方治理在后续 P0 子切片补齐 | -| 2026-08-15 | P2 React AccountList 子模块收口与页面组合边界 | 已完成本切片 | 新增 `AccountCard`、`AccountDeleteDialog`、`AccountQRCodeModal` 和 `AccountAISettingsModal`,将账号卡片与四类弹窗从 851 行根组件拆出;根组件保留请求取消、二维码轮询、账号列表刷新和编辑子模块协调,不改变现有业务行为;新增账号卡片操作转发、AI 草稿补丁、删除错误、二维码风控无外链测试;前端 322 个测试、类型检查、注释门禁和生产构建通过。React 路由懒加载、Provider/页面组合边界、完整页面行为覆盖和首屏包体预算仍未完成,阶段 7 保持“进行中” | -| 2026-08-15 | P2 React 路由懒加载与首屏入口包体边界 | 已完成本切片 | 认证根组件保留会话与导航状态,9 个业务页面在 `app/shell/AuthenticatedShell.tsx` 中改为 `React.lazy`,统一由 `Suspense` 提供加载占位;新增 `bundleBoundary.test.ts`,对入口脚本设置 100KB 原始字节预算、禁止图表 vendor 首屏预加载并要求 9 个页面 chunk 均存在;生产构建实测入口约 41.5KB、页面 chunk 独立生成,前端 325 个测试、类型检查、注释门禁、构建和仓库 `make check` 通过。Provider/路由壳细粒度状态边界、动态 chunk 独立预算、完整页面行为覆盖和大型页面进一步拆分仍未完成,阶段 7 保持“进行中” | -| 2026-08-15 | P2 React 认证后路由壳与页面组合边界 | 已完成本切片 | 新增 `frontend/app/shell/AuthenticatedShell.tsx`,由 `AuthenticatedShell` 统一组合 Sidebar、主内容布局和 `AppContent` 页面选择;`App.tsx` 只保留认证、导航状态及跨页面联动协调,权限回退和商品→规则页参数语义不变;更新 `routing.test.ts`、`rulesFeature.test.ts` 以验证新的壳边界,前端 326 个测试、类型检查、注释门禁、生产构建和 `make check` 通过。Provider 状态边界、动态 chunk 独立预算、完整页面行为覆盖和大型页面进一步拆分仍未完成,阶段 7 保持“进行中” | -| 2026-08-15 | P2 React 认证会话 Provider 状态边界 | 已完成本切片 | 新增 `frontend/app/providers/SessionProvider.tsx`,集中会话校验、AbortController 取消、首次管理员初始化、登录、注销和 `auth:logout` 监听;`App.tsx` 通过 `useSession` 使用认证状态与动作,认证 API 不再直接耦合到页面根组件;新增 `SessionProvider.test.tsx` 覆盖已认证、未初始化、登录/初始化成功、全局注销和注销失败清理,前端 330 个测试、类型检查、注释门禁、生产构建和 `make check` 通过。更细粒度页面 Provider、完整页面行为覆盖、动态 chunk 独立预算和大型页面进一步拆分仍未完成,阶段 7 保持“进行中” | -| 2026-08-15 | P2 React 路由组合行为与动态 chunk 独立预算 | 已完成本切片 | `bundleBoundary.test.ts` 为 Dashboard、AccountList、OrderList、CardList、ItemList、Settings、Rules、Notifications、Chat 分别设置原始字节预算并验证各自只有一个动态 chunk;新增 `AuthenticatedShell.test.tsx` 通过懒加载替身覆盖非管理员设置回退、管理员设置加载、商品→规则目标传递和规则目标消费回调;路由行为、生产构建、前端全量测试、类型检查和注释门禁通过。完整页面行为覆盖、更多大型页面边界和全局 Provider 组合仍未完成,阶段 7 保持“进行中” | -| 2026-08-15 | P2 React AccountList 完整页面行为边界 | 已完成本切片 | 新增 `frontend/components/AccountList.test.tsx`,真实挂载页面并隔离 API、账号数据 Hook、二维码轮询器和弹窗子组件;覆盖搜索过滤/计数、删除确认与状态 Setter 过滤、账号启停、资料刷新、二维码生成→轮询→保存成功、关闭二维码停止轮询并取消请求;前端定向测试、注释门禁和类型检查通过。AccountList QR 协调器进一步 feature 化、其他大型页面完整行为覆盖和全局 Provider 组合仍未完成,阶段 7 保持“进行中” | -| 2026-08-15 | P2 React AccountList 二维码登录协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/accounts/qrLogin.ts` 和 `qrPolling.ts`,将二维码生成、轮询、风控验证、结果持久化、延迟关闭与取消清理从 `AccountList` 根组件迁入账号 feature;旧 `frontend/components/qrPolling.ts` 保留兼容导出,避免测试和外部组件路径突变;新增 Hook 测试覆盖成功、风控验证、生成错误、持久化错误和关闭取消,AccountList 组合测试验证 feature 轮询替身仍正确接线;前端全量测试、类型检查、注释门禁、生产构建和仓库 `make check` 通过后提交。其他大型页面完整行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | -| 2026-08-15 | P2 React OrderList 完整页面行为边界 | 已完成本切片 | 新增 `frontend/components/OrderList.test.tsx`,真实挂载订单页面并隔离查询/导入 Hook、订单 API 和筛选/导入子组件;覆盖筛选转发、同步提示、导入入口、详情打开关闭、编辑字段转换、状态发货结果、单笔同步、删除时分页回退和分页函数式更新;分页按钮增加“上一页/下一页”无障碍名称。OrderList 动作协调器、Rules/ItemList/CardList 等其他大型页面、页面级 Provider 组合和阶段 7 总体验收仍未完成 | -| 2026-08-15 | P2 React OrderList 动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/orders/orderActions.ts` 与 `orderActions.test.tsx`,将同步、发货、详情、编辑、单笔同步、删除分页回退和弹窗关闭状态从 `OrderList` 根组件迁入订单 feature;编辑表单通过 `updateEditingOrder` 函数式补丁更新,保留原有 API、提示和结果语义;Hook 测试覆盖同步/发货/编辑/删除异常、确认取消和弹窗清理,页面组合测试继续覆盖成功流程。Rules/ItemList/CardList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | -| 2026-08-15 | P2 React CardList 动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/cards/cardActions.ts` 和 `cardActions.test.tsx`,将卡密新增、编辑、删除、启停、筛选、复制和模板下载状态/动作从 `CardList` 根组件迁入 cards feature;新增 `CardList.test.tsx` 真实挂载页面,覆盖筛选计数、批量导入入口、新增/编辑字段映射、启停、复制和删除;补充行级按钮无障碍名称。Rules/ItemList 等其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | -| 2026-08-15 | P2 React Rules 动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/rules/ruleActions.ts` 和 `ruleActions.test.tsx`,将自动化规则、关键词回复、默认回复的草稿与动作状态从 `Rules` 根组件迁入 rules feature;保留商品页联动加载、触发/规格编辑、归一化保存、异常恢复与确认语义,更新路由静态契约测试以跟随实现边界;前端全量 366 个测试、类型检查、中文注释门禁和生产构建通过。ItemList 其他大型页面行为覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | -| 2026-08-15 | P2 React ItemList 普通商品动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/items/itemActions.ts` 和 `itemActions.test.tsx`,将商品同步、编辑、删除、手动添加、普通发布、图片预览、模板下载和发货地定位从 `ItemList` 根组件迁入 items feature;批量发布 Hook 保持独立,更新图片预览静态契约;前端全量 62 个测试文件/369 个用例、类型检查、中文注释门禁、生产构建和仓库 `make check` 通过。ItemList 真实页面组合覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 | -| 2026-08-15 | P0 敏感配置调用方与运维输出脱敏代码切片 | 已完成本子切片 | 新增 `Store.ReadSensitiveSetting`/`ReadSensitiveSettingForAccount`,AI API Key、远程验证码密钥、系统 SMTP 密码和 AI 模型查询均在解密前写入不含秘密值的访问审计;新增 `logsafe.Error/Text`,dbverify/dbseed/init-admin/server/spike 及关键 URL/错误日志不再直接输出凭证、查询参数或解密消息正文;三库矩阵新增严格 `REQUIRE_MULTIDB=1` 门禁和 `make test-multidb`,无外部 URL 时明确跳过/失败而不伪造证据。定向 Go 测试、`make check`、前端 369 测试/类型检查/构建和注释门禁通过;受影响包全量 race 曾命中既有订单并发测试一次,聚焦重复验证通过,外部三库证据在后续验收子切片补齐 | -| 2026-08-15 | P0 父切片三库实测与集中式日志/凭证边界验收 | 已完成 | `.github/workflows/ci.yml` 新增 MySQL 8.4/PostgreSQL 17 service job,`docs/architecture/multidb-test-runbook.md` 提供本地复现方式;本机 Docker 实际执行 `make test-multidb`,SQLite/MySQL/PostgreSQL 全部多库测试通过并在结束后清理容器与数据卷;移除无人调用的批量解密 API,集中式 `slog` handler 递归清理敏感属性,Server/spike 的 logger fallback 也统一接入,审计边界与剩余 P1 风险已更新 | -| 2026-08-15 | P1 单商品发布应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `internal/application/items` 的发布输入、结果、平台 Port 和商品仓储 Port;`publishItem` 仅在 Server 边界完成 HTTP/MTOP/DB 模型转换,单商品平台发布与本地商品落库编排已移出 Server;新增应用服务构造、平台失败和成功落库测试,架构门禁、中文注释门禁、Server 回归及聚焦 race 通过。批量发布、商品同步及其他 Server 应用服务仍待迁移;现有商品发布凭证锁覆盖远端 I/O 的风险保留给后续凭证协调切片 | -| 2026-08-15 | P1 续期调度器 Context-aware Stop 切片 | 已完成本切片 | `internal/renewal.Scheduler` 新增私有运行 Context、`StopContext` 和兼容 `Stop`,主动停止会取消登录续期/API 续期 worker 并在调用方 Context 内等待 watcher 收束;重复停止保持幂等;新增主动取消与超时回归,续期测试、全量门禁和聚焦 race 通过。浏览器、Engine 内部任务、账号删除任务登记和统一生命周期清单仍未完成 | -| 2026-08-15 | P1 发货本地事实补偿闭环切片 | 已完成本切片 | 自动化发货远端成功但本地订单状态或事件时间写入失败时创建 `manual_status_ship` pending 补偿记录;补偿记录创建失败会并入 uncertain 错误,不再吞错;扩展远端成功/本地失败回归并实际运行 reconciliation worker 恢复订单状态、清理 pending。其他不可逆自动化动作、退避策略和统一运维查询仍待治理 | -| 2026-08-15 | P1 账号资料刷新应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `internal/application/account` 的非敏感账号摘要、资料刷新 Port 和结果模型;资料刷新 handler 通过用户+账号联合查询完成归属校验,Server 只在既有账号适配边界转换 `db.CookieDetail` 与平台调用;删除旧的 Server 资料刷新双实现,新增应用服务构造、归属失败和平台失败测试,架构门禁、中文注释门禁和 Server 回归通过。账号登录凭证写入、扫码和其他账号操作仍待迁移 | -| 2026-08-15 | P1 浏览器实例生命周期 CloseContext 切片 | 已完成本切片 | Browser Manager 增加活动调用登记、关闭 fencing、幂等 `CloseContext(ctx)` 和 `ErrManagerClosed`;`newPage`、初始化、二维码刷新及持久化续期上下文均在创建/释放时登记,关闭超时返回明确错误且可用更长 Context 重试,不创建游离关闭 goroutine;新增等待、超时重试和空管理器测试,浏览器全量及聚焦 race 通过。Playwright 底层同步 Close 无法被 Context 中断,Engine/账号其他任务仍待统一清单治理 | -| 2026-08-15 | P1 自动化外部成功结果 quarantine 切片 | 已完成本切片 | 统一 automation run 在外部消息已发送但 `FinishRun` 落库失败时立即写入 `needs_review` quarantine 结果并返回 `errAutomationNeedsReview`,避免租约自然重放造成重复外部动作;quarantine 写入失败与 FinishRun 失败使用 `errors.Join` 返回,通知只发送一次;新增双重失败回归,automation 全量和 race 通过。账号任务等旁路仍有忽略 FinishRun/Mark* 错误,后续需继续盘点 | -| 2026-08-15 | P1 商品批量发布应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `items.BatchRunner`、批次/明细模型、租约/取消/中断/收口 Port 和测试;批量 worker 的逐行 claim、失败分类、租约续期和上传清理从 Server 迁入应用层,Server 仅保留既有批量平台单行适配与数据库转换,未扩大新的临时低层白名单;批量 HTTP/应用回归、架构门禁和中文注释门禁通过。单行平台适配、商品同步及其他领域 Port 仍待治理 | -| 2026-08-15 | P1 Engine 内部任务生命周期切片 | 已完成本切片 | Engine 迟到 API 续期 watcher 纳入账号生命周期 `beginTask/finishTask`,继承账号运行 Context,StopContext 会等待其退出;WS recorder 关闭等待改为 Context-aware,未启动 recorder 不误报超时,停止超时后可重试;新增任务超时/重试和迟到 watcher 回归,Engine 全量测试、聚焦 race 和中文注释门禁通过。其他 Engine 网络/浏览器任务仍需统一清单审计 | -| 2026-08-15 | P1 账号自动化动作错误收口切片 | 已完成本切片 | 自动评价/擦亮任务不再吞 Cookie、FinishRun、MarkRateScan/MarkPolished 错误;外部动作成功但本地状态失败会写 `needs_review` 并返回 `errAutomationNeedsReview`,隔离写入失败使用 `errors.Join` 保留双重原因;新增单失败、双失败和日期写入失败回归,automation 全量测试通过。账号任务其他动作和通知旁路仍待盘点 | -| 2026-08-15 | P1 手动登录凭证应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `account.LoginService`,输入 DTO 不含 Cookie/密码;明文 Cookie 只由 Server request-scoped `CookieWriter` 在凭证锁内完成归属校验、写入和旧 Token 清理,登录后审计/资料刷新/运行时重启通过生命周期 Port;新增成功、归属失败、写入失败和缺失依赖测试,Server/应用回归及中文注释门禁通过。密码登录、扫码登录和更新凭证流程仍待统一协调 | -| 2026-08-15 | P1 账号管理器全局 Stop fencing 切片 | 已完成本切片 | `Manager.StopAllContext` 在收集账号前建立全局 stopping fence,停止期间拒绝新的 Start;单账号 Stop 超时保留 stopping 标记,防止存活实例被重启替换;全量停止完成后解除 fence,补充并发启动/停止和已取消 Context 兼容回归,account/Server 测试及 race 通过。删除任务状态查询和统一生命周期清单仍待完善 | -| 2026-08-15 | P1 通知 outbox 不确定状态隔离切片 | 已完成本切片 | 新增 SQLite/MySQL/Postgres `notification_outbox.uncertain_at` 迁移及 `MarkOutboxUncertain`;通知已发送但 `CompleteOutbox` 失败时原子转 `uncertain`、清除租约并禁止自动重发,隔离失败用 `errors.Join` 记录;无效渠道清理不再吞错;新增 SQLite、通知 worker 和三库矩阵回归,notify/db race、全量门禁通过。人工核对查询与运维展示仍待补充 | -| 2026-08-16 | P1 自动化调度器结果收口切片 | 已完成本切片 | 恢复扫描、延迟任务和异常规则处理不再吞 `Claim/Finish/Postpone/Quarantine` 落库错误;外部动作或状态收口失败统一保留原始错误、`needs_review` 和隔离错误,新增隔离成功/失败与非法延迟状态回归。Automation 全量、架构和中文注释门禁通过;账号任务及其他旁路仍待继续盘点 | -| 2026-08-16 | P1 通知 uncertain 查询应用 Port 切片 | 已完成本切片 | 新增纯应用层通知 uncertain DTO、归属隔离 Repository/Service;用户与管理员查询 handler 仅做 DB→应用→HTTP 适配,不再直接编排数据库查询;保留正文、错误原文、渠道配置和凭证不出边界,应用/Server 回归、架构和中文注释门禁通过 | -| 2026-08-16 | P1 Server 后台任务生命周期登记切片 | 已完成本切片 | 新增进程内有限历史任务注册表、任务 ID、running/succeeded/failed/canceled/timed_out 状态和管理员 `/api/v1/admin/tasks` 查询;订单/商品/补偿恢复扫描器使用显式 Context 登记,关闭等待仍受 backgroundWG/Context 约束;不新增 DB 迁移,历史随进程重启清空,补充状态/超时/HTTP/WaitForBackground 回归 | -| 2026-08-16 | P1 应用 Port 与凭证协调增量切片:聊天写入、通知渠道/绑定、普通 Cookie 更新 | 已完成本切片 | 新增聊天文字/图片发送、幂等状态收口和在线账号发送 Port;新增通知渠道 CRUD、测试发送、账号绑定及 uncertain 查询的应用服务与具名 DTO;新增普通 Cookie 更新 `LoginService.UpdateCookie`,由 request-scoped 凭证适配器在短锁内复核归属、执行兼容 `last_refresh_at` 冲突检查、写入 Cookie 和清理旧 Token,解锁后才执行审计/资料刷新/运行时同步;应用、Server 回归,`go test ./...`,Server race,架构/Go/前端注释门禁,前端 369 个测试、类型检查和生产构建均通过;随后使用 Docker Compose 启动 MySQL 8.4 与 PostgreSQL 17,严格执行 `make test-multidb`,SQLite/MySQL/PostgreSQL 全部 `TestMultiDB_*` 通过(约 90 秒),并清理容器、网络和数据卷。该记录只关闭三个子切片,P1 应用 Port、凭证协调、阶段 4/5/8/9 仍保持“进行中”;完整凭证协调及其他 Server 低层依赖待后续收口 | -| 2026-08-16 | P1 应用 Port、生命周期与外部动作补偿增量切片:通知摘要、密码登录策略、账号删除和自动化结果收口 | 已完成本切片 | 通知渠道列表新增不解密 Config 的数据库摘要查询,并用损坏密文 SQLite 回归和三库 `TestMultiDB_Notifications` 覆盖;密码登录启动/查询/取消统一通过关闭策略应用 Port,保留旧/版本化 501 契约且不解析或传播密码;账号删除迁移到 `account.DeleteService`,统一归属校验、账号级 fencing、最多五秒 Context 停止等待、锁内二次复核和可观测错误映射;自动化完整发货 FinishRun 失败转 `needs_review`,准备阶段订单事实 Upsert 失败阻止外部动作,双重失败使用 `errors.Join`;Go 全量测试、完整受影响包 race、Server smoke race、架构/Go/前端注释门禁、前端 369 测试、类型检查和生产构建通过;Docker Compose 实测 MySQL 8.4/PostgreSQL 17,严格 `make test-multidb` 的 SQLite/MySQL/PostgreSQL 全部 `TestMultiDB_*` 通过(约 95 秒),并清理容器、网络和数据卷。该记录只关闭四个子切片,P1 应用 Port、凭证协调、生命周期、外部动作补偿及阶段 4/5/8/9 仍保持“进行中”;浏览器密码登录仍按产品策略禁用,其他自动化旁路和 Server 临时白名单待继续收口 | -| 2026-08-15 | P1 扫码登录应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层扫码登录 DTO、凭证 Repository 和生命周期 Port;Server 仅负责平台结果转换、会话幂等和基础设施适配,扫码新建/更新、归属校验、Cookie 快照合并及旧 Token 清理由应用服务编排;新增成功、跨用户、目标不一致、写入失败、清理失败和敏感结果不泄露测试,账号/Server 回归、架构门禁和中文注释门禁通过。更新凭证及其他账号操作仍待迁移 | -| 2026-08-15 | P1 聊天历史应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层聊天消息/会话分页 DTO、最小 Repository 和 Service;聊天历史 handler 完成实际接入,旧 communication service/repository 不再持有历史查询职责;新增用户归属、参数校验、未装配依赖、底层失败和会话摘要失败测试,Server、架构和中文注释门禁通过。聊天写入与实时会话编排仍待迁移 | -| 2026-08-15 | P1 通知不确定态运维可见性切片 | 已完成本切片 | 新增按用户/管理员隔离的 uncertain outbox 元数据查询、计数和版本化 HTTP 接口;响应不返回通知正文、渠道配置、错误原文或凭证;补充 SQLite 隔离、管理员汇总、非管理员 403、脱敏和 limit 回归,DB/Server、架构和中文注释门禁通过。更多统一运维任务清单和旧入口退场仍待完成 | - -### 11.2 执行纠偏审计(2026-08-15) - -本次审计确认此前的提交节奏和计划顺序均出现偏差,后续以本节为执行闸门: - -- 当日 00:00 至审计时产生 159 个提交,15:00 后产生 39 个提交;其中多个提交只完成一个页面动作或一个 Hook 分支,不能等同于计划中的完整 PR 切片。 -- 阶段状态并非“全部打开”:阶段 0、1、2、3、6 已有完整完成证据;阶段 4、5、7、8、9、10 仍为“进行中”。阶段 2 的关闭不代表审计重开后的目标架构已经完成。 -- 11.1 中标记为“已完成”的记录均按“子切片”解释,不能自动关闭父 PR;P0 曾因外部数据库实测、运维输出脱敏、凭证访问审计和秘密调用方盘点未齐而保持“进行中”,现已由后续验收子切片补齐证据并关闭。其余父 PR 仍按下表状态执行。 -- P0 父切片已经关闭;在 P1 父切片关闭前继续暂停新的 React 页面细粒度提交;已完成的 React 子切片保留,不回滚,但不再继续扩展阶段 7。 - -| 父 PR 切片 | 当前真实状态 | 关闭前必须补齐 | +接口由消费者定义并保持最小。禁止全局 service locator、万能 repository、通过 `any`/反射隐藏 +依赖、或仅为绕过架构检查增加中转层。详细依赖规则以 +`docs/architecture/dependency-rules.md` 为准。 + +## 3. 当前代码基线 + +本节只描述制定后续迭代所需的当前事实,不保存重构历史。 + +- 当前开发分支从本地 `main` 演进;本地 `main` 落后 `xianyu-go/main`,功能对照必须使用 + `xianyu-go/main`,不能只对照本地分支。 +- 当前工作树包含大量未提交和未跟踪文件。后续迭代必须原地保护这些修改,禁止 reset、覆盖或 + 以重建分支代替审计。 +- 远端 `main` 的空卡密修复与当前前端 API 文件存在文本合并冲突。当前代码必须持续保证服务端 + 空列表编码为 `[]`,前端同时接受数组、包裹对象和 `null`;对应回归测试是强制契约。 +- 远端 `main` 的文档链接变更不影响运行功能。生成前端资产的文本冲突必须通过当前源码重新构建 + 解决,禁止手工合并压缩产物。 +- Server 生产代码已大幅迁移到应用 Port,架构检查当前可通过;但仍存在 Server 暴露 + `*sql.Tx` 的遗留事务边界、Server 持有业务 worker/会话状态,以及集中式依赖工厂隐藏底层 + `Store` 的风险,因此阶段 4 和阶段 5 尚未验收。 +- 账号敏感摘要与秘密访问已经分离,并已有审计和多数据库覆盖;阶段 2 可视为完成,但后续迭代 + 不得重新扩大读取、解密、序列化或日志范围。 +- HTTP 已有 `/api/v1` 路径和兼容契约测试,但 transport 仍使用动态 map、部分兼容响应别名和 + 未生成的集中类型,因此阶段 3 尚未验收。 +- Engine `Account`、Automation `Center`、集中前端 API/类型文件和若干大型 Hook 仍承担过多职责; + 目录已经拆分不等于对应阶段完成。 +- 生命周期清单仍列有 Engine 子任务、实时连接、恢复任务和运维观测缺口;阶段 5 尚未验收。 +- 三方言迁移编号当前对齐,订单已有游标和批量写入能力;跨 repository 事务、查询计划、补偿和 + 大数据量行为仍需阶段 8 统一验收。 +- 注释历史基线文件当前为空,但源码仍存在“保存 X 供当前流程使用”等模板化注释。机械基线清零 + 不等于注释质量达标,阶段 10 尚未验收。 +- 与远端 `main` 相比,受冻结规范保护的 CAPTCHA 文件存在差异。其当前行为必须以仓库内冻结规范 + 和全部冻结测试为准;没有用户明确授权不得修改、回退或借重构重新合并这些文件。 + +## 4. 迭代状态与唯一顺序 + +阶段状态只允许使用 `前置完成`、`已完成`、`当前迭代`、`待执行`、`阻塞`。只有一个阶段可以是 +`当前迭代`;后续阶段已有的提前实现代码只作为该阶段未来验收的输入,不代表阶段已启动或完成。 + +| 阶段 | 状态 | 迭代目标 | | --- | --- | --- | -| P0 敏感系统设置与运维输出脱敏 | 已完成 | 运维日志/诊断输出集中脱敏;管理/一次性敏感读取审计且 fail closed;已知秘密调用方清单收口;SQLite/MySQL 8.4/PostgreSQL 17 实测迁移与 CRUD 证据;Go/React 回归 | -| P1 应用 Port 与架构允许边 | 进行中 | 不只订单,其他应用服务和 Server 允许边全部收口;禁止 `sql.Tx`、`db.*`、HTTP/Server 类型泄露;移除临时白名单 | -| P1 凭证快照与账号操作协调器 | 进行中 | 剩余 Server、Renewal、Engine、Automation 调用方统一协调;版本冲突/锁等待可观测;慢 I/O、重试和合并语义有完整回归 | -| P1 生命周期与删除 fencing | 进行中 | 调度器、浏览器、Engine 内部任务纳入统一清单;所有 Stop 等待受 Context 限制;删除任务状态可追踪且无游离 goroutine | -| P1 外部动作补偿与 reconciliation | 进行中 | 自动化准备阶段和其他不可逆外部动作纳入三态结果、补偿记录、重试和审计 | -| P2 商品/订单批量同步 | 进行中 | 商品与订单剩余 N+1、批量写入、缓存失效、MySQL/Postgres 查询计划和大数据量证据 | -| P2 HTTP 契约与兼容退场 | 进行中 | 旧入口遥测、Deprecation/Sunset 条件和删除版本;阶段 3 已关闭不等于阶段 9 已关闭 | -| P2 React 页面边界与初始包体 | 进行中(暂停新子切片) | 其他大型页面真实组合覆盖、页面级 Provider 组合和最终包体/路由验收 | -| P2 复杂度与注释真实性 | 进行中 | 模板短语黑名单、业务语义抽查、复杂度门禁和冻结文件精确例外 | +| 0. 治理与强约束 | 前置完成 | 建立计划、依赖、注释、冻结规范和自动检查 | +| 1. CI 与测试基础 | 已完成 | 建立独立 CI、分层 race 和三数据库门禁 | +| 2. 敏感数据访问边界 | 已完成 | 分离摘要、平台凭证、登录秘密和敏感设置 | +| 3. HTTP API 契约 | 当前迭代 | 完成版本化、具名 DTO、统一错误和前端契约 | +| 4. Server 应用服务 | 待执行 | 把完整业务用例和事务边界移出 transport | +| 5. 应用装配与生命周期 | 待执行 | 消除隐式装配、业务 worker 和游离后台任务 | +| 6. Engine 与 Automation | 待执行 | 将大 facade 拆为有明确状态所有权的组件 | +| 7. React Feature 化 | 待执行 | 完成 feature 边界、请求归属、状态和按路由加载 | +| 8. DB 与事务治理 | 待执行 | 完成窄 repository、Unit of Work 和三方言验收 | +| 9. 架构门禁与兼容退场 | 待执行 | 封死依赖旁路并按 Sunset 删除兼容层 | +| 10. 注释与复杂度收口 | 待执行 | 清除模板注释和复杂度债务,形成最终质量门禁 | -后续提交规则: +执行顺序固定为 `0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10`。除阻塞性 +安全修复、构建修复或用户明确改序外,不得跳过当前阶段推进后续阶段。例外只解决阻塞问题,不能 +借机开启另一个重构阶段。 -1. 只按上表父 PR 的完成条件组织工作;不再为单个函数、文件或一个测试分支单独提交。 -2. 同一父 PR 的实现、测试、计划证据和风险说明放在同一个中文提交中;未满足父 PR 完成条件时,状态只能写“进行中”。 -3. 不改写已有提交历史,避免新的破坏性操作;从本审计之后开始恢复“一个完整 PR 切片、一个提交、可回退”的节奏。 -4. 阶段关闭必须同时具备代码、测试、架构门禁、中文注释门禁和外部依赖实测证据;覆盖率或单次 `make check` 通过不能单独作为关闭理由。 +## 5. 阶段 0:治理与强约束 + +### 目标 + +建立所有后续迭代共同遵守的边界、冻结行为和检查入口。阶段 0 是前置治理,不占十个正式迭代。 + +### 范围 + +- 维护本计划、`dependency-rules.md`、`comment-standard.md` 和 `AGENTS.md`。 +- 冻结滑块 CAPTCHA 实现、调用链和测试。 +- 提供架构检查、Go/TypeScript 注释检查和统一 Make 入口。 + +### 完成条件 + +- 文档规则互不矛盾,执行单位明确为一个阶段对应一个 PR/迭代。 +- 自动检查可在本地和 CI 运行,新增债务不能借历史基线通过。 +- 本计划不包含任何历史日志或阶段内完成记录。 + +### 强制验证 + +```bash +go run ./tools/architecturecheck +go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json +npm --prefix frontend run comments:check +``` + +## 6. 阶段 1:CI 与测试基础 + +### 目标 + +让每个后续迭代都能在独立、稳定、耗时可控的门禁上验收。 + +### 范围 + +- PR CI:Go test/vet/lint、架构、注释、前端 test/typecheck/build。 +- 普通测试与生命周期/凭证并发 race 分层。 +- SQLite 快速回归和 Docker MySQL/PostgreSQL 严格回归。 +- 测试数据库模板、确定性 fixture 和覆盖率产物隔离。 + +### 完成条件 + +- CI 不依附发布 workflow,失败会阻止合并。 +- race 子集覆盖高风险并发路径,完整 race 可在需要时执行。 +- `make test-multidb` 缺少任一外部数据库 URL 时明确失败,而不是静默跳过。 + +### 强制验证 + +```bash +make check +make test-server-race +TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb +npm test --prefix frontend +npm run build --prefix frontend +``` + +## 7. 阶段 2:敏感数据访问边界 + +### 目标 + +让每个用例只读取完成任务所需的最小数据,阻止秘密进入摘要、所有权查询、HTTP DTO 和前端状态。 + +### 范围 + +- 分离 `AccountSummary`、`AccountCredential`、`AccountLoginSecret` 和运行配置。 +- 所有权查询只返回存在性、所有者 ID 或非敏感身份。 +- 敏感读取使用目的明确的方法,管理/一次性读取有审计且失败时 fail closed。 +- 日志、通知、错误和测试输出集中脱敏。 +- SQLite、MySQL、PostgreSQL 验证加密、损坏密文、跨用户和迁移行为。 + +### 完成条件 + +- 账号列表、详情、状态、商品、订单、聊天和规则校验不读取 Cookie、Token 或密码。 +- 敏感持久化模型不被 HTTP 序列化,前端类型不包含可回填的明文秘密。 +- 高频运行时不会为普通摘要读取反复解密或写审计。 +- 三数据库的敏感字段 CRUD、迁移和失败语义一致。 + +### 强制验证 + +```bash +go test ./internal/db ./internal/account ./internal/server -count=1 +go test -race ./internal/account ./internal/server -count=1 +TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb +make comments +``` + +## 8. 阶段 3:HTTP API 契约 + +### 目标 + +在不破坏当前客户端的前提下完成统一 `/api/v1` 契约、具名 DTO、统一错误和可验证的前端类型边界。 + +### 范围 + +- 为全部业务入口提供 `/api/v1` 路径;旧路径只作为调用同一 handler 的兼容适配器。 +- 请求、成功响应、分页结果、批量行结果和错误详情全部使用具名 DTO。 +- 清除 QR、订单导入/批量结果、聊天和设置 transport 中作为响应契约的动态 map。 +- 统一错误 envelope、错误码和 HTTP 状态;禁止新增 `HTTP 200 + success:false`。 +- 建立单一契约来源和只读生成类型;feature adapter 将 transport DTO 转换为 UI model。 +- 固定空集合为 `[]`,并兼容当前发布链路可能返回的 `null` 或历史包裹对象。 +- 契约测试同时覆盖版本化路径和仍被支持的旧路径。 + +### 完成条件 + +- 生产 handler 不直接返回数据库模型、领域模型、匿名 struct 或动态 map 契约。 +- 前端业务 API 不再依靠 `any` 猜测响应形状;兼容归一只发生在 feature/transport 边界。 +- 所有新增失败使用统一错误结构和正确状态码。 +- 当前前端只调用 `/api/v1`;旧路径保留范围和删除条件可由测试清点。 +- 空卡密、空订单、空商品等集合不会因 `null` 阻断页面其他并行请求。 + +### 强制验证 + +```bash +go test ./internal/server -count=1 +npm test --prefix frontend +npm run typecheck --prefix frontend +npm run build --prefix frontend +go run ./tools/architecturecheck +make comments +``` + +## 9. 阶段 4:Server 应用服务 + +### 目标 + +使 Server 成为纯 transport,把订单、商品、账号、登录、聊天、通知、自动化和管理员用例交给应用服务。 + +### 范围 + +- handler 只做鉴权上下文、参数解析、DTO 转换和应用错误到 HTTP 的映射。 +- 应用服务负责所有权、业务校验、跨步骤编排、事务选择和补偿决策。 +- Port 由应用消费者定义,不暴露 `db.*`、`*sql.Tx`、HTTP、Server、MTOP 或 browser 类型。 +- 删除 Server 中遗留的 `*sql.Tx` 执行器、无调用兼容服务和低层 helper。 +- 审查集中式 `adapter.Dependencies`;改为显式、类型化构造,不得成为隐藏 Store 的 service locator。 +- 把仍在 Server 内的账号登录持久化、平台会话和业务 worker 操作迁到应用边界。 + +### 完成条件 + +- Server 生产代码不导入 `database/sql`、`internal/db`、`internal/xianyu` 或 `internal/browser`。 +- Server 不持有 repository 聚合入口,不创建事务,不执行平台业务动作。 +- 应用包不依赖 HTTP、chi、DB、Server 或平台实现。 +- 每个完整用例的正常、越权、缺失、失败、取消和补偿分支有应用层测试。 +- 构造器缺失必需依赖时立即返回错误,不在请求期 panic 或延迟发现。 + +### 强制验证 + +```bash +go test ./internal/application/... ./internal/adapter ./internal/server -count=1 +go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1 +go vet ./... +go run ./tools/architecturecheck +make comments +``` + +## 10. 阶段 5:应用装配与生命周期 + +### 目标 + +明确所有组件、goroutine、连接、timer、channel 和 worker 的所有者、Context、停止与等待边界。 + +### 范围 + +- `cmd` 显式构造全部必需依赖并负责启动顺序和反向关闭顺序。 +- 消除必需依赖 setter、请求期懒装配和部分构造可见状态。 +- 把订单刷新、批量发布、恢复、reconciliation 和实时连接等业务 worker 移出 Server transport。 +- 每个后台任务提供 owner、Context 来源、Cancel、Wait/Join、超时和观测状态。 +- 账号删除先 fencing,受限等待运行时退出,再复核归属并删除。 +- Stop/Close 在契约允许时幂等;晚到写入由 generation、lease 或 token 拒绝。 +- 清空 `lifecycle-inventory.md` 中的剩余风险后,将其保留为静态组件清单而非进度日志。 + +### 完成条件 + +- Server 不保存业务 worker 的锁、cancel map、任务状态或平台会话状态。 +- 所有 goroutine 都能由拥有者取消并等待,不使用超时后遗留的等待 goroutine。 +- 重复 Start/Stop、先 Stop、启动失败回滚、超时和晚到写入有确定性测试。 +- 关闭顺序不持锁等待网络、浏览器或用户操作。 + +### 强制验证 + +```bash +go test ./internal/server ./internal/account ./internal/engine ./internal/automation ./internal/renewal -count=1 +go test -race ./internal/server ./internal/account ./internal/engine ./internal/automation ./internal/renewal -count=1 +go test ./... -count=1 +go run ./tools/architecturecheck +``` + +## 11. 阶段 6:Engine 与 Automation + +### 目标 + +将大型 facade 拆成状态所有权明确、可独立测试的组件,同时保持平台协议和冻结 CAPTCHA 行为不变。 + +### 范围 + +- Engine 分离连接会话、消息分发、去重、防抖、凭证协调、重试和运行状态。 +- Automation 分离规则解析、调度、运行协调、动作执行、库存分配、通知和补偿。 +- 建立统一账号凭证协调器:快照、版本校验、锁外外部 I/O、条件提交和冲突观测。 +- 外部动作使用幂等键和 `succeeded/failed/uncertain` 三态;不确定结果进入人工核对或补偿。 +- 明确凭证锁、自动化库存锁和 worker 锁的顺序。 +- `Account` 与 `Center` 只保留稳定 facade,不继续拥有全部内部可变状态。 + +### 完成条件 + +- facade 的体积和字段职责显著收敛,每个并发组件有独立生命周期和 race 测试。 +- 未在任何互斥锁或数据库事务内执行不可控平台、浏览器或用户等待 I/O。 +- 凭证冲突、取消、超时、旧响应、重复事件和重连均有确定性测试。 +- 发货、评价、求评价、卡密和通知的幂等及不确定态不发生自动重复动作。 +- 所有冻结 CAPTCHA 测试通过,受保护文件没有未经授权的行为变化。 + +### 强制验证 + +```bash +go test ./internal/engine ./internal/automation ./internal/browser -count=1 +go test -race ./internal/engine ./internal/automation -count=1 +RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1 +go run ./tools/architecturecheck +make comments +``` + +## 12. 阶段 7:React Feature 化 + +### 目标 + +完成 `app -> features -> shared` 的真实所有权拆分,而不是只移动页面文件或增加 barrel export。 + +### 范围 + +- `app` 只保留 Provider、认证壳、路由和错误边界。 +- 每个 feature 拥有 page、components、hooks/state、API adapter、UI model 和行为测试。 +- 拆除集中式 `frontend/services/api.ts` 和 `frontend/types.ts` 的业务职责。 +- shared HTTP client 只处理超时、取消、认证和统一错误,不包含领域归一。 +- 服务端数据、表单状态和短暂 UI 状态分离;派生值不重复存入 state。 +- 异步 effect 使用取消或 generation,独立请求并行启动,旧响应不得覆盖新状态。 +- 页面和重型可选依赖按路由/feature 懒加载,并设置初始包体预算。 + +### 完成条件 + +- feature 不导入其他 feature 内部文件,shared 不反向导入 feature。 +- React 组件不直接 `fetch`/`axios`,业务 DTO 转换只在本 feature API adapter。 +- 不再存在承担多个领域的集中 API/类型文件或超大 Hook。 +- 关键流程具有成功、失败、取消、切换、乱序响应和卸载测试。 +- 构建产物由当前源码生成并更新嵌入目录,初始包体满足预算。 + +### 强制验证 + +```bash +npm test --prefix frontend +npm run typecheck --prefix frontend +npm run comments:check --prefix frontend +npm run build --prefix frontend +make cover-frontend +git diff --check +``` + +## 13. 阶段 8:DB 与事务治理 + +### 目标 + +完成窄 repository、应用层 Unit of Work、批量查询写入、补偿持久化和三方言一致性。 + +### 范围 + +- SQL、方言、row model 和加密只留在 `internal/db` 与基础设施 adapter。 +- 跨 repository 原子操作通过消费者定义的 Unit of Work 执行。 +- 清除上层 `*sql.DB`、`*sql.Tx`、DB row 和完整 `Store` 暴露。 +- 商品/订单同步使用游标、批量读取、批量 UPSERT 和明确缓存失效,消除 N+1。 +- 不可逆外部动作的补偿记录、lease、幂等键和人工核对状态跨重启持久化。 +- 所有迁移在 SQLite、MySQL、PostgreSQL 使用相同编号和最终 schema。 +- 对高频查询提供三方言查询计划和大数据量回归。 + +### 完成条件 + +- handler、React 和领域组件不控制数据库事务。 +- 跨 repository 失败原子回滚;外部成功后的本地失败进入可恢复或不确定状态。 +- 三方言迁移、CRUD、事务、并发 claim、软删除、批量写入和补偿行为一致。 +- 大数据量测试证明没有逐账号、逐订单或逐商品的无界查询放大。 + +### 强制验证 + +```bash +go test ./internal/db ./internal/application/... ./internal/adapter -count=1 +go test -race ./internal/db ./internal/application/... ./internal/adapter -count=1 +TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb +go run ./cmd/dbverify "$TEST_MYSQL_URL" +go run ./cmd/dbverify "$TEST_POSTGRES_URL" +``` + +## 14. 阶段 9:架构门禁与兼容退场 + +### 目标 + +把目标依赖图和兼容删除条件变为 fail-closed 门禁,删除所有临时例外和已到期兼容路径。 + +### 范围 + +- 检查 Server 的 `database/sql`、低层 import、业务 worker、裸 Store 和事务暴露。 +- 检查应用 Port 是否泄露 DB/HTTP/Server/平台实现类型。 +- 检查 service locator、运行时必需 setter、反射/动态 import 隐藏依赖。 +- 检查前端 app/features/shared 依赖方向、组件直接请求和集中式 barrel。 +- 为旧路径和兼容字段建立调用遥测、Deprecation、Sunset 版本和删除测试。 +- 删除调用方已迁移的旧路由、别名、适配器、白名单和死代码。 + +### 完成条件 + +- 架构检查覆盖完整目标图且无临时白名单。 +- 所有保留兼容入口都有已知调用方、遥测和明确删除版本。 +- 到期旧路径删除后,前端、契约测试、Vite 代理和嵌入资产同步更新。 +- `go list`、AST、TypeScript/ESLint 规则无法通过简单中转层绕过。 + +### 强制验证 + +```bash +go run ./tools/architecturecheck +go test ./... -count=1 +go test -race ./internal/server ./internal/engine ./internal/automation -count=1 +npm test --prefix frontend +npm run typecheck --prefix frontend +npm run build --prefix frontend +``` + +## 15. 阶段 10:注释与复杂度收口 + +### 目标 + +让中文注释准确描述业务、敏感性和并发约束,并把过长函数和高复杂度热点降到可维护范围。 + +### 范围 + +- 删除“保存 X”“负责 X”“表示错误”等模板化或复述语法的注释。 +- 为函数、参数、返回值、变量、字段、闭包和 React 状态补充准确中文语义。 +- 并发代码说明 owner、锁保护字段、锁顺序、Context、Cancel 和 Wait。 +- 敏感值说明明文作用域、日志/序列化禁令和清理责任。 +- 增加模板短语、复杂度和超大文件门禁;冻结文件只使用精确例外。 +- 删除全部注释历史基线机制和已无必要的例外。 + +### 完成条件 + +- Go、TypeScript、TSX 无历史注释豁免,无模板化占位注释。 +- 自动检查和人工抽查同时通过,注释与当前行为一致。 +- 高复杂度函数被按业务责任拆分,未用注释掩盖结构问题。 +- 全量测试、race、覆盖率、架构、lint、前端构建和三数据库门禁全部通过。 + +### 强制验证 + +```bash +make comments +make check +make cover +make cover-browser +make cover-frontend +TEST_MYSQL_URL=... TEST_POSTGRES_URL=... make test-multidb +npm run build --prefix frontend +``` + +## 16. 迭代强制约束 + +### 16.1 执行单位与提交 + +1. 阶段 1 至阶段 10 各是一个完整迭代、一个 PR、最多一个最终提交。 +2. 不得把阶段内的函数、文件、测试或所谓纵向子切片计作独立轮次、PR 或提交。 +3. 当前阶段的实现、测试、文档和生成产物必须在同一迭代一次完成并统一验收。 +4. 阶段未满足全部完成条件时不得提交为“已完成”,也不得开始下一阶段。 +5. 每个编辑批次保持可编译;每个阶段合并点必须可运行、可回退并通过全部适用门禁。 +6. 不改写已有 Git 历史,不覆盖无关工作树修改,不以重建分支代替合并和冲突审计。 +7. 除用户明确要求外不创建提交;需要提交时只在阶段全部验收后创建一次。 + +### 16.2 行为与兼容 + +1. 重构默认不改变业务行为、HTTP 状态、JSON 字段、重试、超时、幂等或错误优先级。 +2. 与 `main` 比较必须使用最新远端目标;先分析文本冲突,再用契约测试判断功能冲突。 +3. 空集合统一输出 `[]`,前端兼容当前仍可能存在的 `null` 和历史包裹对象。 +4. 新 API 使用 `/api/v1` 和具名 DTO;禁止新增动态 map 响应或 `HTTP 200 + success:false`。 +5. 兼容适配器必须记录调用方、删除条件和 Sunset 版本;条件满足前不得删除。 +6. 前端源码变化后必须重新构建 `internal/webui/static`,禁止手改哈希资产。 + +### 16.3 敏感数据 + +1. 摘要和所有权检查不得读取或解密 Cookie、Token、密码或加密 metadata。 +2. 平台凭证和登录秘密使用不同模型及目的明确的 repository 方法。 +3. 敏感持久化模型不得进入 HTTP、前端状态、日志、通知、错误或测试失败输出。 +4. 管理/一次性敏感读取必须审计且 fail closed,高频运行时使用窄读取。 +5. 不得持凭证锁执行未受规范保护的慢速网络、浏览器或用户等待 I/O。 + +### 16.4 数据库与事务 + +1. 上层不得新增裸 `*sql.DB`、`*sql.Tx` 或完整 Store;跨 repository 原子操作使用应用 Unit of Work。 +2. SQL row、持久化模型、应用模型和 HTTP DTO 不得合并为同一便利类型。 +3. 数据库变化必须同时维护 SQLite、MySQL、PostgreSQL 编号和最终 schema。 +4. 迁移、方言 SQL、claim、锁、批量写入或补偿变化必须执行 Docker 三数据库回归。 +5. 禁止通过逐行查询、无界并发或扩大事务范围掩盖 repository 设计问题。 + +### 16.5 生命周期与并发 + +1. goroutine、timer、channel、WebSocket、browser 和 worker 必须有 owner、Context、Cancel、Wait/Join。 +2. 必需依赖由构造器输入并在 Start 前验证;禁止生产路径使用 setter 补齐必需依赖。 +3. Stop/Close 按契约幂等,超时不得制造新的游离等待 goroutine。 +4. channel 由约定发送方关闭;晚到响应由 generation、lease、版本或 token fencing 拒绝。 +5. 锁保护字段和锁顺序必须注释并测试;禁止持锁等待不可控外部 I/O。 +6. 外部动作必须有幂等键、成功/失败/不确定三态、补偿、重试和人工核对边界。 + +### 16.6 React + +1. 依赖方向固定为 `app -> features -> shared`;feature 不导入其他 feature 内部文件。 +2. 组件不直接请求网络,shared HTTP client 不包含领域归一逻辑。 +3. 服务端数据、表单状态和短暂 UI 状态分离;可派生值不重复存 state。 +4. 异步 effect/request 必须可取消或有 latest-generation 保护;独立请求并行启动。 +5. 不因习惯增加 memo;重型页面和可选依赖按路由/feature 懒加载。 +6. 新或重大流程必须覆盖成功、失败、取消、切换、乱序和卸载,不用源码字符串测试替代行为测试。 + +### 16.7 冻结 CAPTCHA + +1. 未经用户在当前任务明确授权,不得编辑、移动、格式化、回退或间接改变受保护文件和调用链。 +2. 不得改变选择器、258px 标准距离、轨迹、时序、fresh `x5sec`、重试、profile、Cookie 合并、 + Playwright/CDP 顺序、启动参数或结果标签。 +3. 发现与基线差异时只做只读审计;任何行为调整必须同时更新实现、全部测试和冻结规范。 +4. 涉及 browser、登录、凭证、engine、account 或 server 调用路径时必须运行冻结规范要求的验证。 + +### 16.8 注释、测试与覆盖率 + +1. 所有新增或修改的 Go/TypeScript/TSX 函数和变量必须有准确中文注释。 +2. 禁止“err 表示错误”“变量 X 保存 X”等模板化注释,自动检查通过不能替代语义审查。 +3. 每个确定性函数、分支和错误路径必须有聚焦测试;禁止删除、跳过或放宽测试来通过重构。 +4. 测试可跳过的范围仅限真实账号、私有平台状态或不可用外部服务;本地浏览器和数据库不得假跳过。 +5. 覆盖率声明必须写明命令、浏览器开关、Go/前端百分比和真实外部例外,但不得写入本计划。 + +## 17. 阶段统一验收矩阵 + +| 变化范围 | 最低验证 | +| --- | --- | +| 任意 Go | 聚焦测试、`go test ./... -count=1`、`go vet ./...`、架构、Go 注释、`git diff --check` | +| HTTP/应用服务 | Server 与应用契约测试、错误/越权/取消测试、Server race | +| Engine/Automation/生命周期 | 聚焦 race、Stop/Close/超时/晚到写入、全量 Go test | +| 数据库/事务/迁移 | SQLite 聚焦、Docker MySQL/PostgreSQL、`cmd/dbverify`、并发 claim/回滚 | +| React/前端 API | Vitest、typecheck、前端注释、V8 coverage、生产构建、嵌入资产校验 | +| Browser/登录/凭证 | 冻结测试、浏览器集成、凭证 race、日志脱敏检查 | +| 阶段完成 | 该阶段全部强制验证 + `make check` + 适用覆盖率,不允许只凭单项门禁关闭 | + +## 18. 计划维护规则 + +1. 本文只允许修改目标、阶段范围、状态、验收条件、固定顺序和强制约束。 +2. 禁止在本文新增任何历史流水、阶段内工作分类、时间线、提交清单或人员记录。 +3. 阶段内临时发现写入 PR 描述或 issue,不写入总计划;只有改变阶段范围或验收条件时才更新本文。 +4. 阶段完成时只把状态从 `当前迭代` 改为 `已完成`,并把下一个阶段改为 `当前迭代`。 +5. 若阶段被阻塞,只将状态改为 `阻塞`;阻塞原因和尝试过程留在任务报告,不写入本文。 diff --git a/frontend/services/api.test.ts b/frontend/services/api.test.ts index 825e5ed..8f1ecfd 100644 --- a/frontend/services/api.test.ts +++ b/frontend/services/api.test.ts @@ -761,6 +761,13 @@ test('getCards 解析 JSON 和损坏 JSON 的卡密接口配置', /* 当前回 expect(cards[1].api_config).toBeUndefined(); }); +test('getCards 将后端空响应归一化为空列表', /* 当前回调防止空卡密响应阻断自动化规则账号加载。 */ async () => { + // fetchMock 模拟兼容后端返回 JSON null 的卡密列表响应。 + const fetchMock = vi.fn().mockResolvedValue(jsonResponse(null)); + vi.stubGlobal('fetch', fetchMock); + await expect(getCards()).resolves.toEqual([]); +}); + test('默认回复 API 补齐空字段默认值', /* 当前回调验证默认回复字段归一化和保存载荷。 */ async () => { // fetchMock 是默认回复读取和保存接口的网络替身。 const fetchMock = vi.fn() diff --git a/frontend/services/api.ts b/frontend/services/api.ts index d633b7c..30ce323 100644 --- a/frontend/services/api.ts +++ b/frontend/services/api.ts @@ -592,7 +592,7 @@ export const getCards = async (options?: RequestControlOptions): Promise // res 接口响应结果,用于当前 API 处理流程。 const res = await get('/api/v1/cards', undefined, options); // cards 卡密列表,用于当前 API 处理流程。 - const cards = Array.isArray(res) ? res : (res.cards || []); + const cards = Array.isArray(res) ? res : (res?.cards || []); return cards.map(normalizeCard); }; diff --git a/internal/adapter/account_login_audit.go b/internal/adapter/account_login_audit.go new file mode 100644 index 0000000..3a232b5 --- /dev/null +++ b/internal/adapter/account_login_audit.go @@ -0,0 +1,84 @@ +package adapter + +import ( + "context" + "errors" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" +) + +// AccountLoginAuditRepository 将账号登录审计应用 Port 适配为数据库窄写入。 +type AccountLoginAuditRepository struct { + // store 保存数据库聚合入口,仅在基础设施适配器内部使用。 + store *db.Store +} + +// NewAccountLoginAuditRepository 创建账号登录审计数据库适配器。 +func NewAccountLoginAuditRepository(store *db.Store) *AccountLoginAuditRepository { + return &AccountLoginAuditRepository{store: store} +} + +// MarkLogin 保存账号最近一次成功登录方式和时间。 +func (r *AccountLoginAuditRepository) MarkLogin(ctx context.Context, accountID, method string, at int64) error { + // validateErr 表示适配器或 Cookie 仓储未初始化,阻止审计写入继续访问空依赖。 + if validateErr := r.validateCookies(); validateErr != nil { + return validateErr + } + return r.store.Cookies.MarkLogin(ctx, accountID, method, at) +} + +// SetStatusWithReason 在登录成功后启用账号并清空禁用原因。 +func (r *AccountLoginAuditRepository) SetStatusWithReason(ctx context.Context, accountID string, enabled bool, reason string) error { + // validateErr 表示适配器或 Cookie 仓储未初始化,阻止账号状态写入访问空依赖。 + if validateErr := r.validateCookies(); validateErr != nil { + return validateErr + } + return r.store.Cookies.SetStatusWithReason(ctx, accountID, enabled, reason) +} + +// AddLoginLog 将应用层审计模型转换为数据库模型并写入;审计仓储未装配时保持旧的兼容空操作。 +func (r *AccountLoginAuditRepository) AddLoginLog(ctx context.Context, log accountapp.LoginAuditLog) error { + // validateErr 表示数据库适配器未初始化,阻止审计日志转换访问空 Store。 + if validateErr := r.validateStore(); validateErr != nil { + return validateErr + } + if r.store.LoginLogs == nil { + return nil + } + return r.store.LoginLogs.Add(ctx, db.AccountLoginLog{ + CookieID: log.AccountID, + UserID: log.UserID, + OwnerID: log.UserID, + AccountIdentifier: log.AccountID, + Method: log.Method, + Status: log.Status, + Message: log.Message, + TriggerReason: log.TriggerReason, + FailureReason: log.FailureReason, + ErrorMessage: log.Message, + CreatedAt: log.OccurredAt, + }) +} + +// validateStore 检查审计适配器是否具备数据库聚合入口。 +func (r *AccountLoginAuditRepository) validateStore() error { + if r == nil || r.store == nil { + return errors.New("账号登录审计数据库适配器未初始化") + } + return nil +} + +// validateCookies 检查账号状态和登录方式写入所需的 Cookie 仓储。 +func (r *AccountLoginAuditRepository) validateCookies() error { + // validateErr 表示数据库聚合入口缺失,需在检查 Cookie 仓储前原样返回。 + if validateErr := r.validateStore(); validateErr != nil { + return validateErr + } + if r.store.Cookies == nil { + return errors.New("账号登录审计 Cookie 仓储未初始化") + } + return nil +} + +var _ accountapp.LoginAuditRepository = (*AccountLoginAuditRepository)(nil) diff --git a/internal/adapter/account_login_audit_test.go b/internal/adapter/account_login_audit_test.go new file mode 100644 index 0000000..0a63971 --- /dev/null +++ b/internal/adapter/account_login_audit_test.go @@ -0,0 +1,76 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + accountapp "xianyu-go/internal/application/account" +) + +// TestAccountLoginAuditRepositoryMapping 验证登录审计应用模型到 SQLite 数据模型的字段映射。 +func TestAccountLoginAuditRepositoryMapping(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试存储的登录审计适配器。 + repository := NewAccountLoginAuditRepository(store) + // ctx 是本测试数据库操作共用的非取消上下文。 + ctx := context.Background() + // markErr 保存登录方式写入结果。 + if markErr := repository.MarkLogin(ctx, "cid", accountapp.LoginMethodQRScan, 123); markErr != nil { + t.Fatalf("写入登录方式失败: %v", markErr) + } + // statusErr 保存账号启用状态写入结果。 + if statusErr := repository.SetStatusWithReason(ctx, "cid", true, ""); statusErr != nil { + t.Fatalf("写入账号状态失败: %v", statusErr) + } + // logErr 保存登录审计日志写入结果。 + if logErr := repository.AddLoginLog(ctx, accountapp.LoginAuditLog{ + AccountID: "cid", UserID: 1, Method: accountapp.LoginMethodQRScan, + Status: accountapp.LoginStatusSuccess, Message: "扫码登录成功", + TriggerReason: "扫码登录", OccurredAt: 123, + }); logErr != nil { + t.Fatalf("写入登录审计失败: %v", logErr) + } + // detail 保存数据库返回的非敏感登录方式字段。 + detail, detailErr := store.Cookies.GetSummaryOwned(ctx, 1, "cid") + if detailErr != nil || detail.LoginMethod != accountapp.LoginMethodQRScan || detail.LastLoginAt != 123 { + t.Fatalf("登录方式映射异常 detail=%+v err=%v", detail, detailErr) + } + // logs 保存数据库返回的登录审计记录。 + logs, logsErr := store.LoginLogs.ListByCookie(ctx, "cid", 1) + if logsErr != nil || len(logs) != 1 || logs[0].OwnerID != 1 || logs[0].AccountIdentifier != "cid" || logs[0].TriggerReason != "扫码登录" || logs[0].ErrorMessage != "扫码登录成功" { + t.Fatalf("登录审计映射异常 logs=%+v err=%v", logs, logsErr) + } +} + +// TestAccountLoginAuditRepositoryInfrastructureErrors 验证适配器缺少依赖或数据库关闭时不伪装成功。 +func TestAccountLoginAuditRepositoryInfrastructureErrors(t *testing.T) { + // missingErr 保存缺少 Store 时的装配错误。 + missingErr := NewAccountLoginAuditRepository(nil).MarkLogin(context.Background(), "cid", "manual", 1) + if missingErr == nil { + t.Fatal("缺少 Store 时应返回装配错误") + } + // store 是随后主动关闭数据库连接的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定已关闭数据库的登录审计适配器。 + repository := NewAccountLoginAuditRepository(store) + // closeErr 保存主动关闭测试数据库的资源释放结果。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // markErr 保存数据库关闭后登录方式写入结果。 + markErr := repository.MarkLogin(context.Background(), "cid", "manual", 1) + if markErr == nil { + t.Fatal("数据库关闭后应返回登录方式写入错误") + } + // logErr 保存数据库关闭后审计日志写入结果。 + logErr := repository.AddLoginLog(context.Background(), accountapp.LoginAuditLog{AccountID: "cid", Method: "manual"}) + if logErr == nil || errors.Is(logErr, accountapp.ErrLoginAuditUnavailable) { + t.Fatalf("数据库故障应透传而非伪装应用装配错误: %v", logErr) + } +} + +var _ accountapp.LoginAuditRepository = (*AccountLoginAuditRepository)(nil) diff --git a/internal/adapter/account_login_repository.go b/internal/adapter/account_login_repository.go new file mode 100644 index 0000000..d554309 --- /dev/null +++ b/internal/adapter/account_login_repository.go @@ -0,0 +1,316 @@ +package adapter + +import ( + "context" + "errors" + "time" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" +) + +// AccountLoginRepository 将账号登录、扫码凭证和非敏感账号摘要能力适配到应用端口。 +// 该类型是唯一接触 Store、加密 metadata 和浏览器 Cookie 快照的实现。 +type AccountLoginRepository struct { + // store 保存数据库聚合入口;明文凭证只在本适配器的短调用期间存在。 + store *db.Store +} + +// NewAccountLoginRepository 构造账号登录数据库适配器;缺少数据库依赖时返回仍可安全失败的实例。 +func NewAccountLoginRepository(store *db.Store) *AccountLoginRepository { + return &AccountLoginRepository{store: store} +} + +// LockCredentials 串行化同一账号的凭证变更;缺少 Store 时返回无副作用的解锁函数。 +func (r *AccountLoginRepository) LockCredentials(accountID string) func() { + if r == nil || r.store == nil { + return func() {} + } + return r.store.LockAccountCredentials(accountID) +} + +// CreateCookieOwned 原子校验账号归属并写入 Cookie,明文不会离开数据库适配器。 +func (r *AccountLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return validationErr + } + // createErr 保存账号 Cookie 创建结果;并发占用会转换为应用层稳定错误。 + createErr := r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID) + if errors.Is(createErr, db.ErrAlreadyExists) { + return accountapp.ErrAlreadyExists + } + if errors.Is(createErr, db.ErrForbidden) { + return accountapp.ErrForbidden + } + if errors.Is(createErr, db.ErrNotFound) { + return accountapp.ErrNotFound + } + return createErr +} + +// LoadPlatformDetail 读取平台调用所需的窄凭证视图,并补充非敏感刷新版本。 +func (r *AccountLoginRepository) LoadPlatformDetail(ctx context.Context, accountID string) (*accountapp.CredentialDetail, error) { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return nil, validationErr + } + // data 保存只包含 Cookie、metadata 和平台运行设置的窄查询结果;queryErr 保存查询错误。 + data, queryErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) + if queryErr != nil { + if errors.Is(queryErr, db.ErrNotFound) { + // 返回应用层哨兵并保留数据库错误链,兼容仍在迁移中的基础设施调用方。 + return nil, errors.Join(accountapp.ErrCredentialNotFound, queryErr) + } + return nil, queryErr + } + // summary 保存不含凭证的账号摘要,用于乐观冲突检查。 + summary, summaryErr := r.store.Cookies.GetSummaryOwned(ctx, data.UserID, accountID) + if summaryErr != nil { + return nil, summaryErr + } + return &accountapp.CredentialDetail{ + ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, + ShowBrowser: data.ShowBrowser, LastRefreshAt: summary.LastRefreshAt, + }, nil +} + +// UpdateFlatCookieOwned 更新扁平 Cookie 并移除旧的完整浏览器快照。 +func (r *AccountLoginRepository) UpdateFlatCookieOwned(ctx context.Context, detail *accountapp.CredentialDetail, cookies string) error { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return validationErr + } + if detail == nil { + return db.ErrNotFound + } + // metadata 保存剔除完整快照后的加密元数据,避免旧快照与新扁平 Cookie 不一致。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + return r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()) +} + +// UpdateRenewalCookie 保存平台返回的 Cookie 和 metadata。 +func (r *AccountLoginRepository) UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return validationErr + } + return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, at) +} + +// ClearTokens 清理凭证变化后失效的旧 Token;未装配 Token 仓储时保持兼容空操作。 +func (r *AccountLoginRepository) ClearTokens(ctx context.Context, accountID string) error { + // validationErr 表示数据库适配器未完成装配。 + validationErr := r.validateStore() + if validationErr != nil { + return validationErr + } + if r.store.Tokens == nil { + return nil + } + return r.store.Tokens.Clear(ctx, accountID) +} + +// GetStatus 查询账号是否启用;缺少存储或数据库故障时安全地返回停用。 +func (r *AccountLoginRepository) GetStatus(ctx context.Context, accountID string) bool { + if r == nil || r.store == nil || r.store.Cookies == nil { + return false + } + return r.store.Cookies.GetStatus(ctx, accountID) +} + +// UpdateProfile 保存账号昵称和头像等非敏感展示资料。 +func (r *AccountLoginRepository) UpdateProfile(ctx context.Context, accountID, nickname, avatarURL string) error { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return validationErr + } + return r.store.Cookies.UpdateProfile(ctx, accountID, nickname, avatarURL) +} + +// FindAccount 查询扫码账号的存在性和归属,不读取任何凭证字段。 +func (r *AccountLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return accountapp.QRLoginAccount{}, validationErr + } + // ownerID 保存数据库返回的非敏感账号所有者标识;queryErr 保存查询错误。 + ownerID, queryErr := r.store.Cookies.GetOwnerID(ctx, accountID) + if queryErr != nil { + if errors.Is(queryErr, db.ErrNotFound) { + return accountapp.QRLoginAccount{}, accountapp.ErrNotFound + } + return accountapp.QRLoginAccount{}, queryErr + } + return accountapp.QRLoginAccount{ID: accountID, UserID: ownerID}, nil +} + +// UpdateFlatCookieOwnedForQR 更新扫码登录已有账号的扁平 Cookie并清除快照。 +func (r *AccountLoginRepository) UpdateFlatCookieOwnedForQR(ctx context.Context, accountID, cookies string) error { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return validationErr + } + // detail 保存仅供适配器内部使用的平台凭证视图;queryErr 保存查询错误。 + detail, queryErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) + if queryErr != nil { + return queryErr + } + // metadata 保存剔除旧快照后的加密元数据。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()) +} + +// UpdateCookieSnapshotOwned 更新扫码 Cookie 并合并完整浏览器快照到加密 metadata。 +func (r *AccountLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return validationErr + } + // detail 保存仅供适配器内部使用的平台凭证视图;queryErr 保存查询错误。 + detail, queryErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) + if queryErr != nil { + return queryErr + } + // browserSnapshot 保存转换后的浏览器快照,明文不向应用层或 HTTP 层返回。 + browserSnapshot := make([]cookierefresh.BrowserCookie, 0, len(snapshot)) + // snapshotEntry 表示当前待转换的应用层 Cookie 快照。 + for _, snapshotEntry := range snapshot { + browserSnapshot = append(browserSnapshot, cookierefresh.BrowserCookie{ + Name: snapshotEntry.Name, Value: snapshotEntry.Value, Domain: snapshotEntry.Domain, + Path: snapshotEntry.Path, Expires: snapshotEntry.Expires, HTTPOnly: snapshotEntry.HTTPOnly, + Secure: snapshotEntry.Secure, SameSite: snapshotEntry.SameSite, PartitionKey: snapshotEntry.PartitionKey, + }) + } + // metadata 保存合并浏览器快照后的加密元数据文本。 + metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, browserSnapshot) + return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()) +} + +// GetOwnedSummary 查询指定用户拥有的非敏感账号摘要。 +func (r *AccountLoginRepository) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (accountapp.Summary, error) { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return accountapp.Summary{}, validationErr + } + // summary 保存数据库返回的非敏感账号摘要;queryErr 保存摘要查询错误。 + summary, queryErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID) + if queryErr != nil { + if errors.Is(queryErr, db.ErrForbidden) { + return accountapp.Summary{}, accountapp.ErrForbidden + } + if errors.Is(queryErr, db.ErrNotFound) { + // ownerID 和 ownerErr 用于区分不存在账号与跨用户账号,保持 HTTP 兼容状态码。 + ownerID, ownerErr := r.store.Cookies.GetOwnerID(ctx, accountID) + if ownerErr == nil && ownerID != userID { + return accountapp.Summary{}, accountapp.ErrForbidden + } + return accountapp.Summary{}, accountapp.ErrNotFound + } + return accountapp.Summary{}, queryErr + } + return accountapp.Summary{ + ID: summary.ID, UserID: summary.UserID, Remark: summary.Remark, + Nickname: summary.Nickname, AvatarURL: summary.AvatarURL, + AutoConfirm: summary.AutoConfirm, PauseDuration: summary.PauseDuration, + PausedUntil: summary.PausedUntil, Username: summary.Username, + ShowBrowser: summary.ShowBrowser, LastRefreshAt: summary.LastRefreshAt, + LoginMethod: summary.LoginMethod, + LastLoginAt: summary.LastLoginAt, CreatedAt: summary.CreatedAt, + }, nil +} + +// DeleteOwned 在凭证锁内再次确认账号归属后删除账号,避免停止 fencing 期间误删被替换账号。 +func (r *AccountLoginRepository) DeleteOwned(ctx context.Context, userID int64, accountID string) error { + // validationErr 表示数据库或 Cookie 仓储未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return validationErr + } + // unlock 保护最终归属复核与删除之间的账号凭证状态。 + unlock := r.LockCredentials(accountID) + defer unlock() + // summaryErr 保存锁内最终归属复核失败的原因。 + if _, summaryErr := r.GetOwnedSummary(ctx, userID, accountID); summaryErr != nil { + return summaryErr + } + return r.store.Cookies.Delete(ctx, accountID) +} + +// validateStore 检查数据库聚合入口是否已完成装配。 +func (r *AccountLoginRepository) validateStore() error { + if r == nil || r.store == nil { + return errors.New("账号登录数据库适配器未初始化") + } + return nil +} + +// validateCookies 检查账号凭证仓储是否已完成装配。 +func (r *AccountLoginRepository) validateCookies() error { + // validationErr 表示数据库适配器未完成装配。 + validationErr := r.validateStore() + if validationErr != nil { + return validationErr + } + if r.store.Cookies == nil { + return errors.New("账号登录 Cookie 仓储未初始化") + } + return nil +} + +var _ accountapp.CredentialRepository = (*AccountLoginRepository)(nil) +var _ accountapp.ProfileSummaryRepository = (*AccountLoginRepository)(nil) +var _ accountapp.DeleteSummaryRepository = (*AccountLoginRepository)(nil) + +// QRLoginRepository 将账号登录适配器限制为扫码持久化端口,避免应用层接触数据库模型。 +type QRLoginRepository struct { + // repository 保存共享的账号凭证适配器。 + repository *AccountLoginRepository +} + +// NewQRLoginRepository 构造扫码登录专用凭证端口。 +func NewQRLoginRepository(store *db.Store) accountapp.QRLoginRepository { + return QRLoginRepository{repository: NewAccountLoginRepository(store)} +} + +// LockCredentials 串行化扫码登录对同一账号的凭证变更。 +func (r QRLoginRepository) LockCredentials(accountID string) func() { + return r.repository.LockCredentials(accountID) +} + +// FindAccount 查询扫码账号的存在性和归属,不读取凭证字段。 +func (r QRLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) { + return r.repository.FindAccount(ctx, accountID) +} + +// CreateCookieOwned 创建扫码登录得到的新账号 Cookie。 +func (r QRLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error { + return r.repository.CreateCookieOwned(ctx, accountID, cookies, userID) +} + +// UpdateFlatCookieOwned 更新已有账号扁平 Cookie并清除完整快照。 +func (r QRLoginRepository) UpdateFlatCookieOwned(ctx context.Context, accountID, cookies string) error { + return r.repository.UpdateFlatCookieOwnedForQR(ctx, accountID, cookies) +} + +// UpdateCookieSnapshotOwned 更新 Cookie 并合并完整浏览器快照。 +func (r QRLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error { + return r.repository.UpdateCookieSnapshotOwned(ctx, accountID, cookies, snapshot) +} + +// ClearTokens 清理扫码登录前遗留的旧连接 Token。 +func (r QRLoginRepository) ClearTokens(ctx context.Context, accountID string) error { + return r.repository.ClearTokens(ctx, accountID) +} + +var _ accountapp.QRLoginRepository = QRLoginRepository{} diff --git a/internal/adapter/account_login_repository_test.go b/internal/adapter/account_login_repository_test.go new file mode 100644 index 0000000..d98efa0 --- /dev/null +++ b/internal/adapter/account_login_repository_test.go @@ -0,0 +1,152 @@ +package adapter + +import ( + "context" + "errors" + "testing" + "time" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/xianyu/cookierefresh" +) + +// TestAccountLoginRepositoryKeepsPlatformViewNarrow 验证平台凭证 Port 只返回 Cookie 运行所需字段。 +func TestAccountLoginRepositoryKeepsPlatformViewNarrow(t *testing.T) { + // store 是包含测试账号和加密凭证的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试共用的数据库上下文。 + ctx := context.Background() + // metadata 是带浏览器快照的加密元数据样例。 + metadata := cookierefresh.MetadataWithSnapshot(`{"device":"test"}`, []cookierefresh.BrowserCookie{{Name: "sid", Value: "snapshot", Domain: ".goofish.com", Path: "/"}}) + // updateErr 保存写入平台凭证视图的结果。 + if updateErr := store.Cookies.UpdateRenewalCookie(ctx, "cid", "sid=flat", metadata, 123); updateErr != nil { + t.Fatalf("写入平台凭证视图失败: %v", updateErr) + } + // repository 是绑定 SQLite 存储的账号登录适配器。 + repository := NewAccountLoginRepository(store) + // detail、loadErr 保存应用 Port 返回的窄凭证视图及错误。 + detail, loadErr := repository.LoadPlatformDetail(ctx, "cid") + if loadErr != nil { + t.Fatalf("读取平台凭证视图失败: %v", loadErr) + } + if detail == nil || detail.ID != "cid" || detail.UserID != 1 || detail.Value != "sid=flat" || detail.LastRefreshAt != 123 { + t.Fatalf("平台凭证视图映射异常: %+v", detail) + } + if detail.MetadataJSON == "" || detail.ShowBrowser { + t.Fatalf("平台凭证视图未保留必要 metadata 或浏览器设置: %+v", detail) + } +} + +// TestAccountLoginRepositoryUpdatesCookieSnapshot 验证扁平更新清除旧快照而扫码快照更新保留完整作用域。 +func TestAccountLoginRepositoryUpdatesCookieSnapshot(t *testing.T) { + // store 是用于验证 Cookie metadata 合并的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试共用的数据库上下文。 + ctx := context.Background() + // repository 是绑定测试存储的账号登录适配器。 + repository := NewAccountLoginRepository(store) + // initialMetadata 是待被扁平更新清除的旧浏览器快照。 + initialMetadata := cookierefresh.MetadataWithSnapshot(`{}`, []cookierefresh.BrowserCookie{{Name: "old", Value: "1", Domain: ".goofish.com", Path: "/"}}) + // initialErr 保存旧快照写入结果。 + if initialErr := store.Cookies.UpdateRenewalCookie(ctx, "cid", "sid=old", initialMetadata, time.Now().Unix()); initialErr != nil { + t.Fatalf("写入旧快照失败: %v", initialErr) + } + // detail、detailErr 保存扁平更新前的窄凭证视图。 + detail, detailErr := repository.LoadPlatformDetail(ctx, "cid") + if detailErr != nil { + t.Fatalf("读取旧凭证视图失败: %v", detailErr) + } + // flatErr 保存扁平 Cookie 更新结果。 + if flatErr := repository.UpdateFlatCookieOwned(ctx, detail, "sid=flat"); flatErr != nil { + t.Fatalf("扁平 Cookie 更新失败: %v", flatErr) + } + // flatDetail、flatLoadErr 保存扁平更新后的凭证视图。 + flatDetail, flatLoadErr := repository.LoadPlatformDetail(ctx, "cid") + if flatLoadErr != nil { + t.Fatalf("读取扁平 Cookie 失败: %v", flatLoadErr) + } + // complete 表示扁平更新后 metadata 是否仍包含完整浏览器快照。 + if _, complete := cookierefresh.SnapshotFromMetadataOK(flatDetail.MetadataJSON); complete { + t.Fatal("扁平 Cookie 更新不应保留旧快照") + } + // snapshotErr 保存扫码快照更新结果。 + snapshotErr := repository.UpdateCookieSnapshotOwned(ctx, "cid", "sid=snapshot", []accountapp.CookieSnapshot{{Name: "sid", Value: "snapshot", Domain: ".goofish.com", Path: "/"}}) + if snapshotErr != nil { + t.Fatalf("扫码快照更新失败: %v", snapshotErr) + } + // snapshotDetail、snapshotLoadErr 保存扫码快照更新后的凭证视图。 + snapshotDetail, snapshotLoadErr := repository.LoadPlatformDetail(ctx, "cid") + if snapshotLoadErr != nil { + t.Fatalf("读取扫码快照失败: %v", snapshotLoadErr) + } + // snapshot、snapshotOK 保存适配器合并后的 Cookie 快照及完整性。 + snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(snapshotDetail.MetadataJSON) + if !snapshotOK || len(snapshot) != 1 || snapshot[0].Value != "snapshot" { + t.Fatalf("扫码 Cookie 快照未正确保存: ok=%v snapshot=%+v", snapshotOK, snapshot) + } +} + +// TestAccountLoginRepositoryMapsOwnershipErrors 验证摘要与扫码账号查询不会泄露跨用户凭证内容。 +func TestAccountLoginRepositoryMapsOwnershipErrors(t *testing.T) { + // store 是包含一个账号所有者的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试共用的数据库上下文。 + ctx := context.Background() + // repository 是绑定测试存储的账号登录适配器。 + repository := NewAccountLoginRepository(store) + // forbiddenSummaryErr 保存跨用户摘要查询的应用错误。 + _, forbiddenSummaryErr := repository.GetOwnedSummary(ctx, 2, "cid") + if !errors.Is(forbiddenSummaryErr, accountapp.ErrForbidden) { + t.Fatalf("跨用户摘要应返回应用越权错误,got %v", forbiddenSummaryErr) + } + // missingAccountErr 保存不存在扫码账号的应用错误。 + _, missingAccountErr := repository.FindAccount(ctx, "missing") + if !errors.Is(missingAccountErr, accountapp.ErrNotFound) { + t.Fatalf("不存在扫码账号应返回应用不存在错误,got %v", missingAccountErr) + } + // missingStoreErr 保存未装配数据库时的快速失败结果。 + missingStoreErr := NewAccountLoginRepository(nil).CreateCookieOwned(ctx, "cid", "secret", 1) + if missingStoreErr == nil { + t.Fatal("未装配数据库时不应伪装凭证写入成功") + } + // duplicateErr 验证并发/重复创建被转换为应用层稳定错误,而不是泄露数据库错误类型。 + duplicateErr := repository.CreateCookieOwned(ctx, "cid", "sid=duplicate", 1) + if !errors.Is(duplicateErr, accountapp.ErrAlreadyExists) { + t.Fatalf("重复创建应返回账号已存在错误,got %v", duplicateErr) + } +} + +// TestAccountLoginRepositoryMapsMissingPlatformCredential 验证平台凭证缺失时返回应用层哨兵。 +func TestAccountLoginRepositoryMapsMissingPlatformCredential(t *testing.T) { + // store、cleanup 保存用于查询不存在账号的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试存储的账号登录适配器。 + repository := NewAccountLoginRepository(store) + // loadErr 保存不存在平台账号的窄凭证查询错误。 + _, loadErr := repository.LoadPlatformDetail(context.Background(), "missing-platform-account") + if !errors.Is(loadErr, accountapp.ErrCredentialNotFound) { + t.Fatalf("缺失平台账号应返回应用错误: %v", loadErr) + } +} + +// TestAccountLoginRepositoryPropagatesDatabaseFailure 验证数据库关闭后凭证 Port 原样报告基础设施错误。 +func TestAccountLoginRepositoryPropagatesDatabaseFailure(t *testing.T) { + // store 是随后主动关闭的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定待关闭存储的账号登录适配器。 + repository := NewAccountLoginRepository(store) + // closeErr 保存主动关闭数据库的结果。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // loadErr 保存数据库关闭后平台视图查询的错误。 + _, loadErr := repository.LoadPlatformDetail(context.Background(), "cid") + if loadErr == nil { + t.Fatal("数据库关闭后应返回凭证查询错误") + } +} diff --git a/internal/adapter/account_long_login.go b/internal/adapter/account_long_login.go new file mode 100644 index 0000000..fd0b8d5 --- /dev/null +++ b/internal/adapter/account_long_login.go @@ -0,0 +1,186 @@ +package adapter + +import ( + "context" + "errors" + "log/slog" + "time" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/xianyu/cookierefresh" + xrenew "xianyu-go/internal/xianyu/renew" +) + +// LongLoginClient 定义长登录平台客户端的最小协议,隔离 Server 与 renew 实现。 +type LongLoginClient interface { + // QueryLongLoginSettings 查询平台当前长登录状态,并返回响应 Cookie。 + QueryLongLoginSettings(context.Context, string, ...[]cookierefresh.BrowserCookie) (*xrenew.LongLoginSettings, error) + // SetLongLoginSettings 更新平台长登录状态,并返回响应 Cookie。 + SetLongLoginSettings(context.Context, string, bool, ...[]cookierefresh.BrowserCookie) (*xrenew.LongLoginSettings, error) +} + +// LongLoginAdapter 将长登录平台协议和 Cookie 持久化适配到账号应用端口。 +type LongLoginAdapter struct { + // repository 提供凭证锁、平台窄视图和 Cookie 写回能力。 + repository accountapp.CredentialRepository + // service 返回当前 Server 配置的平台长登录客户端;函数形式允许测试在构造后替换客户端。 + service func() LongLoginClient + // updateRunningCookie 在凭证锁释放后同步已变化的运行时 Cookie。 + updateRunningCookie func(context.Context, string, string) + // logger 记录不包含明文 Cookie 的持久化错误。 + logger *slog.Logger +} + +// NewLongLoginAdapter 构造长登录平台适配器。 +func NewLongLoginAdapter(repository accountapp.CredentialRepository, service func() LongLoginClient, updateRunningCookie func(context.Context, string, string), logger *slog.Logger) *LongLoginAdapter { + return &LongLoginAdapter{repository: repository, service: service, updateRunningCookie: updateRunningCookie, logger: logger} +} + +// QueryLongLogin 查询长登录状态并持久化平台返回的 Cookie。 +func (a *LongLoginAdapter) QueryLongLogin(ctx context.Context, accountID string) (accountapp.LongLoginResult, error) { + return a.execute(ctx, accountID, nil) +} + +// SetLongLogin 更新长登录开关并持久化平台返回的 Cookie。 +func (a *LongLoginAdapter) SetLongLogin(ctx context.Context, accountID string, enabled bool) (accountapp.LongLoginResult, error) { + return a.execute(ctx, accountID, &enabled) +} + +// execute 在凭证锁内读取最新平台视图并完成平台调用,锁只覆盖凭证一致性和写回。 +func (a *LongLoginAdapter) execute(ctx context.Context, accountID string, enabled *bool) (accountapp.LongLoginResult, error) { + if a == nil || a.repository == nil || a.service == nil { + return accountapp.LongLoginResult{}, errors.New("长登录适配器未初始化") + } + // unlock 保护本次平台 Cookie 读取和写回;平台网络请求必须在锁外执行。 + unlock := a.repository.LockCredentials(accountID) + // detail 保存平台调用所需的 Cookie 与加密 metadata 窄视图。 + detail, loadErr := a.repository.LoadPlatformDetail(ctx, accountID) + unlock() + if loadErr != nil { + return accountapp.LongLoginResult{}, loadErr + } + if detail == nil { + return accountapp.LongLoginResult{}, accountapp.ErrNotFound + } + // requestCookies 保存按请求域过滤后的 Cookie;snapshot 保存完整 Cookie Jar(如存在)。 + requestCookies, snapshot := longLoginCookies(detail, queryURL(enabled)) + // platformResult 保存平台返回的非敏感长登录状态;requestErr 保留平台业务或网络错误。 + var platformResult *xrenew.LongLoginSettings + // requestErr 保存平台请求失败;即使失败,响应 Set-Cookie 也可能已完成持久化。 + var requestErr error + // client 是本次请求使用的长登录平台客户端。 + client := a.service() + if enabled == nil { + if snapshot != nil { + platformResult, requestErr = client.QueryLongLoginSettings(ctx, requestCookies, snapshot) + } else { + platformResult, requestErr = client.QueryLongLoginSettings(ctx, requestCookies) + } + } else if snapshot != nil { + platformResult, requestErr = client.SetLongLoginSettings(ctx, requestCookies, *enabled, snapshot) + } else { + platformResult, requestErr = client.SetLongLoginSettings(ctx, requestCookies, *enabled) + } + // credentialChanged 表示平台响应使本地凭证或完整 Cookie Jar 发生变化。 + credentialChanged, persistErr := a.persist(ctx, detail, platformResult, queryURL(enabled)) + if persistErr != nil { + return accountapp.LongLoginResult{}, persistErr + } + if credentialChanged && a.updateRunningCookie != nil { + a.updateRunningCookie(ctx, accountID, platformResult.NewCookies) + } + if requestErr != nil { + return toLongLoginResult(platformResult), errors.Join(accountapp.ErrLongLoginPlatform, requestErr) + } + return toLongLoginResult(platformResult), nil +} + +// queryURL 返回当前长登录操作对应的官方请求地址。 +func queryURL(enabled *bool) string { + if enabled == nil { + return xrenew.QueryLoginSettingsURL + } + return xrenew.SetLoginSettingsURL +} + +// longLoginCookies 从平台窄视图提取请求 Cookie 和完整快照,历史扁平账号不伪造快照。 +func longLoginCookies(detail *accountapp.CredentialDetail, requestURL string) (string, []cookierefresh.BrowserCookie) { + if detail == nil { + return "", nil + } + // snapshot、complete 保存 metadata 中的完整 Cookie 快照及其权威标记。 + if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete { + // header、authoritative 保存按平台请求 URL 过滤后的 Cookie 头及完整性标记。 + header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now()) + _ = authoritative + return header, snapshot + } + return detail.Value, nil +} + +// persist 合并平台响应 Cookie 并在凭证锁内保存最新扁平 Cookie 与完整快照。 +func (a *LongLoginAdapter) persist(ctx context.Context, detail *accountapp.CredentialDetail, result *xrenew.LongLoginSettings, requestURL string) (bool, error) { + if result == nil || detail == nil { + return false, nil + } + // unlock 保护加锁后重读和最终写回,避免平台请求期间持有凭证锁。 + unlock := a.repository.LockCredentials(detail.ID) + defer unlock() + // latest 保存平台调用期间可能被其他流程更新后的最新凭证视图。 + latest, loadErr := a.repository.LoadPlatformDetail(ctx, detail.ID) + if loadErr != nil || latest == nil { + if a.logger != nil { + a.logger.Warn("读取长登录最新凭证失败", "cookie_id", detail.ID, "err", loadErr) + } + return false, loadErr + } + // metadata 保存合并响应 Cookie 后的加密元数据。 + metadata := latest.MetadataJSON + // snapshot、hasSnapshot 保存现有完整 Cookie Jar及其权威标志。 + snapshot, hasSnapshot := cookierefresh.SnapshotFromMetadataOK(latest.MetadataJSON) + if result.CookieSnapshotComplete { + snapshot = cookierefresh.NormalizeSnapshot(result.CookieSnapshot) + if snapshot == nil { + snapshot = []cookierefresh.BrowserCookie{} + } + result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now()) + metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) + } else if hasSnapshot { + snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), "https://goofish.com") + if snapshot == nil { + snapshot = []cookierefresh.BrowserCookie{} + } + result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now()) + metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) + } else { + result.NewCookies = xrenew.MergeSetCookies(latest.Value, result.SetCookies) + metadata = cookierefresh.MetadataWithoutSnapshot(metadata) + } + // changed 表示写回后 Cookie 或 metadata 是否发生变化。 + changed := result.NewCookies != latest.Value || metadata != latest.MetadataJSON + if !changed && len(result.SetCookies) == 0 { + return false, nil + } + // persistErr 保存长登录 Cookie 与 metadata 的持久化错误。 + if persistErr := a.repository.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); persistErr != nil { + if a.logger != nil { + a.logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", persistErr) + } + return false, persistErr + } + if changed { + // clearErr 保存凭证变化后清理旧连接 Token 的错误;不回滚已成功的 Cookie 写入。 + if clearErr := a.repository.ClearTokens(ctx, detail.ID); clearErr != nil && a.logger != nil { + a.logger.Warn("长登录 Cookie 保存后清理旧连接凭证失败", "cookie_id", detail.ID, "err", clearErr) + } + } + return changed, nil +} + +// toLongLoginResult 将平台结果限制为不含 Cookie 的应用层结果。 +func toLongLoginResult(result *xrenew.LongLoginSettings) accountapp.LongLoginResult { + if result == nil { + return accountapp.LongLoginResult{} + } + return accountapp.LongLoginResult{CanOpenLongLogin: result.CanOpenLongLogin, Enabled: result.Enabled} +} diff --git a/internal/adapter/account_profile.go b/internal/adapter/account_profile.go new file mode 100644 index 0000000..9660220 --- /dev/null +++ b/internal/adapter/account_profile.go @@ -0,0 +1,165 @@ +package adapter + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/xianyu/mtop" +) + +// AccountProfilePort 将平台资料查询和账号资料持久化适配到账号应用层。 +type AccountProfilePort struct { + // repository 提供凭证快照读取、Cookie 写回和资料保存能力。 + repository *AccountLoginRepository + // client 提供平台资料查询能力。 + client func() mtop.Client + // updateRunningCookie 在凭证锁释放后同步运行时 Cookie。 + updateRunningCookie func(context.Context, string, string) + // recoverSession 在平台返回会话失效时触发账号恢复。 + recoverSession func(context.Context, string, error) bool + // logger 记录不包含凭证内容的资料刷新错误。 + logger *slog.Logger +} + +// NewAccountProfilePort 构造账号资料平台适配器。 +func NewAccountProfilePort(repository *AccountLoginRepository, client func() mtop.Client, updateRunningCookie func(context.Context, string, string), recoverSession func(context.Context, string, error) bool, logger *slog.Logger) *AccountProfilePort { + return &AccountProfilePort{repository: repository, client: client, updateRunningCookie: updateRunningCookie, recoverSession: recoverSession, logger: logger} +} + +// RefreshProfile 调用平台资料接口、持久化响应 Cookie 和展示资料。 +func (p *AccountProfilePort) RefreshProfile(ctx context.Context, input accountapp.ProfileInput) (accountapp.ProfileResult, error) { + if p == nil || p.repository == nil || p.client == nil || p.client() == nil { + return accountapp.ProfileResult{}, errors.New("账号资料适配器未初始化") + } + // fallbackNickname、fallbackAvatar 保存平台失败时的非敏感展示兜底。 + fallbackNickname, fallbackAvatar := cachedProfile(input.Summary) + // unlock 保护平台凭证快照读取和响应写回;网络请求发生在解锁后。 + unlock := p.repository.LockCredentials(input.AccountID) + // detail、loadErr 保存锁外读取的平台凭证窄视图及其错误。 + detail, loadErr := p.repository.LoadPlatformDetail(ctx, input.AccountID) + unlock() + if loadErr != nil || detail == nil || detail.UserID != input.UserID { + if loadErr == nil { + loadErr = accountapp.ErrNotFound + } + return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: fallbackNickname, AvatarURL: fallbackAvatar, ErrorMessage: truncateProfileError(loadErr)}, nil + } + // requestCtx、session 保存带完整 Jar 或扁平 Cookie 的平台请求上下文。 + requestCtx, session := withProfileCookieSession(ctx, detail) + // profile、callErr 保存平台资料结果和调用错误;响应 Cookie 仍会继续处理。 + profile, callErr := p.client().FetchUserProfile(requestCtx, detail.Value) + // value、changed、handled、persistErr 保存响应 Cookie 会话写回结果。 + value, changed, handled, persistErr := p.persistProfileSession(ctx, detail, session) + if persistErr != nil { + callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", persistErr)) + } else if changed && p.updateRunningCookie != nil { + p.updateRunningCookie(ctx, input.AccountID, value) + } + if !handled && callErr == nil && profile != nil && profile.UpdatedCookies != "" && profile.UpdatedCookies != detail.Value { + // flatErr 保存历史扁平 Cookie 写回错误;没有完整 Jar 时才走该兼容分支。 + if flatErr := p.repository.UpdateFlatCookieOwned(ctx, detail, profile.UpdatedCookies); flatErr != nil { + callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", flatErr)) + } else if p.updateRunningCookie != nil { + p.updateRunningCookie(ctx, input.AccountID, profile.UpdatedCookies) + } + } + if callErr != nil { + if p.recoverSession != nil { + p.recoverSession(ctx, input.AccountID, callErr) + } + if p.logger != nil { + p.logger.Warn("刷新账号资料失败", "account", input.AccountID, "err", callErr) + } + return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: fallbackNickname, AvatarURL: fallbackAvatar, ErrorMessage: truncateProfileError(callErr)}, nil + } + if profile == nil { + return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: fallbackNickname, AvatarURL: fallbackAvatar, ErrorMessage: "账号资料接口未返回结果"}, nil + } + // nickname 保存归一化后的平台昵称;avatarURL 保存归一化后的非敏感头像地址。 + nickname := strings.TrimSpace(profile.Nickname) + // avatarURL 保存归一化后的非敏感平台头像地址。 + avatarURL := normalizeProfileAvatar(profile.AvatarURL) + // saveErr 保存资料展示字段写回错误;写回失败不覆盖已获得的平台资料。 + if saveErr := p.repository.UpdateProfile(ctx, input.AccountID, nickname, avatarURL); saveErr != nil && p.logger != nil { + p.logger.Warn("保存账号资料失败", "account", input.AccountID, "err", saveErr) + } + if nickname == "" { + nickname = fallbackNickname + } + if avatarURL == "" { + avatarURL = fallbackAvatar + } + return accountapp.ProfileResult{AccountID: input.AccountID, Nickname: nickname, AvatarURL: avatarURL}, nil +} + +// withProfileCookieSession 将平台凭证窄视图转换为带快照更新能力的请求会话。 +func withProfileCookieSession(ctx context.Context, detail *accountapp.CredentialDetail) (context.Context, *CookieSession) { + // snapshot、ok 保存 metadata 中的完整 Cookie 快照及其有效标记。 + if snapshot, ok := SnapshotFromMetadata(detail.MetadataJSON); ok { + return WithCookieSnapshot(ctx, snapshot) + } + return WithFlatCookieSession(ctx, detail.Value) +} + +// persistProfileSession 在短凭证锁内保存平台响应 Cookie,避免慢速网络位于锁内。 +func (p *AccountProfilePort) persistProfileSession(ctx context.Context, detail *accountapp.CredentialDetail, session *CookieSession) (string, bool, bool, error) { + // unlock 保护响应 Cookie 写回期间的账号凭证一致性。 + unlock := p.repository.LockCredentials(detail.ID) + defer unlock() + // latest、loadErr 保存加锁后重读的最新凭证视图及读取错误。 + latest, loadErr := p.repository.LoadPlatformDetail(ctx, detail.ID) + if loadErr != nil { + return "", false, true, loadErr + } + return PersistCookieSessionLocked(ctx, p.repository, latest, session) +} + +// cachedProfile 生成资料失败时使用的本地非敏感展示值。 +func cachedProfile(summary accountapp.Summary) (string, string) { + // nickname 保存资料失败时优先使用的备注或缓存昵称。 + nickname := strings.TrimSpace(summary.Remark) + if nickname == "" { + nickname = strings.TrimSpace(summary.Nickname) + } + if nickname == "" { + nickname = "账号 " + shortProfileID(summary.ID) + } + return nickname, normalizeProfileAvatar(summary.AvatarURL) +} + +// normalizeProfileAvatar 统一平台返回的头像协议,避免把 HTTP 头像写回展示资料。 +func normalizeProfileAvatar(raw string) string { + raw = strings.TrimSpace(raw) + if strings.HasPrefix(raw, "//") { + return "https:" + raw + } + if strings.HasPrefix(raw, "http://") { + return "https://" + strings.TrimPrefix(raw, "http://") + } + return raw +} + +// truncateProfileError 限制资料刷新错误长度,避免平台响应原文过长进入 HTTP。 +func truncateProfileError(err error) string { + if err == nil { + return "" + } + // message 保存待截断的错误文本,避免平台原文无限进入响应。 + message := err.Error() + if len(message) > 180 { + return message[:180] + } + return message +} + +// shortProfileID 限制兜底展示中的账号标识长度,避免错误响应或日志暴露完整标识。 +func shortProfileID(accountID string) string { + if len(accountID) > 6 { + return accountID[:6] + } + return accountID +} diff --git a/internal/adapter/account_settings.go b/internal/adapter/account_settings.go new file mode 100644 index 0000000..ee3d6f6 --- /dev/null +++ b/internal/adapter/account_settings.go @@ -0,0 +1,179 @@ +package adapter + +import ( + "context" + "errors" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" +) + +// ClearTokens 清理 Cookie 更新后失效的旧连接凭证;缺少 Token 仓储时保持兼容空操作。 +func (r *AccountSettingsRepository) ClearTokens(ctx context.Context, accountID string) error { + // validationErr 表示账号设置适配器缺少数据库依赖。 + if validationErr := r.validate(); validationErr != nil { + return validationErr + } + if r.store.Tokens == nil { + return nil + } + return r.store.Tokens.Clear(ctx, accountID) +} + +// AccountSettingsRepository 将账号设置、登录秘密和暂停状态适配到应用层 Port。 +// 明文 Cookie 与登录密码只在本适配器调用数据库加密写入时短暂存在。 +type AccountSettingsRepository struct { + // store 保存数据库聚合入口,不向应用层暴露裸数据库连接或模型。 + store *db.Store +} + +// NewAccountSettingsRepository 构造账号设置数据库适配器。 +func NewAccountSettingsRepository(store *db.Store) *AccountSettingsRepository { + return &AccountSettingsRepository{store: store} +} + +// LockCredentials 串行化同一账号的敏感设置写入;缺少数据库时返回空操作解锁函数。 +func (r *AccountSettingsRepository) LockCredentials(accountID string) func() { + if r == nil || r.store == nil { + return func() {} + } + return r.store.LockAccountCredentials(accountID) +} + +// UpdateSettings 将应用层账号设置转换为数据库事务输入并执行归属复核。 +func (r *AccountSettingsRepository) UpdateSettings(ctx context.Context, input accountapp.SettingsUpdateInput) (int64, error) { + // validationErr 表示账号设置适配器缺少数据库依赖。 + if validationErr := r.validate(); validationErr != nil { + return 0, validationErr + } + // databaseInput 只在适配器边界携带数据库模型,避免上层依赖 internal/db。 + databaseInput := db.AccountSettingsUpdate{ + UserID: input.UserID, Value: input.Cookie, Remark: input.Remark, + AutoConfirm: input.AutoConfirm, PauseDuration: input.PauseDuration, + Username: input.Username, Password: input.Password, + ShowBrowser: input.ShowBrowser, ChannelIDs: input.ChannelIDs, + } + // pausedUntil、updateErr 保存数据库返回的暂停截止时间和事务错误。 + pausedUntil, updateErr := r.store.Cookies.UpdateSettings(ctx, input.AccountID, databaseInput) + return pausedUntil, normalizeAccountSettingsError(updateErr) +} + +// UpdateLoginInfo 将登录用户名、可选密码和浏览器显示设置复用为原子账号设置更新。 +func (r *AccountSettingsRepository) UpdateLoginInfo(ctx context.Context, input accountapp.LoginInfoUpdateInput) error { + // validationErr 表示账号设置适配器缺少数据库依赖。 + if validationErr := r.validate(); validationErr != nil { + return validationErr + } + // username 保存兼容旧接口的用户名覆盖值。 + username := input.Username + // showBrowser 保存密码登录时是否显示浏览器的配置值。 + showBrowser := input.ShowBrowser + // updateErr 保存复用账号设置事务写入登录信息时的错误。 + _, updateErr := r.UpdateSettings(ctx, accountapp.SettingsUpdateInput{ + UserID: input.UserID, AccountID: input.AccountID, + Username: &username, Password: input.Password, ShowBrowser: &showBrowser, + }) + return updateErr +} + +// SetStatusOwned 更新账号启用状态,并在数据库访问前验证账号归属。 +func (r *AccountSettingsRepository) SetStatusOwned(ctx context.Context, userID int64, accountID string, enabled bool, reason string) error { + // validationErr 表示账号设置适配器缺少数据库依赖。 + if validationErr := r.validate(); validationErr != nil { + return validationErr + } + // ownershipErr 表示状态写入前的账号归属校验错误。 + if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil { + return ownershipErr + } + return normalizeAccountSettingsError(r.store.Cookies.SetStatusWithReason(ctx, accountID, enabled, reason)) +} + +// StatusOwned 查询指定用户账号的启用状态,不读取 Cookie、metadata 或登录密码。 +func (r *AccountSettingsRepository) StatusOwned(ctx context.Context, userID int64, accountID string) (bool, error) { + // validationErr 表示账号设置适配器缺少数据库依赖。 + if validationErr := r.validate(); validationErr != nil { + return false, validationErr + } + // ownershipErr 表示状态读取前的账号归属校验错误。 + if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil { + return false, ownershipErr + } + // enabled、statusErr 保存数据库返回的启用状态和查询错误。 + enabled, statusErr := r.store.Cookies.Status(ctx, accountID) + return enabled, normalizeAccountSettingsError(statusErr) +} + +// SetPauseOwned 更新指定用户账号的暂停时长,并保留零值唤醒待执行任务的数据库语义。 +func (r *AccountSettingsRepository) SetPauseOwned(ctx context.Context, userID int64, accountID string, duration int) (int64, error) { + // validationErr 表示账号设置适配器缺少数据库依赖。 + if validationErr := r.validate(); validationErr != nil { + return 0, validationErr + } + // ownershipErr 表示暂停写入前的账号归属校验错误。 + if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil { + return 0, ownershipErr + } + // pausedUntil、pauseErr 保存数据库返回的暂停截止时间和写入错误。 + pausedUntil, pauseErr := r.store.Cookies.SetPause(ctx, accountID, duration) + return pausedUntil, normalizeAccountSettingsError(pauseErr) +} + +// GetPauseOwned 查询指定用户账号的暂停状态和配置时长。 +func (r *AccountSettingsRepository) GetPauseOwned(ctx context.Context, userID int64, accountID string) (accountapp.PauseState, error) { + // validationErr 表示账号设置适配器缺少数据库依赖。 + if validationErr := r.validate(); validationErr != nil { + return accountapp.PauseState{}, validationErr + } + // ownershipErr 表示暂停读取前的账号归属校验错误。 + if ownershipErr := r.requireOwner(ctx, userID, accountID); ownershipErr != nil { + return accountapp.PauseState{}, ownershipErr + } + // paused、pausedUntil、pauseErr 保存数据库返回的暂停标记、截止时间和查询错误。 + paused, pausedUntil, pauseErr := r.store.Cookies.IsPaused(ctx, accountID) + if pauseErr != nil { + return accountapp.PauseState{}, normalizeAccountSettingsError(pauseErr) + } + return accountapp.PauseState{Duration: r.store.Cookies.GetPauseDuration(ctx, accountID), PausedUntil: pausedUntil, Paused: paused}, nil +} + +// requireOwner 在数据库适配器内部完成非敏感账号归属复核。 +func (r *AccountSettingsRepository) requireOwner(ctx context.Context, userID int64, accountID string) error { + // _, ownershipErr 丢弃非敏感摘要本身,只保留账号是否属于当前用户的结论。 + if _, ownershipErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID); ownershipErr != nil { + if errors.Is(ownershipErr, db.ErrNotFound) { + // ownerID、ownerErr 用于区分账号不存在与账号属于其他用户,保持越权错误语义。 + // ownerID、ownerErr 保存账号所有者标识和归属查询错误。 + ownerID, ownerErr := r.store.Cookies.GetOwnerID(ctx, accountID) + if ownerErr == nil && ownerID != userID { + return accountapp.ErrForbidden + } + } + return normalizeAccountSettingsError(ownershipErr) + } + return nil +} + +// validate 检查账号设置适配器所需的数据库依赖是否已装配。 +func (r *AccountSettingsRepository) validate() error { + if r == nil || r.store == nil || r.store.Cookies == nil { + return errors.New("账号设置数据库 repository 未初始化") + } + return nil +} + +// normalizeAccountSettingsError 将数据库所有权错误转换为应用层稳定错误,不泄露数据库模型。 +func normalizeAccountSettingsError(err error) error { + if err == nil { + return nil + } + if errors.Is(err, db.ErrNotFound) { + return accountapp.ErrNotFound + } + if errors.Is(err, db.ErrForbidden) { + return accountapp.ErrForbidden + } + return err +} + +var _ accountapp.SettingsRepository = (*AccountSettingsRepository)(nil) diff --git a/internal/adapter/account_settings_test.go b/internal/adapter/account_settings_test.go new file mode 100644 index 0000000..a877a95 --- /dev/null +++ b/internal/adapter/account_settings_test.go @@ -0,0 +1,145 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" +) + +// TestAccountSettingsRepositoryRejectsMissingStore 验证账号设置适配器缺少数据库时所有入口均快速失败。 +func TestAccountSettingsRepositoryRejectsMissingStore(t *testing.T) { + // repository 保存未装配数据库的账号设置适配器。 + repository := NewAccountSettingsRepository(nil) + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // err 保存缺少数据库时的账号设置写入错误。 + if _, err := repository.UpdateSettings(ctx, accountapp.SettingsUpdateInput{AccountID: "cid"}); err == nil { + t.Fatal("UpdateSettings 缺少数据库时不应成功") + } + // err 保存缺少数据库时的登录信息写入错误。 + if err := repository.UpdateLoginInfo(ctx, accountapp.LoginInfoUpdateInput{AccountID: "cid"}); err == nil { + t.Fatal("UpdateLoginInfo 缺少数据库时不应成功") + } + // err 保存缺少数据库时的状态写入错误。 + if err := repository.SetStatusOwned(ctx, 1, "cid", true, ""); err == nil { + t.Fatal("SetStatusOwned 缺少数据库时不应成功") + } + // err 保存缺少数据库时的状态读取错误。 + if _, err := repository.StatusOwned(ctx, 1, "cid"); err == nil { + t.Fatal("StatusOwned 缺少数据库时不应成功") + } + // err 保存缺少数据库时的暂停写入错误。 + if _, err := repository.SetPauseOwned(ctx, 1, "cid", 1); err == nil { + t.Fatal("SetPauseOwned 缺少数据库时不应成功") + } + // err 保存缺少数据库时的暂停读取错误。 + if _, err := repository.GetPauseOwned(ctx, 1, "cid"); err == nil { + t.Fatal("GetPauseOwned 缺少数据库时不应成功") + } + // err 保存缺少数据库时的旧 Token 清理错误。 + if err := repository.ClearTokens(ctx, "cid"); err == nil { + t.Fatal("ClearTokens 缺少数据库时不应成功") + } +} + +// TestAccountSettingsRepositoryWritesAndReadsSettings 验证账号设置、登录秘密、状态和暂停端口的真实 SQLite 行为。 +func TestAccountSettingsRepositoryWritesAndReadsSettings(t *testing.T) { + // XIANYU_DATA_KEY 让本测试验证启用密钥时登录秘密确实加密落盘。 + t.Setenv("XIANYU_DATA_KEY", "account-settings-test-key") + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的账号设置适配器。 + repository := NewAccountSettingsRepository(store) + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // admin、userErr 保存测试账号所属用户和查询错误。 + admin, userErr := store.Users.GetByUsername(ctx, "admin") + if userErr != nil { + t.Fatalf("GetByUsername: %v", userErr) + } + // remark、password 保存本次设置写入的非敏感备注和敏感密码输入。 + remark := "新备注" + password := "new-password" // password 保存仅用于适配器加密写入的测试秘密。 + // enabled、showBrowser 保存账号开关设置。 + enabled, showBrowser := true, false + // updateErr 保存账号设置事务写入错误。 + _, updateErr := repository.UpdateSettings(ctx, accountapp.SettingsUpdateInput{ + UserID: admin.ID, AccountID: "cid", Remark: &remark, AutoConfirm: &enabled, + Username: ptrString("login-user"), Password: &password, ShowBrowser: &showBrowser, + }) + if updateErr != nil { + t.Fatalf("UpdateSettings: %v", updateErr) + } + // detail、detailErr 保存数据库返回的兼容详情,用于确认敏感字段由数据库加密保存。 + detail, detailErr := store.Cookies.GetDetails(ctx, "cid") + if detailErr != nil || detail.Remark != remark || !detail.AutoConfirm || detail.Username != "login-user" || detail.ShowBrowser { + t.Fatalf("settings detail=%+v err=%v", detail, detailErr) + } + // storedPassword 保存数据库中加密后的密码字段,仅用于确认敏感值未以明文落盘。 + var storedPassword string + // scanErr 保存读取数据库加密字段的错误。 + if scanErr := store.DB.QueryRowContext(ctx, `SELECT password FROM cookies WHERE id=?`, "cid").Scan(&storedPassword); scanErr != nil { + t.Fatalf("读取加密密码字段: %v", scanErr) + } + if storedPassword == password { + t.Fatal("登录密码不应以明文保存") + } + // statusErr 保存状态写入错误。 + statusErr := repository.SetStatusOwned(ctx, admin.ID, "cid", false, "manual") + if statusErr != nil { + t.Fatalf("SetStatusOwned: %v", statusErr) + } + // status、statusErr 保存状态读取结果和错误。 + status, statusErr := repository.StatusOwned(ctx, admin.ID, "cid") + if statusErr != nil || status { + t.Fatalf("StatusOwned status=%v err=%v", status, statusErr) + } + // pausedUntil、pauseErr 保存暂停写入结果和错误。 + pausedUntil, pauseErr := repository.SetPauseOwned(ctx, admin.ID, "cid", 5) + if pauseErr != nil || pausedUntil == 0 { + t.Fatalf("SetPauseOwned until=%d err=%v", pausedUntil, pauseErr) + } + // pauseState、pauseErr 保存暂停查询结果和错误。 + pauseState, pauseErr := repository.GetPauseOwned(ctx, admin.ID, "cid") + if pauseErr != nil || pauseState.Duration != 5 || !pauseState.Paused { + t.Fatalf("GetPauseOwned state=%+v err=%v", pauseState, pauseErr) + } + // other、otherErr 保存第二个用户,确保跨用户测试命中真实账号但不属于当前用户。 + if _, otherCreateErr := store.Users.Create(ctx, "other", "other@example.com", "pw"); otherCreateErr != nil { + t.Fatalf("Create other user: %v", otherCreateErr) + } + // other、otherErr 保存第二个用户及其查询错误。 + other, otherErr := store.Users.GetByUsername(ctx, "other") + if otherErr != nil { + t.Fatalf("GetByUsername other: %v", otherErr) + } + // wrongStatusErr 保存跨用户状态更新错误,确认适配器不会越权写入。 + wrongStatusErr := repository.SetStatusOwned(ctx, other.ID, "cid", true, "") + if !errors.Is(wrongStatusErr, accountapp.ErrForbidden) && !errors.Is(wrongStatusErr, db.ErrForbidden) { + t.Fatalf("跨用户状态更新错误=%v", wrongStatusErr) + } +} + +// TestAccountSettingsRepositoryClearTokensWithoutTokenStore 验证未装配 Token 仓储时清理动作保持兼容空操作。 +func TestAccountSettingsRepositoryClearTokensWithoutTokenStore(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的账号设置适配器。 + repository := NewAccountSettingsRepository(store) + // tokenStore 保存原始 Token 仓储并暂时清空,模拟最小装配场景。 + tokenStore := store.Tokens + store.Tokens = nil + defer func() { store.Tokens = tokenStore }() + // err 保存无 Token 仓储时的兼容清理结果。 + if err := repository.ClearTokens(context.Background(), "cid"); err != nil { + t.Fatalf("未装配 Token 仓储时不应失败: %v", err) + } +} + +// ptrString 返回指向给定字符串的输入指针,供设置端口测试构造可选字段。 +func ptrString(value string) *string { return &value } diff --git a/internal/adapter/account_summary.go b/internal/adapter/account_summary.go new file mode 100644 index 0000000..ed6240d --- /dev/null +++ b/internal/adapter/account_summary.go @@ -0,0 +1,164 @@ +package adapter + +import ( + "context" + "errors" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" +) + +// AccountSummaryRepository 将数据库账号摘要查询适配为应用层 Port,不向上层暴露数据库模型或凭证字段。 +type AccountSummaryRepository struct { + // store 保存数据库聚合入口,仅用于调用窄账号摘要查询。 + store *db.Store +} + +// NewAccountSummaryRepository 构造账号摘要数据库适配器。 +func NewAccountSummaryRepository(store *db.Store) *AccountSummaryRepository { + return &AccountSummaryRepository{store: store} +} + +// ListOwnedIDs 查询指定用户的账号 ID 列表,不解密任何凭证。 +func (r *AccountSummaryRepository) ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) { + // validationErr 表示摘要数据库适配器尚未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return nil, validationErr + } + return r.store.Cookies.ListOwnedIDs(ctx, userID) +} + +// ListSummaries 查询指定用户的非敏感账号摘要并转换为应用模型。 +func (r *AccountSummaryRepository) ListSummaries(ctx context.Context, userID int64) ([]accountapp.AccountSummary, error) { + // validationErr 表示摘要数据库适配器尚未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return nil, validationErr + } + // records、queryErr 保存数据库摘要行及查询错误。 + records, queryErr := r.store.Cookies.ListSummaries(ctx, userID) + if queryErr != nil { + return nil, normalizeAccountSummaryError(queryErr) + } + // summaries 保存与数据库模型解耦的应用摘要列表。 + summaries := make([]accountapp.AccountSummary, 0, len(records)) + // record 表示当前待转换的数据库账号摘要。 + for _, record := range records { + summaries = append(summaries, accountSummaryModel(record)) + } + return summaries, nil +} + +// GetOwnedSummary 查询指定用户的单个非敏感账号摘要。 +func (r *AccountSummaryRepository) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (accountapp.AccountSummary, error) { + // validationErr 表示摘要数据库适配器尚未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return accountapp.AccountSummary{}, validationErr + } + // record、queryErr 保存数据库摘要行及查询错误。 + record, queryErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID) + if queryErr != nil { + return accountapp.AccountSummary{}, normalizeAccountSummaryError(queryErr) + } + return accountSummaryModel(record), nil +} + +// ExistsOwned 判断账号是否属于指定用户,仅返回非敏感存在性结论。 +func (r *AccountSummaryRepository) ExistsOwned(ctx context.Context, userID int64, accountID string) (bool, error) { + // validationErr 表示摘要数据库适配器尚未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return false, validationErr + } + return r.store.Cookies.ExistsOwned(ctx, userID, accountID) +} + +// GetOwnerID 查询指定账号所属用户标识,不读取 Cookie、密码或 metadata。 +func (r *AccountSummaryRepository) GetOwnerID(ctx context.Context, accountID string) (int64, error) { + // validationErr 表示摘要数据库适配器尚未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return 0, validationErr + } + // ownerID、queryErr 保存数据库返回的账号所有者及查询错误。 + ownerID, queryErr := r.store.Cookies.GetOwnerID(ctx, accountID) + return ownerID, normalizeAccountSummaryError(queryErr) +} + +// StatusOwned 查询账号启用状态,并在状态读取前按用户复核账号归属。 +func (r *AccountSummaryRepository) StatusOwned(ctx context.Context, userID int64, accountID string) (bool, error) { + // validationErr 表示摘要数据库适配器尚未完成装配。 + validationErr := r.validateCookies() + if validationErr != nil { + return false, validationErr + } + // _, ownershipErr 丢弃摘要内容,只保留状态查询前的归属结论。 + if _, ownershipErr := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID); ownershipErr != nil { + return false, normalizeAccountSummaryError(ownershipErr) + } + // enabled、statusErr 保存数据库返回的状态及查询错误。 + enabled, statusErr := r.store.Cookies.Status(ctx, accountID) + return enabled, normalizeAccountSummaryError(statusErr) +} + +// ListAdminSummaries 查询管理员账号摘要并补充启用状态,不读取凭证字段。 +func (r *AccountSummaryRepository) ListAdminSummaries(ctx context.Context) ([]accountapp.AdminAccountSummary, error) { + if r == nil || r.store == nil || r.store.Admin == nil || r.store.Cookies == nil { + return nil, errors.New("管理员账号摘要数据库适配器未初始化") + } + // records、queryErr 保存管理员账号摘要行及查询错误。 + records, queryErr := r.store.Admin.ListCookies(ctx) + if queryErr != nil { + return nil, queryErr + } + // summaries 保存管理员端所需的非敏感账号摘要。 + summaries := make([]accountapp.AdminAccountSummary, 0, len(records)) + // record 表示当前待补充启用状态的管理员账号摘要。 + for _, record := range records { + // enabled 表示当前账号的启用状态;数据库故障按停用处理以保持既有响应语义。 + enabled := r.store.Cookies.GetStatus(ctx, record.ID) + summaries = append(summaries, accountapp.AdminAccountSummary{ + ID: record.ID, UserID: record.UserID, Remark: record.Remark, + CreatedAt: record.CreatedAt, Owner: record.Owner, Enabled: enabled, + }) + } + return summaries, nil +} + +// validateCookies 检查账号摘要适配器是否拥有必要的数据库子仓储。 +func (r *AccountSummaryRepository) validateCookies() error { + if r == nil || r.store == nil || r.store.Cookies == nil { + return errors.New("账号摘要数据库适配器未初始化") + } + return nil +} + +// accountSummaryModel 将数据库摘要转换为不含敏感字段的应用模型。 +func accountSummaryModel(record db.CookieSummary) accountapp.AccountSummary { + return accountapp.AccountSummary{ + ID: record.ID, UserID: record.UserID, AutoConfirm: record.AutoConfirm, + Remark: record.Remark, PauseDuration: record.PauseDuration, PausedUntil: record.PausedUntil, + Username: record.Username, ShowBrowser: record.ShowBrowser, Nickname: record.Nickname, + AvatarURL: record.AvatarURL, LastRefreshAt: record.LastRefreshAt, LoginMethod: record.LoginMethod, + LastLoginAt: record.LastLoginAt, CreatedAt: record.CreatedAt, + } +} + +// normalizeAccountSummaryError 将数据库所有权错误转换为应用层稳定错误。 +func normalizeAccountSummaryError(err error) error { + if err == nil { + return nil + } + if errors.Is(err, db.ErrNotFound) { + return accountapp.ErrNotFound + } + if errors.Is(err, db.ErrForbidden) { + return accountapp.ErrForbidden + } + return err +} + +var _ accountapp.AccountSummaryRepository = (*AccountSummaryRepository)(nil) +var _ accountapp.AdminSummaryRepository = (*AccountSummaryRepository)(nil) diff --git a/internal/adapter/account_summary_test.go b/internal/adapter/account_summary_test.go new file mode 100644 index 0000000..7a5ef31 --- /dev/null +++ b/internal/adapter/account_summary_test.go @@ -0,0 +1,129 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + accountapp "xianyu-go/internal/application/account" +) + +// TestAccountSummaryRepositoryRejectsMissingStore 验证账号摘要适配器缺少数据库时所有入口均快速失败。 +func TestAccountSummaryRepositoryRejectsMissingStore(t *testing.T) { + // repository 是未装配数据库的账号摘要适配器。 + repository := NewAccountSummaryRepository(nil) + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // err 表示账号 ID 列表查询因缺少数据库依赖返回的装配错误。 + if _, err := repository.ListOwnedIDs(ctx, 1); err == nil { + t.Fatal("缺少数据库时 ListOwnedIDs 不应成功") + } + // err 表示账号摘要列表查询因缺少数据库依赖返回的装配错误。 + if _, err := repository.ListSummaries(ctx, 1); err == nil { + t.Fatal("缺少数据库时 ListSummaries 不应成功") + } + // err 表示单个账号摘要查询因缺少数据库依赖返回的装配错误。 + if _, err := repository.GetOwnedSummary(ctx, 1, "cid"); err == nil { + t.Fatal("缺少数据库时 GetOwnedSummary 不应成功") + } + // err 表示账号所有权查询因缺少数据库依赖返回的装配错误。 + if _, err := repository.ExistsOwned(ctx, 1, "cid"); err == nil { + t.Fatal("缺少数据库时 ExistsOwned 不应成功") + } + // err 表示账号所有者查询因缺少数据库依赖返回的装配错误。 + if _, err := repository.GetOwnerID(ctx, "cid"); err == nil { + t.Fatal("缺少数据库时 GetOwnerID 不应成功") + } + // err 表示账号启用状态查询因缺少数据库依赖返回的装配错误。 + if _, err := repository.StatusOwned(ctx, 1, "cid"); err == nil { + t.Fatal("缺少数据库时 StatusOwned 不应成功") + } + // err 表示管理员账号摘要查询因缺少数据库依赖返回的装配错误。 + if _, err := repository.ListAdminSummaries(ctx); err == nil { + t.Fatal("缺少数据库时 ListAdminSummaries 不应成功") + } +} + +// TestAccountSummaryRepositoryMapsNonSensitiveQueries 验证真实 SQLite 下摘要、所有权、状态和管理员列表的映射。 +func TestAccountSummaryRepositoryMapsNonSensitiveQueries(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的账号摘要适配器。 + repository := NewAccountSummaryRepository(store) + // ctx 是本测试共用的非取消数据库上下文。 + ctx := context.Background() + // ids、idsErr 保存账号 ID 列表及查询错误。 + ids, idsErr := repository.ListOwnedIDs(ctx, 1) + if idsErr != nil || len(ids) != 1 || ids[0] != "cid" { + t.Fatalf("账号 ID 列表异常 ids=%v err=%v", ids, idsErr) + } + // summaries、summariesErr 保存账号摘要列表及查询错误。 + summaries, summariesErr := repository.ListSummaries(ctx, 1) + if summariesErr != nil || len(summaries) != 1 || summaries[0].ID != "cid" { + t.Fatalf("账号摘要异常 summaries=%+v err=%v", summaries, summariesErr) + } + // summary、summaryErr 保存单个账号摘要及查询错误。 + summary, summaryErr := repository.GetOwnedSummary(ctx, 1, "cid") + if summaryErr != nil || summary.ID != "cid" || summary.UserID != 1 { + t.Fatalf("单个摘要异常 summary=%+v err=%v", summary, summaryErr) + } + // owned、ownedErr 保存本人账号的所有权结论。 + owned, ownedErr := repository.ExistsOwned(ctx, 1, "cid") + if ownedErr != nil || !owned { + t.Fatalf("本人所有权异常 owned=%v err=%v", owned, ownedErr) + } + // ownerID、ownerErr 保存账号所有者查询结果。 + ownerID, ownerErr := repository.GetOwnerID(ctx, "cid") + if ownerErr != nil || ownerID != 1 { + t.Fatalf("账号所有者异常 ownerID=%d err=%v", ownerID, ownerErr) + } + // enabled、statusErr 保存账号启用状态及查询错误。 + enabled, statusErr := repository.StatusOwned(ctx, 1, "cid") + if statusErr != nil || !enabled { + t.Fatalf("账号状态异常 enabled=%v err=%v", enabled, statusErr) + } + // adminSummaries、adminErr 保存管理员账号摘要及查询错误。 + adminSummaries, adminErr := repository.ListAdminSummaries(ctx) + if adminErr != nil || len(adminSummaries) != 1 || adminSummaries[0].ID != "cid" || !adminSummaries[0].Enabled { + t.Fatalf("管理员摘要异常 summaries=%+v err=%v", adminSummaries, adminErr) + } +} + +// TestAccountSummaryRepositoryMapsOwnershipAndInfrastructureErrors 验证越权、缺失账号和数据库故障不会返回伪成功。 +func TestAccountSummaryRepositoryMapsOwnershipAndInfrastructureErrors(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的账号摘要适配器。 + repository := NewAccountSummaryRepository(store) + // ctx 是本测试共用的非取消数据库上下文。 + ctx := context.Background() + // _, otherErr 保存第二个用户创建错误;用户主键随后从摘要查询得到。 + _, otherErr := store.Users.Create(ctx, "other", "other@example.com", "pw") + if otherErr != nil { + t.Fatalf("创建第二用户失败: %v", otherErr) + } + // other、otherLookupErr 保存第二个用户及读取错误。 + other, otherLookupErr := store.Users.GetByUsername(ctx, "other") + if otherLookupErr != nil { + t.Fatalf("读取第二用户失败: %v", otherLookupErr) + } + // wrongOwned、wrongOwnedErr 保存跨用户所有权查询结果。 + wrongOwned, wrongOwnedErr := repository.ExistsOwned(ctx, other.ID, "cid") + if wrongOwnedErr != nil || wrongOwned { + t.Fatalf("跨用户所有权异常 owned=%v err=%v", wrongOwned, wrongOwnedErr) + } + // _, missingErr 验证缺失账号被转换为应用层稳定错误。 + if _, missingErr := repository.GetOwnedSummary(ctx, 1, "missing"); !errors.Is(missingErr, accountapp.ErrNotFound) { + t.Fatalf("缺失账号错误=%v,期望=%v", missingErr, accountapp.ErrNotFound) + } + // closeErr 保存关闭数据库连接的资源释放错误。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // _, queryErr 验证数据库关闭后适配器透传基础设施错误。 + if _, queryErr := repository.ListSummaries(ctx, 1); queryErr == nil { + t.Fatal("数据库关闭后不应伪装摘要读取成功") + } +} diff --git a/internal/adapter/account_tasks.go b/internal/adapter/account_tasks.go new file mode 100644 index 0000000..a64e167 --- /dev/null +++ b/internal/adapter/account_tasks.go @@ -0,0 +1,113 @@ +package adapter + +import ( + "context" + "errors" + + automationapp "xianyu-go/internal/application/automation" + "xianyu-go/internal/automation" + "xianyu-go/internal/db" +) + +// AccountTaskRepository 将账号任务数据库模型适配为应用层模型。 +type AccountTaskRepository struct { + // store 保存账号任务持久化入口。 + store *db.Store +} + +// NewAccountTaskRepository 构造账号任务仓储适配器。 +func NewAccountTaskRepository(store *db.Store) *AccountTaskRepository { + return &AccountTaskRepository{store: store} +} + +// GetSettings 读取账号任务设置并移除数据库模型依赖。 +func (r *AccountTaskRepository) GetSettings(ctx context.Context, accountID string) (automationapp.AccountTaskSettings, error) { + // validateErr 表示适配器缺少数据库任务仓储时的装配错误。 + if validateErr := r.validate(); validateErr != nil { + return automationapp.AccountTaskSettings{}, validateErr + } + // settings、err 保存数据库设置及读取错误。 + settings, err := r.store.AccountTasks.Get(ctx, accountID) + return accountTaskSettingsModel(settings), err +} + +// SaveSettings 将应用层账号任务设置写入数据库。 +func (r *AccountTaskRepository) SaveSettings(ctx context.Context, settings automationapp.AccountTaskSettings) error { + // validateErr 表示适配器缺少数据库任务仓储时的装配错误。 + if validateErr := r.validate(); validateErr != nil { + return validateErr + } + return r.store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{ + CookieID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent, + AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime, + LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt, + }) +} + +// ListRuns 读取账号任务运行记录并转换为应用层模型。 +func (r *AccountTaskRepository) ListRuns(ctx context.Context, accountID string, limit int) ([]automationapp.AccountTaskRun, error) { + // validateErr 表示适配器缺少数据库任务仓储时的装配错误。 + if validateErr := r.validate(); validateErr != nil { + return nil, validateErr + } + // runs、err 保存数据库运行记录及读取错误。 + runs, err := r.store.AccountTasks.RecentRuns(ctx, accountID, limit) + if err != nil { + return nil, err + } + // result 保存转换后的应用层运行记录。 + result := make([]automationapp.AccountTaskRun, 0, len(runs)) + // run 是当前待转换的数据库运行记录。 + for _, run := range runs { + result = append(result, automationapp.AccountTaskRun{ + ID: run.ID, RunKey: run.RunKey, CookieID: run.CookieID, TaskType: run.TaskType, TargetID: run.TargetID, + RunDate: run.RunDate, Status: run.Status, SuccessCount: run.SuccessCount, FailedCount: run.FailedCount, + ErrorMessage: run.ErrorMessage, NextRetryAt: run.NextRetryAt, StartedAt: run.StartedAt, FinishedAt: run.FinishedAt, + }) + } + return result, nil +} + +// validate 检查账号任务数据库适配器是否具备必需的 Store 和子仓储。 +func (r *AccountTaskRepository) validate() error { + if r == nil || r.store == nil || r.store.AccountTasks == nil { + return errors.New("账号任务数据库适配器未初始化") + } + return nil +} + +// accountTaskSettingsModel 将数据库账号任务设置转换为应用模型。 +func accountTaskSettingsModel(settings db.AccountTaskSettings) automationapp.AccountTaskSettings { + return automationapp.AccountTaskSettings{ + CookieID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent, + AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime, + LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt, + } +} + +// AccountTaskRunner 将自动化中心的执行结果适配为应用层摘要。 +type AccountTaskRunner struct { + // center 执行账号评价和商品擦亮任务。 + center *automation.Center +} + +// NewAccountTaskRunner 构造账号任务执行适配器。 +func NewAccountTaskRunner(center *automation.Center) *AccountTaskRunner { + return &AccountTaskRunner{center: center} +} + +// RunAccountTask 执行任务并转换非敏感结果摘要。 +func (r *AccountTaskRunner) RunAccountTask(ctx context.Context, accountID, taskType string) (automationapp.TaskSummary, error) { + if r == nil || r.center == nil { + return automationapp.TaskSummary{}, automationapp.ErrUnavailable + } + // summary、err 保存自动化中心结果及执行错误。 + summary, err := r.center.RunAccountTask(ctx, accountID, taskType) + return automationapp.TaskSummary{ + TaskType: summary.TaskType, Found: summary.Found, Success: summary.Success, + Failed: summary.Failed, Skipped: summary.Skipped, Message: summary.Message, + }, err +} + +var _ automationapp.Repository = (*AccountTaskRepository)(nil) +var _ automationapp.Runner = (*AccountTaskRunner)(nil) diff --git a/internal/adapter/account_tasks_test.go b/internal/adapter/account_tasks_test.go new file mode 100644 index 0000000..d14692c --- /dev/null +++ b/internal/adapter/account_tasks_test.go @@ -0,0 +1,16 @@ +package adapter + +import ( + "context" + "testing" +) + +// TestAccountTaskRepositoryRejectsMissingStore 验证账号任务数据库适配器不会因缺少 Store 而 panic。 +func TestAccountTaskRepositoryRejectsMissingStore(t *testing.T) { + // repository 是未装配数据库的账号任务适配器。 + repository := NewAccountTaskRepository(nil) + // _, err 保存缺少数据库时的明确错误。 + if _, err := repository.GetSettings(context.Background(), "account-1"); err == nil { + t.Fatal("缺少 Store 时应返回错误") + } +} diff --git a/internal/adapter/admin_repository.go b/internal/adapter/admin_repository.go new file mode 100644 index 0000000..4012b3d --- /dev/null +++ b/internal/adapter/admin_repository.go @@ -0,0 +1,62 @@ +package adapter + +import ( + "context" + "errors" + + adminapp "xianyu-go/internal/application/admin" + "xianyu-go/internal/db" +) + +// AdminRepository 将管理员数据库查询转换为非敏感应用模型。 +type AdminRepository struct { + // store 保存管理员查询所需的数据库聚合入口,仅在适配器内部使用。 + store *db.Store +} + +// NewAdminRepository 构造管理员数据库适配器。 +func NewAdminRepository(store *db.Store) *AdminRepository { + return &AdminRepository{store: store} +} + +// ListUsers 查询用户摘要并丢弃密码及其他敏感字段。 +func (r *AdminRepository) ListUsers(ctx context.Context) ([]adminapp.UserSummary, error) { + if r == nil || r.store == nil || r.store.Admin == nil { + return nil, errors.New("管理员查询适配器未初始化") + } + // rows、err 保存数据库用户摘要行及查询错误。 + rows, err := r.store.Admin.ListUsers(ctx) + if err != nil { + return nil, err + } + // users 保存已脱敏的应用层用户摘要。 + users := make([]adminapp.UserSummary, 0, len(rows)) + // row 表示当前待转换的数据库用户摘要。 + for _, row := range rows { + users = append(users, adminapp.UserSummary{ID: row.ID, Username: row.Username, Email: row.Email, IsActive: row.IsActive, IsAdmin: row.IsAdmin, CreatedAt: row.CreatedAt, CookieCount: row.CookieCount}) + } + return users, nil +} + +// DeleteUser 删除指定用户及其关联账号。 +func (r *AdminRepository) DeleteUser(ctx context.Context, userID int64) error { + if r == nil || r.store == nil || r.store.Users == nil { + return errors.New("管理员删除适配器未初始化") + } + return r.store.Users.Delete(ctx, userID) +} + +// Stats 查询数据库聚合统计并转换为应用模型。 +func (r *AdminRepository) Stats(ctx context.Context) (adminapp.Stats, error) { + if r == nil || r.store == nil || r.store.Admin == nil { + return adminapp.Stats{}, errors.New("管理员统计适配器未初始化") + } + // stats、err 保存数据库聚合统计及查询错误。 + stats, err := r.store.Admin.Stats(ctx) + if err != nil { + return adminapp.Stats{}, err + } + return adminapp.Stats{TotalUsers: stats.TotalUsers, TotalCookies: stats.TotalCookies, ActiveCookies: stats.ActiveCookies, TotalCards: stats.TotalCards, TotalKeywords: stats.TotalKeywords, TotalOrders: stats.TotalOrders}, nil +} + +var _ adminapp.Repository = (*AdminRepository)(nil) diff --git a/internal/adapter/admin_repository_test.go b/internal/adapter/admin_repository_test.go new file mode 100644 index 0000000..8e01070 --- /dev/null +++ b/internal/adapter/admin_repository_test.go @@ -0,0 +1,46 @@ +package adapter + +import ( + "context" + "testing" +) + +// TestAdminRepositoryMapsUsersStatsAndDelete 验证管理员适配器只返回摘要并保留删除/统计语义。 +func TestAdminRepositoryMapsUsersStatsAndDelete(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 保存本测试共用的数据库操作上下文。 + ctx := context.Background() + // created、createErr 保存普通用户创建结果。 + created, createErr := store.Users.Create(ctx, "admin-repository-user", "admin-repository@example.com", "password") + if createErr != nil || !created { + t.Fatalf("创建管理员适配器测试用户失败 created=%v err=%v", created, createErr) + } + // repository 保存绑定 SQLite Store 的管理员适配器。 + repository := NewAdminRepository(store) + // users、usersErr 保存脱敏用户列表及错误。 + users, usersErr := repository.ListUsers(ctx) + if usersErr != nil || len(users) < 2 { + t.Fatalf("用户列表查询异常 len=%d err=%v", len(users), usersErr) + } + // stats、statsErr 保存管理员统计及错误。 + stats, statsErr := repository.Stats(ctx) + if statsErr != nil || stats.TotalUsers < 2 { + t.Fatalf("管理员统计异常 stats=%+v err=%v", stats, statsErr) + } + // targetID 保存待删除用户的数据库标识。 + target, targetErr := store.Users.GetByUsername(ctx, "admin-repository-user") + if targetErr != nil || target == nil { + t.Fatalf("查询待删除用户失败 target=%v err=%v", target, targetErr) + } + // deleteErr 保存管理员删除操作的错误。 + if deleteErr := repository.DeleteUser(ctx, target.ID); deleteErr != nil { + t.Fatalf("删除用户失败: %v", deleteErr) + } + // missingErr 保存缺失适配器依赖的错误。 + missingErr := (*AdminRepository)(nil).DeleteUser(ctx, target.ID) + if missingErr == nil { + t.Fatal("空管理员适配器应拒绝删除") + } +} diff --git a/internal/adapter/ai_model_client.go b/internal/adapter/ai_model_client.go new file mode 100644 index 0000000..f86cfd1 --- /dev/null +++ b/internal/adapter/ai_model_client.go @@ -0,0 +1,163 @@ +package adapter + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "xianyu-go/internal/netguard" +) + +// MaxAIModelsResponseBytes 限制远端模型目录响应大小,避免管理员配置的端点耗尽内存。 +const MaxAIModelsResponseBytes = 4 << 20 + +// AIModelClient 通过管理员明确配置的端点读取 AI 模型目录。 +type AIModelClient struct { + // newHTTPClient 允许测试替换端点客户端,同时生产默认使用受信任端点策略。 + newHTTPClient func(baseURL string) (*http.Client, error) +} + +// NewAIModelClient 构造 AI 模型目录适配器。 +func NewAIModelClient() *AIModelClient { + // client 保存生产环境使用的模型目录客户端。 + client := &AIModelClient{newHTTPClient: func(baseURL string) (*http.Client, error) { + return netguard.TrustedEndpointHTTPClient(baseURL, 20*time.Second) + }} + return client +} + +// Fetch 请求模型目录并只返回模型名称,不返回 API 密钥或原始响应内容。 +func (c *AIModelClient) Fetch(ctx context.Context, baseURL, apiKey string) ([]string, error) { + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + if baseURL == "" { + return nil, fmt.Errorf("AI API 地址为空") + } + if c == nil || c.newHTTPClient == nil { + return nil, fmt.Errorf("AI 模型客户端未初始化") + } + // req 是带有请求上下文的模型目录请求;API 密钥只存在于请求头。 + req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/models", nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + if strings.TrimSpace(apiKey) != "" { + req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(apiKey)) + } + // client 是经过地址校验的出站客户端。 + client, err := c.newHTTPClient(baseURL) + if err != nil { + return nil, fmt.Errorf("AI API 地址无效: %w", err) + } + // response 是远端模型目录 HTTP 响应。 + response, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("读取模型失败: %w", err) + } + defer response.Body.Close() + // raw 是限制大小后读取的响应内容。 + raw, err := ReadAIModelsBody(response.Body) + if err != nil { + return nil, err + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + return nil, fmt.Errorf("读取模型失败: HTTP %d %s", response.StatusCode, truncateAIModelBody(string(raw), 180)) + } + // models、err 保存解析后的模型名称及解析错误。 + models, err := ParseAIModels(raw) + if err != nil { + return nil, err + } + if len(models) == 0 { + return nil, fmt.Errorf("模型列表为空") + } + return models, nil +} + +// ReadAIModelsBody 读取并限制远端模型目录响应。 +func ReadAIModelsBody(reader io.Reader) ([]byte, error) { + // raw 是限制大小后读取的响应内容。 + raw, err := io.ReadAll(io.LimitReader(reader, MaxAIModelsResponseBytes+1)) + if err != nil { + return nil, err + } + if len(raw) > MaxAIModelsResponseBytes { + return nil, fmt.Errorf("模型列表响应超过 %d MiB", MaxAIModelsResponseBytes>>20) + } + return raw, nil +} + +// ParseAIModels 从兼容 OpenAI 的多种响应形状提取去重模型名称。 +func ParseAIModels(raw []byte) ([]string, error) { + // payload 是远端模型目录的通用 JSON 载荷。 + var payload any + // err 表示远端模型目录 JSON 解析错误。 + if err := json.Unmarshal(raw, &payload); err != nil { + return nil, fmt.Errorf("解析模型列表失败: %w", err) + } + // seen 保存已返回的模型名称,避免重复项污染下拉列表。 + seen := make(map[string]bool) + // result 保存按远端出现顺序排列的模型名称。 + var result []string + // addModel 将非空模型名称加入结果并去重。 + addModel := func(value string) { + value = strings.TrimSpace(value) + if value == "" || seen[value] { + return + } + seen[value] = true + result = append(result, value) + } + // walk 递归解析 data、models、对象和字符串等兼容响应结构。 + var walk func(any) + walk = func(value any) { + // typed 是当前 JSON 节点的具体类型。 + switch typed := value.(type) { + case []any: + // item 是模型目录数组中的当前元素。 + for _, item := range typed { + walk(item) + } + case map[string]any: + // id、ok 保存优先使用的模型标识及其类型判断结果。 + if id, ok := typed["id"].(string); ok && id != "" { + addModel(id) + } else if // name、ok 保存模型名称回退值及其类型判断结果。 + name, ok := typed["name"].(string); ok && name != "" { + addModel(name) + } + case string: + addModel(typed) + } + } + // root、ok 保存顶层对象及对象类型判断结果。 + if root, ok := payload.(map[string]any); ok { + // data、ok 保存兼容 OpenAI 的 data 字段及存在性判断结果。 + if data, ok := root["data"]; ok { + walk(data) + } else if // models、ok 保存兼容服务的 models 字段及存在性判断结果。 + models, ok := root["models"]; ok { + walk(models) + } + } else { + walk(payload) + } + return result, nil +} + +// truncateAIModelBody 截取错误响应,避免把超大远端正文写入日志或 HTTP 错误。 +func truncateAIModelBody(value string, limit int) string { + value = strings.TrimSpace(value) + if len(value) <= limit { + return value + } + return value[:limit] +} + +var _ interface { + Fetch(context.Context, string, string) ([]string, error) +} = (*AIModelClient)(nil) diff --git a/internal/adapter/ai_model_client_test.go b/internal/adapter/ai_model_client_test.go new file mode 100644 index 0000000..0aa4d66 --- /dev/null +++ b/internal/adapter/ai_model_client_test.go @@ -0,0 +1,42 @@ +package adapter + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestParseAIModelsSupportsOpenAIShapes 验证模型目录解析兼容 data、models 和名称回退结构。 +func TestParseAIModelsSupportsOpenAIShapes(t *testing.T) { + // models、err 保存模型目录解析结果和错误。 + models, err := ParseAIModels([]byte(`{"data":[{"id":"qwen-plus"},{"name":"fallback"},{"id":"qwen-plus"}]}`)) + if err != nil || len(models) != 2 || models[0] != "qwen-plus" || models[1] != "fallback" { + t.Fatalf("models=%v err=%v", models, err) + } +} + +// TestAIModelClientFetchUsesHeaderAndBounds 验证模型请求只把密钥放入请求头并拒绝空模型列表。 +func TestAIModelClientFetchUsesHeaderAndBounds(t *testing.T) { + // server 是返回固定模型目录的本地测试端点。 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.Header.Get("Authorization") != "Bearer test-secret" { + t.Error("authorization header was not forwarded") + } + _, _ = writer.Write([]byte(`{"models":["qwen-plus"]}`)) + })) + defer server.Close() + // client 是替换了受信任端点 HTTP 工厂的测试客户端。 + client := &AIModelClient{newHTTPClient: func(string) (*http.Client, error) { return &http.Client{}, nil }} + // models、err 保存模型请求结果和错误。 + models, err := client.Fetch(context.Background(), server.URL, "test-secret") + if err != nil || len(models) != 1 || models[0] != "qwen-plus" { + t.Fatalf("models=%v err=%v", models, err) + } + // oversizedErr 表示超大模型响应被拒绝的错误。 + _, oversizedErr := ReadAIModelsBody(strings.NewReader(strings.Repeat("x", MaxAIModelsResponseBytes+1))) + if oversizedErr == nil { + t.Fatal("oversized model response should fail") + } +} diff --git a/internal/adapter/analytics_repository.go b/internal/adapter/analytics_repository.go new file mode 100644 index 0000000..ff4c3e3 --- /dev/null +++ b/internal/adapter/analytics_repository.go @@ -0,0 +1,319 @@ +package adapter + +import ( + "context" + "database/sql" + "strings" + + analyticsapp "xianyu-go/internal/application/analytics" + "xianyu-go/internal/db" +) + +// AnalyticsRepository 将 Store 的只读查询能力适配为订单分析应用 Port。 +type AnalyticsRepository struct { + // store 保存数据库聚合入口,仅由该基础设施适配器访问。 + store *db.Store +} + +// NewAnalyticsRepository 构造订单分析查询适配器。 +func NewAnalyticsRepository(store *db.Store) *AnalyticsRepository { + return &AnalyticsRepository{store: store} +} + +// DashboardStats 返回用户范围内的仪表盘计数,不读取账号凭证字段。 +func (r *AnalyticsRepository) DashboardStats(ctx context.Context, userID int64) (analyticsapp.DashboardStats, error) { + // stats 保存基础统计结果。 + stats := analyticsapp.DashboardStats{} + // queries 保存用户范围内的固定计数查询及其目标字段。 + queries := []struct { + // query 是当前统计项的 SQL。 + query string + // target 是统计项写入结果的字段名称。 + target string + }{ + {query: `SELECT COUNT(*) FROM cookies WHERE user_id=?`, target: "cookies"}, + {query: `SELECT COUNT(*) FROM cards WHERE user_id=?`, target: "cards"}, + {query: `SELECT COUNT(*) FROM keywords k WHERE EXISTS (SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`, target: "keywords"}, + {query: `SELECT COUNT(*) FROM orders o WHERE o.deleted_at IS NULL AND EXISTS (SELECT 1 FROM cookies c WHERE c.id=o.cookie_id AND c.user_id=?)`, target: "orders"}, + } + // item 是当前遍历的仪表盘统计项。 + for _, item := range queries { + // count 是当前统计项的数据库结果。 + var count int64 + if // err 是当前统计项查询错误。 + err := r.store.Analytics.QueryRowContext(ctx, item.query, userID).Scan(&count); err != nil { + return analyticsapp.DashboardStats{}, err + } + switch item.target { + case "cookies": + stats.TotalCookies = count + case "cards": + stats.TotalCards = count + case "keywords": + stats.TotalKeywords = count + case "orders": + stats.TotalOrders = count + } + } + // activeCookies 是没有明确禁用记录的账号数量。 + var activeCookies int64 + if // err 是活跃账号统计查询错误。 + err := r.store.Analytics.QueryRowContext(ctx, ` + SELECT COUNT(*) FROM cookies c WHERE c.user_id=? + AND NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0) + `, userID).Scan(&activeCookies); err != nil { + return analyticsapp.DashboardStats{}, err + } + stats.ActiveCookies = activeCookies + return stats, nil +} + +// AvailableCardStock 计算启用数据卡密组中的非空卡密行数,不向应用层传递卡密内容。 +func (r *AnalyticsRepository) AvailableCardStock(ctx context.Context, userID int64) (int64, error) { + // rows 是用户数据卡密组的最小查询结果。 + // rows、err 是用户数据卡密组查询结果及错误。 + rows, err := r.store.DB.QueryContext(ctx, `SELECT enabled, type, data_content FROM cards WHERE user_id=?`, userID) + if err != nil { + return 0, err + } + defer rows.Close() + // stock 是可用卡密行数。 + var stock int64 + for rows.Next() { + // enabled 是当前卡密组是否启用的可空数据库字段。 + var enabled sql.NullInt64 + // cardType 是当前卡密组的业务类型。 + var cardType sql.NullString + // dataContent 是当前数据卡密组的换行分隔内容。 + var dataContent sql.NullString + if // err 是当前卡密组读取错误。 + err := rows.Scan(&enabled, &cardType, &dataContent); err != nil { + return 0, err + } + if !enabled.Valid || enabled.Int64 == 0 || !cardType.Valid || cardType.String != "data" { + continue + } + // line 是数据卡密组中的单行卡密。 + for _, line := range strings.Split(strings.ReplaceAll(dataContent.String, "\r\n", "\n"), "\n") { + if strings.TrimSpace(line) != "" { + stock++ + } + } + } + return stock, rows.Err() +} + +// QueryRevenue 返回订单收益汇总。 +func (r *AnalyticsRepository) QueryRevenue(ctx context.Context, filter analyticsapp.Filter) (analyticsapp.RevenueStats, error) { + // where、args、clean 和 amountFilter 是当前方言的订单范围条件。 + where, args, clean, amountFilter := r.orderScope(filter, "amount") + // stats 是数据库返回的收益聚合值。 + var stats analyticsapp.RevenueStats + // err 是收益汇总查询错误。 + err := r.store.Analytics.QueryRowContext(ctx, ` + SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0), + COALESCE(AVG(`+clean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id) + FROM orders `+where+amountFilter, args...).Scan( + &stats.TotalOrders, &stats.TotalAmount, &stats.AvgAmount, &stats.UniqueBuyers, &stats.UniqueItems) + return stats, err +} + +// QueryDaily 返回按订单读取的日期聚合原始记录。 +func (r *AnalyticsRepository) QueryDaily(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.DailyRecord, error) { + // where、args、clean 和 amountFilter 是当前方言的订单范围条件。 + where, args, _, amountFilter := r.orderScope(filter, "amount") + // rows、err 是日期聚合查询结果及错误。 + rows, err := r.store.Analytics.QueryContext(ctx, `SELECT order_id,amount,created_at FROM orders `+where+amountFilter, args...) + if err != nil { + return nil, err + } + defer rows.Close() + // records 是订单日期聚合原始记录。 + records := make([]analyticsapp.DailyRecord, 0) + for rows.Next() { + // record 是当前订单的原始统计字段。 + var record analyticsapp.DailyRecord + if // err 是当前日期记录读取错误。 + err := rows.Scan(&record.OrderID, &record.Amount, &record.CreatedAt); err != nil { + return nil, err + } + records = append(records, record) + } + return records, rows.Err() +} + +// QueryStatus 返回按原始订单状态聚合的结果。 +func (r *AnalyticsRepository) QueryStatus(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.StatusRecord, error) { + // where、args、clean 和 amountFilter 是当前方言的订单范围条件。 + where, args, clean, amountFilter := r.orderScope(filter, "amount") + // rows、err 是状态聚合查询结果及错误。 + rows, err := r.store.Analytics.QueryContext(ctx, ` + SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0) + FROM orders `+where+amountFilter+` + GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + // records 是数据库按原始状态返回的聚合记录。 + records := make([]analyticsapp.StatusRecord, 0) + for rows.Next() { + // record 是当前状态的聚合字段。 + var record analyticsapp.StatusRecord + if // err 是当前状态记录读取错误。 + err := rows.Scan(&record.Status, &record.Count, &record.Amount); err != nil { + return nil, err + } + records = append(records, record) + } + return records, rows.Err() +} + +// QueryCity 返回按收货城市聚合的结果。 +func (r *AnalyticsRepository) QueryCity(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.CityRecord, error) { + // where、args、clean 和 amountFilter 是当前方言的订单范围条件。 + where, args, clean, amountFilter := r.orderScope(filter, "amount") + // rows、err 是城市聚合查询结果及错误。 + rows, err := r.store.Analytics.QueryContext(ctx, ` + SELECT receiver_city, COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0) + FROM orders `+where+amountFilter+` + AND receiver_city IS NOT NULL AND receiver_city != '' + GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + // records 是数据库按城市返回的聚合记录。 + records := make([]analyticsapp.CityRecord, 0) + for rows.Next() { + // record 是当前城市的聚合字段。 + var record analyticsapp.CityRecord + if // err 是当前城市记录读取错误。 + err := rows.Scan(&record.City, &record.Count, &record.Amount); err != nil { + return nil, err + } + records = append(records, record) + } + return records, rows.Err() +} + +// QueryItem 返回按商品标识聚合的结果。 +func (r *AnalyticsRepository) QueryItem(ctx context.Context, filter analyticsapp.Filter) ([]analyticsapp.ItemRecord, error) { + // where、args、clean 和 amountFilter 是当前方言的订单范围条件。 + where, args, clean, amountFilter := r.orderScope(filter, "amount") + // rows、err 是商品聚合查询结果及错误。 + rows, err := r.store.Analytics.QueryContext(ctx, ` + SELECT item_id, COUNT(DISTINCT order_id), COALESCE(SUM(`+clean+`),0), COALESCE(AVG(`+clean+`),0) + FROM orders `+where+amountFilter+` + AND item_id IS NOT NULL AND item_id != '' + GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + // records 是数据库按商品返回的聚合记录。 + records := make([]analyticsapp.ItemRecord, 0) + for rows.Next() { + // record 是当前商品的聚合字段。 + var record analyticsapp.ItemRecord + if // err 是当前商品记录读取错误。 + err := rows.Scan(&record.ItemID, &record.Count, &record.TotalAmount, &record.AvgAmount); err != nil { + return nil, err + } + records = append(records, record) + } + return records, rows.Err() +} + +// CountValidOrders 返回有效订单总数。 +func (r *AnalyticsRepository) CountValidOrders(ctx context.Context, filter analyticsapp.Filter) (int, error) { + // where、args、clean 和 amountFilter 是当前方言的订单范围条件。 + where, args, _, amountFilter := r.orderScope(filter, "orders.amount") + // total 是数据库返回的有效订单数量。 + var total int + // err 是有效订单总数查询错误。 + err := r.store.Analytics.QueryRowContext(ctx, `SELECT COUNT(*) FROM orders `+where+amountFilter, args...).Scan(&total) + return total, err +} + +// ListValidOrders 返回有效订单分页明细。 +func (r *AnalyticsRepository) ListValidOrders(ctx context.Context, filter analyticsapp.Filter, limit, offset int) ([]analyticsapp.ValidOrderRecord, error) { + // where、args、clean 和 amountFilter 是当前方言的订单范围条件。 + where, args, _, amountFilter := r.orderScope(filter, "orders.amount") + args = append(args, limit, offset) + // rows、err 是有效订单分页查询结果及错误。 + rows, err := r.store.Analytics.QueryContext(ctx, ` + SELECT orders.order_id, COALESCE(orders.item_id,''), COALESCE(item_info.item_title,''), + COALESCE(item_info.item_detail,''), COALESCE(orders.buyer_id,''), COALESCE(orders.quantity,'1'), + orders.amount, COALESCE(orders.order_status,'unknown'), COALESCE(orders.cookie_id,''), orders.created_at + FROM orders LEFT JOIN item_info ON item_info.cookie_id=orders.cookie_id AND item_info.item_id=orders.item_id + `+where+amountFilter+` ORDER BY orders.created_at DESC LIMIT ? OFFSET ?`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + // records 是当前分页的有效订单字段。 + records := make([]analyticsapp.ValidOrderRecord, 0) + for rows.Next() { + // record 是当前订单的明细字段。 + var record analyticsapp.ValidOrderRecord + if // err 是当前有效订单记录读取错误。 + err := rows.Scan(&record.OrderID, &record.ItemID, &record.ItemTitle, &record.ItemDetail, &record.BuyerID, &record.Quantity, &record.Amount, &record.Status, &record.CookieID, &record.CreatedAt); err != nil { + return nil, err + } + records = append(records, record) + } + return records, rows.Err() +} + +// orderScope 构造订单查询的用户、日期、状态和金额过滤条件。 +func (r *AnalyticsRepository) orderScope(filter analyticsapp.Filter, amountColumn string) (string, []any, string, string) { + // conditions 保存 SQL WHERE 条件片段。 + conditions := []string{"orders.deleted_at IS NULL"} + // args 保存条件对应的参数值。 + args := make([]any, 0, len(filter.Statuses)+3) + if filter.StartAt != "" { + conditions = append(conditions, "orders.created_at >= ?") + args = append(args, filter.StartAt) + } + if filter.EndBefore != "" { + conditions = append(conditions, "orders.created_at < ?") + args = append(args, filter.EndBefore) + } + if filter.UserID != 0 { + conditions = append(conditions, "EXISTS (SELECT 1 FROM cookies WHERE cookies.id = orders.cookie_id AND cookies.user_id = ?)") + args = append(args, filter.UserID) + } + if len(filter.Statuses) > 0 { + // placeholders 是状态条件需要的占位符列表。 + placeholders := make([]string, len(filter.Statuses)) + // index 是当前状态占位符的序号。 + for index := range filter.Statuses { + placeholders[index] = "?" + args = append(args, filter.Statuses[index]) + } + conditions = append(conditions, "orders.order_status IN ("+strings.Join(placeholders, ",")+")") + } + // where 是带 WHERE 前缀和尾随空格的条件文本。 + where := "WHERE " + strings.Join(conditions, " AND ") + " " + // clean 是当前数据库方言清洗金额文本的表达式。 + clean := amountExpression(r.store.Dialect, amountColumn) + return where, args, clean, " AND " + clean + " IS NOT NULL" +} + +// amountExpression 返回当前数据库方言的安全金额表达式。 +func amountExpression(dialect db.Dialect, column string) string { + // clean 是移除货币符号和千分位后的金额文本表达式。 + clean := `TRIM(REPLACE(REPLACE(` + column + `, '¥', ''), ',', ''))` + switch dialect { + case db.DialectPostgres: + return `CASE WHEN ` + clean + ` ~ '^[0-9]+([.][0-9]+)?$' THEN CAST(` + clean + ` AS DOUBLE PRECISION) END` + case db.DialectMySQL: + return `CASE WHEN ` + clean + ` REGEXP '^[0-9]+([.][0-9]+)?$' THEN CAST(` + clean + ` AS DOUBLE) END` + default: + return `CASE WHEN ` + clean + ` GLOB '[0-9]*' AND ` + clean + ` NOT GLOB '*[^0-9.]*' AND ` + clean + ` NOT GLOB '*.*.*' AND ` + clean + ` NOT LIKE '%.' THEN CAST(` + clean + ` AS REAL) END` + } +} + +// 确保基础设施适配器实现完整的订单分析应用 Port。 +var _ analyticsapp.Repository = (*AnalyticsRepository)(nil) diff --git a/internal/adapter/authentication_repository.go b/internal/adapter/authentication_repository.go new file mode 100644 index 0000000..38ef086 --- /dev/null +++ b/internal/adapter/authentication_repository.go @@ -0,0 +1,151 @@ +package adapter + +import ( + "context" + "errors" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" +) + +// AuthenticationRepository 将用户密码与会话数据库操作适配为账号认证应用端口。 +type AuthenticationRepository struct { + // store 保存数据库聚合入口;用户密码只在适配器调用期间参与校验或写入。 + store *db.Store +} + +// NewAuthenticationRepository 构造认证数据库适配器。 +func NewAuthenticationRepository(store *db.Store) *AuthenticationRepository { + return &AuthenticationRepository{store: store} +} + +// IsSystemInitialized 查询数据库中是否已经存在管理员账号。 +func (r *AuthenticationRepository) IsSystemInitialized(ctx context.Context) (bool, error) { + // validationErr 表示认证用户仓储是否已经完成装配。 + validationErr := r.validateUsers() + if validationErr != nil { + return false, validationErr + } + return r.store.Users.IsSystemInitialized(ctx) +} + +// InitializeAdmin 创建或重置管理员账号,保持命令行初始化入口的兼容语义。 +func (r *AuthenticationRepository) InitializeAdmin(ctx context.Context, email, password string) (bool, error) { + // validationErr 表示认证用户仓储是否已经完成装配。 + validationErr := r.validateUsers() + if validationErr != nil { + return false, validationErr + } + // existing、lookupErr 保存现有管理员和查询错误;初始化调用方会在外层先做未初始化检查。 + existing, lookupErr := r.store.Users.GetAdmin(ctx) + if lookupErr != nil && !errors.Is(lookupErr, db.ErrNotFound) { + return false, lookupErr + } + if existing != nil { + // updated、updateErr 保存既有管理员密码更新结果。 + updated, updateErr := r.store.Users.UpdatePassword(ctx, existing.Username, password) + if updateErr != nil { + return false, updateErr + } + if !updated { + return false, errors.New("管理员存在但密码未更新") + } + return false, r.store.Users.SetAdmin(ctx, existing.Username) + } + // created、createErr 保存新管理员创建结果。 + created, createErr := r.store.Users.Create(ctx, "admin", email, password) + if createErr != nil { + return false, createErr + } + if !created { + return false, errors.New("创建管理员失败:用户名或邮箱可能已存在") + } + return true, r.store.Users.SetAdmin(ctx, "admin") +} + +// UsernameByEmail 按邮箱取得登录用户名,不向应用层暴露密码哈希等完整用户字段。 +func (r *AuthenticationRepository) UsernameByEmail(ctx context.Context, email string) (string, error) { + // validationErr 表示认证用户仓储是否已经完成装配。 + validationErr := r.validateUsers() + if validationErr != nil { + return "", validationErr + } + // user、lookupErr 保存邮箱查询结果;仅提取登录用户名后立即丢弃数据库模型。 + user, lookupErr := r.store.Users.GetByEmail(ctx, email) + if lookupErr != nil { + return "", lookupErr + } + if user == nil { + return "", db.ErrNotFound + } + return user.Username, nil +} + +// VerifyPassword 校验密码并转换为不含敏感字段的应用身份。 +func (r *AuthenticationRepository) VerifyPassword(ctx context.Context, username, password string) (accountapp.AuthUser, bool, error) { + // validationErr 表示认证用户仓储是否已经完成装配。 + validationErr := r.validateUsers() + if validationErr != nil { + return accountapp.AuthUser{}, false, validationErr + } + // user、matched、verifyErr 保存数据库密码校验结果;密码哈希不跨出本方法。 + user, matched, verifyErr := r.store.Users.VerifyAndUpgrade(ctx, username, password) + if verifyErr != nil { + if errors.Is(verifyErr, db.ErrPasswordMismatch) { + return accountapp.AuthUser{}, false, accountapp.ErrPasswordMismatch + } + return accountapp.AuthUser{}, false, verifyErr + } + if !matched || user == nil { + return accountapp.AuthUser{}, false, nil + } + return accountapp.AuthUser{ID: user.ID, Username: user.Username, IsAdmin: user.IsAdmin}, true, nil +} + +// UpdatePassword 更新密码并撤销该用户全部旧会话。 +func (r *AuthenticationRepository) UpdatePassword(ctx context.Context, username, password string) (bool, error) { + // validationErr 表示认证用户仓储是否已经完成装配。 + validationErr := r.validateUsers() + if validationErr != nil { + return false, validationErr + } + return r.store.Users.UpdatePassword(ctx, username, password) +} + +// UpdateCredentials 原子更新登录用户名及可选密码,并转换用户名冲突错误。 +func (r *AuthenticationRepository) UpdateCredentials(ctx context.Context, userID int64, username, password string) error { + // validationErr 表示认证用户仓储是否已经完成装配。 + validationErr := r.validateUsers() + if validationErr != nil { + return validationErr + } + // updateErr 保存登录凭据写入及事务提交结果。 + updateErr := r.store.Users.UpdateCredentials(ctx, userID, username, password) + if updateErr != nil { + if errors.Is(updateErr, db.ErrUsernameTaken) { + return accountapp.ErrUsernameTaken + } + return updateErr + } + return nil +} + +// CreateSession 为认证成功的应用身份创建数据库会话。 +func (r *AuthenticationRepository) CreateSession(ctx context.Context, user accountapp.AuthUser) (string, error) { + if r == nil || r.store == nil || r.store.Sessions == nil { + return "", errors.New("认证会话数据库适配器未初始化") + } + // dbUser 是仅供会话仓储写入的非敏感数据库用户投影。 + dbUser := &db.User{ID: user.ID, Username: user.Username, IsAdmin: user.IsAdmin} + return r.store.Sessions.Create(ctx, dbUser) +} + +// validateUsers 检查认证适配器是否已装配用户仓储。 +func (r *AuthenticationRepository) validateUsers() error { + if r == nil || r.store == nil || r.store.Users == nil { + return errors.New("认证用户数据库适配器未初始化") + } + return nil +} + +var _ accountapp.AuthenticationRepository = (*AuthenticationRepository)(nil) diff --git a/internal/adapter/authentication_repository_test.go b/internal/adapter/authentication_repository_test.go new file mode 100644 index 0000000..a50aeba --- /dev/null +++ b/internal/adapter/authentication_repository_test.go @@ -0,0 +1,117 @@ +package adapter + +import ( + "context" + "errors" + "path/filepath" + "testing" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" +) + +// TestAuthenticationRepositoryMapsLoginAndPasswordOperations 验证认证端口在 SQLite 中映射登录、会话和改密行为。 +func TestAuthenticationRepositoryMapsLoginAndPasswordOperations(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的认证适配器。 + repository := NewAuthenticationRepository(store) + // ctx 是本测试数据库操作共用的非取消上下文。 + ctx := context.Background() + // setAdminErr 保存测试管理员标记结果,确保初始化状态与夹具语义一致。 + if setAdminErr := store.Users.SetAdmin(ctx, "admin"); setAdminErr != nil { + t.Fatalf("标记管理员失败: %v", setAdminErr) + } + // initialized、initializedErr 保存系统初始化状态查询结果。 + initialized, initializedErr := repository.IsSystemInitialized(ctx) + if initializedErr != nil || !initialized { + t.Fatalf("初始化状态异常 initialized=%v err=%v", initialized, initializedErr) + } + // username、usernameErr 保存邮箱映射结果。 + username, usernameErr := repository.UsernameByEmail(ctx, "a@e.com") + if usernameErr != nil || username != "admin" { + t.Fatalf("邮箱映射异常 username=%q err=%v", username, usernameErr) + } + // user、matched、verifyErr 保存正确密码校验结果。 + user, matched, verifyErr := repository.VerifyPassword(ctx, "admin", "pw") + if verifyErr != nil || !matched || user.ID == 0 || !user.IsAdmin { + t.Fatalf("正确密码校验异常 user=%+v matched=%v err=%v", user, matched, verifyErr) + } + // sessionID、sessionErr 保存认证成功后的会话写入结果。 + sessionID, sessionErr := repository.CreateSession(ctx, user) + if sessionErr != nil || sessionID == "" { + t.Fatalf("会话写入异常 session=%q err=%v", sessionID, sessionErr) + } + // _, wrongMatched、wrongErr 保存错误密码的稳定失败语义。 + _, wrongMatched, wrongErr := repository.VerifyPassword(ctx, "admin", "wrong") + if wrongMatched || !errors.Is(wrongErr, accountapp.ErrPasswordMismatch) { + t.Fatalf("错误密码映射异常 matched=%v err=%v", wrongMatched, wrongErr) + } + // updated、updateErr 保存管理员密码更新结果。 + updated, updateErr := repository.UpdatePassword(ctx, "admin", "new-password") + if updateErr != nil || !updated { + t.Fatalf("密码更新异常 updated=%v err=%v", updated, updateErr) + } + // _, newMatched、newVerifyErr 验证新密码生效。 + _, newMatched, newVerifyErr := repository.VerifyPassword(ctx, "admin", "new-password") + if newVerifyErr != nil || !newMatched { + t.Fatalf("新密码校验异常 matched=%v err=%v", newMatched, newVerifyErr) + } +} + +// TestAuthenticationRepositoryMapsInitializationAndUsernameConflicts 验证管理员初始化和用户名冲突映射。 +func TestAuthenticationRepositoryMapsInitializationAndUsernameConflicts(t *testing.T) { + // database、dialect、openErr 保存全新 SQLite 数据库的打开结果。 + database, dialect, openErr := db.Open(context.Background(), filepath.Join(t.TempDir(), "auth.db")) + if openErr != nil { + t.Fatalf("打开数据库失败: %v", openErr) + } + defer database.Close() + // store 是全新数据库的 repository 聚合入口。 + store := db.NewStore(database, dialect) + // repository 是绑定全新数据库的认证适配器。 + repository := NewAuthenticationRepository(store) + // ctx 是本测试数据库操作共用的非取消上下文。 + ctx := context.Background() + // created、createErr 保存首次管理员初始化结果。 + created, createErr := repository.InitializeAdmin(ctx, "admin@example.com", "password") + if createErr != nil || !created { + t.Fatalf("首次初始化异常 created=%v err=%v", created, createErr) + } + // createdAgain、resetErr 保存已初始化管理员的兼容重置结果。 + createdAgain, resetErr := repository.InitializeAdmin(ctx, "ignored@example.com", "new-password") + if resetErr != nil || createdAgain { + t.Fatalf("重复初始化异常 created=%v err=%v", createdAgain, resetErr) + } + // _, otherCreateErr 验证重复用户名的数据库结果不会伪装成认证成功。 + if _, otherCreateErr := store.Users.Create(ctx, "other", "other@example.com", "password"); otherCreateErr != nil { + t.Fatalf("创建冲突测试用户失败: %v", otherCreateErr) + } + // admin、adminErr 保存管理员用户查询结果。 + admin, adminErr := store.Users.GetByUsername(ctx, "admin") + if adminErr != nil { + t.Fatalf("查询管理员失败: %v", adminErr) + } + // conflictErr 保存将管理员改成已占用用户名的结果。 + conflictErr := repository.UpdateCredentials(ctx, admin.ID, "other", "") + if !errors.Is(conflictErr, accountapp.ErrUsernameTaken) { + t.Fatalf("用户名冲突映射异常: %v", conflictErr) + } +} + +// TestAuthenticationRepositoryRejectsMissingDependencies 验证认证适配器缺少数据库时所有入口均快速失败。 +func TestAuthenticationRepositoryRejectsMissingDependencies(t *testing.T) { + // repository 是未装配数据库的认证适配器。 + repository := NewAuthenticationRepository(nil) + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // initializedErr 保存缺少用户仓储时的初始化状态错误。 + if _, initializedErr := repository.IsSystemInitialized(ctx); initializedErr == nil { + t.Fatal("缺少用户仓储时不应返回初始化成功") + } + // sessionErr 保存缺少会话仓储时的会话创建错误。 + if _, sessionErr := repository.CreateSession(ctx, accountapp.AuthUser{ID: 1, Username: "admin"}); sessionErr == nil { + t.Fatal("缺少会话仓储时不应返回会话成功") + } +} diff --git a/internal/adapter/automation_credential_wake.go b/internal/adapter/automation_credential_wake.go new file mode 100644 index 0000000..a32d174 --- /dev/null +++ b/internal/adapter/automation_credential_wake.go @@ -0,0 +1,31 @@ +package adapter + +import ( + "context" + "errors" + + automationapp "xianyu-go/internal/application/automation" + "xianyu-go/internal/db" +) + +// AutomationCredentialWakeRepository 将自动化任务唤醒 Port 适配为数据库仓储。 +type AutomationCredentialWakeRepository struct { + // store 保存自动化任务数据库仓储入口。 + store *db.Store +} + +// NewAutomationCredentialWakeRepository 构造自动化凭证唤醒数据库适配器。 +func NewAutomationCredentialWakeRepository(store *db.Store) *AutomationCredentialWakeRepository { + return &AutomationCredentialWakeRepository{store: store} +} + +// WakeCredentialBlocked 唤醒指定账号因凭证失效而暂停的自动化任务。 +func (r *AutomationCredentialWakeRepository) WakeCredentialBlocked(ctx context.Context, accountID string) error { + if r == nil || r.store == nil || r.store.Automation == nil { + return errors.New("自动化任务存储未初始化") + } + return r.store.Automation.WakeCredentialBlocked(ctx, accountID) +} + +// 确保数据库适配器覆盖凭证恢复唤醒应用 Port。 +var _ automationapp.CredentialWakeRepository = (*AutomationCredentialWakeRepository)(nil) diff --git a/internal/adapter/automation_credential_wake_test.go b/internal/adapter/automation_credential_wake_test.go new file mode 100644 index 0000000..a37ed7f --- /dev/null +++ b/internal/adapter/automation_credential_wake_test.go @@ -0,0 +1,16 @@ +package adapter + +import ( + "context" + "testing" +) + +// TestAutomationCredentialWakeRepositoryRejectsMissingStore 验证缺失数据库时返回明确错误。 +func TestAutomationCredentialWakeRepositoryRejectsMissingStore(t *testing.T) { + // repository 是未装配数据库的自动化凭证唤醒适配器。 + repository := NewAutomationCredentialWakeRepository(nil) + // err 保存缺失数据库依赖时的适配器错误。 + if err := repository.WakeCredentialBlocked(context.Background(), "acc1"); err == nil { + t.Fatal("缺少数据库时不应伪装唤醒成功") + } +} diff --git a/internal/adapter/automation_repository.go b/internal/adapter/automation_repository.go new file mode 100644 index 0000000..4fbf344 --- /dev/null +++ b/internal/adapter/automation_repository.go @@ -0,0 +1,221 @@ +package adapter + +import ( + "context" + "errors" + + automationapp "xianyu-go/internal/application/automation" + "xianyu-go/internal/db" +) + +// AutomationRepository 将 Store 的自动化异常查询与 resolve 能力适配为应用 Port。 +type AutomationRepository struct { + // store 保存数据库聚合入口,仅由该基础设施适配器访问。 + store *db.Store +} + +// NewAutomationRepository 构造自动化异常应用 Port 的数据库适配器。 +func NewAutomationRepository(store *db.Store) *AutomationRepository { + return &AutomationRepository{store: store} +} + +// ListIssues 查询并转换当前用户可见的自动化异常摘要。 +func (r *AutomationRepository) ListIssues(ctx context.Context, userID int64) ([]automationapp.RunIssue, []automationapp.DeferredIssue, error) { + // runIssues、deferredIssues、err 保存数据库异常摘要和查询错误。 + runIssues, deferredIssues, err := r.store.Automation.ListIssues(ctx, userID) + if err != nil { + return nil, nil, mapAutomationIssueError(err) + } + // runs 是不携带数据库模型的运行异常摘要列表。 + runs := make([]automationapp.RunIssue, 0, len(runIssues)) + // runIssue 是当前待转换的数据库运行异常记录。 + for _, runIssue := range runIssues { + runs = append(runs, automationapp.RunIssue{ + ID: runIssue.ID, CookieID: runIssue.CookieID, OrderID: runIssue.OrderID, + TriggerType: runIssue.TriggerType, ErrorMessage: runIssue.ErrorMessage, + IssueKind: runIssue.IssueKind, AllowedResolutions: runIssue.AllowedResolutions, + ActionCursor: runIssue.ActionCursor, SentCount: runIssue.SentCount, UpdatedAt: runIssue.UpdatedAt, + }) + } + // tasks 是不携带数据库模型的延期异常摘要列表。 + tasks := make([]automationapp.DeferredIssue, 0, len(deferredIssues)) + // deferredIssue 是当前待转换的数据库延期异常记录。 + for _, deferredIssue := range deferredIssues { + tasks = append(tasks, automationapp.DeferredIssue{ + ID: deferredIssue.ID, CookieID: deferredIssue.CookieID, TriggerType: deferredIssue.TriggerType, + ErrorMessage: deferredIssue.ErrorMessage, AttemptCount: deferredIssue.AttemptCount, UpdatedAt: deferredIssue.UpdatedAt, + }) + } + return runs, tasks, nil +} + +// ResolveRunIssue 按用户归属执行异常运行人工处理,并归一化未找到错误。 +func (r *AutomationRepository) ResolveRunIssue(ctx context.Context, userID, runID int64, resolution string) error { + return mapAutomationIssueError(r.store.Automation.ResolveRunIssue(ctx, userID, runID, resolution)) +} + +// ResolveDeferredIssue 按用户归属重试或删除死信延期任务,并归一化未找到错误。 +func (r *AutomationRepository) ResolveDeferredIssue(ctx context.Context, userID, taskID int64, retry bool) error { + return mapAutomationIssueError(r.store.Automation.ResolveDeferredIssue(ctx, userID, taskID, retry)) +} + +// mapAutomationIssueError 将数据库未找到错误转换为应用层错误,避免 Port 暴露数据库包。 +func mapAutomationIssueError(err error) error { + if errors.Is(err, db.ErrNotFound) { + return automationapp.ErrNotFound + } + return err +} + +// ListForUser 返回用户全部自动化规则的应用模型。 +func (r *AutomationRepository) ListForUser(ctx context.Context, userID int64) ([]automationapp.Rule, error) { + // rules、err 保存数据库规则列表及查询失败原因。 + rules, err := r.store.Automation.ListForUser(ctx, userID) + if err != nil { + return nil, err + } + return automationRulesModel(rules), nil +} + +// ListPageForUser 返回用户自动化规则分页及总数。 +func (r *AutomationRepository) ListPageForUser(ctx context.Context, filter automationapp.RuleFilter) ([]automationapp.Rule, int, error) { + // rules、total、err 保存分页规则、总数及数据库查询失败原因。 + rules, total, err := r.store.Automation.ListPageForUser(ctx, db.AutomationRuleListFilter{ + UserID: filter.UserID, CookieID: filter.CookieID, TriggerType: filter.TriggerType, + Enabled: filter.Enabled, Search: filter.Search, Limit: filter.Limit, Offset: filter.Offset, + }) + if err != nil { + return nil, 0, err + } + return automationRulesModel(rules), total, nil +} + +// CountByTriggerForUser 返回用户规则触发类型统计。 +func (r *AutomationRepository) CountByTriggerForUser(ctx context.Context, filter automationapp.RuleFilter) (map[string]int, error) { + return r.store.Automation.CountByTriggerForUser(ctx, db.AutomationRuleListFilter{ + UserID: filter.UserID, CookieID: filter.CookieID, TriggerType: filter.TriggerType, + Enabled: filter.Enabled, Search: filter.Search, + }) +} + +// Create 将应用层规则输入转换为数据库模型并创建规则。 +func (r *AutomationRepository) Create(ctx context.Context, input automationapp.RuleInput) (int64, error) { + return r.store.Automation.Create(ctx, automationRuleInputDB(input)) +} + +// EnsurePublishRule 将发布自动化规则输入转换为数据库模型并执行幂等创建。 +func (r *AutomationRepository) EnsurePublishRule(ctx context.Context, input automationapp.RuleInput) error { + // databaseInput 保存发布自动化规则对应的数据库写入模型。 + databaseInput := automationRuleInputDB(input) + // exists、err 保存同一发布规则的存在状态及查询错误。 + exists, err := r.store.Automation.ExistsPublishRule(ctx, databaseInput) + if err != nil { + return err + } + if exists { + return nil + } + // _, err 保存首次创建发布自动化规则的结果。 + _, err = r.store.Automation.Create(ctx, databaseInput) + return err +} + +// Update 将应用层规则输入转换为数据库模型并更新规则。 +func (r *AutomationRepository) Update(ctx context.Context, userID, ruleID int64, input automationapp.RuleInput) error { + // err 保存数据库更新失败原因,随后转换为应用层错误。 + err := r.store.Automation.Update(ctx, userID, ruleID, automationRuleInputDB(input)) + return mapAutomationRuleError(err) +} + +// Delete 删除用户拥有的规则并转换数据库错误边界。 +func (r *AutomationRepository) Delete(ctx context.Context, userID, ruleID int64) error { + return mapAutomationRuleError(r.store.Automation.Delete(ctx, userID, ruleID)) +} + +// OwnsAccount 返回账号是否属于指定用户。 +func (r *AutomationRepository) OwnsAccount(ctx context.Context, userID int64, accountID string) (bool, error) { + return r.store.Cookies.ExistsOwned(ctx, userID, accountID) +} + +// OwnsItem 返回商品是否属于指定用户账号。 +func (r *AutomationRepository) OwnsItem(ctx context.Context, userID int64, accountID, itemID string) (bool, error) { + // owned、err 保存账号归属查询结果及失败原因。 + owned, err := r.store.Cookies.ExistsOwned(ctx, userID, accountID) + if err != nil || !owned { + return false, err + } + // _, err 保存按账号和商品双键读取结果;只有未找到才转换为业务上的不归属。 + _, err = r.store.Items.Get(ctx, accountID, itemID) + if errors.Is(err, db.ErrNotFound) { + return false, nil + } + if err != nil { + return false, err + } + return true, nil +} + +// GetCard 返回用户拥有的卡密组类型,不将卡密内容传入应用层。 +func (r *AutomationRepository) GetCard(ctx context.Context, userID, cardID int64) (automationapp.CardInfo, error) { + // card、err 保存卡密组摘要及读取失败原因;卡密正文不会进入应用层。 + card, err := r.store.Cards.Get(ctx, cardID) + if errors.Is(err, db.ErrNotFound) || (err == nil && (card == nil || card.UserID != userID)) { + return automationapp.CardInfo{}, automationapp.ErrRuleNotFound + } + if err != nil { + return automationapp.CardInfo{}, err + } + return automationapp.CardInfo{Type: card.Type}, nil +} + +// automationRulesModel 将数据库规则列表转换为应用模型。 +func automationRulesModel(rules []db.AutomationRule) []automationapp.Rule { + // result 保存从数据库模型转换出的应用规则列表。 + result := make([]automationapp.Rule, 0, len(rules)) + // rule 是当前待转换的数据库规则。 + for _, rule := range rules { + // actions 保存当前规则转换后的应用动作列表。 + actions := make([]automationapp.Action, 0, len(rule.Actions)) + // action 是当前待转换的数据库动作。 + for _, action := range rule.Actions { + actions = append(actions, automationapp.Action{ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, + CardName: action.CardName, DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate, + DelaySeconds: action.DelaySeconds, ConfigJSON: action.ConfigJSON, Enabled: action.Enabled, SortOrder: action.SortOrder}) + } + result = append(result, automationapp.Rule{ID: rule.ID, CookieID: rule.CookieID, ItemID: rule.ItemID, ItemTitle: rule.ItemTitle, + Name: rule.Name, TriggerType: rule.TriggerType, Enabled: rule.Enabled, Priority: rule.Priority, + ConfigJSON: rule.ConfigJSON, Actions: actions, CreatedAt: rule.CreatedAt, UpdatedAt: rule.UpdatedAt}) + } + return result +} + +// automationRuleInputDB 将应用规则输入转换为数据库写入模型。 +func automationRuleInputDB(input automationapp.RuleInput) db.AutomationRuleInput { + // actions 保存转换后的数据库动作写入模型。 + actions := make([]db.AutomationActionInput, 0, len(input.Actions)) + // action 是当前待转换的应用动作。 + for _, action := range input.Actions { + actions = append(actions, db.AutomationActionInput{ActionType: action.ActionType, CardID: action.CardID, + DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate, DelaySeconds: action.DelaySeconds, + ConfigJSON: action.ConfigJSON, Enabled: action.Enabled, SortOrder: action.SortOrder}) + } + return db.AutomationRuleInput{UserID: input.UserID, CookieID: input.CookieID, ItemID: input.ItemID, Name: input.Name, + TriggerType: input.TriggerType, Enabled: input.Enabled, Priority: input.Priority, ConfigJSON: input.ConfigJSON, Actions: actions} +} + +// mapAutomationRuleError 将数据库规则错误转换为应用层错误。 +func mapAutomationRuleError(err error) error { + if errors.Is(err, db.ErrNotFound) { + return automationapp.ErrRuleNotFound + } + if errors.Is(err, db.ErrAutomationRunActive) { + return automationapp.ErrRuleActive + } + return err +} + +// automationRepositoryCompileCheck 确保数据库适配器完整实现应用 Port。 +var _ automationapp.IssueRepository = (*AutomationRepository)(nil) +var _ automationapp.RuleRepository = (*AutomationRepository)(nil) +var _ automationapp.RuleOwnership = (*AutomationRepository)(nil) +var _ automationapp.PublishRuleRepository = (*AutomationRepository)(nil) diff --git a/internal/adapter/automation_repository_test.go b/internal/adapter/automation_repository_test.go new file mode 100644 index 0000000..ebc8064 --- /dev/null +++ b/internal/adapter/automation_repository_test.go @@ -0,0 +1,104 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + automationapp "xianyu-go/internal/application/automation" + "xianyu-go/internal/db" +) + +// TestAutomationRepositoryOwnershipMapsNotFound 验证资源缺失只表现为不归属,不泄露数据库模型错误。 +func TestAutomationRepositoryOwnershipMapsNotFound(t *testing.T) { + // store 是当前适配器测试使用的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定 SQLite 存储的自动化规则适配器。 + repository := NewAutomationRepository(store) + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // owned、ownedErr 保存不存在商品的归属判断结果。 + owned, ownedErr := repository.OwnsItem(ctx, 1, "cid", "missing-item") + if owned || ownedErr != nil { + t.Fatalf("缺失商品应返回 false,nil,owned=%v err=%v", owned, ownedErr) + } + // cardInfo、cardErr 保存不存在卡密组的最小应用摘要及错误。 + cardInfo, cardErr := repository.GetCard(ctx, 1, 999999) + if cardInfo != (automationapp.CardInfo{}) || !errors.Is(cardErr, automationapp.ErrRuleNotFound) { + t.Fatalf("缺失卡密组应映射为应用未找到,info=%+v err=%v", cardInfo, cardErr) + } +} + +// TestAutomationRepositoryOwnershipPropagatesDatabaseErrors 验证数据库不可用时不会伪装成归属失败。 +func TestAutomationRepositoryOwnershipPropagatesDatabaseErrors(t *testing.T) { + // store 是当前适配器测试使用的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定 SQLite 存储的自动化规则适配器。 + repository := NewAutomationRepository(store) + // ctx 是数据库关闭后调用适配器的非取消上下文。 + ctx := context.Background() + // closeErr 表示提前关闭测试数据库时的资源释放错误。 + closeErr := store.DB.Close() + if closeErr != nil { + t.Fatal(closeErr) + } + // _, itemErr 保存商品归属查询透传的数据库错误。 + _, itemErr := repository.OwnsItem(ctx, 1, "cid", "item-1") + if itemErr == nil { + t.Fatal("数据库关闭后商品归属查询应返回错误") + } + // _, cardErr 保存卡密组查询透传的数据库错误。 + _, cardErr := repository.GetCard(ctx, 1, 1) + if cardErr == nil || errors.Is(cardErr, db.ErrNotFound) || errors.Is(cardErr, automationapp.ErrRuleNotFound) { + t.Fatalf("数据库关闭后卡密查询应保留底层错误,err=%v", cardErr) + } +} + +// TestAutomationRepositoryEnsurePublishRuleIsIdempotent 验证发布自动化规则只创建一次。 +func TestAutomationRepositoryEnsurePublishRuleIsIdempotent(t *testing.T) { + // store 是当前适配器测试使用的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定 SQLite 存储的自动化规则适配器。 + repository := NewAutomationRepository(store) + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // input 是代表发布成功后自动发货的规则输入。 + input := automationapp.RuleInput{UserID: 1, CookieID: "cid", ItemID: "item-1", Name: "付款后自动发货 - 商品", TriggerType: automationapp.TriggerOrderPaid, Enabled: true, Priority: 100, ConfigJSON: "{}", Actions: []automationapp.ActionInput{{ActionType: automationapp.ActionConfirmShipment, Enabled: true, SortOrder: 1}}} + // firstErr 保存第一次幂等准备的错误。 + firstErr := repository.EnsurePublishRule(ctx, input) + if firstErr != nil { + t.Fatal(firstErr) + } + // secondErr 保存第二次幂等准备的错误。 + secondErr := repository.EnsurePublishRule(ctx, input) + if secondErr != nil { + t.Fatal(secondErr) + } + // rules、matchErr 保存按发布规则唯一条件查询到的规则。 + rules, matchErr := store.Automation.Match(ctx, input.CookieID, input.ItemID, input.TriggerType) + if matchErr != nil || len(rules) != 1 { + t.Fatalf("幂等准备应只保留一条规则,rules=%+v err=%v", rules, matchErr) + } +} + +// TestAutomationRepositoryEnsurePublishRulePropagatesDatabaseError 验证数据库故障不会被发布规则适配器吞掉。 +func TestAutomationRepositoryEnsurePublishRulePropagatesDatabaseError(t *testing.T) { + // store 是当前适配器测试使用的 SQLite 存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定 SQLite 存储的自动化规则适配器。 + repository := NewAutomationRepository(store) + // closeErr 表示提前关闭测试数据库时的资源释放错误。 + closeErr := store.DB.Close() + if closeErr != nil { + t.Fatal(closeErr) + } + // err 保存关闭数据库后执行幂等准备的错误。 + err := repository.EnsurePublishRule(context.Background(), automationapp.RuleInput{UserID: 1, CookieID: "account-1", ItemID: "item-1", Name: "规则", TriggerType: automationapp.TriggerOrderPaid}) + if err == nil { + t.Fatal("数据库关闭后应返回发布规则持久化错误") + } +} diff --git a/internal/adapter/cards_repository.go b/internal/adapter/cards_repository.go new file mode 100644 index 0000000..f6b076b --- /dev/null +++ b/internal/adapter/cards_repository.go @@ -0,0 +1,127 @@ +package adapter + +import ( + "context" + "errors" + + cardsapp "xianyu-go/internal/application/cards" + "xianyu-go/internal/db" +) + +// CardsRepository 将卡券数据库仓储适配为应用层消费者定义的 CRUD Port。 +type CardsRepository struct { + // store 保存数据库聚合入口,但只通过 Cards 子仓储访问卡券数据。 + store *db.Store +} + +// NewCardsRepository 构造卡券数据库适配器;装配缺失会在方法调用时返回错误。 +func NewCardsRepository(store *db.Store) *CardsRepository { + return &CardsRepository{store: store} +} + +// ListForUser 查询指定用户的卡券组并转换为应用模型。 +func (r *CardsRepository) ListForUser(ctx context.Context, userID int64) ([]cardsapp.Card, error) { + // err 表示卡券适配器依赖缺失时的装配错误。 + if err := r.validate(); err != nil { + return nil, err + } + // records 是数据库仓储按倒序返回的卡券完整记录。 + records, err := r.store.Cards.AllForUser(ctx, userID) + if err != nil { + return nil, err + } + // result 是与数据库模型解耦的应用卡券列表。 + result := make([]cardsapp.Card, 0, len(records)) + // record 是当前待转换的数据库卡券记录。 + for _, record := range records { + result = append(result, cardApplicationModel(record)) + } + return result, nil +} + +// Get 查询单个卡券组,并把数据库缺失错误映射为应用层稳定错误。 +func (r *CardsRepository) Get(ctx context.Context, cardID int64) (cardsapp.Card, error) { + // err 表示卡券适配器依赖缺失时的装配错误。 + if err := r.validate(); err != nil { + return cardsapp.Card{}, err + } + // record 是数据库返回的完整卡券记录。 + record, err := r.store.Cards.Get(ctx, cardID) + if err != nil { + if errors.Is(err, db.ErrNotFound) { + return cardsapp.Card{}, cardsapp.ErrNotFound + } + return cardsapp.Card{}, err + } + return cardApplicationModel(*record), nil +} + +// Create 将已校验的应用卡券模型转换为数据库模型并返回新标识。 +func (r *CardsRepository) Create(ctx context.Context, card cardsapp.Card) (int64, error) { + // err 表示卡券适配器依赖缺失时的装配错误。 + if err := r.validate(); err != nil { + return 0, err + } + // record 是仅在适配器内存在的数据库写入模型。 + record := cardDatabaseModel(card) + return r.store.Cards.Create(ctx, &record) +} + +// Update 将应用层可编辑字段写入数据库,不向上层暴露数据库模型。 +func (r *CardsRepository) Update(ctx context.Context, card cardsapp.Card) error { + // err 表示卡券适配器依赖缺失时的装配错误。 + if err := r.validate(); err != nil { + return err + } + // record 是仅在适配器内存在的数据库更新模型。 + record := cardDatabaseModel(card) + return r.store.Cards.Update(ctx, &record) +} + +// Delete 删除指定卡券组,并原样返回数据库约束或连接错误。 +func (r *CardsRepository) Delete(ctx context.Context, cardID int64) error { + // err 表示卡券适配器依赖缺失时的装配错误。 + if err := r.validate(); err != nil { + return err + } + return r.store.Cards.Delete(ctx, cardID) +} + +// AppendData 将 data 卡券组的逐行库存追加能力适配到应用 Port。 +func (r *CardsRepository) AppendData(ctx context.Context, cardID int64, content string) (int, error) { + // err 表示卡券适配器依赖缺失时的装配错误。 + if err := r.validate(); err != nil { + return 0, err + } + return r.store.Cards.AppendBatchData(ctx, cardID, content) +} + +// validate 检查卡券适配器是否具备 Store 与 Cards 子仓储。 +func (r *CardsRepository) validate() error { + if r == nil || r.store == nil || r.store.Cards == nil { + return errors.New("卡券数据库适配器未初始化") + } + return nil +} + +// cardApplicationModel 将数据库卡券记录转换为基础设施无关的应用模型。 +func cardApplicationModel(record db.CardFull) cardsapp.Card { + return cardsapp.Card{ + ID: record.ID, Name: record.Name, Type: record.Type, APIConfig: record.APIConfig, + TextContent: record.TextContent, DataContent: record.DataContent, ImageURL: record.ImageURL, + Description: record.Description, Enabled: record.Enabled, DelaySeconds: record.DelaySeconds, + IsMultiSpec: record.IsMultiSpec, SpecName: record.SpecName, SpecValue: record.SpecValue, UserID: record.UserID, + } +} + +// cardDatabaseModel 将应用卡券模型转换为数据库仓储要求的写入模型。 +func cardDatabaseModel(card cardsapp.Card) db.CardFull { + return db.CardFull{ + ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig, + TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL, + Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds, + IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID, + } +} + +var _ cardsapp.Repository = (*CardsRepository)(nil) diff --git a/internal/adapter/cards_repository_test.go b/internal/adapter/cards_repository_test.go new file mode 100644 index 0000000..7f7796a --- /dev/null +++ b/internal/adapter/cards_repository_test.go @@ -0,0 +1,121 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + cardsapp "xianyu-go/internal/application/cards" +) + +// TestCardsRepositoryCRUDMapping 验证 SQLite 卡券 CRUD 与应用模型之间的完整字段映射。 +func TestCardsRepositoryCRUDMapping(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是待验证的卡券数据库适配器。 + repository := NewCardsRepository(store) + // ctx 是本测试全部数据库操作使用的非取消上下文。 + ctx := context.Background() + // owner 是测试模板中创建的卡券所有者。 + owner, ownerErr := store.Users.GetByUsername(ctx, "admin") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // input 是覆盖全部持久化字段的应用卡券模型。 + input := cardsapp.Card{ + Name: "库存卡", Type: "data", APIConfig: "legacy", TextContent: "text", DataContent: "A\nB", + ImageURL: "https://example.invalid/card.png", Description: "description", Enabled: true, + DelaySeconds: 12, IsMultiSpec: true, SpecName: "颜色", SpecValue: "蓝", UserID: owner.ID, + } + // cardID、createErr 保存创建结果。 + cardID, createErr := repository.Create(ctx, input) + if createErr != nil || cardID <= 0 { + t.Fatalf("创建卡券失败 id=%d err=%v", cardID, createErr) + } + // got、getErr 保存详情查询结果。 + got, getErr := repository.Get(ctx, cardID) + if getErr != nil { + t.Fatal(getErr) + } + input.ID = cardID + if got != input { + t.Fatalf("详情字段映射不匹配 got=%+v want=%+v", got, input) + } + // listed、listErr 保存按用户隔离的列表结果。 + listed, listErr := repository.ListForUser(ctx, owner.ID) + if listErr != nil || len(listed) != 1 || listed[0] != input { + t.Fatalf("列表字段映射不匹配 listed=%+v err=%v", listed, listErr) + } + got.Name = "更新后" + got.Enabled = false + // updateErr 表示更新卡券组时的数据库错误。 + if updateErr := repository.Update(ctx, got); updateErr != nil { + t.Fatal(updateErr) + } + // updated、updatedErr 保存更新后的详情。 + updated, updatedErr := repository.Get(ctx, cardID) + if updatedErr != nil || updated.Name != "更新后" || updated.Enabled { + t.Fatalf("更新结果异常 card=%+v err=%v", updated, updatedErr) + } + // deleteErr 表示删除卡券组时的数据库错误。 + if deleteErr := repository.Delete(ctx, cardID); deleteErr != nil { + t.Fatal(deleteErr) + } + // missingErr 表示删除后再次读取卡券组的应用层未找到错误。 + if _, missingErr := repository.Get(ctx, cardID); !errors.Is(missingErr, cardsapp.ErrNotFound) { + t.Fatalf("删除后应映射为应用层未找到,err=%v", missingErr) + } +} + +// TestCardsRepositoryAppendDataMapping 验证卡券适配器把追加库存结果和内容写入数据库。 +func TestCardsRepositoryAppendDataMapping(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是待验证的卡券数据库适配器。 + repository := NewCardsRepository(store) + // ctx 是本测试数据库操作使用的非取消上下文。 + ctx := context.Background() + // owner、ownerErr 保存测试模板中的卡券所有者及查询错误。 + owner, ownerErr := store.Users.GetByUsername(ctx, "admin") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // cardID、createErr 保存 data 卡券组标识及创建错误。 + cardID, createErr := repository.Create(ctx, cardsapp.Card{Name: "库存卡", Type: "data", DataContent: "A\n", UserID: owner.ID}) + if createErr != nil { + t.Fatal(createErr) + } + // added、appendErr 保存适配器返回的有效新增行数及错误。 + added, appendErr := repository.AppendData(ctx, cardID, "B\n\nC") + if appendErr != nil || added != 2 { + t.Fatalf("追加结果异常 added=%d err=%v", added, appendErr) + } + // got、getErr 保存追加后的卡券记录及读取错误。 + got, getErr := repository.Get(ctx, cardID) + if getErr != nil || got.DataContent != "A\n\nB\n\nC" { + t.Fatalf("追加内容未正确映射 card=%+v err=%v", got, getErr) + } +} + +// TestCardsRepositoryPropagatesInfrastructureErrors 验证数据库不可用时不会伪装成卡券缺失。 +func TestCardsRepositoryPropagatesInfrastructureErrors(t *testing.T) { + // store 是随后主动关闭数据库连接的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定已关闭数据库的卡券适配器。 + repository := NewCardsRepository(store) + // closeErr 表示主动关闭测试数据库连接时的资源释放错误。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // err 表示关闭数据库后读取卡券组的底层错误。 + if _, err := repository.Get(context.Background(), 1); err == nil || errors.Is(err, cardsapp.ErrNotFound) { + t.Fatalf("数据库故障应原样返回,err=%v", err) + } + // err 表示缺少 Store 时的适配器装配错误。 + if _, err := NewCardsRepository(nil).ListForUser(context.Background(), 1); err == nil { + t.Fatal("缺少 Store 时应返回装配错误") + } +} diff --git a/internal/adapter/chat_contract_conversion.go b/internal/adapter/chat_contract_conversion.go new file mode 100644 index 0000000..871f427 --- /dev/null +++ b/internal/adapter/chat_contract_conversion.go @@ -0,0 +1,24 @@ +package adapter + +import ( + chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/db" +) + +// ChatSessionFromApplication 将聊天应用会话转换为 legacy 聊天领域写入模型。 +// 转换只包含会话展示字段,不携带 Cookie、Token 或其他账号秘密。 +func ChatSessionFromApplication(session chatapp.Session) db.ChatSession { + return dbChatSession(session) +} + +// ChatMessagesFromDB 将 legacy 聊天领域消息转换为应用层非敏感消息模型。 +// 数据库模型只在 adapter 内部出现,调用方获得的结果不暴露存储层类型。 +func ChatMessagesFromDB(messages []db.ChatMessage) []chatapp.Message { + // result 保存转换后的应用层消息列表。 + result := make([]chatapp.Message, 0, len(messages)) + // message 表示当前待转换的 legacy 聊天消息。 + for _, message := range messages { + result = append(result, chatApplicationMessage(&message)) + } + return result +} diff --git a/internal/adapter/chat_contract_conversion_test.go b/internal/adapter/chat_contract_conversion_test.go new file mode 100644 index 0000000..b8b13e5 --- /dev/null +++ b/internal/adapter/chat_contract_conversion_test.go @@ -0,0 +1,47 @@ +package adapter + +import ( + "reflect" + "testing" + + chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/db" +) + +// TestChatSessionFromApplicationKeepsNonSensitiveFields 验证会话转换只复制非敏感展示字段。 +func TestChatSessionFromApplicationKeepsNonSensitiveFields(t *testing.T) { + // session 保存应用层聊天会话摘要。 + session := chatapp.Session{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", BuyerAvatar: "avatar", ItemID: "item-1", ItemTitle: "商品", LastMessage: "你好", LastMessageAt: 42, UnreadCount: 3} + // converted 保存转换后的 legacy 聊天会话模型。 + converted := ChatSessionFromApplication(session) + // expected 保存应由领域仓储接收的非敏感会话字段。 + expected := db.ChatSession{CookieID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", BuyerAvatar: "avatar", ItemID: "item-1", ItemTitle: "商品", LastMessage: "你好", LastMessageAt: 42, UnreadCount: 3} + if !reflect.DeepEqual(converted, expected) { + t.Fatalf("聊天会话转换异常: got=%+v want=%+v", converted, expected) + } +} + +// TestChatMessagesFromDBKeepsMessageContract 验证数据库消息转换为应用消息时完整保留 API 所需字段。 +func TestChatMessagesFromDBKeepsMessageContract(t *testing.T) { + // messages 保存 legacy 聊天仓储返回的消息模型。 + messages := []db.ChatMessage{{ID: 7, CookieID: "account-1", ChatID: "chat-1", MessageKey: "key-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家", MessageType: "text", Content: "你好", Status: "received", SentAt: 99}} + // converted 保存不再暴露数据库模型的应用层消息。 + converted := ChatMessagesFromDB(messages) + if len(converted) != 1 { + t.Fatalf("消息数量异常: got=%d", len(converted)) + } + // expected 保存应用层消息字段。 + expected := chatapp.Message{ID: 7, AccountID: "account-1", ChatID: "chat-1", MessageKey: "key-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家", MessageType: "text", Content: "你好", Status: "received", SentAt: 99} + if !reflect.DeepEqual(converted[0], expected) { + t.Fatalf("聊天消息转换异常: got=%+v want=%+v", converted[0], expected) + } +} + +// TestChatMessagesFromDBHandlesEmptyInput 验证空消息页转换后保持可安全遍历的空切片。 +func TestChatMessagesFromDBHandlesEmptyInput(t *testing.T) { + // converted 保存空 legacy 消息列表转换结果。 + converted := ChatMessagesFromDB(nil) + if converted == nil || len(converted) != 0 { + t.Fatalf("空消息转换应返回非 nil 空切片: %#v", converted) + } +} diff --git a/internal/adapter/chat_repository.go b/internal/adapter/chat_repository.go new file mode 100644 index 0000000..aa40d0b --- /dev/null +++ b/internal/adapter/chat_repository.go @@ -0,0 +1,134 @@ +package adapter + +import ( + "context" + "errors" + + chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +// chatRepository 将数据库聊天仓储和账号归属查询适配为聊天应用端口。 +type chatRepository struct { + // store 保存数据库聚合入口,仅在本适配器内执行聊天窄查询。 + store *db.Store +} + +// NewChatRepository 创建聊天历史应用服务使用的数据库适配器。 +func NewChatRepository(store *db.Store) chatapp.Repository { + if store == nil || store.Chats == nil || store.Cookies == nil { + return nil + } + return chatRepository{store: store} +} + +// ListMessages 查询带用户归属条件的聊天消息,并转换为应用层模型。 +func (r chatRepository) ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]chatapp.Message, error) { + // rows 和 err 保存数据库消息记录及查询错误。 + rows, err := r.store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit) + if err != nil { + return nil, err + } + // messages 保存脱离数据库模型的应用层消息。 + messages := make([]chatapp.Message, 0, len(rows)) + // row 表示当前待转换的数据库聊天消息。 + for _, row := range rows { + messages = append(messages, chatapp.Message{ + ID: row.ID, AccountID: row.CookieID, ChatID: row.ChatID, MessageKey: row.MessageKey, + Direction: row.Direction, SenderID: row.SenderID, SenderName: row.SenderName, + MessageType: row.MessageType, Content: row.Content, Status: row.Status, SentAt: row.SentAt, + }) + } + return messages, nil +} + +// ListSessions 查询带用户归属条件的聊天会话,并转换为应用层模型。 +func (r chatRepository) ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]chatapp.Session, error) { + // rows 和 err 保存数据库会话记录及查询错误。 + rows, err := r.store.Chats.ListSessions(ctx, userID, accountID, limit) + if err != nil { + return nil, err + } + // sessions 保存脱离数据库模型的应用层会话摘要。 + sessions := make([]chatapp.Session, 0, len(rows)) + // row 表示当前待转换的数据库聊天会话。 + for _, row := range rows { + sessions = append(sessions, chatapp.Session{ + AccountID: row.CookieID, ChatID: row.ChatID, BuyerID: row.BuyerID, + BuyerName: row.BuyerName, BuyerAvatar: row.BuyerAvatar, ItemID: row.ItemID, + ItemTitle: row.ItemTitle, LastMessage: row.LastMessage, LastMessageAt: row.LastMessageAt, + UnreadCount: row.UnreadCount, + }) + } + return sessions, nil +} + +// DeleteEmptySessions 删除没有有效消息的聊天会话壳。 +func (r chatRepository) DeleteEmptySessions(ctx context.Context, accountID string) error { + return r.store.Chats.DeleteEmptySessions(ctx, accountID) +} + +// UpdateSessionIdentity 更新会话的买家身份缓存。 +func (r chatRepository) UpdateSessionIdentity(ctx context.Context, accountID, chatID, buyerID, buyerName, buyerAvatar string) error { + return r.store.Chats.UpdateSessionIdentity(ctx, accountID, chatID, buyerID, buyerName, buyerAvatar) +} + +// ExistsOwned 判断账号是否归属于指定用户,只返回非敏感存在性。 +func (r chatRepository) ExistsOwned(ctx context.Context, userID int64, accountID string) (bool, error) { + return r.store.Cookies.ExistsOwned(ctx, userID, accountID) +} + +// MarkRead 将用户拥有的聊天会话未读数归零,不读取或解密账号凭证。 +func (r chatRepository) MarkRead(ctx context.Context, userID int64, accountID, chatID string) error { + return r.store.Chats.MarkRead(ctx, userID, accountID, chatID) +} + +// chatIdentityResolver 在适配器内读取 Cookie 并调用平台身份查询接口。 +type chatIdentityResolver struct { + // store 提供账号凭证读取能力,明文只在本次平台调用期间存在。 + store *db.Store + // clientProvider 返回当前可注入的 MTOP 客户端,便于运行时替换和测试。 + clientProvider func() mtop.Client +} + +// NewChatIdentityResolver 创建聊天身份查询适配器。 +func NewChatIdentityResolver(store *db.Store, clientProvider func() mtop.Client) chatapp.IdentityResolver { + if store == nil || store.Cookies == nil || clientProvider == nil { + return nil + } + return chatIdentityResolver{store: store, clientProvider: clientProvider} +} + +// Resolve 查询聊天买家展示身份;Cookie 和平台客户端均不会离开适配器。 +func (r chatIdentityResolver) Resolve(ctx context.Context, accountID, chatID string) (chatapp.Identity, error) { + // cookies 和 err 保存平台调用需要的短暂凭证及读取错误,不得写入日志或响应。 + cookies, err := r.store.Cookies.GetValue(ctx, accountID) + if err != nil { + return chatapp.Identity{}, err + } + // client 保存当前 MTOP 客户端。 + client := r.clientProvider() + // fetcher 和 supported 保存身份查询能力及接口支持情况。 + fetcher, supported := client.(interface { + FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error) + }) + if !supported { + return chatapp.Identity{}, errors.New("当前 MTOP 客户端不支持聊天身份查询") + } + // info 和 err 保存平台返回的非敏感身份及查询错误。 + info, err := fetcher.FetchChatUserInfo(ctx, cookies, chatID) + if err != nil { + return chatapp.Identity{}, err + } + if info == nil { + return chatapp.Identity{}, nil + } + return chatapp.Identity{BuyerName: info.Nickname, BuyerAvatar: info.AvatarURL}, nil +} + +// 确保数据库聊天适配器覆盖应用层会话端口的全部能力。 +var _ chatapp.SessionRepository = chatRepository{} + +// 确保聊天身份适配器覆盖应用层平台身份端口。 +var _ chatapp.IdentityResolver = chatIdentityResolver{} diff --git a/internal/adapter/chat_repository_test.go b/internal/adapter/chat_repository_test.go new file mode 100644 index 0000000..001b5c0 --- /dev/null +++ b/internal/adapter/chat_repository_test.go @@ -0,0 +1,145 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +// fakeChatUploadClient 只实现聊天图片上传能力,用于隔离平台网络请求。 +type fakeChatUploadClient struct { + // mtop.Client 保留其余平台能力占位,测试只关注图片上传方法。 + mtop.Client + // upload 保存模拟平台返回的图片结果。 + upload *mtop.ChatImageUpload + // err 保存模拟平台上传错误。 + err error +} + +// UploadChatImage 返回预设图片结果或错误,不记录传入 Cookie。 +func (c fakeChatUploadClient) UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error) { + return c.upload, c.err +} + +// fakeChatIdentityClient 只实现聊天身份查询,其余 MTOP 能力由嵌入接口占位。 +type fakeChatIdentityClient struct { + // mtop.Client 保留未涉及本切片的 MTOP 能力占位。 + mtop.Client + // info 保存模拟平台返回的买家展示身份。 + info *mtop.ChatUserInfo +} + +// FetchChatUserInfo 返回预设聊天身份,并记录适配器已能调用动态能力。 +func (c fakeChatIdentityClient) FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error) { + return c.info, nil +} + +// TestChatRepositoryMapsSessionMaintenance 验证聊天数据库适配器覆盖列表、清理、身份和归属端口。 +func TestChatRepositoryMapsSessionMaintenance(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试数据库操作使用的非取消上下文。 + ctx := context.Background() + // repository 是聊天应用层会话端口的数据库实现。 + repository := NewChatRepository(store) + // owner 是模板账号的所有者。 + owner, ownerErr := store.Users.GetByUsername(ctx, "admin") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // session 是待写入数据库并转换回应用模型的非敏感会话。 + session := db.ChatSession{CookieID: "cid", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", LastMessage: "你好", LastMessageAt: 10} + // saveErr 表示写入测试会话时的数据库错误。 + if saveErr := store.Chats.UpsertSession(ctx, session); saveErr != nil { + t.Fatal(saveErr) + } + // port 是经类型断言确认的完整聊天维护端口。 + port, ok := repository.(chatapp.SessionRepository) + if !ok { + t.Fatal("聊天适配器未覆盖 SessionRepository") + } + // listed 和 listErr 保存应用层会话列表及转换错误。 + listed, listErr := port.ListSessions(ctx, owner.ID, "cid", 20) + if listErr != nil || len(listed) != 1 || listed[0].BuyerName != "买家" { + t.Fatalf("会话列表映射异常 listed=%+v err=%v", listed, listErr) + } + // owned 和 ownershipErr 保存账号归属查询结果。 + owned, ownershipErr := port.ExistsOwned(ctx, owner.ID, "cid") + if ownershipErr != nil || !owned { + t.Fatalf("账号归属映射异常 owned=%v err=%v", owned, ownershipErr) + } + // updateErr 保存会话身份缓存写入错误。 + if updateErr := port.UpdateSessionIdentity(ctx, "cid", "chat-1", "buyer-1", "新名称", "avatar"); updateErr != nil { + t.Fatal(updateErr) + } + // refreshed 和 refreshedErr 保存身份缓存写入后的会话列表。 + refreshed, refreshedErr := port.ListSessions(ctx, owner.ID, "cid", 20) + if refreshedErr != nil || refreshed[0].BuyerName != "新名称" || refreshed[0].BuyerAvatar != "avatar" { + t.Fatalf("身份缓存未更新 refreshed=%+v err=%v", refreshed, refreshedErr) + } + // emptyErr 保存删除无消息会话壳的结果。 + if emptyErr := port.DeleteEmptySessions(ctx, "cid"); emptyErr != nil { + t.Fatal(emptyErr) + } +} + +// TestChatIdentityResolverKeepsCredentialsInsideAdapter 验证身份适配器只向应用层返回展示字段。 +func TestChatIdentityResolverKeepsCredentialsInsideAdapter(t *testing.T) { + // store 是包含测试账号 Cookie 的临时数据库。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // client 是返回非敏感身份的测试 MTOP 客户端。 + client := fakeChatIdentityClient{info: &mtop.ChatUserInfo{Nickname: "买家新名", AvatarURL: "https://example.invalid/avatar"}} + // resolver 是读取 Cookie 并调用测试平台客户端的聊天身份适配器。 + resolver := NewChatIdentityResolver(store, func() mtop.Client { return client }) + // identity 和 resolveErr 保存适配器转换后的身份及查询错误。 + identity, resolveErr := resolver.Resolve(context.Background(), "cid", "chat-1") + if resolveErr != nil || identity.BuyerName != "买家新名" || identity.BuyerAvatar == "" { + t.Fatalf("身份映射异常 identity=%+v err=%v", identity, resolveErr) + } +} + +// TestChatSendingAdaptersRejectUnavailableDependencies 验证实时聊天适配器的未装配错误分支。 +func TestChatSendingAdaptersRejectUnavailableDependencies(t *testing.T) { + // outgoingErr 保存未装配聊天领域服务时的稳定应用错误。 + _, outgoingErr := NewChatOutgoingRepository(nil).CreateOutgoing(context.Background(), chatapp.Session{}, "文本") + if !errors.Is(outgoingErr, chatapp.ErrUnavailable) { + t.Fatalf("nil outgoing service error=%v", outgoingErr) + } + // senderProvider 是未装配账号管理器的在线发送适配器。 + senderProvider := NewChatSenderProvider(nil) + // sender、ok 保存未装配管理器时返回的发送器和存在性标记。 + if sender, ok := senderProvider.Sender("account-1"); ok || sender != nil { + t.Fatalf("nil sender provider returned sender=%v ok=%v", sender, ok) + } + // uploadErr 保存未提供平台客户端时的稳定应用错误。 + _, uploadErr := NewChatImageUploader(nil, nil, nil).UploadChatImage(context.Background(), "account-1", "a.jpg", "image/jpeg", []byte("image")) + if !errors.Is(uploadErr, chatapp.ErrUnavailable) { + t.Fatalf("nil image client error=%v", uploadErr) + } +} + +// TestChatImageUploaderRejectsUnsupportedAndEmptyPlatformResults 验证图片上传适配器不会吞掉平台能力缺失或空结果。 +func TestChatImageUploaderRejectsUnsupportedAndEmptyPlatformResults(t *testing.T) { + // store 是包含测试 Cookie 的临时数据库,凭证只在适配器调用期间读取。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // unsupportedErr 保存客户端缺少图片上传能力时的稳定错误。 + _, unsupportedErr := NewChatImageUploader(store, func() mtop.Client { return fakeChatIdentityClient{} }, nil).UploadChatImage(context.Background(), "cid", "a.jpg", "image/jpeg", []byte("image")) + if !errors.Is(unsupportedErr, chatapp.ErrUnavailable) { + t.Fatalf("unsupported image client error=%v", unsupportedErr) + } + // emptyErr 保存平台返回空图片结果时的发送错误。 + _, emptyErr := NewChatImageUploader(store, func() mtop.Client { return fakeChatUploadClient{} }, nil).UploadChatImage(context.Background(), "cid", "a.jpg", "image/jpeg", []byte("image")) + if !errors.Is(emptyErr, chatapp.ErrSend) { + t.Fatalf("empty image result error=%v", emptyErr) + } +} + +var _ chatapp.SessionRepository = chatRepository{} +var _ chatapp.IdentityResolver = chatIdentityResolver{} diff --git a/internal/adapter/chat_sending.go b/internal/adapter/chat_sending.go new file mode 100644 index 0000000..b408031 --- /dev/null +++ b/internal/adapter/chat_sending.go @@ -0,0 +1,221 @@ +package adapter + +import ( + "context" + + "xianyu-go/internal/account" + chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/automation" + domainchat "xianyu-go/internal/chat" + "xianyu-go/internal/db" + "xianyu-go/internal/engine" + "xianyu-go/internal/xianyu/mtop" +) + +// chatOutgoingRepository 将聊天领域服务适配为应用层外发消息端口。 +type chatOutgoingRepository struct { + // service 保存聊天消息幂等写入和实时事件发布能力。 + service *domainchat.Service +} + +// NewChatSendingApplication 装配聊天历史、实时发送、图片上传和身份补全端口。 +func NewChatSendingApplication(domainService *domainchat.Service, store *db.Store, manager *account.Manager, clientProvider func() mtop.Client) *chatapp.Service { + return chatapp.NewWithSending( + NewChatRepository(store), + NewChatOutgoingRepository(domainService), + NewChatSenderProvider(manager), + NewChatImageUploader(store, clientProvider, manager), + NewChatIdentityResolver(store, clientProvider), + ) +} + +// NewChatOutgoingRepository 创建聊天外发消息的领域适配器。 +func NewChatOutgoingRepository(service *domainchat.Service) chatapp.OutgoingRepository { + return chatOutgoingRepository{service: service} +} + +// CreateOutgoing 创建文字消息并转换为应用层非敏感模型。 +func (r chatOutgoingRepository) CreateOutgoing(ctx context.Context, session chatapp.Session, text string) (chatapp.Message, error) { + if r.service == nil { + return chatapp.Message{}, chatapp.ErrUnavailable + } + // message、err 保存领域服务返回的消息及写入错误。 + message, err := r.service.CreateOutgoing(ctx, dbChatSession(session), text) + return chatApplicationMessage(message), err +} + +// CreateOutgoingMedia 创建媒体消息并转换为应用层非敏感模型。 +func (r chatOutgoingRepository) CreateOutgoingMedia(ctx context.Context, session chatapp.Session, messageType, content string) (chatapp.Message, error) { + if r.service == nil { + return chatapp.Message{}, chatapp.ErrUnavailable + } + // message、err 保存领域服务返回的媒体消息及写入错误。 + message, err := r.service.CreateOutgoingMedia(ctx, dbChatSession(session), messageType, content) + return chatApplicationMessage(message), err +} + +// SetOutgoingStatus 更新外发消息状态并转换为应用层非敏感模型。 +func (r chatOutgoingRepository) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (chatapp.Message, error) { + if r.service == nil { + return chatapp.Message{}, chatapp.ErrUnavailable + } + // message、err 保存领域服务返回的状态消息及更新错误。 + message, err := r.service.SetOutgoingStatus(ctx, accountID, key, status) + return chatApplicationMessage(message), err +} + +// dbChatSession 将应用层会话摘要转换为领域层写入模型,不携带账号凭证。 +func dbChatSession(session chatapp.Session) db.ChatSession { + return db.ChatSession{ + CookieID: session.AccountID, ChatID: session.ChatID, BuyerID: session.BuyerID, + BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID, + ItemTitle: session.ItemTitle, LastMessage: session.LastMessage, LastMessageAt: session.LastMessageAt, + UnreadCount: session.UnreadCount, + } +} + +// chatApplicationMessage 将领域消息转换为应用层非敏感模型;空指针保持零值。 +func chatApplicationMessage(message *db.ChatMessage) chatapp.Message { + if message == nil { + return chatapp.Message{} + } + return chatapp.Message{ + ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID, MessageKey: message.MessageKey, + Direction: message.Direction, SenderID: message.SenderID, SenderName: message.SenderName, + MessageType: message.MessageType, Content: message.Content, Status: message.Status, SentAt: message.SentAt, + } +} + +// chatSenderProvider 将账号管理器适配为聊天应用的在线发送端口。 +type chatSenderProvider struct { + // manager 保存当前进程内的账号运行时管理器。 + manager *account.Manager +} + +// NewChatSenderProvider 创建按账号解析在线发送器的适配器。 +func NewChatSenderProvider(manager *account.Manager) chatapp.SenderProvider { + return chatSenderProvider{manager: manager} +} + +// Sender 返回指定账号的在线发送能力;账号不存在或运行时未装配时返回 false。 +func (p chatSenderProvider) Sender(accountID string) (chatapp.Sender, bool) { + if p.manager == nil { + return nil, false + } + // sender、ok 保存账号管理器返回的运行时发送器及存在性。 + sender, ok := p.manager.GetInstance(accountID) + if !ok || sender == nil { + return nil, false + } + return chatSender{sender: sender}, true +} + +// chatSender 将自动化消息发送接口收敛为应用聊天端口,并注入幂等键上下文。 +type chatSender struct { + // sender 保存账号运行时提供的最小消息发送能力。 + sender automation.MessageSender +} + +// SendText 发送文字并将应用层幂等键传递给运行时旁路观察器。 +func (s chatSender) SendText(ctx context.Context, chatID, toUserID, text, messageKey string) error { + if s.sender == nil { + return chatapp.ErrUnavailable + } + return s.sender.SendText(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, text) +} + +// SendImage 发送图片并将应用层幂等键传递给运行时接口。 +func (s chatSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, messageKey string) error { + if s.sender == nil { + return chatapp.ErrUnavailable + } + return s.sender.SendImage(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, imageURL, cardID) +} + +// chatCredentialRepository 将 Cookie 读取与写回限制在平台适配器内。 +type chatCredentialRepository struct { + // store 保存数据库聚合入口,仅在适配器内读取和更新明文 Cookie。 + store *db.Store +} + +// getCookieValue 读取图片上传所需的账号凭证;调用方不得记录返回值。 +func (r chatCredentialRepository) getCookieValue(ctx context.Context, accountID string) (string, error) { + if r.store == nil || r.store.Cookies == nil { + return "", chatapp.ErrUnavailable + } + return r.store.Cookies.GetValue(ctx, accountID) +} + +// updateCookieValue 保存图片上传后平台刷新的账号凭证。 +func (r chatCredentialRepository) updateCookieValue(ctx context.Context, accountID, cookieValue string) error { + if r.store == nil || r.store.Cookies == nil { + return chatapp.ErrUnavailable + } + return r.store.Cookies.UpdateValueExisting(ctx, accountID, cookieValue) +} + +// chatImageUploader 将 MTOP 图片上传和凭证刷新适配为聊天应用端口。 +type chatImageUploader struct { + // clientProvider 返回当前可注入的 MTOP 客户端,便于运行时替换和测试。 + clientProvider func() mtop.Client + // credentials 负责在平台刷新后持久化明文凭证,但不向应用层返回。 + credentials chatCredentialRepository + // manager 负责将刷新后的凭证同步到在线运行时。 + manager *account.Manager +} + +// NewChatImageUploader 创建聊天图片上传适配器;平台客户端和数据库依赖由调用方注入。 +func NewChatImageUploader(store *db.Store, clientProvider func() mtop.Client, manager *account.Manager) chatapp.ImageUploader { + return chatImageUploader{clientProvider: clientProvider, credentials: chatCredentialRepository{store: store}, manager: manager} +} + +// UploadChatImage 在适配器内部读取和刷新凭证,只向应用层返回图片地址。 +func (u chatImageUploader) UploadChatImage(ctx context.Context, accountID, filename, contentType string, data []byte) (chatapp.ImageUpload, error) { + if u.clientProvider == nil { + return chatapp.ImageUpload{}, chatapp.ErrUnavailable + } + // cookieValue 和 err 保存平台调用所需的短暂明文凭证及读取错误,不得离开适配器。 + cookieValue, err := u.credentials.getCookieValue(ctx, accountID) + if err != nil { + return chatapp.ImageUpload{}, err + } + // client 保存当前可用的 MTOP 客户端。 + client := u.clientProvider() + // uploader、ok 保存 MTOP 图片上传能力及接口支持情况。 + uploader, ok := client.(interface { + UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error) + }) + if !ok { + return chatapp.ImageUpload{}, chatapp.ErrUnavailable + } + // upload、err 保存图片平台返回结果及调用错误。 + upload, err := uploader.UploadChatImage(ctx, cookieValue, filename, contentType, data) + if err != nil { + return chatapp.ImageUpload{}, err + } + if upload == nil { + return chatapp.ImageUpload{}, chatapp.ErrSend + } + if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookieValue { + // persistErr 保存刷新凭证的持久化错误;该错误必须反馈给调用方,避免静默丢失会话状态。 + if persistErr := u.credentials.updateCookieValue(ctx, accountID, upload.UpdatedCookies); persistErr != nil { + return chatapp.ImageUpload{}, persistErr + } + if u.manager != nil { + // sender、senderOK 保存刷新凭证同步到运行时的结果。 + sender, senderOK := u.manager.GetInstance(accountID) + if senderOK && sender != nil { + sender.UpdateCookie(upload.UpdatedCookies) + } + } + } + return chatapp.ImageUpload{URL: upload.URL}, nil +} + +// 编译期确认聊天实时适配器覆盖应用层定义的全部能力。 +var ( + _ chatapp.OutgoingRepository = chatOutgoingRepository{} + _ chatapp.SenderProvider = chatSenderProvider{} + _ chatapp.Sender = chatSender{} + _ chatapp.ImageUploader = chatImageUploader{} +) diff --git a/internal/adapter/cookie_identity.go b/internal/adapter/cookie_identity.go new file mode 100644 index 0000000..9c01597 --- /dev/null +++ b/internal/adapter/cookie_identity.go @@ -0,0 +1,42 @@ +package adapter + +import ( + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/protocol" +) + +// AccountIDFromCookie 从平台 Cookie 中提取扫码结果使用的账号标识;解析失败返回空字符串。 +func AccountIDFromCookie(cookies string) string { + return protocol.TransCookies(cookies)["unb"] +} + +// CookieSnapshotsFromResult 将扫码服务结果中的浏览器快照转换为应用层模型,避免 Server 依赖 Cookie 实现类型。 +func CookieSnapshotsFromResult(result map[string]any) ([]accountapp.CookieSnapshot, bool) { + // raw 保存扫码结果中的原始 Cookie 快照;exists 表示结果是否提供该字段。 + raw, exists := result["cookie_snapshot"] + if !exists { + return nil, false + } + // snapshot 保存平台 Cookie 快照;ok 表示其类型符合浏览器适配器约定。 + snapshot, ok := raw.([]cookierefresh.BrowserCookie) + if !ok || snapshot == nil { + return nil, false + } + // normalized 保存去重、归一化后的 Cookie 快照。 + normalized := cookierefresh.NormalizeSnapshot(snapshot) + if normalized == nil { + normalized = []cookierefresh.BrowserCookie{} + } + // converted 保存脱离浏览器实现类型的应用层快照。 + converted := make([]accountapp.CookieSnapshot, 0, len(normalized)) + // cookie 表示当前待转换的浏览器 Cookie,明文只在适配器转换期间存在。 + for _, cookie := range normalized { + converted = append(converted, accountapp.CookieSnapshot{ + Name: cookie.Name, Value: cookie.Value, Domain: cookie.Domain, Path: cookie.Path, + Expires: cookie.Expires, HTTPOnly: cookie.HTTPOnly, Secure: cookie.Secure, + SameSite: cookie.SameSite, PartitionKey: cookie.PartitionKey, + }) + } + return converted, true +} diff --git a/internal/adapter/cookie_identity_test.go b/internal/adapter/cookie_identity_test.go new file mode 100644 index 0000000..5097f05 --- /dev/null +++ b/internal/adapter/cookie_identity_test.go @@ -0,0 +1,15 @@ +package adapter + +import "testing" + +// TestAccountIDFromCookie 验证扫码 Cookie 中账号标识的解析及缺失字段行为。 +func TestAccountIDFromCookie(t *testing.T) { + // got 是从完整 Cookie 字符串提取出的平台账号标识。 + if got := AccountIDFromCookie("sid=value; unb=account-1; foo=bar"); got != "account-1" { + t.Fatalf("账号标识解析错误: %q", got) + } + // got 是缺少 unb 字段时的空账号标识结果。 + if got := AccountIDFromCookie("sid=value"); got != "" { + t.Fatalf("缺少 unb 时应返回空字符串: %q", got) + } +} diff --git a/internal/adapter/cookie_session.go b/internal/adapter/cookie_session.go new file mode 100644 index 0000000..df797c5 --- /dev/null +++ b/internal/adapter/cookie_session.go @@ -0,0 +1,79 @@ +package adapter + +import ( + "context" + "errors" + "time" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" +) + +// CookieSession 是一次平台请求流程使用的 Cookie 会话实现别名;Server 通过本适配器访问它,避免直接依赖平台包。 +type CookieSession = mtop.CookieSession + +// BrowserCookie 是浏览器 Cookie 快照的适配器别名,仅用于测试和平台边界转换。 +type BrowserCookie = cookierefresh.BrowserCookie + +// WithCookieSnapshot 为平台请求上下文安装完整 Cookie 快照,并保留权威 Jar 的更新状态。 +func WithCookieSnapshot(ctx context.Context, snapshot []BrowserCookie) (context.Context, *CookieSession) { + return mtop.WithCookieSnapshot(ctx, snapshot) +} + +// WithFlatCookieSession 为历史扁平 Cookie 安装兼容会话,不伪造完整 Jar 属性。 +func WithFlatCookieSession(ctx context.Context, cookies string) (context.Context, *CookieSession) { + return mtop.WithFlatCookieSession(ctx, cookies) +} + +// SnapshotFromMetadata 读取完整 Cookie 快照;解析失败或 metadata 不完整时返回 false。 +func SnapshotFromMetadata(metadata string) ([]BrowserCookie, bool) { + return cookierefresh.SnapshotFromMetadataOK(metadata) +} + +// HasStoredCookieCredential 判断凭证视图是否包含扁平 Cookie 或完整 Cookie 快照。 +func HasStoredCookieCredential(detail *accountapp.CredentialDetail) bool { + if detail == nil { + return false + } + if detail.Value != "" { + return true + } + // complete 表示 metadata 是否包含可用于平台请求的完整快照。 + _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) + return complete +} + +// PersistCookieSessionLocked 持久化平台响应后的 Cookie 会话;调用方必须已持有凭证锁。 +func PersistCookieSessionLocked( + ctx context.Context, + repository accountapp.CredentialRepository, + detail *accountapp.CredentialDetail, + session *CookieSession, +) (value string, valueChanged, handled bool, err error) { + if detail == nil || session == nil { + return "", false, false, nil + } + // value、snapshot、changed 保存平台会话当前 Cookie、完整快照及变更状态。 + value, snapshot, changed := session.State() + if !changed { + if snapshot != nil { + return detail.Value, false, true, nil + } + return "", false, false, nil + } + // metadata 保存去除旧快照或合并新快照后的凭证元数据。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + } + if repository == nil { + return value, value != detail.Value, true, errors.New("cookie 会话持久化 repository 未初始化") + } + // persistErr 保存凭证 Port 写回结果;明文 Cookie 不离开当前适配器调用边界。 + persistErr := repository.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()) + if persistErr != nil { + return value, value != detail.Value, true, persistErr + } + return value, value != detail.Value, true, nil +} diff --git a/internal/adapter/cookie_session_test.go b/internal/adapter/cookie_session_test.go new file mode 100644 index 0000000..a24da2d --- /dev/null +++ b/internal/adapter/cookie_session_test.go @@ -0,0 +1,75 @@ +package adapter + +import ( + "context" + "strings" + "testing" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/xianyu/cookierefresh" +) + +// TestCookieSessionAdapterPersistsAuthoritativeSnapshot 验证平台 Cookie 会话快照经凭证 Port 写回并保留作用域。 +func TestCookieSessionAdapterPersistsAuthoritativeSnapshot(t *testing.T) { + // store、cleanup 保存测试数据库及其资源清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是当前凭证会话测试共用的上下文。 + ctx := context.Background() + // repository 是将 Cookie 写回 SQLite 的账号凭证适配器。 + repository := NewAccountLoginRepository(store) + // detail、loadErr 保存平台调用所需的窄凭证视图及读取错误。 + detail, loadErr := repository.LoadPlatformDetail(ctx, "cid") + if loadErr != nil { + t.Fatalf("读取凭证视图失败: %v", loadErr) + } + // sessionContext、session 保存本次平台流程的 Cookie 会话。 + _, session := WithFlatCookieSession(ctx, detail.Value) + session.ReplaceSnapshot([]BrowserCookie{{Name: "sid", Value: "new", Domain: ".goofish.com", Path: "/"}}) + // value、changed、handled、persistErr 保存会话写回结果及阶段错误。 + value, changed, handled, persistErr := PersistCookieSessionLocked(ctx, repository, detail, session) + if persistErr != nil || !changed || !handled || value == "" { + t.Fatalf("快照写回异常: value=%q changed=%v handled=%v err=%v", value, changed, handled, persistErr) + } + // updated、updatedErr 保存写回后的平台凭证视图。 + updated, updatedErr := repository.LoadPlatformDetail(ctx, detail.ID) + if updatedErr != nil { + t.Fatalf("读取写回凭证失败: %v", updatedErr) + } + // snapshot、complete 保存数据库中快照及完整性标记。 + snapshot, complete := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON) + if !complete || len(snapshot) != 1 || snapshot[0].Value != "new" { + t.Fatalf("快照写回不完整: complete=%v snapshot=%+v", complete, snapshot) + } +} + +// TestCookieSessionAdapterRejectsMissingRepository 验证凭证适配器缺失时不会伪装写回成功。 +func TestCookieSessionAdapterRejectsMissingRepository(t *testing.T) { + // detail 是不含登录密码的最小平台凭证视图。 + detail := &accountapp.CredentialDetail{ID: "cid", Value: "sid=old", MetadataJSON: "{}"} + // ctx、session 保存发生权威快照变化的当前平台会话。 + ctx, session := WithFlatCookieSession(context.Background(), detail.Value) + session.ReplaceSnapshot([]BrowserCookie{{Name: "sid", Value: "new", Domain: ".goofish.com", Path: "/"}}) + // _, changed、handled、persistErr 保存缺失 repository 时的结果。 + _, changed, handled, persistErr := PersistCookieSessionLocked(ctx, nil, detail, session) + if !changed || !handled || persistErr == nil || !strings.Contains(persistErr.Error(), "repository 未初始化") { + t.Fatalf("缺失 repository 错误阶段异常: changed=%v handled=%v err=%v", changed, handled, persistErr) + } +} + +// TestCookieSessionAdapterHasStoredCredential 验证扁平 Cookie 和完整快照均被识别为可用凭证。 +func TestCookieSessionAdapterHasStoredCredential(t *testing.T) { + // flat 是只含扁平 Cookie 的历史平台凭证视图。 + flat := &accountapp.CredentialDetail{Value: "sid=flat"} + if !HasStoredCookieCredential(flat) { + t.Fatal("扁平 Cookie 应被识别为已存储凭证") + } + // snapshotMetadata 是包含完整 Jar 的 metadata。 + snapshotMetadata := cookierefresh.MetadataWithSnapshot(`{}`, []BrowserCookie{{Name: "sid", Value: "snapshot", Domain: ".goofish.com", Path: "/"}}) + if !HasStoredCookieCredential(&accountapp.CredentialDetail{MetadataJSON: snapshotMetadata}) { + t.Fatal("完整 Cookie 快照应被识别为已存储凭证") + } + if HasStoredCookieCredential(nil) { + t.Fatal("空凭证视图不应被识别为已存储凭证") + } +} diff --git a/internal/adapter/database_health.go b/internal/adapter/database_health.go new file mode 100644 index 0000000..8bf0225 --- /dev/null +++ b/internal/adapter/database_health.go @@ -0,0 +1,31 @@ +package adapter + +import ( + "context" + "database/sql" + "errors" + + "xianyu-go/internal/db" +) + +// DatabaseHealth 将数据库连通性探测收口为 Server 健康检查所需的最小适配器。 +type DatabaseHealth struct { + // database 保存待探测的数据库连接;连接生命周期仍由数据库装配方负责关闭。 + database *sql.DB +} + +// NewDatabaseHealth 创建数据库健康检查适配器,缺少 Store 时保留可诊断的空依赖实例。 +func NewDatabaseHealth(store *db.Store) *DatabaseHealth { + if store == nil { + return &DatabaseHealth{} + } + return &DatabaseHealth{database: store.DB} +} + +// Ping 在调用方 Context 限制内探测数据库连接,避免 HTTP 层直接访问 SQL 连接。 +func (health *DatabaseHealth) Ping(ctx context.Context) error { + if health == nil || health.database == nil { + return errors.New("数据库健康检查未初始化") + } + return health.database.PingContext(ctx) +} diff --git a/internal/adapter/database_health_test.go b/internal/adapter/database_health_test.go new file mode 100644 index 0000000..83cf6f7 --- /dev/null +++ b/internal/adapter/database_health_test.go @@ -0,0 +1,42 @@ +package adapter + +import ( + "context" + "testing" + + "xianyu-go/internal/db" +) + +// TestDatabaseHealthRejectsMissingDependency 验证健康检查缺少数据库时不会伪装成功。 +func TestDatabaseHealthRejectsMissingDependency(t *testing.T) { + // health 保存缺少 Store 的数据库健康检查适配器。 + health := NewDatabaseHealth(nil) + // err 保存缺少数据库依赖时的探测错误。 + if err := health.Ping(context.Background()); err == nil { + t.Fatal("缺少数据库时健康检查不应成功") + } +} + +// TestDatabaseHealthPingsDatabase 验证健康检查适配器能够在 Context 内探测 SQLite 连接。 +func TestDatabaseHealthPingsDatabase(t *testing.T) { + // database、dialect 和 openErr 保存临时 SQLite 连接及其方言。 + database, dialect, openErr := db.Open(context.Background(), t.TempDir()+"/health.db") + if openErr != nil { + t.Fatalf("打开测试数据库失败: %v", openErr) + } + defer database.Close() + // health 保存绑定 SQLite 连接的健康检查适配器。 + health := NewDatabaseHealth(db.NewStore(database, dialect)) + // err 保存数据库连接仍可用时的探测错误。 + if err := health.Ping(context.Background()); err != nil { + t.Fatalf("数据库健康检查失败: %v", err) + } + // closeErr 保存关闭数据库后的探测错误,验证故障状态会被上报。 + if closeErr := database.Close(); closeErr != nil { + t.Fatalf("关闭测试数据库失败: %v", closeErr) + } + // err 保存数据库已关闭后的探测错误。 + if err := health.Ping(context.Background()); err == nil { + t.Fatal("关闭数据库后健康检查不应成功") + } +} diff --git a/internal/adapter/default_reply_repository.go b/internal/adapter/default_reply_repository.go new file mode 100644 index 0000000..fb33b05 --- /dev/null +++ b/internal/adapter/default_reply_repository.go @@ -0,0 +1,133 @@ +package adapter + +import ( + "context" + "errors" + + defaultreplyapp "xianyu-go/internal/application/defaultreply" + "xianyu-go/internal/db" +) + +// DefaultReplyRepository 将默认回复数据库仓储适配为应用层消费者定义的 Port。 +type DefaultReplyRepository struct { + // store 保存数据库聚合入口;敏感账号字段只由 Cookies 的非敏感归属方法访问。 + store *db.Store +} + +// NewDefaultReplyRepository 创建默认回复数据库适配器。 +func NewDefaultReplyRepository(store *db.Store) *DefaultReplyRepository { + // repository 保存后续用例调用所需的数据库聚合入口。 + repository := &DefaultReplyRepository{store: store} + return repository +} + +// CheckOwnership 查询账号所有者,并把数据库缺失错误转换为应用错误。 +func (r *DefaultReplyRepository) CheckOwnership(ctx context.Context, userID int64, cookieID string) (defaultreplyapp.AccountOwnership, error) { + // err 表示适配器依赖缺失或账号所有权查询失败的原因。 + if err := r.validate(); err != nil { + return defaultreplyapp.AccountOwnership{}, err + } + // owned 表示账号是否直接属于当前用户;查询不读取账号凭证。 + owned, err := r.store.Cookies.ExistsOwned(ctx, userID, cookieID) + if err != nil { + return defaultreplyapp.AccountOwnership{}, err + } + if owned { + return defaultreplyapp.AccountOwnership{OwnerID: userID}, nil + } + // ownerID 保存账号的非敏感所有者标识,用于区分不存在和跨用户访问。 + ownerID, err := r.store.Cookies.GetOwnerID(ctx, cookieID) + if err != nil { + if errors.Is(err, db.ErrNotFound) { + return defaultreplyapp.AccountOwnership{}, defaultreplyapp.ErrAccountNotFound + } + return defaultreplyapp.AccountOwnership{}, err + } + return defaultreplyapp.AccountOwnership{OwnerID: ownerID}, nil +} + +// Get 读取单个账号默认回复,并隐藏数据库模型与 ErrNotFound 语义。 +func (r *DefaultReplyRepository) Get(ctx context.Context, cookieID string) (defaultreplyapp.Reply, error) { + // err 表示适配器依赖缺失或默认回复读取失败的原因。 + if err := r.validate(); err != nil { + return defaultreplyapp.Reply{}, err + } + // record、err 保存数据库默认回复记录及读取错误。 + record, err := r.store.DefaultReps.Get(ctx, cookieID) + if err != nil { + if errors.Is(err, db.ErrNotFound) { + return defaultreplyapp.Reply{}, defaultreplyapp.ErrConfigNotFound + } + return defaultreplyapp.Reply{}, err + } + return defaultreplyapp.Reply{ + Enabled: record.Enabled, ReplyContent: record.ReplyContent, + ReplyImageURL: record.ReplyImageURL, ReplyOnce: record.ReplyOnce, + }, nil +} + +// Upsert 将应用默认回复模型转换为数据库模型并保存。 +func (r *DefaultReplyRepository) Upsert(ctx context.Context, cookieID string, reply defaultreplyapp.Reply) error { + // err 表示适配器依赖缺失或默认回复写入失败的原因。 + if err := r.validate(); err != nil { + return err + } + return r.store.DefaultReps.Upsert(ctx, cookieID, db.DefaultReply{ + Enabled: reply.Enabled, ReplyContent: reply.ReplyContent, + ReplyImageURL: reply.ReplyImageURL, ReplyOnce: reply.ReplyOnce, + }) +} + +// ListForUser 查询用户默认回复摘要并转换为应用模型。 +func (r *DefaultReplyRepository) ListForUser(ctx context.Context, userID int64) ([]defaultreplyapp.Summary, error) { + // err 表示适配器依赖缺失或默认回复列表查询失败的原因。 + if err := r.validate(); err != nil { + return nil, err + } + // records、err 保存数据库摘要列表及查询错误。 + records, err := r.store.DefaultReps.ListForUser(ctx, userID) + if err != nil { + return nil, err + } + // result 保存不暴露数据库模型的应用层默认回复摘要。 + result := make([]defaultreplyapp.Summary, 0, len(records)) + // record 表示当前待转换的数据库默认回复摘要。 + for _, record := range records { + result = append(result, defaultreplyapp.Summary{ + CookieID: record.CookieID, + Reply: defaultreplyapp.Reply{ + Enabled: record.Enabled, ReplyContent: record.ReplyContent, + ReplyImageURL: record.ReplyImageURL, ReplyOnce: record.ReplyOnce, + }, + }) + } + return result, nil +} + +// Delete 删除指定账号的默认回复配置。 +func (r *DefaultReplyRepository) Delete(ctx context.Context, cookieID string) error { + // err 表示适配器依赖缺失或默认回复删除失败的原因。 + if err := r.validate(); err != nil { + return err + } + return r.store.DefaultReps.Delete(ctx, cookieID) +} + +// ClearRecords 删除指定账号的默认回复投递记录。 +func (r *DefaultReplyRepository) ClearRecords(ctx context.Context, cookieID string) error { + // err 表示适配器依赖缺失或投递记录清理失败的原因。 + if err := r.validate(); err != nil { + return err + } + return r.store.DefaultReps.ClearRecords(ctx, cookieID) +} + +// validate 检查数据库聚合入口及默认回复子仓储是否已装配。 +func (r *DefaultReplyRepository) validate() error { + if r == nil || r.store == nil || r.store.DefaultReps == nil || r.store.Cookies == nil { + return errors.New("默认回复数据库适配器未初始化") + } + return nil +} + +var _ defaultreplyapp.Repository = (*DefaultReplyRepository)(nil) diff --git a/internal/adapter/default_reply_repository_test.go b/internal/adapter/default_reply_repository_test.go new file mode 100644 index 0000000..22acf96 --- /dev/null +++ b/internal/adapter/default_reply_repository_test.go @@ -0,0 +1,117 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + defaultreplyapp "xianyu-go/internal/application/defaultreply" +) + +// TestDefaultReplyRepositoryCRUDMapping 验证默认回复 CRUD 和应用模型之间的字段映射。 +func TestDefaultReplyRepositoryCRUDMapping(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定 SQLite 存储的默认回复数据库适配器。 + repository := NewDefaultReplyRepository(store) + // ctx 是本测试所有数据库操作使用的非取消上下文。 + ctx := context.Background() + // owner 是测试模板中创建的默认管理员用户。 + owner, ownerErr := store.Users.GetByUsername(ctx, "admin") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // ownership、ownershipErr 保存账号所有权 Port 的返回结果。 + ownership, ownershipErr := repository.CheckOwnership(ctx, owner.ID, "cid") + if ownershipErr != nil || ownership.OwnerID != owner.ID { + t.Fatalf("账号归属映射异常 ownership=%+v err=%v", ownership, ownershipErr) + } + // input 是覆盖全部默认回复字段的应用模型。 + input := defaultreplyapp.Reply{Enabled: true, ReplyContent: "你好", ReplyImageURL: "https://example.invalid/reply.png", ReplyOnce: true} + // upsertErr 表示保存默认回复的数据库错误。 + if upsertErr := repository.Upsert(ctx, "cid", input); upsertErr != nil { + t.Fatal(upsertErr) + } + // got、getErr 保存适配器转换后的默认回复模型及查询错误。 + got, getErr := repository.Get(ctx, "cid") + if getErr != nil || got != input { + t.Fatalf("默认回复字段映射异常 got=%+v want=%+v err=%v", got, input, getErr) + } + // listed、listErr 保存按用户隔离的默认回复摘要列表。 + listed, listErr := repository.ListForUser(ctx, owner.ID) + if listErr != nil || len(listed) != 1 || listed[0].CookieID != "cid" || listed[0].Reply != input { + t.Fatalf("默认回复列表映射异常 listed=%+v err=%v", listed, listErr) + } + // updated 是第二次写入的应用模型,用于验证覆盖语义。 + updated := defaultreplyapp.Reply{Enabled: false, ReplyContent: "更新后"} + // updateErr 表示覆盖默认回复的数据库错误。 + if updateErr := repository.Upsert(ctx, "cid", updated); updateErr != nil { + t.Fatal(updateErr) + } + // afterUpdate、afterUpdateErr 保存覆盖后的默认回复模型及查询错误。 + afterUpdate, afterUpdateErr := repository.Get(ctx, "cid") + if afterUpdateErr != nil || afterUpdate != updated { + t.Fatalf("默认回复覆盖异常 got=%+v err=%v", afterUpdate, afterUpdateErr) + } + // clearErr 表示清理默认回复投递记录的数据库错误。 + if clearErr := repository.ClearRecords(ctx, "cid"); clearErr != nil { + t.Fatal(clearErr) + } + // deleteErr 表示删除默认回复的数据库错误。 + if deleteErr := repository.Delete(ctx, "cid"); deleteErr != nil { + t.Fatal(deleteErr) + } + // missingErr 保存删除后读取配置的应用层缺失错误。 + if _, missingErr := repository.Get(ctx, "cid"); !errors.Is(missingErr, defaultreplyapp.ErrConfigNotFound) { + t.Fatalf("删除后应映射为配置缺失,err=%v", missingErr) + } +} + +// TestDefaultReplyRepositoryOwnershipErrors 验证不存在账号和跨用户账号的非敏感归属语义。 +func TestDefaultReplyRepositoryOwnershipErrors(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定 SQLite 存储的默认回复数据库适配器。 + repository := NewDefaultReplyRepository(store) + // ctx 是本测试使用的非取消上下文。 + ctx := context.Background() + // missingErr 保存不存在账号的归属查询错误。 + _, missingErr := repository.CheckOwnership(ctx, 1, "missing-account") + if !errors.Is(missingErr, defaultreplyapp.ErrAccountNotFound) { + t.Fatalf("不存在账号应返回应用缺失错误,err=%v", missingErr) + } + // otherErr 保存跨用户账号的归属查询错误;模板账号 cid 属于管理员。 + other, otherErr := repository.CheckOwnership(ctx, 999, "cid") + if otherErr != nil || other.OwnerID != 1 { + t.Fatalf("跨用户归属应返回真实所有者而非敏感数据 owner=%+v err=%v", other, otherErr) + } +} + +// TestDefaultReplyRepositoryPropagatesInfrastructureErrors 验证数据库不可用时不伪装为业务缺失。 +func TestDefaultReplyRepositoryPropagatesInfrastructureErrors(t *testing.T) { + // store 是随后主动关闭数据库连接的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定已关闭数据库的默认回复适配器。 + repository := NewDefaultReplyRepository(store) + // closeErr 表示主动关闭测试数据库连接时的资源释放错误。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // err 保存数据库关闭后执行默认回复查询的底层错误。 + if _, err := repository.Get(context.Background(), "cid"); err == nil || errors.Is(err, defaultreplyapp.ErrConfigNotFound) { + t.Fatalf("数据库故障应透传而非映射为配置缺失,err=%v", err) + } + // ownershipErr 保存数据库关闭后执行归属查询的底层错误。 + if _, ownershipErr := repository.CheckOwnership(context.Background(), 1, "cid"); ownershipErr == nil { + t.Fatal("数据库故障时归属查询应返回错误") + } + // invalidErr 保存空适配器的装配错误。 + if _, invalidErr := NewDefaultReplyRepository(nil).ListForUser(context.Background(), 1); invalidErr == nil { + t.Fatal("缺少 Store 时应返回适配器装配错误") + } +} + +var _ defaultreplyapp.Repository = (*DefaultReplyRepository)(nil) diff --git a/internal/adapter/item_batch_preview.go b/internal/adapter/item_batch_preview.go new file mode 100644 index 0000000..9ba9ebf --- /dev/null +++ b/internal/adapter/item_batch_preview.go @@ -0,0 +1,97 @@ +package adapter + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" +) + +// ItemBatchPreviewPort 将批量预检所需的非敏感归属与本地路径校验适配到基础设施。 +type ItemBatchPreviewPort struct { + // store 提供账号和卡券归属查询能力。 + store *db.Store +} + +// NewItemBatchPreviewPort 创建批量预检基础设施 Port。 +func NewItemBatchPreviewPort(store *db.Store) *ItemBatchPreviewPort { + return &ItemBatchPreviewPort{store: store} +} + +// CookieOwned 判断账号是否属于用户,不读取或解密 Cookie 内容。 +func (port *ItemBatchPreviewPort) CookieOwned(ctx context.Context, userID int64, cookieID string) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := port.validate(); err != nil { + return false, err + } + return port.store.Cookies.ExistsOwned(ctx, userID, strings.TrimSpace(cookieID)) +} + +// CardOwned 判断卡券组是否属于用户,不向应用层暴露卡券库存内容。 +func (port *ItemBatchPreviewPort) CardOwned(ctx context.Context, userID, cardID int64) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := port.validate(); err != nil { + return false, err + } + return port.store.Cards.ExistsOwned(ctx, cardID, userID) +} + +// ValidateImageReference 校验本地图片路径位于指定上传目录内且对应普通文件。 +func (port *ItemBatchPreviewPort) ValidateImageReference(uploadDir, reference string) error { + _ = port + if isPreviewHTTPURL(reference) { + return nil + } + // relative 和 err 表示清理后的相对路径及安全校验错误。 + relative, err := safePreviewPath(reference) + if err != nil { + return err + } + // path 表示上传根目录下的目标文件路径。 + path := filepath.Join(uploadDir, relative) + // info 和 err 表示文件属性及读取错误。 + info, err := os.Stat(path) + if err != nil || info.IsDir() { + return fmt.Errorf("图片文件不存在: %s", reference) + } + return nil +} + +// validate 检查账号和卡券子仓储是否已装配。 +func (port *ItemBatchPreviewPort) validate() error { + if port == nil || port.store == nil || port.store.Cookies == nil || port.store.Cards == nil { + return errors.New("批量预检数据库适配器未初始化") + } + return nil +} + +// isPreviewHTTPURL 判断图片引用是否为允许的远程 HTTP 地址。 +func isPreviewHTTPURL(reference string) bool { + // value 保存标准化后的远程地址文本。 + value := strings.ToLower(strings.TrimSpace(reference)) + return strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") +} + +// safePreviewPath 清理本地图片路径并拒绝绝对路径和目录穿越。 +func safePreviewPath(raw string) (string, error) { + // value 保存统一路径分隔符后的原始路径。 + value := strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/")) + if value == "" || strings.HasPrefix(value, "/") { + return "", fmt.Errorf("图片路径不安全: %s", value) + } + // clean 保存清理后的相对路径。 + clean := filepath.Clean(value) + if clean == "." || clean == ".." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) { + return "", fmt.Errorf("图片路径不安全: %s", value) + } + return clean, nil +} + +// 确保适配器实现批量预检的所有基础设施 Port。 +var _ itemapp.BatchPreviewOwnershipPort = (*ItemBatchPreviewPort)(nil) +var _ itemapp.BatchPreviewImagePort = (*ItemBatchPreviewPort)(nil) diff --git a/internal/adapter/item_batch_preview_test.go b/internal/adapter/item_batch_preview_test.go new file mode 100644 index 0000000..1f56923 --- /dev/null +++ b/internal/adapter/item_batch_preview_test.go @@ -0,0 +1,60 @@ +package adapter + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// TestItemBatchPreviewPortRejectsMissingStore 验证归属查询在未装配数据库时快速失败。 +func TestItemBatchPreviewPortRejectsMissingStore(t *testing.T) { + // port 是未装配数据库的批量预检适配器。 + port := NewItemBatchPreviewPort(nil) + // err 表示账号归属查询错误。 + if _, err := port.CookieOwned(context.Background(), 1, "acc1"); err == nil { + t.Error("CookieOwned() expected missing store error") + } + // err 表示卡券归属查询错误。 + if _, err := port.CardOwned(context.Background(), 1, 1); err == nil { + t.Error("CardOwned() expected missing store error") + } +} + +// TestItemBatchPreviewPortValidatesImageReferences 验证本地图片路径安全规则和普通文件检查。 +func TestItemBatchPreviewPortValidatesImageReferences(t *testing.T) { + // port 是只使用路径校验能力的批量预检适配器。 + port := NewItemBatchPreviewPort(nil) + // root 是测试上传目录。 + root := t.TempDir() + // imagePath 是测试图片的绝对路径。 + imagePath := filepath.Join(root, "img", "a.png") + // err 表示测试图片目录创建错误。 + if err := os.MkdirAll(filepath.Dir(imagePath), 0o750); err != nil { + t.Fatalf("MkdirAll() error = %v", err) + } + // err 表示测试图片写入错误。 + if err := os.WriteFile(imagePath, []byte("png"), 0o640); err != nil { + t.Fatalf("WriteFile() error = %v", err) + } + // err 表示有效本地图片校验错误。 + if err := port.ValidateImageReference(root, "img/a.png"); err != nil { + t.Fatalf("valid image reference error = %v", err) + } + // err 表示远程图片校验错误。 + if err := port.ValidateImageReference(root, "https://example.com/a.png"); err != nil { + t.Fatalf("remote image reference error = %v", err) + } + // reference 表示当前待拒绝的图片引用。 + for _, reference := range []string{"../a.png", "/tmp/a.png", "missing.png"} { + // err 表示不安全或不存在图片的校验结果。 + if err := port.ValidateImageReference(root, reference); err == nil { + t.Errorf("ValidateImageReference(%q) expected error", reference) + } + } + // err 表示路径穿越校验错误。 + if err := port.ValidateImageReference(root, "../a.png"); !strings.Contains(err.Error(), "图片路径不安全") { + t.Fatalf("path traversal error = %v", err) + } +} diff --git a/internal/adapter/item_batch_publish.go b/internal/adapter/item_batch_publish.go new file mode 100644 index 0000000..a416182 --- /dev/null +++ b/internal/adapter/item_batch_publish.go @@ -0,0 +1,382 @@ +package adapter + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strconv" + "strings" + "time" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" +) + +// ItemBatchPublishPort 将批量发布的 MTOP 调用、凭证会话和远端检查点适配为应用端口。 +type ItemBatchPublishPort struct { + // store 提供批次检查点、平台凭证和 Cookie 会话持久化能力。 + store *db.Store + // client 返回当前批量发布使用的平台客户端,允许测试替换实现。 + client func() mtop.Client + // logger 记录不含凭证明文的会话提交错误。 + logger *slog.Logger + // updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。 + updateRunningCookie func(context.Context, string, string) + // recoverExpiredSession 在平台报告会话失效时触发账号恢复协调。 + recoverExpiredSession func(context.Context, string, error) + // readImage 从受控上传目录读取并校验本地图片。 + readImage ReadPublishImageFile + // downloadImage 下载并校验批量发布使用的远程图片。 + downloadImage DownloadPublishImageURL +} + +// NewItemBatchPublishPort 构造批量发布远端适配器并注入图片安全回调。 +func NewItemBatchPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error), readImage ReadPublishImageFile, downloadImage DownloadPublishImageURL) *ItemBatchPublishPort { + // resolvedLogger 保存可用于记录适配器错误的日志器。 + resolvedLogger := logger + if resolvedLogger == nil { + resolvedLogger = slog.Default() + } + return &ItemBatchPublishPort{store: store, client: client, logger: resolvedLogger, updateRunningCookie: updateRunningCookie, recoverExpiredSession: recoverExpiredSession, readImage: readImage, downloadImage: downloadImage} +} + +// PublishRemoteRow 执行单行商品远端发布并保存远端结果检查点,不写入本地商品或自动化规则。 +func (p *ItemBatchPublishPort) PublishRemoteRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) (itemapp.BatchPublishOutcome, error) { + // validateErr 保存适配器依赖校验错误。 + if validateErr := p.validate(); validateErr != nil { + return itemapp.BatchPublishOutcome{}, validateErr + } + // batch、batchErr 保存按用户隔离后的批次配置。 + batch, batchErr := p.store.PublishBatches.Get(ctx, userID, row.BatchID) + if batchErr != nil || batch == nil { + return itemapp.BatchPublishOutcome{}, errors.New("批量任务不存在") + } + // savedResult 保存已完成远端发布的断点,重试时禁止再次调用平台。 + if strings.TrimSpace(row.ItemID) != "" { + return itemapp.BatchPublishOutcome{Result: batchPublishResultFromRow(row)}, nil + } + // imageDependencyErr 保存新建远端商品所需的图片读取依赖校验错误;已保存检查点的重试已在此前返回。 + if imageDependencyErr := p.validateImageDependencies(); imageDependencyErr != nil { + return itemapp.BatchPublishOutcome{}, imageDependencyErr + } + // location、locationErr 保存批次发货地配置及解析错误。 + location, locationErr := batchPublishLocation(batch.LocationJSON) + if locationErr != nil { + return itemapp.BatchPublishOutcome{}, locationErr + } + // priceCents、priceErr 保存商品售价的分值表示。 + priceCents, priceErr := parseBatchMoneyCents(row.Price) + if priceErr != nil || priceCents <= 0 { + return itemapp.BatchPublishOutcome{}, errors.New("商品价格必须大于 0") + } + // originalPriceCents、postageCents 保存原价和邮费的分值表示。 + originalPriceCents, _ := parseBatchMoneyCents(row.OriginalPrice) + // postageCents 保存邮费的分值表示。 + postageCents, _ := parseBatchMoneyCents(row.Postage) + // preferredCategory 保存批次配置的可选发布类目。 + preferredCategory, categoryErr := batchPublishCategory(row.CategoryJSON) + if categoryErr != nil { + return itemapp.BatchPublishOutcome{}, categoryErr + } + // images、imageErr 保存平台发布需要的本地或远程图片内容。 + images, imageErr := LoadBatchPublishImages(ctx, batch.UploadDir, row.ImagesJSON, p.readImage, p.downloadImage) + if imageErr != nil { + return itemapp.BatchPublishOutcome{}, imageErr + } + // markCtx、markCancel 限制远端开始检查点写入时间,避免租约失效时无限等待。 + markCtx, markCancel := batchPublishStatusContext(ctx) + // remoteStarted、markErr 保存远端开始检查点的写入结果。 + remoteStarted, markErr := p.store.PublishBatches.MarkClaimedRemoteStarted(markCtx, row.ID, workerToken) + markCancel() + if markErr != nil || !remoteStarted { + return itemapp.BatchPublishOutcome{}, fmt.Errorf("保存远端发布前检查点失败: %w", firstBatchError(markErr, itemapp.ErrBatchLeaseLost)) + } + // unlock、latest、loadErr 保存凭证快照读取及其串行化锁释放结果。 + unlock := p.store.LockAccountCredentials(row.CookieID) + // latest、loadErr 保存加锁读取的平台凭证视图及错误。 + latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, row.CookieID) + if loadErr != nil || latest.UserID != userID || !hasStoredCredential(latest) { + unlock() + return itemapp.BatchPublishOutcome{}, errors.New("账号凭证已变化,请重试") + } + // initialValue、initialMetadata 用于远端返回后复核期间的凭证一致性。 + initialValue, initialMetadata := latest.Value, latest.MetadataJSON + // requestCtx、cancel 控制单行远端发布的最长执行时间。 + requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) + // mtopCtx、cookieSession 挂载本次调用使用的 Cookie 会话。 + mtopCtx, cookieSession := withCookieSnapshot(requestCtx, latest) + // unlock 在远端 I/O 前释放,避免凭证锁覆盖慢速平台请求。 + unlock() + // result、callErr 保存平台返回结果及调用错误。 + result, callErr := p.mtopClient().PublishItem(mtopCtx, latest.Value, mtop.PublishItemRequest{ + Title: row.Title, Description: firstBatchNonEmpty(row.Description, row.Title), PriceCents: priceCents, + OriginalPriceCents: originalPriceCents, Quantity: row.Quantity, PostageMode: row.PostageMode, + PostageCents: postageCents, Virtual: true, Location: location, PreferredCategory: preferredCategory, Images: images, + }) + cancel() + // runtimeCookie、persistErr 保存会话写回后的运行时 Cookie 和错误。 + runtimeCookie, persistErr := p.persistBatchSession(ctx, userID, row.CookieID, initialValue, initialMetadata, cookieSession, result, callErr) + if runtimeCookie != "" && p.updateRunningCookie != nil { + p.updateRunningCookie(ctx, row.CookieID, runtimeCookie) + } + if persistErr != nil && callErr != nil { + callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr)) + } + if callErr != nil { + p.recoverExpired(ctx, row.CookieID, callErr) + if ctx.Err() != nil { + return itemapp.BatchPublishOutcome{}, &itemapp.UncertainRemotePublishError{Err: fmt.Errorf("取消时远端发布结果未知: %w", ctx.Err())} + } + // publishErr 保存库存权限等可直接展示的确定性平台错误。 + var publishErr *mtop.PublishError + if errors.As(callErr, &publishErr) && publishErr.Code == mtop.PublishErrorStockPermissionMissing { + return itemapp.BatchPublishOutcome{}, errors.New("该账号没有库存发布权限,无法按库存数量发布商品") + } + if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) { + return itemapp.BatchPublishOutcome{}, callErr + } + return itemapp.BatchPublishOutcome{}, &itemapp.UncertainRemotePublishError{Err: fmt.Errorf("远端发布调用失败且结果未知: %w", callErr)} + } + if result == nil { + return itemapp.BatchPublishOutcome{}, errors.New("发布商品接口未返回结果") + } + // rawJSON 保存远端原始结果,供重试恢复和本地详情持久化使用。 + rawJSON, _ := json.Marshal(result.RawData) + // saveCtx、saveCancel 限制远端结果检查点写入时间。 + saveCtx, saveCancel := batchPublishStatusContext(ctx) + // saved、saveErr 保存远端结果检查点的写入结果。 + saved, saveErr := p.store.PublishBatches.SaveClaimedRemoteResult(saveCtx, row.ID, workerToken, result.ItemID, result.ItemURL, string(rawJSON)) + saveCancel() + if saveErr != nil || !saved { + return itemapp.BatchPublishOutcome{}, &itemapp.UncertainRemotePublishError{Err: fmt.Errorf("保存远端发布结果失败: %w", firstBatchError(saveErr, itemapp.ErrBatchLeaseLost))} + } + // outcome 保存平台结果和已完成远端调用后的 Cookie 后置错误。 + outcome := itemapp.BatchPublishOutcome{Result: batchPublishResultFromMTOP(result)} + if persistErr != nil { + outcome.ResponseCookieErr = persistErr + } + return outcome, nil +} + +// persistBatchSession 在远端调用结束后复核凭证并写回 Cookie 会话变化。 +func (p *ItemBatchPublishPort) persistBatchSession(ctx context.Context, userID int64, cookieID, initialValue, initialMetadata string, session *mtop.CookieSession, result *mtop.PublishItemResult, callErr error) (string, error) { + // unlock 保护远端调用完成后的凭证复核和持久化。 + unlock := p.store.LockAccountCredentials(cookieID) + defer unlock() + // latest、loadErr 保存远端调用完成后的最新平台凭证视图。 + latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) + if loadErr != nil || latest.UserID != userID || latest.Value != initialValue || latest.MetadataJSON != initialMetadata { + return "", errors.New("账号凭证已变化,请重试") + } + // value、valueChanged、handled、persistErr 保存会话持久化状态。 + value, valueChanged, handled, persistErr := persistBatchCookieSession(ctx, p.store, latest, session) + if persistErr != nil { + if p.logger != nil { + p.logger.Error("保存批量发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr) + } + return "", persistErr + } + if handled && valueChanged { + return value, nil + } + if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != latest.Value { + // saveErr 保存平台返回平面 Cookie 的写回错误。 + if saveErr := p.store.Cookies.UpdateValueOwned(ctx, cookieID, result.UpdatedCookies, userID); saveErr != nil { + return "", saveErr + } + return result.UpdatedCookies, nil + } + return "", nil +} + +// persistBatchCookieSession 保存完整 Cookie Jar 或兼容的平面 Cookie 会话。 +func persistBatchCookieSession(ctx context.Context, store *db.Store, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession) (string, bool, bool, error) { + if session == nil { + return "", false, false, nil + } + // value、snapshot、changed 保存平台会话当前状态。 + value, snapshot, changed := session.State() + if !changed { + return detail.Value, false, snapshot != nil, nil + } + // metadata 保存移除旧快照后待写入的新 metadata。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + } + // persistErr 保存 Cookie 会话的加密持久化结果。 + persistErr := store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()) + return value, value != detail.Value, true, persistErr +} + +// validate 检查批量远端适配器所需的数据库、图片和平台依赖。 +func (p *ItemBatchPublishPort) validate() error { + if p == nil || p.store == nil || p.store.Cookies == nil || p.store.PublishBatches == nil { + return errors.New("批量发布远端适配器未初始化") + } + return nil +} + +// validateImageDependencies 检查新建远端商品时必需的图片安全回调。 +func (p *ItemBatchPublishPort) validateImageDependencies() error { + if p.readImage == nil || p.downloadImage == nil { + return errors.New("批量发布图片读取端口未初始化") + } + return nil +} + +// mtopClient 返回当前平台客户端,并在测试构造缺失时提供默认实现。 +func (p *ItemBatchPublishPort) mtopClient() mtop.Client { + if p != nil && p.client != nil { + // resolvedClient 保存回调返回的平台客户端。 + if resolvedClient := p.client(); resolvedClient != nil { + return resolvedClient + } + } + return mtop.NewClient() +} + +// recoverExpired 在平台会话失效时通知账号恢复协调器。 +func (p *ItemBatchPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) { + if p != nil && p.recoverExpiredSession != nil && err != nil { + p.recoverExpiredSession(ctx, cookieID, err) + } +} + +// batchPublishResultFromMTOP 将平台结果转换为不泄露平台类型的应用结果。 +func batchPublishResultFromMTOP(result *mtop.PublishItemResult) *itemapp.BatchPublishResult { + if result == nil { + return nil + } + return &itemapp.BatchPublishResult{ItemID: result.ItemID, ItemURL: result.ItemURL, Title: result.Title, PriceText: result.PriceText, CategoryID: result.CategoryID, CategoryName: result.CategoryName, ImageURL: result.ImageURL, Quantity: result.Quantity, RawData: result.RawData} +} + +// batchPublishResultFromRow 将已有远端检查点转换为应用结果,避免重试重复调用平台。 +func batchPublishResultFromRow(row itemapp.BatchRow) *itemapp.BatchPublishResult { + // rawData 保存已有远端结果的结构化 JSON。 + rawData := map[string]any{} + if strings.TrimSpace(row.RawJSON) != "" { + _ = json.Unmarshal([]byte(row.RawJSON), &rawData) + } + return &itemapp.BatchPublishResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity, RawData: rawData} +} + +// batchPublishLocation 解析批次级别的发货地配置。 +func batchPublishLocation(raw string) (*mtop.PublishLocation, error) { + if strings.TrimSpace(raw) == "" { + raw = "{}" + } + // location 保存批次发货地配置。 + var location mtop.PublishLocation + // decodeErr 保存发货地 JSON 解析错误。 + if decodeErr := json.Unmarshal([]byte(raw), &location); decodeErr != nil { + return nil, errors.New("批量任务发货地配置损坏,请重新创建任务") + } + if strings.TrimSpace(location.DivisionID) == "" { + return nil, nil + } + return &location, nil +} + +// batchPublishCategory 解析批次默认类目并校验平台必需字段。 +func batchPublishCategory(raw string) (*mtop.PublishCategory, error) { + if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" { + return nil, nil + } + // category 保存批次默认类目配置。 + var category mtop.PublishCategory + // decodeErr 保存类目 JSON 解析错误。 + if decodeErr := json.Unmarshal([]byte(raw), &category); decodeErr != nil { + return nil, errors.New("默认类目配置损坏,请重新创建批量任务") + } + if strings.TrimSpace(category.CatID) == "" && strings.TrimSpace(category.CatName) == "" && strings.TrimSpace(category.ChannelCatID) == "" && strings.TrimSpace(category.TBCatID) == "" { + return nil, nil + } + if strings.TrimSpace(category.CatID) == "" || strings.TrimSpace(category.CatName) == "" || strings.TrimSpace(category.ChannelCatID) == "" { + return nil, errors.New("默认类目信息不完整,请重新创建批量任务") + } + return &category, nil +} + +// parseBatchMoneyCents 将用户金额文本转换为平台使用的分值。 +func parseBatchMoneyCents(raw string) (int64, error) { + raw = strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(raw, "¥"), "¥")) + if raw == "" { + return 0, nil + } + // sign、unsigned 保存金额符号和去除符号后的文本。 + sign := int64(1) + // unsigned 保存去除金额符号后的文本。 + unsigned := raw + if strings.HasPrefix(unsigned, "-") { + sign, unsigned = -1, strings.TrimPrefix(unsigned, "-") + } else { + unsigned = strings.TrimPrefix(unsigned, "+") + } + // parts 保存整数和小数部分。 + parts := strings.Split(unsigned, ".") + if len(parts) > 2 { + return 0, errors.New("金额格式错误") + } + // yuan、err 保存元金额及解析错误。 + yuan, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64) + if err != nil { + return 0, err + } + // cents 保存补齐两位小数后的分金额。 + cents := int64(0) + if len(parts) == 2 { + // fraction 保存金额的小数部分。 + fraction := strings.TrimSpace(parts[1]) + if len(fraction) > 2 { + return 0, errors.New("金额最多支持两位小数") + } + for len(fraction) < 2 { + fraction += "0" + } + cents, err = strconv.ParseInt(fraction, 10, 64) + if err != nil { + return 0, err + } + } + return sign * (yuan*100 + cents), nil +} + +// batchPublishStatusContext 为远端检查点写入提供独立的短超时。 +func batchPublishStatusContext(parent context.Context) (context.Context, context.CancelFunc) { + if parent != nil && parent.Err() == nil { + return context.WithTimeout(parent, 5*time.Second) + } + return context.WithTimeout(context.Background(), 5*time.Second) +} + +// firstBatchError 返回第一个有效错误,确保租约错误不会覆盖数据库错误。 +func firstBatchError(err, fallback error) error { + if err != nil { + return err + } + return fallback +} + +// firstBatchNonEmpty 返回候选文本中第一个非空白值。 +func firstBatchNonEmpty(values ...string) string { + // value 表示当前候选文本。 + for _, value := range values { + if strings.TrimSpace(value) != "" { + return value + } + } + return "" +} + +// 确保批量远端适配器实现应用层定义的端口。 +var _ itemapp.BatchPublishPort = (*ItemBatchPublishPort)(nil) + +// IsSessionExpiredError 判断批量发布错误是否要求终止剩余明细并进入账号恢复。 +func IsSessionExpiredError(err error) bool { + return mtop.IsSessionExpiredErr(err) +} diff --git a/internal/adapter/item_batch_publish_test.go b/internal/adapter/item_batch_publish_test.go new file mode 100644 index 0000000..3859a29 --- /dev/null +++ b/internal/adapter/item_batch_publish_test.go @@ -0,0 +1,116 @@ +package adapter + +import ( + "context" + "testing" + "time" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +// batchPublishClientStub 是批量远端发布测试使用的平台客户端替身。 +type batchPublishClientStub struct { + // mtop.Client 提供未涉及本测试的方法默认实现。 + mtop.Client + // publish 保存批量发布请求的可控行为。 + publish func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) +} + +// PublishItem 调用测试注入的批量发布行为。 +func (c batchPublishClientStub) PublishItem(ctx context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) { + return c.publish(ctx, cookies, request) +} + +// TestItemBatchPublishPortPersistsRemoteCheckpoint 验证批量远端端口完成租约检查点和 Cookie 写回。 +func TestItemBatchPublishPortPersistsRemoteCheckpoint(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // admin、adminErr 保存批次所属用户及读取错误。 + admin, adminErr := store.Users.GetByUsername(ctx, "admin") + if adminErr != nil { + t.Fatalf("读取测试用户失败: %v", adminErr) + } + // batch 保存待发布的批次配置。 + batch := &db.ItemPublishBatch{ID: "batch-remote-port", UserID: admin.ID, DefaultCookieID: "cid", UploadDir: t.TempDir(), LocationJSON: `{"division_id":"330100"}`, Status: "pending"} + // rows 保存待发布的单条明细。 + rows := []db.ItemPublishBatchRow{{RowNo: 1, CookieID: "cid", Title: "批量商品", Description: "批量描述", Price: "12.50", Quantity: 2, PostageMode: "free", ImagesJSON: `["a.png"]`, CategoryJSON: `{"cat_id":"1","cat_name":"类目","channel_cat_id":"2"}`, Status: "pending"}} + // createErr 保存批次写入错误。 + if createErr := store.PublishBatches.Create(ctx, batch, rows); createErr != nil { + t.Fatalf("创建测试批次失败: %v", createErr) + } + // lease 保存本次 worker 的有效租约时间。 + lease := time.Now().UTC().Add(time.Minute).Unix() + // claimed、claimErr 保存批次租约抢占结果。 + claimed, claimErr := store.PublishBatches.ClaimBatch(ctx, batch.ID, "worker-remote", lease) + if claimErr != nil || !claimed { + t.Fatalf("抢占批次失败: claimed=%v err=%v", claimed, claimErr) + } + // storedRows、rowsErr 保存抢占后的明细行。 + storedRows, rowsErr := store.PublishBatches.Rows(ctx, batch.ID) + if rowsErr != nil || len(storedRows) != 1 { + t.Fatalf("读取测试明细失败: rows=%+v err=%v", storedRows, rowsErr) + } + // rowClaimed、rowClaimErr 保存明细租约抢占结果。 + rowClaimed, rowClaimErr := store.PublishBatches.ClaimRow(ctx, storedRows[0].ID, "worker-remote") + if rowClaimErr != nil || !rowClaimed { + t.Fatalf("抢占明细失败: claimed=%v err=%v", rowClaimed, rowClaimErr) + } + // publishCalls 记录平台调用次数,用于确认远端检查点重试不会再次创建商品。 + publishCalls := 0 + // client 是返回成功商品和新 Cookie 的平台替身。 + client := batchPublishClientStub{publish: func(_ context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) { + publishCalls++ + if cookies == "" || request.PriceCents != 1250 || request.Quantity != 2 || len(request.Images) != 1 { + t.Fatalf("平台请求字段异常: cookies=%q price=%d quantity=%d images=%d", cookies, request.PriceCents, request.Quantity, len(request.Images)) + } + return &mtop.PublishItemResult{ItemID: "remote-item", ItemURL: "https://example.test/item/remote-item", Title: "批量商品", PriceText: "12.50", Quantity: 2, UpdatedCookies: "unb=2; _m_h5_tk=next"}, nil + }} + // port 是绑定测试数据库、平台替身和图片回调的批量远端适配器。 + port := NewItemBatchPublishPort(store, func() mtop.Client { return client }, nil, nil, nil, + func(_ string, ref string) ([]byte, string, string, error) { + return []byte("image"), "image/png", ref, nil + }, + func(context.Context, string) ([]byte, string, error) { return nil, "", nil }) + // outcome、publishErr 保存远端端口结果及错误。 + outcome, publishErr := port.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(storedRows[0]), "worker-remote") + if publishErr != nil || outcome.Result == nil || outcome.Result.ItemID != "remote-item" { + t.Fatalf("远端端口结果异常: outcome=%+v err=%v", outcome, publishErr) + } + // savedRows、savedErr 保存远端检查点和明细状态。 + savedRows, savedErr := store.PublishBatches.Rows(ctx, batch.ID) + if savedErr != nil || len(savedRows) != 1 || savedRows[0].ItemID != "remote-item" || savedRows[0].FailureKind != "post_publish" { + t.Fatalf("远端检查点未保存: rows=%+v err=%v", savedRows, savedErr) + } + // cookieValue、cookieErr 保存平台响应 Cookie 的持久化结果。 + cookieValue, cookieErr := store.Cookies.GetValue(ctx, "cid") + if cookieErr != nil || cookieValue != "unb=2; _m_h5_tk=next" { + t.Fatalf("响应 Cookie 未写回: value=%q err=%v", cookieValue, cookieErr) + } + // checkpointPort 使用缺少图片回调的适配器,验证已有远端结果可以直接恢复。 + checkpointPort := NewItemBatchPublishPort(store, func() mtop.Client { return client }, nil, nil, nil, nil, nil) + // checkpointOutcome 保存从远端检查点恢复出的应用结果。 + // checkpointErr 保存检查点恢复阶段的错误。 + checkpointOutcome, checkpointErr := checkpointPort.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(savedRows[0]), "worker-remote") + if checkpointErr != nil || checkpointOutcome.Result == nil || checkpointOutcome.Result.ItemID != "remote-item" { + t.Fatalf("远端检查点重试异常: outcome=%+v err=%v", checkpointOutcome, checkpointErr) + } + if publishCalls != 1 { + t.Fatalf("远端检查点重试不应再次调用平台: calls=%d", publishCalls) + } +} + +// TestItemBatchPublishPortRejectsMissingDependencies 验证批量远端适配器缺少端口依赖时快速失败。 +func TestItemBatchPublishPortRejectsMissingDependencies(t *testing.T) { + // port 是未配置数据库的批量远端适配器。 + port := NewItemBatchPublishPort(nil, nil, nil, nil, nil, func(string, string) ([]byte, string, string, error) { return nil, "", "", nil }, func(context.Context, string) ([]byte, string, error) { return nil, "", nil }) + // _, publishErr 保存依赖校验错误。 + _, publishErr := port.PublishRemoteRow(context.Background(), 1, itemapp.BatchRow{BatchID: "batch"}, "worker") + if publishErr == nil { + t.Fatal("缺少数据库时不应伪装批量远端发布成功") + } +} diff --git a/internal/adapter/item_batch_repository.go b/internal/adapter/item_batch_repository.go new file mode 100644 index 0000000..a897286 --- /dev/null +++ b/internal/adapter/item_batch_repository.go @@ -0,0 +1,414 @@ +package adapter + +import ( + "context" + "encoding/json" + "errors" + "os" + "strings" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" +) + +// ItemBatchRepository 将商品批量发布数据库仓储适配为应用层 worker Port。 +type ItemBatchRepository struct { + // store 保存数据库聚合入口;批量 worker 不会接触该字段。 + store *db.Store +} + +// NewItemBatchRepository 构造商品批量发布 worker 的数据库适配器。 +func NewItemBatchRepository(store *db.Store) *ItemBatchRepository { + return &ItemBatchRepository{store: store} +} + +// CreateBatch 将应用预检模型转换为数据库批次并在单事务内写入。 +func (r *ItemBatchRepository) CreateBatch(ctx context.Context, batch itemapp.BatchPreviewPersistenceBatch, rows []itemapp.BatchPreviewRow) error { + // err 表示批次仓储依赖校验错误。 + if err := r.validate(); err != nil { + return err + } + // locationJSON 和 err 分别保存发货地 JSON 与序列化错误。 + locationJSON, err := json.Marshal(batch.Location) + if err != nil { + return err + } + // status 保存未显式指定时兼容预检批次的默认状态。 + status := batch.Status + if strings.TrimSpace(status) == "" { + status = "preview" + } + // databaseRows 保存转换后的数据库明细行。 + databaseRows := make([]db.ItemPublishBatchRow, 0, len(rows)) + // row 表示当前待转换的应用预检行。 + for _, row := range rows { + // imagesJSON 和 imagesErr 分别保存图片字段 JSON 与序列化错误。 + imagesJSON, imagesErr := json.Marshal(row.Images) + if imagesErr != nil { + return imagesErr + } + // categoryJSON 和 categoryErr 分别保存类目字段 JSON 与序列化错误。 + categoryJSON, categoryErr := json.Marshal(row.Category) + if categoryErr != nil { + return categoryErr + } + // automationJSON 和 automationErr 分别保存自动化字段 JSON 与序列化错误。 + automationJSON, automationErr := json.Marshal(row.Automation) + if automationErr != nil { + return automationErr + } + // rawJSON 和 rawErr 分别保存原始行 JSON 与序列化错误。 + rawJSON, rawErr := json.Marshal(row.Raw) + if rawErr != nil { + return rawErr + } + // status、errorMessage 和 failureKind 保存数据库状态、展示错误与失败分类。 + status, errorMessage, failureKind := "pending", "", "" + if len(row.Errors) > 0 { + status, errorMessage, failureKind = "failed", strings.Join(row.Errors, ";"), "validation" + } + databaseRows = append(databaseRows, db.ItemPublishBatchRow{ + RowNo: row.RowNo, CookieID: row.CookieID, Title: row.Title, Description: row.Description, + Price: row.Price, OriginalPrice: row.OriginalPrice, Quantity: row.Quantity, + PostageMode: row.PostageMode, Postage: row.Postage, ImagesJSON: string(imagesJSON), + CategoryJSON: string(categoryJSON), AutomationJSON: string(automationJSON), Status: status, + ErrorMessage: errorMessage, FailureKind: failureKind, RawJSON: string(rawJSON), + }) + } + return r.store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ID: batch.ID, UserID: batch.UserID, DefaultCookieID: batch.DefaultCookieID, Filename: batch.Filename, UploadDir: batch.UploadDir, LocationJSON: string(locationJSON), Status: status}, databaseRows) +} + +// PendingRows 查询批次待处理明细并转换为应用模型。 +func (r *ItemBatchRepository) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]itemapp.BatchRow, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return nil, err + } + // rows 保存数据库仓储返回的批量明细。 + rows, err := r.store.PublishBatches.PendingRows(ctx, batchID, failedOnly) + if err != nil { + return nil, err + } + // result 保存不暴露数据库类型的应用批量明细。 + result := make([]itemapp.BatchRow, 0, len(rows)) + // row 表示当前待转换的数据库批次明细。 + for _, row := range rows { + result = append(result, batchRowApplicationModel(row)) + } + return result, nil +} + +// RenewBatchLease 委托数据库延长当前 worker 的批次租约。 +func (r *ItemBatchRepository) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.RenewBatchLease(ctx, batchID, workerToken, leaseExpiresAt) +} + +// GetBatch 查询批次并转换为应用状态模型。 +func (r *ItemBatchRepository) GetBatch(ctx context.Context, userID int64, batchID string) (itemapp.BatchInfo, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return itemapp.BatchInfo{}, err + } + // batch 保存按用户隔离后的数据库批次。 + batch, err := r.store.PublishBatches.Get(ctx, userID, batchID) + if err != nil { + return itemapp.BatchInfo{}, err + } + return batchInfoApplicationModel(*batch), nil +} + +// ListBatchesForUser 查询用户批次摘要并转换为应用模型。 +func (r *ItemBatchRepository) ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]itemapp.BatchInfo, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return nil, err + } + // batches 保存数据库返回的用户批次。 + batches, err := r.store.PublishBatches.ListForUser(ctx, userID, limit) + if err != nil { + return nil, err + } + // result 保存不暴露数据库模型的应用批次摘要。 + result := make([]itemapp.BatchInfo, 0, len(batches)) + // batch 表示当前待转换的数据库批次。 + for _, batch := range batches { + result = append(result, batchInfoApplicationModel(batch)) + } + return result, nil +} + +// ListBatchRows 查询批次全部明细并转换为应用模型。 +func (r *ItemBatchRepository) ListBatchRows(ctx context.Context, batchID string) ([]itemapp.BatchRow, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return nil, err + } + // rows 保存数据库返回的批次明细。 + rows, err := r.store.PublishBatches.Rows(ctx, batchID) + if err != nil { + return nil, err + } + // result 保存不暴露数据库模型的应用批次明细。 + result := make([]itemapp.BatchRow, 0, len(rows)) + // row 表示当前待转换的数据库明细。 + for _, row := range rows { + result = append(result, batchRowApplicationModel(row)) + } + return result, nil +} + +// ExpiredUploadBatches 查询已超过上传目录保留期限的批次并转换为应用模型。 +func (r *ItemBatchRepository) ExpiredUploadBatches(ctx context.Context, cutoff string, limit int) ([]itemapp.BatchInfo, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return nil, err + } + // batches 保存数据库返回的过期上传批次。 + batches, err := r.store.PublishBatches.ExpiredUploads(ctx, cutoff, limit) + if err != nil { + return nil, err + } + // result 保存不暴露数据库模型的应用批次状态。 + result := make([]itemapp.BatchInfo, 0, len(batches)) + // batch 表示当前待转换的过期批次。 + for _, batch := range batches { + result = append(result, batchInfoApplicationModel(batch)) + } + return result, nil +} + +// RequestCancel 请求批次进入取消状态。 +func (r *ItemBatchRepository) RequestCancel(ctx context.Context, batchID string) (string, bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return "", false, err + } + // token、running、requestErr 保存数据库取消请求的结果。 + token, running, requestErr := r.store.PublishBatches.RequestCancel(ctx, batchID) + if errors.Is(requestErr, db.ErrPublishBatchChanged) { + return "", false, itemapp.ErrBatchConflict + } + return token, running, requestErr +} + +// DeleteBatch 删除用户拥有的批次及其受控上传目录。 +func (r *ItemBatchRepository) DeleteBatch(ctx context.Context, userID int64, batchID string) error { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return err + } + // batch 保存删除前的上传目录,路径只在适配器内使用。 + batch, err := r.store.PublishBatches.Get(ctx, userID, batchID) + if err != nil { + return err + } + // err 表示数据库批次及其上传目录删除错误。 + if err := r.store.PublishBatches.Delete(ctx, userID, batchID); err != nil { + return err + } + if batch != nil && batch.UploadDir != "" { + return os.RemoveAll(batch.UploadDir) + } + return nil +} + +// ResetFailed 重置批次中的可重试失败明细。 +func (r *ItemBatchRepository) ResetFailed(ctx context.Context, batchID string) error { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return err + } + return r.store.PublishBatches.ResetFailed(ctx, batchID) +} + +// FailClaimedBatch 释放当前 worker 持有的批次租约。 +func (r *ItemBatchRepository) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.FailClaimedBatch(ctx, batchID, workerToken) +} + +// RecoverableBatches 查询可恢复批次并转换为应用层状态模型。 +func (r *ItemBatchRepository) RecoverableBatches(ctx context.Context, now int64, limit int) ([]itemapp.BatchInfo, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return nil, err + } + // batches 保存数据库返回的可恢复批次。 + batches, err := r.store.PublishBatches.Recoverable(ctx, now, limit) + if err != nil { + return nil, err + } + // result 保存不暴露数据库类型的应用批次状态。 + result := make([]itemapp.BatchInfo, 0, len(batches)) + // batch 表示当前待转换的数据库批次。 + for _, batch := range batches { + result = append(result, batchInfoApplicationModel(batch)) + } + return result, nil +} + +// FinalizeExpiredCancellation 收口已经超过租约截止时间的取消请求。 +func (r *ItemBatchRepository) FinalizeExpiredCancellation(ctx context.Context, batchID string, now int64) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.FinalizeExpiredCancellation(ctx, batchID, now) +} + +// ClaimBatch 抢占批次恢复租约并返回是否成功。 +func (r *ItemBatchRepository) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.ClaimBatch(ctx, batchID, workerToken, leaseExpiresAt) +} + +// ResetInterrupted 重置可确认由进程中断造成的失败明细。 +func (r *ItemBatchRepository) ResetInterrupted(ctx context.Context, batchID string) error { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return err + } + return r.store.PublishBatches.ResetInterrupted(ctx, batchID) +} + +// ClaimRow 抢占单条批次明细的 worker 租约。 +func (r *ItemBatchRepository) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.ClaimRow(ctx, rowID, workerToken) +} + +// BatchStatus 读取批次状态供应用层决定失败分类。 +func (r *ItemBatchRepository) BatchStatus(ctx context.Context, batchID string) (string, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return "", err + } + return r.store.PublishBatches.BatchStatus(ctx, batchID) +} + +// MarkClaimedRowFailed 保存当前 worker 持有明细的失败结果。 +func (r *ItemBatchRepository) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.MarkClaimedRowFailed(ctx, rowID, workerToken, message, kind) +} + +// MarkClaimedRowSuccess 保存当前 worker 持有明细的远端成功结果。 +func (r *ItemBatchRepository) MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.MarkClaimedRowSuccess(ctx, rowID, workerToken, itemID, itemURL, rawJSON) +} + +// RecountBatch 重算批次的成功与失败统计。 +func (r *ItemBatchRepository) RecountBatch(ctx context.Context, batchID string) error { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return err + } + return r.store.PublishBatches.Recount(ctx, batchID) +} + +// FinalizeBatch 尝试收口当前 worker 完成的批次。 +func (r *ItemBatchRepository) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return "", false, err + } + return r.store.PublishBatches.FinalizeBatch(ctx, batchID, workerToken) +} + +// FinalizeCanceled 收口当前 worker 持有的取消批次。 +func (r *ItemBatchRepository) FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return false, err + } + return r.store.PublishBatches.FinalizeCanceled(ctx, batchID, workerToken) +} + +// FinalizeInterrupted 收口被取消或租约中断的批次。 +func (r *ItemBatchRepository) FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return "", false, err + } + return r.store.PublishBatches.FinalizeInterrupted(ctx, batchID, workerToken, message) +} + +// DeleteUpload 删除批次上传目录并清除数据库中的目录记录。 +func (r *ItemBatchRepository) DeleteUpload(ctx context.Context, batchID, uploadDir string) error { + // err 表示适配器依赖校验错误。 + if err := r.validate(); err != nil { + return err + } + if uploadDir == "" { + return nil + } + // removeErr 保存上传目录删除结果;即使删除失败也继续清理数据库记录。 + removeErr := os.RemoveAll(uploadDir) + // clearErr 保存数据库上传目录字段清理结果。 + clearErr := r.store.PublishBatches.ClearUploadDir(ctx, batchID) + if removeErr != nil { + return removeErr + } + return clearErr +} + +// validate 检查批量发布数据库适配器的必需依赖。 +func (r *ItemBatchRepository) validate() error { + if r == nil || r.store == nil || r.store.PublishBatches == nil { + return errors.New("商品批量发布数据库适配器未初始化") + } + return nil +} + +// batchRowApplicationModel 将数据库明细完整转换为应用层批量明细。 +func batchRowApplicationModel(row db.ItemPublishBatchRow) itemapp.BatchRow { + return itemapp.BatchRow{ + ID: row.ID, BatchID: row.BatchID, RowNo: row.RowNo, CookieID: row.CookieID, + Title: row.Title, Description: row.Description, Price: row.Price, OriginalPrice: row.OriginalPrice, + Quantity: row.Quantity, PostageMode: row.PostageMode, Postage: row.Postage, + ImagesJSON: row.ImagesJSON, CategoryJSON: row.CategoryJSON, AutomationJSON: row.AutomationJSON, + RawJSON: row.RawJSON, ItemID: row.ItemID, ItemURL: row.ItemURL, Status: row.Status, + ErrorMessage: row.ErrorMessage, FailureKind: row.FailureKind, WorkerToken: row.WorkerToken, + CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, + } +} + +// batchInfoApplicationModel 将数据库批次完整转换为应用层批次状态。 +func batchInfoApplicationModel(batch db.ItemPublishBatch) itemapp.BatchInfo { + return itemapp.BatchInfo{ + ID: batch.ID, UserID: batch.UserID, Status: batch.Status, WorkerToken: batch.WorkerToken, + DefaultCookieID: batch.DefaultCookieID, Filename: batch.Filename, UploadDir: batch.UploadDir, + LocationJSON: batch.LocationJSON, TotalCount: batch.TotalCount, SuccessCount: batch.SuccessCount, + FailedCount: batch.FailedCount, LeaseExpiresAt: batch.LeaseExpiresAt, + CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt, + } +} + +// 确保适配器覆盖批量发布 worker 的全部持久化端口。 +var _ itemapp.BatchRepository = (*ItemBatchRepository)(nil) + +// 确保适配器覆盖批次管理应用服务的全部持久化端口。 +var _ itemapp.BatchManagementRepository = (*ItemBatchRepository)(nil) + +// 确保适配器实现批量恢复扫描所需的状态端口。 +var _ itemapp.BatchRecoveryRepository = (*ItemBatchRepository)(nil) diff --git a/internal/adapter/item_batch_repository_test.go b/internal/adapter/item_batch_repository_test.go new file mode 100644 index 0000000..49037c1 --- /dev/null +++ b/internal/adapter/item_batch_repository_test.go @@ -0,0 +1,165 @@ +package adapter + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" +) + +// TestItemBatchRepositoryCreatesPreviewFromApplicationModels 验证预检应用模型到数据库字段的转换。 +func TestItemBatchRepositoryCreatesPreviewFromApplicationModels(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // repository 是绑定测试数据库的预检批次适配器。 + repository := NewItemBatchRepository(store) + // expectedRaw 保存预检行原始输入,验证 JSON 边界不会丢失字段。 + expectedRaw := map[string]any{"title": "应用模型商品"} + // rows 保存一条有效行和一条校验失败行。 + rows := []itemapp.BatchPreviewRow{ + {RowNo: 2, CookieID: "cid", Title: "应用模型商品", Price: "10", Quantity: 2, Raw: expectedRaw, Category: itemapp.BatchPreviewCategory{CatID: "cat-1"}}, + {RowNo: 3, CookieID: "cid", Title: "失败商品", Errors: []string{"标题错误"}}, + } + // batch 保存应用层批次元数据。 + batch := itemapp.BatchPreviewPersistenceBatch{ID: "preview-adapter", UserID: 1, DefaultCookieID: "cid", Filename: "items.csv", UploadDir: t.TempDir(), Location: itemapp.Location{DivisionID: "3301"}} + // err 保存应用模型落库错误。 + if err := repository.CreateBatch(ctx, batch, rows); err != nil { + t.Fatalf("创建预检批次失败: %v", err) + } + // storedBatch、batchErr 保存数据库批次读取结果。 + storedBatch, batchErr := store.PublishBatches.Get(ctx, 1, batch.ID) + if batchErr != nil || storedBatch.Status != "preview" || storedBatch.LocationJSON == "{}" { + t.Fatalf("批次字段映射异常: batch=%+v err=%v", storedBatch, batchErr) + } + // storedRows、rowsErr 保存数据库明细读取结果。 + storedRows, rowsErr := store.PublishBatches.Rows(ctx, batch.ID) + if rowsErr != nil || len(storedRows) != 2 || storedRows[1].Status != "failed" || storedRows[1].FailureKind != "validation" { + t.Fatalf("明细状态映射异常: rows=%+v err=%v", storedRows, rowsErr) + } + // decodedRaw 保存读取后的原始 JSON 对象。 + decodedRaw := map[string]any{} + if json.Unmarshal([]byte(storedRows[0].RawJSON), &decodedRaw) != nil || decodedRaw["title"] != expectedRaw["title"] { + t.Fatalf("原始字段 JSON 映射异常: %s", storedRows[0].RawJSON) + } +} + +// TestItemBatchRepositoryRejectsMissingStore 验证批量 worker 适配器缺少数据库时快速失败。 +func TestItemBatchRepositoryRejectsMissingStore(t *testing.T) { + // repository 保存未装配数据库的批量仓储适配器。 + repository := NewItemBatchRepository(nil) + // ctx 是本测试使用的非取消上下文。 + ctx := context.Background() + // rowsErr 保存待处理明细查询的装配错误。 + if _, rowsErr := repository.PendingRows(ctx, "batch-1", false); rowsErr == nil { + t.Fatal("缺少数据库时 PendingRows 不应伪装成功") + } + // batchErr 保存批次查询的装配错误。 + if _, batchErr := repository.GetBatch(ctx, 1, "batch-1"); batchErr == nil { + t.Fatal("缺少数据库时 GetBatch 不应伪装成功") + } + // deleteErr 保存上传目录清理的装配错误。 + if deleteErr := repository.DeleteUpload(ctx, "batch-1", "upload"); deleteErr == nil { + t.Fatal("缺少数据库时 DeleteUpload 不应伪装成功") + } +} + +// TestItemBatchRepositoryMapsAndCleansBatch 验证批次行和状态完整映射及上传目录清理。 +func TestItemBatchRepositoryMapsAndCleansBatch(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // admin、adminErr 保存测试用户及读取错误。 + admin, adminErr := store.Users.GetByUsername(ctx, "admin") + if adminErr != nil { + t.Fatalf("读取测试用户失败: %v", adminErr) + } + // uploadDir 是批次上传目录的临时路径。 + uploadDir := filepath.Join(t.TempDir(), "batch-upload") + // err 保存创建上传目录的错误。 + if err := os.MkdirAll(uploadDir, 0o750); err != nil { + t.Fatalf("创建上传目录失败: %v", err) + } + // batch 保存待适配的数据库批次。 + batch := &db.ItemPublishBatch{ + ID: "batch-adapter", UserID: admin.ID, DefaultCookieID: "cid", Filename: "items.csv", + UploadDir: uploadDir, LocationJSON: `{"area":"杭州"}`, Status: "running", + } + // rows 保存待适配的批次明细。 + rows := []db.ItemPublishBatchRow{{ + RowNo: 2, CookieID: "cid", Title: "标题", Description: "描述", Price: "12.00", + OriginalPrice: "15.00", Quantity: 3, PostageMode: "free", Postage: "0", + ImagesJSON: `["a.jpg"]`, CategoryJSON: `{"cat_id":"1"}`, AutomationJSON: `{"enabled":true}`, + Status: "pending", ItemID: "item-1", ItemURL: "https://example/item-1", ErrorMessage: "", + FailureKind: "", WorkerToken: "worker", RawJSON: `{"ok":true}`, + }} + // err 保存创建测试批次的错误。 + if err := store.PublishBatches.Create(ctx, batch, rows); err != nil { + t.Fatalf("创建测试批次失败: %v", err) + } + // repository 是绑定测试数据库的应用 Port 适配器。 + repository := NewItemBatchRepository(store) + // pending、pendingErr 保存应用层待处理明细及查询错误。 + pending, pendingErr := repository.PendingRows(ctx, batch.ID, false) + if pendingErr != nil || len(pending) != 1 { + t.Fatalf("读取待处理明细异常:rows=%+v err=%v", pending, pendingErr) + } + // row 保存已转换的应用明细。 + row := pending[0] + if row.RowNo != 2 || row.Title != "标题" || row.ItemID != "item-1" || row.RawJSON != `{"ok":true}` { + t.Fatalf("批次明细映射不完整:%+v", row) + } + // gotBatch、batchErr 保存应用层批次状态及查询错误。 + gotBatch, batchErr := repository.GetBatch(ctx, admin.ID, batch.ID) + if batchErr != nil || gotBatch.ID != batch.ID || gotBatch.UserID != admin.ID || gotBatch.UploadDir != uploadDir || gotBatch.LocationJSON != batch.LocationJSON { + t.Fatalf("批次状态映射异常:batch=%+v err=%v", gotBatch, batchErr) + } + // updateErr 保存将批次置为过期状态的测试更新结果。 + _, updateErr := store.DB.ExecContext(ctx, `UPDATE item_publish_batches SET status='completed',updated_at='2000-01-01 00:00:00' WHERE id=?`, batch.ID) + if updateErr != nil { + t.Fatalf("设置过期批次失败: %v", updateErr) + } + // expired、expiredErr 保存过期上传批次查询结果。 + expired, expiredErr := repository.ExpiredUploadBatches(ctx, "2020-01-01 00:00:00", 10) + if expiredErr != nil || len(expired) != 1 || expired[0].ID != batch.ID || expired[0].UploadDir != uploadDir { + t.Fatalf("过期上传批次映射异常:batches=%+v err=%v", expired, expiredErr) + } + // deleteErr 保存上传目录与数据库字段清理结果。 + if deleteErr := repository.DeleteUpload(ctx, batch.ID, uploadDir); deleteErr != nil { + t.Fatalf("清理上传目录失败: %v", deleteErr) + } + // statErr 保存确认上传目录已删除的文件系统错误。 + if _, statErr := os.Stat(uploadDir); !os.IsNotExist(statErr) { + t.Fatalf("上传目录仍存在:err=%v", statErr) + } + // clearedBatch、clearedErr 保存清理后的批次记录。 + clearedBatch, clearedErr := store.PublishBatches.Get(ctx, admin.ID, batch.ID) + if clearedErr != nil || clearedBatch.UploadDir != "" { + t.Fatalf("数据库上传目录未清理:batch=%+v err=%v", clearedBatch, clearedErr) + } +} + +// TestBatchRowApplicationModelPreservesSensitiveFreeBusinessFields 验证明细转换保留业务字段且不引入凭证字段。 +func TestBatchRowApplicationModelPreservesSensitiveFreeBusinessFields(t *testing.T) { + // source 保存带有完整业务字段的数据库明细。 + source := db.ItemPublishBatchRow{ + ID: 4, BatchID: "b", RowNo: 7, CookieID: "cid", Title: "标题", Description: "描述", + Price: "1", OriginalPrice: "2", Quantity: 4, PostageMode: "buyer", Postage: "3", + ImagesJSON: "[]", CategoryJSON: "{}", AutomationJSON: "{}", Status: "failed", ItemID: "i", + ItemURL: "u", ErrorMessage: "失败", FailureKind: "publish", WorkerToken: "w", + RawJSON: "{}", CreatedAt: "created", UpdatedAt: "updated", + } + // converted 保存转换后的应用明细。 + converted := batchRowApplicationModel(source) + if converted.ID != source.ID || converted.BatchID != source.BatchID || converted.RowNo != source.RowNo || converted.CookieID != source.CookieID || converted.Title != source.Title || converted.Description != source.Description || converted.Price != source.Price || converted.OriginalPrice != source.OriginalPrice || converted.Quantity != source.Quantity || converted.PostageMode != source.PostageMode || converted.Postage != source.Postage || converted.ImagesJSON != source.ImagesJSON || converted.CategoryJSON != source.CategoryJSON || converted.AutomationJSON != source.AutomationJSON || converted.Status != source.Status || converted.ItemID != source.ItemID || converted.ItemURL != source.ItemURL || converted.ErrorMessage != source.ErrorMessage || converted.FailureKind != source.FailureKind || converted.WorkerToken != source.WorkerToken || converted.RawJSON != source.RawJSON || converted.CreatedAt != source.CreatedAt || converted.UpdatedAt != source.UpdatedAt { + t.Fatalf("明细字段未完整转换:source=%+v converted=%+v", source, converted) + } +} diff --git a/internal/adapter/item_catalog.go b/internal/adapter/item_catalog.go new file mode 100644 index 0000000..1a57345 --- /dev/null +++ b/internal/adapter/item_catalog.go @@ -0,0 +1,124 @@ +package adapter + +import ( + "context" + "errors" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" +) + +// ItemCatalogRepository 将商品读取 Port 适配到数据库商品仓储。 +type ItemCatalogRepository struct { + // store 提供商品查询能力。 + store *db.Store +} + +// NewItemCatalogRepository 创建商品读取数据库适配器。 +func NewItemCatalogRepository(store *db.Store) *ItemCatalogRepository { + return &ItemCatalogRepository{store: store} +} + +// ListForUser 查询用户范围商品并转换为应用模型。 +func (repository *ItemCatalogRepository) ListForUser(ctx context.Context, userID int64, cookieID string) ([]itemapp.CatalogItem, error) { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return nil, errors.New("商品读取存储未初始化") + } + // rows 和 err 保存用户范围商品行及查询错误。 + rows, err := repository.store.Items.ListForUser(ctx, userID, cookieID) + if err != nil { + return nil, err + } + return catalogItemsFromRows(rows), nil +} + +// ListByCookie 查询账号商品并转换为应用模型。 +func (repository *ItemCatalogRepository) ListByCookie(ctx context.Context, cookieID string) ([]itemapp.CatalogItem, error) { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return nil, errors.New("商品读取存储未初始化") + } + // rows 和 err 保存账号商品行及查询错误。 + rows, err := repository.store.Items.AllForCookie(ctx, cookieID) + if err != nil { + return nil, err + } + return catalogItemsFromRows(rows), nil +} + +// Get 查询单个商品并转换为应用模型。 +func (repository *ItemCatalogRepository) Get(ctx context.Context, cookieID, itemID string) (itemapp.CatalogItem, error) { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return itemapp.CatalogItem{}, errors.New("商品读取存储未初始化") + } + // row 和 err 保存单个商品行及查询错误。 + row, err := repository.store.Items.Get(ctx, cookieID, itemID) + if err != nil { + if errors.Is(err, db.ErrNotFound) { + return itemapp.CatalogItem{}, itemapp.ErrCatalogNotFound + } + return itemapp.CatalogItem{}, err + } + return itemapp.CatalogItem{ID: row.ID, CookieID: row.CookieID, ItemID: row.ItemID, ItemTitle: row.ItemTitle, ItemDescription: row.ItemDescription, ItemCategory: row.ItemCategory, ItemPrice: row.ItemPrice, ItemDetail: row.ItemDetail, IsMultiSpec: row.IsMultiSpec, MultiQuantityDelivery: row.MultiQuantityDelivery}, nil +} + +// Upsert 创建或完整保存本地商品,并将应用输入转换为数据库行模型。 +func (repository *ItemCatalogRepository) Upsert(ctx context.Context, cookieID string, input itemapp.CatalogWriteInput) error { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return errors.New("商品写入存储未初始化") + } + return repository.store.Items.Upsert(ctx, &db.ItemInfoRow{ + CookieID: cookieID, ItemID: input.ItemID, ItemTitle: input.ItemTitle, ItemDescription: input.ItemDescription, + ItemCategory: input.ItemCategory, ItemPrice: input.ItemPrice, ItemDetail: input.ItemDetail, + IsMultiSpec: input.IsMultiSpec, MultiQuantityDelivery: input.MultiQuantityDelivery, + }) +} + +// UpsertPublishedItem 保存批量发布成功后的商品目录记录。 +func (repository *ItemCatalogRepository) UpsertPublishedItem(ctx context.Context, input itemapp.BatchPublishedItem) error { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return errors.New("商品写入存储未初始化") + } + return repository.store.Items.Upsert(ctx, &db.ItemInfoRow{ + CookieID: input.CookieID, ItemID: input.ItemID, ItemTitle: input.ItemTitle, ItemDescription: input.ItemDescription, + ItemCategory: input.ItemCategory, ItemPrice: input.ItemPrice, ItemDetail: input.ItemDetail, + MultiQuantityDelivery: input.MultiQuantityDelivery, + }) +} + +// Delete 逻辑删除本地商品及其商品级自动化规则。 +func (repository *ItemCatalogRepository) Delete(ctx context.Context, cookieID, itemID string) error { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return errors.New("商品写入存储未初始化") + } + return repository.store.Items.Delete(ctx, cookieID, itemID) +} + +// SetMultiSpec 更新本地商品的多规格交付开关。 +func (repository *ItemCatalogRepository) SetMultiSpec(ctx context.Context, cookieID, itemID string, enabled bool) error { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return errors.New("商品写入存储未初始化") + } + return repository.store.Items.SetMultiSpec(ctx, cookieID, itemID, enabled) +} + +// SetMultiQuantity 更新本地商品的多数量交付开关。 +func (repository *ItemCatalogRepository) SetMultiQuantity(ctx context.Context, cookieID, itemID string, enabled bool) error { + if repository == nil || repository.store == nil || repository.store.Items == nil { + return errors.New("商品写入存储未初始化") + } + return repository.store.Items.SetMultiQuantity(ctx, cookieID, itemID, enabled) +} + +// catalogItemsFromRows 转换数据库商品行并保持查询顺序。 +func catalogItemsFromRows(rows []db.ItemInfoRow) []itemapp.CatalogItem { + // items 保存转换后的应用商品模型并保持数据库顺序。 + items := make([]itemapp.CatalogItem, 0, len(rows)) + // row 表示当前待转换的数据库商品行。 + for _, row := range rows { + items = append(items, itemapp.CatalogItem{ID: row.ID, CookieID: row.CookieID, ItemID: row.ItemID, ItemTitle: row.ItemTitle, ItemDescription: row.ItemDescription, ItemCategory: row.ItemCategory, ItemPrice: row.ItemPrice, ItemDetail: row.ItemDetail, IsMultiSpec: row.IsMultiSpec, MultiQuantityDelivery: row.MultiQuantityDelivery}) + } + return items +} + +var _ itemapp.CatalogRepository = (*ItemCatalogRepository)(nil) +var _ itemapp.CatalogMutationRepository = (*ItemCatalogRepository)(nil) diff --git a/internal/adapter/item_catalog_test.go b/internal/adapter/item_catalog_test.go new file mode 100644 index 0000000..ec385e7 --- /dev/null +++ b/internal/adapter/item_catalog_test.go @@ -0,0 +1,92 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" +) + +// TestItemCatalogRepositoryRejectsMissingStore 验证商品读取适配器缺少数据库时快速失败。 +func TestItemCatalogRepositoryRejectsMissingStore(t *testing.T) { + // repository 保存缺少数据库依赖的商品读取适配器。 + repository := NewItemCatalogRepository(nil) + // err 保存用户范围读取的装配错误。 + if _, err := repository.ListForUser(context.Background(), 1, "account-1"); err == nil { + t.Fatal("缺少数据库时 ListForUser 不应伪装成功") + } + // err 保存账号范围读取的装配错误。 + if _, err := repository.ListByCookie(context.Background(), "account-1"); err == nil { + t.Fatal("缺少数据库时 ListByCookie 不应伪装成功") + } + // err 保存详情读取的装配错误。 + if _, err := repository.Get(context.Background(), "account-1", "item-1"); err == nil { + t.Fatal("缺少数据库时 Get 不应伪装成功") + } + // writeErr 保存创建商品时的装配错误。 + if writeErr := repository.Upsert(context.Background(), "account-1", itemapp.CatalogWriteInput{ItemID: "item-1"}); writeErr == nil { + t.Fatal("缺少数据库时 Upsert 不应伪装成功") + } + // deleteErr 保存删除商品时的装配错误。 + if deleteErr := repository.Delete(context.Background(), "account-1", "item-1"); deleteErr == nil { + t.Fatal("缺少数据库时 Delete 不应伪装成功") + } + // specErr 保存多规格更新时的装配错误。 + if specErr := repository.SetMultiSpec(context.Background(), "account-1", "item-1", true); specErr == nil { + t.Fatal("缺少数据库时 SetMultiSpec 不应伪装成功") + } + // quantityErr 保存多数量更新时的装配错误。 + if quantityErr := repository.SetMultiQuantity(context.Background(), "account-1", "item-1", true); quantityErr == nil { + t.Fatal("缺少数据库时 SetMultiQuantity 不应伪装成功") + } +} + +// TestCatalogItemsFromRowsConvertsAllFields 验证数据库商品行完整转换为应用模型。 +func TestCatalogItemsFromRowsConvertsAllFields(t *testing.T) { + // rows 保存带有全部业务字段的数据库商品行。 + rows := []db.ItemInfoRow{{ID: 9, CookieID: "account-1", ItemID: "item-1", ItemTitle: "标题", ItemDescription: "描述", ItemCategory: "cat", ItemPrice: "1.00", ItemDetail: "{}", IsMultiSpec: true, MultiQuantityDelivery: true}} + // items 保存适配器转换后的商品模型。 + items := catalogItemsFromRows(rows) + if len(items) != 1 || items[0].ID != 9 || items[0].CookieID != "account-1" || !items[0].IsMultiSpec || !items[0].MultiQuantityDelivery { + t.Fatalf("catalogItemsFromRows()=%+v", items) + } +} + +// TestItemCatalogRepositoryWritesAndDeletesItem 验证商品写适配器覆盖创建、开关更新和逻辑删除。 +func TestItemCatalogRepositoryWritesAndDeletesItem(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的商品读写适配器。 + repository := NewItemCatalogRepository(store) + // ctx 是本测试共用的非取消上下文。 + ctx := context.Background() + // upsertErr 保存创建商品的写入错误。 + upsertErr := repository.Upsert(ctx, "cid", itemapp.CatalogWriteInput{ItemID: "item-write", ItemTitle: "商品", IsMultiSpec: true}) + if upsertErr != nil { + t.Fatalf("Upsert error: %v", upsertErr) + } + // specErr 保存多规格开关更新错误。 + if specErr := repository.SetMultiSpec(ctx, "cid", "item-write", false); specErr != nil { + t.Fatalf("SetMultiSpec error: %v", specErr) + } + // quantityErr 保存多数量开关更新错误。 + if quantityErr := repository.SetMultiQuantity(ctx, "cid", "item-write", true); quantityErr != nil { + t.Fatalf("SetMultiQuantity error: %v", quantityErr) + } + // row、getErr 保存开关更新后的商品记录。 + row, getErr := store.Items.Get(ctx, "cid", "item-write") + if getErr != nil || row.IsMultiSpec || !row.MultiQuantityDelivery { + t.Fatalf("商品写入或开关更新异常:row=%+v err=%v", row, getErr) + } + // deleteErr 保存逻辑删除错误。 + if deleteErr := repository.Delete(ctx, "cid", "item-write"); deleteErr != nil { + t.Fatalf("Delete error: %v", deleteErr) + } + // missingErr 保存删除后再次读取的错误。 + if _, missingErr := store.Items.Get(ctx, "cid", "item-write"); !errors.Is(missingErr, db.ErrNotFound) { + t.Fatalf("删除后商品应不可见,err=%v", missingErr) + } +} diff --git a/internal/adapter/item_publish.go b/internal/adapter/item_publish.go new file mode 100644 index 0000000..f1042df --- /dev/null +++ b/internal/adapter/item_publish.go @@ -0,0 +1,300 @@ +package adapter + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" +) + +// ItemPublishPort 将 MTOP、Cookie 会话与运行时同步适配为商品发布端口。 +type ItemPublishPort struct { + // store 提供平台凭证读取、凭证锁和 Cookie 写回能力。 + store *db.Store + // client 返回商品发布平台客户端,允许运行时注入测试客户端。 + client func() mtop.Client + // logger 记录不含凭证内容的发布适配阶段信息。 + logger *slog.Logger + // updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。 + updateRunningCookie func(context.Context, string, string) + // recoverExpiredSession 在平台报告会话过期时触发账号恢复。 + recoverExpiredSession func(context.Context, string, error) +} + +// NewItemPublishPort 构造单商品发布基础设施端口。 +func NewItemPublishPort(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error)) *ItemPublishPort { + // resolvedLogger 保存可用于记录发布适配错误的日志器。 + resolvedLogger := logger + if resolvedLogger == nil { + resolvedLogger = slog.Default() + } + return &ItemPublishPort{store: store, client: client, logger: resolvedLogger, updateRunningCookie: updateRunningCookie, recoverExpiredSession: recoverExpiredSession} +} + +// categoryRecommender 是 MTOP 类目推荐能力的适配器内部契约。 +type categoryRecommender interface { + // RecommendPublishCategory 根据关键词返回平台类目及可能刷新的 Cookie。 + RecommendPublishCategory(context.Context, string, string) (mtop.PublishCategory, string, error) +} + +// RecommendCategory 读取账号平台凭证、调用类目推荐并提交响应会话变化。 +func (p *ItemPublishPort) RecommendCategory(ctx context.Context, userID int64, cookieID, keyword string) (itemapp.BatchPreviewCategory, error) { + if p == nil || p.store == nil || p.store.Cookies == nil { + return itemapp.BatchPreviewCategory{}, errors.New("商品发布存储未初始化") + } + // recommender 和 ok 表示当前 MTOP 客户端是否支持类目推荐。 + recommender, ok := p.mtopClient().(categoryRecommender) + if !ok { + return itemapp.BatchPreviewCategory{}, itemapp.ErrCategoryUnsupported + } + // unlock 保护凭证快照读取,远端调用前会释放该锁。 + unlock := p.store.LockAccountCredentials(cookieID) + // latest 和 loadErr 保存账号平台凭证视图及读取错误。 + latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) + if loadErr != nil || latest.UserID != userID || !hasStoredCredential(latest) { + unlock() + return itemapp.BatchPreviewCategory{}, itemapp.ErrCategoryCredentialChanged + } + // requestCtx 和 cancel 控制类目推荐远端调用的最长时间。 + requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + // mtopCtx 和 cookieSession 保存带凭证快照的平台上下文及会话。 + mtopCtx, cookieSession := withCookieSnapshot(requestCtx, latest) + // initialValue 和 initialMetadata 保存远端调用前的凭证版本。 + initialValue, initialMetadata := latest.Value, latest.MetadataJSON + unlock() + + // category、updatedCookies 和 callErr 保存平台推荐结果、刷新 Cookie 与调用错误。 + category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, strings.TrimSpace(keyword)) + // runtimeCookie 和 persistErr 保存会话写回后的运行时 Cookie 与错误。 + runtimeCookie, persistErr := p.persistCategorySession(ctx, userID, cookieID, initialValue, initialMetadata, cookieSession, updatedCookies) + if runtimeCookie != "" && p.updateRunningCookie != nil { + p.updateRunningCookie(ctx, cookieID, runtimeCookie) + } + if persistErr != nil { + return itemapp.BatchPreviewCategory{}, errors.Join(itemapp.ErrCategoryPersistence, persistErr) + } + if callErr != nil { + if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) { + return itemapp.BatchPreviewCategory{}, errors.Join(itemapp.ErrCategoryUnrecognized, callErr) + } + return itemapp.BatchPreviewCategory{}, callErr + } + return itemapp.BatchPreviewCategory{CatID: category.CatID, CatName: category.CatName, ChannelCatID: category.ChannelCatID, TBCatID: category.TBCatID}, nil +} + +// persistCategorySession 在远端调用后复核凭证并保存完整会话或平面 Cookie。 +func (p *ItemPublishPort) persistCategorySession(ctx context.Context, userID int64, cookieID, initialValue, initialMetadata string, session *mtop.CookieSession, updatedCookies string) (string, error) { + // unlock 保护远端调用完成后的凭证复核与会话写回。 + unlock := p.store.LockAccountCredentials(cookieID) + defer unlock() + // latest 和 loadErr 保存远端调用后的凭证视图及读取错误。 + latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) + if loadErr != nil || latest.UserID != userID || latest.Value != initialValue || latest.MetadataJSON != initialMetadata { + return "", itemapp.ErrCategoryCredentialChanged + } + // value、valueChanged、handled 和 persistErr 保存会话转换结果及写回错误。 + value, valueChanged, handled, persistErr := p.persistSession(ctx, latest, session) + if persistErr != nil { + return "", persistErr + } + if handled && valueChanged { + return value, nil + } + if !handled && updatedCookies != "" && updatedCookies != latest.Value { + // err 表示平面 Cookie 写回错误。 + if err := p.store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil { + return "", err + } + return updatedCookies, nil + } + return "", nil +} + +// Publish 执行单商品平台发布及响应 Cookie 持久化,不向应用层泄露 MTOP 类型。 +func (p *ItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInput) (itemapp.PublishOutcome, error) { + if p == nil || p.store == nil || p.store.Cookies == nil { + return itemapp.PublishOutcome{}, errors.New("商品发布存储未初始化") + } + // unlock 保护账号凭证快照读取与远端调用后的提交复核。 + unlock := p.store.LockAccountCredentials(input.CookieID) + // latest、loadErr 保存加锁后读取的平台凭证视图。 + latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, input.CookieID) + if loadErr != nil || latest.UserID != input.UserID || !hasStoredCredential(latest) { + unlock() + return itemapp.PublishOutcome{}, errors.New("账号凭证已变化,请重试") + } + // requestCtx、cancel 控制单商品平台发布的最长执行时间。 + requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + // images 保存应用图片转换后的平台图片请求。 + images := make([]mtop.PublishImage, 0, len(input.Images)) + // image 表示当前待转换的应用图片。 + for _, image := range input.Images { + images = append(images, mtop.PublishImage{Filename: image.Filename, ContentType: image.ContentType, Data: image.Data}) + } + // location 保存应用发货地转换后的平台位置请求。 + var location *mtop.PublishLocation + if input.Location != nil { + location = &mtop.PublishLocation{ + Area: input.Location.Area, City: input.Location.City, DivisionID: input.Location.DivisionID, + Longitude: input.Location.Longitude, Latitude: input.Location.Latitude, POIID: input.Location.POIID, + POIName: input.Location.POIName, Province: input.Location.Province, + } + } + // mtopCtx、cookieSession 保存带 Cookie 快照的平台调用上下文。 + mtopCtx, cookieSession := withCookieSnapshot(requestCtx, latest) + // initialValue、initialMetadata 保存远端调用前的凭证快照,用于提交阶段复核。 + initialValue, initialMetadata := latest.Value, latest.MetadataJSON + // unlock 在远端调用前释放,避免慢速平台 I/O 占用账号凭证锁。 + unlock() + // result、callErr 保存平台发布结果及调用错误。 + result, callErr := p.mtopClient().PublishItem(mtopCtx, latest.Value, mtop.PublishItemRequest{ + Title: input.Title, Description: input.Description, PriceCents: input.PriceCents, + OriginalPriceCents: input.OriginalPriceCents, Quantity: input.Quantity, + PostageMode: input.PostageMode, PostageCents: input.PostageCents, Virtual: true, + Location: location, Images: images, + }) + // callErr 由适配器转换为应用层错误,保留原始错误链供基础设施恢复逻辑使用。 + callErr = publishErrorToApplication(callErr) + // runtimeCookie、persistErr 保存响应 Cookie 提交后的运行时同步值和错误。 + runtimeCookie, persistErr := p.persistPublishSession(ctx, input, initialValue, initialMetadata, cookieSession, result, callErr) + if runtimeCookie != "" && p.updateRunningCookie != nil { + p.updateRunningCookie(ctx, input.CookieID, runtimeCookie) + } + if callErr != nil { + if persistErr != nil { + callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr)) + } + p.recoverExpired(ctx, input.CookieID, callErr) + return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, callErr + } + if result == nil { + return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, nil + } + return itemapp.PublishOutcome{Result: &itemapp.PublishResult{ + ItemID: result.ItemID, ItemURL: result.ItemURL, Title: result.Title, PriceText: result.PriceText, + CategoryID: result.CategoryID, CategoryName: result.CategoryName, ImageURL: result.ImageURL, + Quantity: result.Quantity, RawData: result.RawData, + }, ResponseCookieErr: persistErr}, nil +} + +// publishErrorToApplication 将平台发布错误转换为不依赖平台包的应用错误。 +func publishErrorToApplication(err error) error { + if err == nil { + return nil + } + // platformErr 保存平台客户端返回的发布错误;其文本已由平台客户端截断或脱敏。 + var platformErr *mtop.PublishError + if !errors.As(err, &platformErr) { + return err + } + return &itemapp.PublishError{ + Code: itemapp.PublishErrorCode(platformErr.Code), Ret: append([]string(nil), platformErr.Ret...), + Body: platformErr.Body, Err: err, + } +} + +// persistPublishSession 在远端调用结束后复核凭证并保存 Cookie 会话变化。 +func (p *ItemPublishPort) persistPublishSession(ctx context.Context, input itemapp.PublishInput, initialValue, initialMetadata string, session *mtop.CookieSession, result *mtop.PublishItemResult, callErr error) (string, error) { + // unlock 保护远端调用完成后的凭证复核和写回。 + unlock := p.store.LockAccountCredentials(input.CookieID) + defer unlock() + // latest、loadErr 保存远端调用完成后重新读取的平台凭证视图。 + latest, loadErr := p.store.Cookies.GetCookiePlatformRuntimeData(ctx, input.CookieID) + if loadErr != nil || latest.UserID != input.UserID || latest.Value != initialValue || latest.MetadataJSON != initialMetadata { + return "", errors.New("账号凭证已变化,请重试") + } + // value、valueChanged、handled、persistErr 保存 Cookie 会话提交结果。 + value, valueChanged, handled, persistErr := p.persistSession(ctx, latest, session) + if persistErr != nil { + if p.logger != nil { + p.logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", input.CookieID, "err", persistErr) + } + return "", persistErr + } + if handled && valueChanged { + return value, nil + } + if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != latest.Value { + // saveErr 保存平台返回新 Cookie 的错误。 + if saveErr := p.store.Cookies.UpdateValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil { + return "", saveErr + } + return result.UpdatedCookies, nil + } + return "", nil +} + +// persistSession 保存完整 Cookie Jar 或平面 Cookie 的会话变化。 +func (p *ItemPublishPort) persistSession(ctx context.Context, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession) (string, bool, bool, error) { + if session == nil { + return "", false, false, nil + } + // value、snapshot、changed 保存平台会话当前状态。 + value, snapshot, changed := session.State() + if !changed { + return detail.Value, false, snapshot != nil, nil + } + // metadata 保存移除旧快照后待写入的新 metadata。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + } + // err 保存 Cookie 会话持久化错误。 + err := p.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()) + return value, value != detail.Value, true, err +} + +// ItemPublishRepository 将本地商品写入适配为应用层商品仓储端口。 +type ItemPublishRepository struct { + // store 提供商品基础信息持久化能力。 + store *db.Store +} + +// NewItemPublishRepository 构造本地商品发布仓储适配器。 +func NewItemPublishRepository(store *db.Store) *ItemPublishRepository { + return &ItemPublishRepository{store: store} +} + +// Upsert 保存应用层商品记录,并转换为数据库行模型。 +func (r *ItemPublishRepository) Upsert(ctx context.Context, record itemapp.ItemRecord) error { + if r == nil || r.store == nil || r.store.Items == nil { + return errors.New("商品发布存储未初始化") + } + return r.store.Items.Upsert(ctx, &db.ItemInfoRow{ + CookieID: record.CookieID, ItemID: record.ItemID, ItemTitle: record.ItemTitle, + ItemDescription: record.ItemDescription, ItemCategory: record.ItemCategory, + ItemPrice: record.ItemPrice, ItemDetail: record.ItemDetail, + MultiQuantityDelivery: record.MultiQuantityDelivery, + }) +} + +// mtopClient 返回当前商品发布使用的平台客户端,并在测试构造缺失时提供默认实现。 +func (p *ItemPublishPort) mtopClient() mtop.Client { + if p != nil && p.client != nil { + // client 保存当前回调返回的平台客户端。 + if client := p.client(); client != nil { + return client + } + } + return mtop.NewClient() +} + +// recoverExpired 在平台会话过期时通知账号恢复协调器。 +func (p *ItemPublishPort) recoverExpired(ctx context.Context, cookieID string, err error) { + if p != nil && p.recoverExpiredSession != nil && err != nil { + p.recoverExpiredSession(ctx, cookieID, err) + } +} + +// 确保发布端口和仓储实现覆盖应用层定义的最小接口。 +var _ itemapp.PublishPort = (*ItemPublishPort)(nil) +var _ itemapp.ItemRepository = (*ItemPublishRepository)(nil) diff --git a/internal/adapter/item_publish_images.go b/internal/adapter/item_publish_images.go new file mode 100644 index 0000000..86ccc9a --- /dev/null +++ b/internal/adapter/item_publish_images.go @@ -0,0 +1,75 @@ +package adapter + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "strings" + + "xianyu-go/internal/xianyu/mtop" +) + +// ReadPublishImageFile 是批量发布图片本地读取回调;实现方负责路径安全和图片格式校验。 +type ReadPublishImageFile func(uploadDir, ref string) ([]byte, string, string, error) + +// DownloadPublishImageURL 是批量发布远程图片下载回调;实现方负责 URL 安全、超时和响应大小限制。 +type DownloadPublishImageURL func(context.Context, string) ([]byte, string, error) + +// LoadBatchPublishImages 解析批次图片引用并转换为平台发布图片模型。 +// 文件读取和远程下载通过回调注入,避免应用/适配器层重复拥有网络或文件安全策略。 +func LoadBatchPublishImages(ctx context.Context, uploadDir, imagesJSON string, readLocal ReadPublishImageFile, downloadRemote DownloadPublishImageURL) ([]mtop.PublishImage, error) { + if readLocal == nil || downloadRemote == nil { + return nil, errors.New("批量发布图片读取端口未初始化") + } + // refs 保存持久化图片 JSON 中的本地路径或远程 URL 引用。 + var refs []string + // err 表示持久化图片引用 JSON 无法解析,调用方应将其作为批次数据损坏处理。 + if err := json.Unmarshal([]byte(imagesJSON), &refs); err != nil { + return nil, fmt.Errorf("图片字段格式错误") + } + if len(refs) == 0 { + return nil, errors.New("至少上传 1 张商品图片") + } + // images 保存经过读取回调校验、可交给平台发布端口的图片数据。 + images := make([]mtop.PublishImage, 0, len(refs)) + // ref 表示当前遍历的图片引用。 + for _, ref := range refs { + // data、contentType 和 filename 保存当前图片的内容、媒体类型及展示文件名。 + var data []byte + // contentType 保存当前图片的媒体类型。 + var contentType string + // filename 保存当前图片交给平台时使用的文件名。 + var filename string + // err 保存当前图片读取或下载失败的原因。 + var err error + if isPublishImageHTTPURL(ref) { + data, contentType, err = downloadRemote(ctx, ref) + filename = publishImagePathBase(ref) + } else { + data, contentType, filename, err = readLocal(uploadDir, ref) + } + if err != nil { + return nil, err + } + images = append(images, mtop.PublishImage{Filename: filename, ContentType: contentType, Data: data}) + } + return images, nil +} + +// isPublishImageHTTPURL 判断图片引用是否为远程 HTTP(S) 地址;具体网络访问由调用方回调执行。 +func isPublishImageHTTPURL(ref string) bool { + ref = strings.TrimSpace(strings.ToLower(ref)) + return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://") +} + +// publishImagePathBase 从远程 URL 提取稳定文件名,缺少路径名时使用通用图片名。 +func publishImagePathBase(rawURL string) string { + // base 保存从 URL 路径提取出的文件名;空路径回退到通用图片名。 + base := filepath.Base(strings.Split(rawURL, "?")[0]) + if base == "." || base == "/" || base == "" { + return "image.jpg" + } + return base +} diff --git a/internal/adapter/item_publish_images_test.go b/internal/adapter/item_publish_images_test.go new file mode 100644 index 0000000..0740483 --- /dev/null +++ b/internal/adapter/item_publish_images_test.go @@ -0,0 +1,67 @@ +package adapter + +import ( + "context" + "testing" +) + +// TestLoadBatchPublishImagesConvertsLocalAndRemoteRefs 验证本地与远程图片回调均转换为平台模型。 +func TestLoadBatchPublishImagesConvertsLocalAndRemoteRefs(t *testing.T) { + // localCalls、remoteCalls 记录两类图片读取回调的调用次数。 + localCalls, remoteCalls := 0, 0 + // readLocal 返回本地图片测试数据和稳定文件名。 + readLocal := func(_ string, ref string) ([]byte, string, string, error) { + localCalls++ + return []byte("local"), "image/png", ref, nil + } + // downloadRemote 返回远程图片测试数据。 + downloadRemote := func(_ context.Context, _ string) ([]byte, string, error) { + remoteCalls++ + return []byte("remote"), "image/jpeg", nil + } + // images、loadErr 保存图片转换结果和执行错误。 + images, loadErr := LoadBatchPublishImages(context.Background(), "/tmp/upload", `["local.png","https://example.test/remote.jpg?x=1"]`, readLocal, downloadRemote) + if loadErr != nil { + t.Fatalf("加载图片失败: %v", loadErr) + } + if len(images) != 2 || localCalls != 1 || remoteCalls != 1 { + t.Fatalf("图片回调或结果异常: images=%+v local=%d remote=%d", images, localCalls, remoteCalls) + } + if images[1].Filename != "remote.jpg" || images[1].ContentType != "image/jpeg" { + t.Fatalf("远程图片元数据异常: %+v", images[1]) + } +} + +// TestLoadBatchPublishImagesRejectsInvalidInput 验证缺失端口、非法 JSON 和空图片列表均明确失败。 +func TestLoadBatchPublishImagesRejectsInvalidInput(t *testing.T) { + // readLocal、downloadRemote 是不应被非法输入调用的测试回调。 + readLocal := func(string, string) ([]byte, string, string, error) { return nil, "", "", nil } + // downloadRemote 是远程图片测试回调。 + downloadRemote := func(context.Context, string) ([]byte, string, error) { return nil, "", nil } + // cases 保存不同非法输入及其预期错误断言。 + cases := []struct { + name string + imagesJSON string + readLocal ReadPublishImageFile + wantErr bool + }{ + {name: "missing port", imagesJSON: `[]`, wantErr: true}, + {name: "bad json", imagesJSON: "not-json", readLocal: readLocal, wantErr: true}, + {name: "empty", imagesJSON: `[]`, readLocal: readLocal, wantErr: true}, + } + // testCase 描述当前非法图片输入分支。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // remote 是当前分支可用的远程下载回调,缺失端口分支故意传入 nil。 + remote := downloadRemote + if testCase.readLocal == nil { + remote = nil + } + // _, loadErr 保存当前非法输入的执行错误。 + _, loadErr := LoadBatchPublishImages(context.Background(), "/tmp/upload", testCase.imagesJSON, testCase.readLocal, remote) + if (loadErr != nil) != testCase.wantErr { + t.Fatalf("错误断言不符: %v", loadErr) + } + }) + } +} diff --git a/internal/adapter/item_publish_test.go b/internal/adapter/item_publish_test.go new file mode 100644 index 0000000..778f98b --- /dev/null +++ b/internal/adapter/item_publish_test.go @@ -0,0 +1,199 @@ +package adapter + +import ( + "context" + "errors" + "testing" + "time" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/xianyu/mtop" +) + +// itemPublishClientStub 是单商品发布端口测试使用的平台客户端替身。 +type itemPublishClientStub struct { + // mtop.Client 提供未涉及本测试的方法默认实现。 + mtop.Client + // publish 保存单商品发布请求的可控行为。 + publish func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) + // recommend 保存类目推荐请求的可控行为。 + recommend func(context.Context, string, string) (mtop.PublishCategory, string, error) +} + +// PublishItem 调用测试注入的单商品发布行为。 +func (c itemPublishClientStub) PublishItem(ctx context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) { + return c.publish(ctx, cookies, request) +} + +// RecommendPublishCategory 调用测试注入的类目推荐行为。 +func (c itemPublishClientStub) RecommendPublishCategory(ctx context.Context, cookies, keyword string) (mtop.PublishCategory, string, error) { + return c.recommend(ctx, cookies, keyword) +} + +// unsupportedItemPublishClient 是不提供类目推荐能力的平台客户端替身。 +type unsupportedItemPublishClient struct{ mtop.Client } + +// TestItemPublishPortRecommendsCategoryAndPersistsUpdatedCookie 验证类目推荐和 Cookie 写回。 +func TestItemPublishPortRecommendsCategoryAndPersistsUpdatedCookie(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // client 是返回类目及刷新 Cookie 的平台替身。 + client := itemPublishClientStub{recommend: func(_ context.Context, cookies, keyword string) (mtop.PublishCategory, string, error) { + if cookies == "" || keyword != "资料" { + t.Fatalf("推荐请求参数异常: cookies=%q keyword=%q", cookies, keyword) + } + return mtop.PublishCategory{CatID: "cat-1", CatName: "资料", ChannelCatID: "channel-1"}, "unb=2; _m_h5_tk=tk2;", nil + }} + // port 是绑定测试数据库和平台替身的商品发布端口。 + port := NewItemPublishPort(store, func() mtop.Client { return client }, nil, nil, nil) + // category、err 保存类目推荐结果。 + category, err := port.RecommendCategory(context.Background(), 1, "cid", "资料") + if err != nil || category.CatID != "cat-1" { + t.Fatalf("类目推荐失败: category=%+v err=%v", category, err) + } + // value、valueErr 保存平台返回 Cookie 的本地持久化结果。 + value, valueErr := store.Cookies.GetValue(context.Background(), "cid") + if valueErr != nil || value != "unb=2; _m_h5_tk=tk2;" { + t.Fatalf("类目推荐 Cookie 未保存: value=%q err=%v", value, valueErr) + } +} + +// TestItemPublishPortRejectsUnsupportedCategoryRecommendation 验证未实现平台能力时返回应用错误。 +func TestItemPublishPortRejectsUnsupportedCategoryRecommendation(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // port 是返回不支持能力客户端的商品发布端口。 + port := NewItemPublishPort(store, func() mtop.Client { return unsupportedItemPublishClient{} }, nil, nil, nil) + // err 保存能力缺失错误。 + _, err := port.RecommendCategory(context.Background(), 1, "cid", "资料") + if !errors.Is(err, itemapp.ErrCategoryUnsupported) { + t.Fatalf("未返回能力缺失错误: %v", err) + } +} + +// TestItemPublishPortReleasesCredentialLockDuringRemoteCall 验证单商品发布远端调用期间不占用凭证锁。 +func TestItemPublishPortReleasesCredentialLockDuringRemoteCall(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // started 表示平台发布已进入慢速调用阶段。 + started := make(chan struct{}) + // release 控制测试平台调用继续返回。 + release := make(chan struct{}) + // client 是带阻塞控制的单商品发布平台替身。 + client := itemPublishClientStub{publish: func(_ context.Context, cookies string, request mtop.PublishItemRequest) (*mtop.PublishItemResult, error) { + if cookies == "" || request.Quantity != 2 { + t.Fatalf("发布请求未携带预期凭证或库存:cookies=%q quantity=%d", cookies, request.Quantity) + } + close(started) + <-release + return &mtop.PublishItemResult{ItemID: "published-1", UpdatedCookies: "unb=2; _m_h5_tk=tk2;"}, nil + }} + // port 是绑定测试数据库和平台替身的发布适配器。 + port := NewItemPublishPort(store, func() mtop.Client { return client }, nil, nil, nil) + // result 保存异步发布调用的结果。 + result := make(chan struct { + outcome itemapp.PublishOutcome + err error + }, 1) + go func() { + // outcome、err 保存发布适配器返回的结果及错误。 + outcome, err := port.Publish(context.Background(), itemapp.PublishInput{UserID: 1, CookieID: "cid", Quantity: 2}) + result <- struct { + outcome itemapp.PublishOutcome + err error + }{outcome: outcome, err: err} + }() + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("平台发布未进入阻塞阶段") + } + // lockAcquired 表示并行操作已取得同账号凭证锁。 + lockAcquired := make(chan struct{}) + go func() { + // unlock 释放并行测试操作取得的凭证锁。 + unlock := store.LockAccountCredentials("cid") + close(lockAcquired) + unlock() + }() + select { + case <-lockAcquired: + case <-time.After(time.Second): + t.Fatal("远端发布期间凭证锁仍被占用") + } + close(release) + select { + // completed 保存发布 goroutine 返回的结果和错误。 + case completed := <-result: + if completed.err != nil || completed.outcome.Result == nil || completed.outcome.Result.ItemID != "published-1" { + t.Fatalf("发布结果异常:outcome=%+v err=%v", completed.outcome, completed.err) + } + case <-time.After(3 * time.Second): + t.Fatal("发布适配器未收束") + } + // value、valueErr 保存平台返回 Cookie 的本地持久化结果。 + value, valueErr := store.Cookies.GetValue(context.Background(), "cid") + if valueErr != nil || value != "unb=2; _m_h5_tk=tk2;" { + t.Fatalf("平台返回 Cookie 未保存:value=%q err=%v", value, valueErr) + } +} + +// TestItemPublishRepositoryUpsertMapsApplicationRecord 验证商品仓储适配器正确转换应用记录。 +func TestItemPublishRepositoryUpsertMapsApplicationRecord(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的商品仓储适配器。 + repository := NewItemPublishRepository(store) + // err 保存应用商品记录写入结果。 + err := repository.Upsert(context.Background(), itemapp.ItemRecord{CookieID: "cid", ItemID: "local-1", ItemTitle: "商品", ItemDescription: "描述", ItemCategory: "cat", ItemPrice: "12.00", ItemDetail: `{"quantity":2}`, MultiQuantityDelivery: true}) + if err != nil { + t.Fatalf("Upsert error: %v", err) + } + // record、recordErr 保存数据库读取到的商品记录。 + record, recordErr := store.Items.Get(context.Background(), "cid", "local-1") + if recordErr != nil || record == nil || record.ItemTitle != "商品" || !record.MultiQuantityDelivery { + t.Fatalf("商品记录转换异常:record=%+v err=%v", record, recordErr) + } +} + +// TestPublishErrorToApplicationMapsPlatformError 验证发布适配器转换错误时保留分类和原始错误链。 +func TestPublishErrorToApplicationMapsPlatformError(t *testing.T) { + // platformErr 是平台客户端返回的库存权限错误替身。 + platformErr := &mtop.PublishError{ + Code: mtop.PublishErrorStockPermissionMissing, + Ret: []string{"库存权限缺失"}, + } + // convertedErr 是适配器转换后的应用层错误。 + convertedErr := publishErrorToApplication(platformErr) + // applicationErr 是转换结果中的应用层发布错误。 + var applicationErr *itemapp.PublishError + if !errors.As(convertedErr, &applicationErr) { + t.Fatalf("未转换为应用发布错误: %v", convertedErr) + } + if applicationErr.Code != itemapp.PublishErrorStockPermissionMissing || applicationErr.Error() != "库存权限缺失" { + t.Fatalf("应用发布错误分类异常: %+v", applicationErr) + } + // originalErr 是通过应用错误 Unwrap 保留的平台错误。 + var originalErr *mtop.PublishError + if !errors.As(convertedErr, &originalErr) || originalErr != platformErr { + t.Fatalf("未保留原始平台错误链: %v", convertedErr) + } +} + +// TestPublishErrorToApplicationKeepsNonPlatformError 验证普通基础设施错误不会被错误包装。 +func TestPublishErrorToApplicationKeepsNonPlatformError(t *testing.T) { + // plainErr 是不属于平台发布错误类型的基础设施错误。 + plainErr := errors.New("transport failed") + // convertedErr 是普通错误经过适配器转换后的结果。 + convertedErr := publishErrorToApplication(plainErr) + if convertedErr != plainErr || !errors.Is(convertedErr, plainErr) { + t.Fatalf("普通错误不应被改写: got=%v", convertedErr) + } + if publishErrorToApplication(nil) != nil { + t.Fatal("空错误应保持为空") + } +} diff --git a/internal/adapter/item_sync.go b/internal/adapter/item_sync.go new file mode 100644 index 0000000..4674a66 --- /dev/null +++ b/internal/adapter/item_sync.go @@ -0,0 +1,478 @@ +package adapter + +import ( + "context" + "errors" + "log/slog" + "strings" + "sync" + "time" + + itemapp "xianyu-go/internal/application/items" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" +) + +// ItemSyncRepository 将商品同步应用 Port 适配到数据库、MTOP 和账号运行时。 +type ItemSyncRepository struct { + // store 提供账号凭证和商品持久化能力。 + store *db.Store + // client 返回商品列表和详情平台调用能力,允许运行时注入测试客户端。 + client func() mtop.Client + // logger 记录不含凭证的同步阶段信息。 + logger *slog.Logger + // updateRunningCookie 将平台返回的新 Cookie 同步到运行中的账号实例。 + updateRunningCookie func(context.Context, string, string) + // recoverExpiredSession 在平台报告会话过期时触发账号恢复。 + recoverExpiredSession func(context.Context, string, error) + // cacheMu 保护商品多规格探测缓存。 + cacheMu sync.Mutex + // cache 保存短期商品多规格探测结果。 + cache map[string]itemSpecCacheEntry +} + +// itemSpecCacheEntry 保存商品多规格结果及过期时间。 +type itemSpecCacheEntry struct { + // isMultiSpec 表示商品是否包含多规格。 + isMultiSpec bool + // expiresAt 表示缓存项失效时间。 + expiresAt time.Time +} + +// NewItemSyncRepository 构造商品同步基础设施适配器。 +func NewItemSyncRepository(store *db.Store, client func() mtop.Client, logger *slog.Logger, updateRunningCookie func(context.Context, string, string), recoverExpiredSession func(context.Context, string, error)) *ItemSyncRepository { + if client == nil { + client = func() mtop.Client { return mtop.NewClient() } + } + if logger == nil { + logger = slog.Default() + } + return &ItemSyncRepository{store: store, client: client, logger: logger, updateRunningCookie: updateRunningCookie, recoverExpiredSession: recoverExpiredSession, cache: make(map[string]itemSpecCacheEntry)} +} + +// OwnsAccount 按非敏感所有者字段判断用户是否拥有账号。 +func (r *ItemSyncRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) { + if r == nil || r.store == nil || r.store.Cookies == nil { + return false, syncStageError(itemapp.SyncErrorPersistence, errors.New("商品同步存储未初始化")) + } + // ownerID、ownerErr 保存只读取账号归属的查询结果。 + ownerID, ownerErr := r.store.Cookies.GetOwnerID(ctx, cookieID) + if errors.Is(ownerErr, db.ErrNotFound) { + return false, nil + } + if ownerErr != nil { + return false, syncStageError(itemapp.SyncErrorPersistence, ownerErr) + } + return ownerID == userID, nil +} + +// SyncAll 读取平台商品全集、探测多规格并完成本地 reconcile。 +func (r *ItemSyncRepository) SyncAll(ctx context.Context, query itemapp.SyncQuery) (itemapp.SyncAllResult, error) { + // requestCtx、cancel 控制全量同步的最长执行时间。 + requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + // latest、cookieValue、requestContext、session、unlock 保存远端请求使用的凭证快照及锁。 + latest, cookieValue, requestContext, session, unlock, err := r.begin(requestCtx, query) + if err != nil { + return itemapp.SyncAllResult{}, err + } + // unlock 在创建完整 Cookie 会话后立即释放,避免慢速平台 I/O 占用账号锁。 + unlock() + // result、callErr 保存平台全集结果和调用错误。 + result, callErr := r.mtopClient().FetchAllItems(requestContext, cookieValue, query.PageSize, query.MaxPages) + // latest、session 和 callErr 通过重新加锁的提交阶段处理平台 Cookie 变化。 + latest, session, callErr, err = r.finishRemote(requestCtx, query, latest, session, callErr) + if err != nil { + return itemapp.SyncAllResult{}, err + } + if callErr != nil { + r.recoverExpired(requestCtx, query.CookieID, callErr) + return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPlatform, callErr) + } + if result == nil { + return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPlatform, errors.New("商品列表接口未返回结果")) + } + // detailCookies 保存规格探测使用的最新 Cookie 串。 + detailCookies := cookieValue + if result.UpdatedCookies != "" { + detailCookies = result.UpdatedCookies + } + // detailErr 保存远端多规格探测错误。 + detailErr := r.enrichMultiSpec(requestCtx, detailCookies, query.CookieID, result.Items) + if detailErr != nil { + r.recoverExpired(requestCtx, query.CookieID, detailErr) + return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPlatform, detailErr) + } + // persistErr 保存探测后 Cookie 会话提交错误。 + persistErr := r.persistAfterEnrich(requestCtx, query, latest, session, cookieValue, result.UpdatedCookies) + if persistErr != nil { + return itemapp.SyncAllResult{}, persistErr + } + // syncResult、syncErr 保存本地全集 reconcile 结果及错误。 + syncResult, syncErr := r.syncItems(requestCtx, query.CookieID, result.Items) + if syncErr != nil { + return itemapp.SyncAllResult{}, syncStageError(itemapp.SyncErrorPersistence, syncErr) + } + return itemapp.SyncAllResult{TotalCount: len(result.Items), TotalPages: result.TotalPages, SavedCount: syncResult.Saved, DeletedCount: syncResult.Deleted}, nil +} + +// SyncPage 读取平台指定页、探测多规格并保存本页商品。 +func (r *ItemSyncRepository) SyncPage(ctx context.Context, query itemapp.SyncQuery) (itemapp.SyncPageResult, error) { + // requestCtx、cancel 控制分页同步的最长执行时间。 + requestCtx, cancel := context.WithTimeout(ctx, time.Minute) + defer cancel() + // latest、cookieValue、requestContext、session、unlock 保存远端请求使用的凭证快照及锁。 + latest, cookieValue, requestContext, session, unlock, err := r.begin(requestCtx, query) + if err != nil { + return itemapp.SyncPageResult{}, err + } + unlock() + // result、callErr 保存平台分页结果和调用错误。 + result, callErr := r.mtopClient().FetchItemsPage(requestContext, cookieValue, query.PageNumber, query.PageSize) + // latest、session 和 callErr 通过提交阶段处理平台 Cookie 变化。 + latest, session, callErr, err = r.finishRemote(requestCtx, query, latest, session, callErr) + if err != nil { + return itemapp.SyncPageResult{}, err + } + if callErr != nil { + r.recoverExpired(requestCtx, query.CookieID, callErr) + return itemapp.SyncPageResult{}, syncStageError(itemapp.SyncErrorPlatform, callErr) + } + if result == nil { + return itemapp.SyncPageResult{}, syncStageError(itemapp.SyncErrorPlatform, errors.New("商品列表接口未返回结果")) + } + // detailCookies 保存规格探测使用的最新 Cookie 串。 + detailCookies := cookieValue + if result.UpdatedCookies != "" { + detailCookies = result.UpdatedCookies + } + // detailErr 保存远端多规格探测错误。 + detailErr := r.enrichMultiSpec(requestCtx, detailCookies, query.CookieID, result.Items) + if detailErr != nil { + r.recoverExpired(requestCtx, query.CookieID, detailErr) + return itemapp.SyncPageResult{}, syncStageError(itemapp.SyncErrorPlatform, detailErr) + } + // persistErr 保存探测后 Cookie 会话提交错误。 + persistErr := r.persistAfterEnrich(requestCtx, query, latest, session, cookieValue, result.UpdatedCookies) + if persistErr != nil { + return itemapp.SyncPageResult{}, persistErr + } + // saved 保存本页成功写入商品的数量。 + saved := r.saveItems(requestCtx, query.CookieID, result.Items) + return itemapp.SyncPageResult{PageNumber: result.PageNumber, PageSize: result.PageSize, CurrentCount: len(result.Items), SavedCount: saved}, nil +} + +// begin 读取并校验账号平台视图,同时创建本次请求的 Cookie 会话。 +func (r *ItemSyncRepository) begin(ctx context.Context, query itemapp.SyncQuery) (*db.CookiePlatformRuntimeData, string, context.Context, *mtop.CookieSession, func(), error) { + if r == nil || r.store == nil || r.store.Cookies == nil || r.store.Items == nil { + return nil, "", ctx, nil, func() {}, syncStageError(itemapp.SyncErrorPersistence, errors.New("商品同步存储未初始化")) + } + // unlock 保护账号凭证快照的读取和提交。 + unlock := r.store.LockAccountCredentials(query.CookieID) + // latest、loadErr 保存平台凭证视图及读取错误。 + latest, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, query.CookieID) + if errors.Is(loadErr, db.ErrNotFound) { + unlock() + return nil, "", ctx, nil, func() {}, itemapp.ErrSyncNotOwned + } + if loadErr != nil { + unlock() + return nil, "", ctx, nil, func() {}, syncStageError(itemapp.SyncErrorPersistence, loadErr) + } + if latest.UserID != query.UserID { + unlock() + return nil, "", ctx, nil, func() {}, itemapp.ErrSyncNotOwned + } + if !hasStoredCredential(latest) { + unlock() + return nil, "", ctx, nil, func() {}, syncStageError(itemapp.SyncErrorCredential, errors.New("账号凭证已变化,请重试")) + } + // requestContext、session 保存平台调用需要的 Cookie 会话上下文。 + requestContext, session := withCookieSnapshot(ctx, latest) + return &latest, latest.Value, requestContext, session, unlock, nil +} + +// finishRemote 在远端调用后重新读取账号并提交 Cookie 会话变化。 +func (r *ItemSyncRepository) finishRemote(ctx context.Context, query itemapp.SyncQuery, detail *db.CookiePlatformRuntimeData, session *mtop.CookieSession, callErr error) (*db.CookiePlatformRuntimeData, *mtop.CookieSession, error, error) { + // unlock 保护远端调用完成后的凭证复核和写回。 + unlock := r.store.LockAccountCredentials(query.CookieID) + defer unlock() + // latest、loadErr 保存远端调用后的最新账号凭证视图。 + latest, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, query.CookieID) + if loadErr != nil || latest.UserID != query.UserID { + return nil, session, callErr, syncStageError(itemapp.SyncErrorCredential, errors.New("账号凭证已变化,请重试")) + } + // changed 表示远端调用期间凭证是否被其他流程更新。 + changed := latest.Value != detail.Value || latest.MetadataJSON != detail.MetadataJSON + if !changed { + // value、valueChanged、handled、persistErr 保存 Cookie 会话提交结果。 + _, _, _, persistErr := r.persistSession(ctx, latest, session) + if persistErr != nil { + return nil, session, callErr, syncStageError(itemapp.SyncErrorPersistence, persistErr) + } + } + return &latest, session, callErr, nil +} + +// persistAfterEnrich 在多规格探测后复核账号并写回平台 Cookie 变化。 +func (r *ItemSyncRepository) persistAfterEnrich(ctx context.Context, query itemapp.SyncQuery, detail *db.CookiePlatformRuntimeData, session *mtop.CookieSession, originalCookie, updatedCookie string) error { + // unlock 保护探测完成后的凭证复核和写回。 + unlock := r.store.LockAccountCredentials(query.CookieID) + defer unlock() + // latest、loadErr 保存探测完成后的最新账号凭证视图。 + latest, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, query.CookieID) + if loadErr != nil || latest.UserID != query.UserID { + return syncStageError(itemapp.SyncErrorCredential, errors.New("账号凭证已变化,请重试")) + } + // changed 表示平台请求期间是否已有其他流程写入凭证。 + changed := latest.Value != detail.Value || latest.MetadataJSON != detail.MetadataJSON + if !changed { + // value、valueChanged、handled、persistErr 保存 Cookie 会话提交结果。 + value, valueChanged, handled, persistErr := r.persistSession(ctx, latest, session) + if persistErr != nil { + return syncStageError(itemapp.SyncErrorPersistence, persistErr) + } + if handled && valueChanged { + r.notifyRunningCookie(ctx, query.CookieID, value) + } else if !handled && updatedCookie != "" && updatedCookie != originalCookie { + // saveErr 保存平台返回的新 Cookie 写回错误。 + if saveErr := r.store.Cookies.UpdateValueOwned(ctx, query.CookieID, updatedCookie, query.UserID); saveErr != nil { + return syncStageError(itemapp.SyncErrorPersistence, saveErr) + } + r.notifyRunningCookie(ctx, query.CookieID, updatedCookie) + } + } + return nil +} + +// persistSession 保存完整 Cookie Jar 或平面 Cookie 的会话变化。 +func (r *ItemSyncRepository) persistSession(ctx context.Context, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession) (string, bool, bool, error) { + if session == nil { + return "", false, false, nil + } + // value、snapshot、changed 保存平台会话当前状态。 + value, snapshot, changed := session.State() + if !changed { + return detail.Value, false, snapshot != nil, nil + } + // metadata 保存移除旧快照后待写入的新 metadata。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + } + // err 保存 Cookie 会话持久化错误。 + err := r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()) + return value, value != detail.Value, true, err +} + +// saveItems 保存分页同步返回的商品基础信息并返回成功数。 +func (r *ItemSyncRepository) saveItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) int { + // saved 保存成功写入的商品数量。 + saved := 0 + // item 表示当前待写入的分页商品。 + for _, item := range items { + // price 保存优先使用格式化价格的商品价格文本。 + price := item.PriceText + if price == "" { + price = item.Price + } + // saveErr 保存当前商品基础信息写入错误。 + saveErr := r.store.Items.UpsertBasic(ctx, &db.ItemInfoRow{CookieID: cookieID, ItemID: item.ID, ItemTitle: item.Title, ItemCategory: item.CategoryID, ItemPrice: price, ItemDetail: item.ItemDetail}) + if saveErr != nil { + r.logger.Warn("保存商品失败", "cookie_id", cookieID, "item_id", item.ID, "err", saveErr) + continue + } + if item.IsMultiSpec { + // multiErr 保存当前商品多规格标记写入错误。 + if multiErr := r.store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil { + r.logger.Warn("保存商品多规格状态失败", "cookie_id", cookieID, "item_id", item.ID, "err", multiErr) + } + } + saved++ + } + return saved +} + +// syncItems 将平台商品模型转换为数据库行并执行全集 reconcile。 +func (r *ItemSyncRepository) syncItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) (db.ItemSyncResult, error) { + // rows 保存待写入数据库的商品行。 + rows := make([]db.ItemInfoRow, 0, len(items)) + // item 表示当前待转换的平台商品。 + for _, item := range items { + // price 保存优先使用格式化价格的商品价格文本。 + price := item.PriceText + if price == "" { + price = item.Price + } + rows = append(rows, db.ItemInfoRow{CookieID: cookieID, ItemID: item.ID, ItemTitle: item.Title, ItemCategory: item.CategoryID, ItemPrice: price, ItemDetail: item.ItemDetail, IsMultiSpec: item.IsMultiSpec}) + } + return r.store.Items.SyncFromRemote(ctx, cookieID, rows) +} + +// enrichMultiSpec 使用本地标记和有限并发远端详情探测补全多规格字段。 +func (r *ItemSyncRepository) enrichMultiSpec(ctx context.Context, cookies, cookieID string, items []mtop.ItemListItem) error { + // fetcher、ok 保存可选商品详情探测能力及其存在状态。 + fetcher, ok := r.mtopClient().(mtop.ItemDetailFetcher) + if !ok { + return nil + } + // itemIDs 保存本次批量读取本地标记的商品标识。 + itemIDs := make([]string, 0, len(items)) + // item 表示当前待收集标识的平台商品。 + for _, item := range items { + itemIDs = append(itemIDs, item.ID) + } + // localFlags、flagsErr 保存本地多规格标记及查询错误。 + localFlags, flagsErr := r.store.Items.MultiSpecFlags(ctx, cookieID, itemIDs) + if flagsErr != nil { + r.logger.Warn("批量读取商品多规格标记失败,将继续远端探测", "cookie_id", cookieID, "err", flagsErr) + } + // candidates 保存需要远端探测的商品下标。 + candidates := make([]int, 0, len(items)) + // index 表示当前商品在结果切片中的下标。 + for index := range items { + if items[index].IsMultiSpec || localFlags[items[index].ID] { + items[index].IsMultiSpec = true + r.cacheSpec(cookieID, items[index].ID, true) + continue + } + // cachedValue、cached 表示是否命中短期多规格缓存。 + cachedValue, cached := r.cachedSpec(cookieID, items[index].ID) + if cached { + items[index].IsMultiSpec = cachedValue + continue + } + candidates = append(candidates, index) + } + if len(candidates) == 0 { + return nil + } + // probeCtx、cancel 控制批量详情探测的收束。 + probeCtx, cancel := context.WithCancel(ctx) + defer cancel() + // semaphore 限制同时进行的详情探测数量。 + semaphore := make(chan struct{}, 4) + // waitGroup 等待所有详情探测 goroutine 结束。 + var waitGroup sync.WaitGroup + // errorMu 保护 sessionErr 的并发写入。 + var errorMu sync.Mutex + // sessionErr 保存首个会话过期错误。 + var sessionErr error + // index 表示当前需要启动详情探测的商品下标。 + for _, index := range candidates { + waitGroup.Add(1) + go func(index int) { + defer waitGroup.Done() + select { + case semaphore <- struct{}{}: + case <-probeCtx.Done(): + return + } + defer func() { <-semaphore }() + // isMultiSpec、detectErr 保存当前商品详情探测结果及错误。 + isMultiSpec, detectErr := fetcher.DetectItemMultiSpec(probeCtx, cookies, items[index].ID) + if detectErr != nil { + if mtop.IsSessionExpiredErr(detectErr) { + errorMu.Lock() + if sessionErr == nil { + sessionErr = detectErr + cancel() + } + errorMu.Unlock() + } + return + } + r.cacheSpec(cookieID, items[index].ID, isMultiSpec) + items[index].IsMultiSpec = isMultiSpec + }(index) + } + waitGroup.Wait() + return sessionErr +} + +// cachedSpec 读取未过期的多规格探测缓存。 +func (r *ItemSyncRepository) cachedSpec(cookieID, itemID string) (bool, bool) { + r.cacheMu.Lock() + defer r.cacheMu.Unlock() + // key 是账号和商品组成的缓存键。 + key := cookieID + "\x00" + itemID + // entry、ok 保存缓存项及存在状态。 + entry, ok := r.cache[key] + if !ok || time.Now().After(entry.expiresAt) { + delete(r.cache, key) + return false, false + } + return entry.isMultiSpec, true +} + +// cacheSpec 写入多规格探测结果并清理已过期缓存。 +func (r *ItemSyncRepository) cacheSpec(cookieID, itemID string, value bool) { + if itemID == "" { + return + } + r.cacheMu.Lock() + defer r.cacheMu.Unlock() + if r.cache == nil { + r.cache = make(map[string]itemSpecCacheEntry) + } + // now 是本次缓存清理和写入的时间基准。 + now := time.Now() + // key、entry 分别表示待清理的缓存键和缓存项。 + for key, entry := range r.cache { + if now.After(entry.expiresAt) { + delete(r.cache, key) + } + } + r.cache[cookieID+"\x00"+itemID] = itemSpecCacheEntry{isMultiSpec: value, expiresAt: now.Add(10 * time.Minute)} +} + +// withCookieSnapshot 创建带完整 Cookie Jar 或平面 Cookie 的平台上下文。 +func withCookieSnapshot(ctx context.Context, detail db.CookiePlatformRuntimeData) (context.Context, *mtop.CookieSession) { + // snapshot、ok 保存 metadata 中的完整 Cookie Jar 快照及解析状态。 + snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) + if !ok { + return mtop.WithFlatCookieSession(ctx, detail.Value) + } + return mtop.WithCookieSnapshot(ctx, snapshot) +} + +// hasStoredCredential 判断账号平台视图是否包含可用 Cookie 凭证。 +func hasStoredCredential(detail db.CookiePlatformRuntimeData) bool { + if strings.TrimSpace(detail.Value) != "" { + return true + } + // complete 表示 metadata 是否包含完整 Cookie Jar。 + _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) + return complete +} + +// syncStageError 将底层错误包装为不泄露基础设施类型的应用错误。 +func syncStageError(kind itemapp.SyncErrorKind, err error) error { + return &itemapp.SyncError{Kind: kind, Err: err} +} + +// notifyRunningCookie 将平台返回的 Cookie 更新到运行中的账号实例。 +func (r *ItemSyncRepository) notifyRunningCookie(ctx context.Context, cookieID, value string) { + if r.updateRunningCookie != nil && value != "" { + r.updateRunningCookie(ctx, cookieID, value) + } +} + +// recoverExpired 在平台会话过期时通知账号恢复协调器。 +func (r *ItemSyncRepository) recoverExpired(ctx context.Context, cookieID string, err error) { + if r.recoverExpiredSession != nil && err != nil { + r.recoverExpiredSession(ctx, cookieID, err) + } +} + +// mtopClient 返回当前商品同步使用的平台客户端,并在测试构造缺失时提供默认实现。 +func (r *ItemSyncRepository) mtopClient() mtop.Client { + if r != nil && r.client != nil { + // client 表示当前回调返回的平台客户端。 + if client := r.client(); client != nil { + return client + } + } + return mtop.NewClient() +} diff --git a/internal/adapter/item_sync_test.go b/internal/adapter/item_sync_test.go new file mode 100644 index 0000000..9c021fb --- /dev/null +++ b/internal/adapter/item_sync_test.go @@ -0,0 +1,105 @@ +package adapter + +import ( + "context" + "fmt" + "sync" + "testing" + "time" + + "xianyu-go/internal/xianyu/mtop" +) + +// itemSyncDetailClient 是商品详情探测测试使用的平台客户端替身。 +type itemSyncDetailClient struct { + // Client 提供商品同步未涉及的平台客户端默认行为。 + mtop.Client + // detect 保存测试控制的多规格探测逻辑。 + detect func(context.Context, string, string) (bool, error) +} + +// DetectItemMultiSpec 执行测试注入的商品多规格探测逻辑。 +func (client *itemSyncDetailClient) DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) { + return client.detect(ctx, cookies, itemID) +} + +// TestItemSyncRepositoryEnrichMultiSpecBoundsConcurrency 验证同步适配器限制探测并发并复用缓存。 +func TestItemSyncRepositoryEnrichMultiSpecBoundsConcurrency(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // stateMu 保护远端探测并发统计。 + var stateMu sync.Mutex + // active、maxActive、probeCalls 保存当前并发数、峰值并发数和探测次数。 + active, maxActive, probeCalls := 0, 0, 0 + // client 是带并发统计的商品详情探测替身。 + client := &itemSyncDetailClient{detect: func(_ context.Context, cookies, itemID string) (bool, error) { + if cookies == "" || itemID == "" { + t.Fatalf("探测参数缺失:cookies=%q itemID=%q", cookies, itemID) + } + stateMu.Lock() + probeCalls++ + active++ + if active > maxActive { + maxActive = active + } + stateMu.Unlock() + time.Sleep(20 * time.Millisecond) + stateMu.Lock() + active-- + stateMu.Unlock() + return true, nil + }} + // repository 是使用测试数据库和平台替身的商品同步适配器。 + repository := NewItemSyncRepository(store, func() mtop.Client { return client }, nil, nil, nil) + // items 保存等待探测的商品列表。 + items := make([]mtop.ItemListItem, 8) + // index 表示当前商品在测试列表中的下标。 + for index := range items { + items[index].ID = fmt.Sprintf("probe-%d", index) + } + // err 保存首次批量多规格探测的错误。 + if err := repository.enrichMultiSpec(context.Background(), "unb=1; _m_h5_tk=t_1;", "cid", items); err != nil { + t.Fatalf("首次多规格探测失败:%v", err) + } + if maxActive > 4 { + t.Fatalf("探测并发=%d,超过上限 4", maxActive) + } + // index、item 分别表示商品下标和探测结果。 + for index, item := range items { + if !item.IsMultiSpec { + t.Fatalf("商品 %d 未标记为多规格", index) + } + } + // cachedItems 保存第二次调用使用的商品列表,验证适配器缓存命中。 + cachedItems := make([]mtop.ItemListItem, len(items)) + // index 表示缓存测试商品下标。 + for index := range cachedItems { + cachedItems[index].ID = fmt.Sprintf("probe-%d", index) + } + // err 保存第二次多规格探测的缓存校验错误。 + if err := repository.enrichMultiSpec(context.Background(), "unb=1; _m_h5_tk=t_1;", "cid", cachedItems); err != nil { + t.Fatalf("缓存多规格探测失败:%v", err) + } + if probeCalls != len(items) { + t.Fatalf("缓存命中后探测次数=%d,期望=%d", probeCalls, len(items)) + } +} + +// TestItemSyncRepositorySpecCacheExpires 验证同步适配器过期缓存不会继续返回旧值。 +func TestItemSyncRepositorySpecCacheExpires(t *testing.T) { + // repository 是仅用于验证缓存生命周期的零基础设施适配器。 + repository := &ItemSyncRepository{cache: map[string]itemSpecCacheEntry{ + "cid\x00item-1": {isMultiSpec: true, expiresAt: time.Now().Add(-time.Second)}, + }} + // value、ok 保存过期缓存的读取结果。 + value, ok := repository.cachedSpec("cid", "item-1") + if ok || value { + t.Fatalf("过期缓存不应命中:value=%v ok=%v", value, ok) + } + repository.cacheSpec("cid", "item-1", false) + value, ok = repository.cachedSpec("cid", "item-1") + if !ok || value { + t.Fatalf("新缓存结果异常:value=%v ok=%v", value, ok) + } +} diff --git a/internal/adapter/keyword_repository.go b/internal/adapter/keyword_repository.go new file mode 100644 index 0000000..83f25ea --- /dev/null +++ b/internal/adapter/keyword_repository.go @@ -0,0 +1,234 @@ +package adapter + +import ( + "context" + "errors" + + keywordsapp "xianyu-go/internal/application/keywords" + "xianyu-go/internal/db" +) + +// KeywordRepository 将关键词和指定商品回复数据库操作适配为应用层 Port。 +type KeywordRepository struct { + // store 保存数据库聚合入口;敏感账号字段不会被本适配器读取。 + store *db.Store +} + +// NewKeywordRepository 创建关键词数据库适配器。 +func NewKeywordRepository(store *db.Store) *KeywordRepository { + return &KeywordRepository{store: store} +} + +// List 查询指定用户账号的关键词规则,并转换为应用模型。 +func (r *KeywordRepository) List(ctx context.Context, userID int64, cookieID string) ([]keywordsapp.Keyword, error) { + // err 表示账号归属校验失败,阻止跨用户读取规则。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return nil, err + } + // rows 保存数据库返回的关键词规则行。 + rows, err := r.store.Keywords.AllRows(ctx, cookieID) + if err != nil { + return nil, err + } + // result 保存转换后的应用层关键词模型,不携带数据库对象。 + result := make([]keywordsapp.Keyword, 0, len(rows)) + // row 表示当前待转换的关键词数据库行。 + for _, row := range rows { + result = append(result, keywordModel(row)) + } + return result, nil +} + +// Add 创建一条指定用户账号的关键词规则。 +func (r *KeywordRepository) Add(ctx context.Context, userID int64, cookieID string, draft keywordsapp.Draft) (int64, error) { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return 0, err + } + return r.store.Keywords.Add(ctx, cookieID, draft.Keyword, draft.Reply, draft.ItemID, draft.Type, draft.ImageURL) +} + +// Replace 原子覆盖指定用户账号的全部关键词规则。 +func (r *KeywordRepository) Replace(ctx context.Context, userID int64, cookieID string, drafts []keywordsapp.Draft) error { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return err + } + // rows 保存转换后的数据库关键词写入行。 + rows := make([]db.KeywordRow, 0, len(drafts)) + // draft 表示当前待转换的应用层关键词草稿。 + for _, draft := range drafts { + rows = append(rows, db.KeywordRow{ + CookieID: cookieID, + Keyword: draft.Keyword, + Reply: draft.Reply, + ItemID: draft.ItemID, + Type: draft.Type, + ImageURL: draft.ImageURL, + }) + } + return r.store.Keywords.ReplaceForCookie(ctx, cookieID, rows) +} + +// Update 更新指定用户账号的一条关键词规则。 +func (r *KeywordRepository) Update(ctx context.Context, userID int64, cookieID string, id int64, draft keywordsapp.Draft) error { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return err + } + // err 表示数据库更新错误或目标规则不存在。 + err := r.store.Keywords.UpdateByID(ctx, db.KeywordRow{ + ID: id, CookieID: cookieID, Keyword: draft.Keyword, Reply: draft.Reply, + ItemID: draft.ItemID, Type: draft.Type, ImageURL: draft.ImageURL, + }) + if errors.Is(err, db.ErrNotFound) { + return keywordsapp.ErrNotFound + } + return err +} + +// DeleteByID 按 ID 删除指定用户账号的一条关键词规则。 +func (r *KeywordRepository) DeleteByID(ctx context.Context, userID int64, cookieID string, id int64) error { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return err + } + // err 表示数据库删除错误或目标规则不存在。 + err := r.store.Keywords.DeleteByID(ctx, cookieID, id) + if errors.Is(err, db.ErrNotFound) { + return keywordsapp.ErrNotFound + } + return err +} + +// DeleteByIndex 按稳定 ID 顺序的零基索引删除关键词规则。 +func (r *KeywordRepository) DeleteByIndex(ctx context.Context, userID int64, cookieID string, index int) error { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return err + } + // err 表示数据库删除错误或索引没有对应规则。 + err := r.store.Keywords.DeleteByIndex(ctx, cookieID, index) + if errors.Is(err, db.ErrNotFound) { + return keywordsapp.ErrNotFound + } + return err +} + +// ListItemReplies 查询当前用户所有账号的商品回复,并保持数据库返回顺序。 +func (r *KeywordRepository) ListItemReplies(ctx context.Context, userID int64) ([]keywordsapp.ItemReply, error) { + // err 表示适配器依赖或用户身份校验失败。 + if err := r.validateUser(userID); err != nil { + return nil, err + } + // cookieIDs 保存当前用户拥有的账号标识,不包含账号凭证。 + cookieIDs, err := r.store.Cookies.ListOwnedIDs(ctx, userID) + if err != nil { + return nil, err + } + // result 保存跨账号聚合后的商品回复应用模型。 + result := make([]keywordsapp.ItemReply, 0) + // cookieID 表示当前遍历的用户账号。 + for _, cookieID := range cookieIDs { + // queryErr 表示当前账号商品回复读取失败。 + // rows 保存当前账号的商品回复数据库行。 + rows, queryErr := r.store.ItemReps.AllForUser(ctx, cookieID) + if queryErr != nil { + return nil, queryErr + } + // row 表示当前待转换的商品回复行。 + for _, row := range rows { + result = append(result, itemReplyModel(row)) + } + } + return result, nil +} + +// GetItemReply 读取指定用户账号和商品的商品回复。 +func (r *KeywordRepository) GetItemReply(ctx context.Context, userID int64, cookieID, itemID string) (keywordsapp.ItemReply, error) { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return keywordsapp.ItemReply{}, err + } + // row、err 保存商品回复数据库行及读取错误。 + row, err := r.store.ItemReps.Get(ctx, cookieID, itemID) + if errors.Is(err, db.ErrNotFound) { + return keywordsapp.ItemReply{}, keywordsapp.ErrNotFound + } + if err != nil { + return keywordsapp.ItemReply{}, err + } + return itemReplyModel(*row), nil +} + +// SetItemReply 覆盖指定用户账号和商品的商品回复。 +func (r *KeywordRepository) SetItemReply(ctx context.Context, userID int64, cookieID, itemID, content string) error { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return err + } + return r.store.ItemReps.Set(ctx, cookieID, itemID, content) +} + +// DeleteItemReply 删除指定用户账号和商品的商品回复。 +func (r *KeywordRepository) DeleteItemReply(ctx context.Context, userID int64, cookieID, itemID string) error { + // err 表示账号归属校验失败。 + if err := r.authorize(ctx, userID, cookieID); err != nil { + return err + } + return r.store.ItemReps.Delete(ctx, cookieID, itemID) +} + +// authorize 只查询账号归属,不读取或解密任何凭证字段。 +func (r *KeywordRepository) authorize(ctx context.Context, userID int64, cookieID string) error { + // err 表示适配器依赖或用户身份校验失败。 + if err := r.validateUser(userID); err != nil { + return err + } + if cookieID == "" { + return keywordsapp.ErrInvalidInput + } + // owned、err 保存当前用户对账号的直接归属结果及查询错误。 + owned, err := r.store.Cookies.ExistsOwned(ctx, userID, cookieID) + if err != nil { + return err + } + if owned { + return nil + } + // ownerID、err 保存账号所有者标识及读取错误,用于区分不存在和跨用户访问。 + ownerID, err := r.store.Cookies.GetOwnerID(ctx, cookieID) + if errors.Is(err, db.ErrNotFound) { + return keywordsapp.ErrNotFound + } + if err != nil { + return err + } + if ownerID != userID { + return keywordsapp.ErrForbidden + } + return nil +} + +// validateUser 检查数据库适配器和用户身份是否可用。 +func (r *KeywordRepository) validateUser(userID int64) error { + if r == nil || r.store == nil || r.store.Cookies == nil || r.store.Keywords == nil || r.store.ItemReps == nil { + return errors.New("关键词数据库适配器未初始化") + } + if userID <= 0 { + return keywordsapp.ErrInvalidUser + } + return nil +} + +// keywordModel 将数据库关键词行转换为应用模型。 +func keywordModel(row db.KeywordRow) keywordsapp.Keyword { + return keywordsapp.Keyword{ID: row.ID, CookieID: row.CookieID, Keyword: row.Keyword, Reply: row.Reply, ItemID: row.ItemID, Type: row.Type, ImageURL: row.ImageURL} +} + +// itemReplyModel 将数据库商品回复行转换为应用模型。 +func itemReplyModel(row db.ItemReply) keywordsapp.ItemReply { + return keywordsapp.ItemReply{ItemID: row.ItemID, CookieID: row.CookieID, ReplyContent: row.ReplyContent} +} + +var _ keywordsapp.Repository = (*KeywordRepository)(nil) diff --git a/internal/adapter/keyword_repository_test.go b/internal/adapter/keyword_repository_test.go new file mode 100644 index 0000000..f72d9de --- /dev/null +++ b/internal/adapter/keyword_repository_test.go @@ -0,0 +1,132 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + keywordsapp "xianyu-go/internal/application/keywords" +) + +// TestKeywordRepositoryCRUDMapping 验证关键词和指定商品回复的 SQLite 映射及成功路径。 +func TestKeywordRepositoryCRUDMapping(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是待验证的关键词数据库适配器。 + repository := NewKeywordRepository(store) + // ctx 是本测试数据库操作共用的非取消上下文。 + ctx := context.Background() + // owner 是测试模板中的关键词所有者。 + owner, ownerErr := store.Users.GetByUsername(ctx, "admin") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // keywordID、createErr 保存关键词创建结果。 + keywordID, createErr := repository.Add(ctx, owner.ID, "cid", keywordsapp.Draft{Keyword: "价格", Reply: "50元", Type: "text", ItemID: "item-1"}) + if createErr != nil || keywordID <= 0 { + t.Fatalf("创建关键词失败 id=%d err=%v", keywordID, createErr) + } + // rows、listErr 保存关键词列表结果。 + rows, listErr := repository.List(ctx, owner.ID, "cid") + if listErr != nil || len(rows) != 1 || rows[0].Keyword != "价格" { + t.Fatalf("关键词列表异常 rows=%+v err=%v", rows, listErr) + } + // updateErr 保存关键词更新结果。 + updateErr := repository.Update(ctx, owner.ID, "cid", keywordID, keywordsapp.Draft{Keyword: "新价格", Reply: "60元", Type: "text"}) + if updateErr != nil { + t.Fatal(updateErr) + } + // replaceErr 保存批量替换结果。 + replaceErr := repository.Replace(ctx, owner.ID, "cid", []keywordsapp.Draft{{Keyword: "图片", Type: "image", ImageURL: "https://example.invalid/a.png"}}) + if replaceErr != nil { + t.Fatal(replaceErr) + } + // replacedRows、replacedErr 保存批量替换后的列表结果。 + replacedRows, replacedErr := repository.List(ctx, owner.ID, "cid") + if replacedErr != nil || len(replacedRows) != 1 || replacedRows[0].Type != "image" { + t.Fatalf("替换结果异常 rows=%+v err=%v", replacedRows, replacedErr) + } + // setErr 保存指定商品回复写入结果。 + if setErr := repository.SetItemReply(ctx, owner.ID, "cid", "item-1", "专属回复"); setErr != nil { + t.Fatal(setErr) + } + // itemReply、getErr 保存指定商品回复读取结果。 + itemReply, getErr := repository.GetItemReply(ctx, owner.ID, "cid", "item-1") + if getErr != nil || itemReply.ReplyContent != "专属回复" { + t.Fatalf("商品回复读取异常 row=%+v err=%v", itemReply, getErr) + } + // itemRows、itemListErr 保存指定商品回复列表结果。 + itemRows, itemListErr := repository.ListItemReplies(ctx, owner.ID) + if itemListErr != nil || len(itemRows) != 1 || itemRows[0].CookieID != "cid" { + t.Fatalf("商品回复列表异常 rows=%+v err=%v", itemRows, itemListErr) + } + // deleteReplyErr 保存指定商品回复删除结果。 + if deleteReplyErr := repository.DeleteItemReply(ctx, owner.ID, "cid", "item-1"); deleteReplyErr != nil { + t.Fatal(deleteReplyErr) + } + // deleteErr 保存关键词 ID 删除结果。 + if deleteErr := repository.DeleteByID(ctx, owner.ID, "cid", keywordID); deleteErr != nil && !errors.Is(deleteErr, keywordsapp.ErrNotFound) { + t.Fatal(deleteErr) + } +} + +// TestKeywordRepositoryRejectsCrossUserAccess 验证跨用户账号无法读写关键词或商品回复。 +func TestKeywordRepositoryRejectsCrossUserAccess(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试数据库操作共用的非取消上下文。 + ctx := context.Background() + // created、createErr 保存第二个用户的创建结果。 + created, createErr := store.Users.Create(ctx, "other", "other@example.invalid", "pw") + if createErr != nil || !created { + t.Fatal(createErr) + } + // other 是第二个用户的非敏感身份摘要。 + other, otherErr := store.Users.GetByUsername(ctx, "other") + if otherErr != nil { + t.Fatal(otherErr) + } + // saveErr 保存第二个用户账号的创建结果。 + if saveErr := store.Cookies.Save(ctx, "other-cid", "cookie", other.ID); saveErr != nil { + t.Fatal(saveErr) + } + // repository 是待验证的关键词数据库适配器。 + repository := NewKeywordRepository(store) + // err 保存跨用户读取结果。 + _, err := repository.List(ctx, 1, "other-cid") + if !errors.Is(err, keywordsapp.ErrForbidden) { + t.Fatalf("跨用户读取应返回 ErrForbidden,err=%v", err) + } + // writeErr 保存跨用户写入结果。 + writeErr := repository.SetItemReply(ctx, 1, "other-cid", "item", "reply") + if !errors.Is(writeErr, keywordsapp.ErrForbidden) { + t.Fatalf("跨用户写入应返回 ErrForbidden,err=%v", writeErr) + } +} + +// TestKeywordRepositoryPropagatesInfrastructureErrors 验证数据库故障不伪装为资源不存在。 +func TestKeywordRepositoryPropagatesInfrastructureErrors(t *testing.T) { + // store 是随后主动关闭数据库连接的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试存储的关键词适配器。 + repository := NewKeywordRepository(store) + // closeErr 保存关闭测试数据库的结果。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // err 保存数据库关闭后的列表结果。 + _, err := repository.List(context.Background(), 1, "cid") + if err == nil || errors.Is(err, keywordsapp.ErrNotFound) || errors.Is(err, keywordsapp.ErrForbidden) { + t.Fatalf("数据库故障应原样返回,err=%v", err) + } + // missingErr 保存缺少数据库适配器依赖时的装配错误。 + _, missingErr := NewKeywordRepository(nil).List(context.Background(), 1, "cid") + if missingErr == nil { + t.Fatal("缺少 Store 时应返回装配错误") + } +} + +var _ keywordsapp.Repository = (*KeywordRepository)(nil) diff --git a/internal/adapter/notification_repository.go b/internal/adapter/notification_repository.go new file mode 100644 index 0000000..413d670 --- /dev/null +++ b/internal/adapter/notification_repository.go @@ -0,0 +1,198 @@ +package adapter + +import ( + "context" + "errors" + + notificationsapp "xianyu-go/internal/application/notifications" + "xianyu-go/internal/db" +) + +// NotificationChannelRepository 将通知渠道数据库能力限制在应用层定义的端口内。 +type NotificationChannelRepository struct { + // store 保存数据库聚合入口,仅在适配器内部使用;配置字段不会进入摘要模型。 + store *db.Store +} + +// NewNotificationChannelRepository 构造通知渠道应用端口适配器;数据库依赖不完整时返回 nil。 +func NewNotificationChannelRepository(store *db.Store) notificationsapp.ChannelRepository { + if store == nil || store.Notifications == nil || store.Cookies == nil { + return nil + } + return NotificationChannelRepository{store: store} +} + +// ListChannels 查询渠道摘要并丢弃敏感配置。 +func (r NotificationChannelRepository) ListChannels(ctx context.Context, userID int64) ([]notificationsapp.ChannelSummary, error) { + // rows、err 保存数据库渠道非敏感摘要;列表路径不会读取或解密 Config。 + rows, err := r.store.Notifications.ListChannelSummariesForUser(ctx, userID) + if err != nil { + return nil, err + } + // summaries 保存不含渠道配置的应用摘要。 + summaries := make([]notificationsapp.ChannelSummary, 0, len(rows)) + // row 表示当前待转换的数据库渠道行。 + for _, row := range rows { + summaries = append(summaries, notificationsapp.ChannelSummary{ID: row.ID, Name: row.Name, Type: row.Type, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID}) + } + return summaries, nil +} + +// GetChannelForUpdate 查询归属渠道的完整记录,仅供应用层合并部分更新。 +func (r NotificationChannelRepository) GetChannelForUpdate(ctx context.Context, channelID, userID int64) (*notificationsapp.ChannelRecord, error) { + // row、err 保存带用户归属的数据库渠道记录。 + row, err := r.store.Notifications.GetChannelRowForUser(ctx, channelID, userID) + if err != nil { + return nil, normalizeNotificationRepositoryError(err) + } + if row == nil { + return nil, nil + } + return ¬ificationsapp.ChannelRecord{ID: row.ID, Name: row.Name, Type: row.Type, Config: row.Config, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID}, nil +} + +// CreateChannel 将应用输入转换为数据库行并创建渠道。 +func (r NotificationChannelRepository) CreateChannel(ctx context.Context, userID int64, input notificationsapp.ChannelInput) (int64, error) { + // row 保存待加密写入数据库的渠道行;Config 不向 HTTP 返回。 + row := db.NotificationChannelRow{Name: input.Name, Type: input.Type, Config: input.Config, EventTypes: input.EventTypes, Enabled: input.Enabled, UserID: userID} + return r.store.Notifications.CreateChannel(ctx, &row) +} + +// UpdateChannel 将应用层完整渠道记录转换为数据库更新,并归一化资源错误。 +func (r NotificationChannelRepository) UpdateChannel(ctx context.Context, userID int64, record notificationsapp.ChannelRecord) error { + // row 保存待加密写入数据库的渠道行;调用方已完成归属和字段校验。 + row := db.NotificationChannelRow{ID: record.ID, Name: record.Name, Type: record.Type, Config: record.Config, EventTypes: record.EventTypes, Enabled: record.Enabled, UserID: userID} + return normalizeNotificationRepositoryError(r.store.Notifications.UpdateChannelForUser(ctx, &row, userID)) +} + +// DeleteChannel 删除用户拥有的渠道并统一转换资源错误。 +func (r NotificationChannelRepository) DeleteChannel(ctx context.Context, channelID, userID int64) error { + return normalizeNotificationRepositoryError(r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID)) +} + +// OwnsChannel 查询通知渠道归属,不读取配置内容。 +func (r NotificationChannelRepository) OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error) { + return r.store.Notifications.OwnsChannel(ctx, channelID, userID) +} + +// OwnsAccount 查询账号归属,不读取或解密 Cookie。 +func (r NotificationChannelRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) { + return r.store.Cookies.ExistsOwned(ctx, userID, cookieID) +} + +// ListBindings 查询绑定摘要并转换为应用模型。 +func (r NotificationChannelRepository) ListBindings(ctx context.Context, userID int64) ([]notificationsapp.BindingSummary, error) { + // rows、err 保存数据库绑定摘要及错误。 + rows, err := r.store.Notifications.ListBindingsForUser(ctx, userID) + if err != nil { + return nil, err + } + // bindings 保存不含配置的应用绑定摘要。 + bindings := make([]notificationsapp.BindingSummary, 0, len(rows)) + // row 表示当前待转换的数据库绑定行。 + for _, row := range rows { + bindings = append(bindings, notificationsapp.BindingSummary{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled}) + } + return bindings, nil +} + +// GetBindingIDs 查询账号启用的通知渠道 ID。 +func (r NotificationChannelRepository) GetBindingIDs(ctx context.Context, cookieID string) ([]int64, error) { + return r.store.Notifications.AccountBindings(ctx, cookieID) +} + +// SetBindings 覆盖保存账号绑定,并保留数据库事务和跨归属校验。 +func (r NotificationChannelRepository) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error { + return normalizeNotificationRepositoryError(r.store.Notifications.SetBindings(ctx, cookieID, channelIDs)) +} + +// SetSingleBinding 更新单个账号绑定状态并归一化资源错误。 +func (r NotificationChannelRepository) SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error { + return normalizeNotificationRepositoryError(r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled)) +} + +// DeleteBinding 删除用户的一条绑定并归一化资源错误。 +func (r NotificationChannelRepository) DeleteBinding(ctx context.Context, userID, bindingID int64) error { + return normalizeNotificationRepositoryError(r.store.Notifications.DeleteBinding(ctx, userID, bindingID)) +} + +// DeleteAccountBindings 删除用户账号的全部绑定并归一化资源错误。 +func (r NotificationChannelRepository) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error { + return normalizeNotificationRepositoryError(r.store.Notifications.DeleteAccountBindings(ctx, userID, cookieID)) +} + +// normalizeNotificationRepositoryError 将数据库归属错误转换为应用错误,隐藏基础设施类型。 +func normalizeNotificationRepositoryError(err error) error { + if errors.Is(err, db.ErrNotFound) { + return notificationsapp.ErrChannelNotFound + } + if errors.Is(err, db.ErrForbidden) { + return notificationsapp.ErrChannelForbidden + } + return err +} + +// NotificationUncertainRepository 将通知不确定状态查询限制在非敏感摘要端口内。 +type NotificationUncertainRepository struct { + // store 保存数据库聚合入口,仅在脱敏摘要适配器内使用。 + store *db.Store +} + +// NewNotificationUncertainRepository 创建通知不确定状态查询适配器;数据库依赖缺失时返回 nil。 +func NewNotificationUncertainRepository(store *db.Store) notificationsapp.Repository { + if store == nil || store.Notifications == nil { + return nil + } + return NotificationUncertainRepository{store: store} +} + +// ListUncertainForUser 查询指定用户的不确定通知摘要,并转换为应用模型。 +func (r NotificationUncertainRepository) ListUncertainForUser(ctx context.Context, userID int64, limit int) ([]notificationsapp.UncertainSummary, error) { + // rows、err 保存数据库摘要查询结果及错误。 + rows, err := r.store.Notifications.ListUncertainOutboxForUser(ctx, userID, limit) + if err != nil { + return nil, err + } + return newNotificationUncertainApplicationSummaries(rows), nil +} + +// CountUncertainForUser 统计指定用户的不确定通知数量。 +func (r NotificationUncertainRepository) CountUncertainForUser(ctx context.Context, userID int64) (int, error) { + return r.store.Notifications.CountUncertainOutboxForUser(ctx, userID) +} + +// ListUncertainForAdmin 查询全局不确定通知摘要,并转换为应用模型。 +func (r NotificationUncertainRepository) ListUncertainForAdmin(ctx context.Context, limit int) ([]notificationsapp.UncertainSummary, error) { + // rows、err 保存数据库全局摘要查询结果及错误。 + rows, err := r.store.Notifications.ListUncertainOutboxForAdmin(ctx, limit) + if err != nil { + return nil, err + } + return newNotificationUncertainApplicationSummaries(rows), nil +} + +// CountUncertainForAdmin 统计全局不确定通知数量。 +func (r NotificationUncertainRepository) CountUncertainForAdmin(ctx context.Context) (int, error) { + return r.store.Notifications.CountUncertainOutboxForAdmin(ctx) +} + +// newNotificationUncertainApplicationSummaries 将数据库摘要转换为不含正文的应用模型。 +func newNotificationUncertainApplicationSummaries(rows []db.NotificationUncertainSummary) []notificationsapp.UncertainSummary { + // summaries 保存脱离数据库模型的非敏感通知摘要。 + summaries := make([]notificationsapp.UncertainSummary, 0, len(rows)) + // row 表示当前待转换的数据库通知摘要。 + for _, row := range rows { + summaries = append(summaries, notificationsapp.UncertainSummary{ + ID: row.ID, ChannelID: row.ChannelID, OwnerUserID: row.OwnerUserID, + EventType: row.EventType, AttemptCount: row.AttemptCount, + UncertainAt: row.UncertainAt, HasError: row.HasError, + }) + } + return summaries +} + +// 编译期确认通知渠道适配器覆盖应用层定义的全部能力。 +var _ notificationsapp.ChannelRepository = NotificationChannelRepository{} + +// 编译期确认通知不确定状态适配器覆盖应用层定义的全部能力。 +var _ notificationsapp.Repository = NotificationUncertainRepository{} diff --git a/internal/adapter/notification_repository_test.go b/internal/adapter/notification_repository_test.go new file mode 100644 index 0000000..d0167b8 --- /dev/null +++ b/internal/adapter/notification_repository_test.go @@ -0,0 +1,90 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + notificationsapp "xianyu-go/internal/application/notifications" + "xianyu-go/internal/db" +) + +// TestNotificationChannelRepositoryKeepsConfigOutOfSummaries 验证渠道摘要映射不携带敏感配置。 +func TestNotificationChannelRepositoryKeepsConfigOutOfSummaries(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试数据库操作使用的非取消上下文。 + ctx := context.Background() + // owner、ownerErr 保存模板管理员及查询错误。 + owner, ownerErr := store.Users.GetByUsername(ctx, "admin") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // channelID、createErr 保存带敏感配置的渠道创建结果。 + channelID, createErr := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{Name: "邮件", Type: "email", Config: `{"password":"secret"}`, EventTypes: "order", Enabled: true, UserID: owner.ID}) + if createErr != nil { + t.Fatal(createErr) + } + // repository 是待验证的通知渠道应用端口适配器。 + repository := NewNotificationChannelRepository(store) + // summaries、listErr 保存适配器返回的脱敏渠道列表。 + summaries, listErr := repository.ListChannels(ctx, owner.ID) + if listErr != nil || len(summaries) != 1 || summaries[0].ID != channelID { + t.Fatalf("渠道摘要映射异常 summaries=%+v err=%v", summaries, listErr) + } + // record、recordErr 保存更新路径读取的完整配置记录;该值只应停留在应用更新端口内。 + record, recordErr := repository.GetChannelForUpdate(ctx, channelID, owner.ID) + if recordErr != nil || record == nil || record.Config == "" { + t.Fatalf("渠道更新记录缺少配置 record=%+v err=%v", record, recordErr) + } +} + +// TestNotificationChannelRepositoryMapsMissingResources 验证资源缺失统一转换为应用层渠道错误。 +func TestNotificationChannelRepositoryMapsMissingResources(t *testing.T) { + // store 是使用临时 SQLite 数据库的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // ctx 是本测试数据库操作使用的非取消上下文。 + ctx := context.Background() + // repository 是待验证的通知渠道应用端口适配器。 + repository := NewNotificationChannelRepository(store) + // updateErr 保存更新不存在渠道时的应用层错误。 + updateErr := repository.UpdateChannel(ctx, 1, notificationsapp.ChannelRecord{ID: 999, Name: "missing", Type: "webhook"}) + if !errors.Is(updateErr, notificationsapp.ErrChannelNotFound) { + t.Fatalf("不存在渠道更新应映射为缺失错误: %v", updateErr) + } + // deleteErr 保存删除不存在渠道时的应用层错误。 + deleteErr := repository.DeleteChannel(ctx, 999, 1) + if !errors.Is(deleteErr, notificationsapp.ErrChannelNotFound) { + t.Fatalf("不存在渠道删除应映射为缺失错误: %v", deleteErr) + } + // nilRepository 验证缺少数据库依赖时不会伪造可用端口。 + nilRepository := NewNotificationChannelRepository(nil) + if nilRepository != nil { + t.Fatal("缺少 Store 时通知渠道适配器应返回 nil") + } +} + +// TestNotificationUncertainRepositoryRejectsClosedStore 验证不确定通知适配器透传基础设施错误且不暴露正文。 +func TestNotificationUncertainRepositoryRejectsClosedStore(t *testing.T) { + // store 是随后关闭连接的临时 SQLite 数据库。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试存储的不确定通知适配器。 + repository := NewNotificationUncertainRepository(store) + // closeErr 保存关闭测试数据库时的资源错误。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // _, listErr 保存数据库关闭后的普通用户查询错误。 + _, listErr := repository.ListUncertainForUser(context.Background(), 1, 10) + if listErr == nil { + t.Fatal("数据库关闭后不确定通知查询应返回基础设施错误") + } + // nilRepository 验证缺少数据库依赖时返回 nil。 + nilRepository := NewNotificationUncertainRepository(nil) + if nilRepository != nil { + t.Fatal("缺少 Store 时不确定通知适配器应返回 nil") + } +} diff --git a/internal/adapter/order_boundary.go b/internal/adapter/order_boundary.go new file mode 100644 index 0000000..4ac2d12 --- /dev/null +++ b/internal/adapter/order_boundary.go @@ -0,0 +1,38 @@ +package adapter + +import ( + "errors" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" +) + +// NormalizeOrderError 将数据库订单错误转换为应用层稳定错误,阻止存储错误类型穿过适配边界。 +func NormalizeOrderError(err error) error { + if errors.Is(err, db.ErrNotFound) { + return orderapp.ErrNotFound + } + if errors.Is(err, db.ErrForbidden) { + return orderapp.ErrForbidden + } + return err +} + +// OrderForAutomation 将应用订单转换为尚未迁移完成的自动化中心数据库模型。 +func OrderForAutomation(order *orderapp.Order) *db.Order { + if order == nil { + return nil + } + return &db.Order{ + OrderID: order.OrderID, ItemID: order.ItemID, BuyerID: order.BuyerID, + SpecName: order.SpecName, SpecValue: order.SpecValue, Quantity: order.Quantity, + Amount: order.Amount, OrderStatus: order.OrderStatus, CookieID: order.CookieID, + IsBargain: order.IsBargain, ReceiverName: order.ReceiverName, + ReceiverPhone: order.ReceiverPhone, ReceiverAddr: order.ReceiverAddress, + ReceiverCity: order.ReceiverCity, Version: order.Version, ChatID: order.ChatID, + SystemShipped: order.SystemShipped, PaidAt: order.PaidAt, ShippedAt: order.ShippedAt, + CompletedAt: order.CompletedAt, BuyerReviewedAt: order.BuyerReviewedAt, + LastReviewRequestAt: order.LastReviewRequestAt, ReviewRequestCount: order.ReviewRequestCount, + CreatedAt: order.CreatedAt, UpdatedAt: order.UpdatedAt, + } +} diff --git a/internal/adapter/order_boundary_test.go b/internal/adapter/order_boundary_test.go new file mode 100644 index 0000000..d0bc070 --- /dev/null +++ b/internal/adapter/order_boundary_test.go @@ -0,0 +1,41 @@ +package adapter + +import ( + "errors" + "testing" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" +) + +// TestNormalizeOrderError 验证数据库错误不会越过订单应用适配边界。 +func TestNormalizeOrderError(t *testing.T) { + // cases 保存数据库错误到应用错误的映射样例及空错误行为。 + cases := []struct { + name string + input error + want error + }{ + {name: "not found", input: db.ErrNotFound, want: orderapp.ErrNotFound}, + {name: "forbidden", input: db.ErrForbidden, want: orderapp.ErrForbidden}, + {name: "wrapped not found", input: errors.Join(errors.New("查询失败"), db.ErrNotFound), want: orderapp.ErrNotFound}, + {name: "other", input: errors.New("数据库暂时不可用"), want: nil}, + {name: "nil", input: nil, want: nil}, + } + // testCase 表示当前错误映射样例。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // got 保存适配器归一化后的错误。 + got := NormalizeOrderError(testCase.input) + if testCase.want == nil { + if got != testCase.input { + t.Fatalf("error identity changed: got=%v want=%v", got, testCase.input) + } + return + } + if !errors.Is(got, testCase.want) { + t.Fatalf("error=%v want=%v", got, testCase.want) + } + }) + } +} diff --git a/internal/adapter/order_reconciliation.go b/internal/adapter/order_reconciliation.go new file mode 100644 index 0000000..da70188 --- /dev/null +++ b/internal/adapter/order_reconciliation.go @@ -0,0 +1,36 @@ +package adapter + +import ( + "context" + "errors" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" +) + +// OrderReconciliationRepository 将订单应用层补偿 Port 适配为数据库写入。 +// 数据库聚合仅在本适配器内部可见,订单应用服务和 Server 运行时不直接访问它。 +type OrderReconciliationRepository struct { + // store 保存补偿记录使用的数据库聚合入口。 + store *db.Store +} + +// NewOrderReconciliationRepository 创建订单补偿记录数据库适配器。 +// 缺少 Store 或补偿仓储时返回 nil,由调用方在运行时边界报告装配错误。 +func NewOrderReconciliationRepository(store *db.Store) *OrderReconciliationRepository { + if store == nil || store.Reconciliations == nil { + return nil + } + return &OrderReconciliationRepository{store: store} +} + +// RecordReconciliation 创建外部动作成功、本地状态待补偿的记录。 +func (r *OrderReconciliationRepository) RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) { + if r == nil || r.store == nil || r.store.Reconciliations == nil { + return "", errors.New("订单补偿存储未初始化") + } + return r.store.Reconciliations.CreatePending(ctx, orderID, cookieID, kind, message) +} + +// 确保数据库适配器覆盖订单应用层声明的补偿 Port。 +var _ orderapp.ReconciliationRecorder = (*OrderReconciliationRepository)(nil) diff --git a/internal/adapter/order_reconciliation_test.go b/internal/adapter/order_reconciliation_test.go new file mode 100644 index 0000000..e4172cd --- /dev/null +++ b/internal/adapter/order_reconciliation_test.go @@ -0,0 +1,57 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + orderapp "xianyu-go/internal/application/orders" +) + +// TestOrderReconciliationRepositoryRecordsPending 验证补偿应用模型能写入数据库并返回记录标识。 +func TestOrderReconciliationRepositoryRecordsPending(t *testing.T) { + // store、cleanup 保存当前测试使用的 SQLite 存储及资源清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 保存绑定测试数据库的订单补偿适配器。 + repository := NewOrderReconciliationRepository(store) + // recordID、err 保存补偿记录写入结果及错误。 + recordID, err := repository.RecordReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "本地写入失败") + if err != nil || recordID == "" { + t.Fatalf("创建补偿记录失败: id=%q err=%v", recordID, err) + } + // records、listErr 保存数据库扫描到的待补偿记录及错误。 + records, listErr := store.Reconciliations.ListPending(context.Background(), 10) + if listErr != nil || len(records) != 1 || records[0].ID != recordID || records[0].OrderID != "order-1" || records[0].Kind != "manual_status_ship" { + t.Fatalf("补偿记录映射异常: records=%+v err=%v", records, listErr) + } +} + +// TestOrderReconciliationRepositoryRejectsMissingDependency 验证缺少数据库依赖时适配器快速失败。 +func TestOrderReconciliationRepositoryRejectsMissingDependency(t *testing.T) { + // repository 保存未装配数据库时返回的空适配器。 + repository := NewOrderReconciliationRepository(nil) + // recordID、err 保存缺少依赖时的写入结果。 + recordID, err := repository.RecordReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "失败") + if recordID != "" || err == nil { + t.Fatalf("缺少数据库时应返回装配错误: id=%q err=%v", recordID, err) + } +} + +// TestOrderReconciliationRepositoryPropagatesPersistenceError 验证数据库关闭后的错误不会被伪装为成功。 +func TestOrderReconciliationRepositoryPropagatesPersistenceError(t *testing.T) { + // store、cleanup 保存随后关闭数据库连接的测试存储。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 保存绑定已关闭数据库的订单补偿适配器。 + repository := NewOrderReconciliationRepository(store) + // closeErr 表示关闭测试数据库连接时产生的资源释放错误。 + if closeErr := store.DB.Close(); closeErr != nil { + t.Fatal(closeErr) + } + // recordID、err 保存底层数据库故障的写入结果。 + recordID, err := repository.RecordReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "失败") + if recordID != "" || err == nil || errors.Is(err, orderapp.ErrNotFound) { + t.Fatalf("数据库故障应透传持久化错误: id=%q err=%v", recordID, err) + } +} diff --git a/internal/server/order_repository.go b/internal/adapter/order_repository.go similarity index 77% rename from internal/server/order_repository.go rename to internal/adapter/order_repository.go index 92e56a3..a5599aa 100644 --- a/internal/server/order_repository.go +++ b/internal/adapter/order_repository.go @@ -1,4 +1,4 @@ -package server +package adapter import ( "context" @@ -8,24 +8,24 @@ import ( "xianyu-go/internal/db" ) -// storeOrderRepository 将完整 Store 适配为订单应用服务窄 repository。 -type storeOrderRepository struct { +// OrderRepository 将数据库 Store 适配为订单应用服务窄 repository。 +type OrderRepository struct { // store 保存数据库聚合入口,仅在适配器内部使用。 store *db.Store } // ExistsOwned 委托账号归属查询。 -func (r storeOrderRepository) ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error) { +func (r OrderRepository) ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error) { return r.store.Cookies.ExistsOwned(ctx, userID, cookieID) } // ListOwnedIDs 委托用户账号列表查询。 -func (r storeOrderRepository) ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) { +func (r OrderRepository) ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) { return r.store.Cookies.ListOwnedIDs(ctx, userID) } // ListOrdersForUser 委托用户订单列表查询。 -func (r storeOrderRepository) ListOrdersForUser(ctx context.Context, filter orderapp.ListFilter) ([]orderapp.OrderRow, int, error) { +func (r OrderRepository) ListOrdersForUser(ctx context.Context, filter orderapp.ListFilter) ([]orderapp.OrderRow, int, error) { // rows、total、err 是数据库订单列表查询结果及其错误。 rows, total, err := r.store.Orders.ListForUser(ctx, db.OrderListFilter{ UserID: filter.UserID, CookieID: filter.CookieID, Status: filter.Status, @@ -97,7 +97,7 @@ func platformRuntimeDataFromDB(data db.CookiePlatformRuntimeData) *orderapp.Plat } // GetOrder 委托订单详情查询。 -func (r storeOrderRepository) GetOrder(ctx context.Context, orderID string) (*orderapp.Order, error) { +func (r OrderRepository) GetOrder(ctx context.Context, orderID string) (*orderapp.Order, error) { // order 和 err 保存数据库订单查询结果及其错误。 order, err := r.store.Orders.Get(ctx, orderID) if err != nil { @@ -107,7 +107,7 @@ func (r storeOrderRepository) GetOrder(ctx context.Context, orderID string) (*or } // FindOrder 委托订单查询并把数据库的不存在错误转换为 exists=false。 -func (r storeOrderRepository) FindOrder(ctx context.Context, orderID string) (*orderapp.Order, bool, error) { +func (r OrderRepository) FindOrder(ctx context.Context, orderID string) (*orderapp.Order, bool, error) { // order、err 保存数据库订单查询结果及其错误。 order, err := r.store.Orders.Get(ctx, orderID) if errors.Is(err, db.ErrNotFound) { @@ -120,7 +120,7 @@ func (r storeOrderRepository) FindOrder(ctx context.Context, orderID string) (*o } // FindOrdersByIDs 委托数据库批量读取订单并转换为应用实体。 -func (r storeOrderRepository) FindOrdersByIDs(ctx context.Context, orderIDs []string) (map[string]*orderapp.Order, error) { +func (r OrderRepository) FindOrdersByIDs(ctx context.Context, orderIDs []string) (map[string]*orderapp.Order, error) { // orders、err 保存数据库批量订单及查询错误。 orders, err := r.store.Orders.FindByIDs(ctx, orderIDs) if err != nil { @@ -136,7 +136,7 @@ func (r storeOrderRepository) FindOrdersByIDs(ctx context.Context, orderIDs []st } // GetItem 委托商品信息查询。 -func (r storeOrderRepository) GetItem(ctx context.Context, cookieID, itemID string) (*orderapp.ItemInfo, error) { +func (r OrderRepository) GetItem(ctx context.Context, cookieID, itemID string) (*orderapp.ItemInfo, error) { // item 和 err 保存数据库商品查询结果及其错误。 item, err := r.store.Items.Get(ctx, cookieID, itemID) if err != nil { @@ -146,12 +146,12 @@ func (r storeOrderRepository) GetItem(ctx context.Context, cookieID, itemID stri } // SoftDeleteOrder 委托订单逻辑删除。 -func (r storeOrderRepository) SoftDeleteOrder(ctx context.Context, orderID string) (bool, error) { +func (r OrderRepository) SoftDeleteOrder(ctx context.Context, orderID string) (bool, error) { return r.store.Orders.SoftDelete(ctx, orderID) } // WithTransaction 创建、提交或回滚订单事务。 -func (r storeOrderRepository) WithTransaction(ctx context.Context, work func(orderapp.Writer) error) error { +func (r OrderRepository) WithTransaction(ctx context.Context, work func(orderapp.Writer) error) error { // tx 和 err 保存事务创建结果。 tx, err := r.store.DB.BeginTx(ctx, nil) if err != nil { @@ -165,7 +165,7 @@ func (r storeOrderRepository) WithTransaction(ctx context.Context, work func(ord } }() // writer 是隐藏数据库事务细节的订单写入适配器。 - writer := storeOrderWriter{store: r.store, tx: tx} + writer := orderWriter{store: r.store, tx: tx} // err 保存事务工作函数的执行错误。 if err := work(writer); err != nil { return err @@ -178,8 +178,8 @@ func (r storeOrderRepository) WithTransaction(ctx context.Context, work func(ord return nil } -// storeOrderWriter 将订单应用写入模型适配为数据库事务操作。 -type storeOrderWriter struct { +// orderWriter 将订单应用写入模型适配为数据库事务操作。 +type orderWriter struct { // store 保存数据库 repository 聚合入口。 store *db.Store // tx 保存当前事务,仅在基础设施适配器内部可见。 @@ -187,7 +187,7 @@ type storeOrderWriter struct { } // PatchOrder 委托事务内订单更新。 -func (w storeOrderWriter) PatchOrder(ctx context.Context, orderID string, patch orderapp.OrderPatch) error { +func (w orderWriter) PatchOrder(ctx context.Context, orderID string, patch orderapp.OrderPatch) error { return w.store.Orders.PatchTx(ctx, w.tx, orderID, db.OrderPatch{ OrderStatus: patch.OrderStatus, ItemID: patch.ItemID, BuyerID: patch.BuyerID, SpecName: patch.SpecName, SpecValue: patch.SpecValue, Quantity: patch.Quantity, @@ -198,7 +198,7 @@ func (w storeOrderWriter) PatchOrder(ctx context.Context, orderID string, patch } // UpsertItemBasic 委托事务内商品基础信息写入。 -func (w storeOrderWriter) UpsertItemBasic(ctx context.Context, item orderapp.ItemWrite) error { +func (w orderWriter) UpsertItemBasic(ctx context.Context, item orderapp.ItemWrite) error { return w.store.Items.UpsertBasicTx(ctx, w.tx, &db.ItemInfoRow{ CookieID: item.CookieID, ItemID: item.ItemID, ItemTitle: item.ItemTitle, ItemPrice: item.ItemPrice, ItemDetail: item.ItemDetail, @@ -206,7 +206,7 @@ func (w storeOrderWriter) UpsertItemBasic(ctx context.Context, item orderapp.Ite } // UpsertOrder 委托事务内订单写入。 -func (w storeOrderWriter) UpsertOrder(ctx context.Context, orderID string, options orderapp.UpsertOptions) error { +func (w orderWriter) UpsertOrder(ctx context.Context, orderID string, options orderapp.UpsertOptions) error { return w.store.Orders.UpsertTx(ctx, w.tx, orderID, db.OrderUpsertOpts{ ItemID: options.ItemID, BuyerID: options.BuyerID, CookieID: options.CookieID, OrderStatus: options.OrderStatus, SpecName: options.SpecName, SpecValue: options.SpecValue, @@ -218,7 +218,7 @@ func (w storeOrderWriter) UpsertOrder(ctx context.Context, orderID string, optio } // UpsertOrder 委托订单写入。 -func (r storeOrderRepository) UpsertOrder(ctx context.Context, orderID string, opts orderapp.UpsertOptions) error { +func (r OrderRepository) UpsertOrder(ctx context.Context, orderID string, opts orderapp.UpsertOptions) error { return r.store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{ ItemID: opts.ItemID, BuyerID: opts.BuyerID, CookieID: opts.CookieID, OrderStatus: opts.OrderStatus, SpecName: opts.SpecName, SpecValue: opts.SpecValue, @@ -230,7 +230,7 @@ func (r storeOrderRepository) UpsertOrder(ctx context.Context, orderID string, o } // BatchUpsertOrders 委托订单详情分片的单条多值 UPSERT。 -func (r storeOrderRepository) BatchUpsertOrders(ctx context.Context, rows []orderapp.RefreshOrderWrite) error { +func (r OrderRepository) BatchUpsertOrders(ctx context.Context, rows []orderapp.RefreshOrderWrite) error { if len(rows) == 0 { return nil } @@ -265,12 +265,12 @@ func (r storeOrderRepository) BatchUpsertOrders(ctx context.Context, rows []orde } // LockCredentials 委托账号凭证锁。 -func (r storeOrderRepository) LockCredentials(cookieID string) func() { +func (r OrderRepository) LockCredentials(cookieID string) func() { return r.store.LockAccountCredentials(cookieID) } // LoadCookiePlatformDetail 委托平台凭证详情查询。 -func (r storeOrderRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*orderapp.PlatformRuntimeData, error) { +func (r OrderRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*orderapp.PlatformRuntimeData, error) { // data 和 err 保存平台运行视图查询结果。 data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) if err != nil { @@ -280,17 +280,17 @@ func (r storeOrderRepository) LoadCookiePlatformDetail(ctx context.Context, cook } // UpdateRenewalCookie 委托续期 Cookie 更新。 -func (r storeOrderRepository) UpdateRenewalCookie(ctx context.Context, cookieID, value, metadata string, at int64) error { +func (r OrderRepository) UpdateRenewalCookie(ctx context.Context, cookieID, value, metadata string, at int64) error { return r.store.Cookies.UpdateRenewalCookie(ctx, cookieID, value, metadata, at) } // SoftDeleteMissingOrders 委托账号远端缺失订单清理。 -func (r storeOrderRepository) SoftDeleteMissingOrders(ctx context.Context, cookieID string, activeIDs map[string]struct{}) (int, error) { +func (r OrderRepository) SoftDeleteMissingOrders(ctx context.Context, cookieID string, activeIDs map[string]struct{}) (int, error) { return r.store.Orders.SoftDeleteMissingForCookie(ctx, cookieID, activeIDs) } // ListOrdersByCookieCursor 委托订单复合游标查询并转换应用层模型。 -func (r storeOrderRepository) ListOrdersByCookieCursor(ctx context.Context, cookieID string, limit int, afterCreatedAt, afterOrderID string) ([]orderapp.OrderRow, error) { +func (r OrderRepository) ListOrdersByCookieCursor(ctx context.Context, cookieID string, limit int, afterCreatedAt, afterOrderID string) ([]orderapp.OrderRow, error) { // rows、err 保存数据库游标查询结果及错误。 rows, err := r.store.Orders.ByCookieCursor(ctx, cookieID, limit, afterCreatedAt, afterOrderID) if err != nil { @@ -300,7 +300,7 @@ func (r storeOrderRepository) ListOrdersByCookieCursor(ctx context.Context, cook } // Create 创建订单刷新后台任务并同步应用层模型默认值。 -func (r storeOrderRepository) Create(ctx context.Context, job *orderapp.RefreshJob) error { +func (r OrderRepository) Create(ctx context.Context, job *orderapp.RefreshJob) error { // dbJob 保存待写入的数据库任务模型。 dbJob := &db.OrderRefreshJob{ ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus, @@ -316,7 +316,7 @@ func (r storeOrderRepository) Create(ctx context.Context, job *orderapp.RefreshJ } // Get 按用户读取订单刷新后台任务并转换为应用层模型。 -func (r storeOrderRepository) Get(ctx context.Context, userID int64, id string) (*orderapp.RefreshJob, error) { +func (r OrderRepository) Get(ctx context.Context, userID int64, id string) (*orderapp.RefreshJob, error) { // job、err 保存数据库任务读取结果及错误。 job, err := r.store.OrderRefreshJobs.Get(ctx, userID, id) if errors.Is(err, db.ErrNotFound) { @@ -329,22 +329,22 @@ func (r storeOrderRepository) Get(ctx context.Context, userID int64, id string) } // Claim 原子抢占订单刷新后台任务。 -func (r storeOrderRepository) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) { +func (r OrderRepository) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) { return r.store.OrderRefreshJobs.Claim(ctx, id, token, leaseExpiresAt) } // Cancel 按用户归属委托订单刷新任务取消。 -func (r storeOrderRepository) Cancel(ctx context.Context, userID int64, id string) (bool, error) { +func (r OrderRepository) Cancel(ctx context.Context, userID int64, id string) (bool, error) { return r.store.OrderRefreshJobs.Cancel(ctx, userID, id) } // Complete 以租约令牌安全写入订单刷新后台任务终态。 -func (r storeOrderRepository) Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) { +func (r OrderRepository) Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) { return r.store.OrderRefreshJobs.Complete(ctx, id, token, status, resultJSON, errorMessage) } // Recoverable 查询租约过期的订单刷新后台任务。 -func (r storeOrderRepository) Recoverable(ctx context.Context, now int64, limit int) ([]orderapp.RefreshJob, error) { +func (r OrderRepository) Recoverable(ctx context.Context, now int64, limit int) ([]orderapp.RefreshJob, error) { // jobs、err 保存数据库层可恢复任务及查询错误。 jobs, err := r.store.OrderRefreshJobs.Recoverable(ctx, now, limit) if err != nil { @@ -359,7 +359,7 @@ func (r storeOrderRepository) Recoverable(ctx context.Context, now int64, limit } // RequeueExpired 将过期订单刷新后台任务恢复为 queued。 -func (r storeOrderRepository) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) { +func (r OrderRepository) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) { return r.store.OrderRefreshJobs.RequeueExpired(ctx, id, now) } @@ -376,24 +376,24 @@ func refreshJobFromDB(job *db.OrderRefreshJob) *orderapp.RefreshJob { } } -// newStoreOrderRepository 从完整 Store 构造订单应用服务窄 repository。 -func newStoreOrderRepository(store *db.Store) *storeOrderRepository { +// NewOrderRepository 从数据库 Store 构造订单应用服务适配器。 +func NewOrderRepository(store *db.Store) *OrderRepository { if store == nil || store.Cookies == nil || store.Orders == nil || store.Items == nil { return nil } - return &storeOrderRepository{store: store} + return &OrderRepository{store: store} } -// newStoreOrderRefreshJobRepository 构造订单刷新任务持久化适配器。 -func newStoreOrderRefreshJobRepository(store *db.Store) orderapp.RefreshJobRepository { +// NewOrderRefreshJobRepository 构造订单刷新任务持久化适配器。 +func NewOrderRefreshJobRepository(store *db.Store) orderapp.RefreshJobRepository { if store == nil || store.OrderRefreshJobs == nil { return nil } - return storeOrderRepository{store: store} + return OrderRepository{store: store} } // 确保 Store 适配器始终覆盖订单应用服务所需的全部能力。 -var _ orderapp.Repository = storeOrderRepository{} -var _ orderapp.UnitOfWork = storeOrderRepository{} -var _ orderapp.Writer = storeOrderWriter{} -var _ orderapp.RefreshJobRepository = storeOrderRepository{} +var _ orderapp.Repository = OrderRepository{} +var _ orderapp.UnitOfWork = OrderRepository{} +var _ orderapp.Writer = orderWriter{} +var _ orderapp.RefreshJobRepository = OrderRepository{} diff --git a/internal/adapter/order_repository_test.go b/internal/adapter/order_repository_test.go new file mode 100644 index 0000000..e7e53c0 --- /dev/null +++ b/internal/adapter/order_repository_test.go @@ -0,0 +1,48 @@ +package adapter + +import ( + "reflect" + "testing" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" +) + +// TestOrderRepositoryModelConversions 保证数据库订单模型转换为应用模型时不丢失业务字段。 +func TestOrderRepositoryModelConversions(t *testing.T) { + // databaseOrder 保存模拟数据库读取的订单实体。 + databaseOrder := &db.Order{OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", SpecName: "颜色", SpecValue: "蓝", Quantity: "2", Amount: "19.90", OrderStatus: "pending_ship", CookieID: "cookie-1", IsBargain: 1, ReceiverName: "收货人", ReceiverPhone: "13800000000", ReceiverAddr: "上海市", ReceiverCity: "上海", Version: 3, ChatID: "chat-1", SystemShipped: true, PaidAt: "paid", ShippedAt: "shipped", CompletedAt: "completed", BuyerReviewedAt: "reviewed", LastReviewRequestAt: "requested", ReviewRequestCount: 2, CreatedAt: "created", UpdatedAt: "updated"} + // expectedOrder 保存应用层应接收的订单实体。 + expectedOrder := &orderapp.Order{OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", SpecName: "颜色", SpecValue: "蓝", Quantity: "2", Amount: "19.90", OrderStatus: "pending_ship", CookieID: "cookie-1", IsBargain: 1, ReceiverName: "收货人", ReceiverPhone: "13800000000", ReceiverAddress: "上海市", ReceiverCity: "上海", Version: 3, ChatID: "chat-1", SystemShipped: true, PaidAt: "paid", ShippedAt: "shipped", CompletedAt: "completed", BuyerReviewedAt: "reviewed", LastReviewRequestAt: "requested", ReviewRequestCount: 2, CreatedAt: "created", UpdatedAt: "updated"} + // convertedOrder 保存适配器转换后的应用订单。 + convertedOrder := orderFromDB(databaseOrder) + if !reflect.DeepEqual(convertedOrder, expectedOrder) { + t.Fatalf("订单转换结果不完整: got=%+v want=%+v", convertedOrder, expectedOrder) + } + if orderFromDB(nil) != nil { + t.Fatal("空数据库订单应转换为空应用订单") + } + + // databaseItem 保存模拟数据库读取的商品实体。 + databaseItem := &db.ItemInfo{ID: 7, CookieID: "cookie-1", ItemID: "item-1", ItemTitle: "商品", ItemDescription: "描述", ItemCategory: "分类", ItemPrice: "9.95", ItemDetail: `{"images":["a"]}`, IsMultiSpec: true, MultiQuantityDelivery: true} + // expectedItem 保存应用层应接收的商品实体。 + expectedItem := &orderapp.ItemInfo{ID: 7, CookieID: "cookie-1", ItemID: "item-1", ItemTitle: "商品", ItemDescription: "描述", ItemCategory: "分类", ItemPrice: "9.95", ItemDetail: `{"images":["a"]}`, IsMultiSpec: true, MultiQuantityDelivery: true} + // convertedItem 保存适配器转换后的应用商品。 + convertedItem := itemInfoFromDB(databaseItem) + if !reflect.DeepEqual(convertedItem, expectedItem) { + t.Fatalf("商品转换结果不完整: got=%+v want=%+v", convertedItem, expectedItem) + } + if itemInfoFromDB(nil) != nil { + t.Fatal("空数据库商品应转换为空应用商品") + } + + // databaseRuntime 保存模拟数据库读取的平台运行视图。 + databaseRuntime := db.CookiePlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true} + // expectedRuntime 保存应用层应接收的平台运行视图。 + expectedRuntime := &orderapp.PlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true} + // convertedRuntime 保存适配器转换后的平台运行视图。 + convertedRuntime := platformRuntimeDataFromDB(databaseRuntime) + if !reflect.DeepEqual(convertedRuntime, expectedRuntime) { + t.Fatalf("平台运行视图转换结果不完整: got=%+v want=%+v", convertedRuntime, expectedRuntime) + } +} diff --git a/internal/adapter/order_runtime.go b/internal/adapter/order_runtime.go new file mode 100644 index 0000000..5593a2b --- /dev/null +++ b/internal/adapter/order_runtime.go @@ -0,0 +1,388 @@ +package adapter + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" +) + +// orderDetailMTop 是订单运行时需要的可选详情接口能力。 +type orderDetailMTop interface { + // FetchOrderDetail 请求订单详情并返回平台响应中的订单字段。 + FetchOrderDetail(context.Context, string, string) (*mtop.OrderDetailResult, error) +} + +// OrderRuntimeHooks 定义 Server 运行时注入订单适配器的非持久化能力。 +type OrderRuntimeHooks struct { + // Client 返回当前使用的平台客户端。 + Client func() mtop.Client + // ClientAvailable 判断平台客户端是否已由 Server 显式装配。 + ClientAvailable func() bool + // AccountRunning 判断账号运行实例是否在线。 + AccountRunning func(string) bool + // AutomationReady 判断完整发货自动化依赖是否可用。 + AutomationReady func() bool + // ManualFullDelivery 执行完整自动化发货;订单模型转换由装配回调负责。 + ManualFullDelivery func(context.Context, *orderapp.Order) (int, error) + // UpdateRunningCookie 同步平台响应中的最新 Cookie 到账号运行实例。 + UpdateRunningCookie func(context.Context, string, string) + // NotifyDelivery 发送手动发货结果通知。 + NotifyDelivery func(string, string, string, string, string) + // RecoverExpiredSession 处理平台会话过期。 + RecoverExpiredSession func(context.Context, string, error) bool + // ReportPersistenceFailure 记录本地订单状态写入失败。 + ReportPersistenceFailure func(string, error) +} + +// OrderRuntime 将订单应用 Port 适配到数据库凭证、MTOP 和账号运行时。 +type OrderRuntime struct { + // store 提供订单确认发货所需的平台凭证读取和 Cookie 写回能力。 + store *db.Store + // hooks 保存 Server 注入的运行时回调,不保存 HTTP 或 Server 对象。 + hooks OrderRuntimeHooks + // reconciliation 保存外部动作成功后的补偿记录端口。 + reconciliation orderapp.ReconciliationRecorder + // logger 记录不含凭证的订单持久化错误。 + logger *slog.Logger +} + +// NewOrderRuntime 构造订单平台与运行时适配器。 +func NewOrderRuntime(store *db.Store, hooks OrderRuntimeHooks, reconciliation orderapp.ReconciliationRecorder, logger *slog.Logger) *OrderRuntime { + // resolvedLogger 保存订单适配器使用的日志器。 + resolvedLogger := logger + if resolvedLogger == nil { + resolvedLogger = slog.Default() + } + return &OrderRuntime{store: store, hooks: hooks, reconciliation: reconciliation, logger: resolvedLogger} +} + +// AccountRunning 判断指定账号是否在线运行。 +func (r *OrderRuntime) AccountRunning(cookieID string) bool { + return r != nil && r.hooks.AccountRunning != nil && r.hooks.AccountRunning(cookieID) +} + +// AutomationReady 判断完整发货自动化依赖是否已装配。 +func (r *OrderRuntime) AutomationReady() bool { + return r != nil && r.hooks.AutomationReady != nil && r.hooks.AutomationReady() +} + +// ManualFullDelivery 执行完整自动化发货。 +func (r *OrderRuntime) ManualFullDelivery(ctx context.Context, order *orderapp.Order) (int, error) { + if r == nil || r.hooks.ManualFullDelivery == nil { + return 0, errors.New("自动化中心未初始化") + } + return r.hooks.ManualFullDelivery(ctx, order) +} + +// MTopAvailable 判断平台客户端是否已由 Server 显式装配。 +func (r *OrderRuntime) MTopAvailable() bool { + return r != nil && r.hooks.ClientAvailable != nil && r.hooks.ClientAvailable() +} + +// mtopClient 返回订单流程使用的平台客户端。 +func (r *OrderRuntime) mtopClient() mtop.Client { + if r == nil || r.hooks.Client == nil { + return nil + } + return r.hooks.Client() +} + +// ConfirmShipment 使用当前账号凭证调用平台确认发货接口。 +func (r *OrderRuntime) ConfirmShipment(ctx context.Context, cookieID, orderID string, userID int64) orderapp.ConsignResult { + // success、messages、runtimeCookie、runtimeCookieChanged、callErr 保存确认发货结果及凭证变化。 + success, messages, runtimeCookie, runtimeCookieChanged, callErr := r.consignWithCurrentCookie(ctx, cookieID, orderID, userID) + return orderapp.ConsignResult{Success: success, Messages: messages, RuntimeCookie: runtimeCookie, RuntimeCookieChanged: runtimeCookieChanged, Err: callErr} +} + +// consignWithCurrentCookie 使用账号平台凭证确认发货并保存响应 Cookie。 +func (r *OrderRuntime) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) { + if r == nil || r.store == nil || r.store.Cookies == nil { + return false, nil, "", false, errors.New("订单凭证存储未初始化") + } + // unlock 保护当前账号凭证读取和写回,保持现有订单流程的串行语义。 + unlock := r.store.LockAccountCredentials(cookieID) + defer unlock() + // detail、loadErr 保存按账号读取的平台运行凭证及错误。 + detail, loadErr := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) + if loadErr != nil { + return false, nil, "", false, loadErr + } + if detail.UserID != userID { + return false, nil, "", false, orderapp.ErrForbidden + } + if !hasStoredOrderCredential(detail) { + return false, nil, "", false, errors.New("账号 Cookie 为空") + } + // requestCtx、session 保存带 Cookie 快照的平台上下文及响应会话。 + requestCtx, session := withOrderCookieSnapshot(ctx, detail) + // client 保存当前平台调用客户端。 + client := r.mtopClient() + if client == nil { + return false, nil, "", false, errors.New("MTop 客户端未初始化") + } + // success、messages、updatedCookies、callErr 保存平台确认发货响应。 + success, messages, updatedCookies, callErr := client.ConsignContext(requestCtx, detail.Value, orderID) + // value、valueChanged、handled、persistErr 保存响应 Cookie 会话写回结果。 + value, valueChanged, handled, persistErr := r.persistOrderCookieSession(ctx, detail, session, updatedCookies) + if persistErr != nil { + // wrappedPersistErr 保存包含订单语义的 Cookie 写回错误。 + wrappedPersistErr := fmt.Errorf("保存发货响应 Cookie Jar: %w", persistErr) + if callErr != nil { + return success, messages, "", false, errors.Join(callErr, wrappedPersistErr) + } + return success, messages, "", false, wrappedPersistErr + } + if handled { + // runtimeCookie 保存完整 Cookie 会话变化后的平面 Cookie 值。 + runtimeCookie := "" + if valueChanged { + runtimeCookie = value + } + return success, messages, runtimeCookie, valueChanged, callErr + } + if callErr != nil { + return false, messages, "", false, callErr + } + if updatedCookies == "" || updatedCookies == detail.Value { + return success, messages, "", false, nil + } + // err 保存旧式平面 Cookie 写回错误。 + if err := r.store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil { + return success, messages, "", false, fmt.Errorf("保存发货响应 Cookie: %w", err) + } + return success, messages, updatedCookies, true, nil +} + +// UpdateRunningCookie 同步运行时账号 Cookie。 +func (r *OrderRuntime) UpdateRunningCookie(ctx context.Context, cookieID, value string) { + if r != nil && r.hooks.UpdateRunningCookie != nil { + r.hooks.UpdateRunningCookie(ctx, cookieID, value) + } +} + +// NotifyDelivery 发送发货结果通知。 +func (r *OrderRuntime) NotifyDelivery(cookieID, buyerID, itemID, chatID, message string) { + if r != nil && r.hooks.NotifyDelivery != nil { + r.hooks.NotifyDelivery(cookieID, buyerID, itemID, chatID, message) + } +} + +// RecordOrderReconciliation 创建外部动作成功后的补偿记录。 +func (r *OrderRuntime) RecordOrderReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) { + if r == nil || r.reconciliation == nil { + return "", errors.New("订单补偿存储未初始化") + } + return r.reconciliation.RecordReconciliation(ctx, orderID, cookieID, kind, message) +} + +// RecordReconciliation 将补偿记录能力暴露给手动发货应用 Port。 +func (r *OrderRuntime) RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) { + return r.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message) +} + +// ReportPersistenceFailure 记录手动发货本地订单状态持久化失败。 +func (r *OrderRuntime) ReportPersistenceFailure(orderID string, err error) { + if r == nil || err == nil { + return + } + r.logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err) + if r.hooks.ReportPersistenceFailure != nil { + r.hooks.ReportPersistenceFailure(orderID, err) + } +} + +// RecoverExpiredSession 处理订单刷新应用服务报告的平台会话过期。 +func (r *OrderRuntime) RecoverExpiredSession(ctx context.Context, cookieID string, err error) bool { + return r != nil && r.hooks.RecoverExpiredSession != nil && r.hooks.RecoverExpiredSession(ctx, cookieID, err) +} + +// DetailAvailable 判断平台详情接口是否可用。 +func (r *OrderRuntime) DetailAvailable() bool { + // client 保存当前平台客户端。 + client := r.mtopClient() + // _, available 丢弃客户端具体类型并记录详情接口能力。 + _, available := client.(orderDetailMTop) + return available +} + +// SoldAvailable 判断平台已售订单列表接口是否可用。 +func (r *OrderRuntime) SoldAvailable() bool { + // client 保存当前平台客户端。 + client := r.mtopClient() + // _, available 丢弃客户端具体类型并记录订单列表接口能力。 + _, available := client.(mtop.SoldOrderFetcher) + return available +} + +// CredentialAvailable 判断平台请求视图是否包含可用 Cookie。 +func (r *OrderRuntime) CredentialAvailable(detail *orderapp.PlatformRuntimeData) bool { + return detail != nil && strings.TrimSpace(detail.Value) != "" +} + +// FetchOrderDetail 调用平台详情接口并收集 Cookie 会话变化。 +func (r *OrderRuntime) FetchOrderDetail(ctx context.Context, detail *orderapp.PlatformRuntimeData, orderID string) (orderapp.RefreshDetailFetchResult, error) { + // fetcher、available 保存详情接口实现及其可用状态。 + fetcher, available := r.mtopClient().(orderDetailMTop) + if !available { + return orderapp.RefreshDetailFetchResult{}, orderapp.ErrRefreshDetailUnsupported + } + if detail == nil { + return orderapp.RefreshDetailFetchResult{}, errors.New("订单详情请求缺少账号凭证") + } + // requestCtx、session 保存带 Cookie 快照的平台上下文及响应会话。 + requestCtx, session := withOrderCookieSnapshot(ctx, platformRuntimeDataForOrder(detail)) + // result、callErr 保存平台详情响应和错误。 + result, callErr := fetcher.FetchOrderDetail(requestCtx, detail.Value, orderID) + // cookieUpdate 保存平台详情请求观察到的 Cookie 会话变化。 + cookieUpdate := orderCookieUpdate(detail, session) + if callErr != nil { + return orderapp.RefreshDetailFetchResult{CookieUpdate: cookieUpdate}, callErr + } + if result == nil { + return orderapp.RefreshDetailFetchResult{CookieUpdate: cookieUpdate}, errors.New("订单详情接口未返回结果") + } + return orderapp.RefreshDetailFetchResult{Detail: &orderapp.RefreshDetail{Quantity: result.Quantity, SpecName: result.SpecName, SpecValue: result.SpecValue, OrderStatus: result.OrderStatus, Amount: result.Amount, UpdatedCookies: result.UpdatedCookies}, CookieUpdate: cookieUpdate}, nil +} + +// FetchSoldOrders 调用平台已售订单接口并收集 Cookie 会话变化。 +func (r *OrderRuntime) FetchSoldOrders(ctx context.Context, detail *orderapp.PlatformRuntimeData) (orderapp.RefreshSoldFetchResult, error) { + // fetcher、available 保存订单列表接口实现及其可用状态。 + fetcher, available := r.mtopClient().(mtop.SoldOrderFetcher) + if !available { + return orderapp.RefreshSoldFetchResult{}, errors.New("当前 MTop 客户端不支持订单列表发现") + } + if detail == nil { + return orderapp.RefreshSoldFetchResult{}, errors.New("订单列表请求缺少账号凭证") + } + // requestCtx、session 保存带 Cookie 快照的平台上下文及响应会话。 + requestCtx, session := withOrderCookieSnapshot(ctx, platformRuntimeDataForOrder(detail)) + // orders 保存跨分页累积的平台订单。 + orders := make([]orderapp.RefreshSoldOrder, 0) + // pageNumber 是当前请求的订单列表页码。 + for pageNumber := 1; pageNumber <= orderRuntimeMaxSoldOrderPages; pageNumber++ { + // page、callErr 保存当前订单列表页及错误。 + page, callErr := fetcher.FetchSoldOrdersPage(requestCtx, detail.Value, pageNumber, 30) + if callErr != nil { + return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: orderCookieUpdate(detail, session)}, callErr + } + if page == nil { + return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: orderCookieUpdate(detail, session)}, errors.New("订单列表接口未返回结果") + } + // remote 是当前平台订单列表项。 + for _, remote := range page.Items { + orders = append(orders, orderapp.RefreshSoldOrder{OrderID: remote.OrderID, ItemID: remote.ItemID, BuyerID: remote.BuyerID, OrderStatus: orderapp.NormalizeOrderStatus(remote.OrderStatus), Quantity: remote.Quantity, Amount: remote.Amount, ReceiverName: remote.ReceiverName, ReceiverPhone: remote.ReceiverPhone, ReceiverAddr: remote.ReceiverAddr, ReceiverCity: remote.ReceiverCity, IsBargain: remote.IsBargain}) + } + if !page.NextPage || len(page.Items) == 0 { + break + } + } + return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: orderCookieUpdate(detail, session)}, nil +} + +// PersistCookieSession 在凭证锁内保存应用层 Cookie 更新。 +func (r *OrderRuntime) PersistCookieSession(ctx context.Context, detail *orderapp.PlatformRuntimeData, update orderapp.RefreshCookieUpdate) (string, bool, bool, error) { + if detail == nil || !update.Handled { + return "", false, false, nil + } + if !update.Changed { + return detail.Value, false, true, nil + } + if r == nil || r.store == nil || r.store.Cookies == nil { + return update.Value, update.Value != detail.Value, true, errors.New("账号 Cookie 持久化服务未初始化") + } + // persistErr 保存账号续期 Cookie 写入错误。 + persistErr := r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, update.Value, update.MetadataJSON, time.Now().Unix()) + if persistErr != nil { + return update.Value, update.Value != detail.Value, true, persistErr + } + return update.Value, update.Value != detail.Value, true, nil +} + +// IsSessionExpired 判断平台错误是否为会话过期。 +func (r *OrderRuntime) IsSessionExpired(err error) bool { + return mtop.IsSessionExpiredErr(err) +} + +// withOrderCookieSnapshot 为订单平台请求挂载平面 Cookie 或完整 Cookie Jar。 +func withOrderCookieSnapshot(ctx context.Context, detail db.CookiePlatformRuntimeData) (context.Context, *mtop.CookieSession) { + // snapshot、complete 保存账号 metadata 中的 Cookie Jar 及其完整性。 + snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) + if !complete { + return mtop.WithFlatCookieSession(ctx, detail.Value) + } + return mtop.WithCookieSnapshot(ctx, snapshot) +} + +// hasStoredOrderCredential 判断订单平台视图是否包含可用凭证。 +func hasStoredOrderCredential(detail db.CookiePlatformRuntimeData) bool { + if strings.TrimSpace(detail.Value) != "" { + return true + } + // _, complete 丢弃 Cookie 快照内容,仅判断是否存在完整凭证。 + _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) + return complete +} + +// platformRuntimeDataForOrder 将应用平台运行视图转换为数据库适配内部模型。 +func platformRuntimeDataForOrder(data *orderapp.PlatformRuntimeData) db.CookiePlatformRuntimeData { + if data == nil { + return db.CookiePlatformRuntimeData{} + } + return db.CookiePlatformRuntimeData{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser} +} + +// orderCookieUpdate 将 MTOP 会话状态转换为订单应用层 Cookie 更新模型。 +func orderCookieUpdate(detail *orderapp.PlatformRuntimeData, session *mtop.CookieSession) orderapp.RefreshCookieUpdate { + if detail == nil || session == nil { + return orderapp.RefreshCookieUpdate{} + } + // value、snapshot、changed 保存会话当前 Cookie、快照及变化状态。 + value, snapshot, changed := session.State() + if snapshot == nil { + return orderapp.RefreshCookieUpdate{Value: value, Changed: changed, Handled: false} + } + // metadata 保存包含最新 Cookie 快照的账号元数据。 + metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + return orderapp.RefreshCookieUpdate{Value: value, MetadataJSON: metadata, Changed: changed, Handled: true} +} + +// persistOrderCookieSession 保存确认发货响应中的完整或平面 Cookie 会话。 +func (r *OrderRuntime) persistOrderCookieSession(ctx context.Context, detail db.CookiePlatformRuntimeData, session *mtop.CookieSession, updatedCookies string) (string, bool, bool, error) { + // value、snapshot、changed 保存平台 CookieSession 状态。 + value, snapshot, changed := session.State() + if !changed { + if snapshot != nil { + return detail.Value, false, true, nil + } + return "", false, false, nil + } + // metadata 保存移除或更新 Cookie 快照后的账号元数据。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) + } + if r.store == nil || r.store.Cookies == nil { + return value, value != detail.Value, true, errors.New("账号 Cookie 持久化 repository 未初始化") + } + // persistErr 保存完整 Cookie 会话写回错误。 + persistErr := r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()) + if persistErr != nil { + return value, value != detail.Value, true, persistErr + } + return value, value != detail.Value, true, nil +} + +// orderRuntimeMaxSoldOrderPages 限制一次订单发现最多请求的平台页数。 +const orderRuntimeMaxSoldOrderPages = 100 + +// 确保订单运行时覆盖手动发货和订单刷新应用层端口。 +var _ orderapp.ManualShipRuntime = (*OrderRuntime)(nil) +var _ orderapp.RefreshRuntime = (*OrderRuntime)(nil) diff --git a/internal/adapter/order_runtime_test.go b/internal/adapter/order_runtime_test.go new file mode 100644 index 0000000..f4e5ae1 --- /dev/null +++ b/internal/adapter/order_runtime_test.go @@ -0,0 +1,137 @@ +package adapter + +import ( + "context" + "errors" + "testing" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/xianyu/mtop" +) + +// orderRuntimeMTopFake 是订单运行时测试使用的平台客户端替身。 +type orderRuntimeMTopFake struct { + // consign 保存确认发货调用结果函数。 + consign func(context.Context, string, string) (bool, []string, string, error) + // consignCalls 记录确认发货调用次数。 + consignCalls int +} + +// FetchUserProfile 满足基础 MTOP 客户端接口但不参与订单测试。 +func (f *orderRuntimeMTopFake) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) { + return nil, errors.New("订单测试未预期资料请求") +} + +// ConsignContext 返回测试预置的确认发货结果。 +func (f *orderRuntimeMTopFake) ConsignContext(ctx context.Context, cookies, orderID string) (bool, []string, string, error) { + f.consignCalls++ + if f.consign == nil { + return false, nil, "", errors.New("订单测试未配置确认发货结果") + } + return f.consign(ctx, cookies, orderID) +} + +// FetchItemsPage 满足基础 MTOP 客户端接口但不参与订单测试。 +func (f *orderRuntimeMTopFake) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) { + return nil, errors.New("订单测试未预期商品分页请求") +} + +// FetchAllItems 满足基础 MTOP 客户端接口但不参与订单测试。 +func (f *orderRuntimeMTopFake) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) { + return nil, errors.New("订单测试未预期商品列表请求") +} + +// PublishItem 满足基础 MTOP 客户端接口但不参与订单测试。 +func (f *orderRuntimeMTopFake) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) { + return nil, errors.New("订单测试未预期商品发布请求") +} + +// RefreshTokenWithDeviceIDContext 满足基础 MTOP 客户端接口但不参与订单测试。 +func (f *orderRuntimeMTopFake) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) { + return nil, errors.New("订单测试未预期令牌请求") +} + +// TestOrderRuntimeConfirmShipmentPersistsCookie 验证确认发货成功会写回平台返回的新 Cookie。 +func TestOrderRuntimeConfirmShipmentPersistsCookie(t *testing.T) { + // store、cleanup 保存测试数据库和资源清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // client 保存返回成功及新 Cookie 的平台客户端替身。 + client := &orderRuntimeMTopFake{consign: func(context.Context, string, string) (bool, []string, string, error) { + return true, []string{"SUCCESS"}, "sid=new", nil + }} + // runtime 保存绑定数据库和平台客户端的订单运行时适配器。 + runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil) + // result 保存确认发货的应用层结果。 + result := runtime.ConfirmShipment(context.Background(), "cid", "order-1", 1) + if !result.Success || result.Err != nil || result.RuntimeCookie != "sid=new" || !result.RuntimeCookieChanged { + t.Fatalf("确认发货结果异常: %+v", result) + } + // savedCookie 保存凭证适配器写回数据库的 Cookie。 + savedCookie, savedErr := store.Cookies.GetValue(context.Background(), "cid") + if savedErr != nil || savedCookie != "sid=new" { + t.Fatalf("Cookie 写回异常: value=%q err=%v", savedCookie, savedErr) + } +} + +// TestOrderRuntimeConfirmShipmentPropagatesPlatformError 验证平台错误会透传且不会伪造成功。 +func TestOrderRuntimeConfirmShipmentPropagatesPlatformError(t *testing.T) { + // store、cleanup 保存测试数据库和资源清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // expectedErr 保存平台确认发货错误。 + expectedErr := errors.New("平台确认发货失败") + // client 保存返回平台错误的客户端替身。 + client := &orderRuntimeMTopFake{consign: func(context.Context, string, string) (bool, []string, string, error) { + return false, []string{"FAIL"}, "", expectedErr + }} + // runtime 保存订单运行时适配器。 + runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil) + // result 保存平台错误对应的应用层结果。 + result := runtime.ConfirmShipment(context.Background(), "cid", "order-1", 1) + if result.Success || !errors.Is(result.Err, expectedErr) || client.consignCalls != 1 { + t.Fatalf("平台错误未正确透传: result=%+v calls=%d", result, client.consignCalls) + } +} + +// TestOrderRuntimeConfirmShipmentRejectsOtherOwner 验证跨用户确认发货会在平台调用前拒绝。 +func TestOrderRuntimeConfirmShipmentRejectsOtherOwner(t *testing.T) { + // store、cleanup 保存测试数据库和资源清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // client 保存用于确认平台未被调用的客户端替身。 + client := &orderRuntimeMTopFake{consign: func(context.Context, string, string) (bool, []string, string, error) { + return true, nil, "sid=unexpected", nil + }} + // runtime 保存订单运行时适配器。 + runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil) + // result 保存跨用户请求的应用层结果。 + result := runtime.ConfirmShipment(context.Background(), "cid", "order-1", 999) + if !errors.Is(result.Err, orderapp.ErrForbidden) || client.consignCalls != 0 { + t.Fatalf("跨用户请求未被拒绝: result=%+v calls=%d", result, client.consignCalls) + } +} + +// TestOrderRuntimeConfirmShipmentHonorsCancellation 验证请求取消会传入平台调用并返回取消错误。 +func TestOrderRuntimeConfirmShipmentHonorsCancellation(t *testing.T) { + // store、cleanup 保存测试数据库和资源清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // client 保存检查 Context 取消状态的客户端替身。 + client := &orderRuntimeMTopFake{consign: func(ctx context.Context, _, _ string) (bool, []string, string, error) { + return false, nil, "", ctx.Err() + }} + // runtime 保存订单运行时适配器。 + runtime := NewOrderRuntime(store, OrderRuntimeHooks{Client: func() mtop.Client { return client }, ClientAvailable: func() bool { return true }}, nil, nil) + // ctx 保存已经取消的订单请求上下文。 + ctx, cancel := context.WithCancel(context.Background()) + cancel() + // result 保存取消请求对应的应用层结果。 + result := runtime.ConfirmShipment(ctx, "cid", "order-1", 1) + if !errors.Is(result.Err, context.Canceled) { + t.Fatalf("取消错误未透传: %+v", result) + } +} + +// 确保测试平台替身覆盖订单运行时依赖的基础客户端接口。 +var _ mtop.Client = (*orderRuntimeMTopFake)(nil) diff --git a/internal/adapter/server_dependencies.go b/internal/adapter/server_dependencies.go new file mode 100644 index 0000000..ba02473 --- /dev/null +++ b/internal/adapter/server_dependencies.go @@ -0,0 +1,216 @@ +package adapter + +import ( + "context" + "errors" + "log/slog" + + "xianyu-go/internal/account" + accountapp "xianyu-go/internal/application/account" + adminapp "xianyu-go/internal/application/admin" + chatapp "xianyu-go/internal/application/chat" + notificationsapp "xianyu-go/internal/application/notifications" + orderapp "xianyu-go/internal/application/orders" + domainchat "xianyu-go/internal/chat" + "xianyu-go/internal/db" + "xianyu-go/internal/reconciliation" + "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/qrlogin" + xrenew "xianyu-go/internal/xianyu/renew" +) + +// MTOPClient 是 Server 装配平台适配器时使用的客户端别名;HTTP 层不直接导入 MTOP 实现包。 +type MTOPClient = mtop.Client + +// QRLoginService 定义 HTTP 扫码端点所需的最小二维码会话协议。 +type QRLoginService interface { + // GenerateQRCode 创建一次待轮询的二维码会话并返回会话标识和二维码地址。 + GenerateQRCode(context.Context) (string, string, error) + // GetSessionStatus 返回会话当前状态;返回值仅在 HTTP 适配器边界做兼容字段转换。 + GetSessionStatus(string) map[string]any + // CompleteVerification 完成风控验证并返回本次请求作用域内的凭证值。 + CompleteVerification(context.Context, string) (string, string, error) +} + +// Dependencies 封装 Server 装配所需的基础设施;底层 Store 仅在 adapter 内部可见。 +type Dependencies struct { + // store 保存所有数据库适配器共享的持久化入口,绝不向 HTTP 层公开。 + store *db.Store +} + +// NewDependencies 构造 Server 使用的基础设施工厂并校验数据库 Store。 +func NewDependencies(store *db.Store) (*Dependencies, error) { + if store == nil { + return nil, errors.New("server 基础设施 Store 不能为空") + } + return &Dependencies{store: store}, nil +} + +// NewMTOPClient 创建默认平台客户端,供生产构造与测试替换使用。 +func NewMTOPClient() MTOPClient { + return mtop.NewClient() +} + +// NewQRLoginService 创建默认二维码会话服务。 +func NewQRLoginService(logger *slog.Logger) QRLoginService { + return qrlogin.NewManager(logger) +} + +// NewLongLoginClient 创建默认长登录平台客户端。 +func NewLongLoginClient() LongLoginClient { + return xrenew.Service{} +} + +// NewOrderRepository 返回订单读写应用服务共用的数据库适配器。 +func (d *Dependencies) NewOrderRepository() *OrderRepository { return NewOrderRepository(d.store) } + +// NewOrderReconciliationRepository 返回订单补偿记录的持久化适配器。 +func (d *Dependencies) NewOrderReconciliationRepository() *OrderReconciliationRepository { + return NewOrderReconciliationRepository(d.store) +} + +// NewOrderRuntime 返回订单运行时适配器,Server 只提供运行时回调而不访问持久化入口。 +func (d *Dependencies) NewOrderRuntime(hooks OrderRuntimeHooks, reconciliation orderapp.ReconciliationRecorder, logger *slog.Logger) *OrderRuntime { + return NewOrderRuntime(d.store, hooks, reconciliation, logger) +} + +// NewOrderRefreshJobRepository 返回订单刷新任务的持久化适配器。 +func (d *Dependencies) NewOrderRefreshJobRepository() orderapp.RefreshJobRepository { + return NewOrderRefreshJobRepository(d.store) +} + +// NewAccountLoginRepository 返回账号凭证和摘要适配器。 +func (d *Dependencies) NewAccountLoginRepository() *AccountLoginRepository { + return NewAccountLoginRepository(d.store) +} + +// NewAccountSettingsRepository 返回账号设置写入适配器。 +func (d *Dependencies) NewAccountSettingsRepository() *AccountSettingsRepository { + return NewAccountSettingsRepository(d.store) +} + +// NewAccountSummaryRepository 返回账号非敏感摘要适配器。 +func (d *Dependencies) NewAccountSummaryRepository() *AccountSummaryRepository { + return NewAccountSummaryRepository(d.store) +} + +// NewAutomationCredentialWakeRepository 返回凭证恢复后的自动化任务唤醒适配器。 +func (d *Dependencies) NewAutomationCredentialWakeRepository() *AutomationCredentialWakeRepository { + return NewAutomationCredentialWakeRepository(d.store) +} + +// NewItemBatchRepository 返回商品批量发布状态适配器。 +func (d *Dependencies) NewItemBatchRepository() *ItemBatchRepository { + return NewItemBatchRepository(d.store) +} + +// NewItemBatchPreviewPort 返回批量预检所需的归属与本地文件适配器。 +func (d *Dependencies) NewItemBatchPreviewPort() *ItemBatchPreviewPort { + return NewItemBatchPreviewPort(d.store) +} + +// NewItemBatchPublishPort 返回批量逐行远端发布适配器。 +func (d *Dependencies) NewItemBatchPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error), readFile ReadPublishImageFile, download DownloadPublishImageURL) *ItemBatchPublishPort { + return NewItemBatchPublishPort(d.store, client, logger, update, recover, readFile, download) +} + +// NewItemPublishPort 返回单商品发布和类目推荐共用的平台适配器。 +func (d *Dependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemPublishPort { + return NewItemPublishPort(d.store, client, logger, update, recover) +} + +// NewItemPublishRepository 返回单商品发布后的本地持久化适配器。 +func (d *Dependencies) NewItemPublishRepository() *ItemPublishRepository { + return NewItemPublishRepository(d.store) +} + +// NewItemCatalogRepository 返回商品目录读写适配器。 +func (d *Dependencies) NewItemCatalogRepository() *ItemCatalogRepository { + return NewItemCatalogRepository(d.store) +} + +// NewItemSyncRepository 返回商品同步适配器。 +func (d *Dependencies) NewItemSyncRepository(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemSyncRepository { + return NewItemSyncRepository(d.store, client, logger, update, recover) +} + +// NewQRLoginRepository 返回扫码登录持久化适配器。 +func (d *Dependencies) NewQRLoginRepository() accountapp.QRLoginRepository { + return NewQRLoginRepository(d.store) +} + +// NewAutomationRepository 返回自动化规则、异常和发布规则共用适配器。 +func (d *Dependencies) NewAutomationRepository() *AutomationRepository { + return NewAutomationRepository(d.store) +} + +// NewSettingsRepository 返回系统设置适配器。 +func (d *Dependencies) NewSettingsRepository() *SettingsRepository { + return NewSettingsRepository(d.store) +} + +// NewAuthenticationRepository 返回用户认证持久化适配器。 +func (d *Dependencies) NewAuthenticationRepository() *AuthenticationRepository { + return NewAuthenticationRepository(d.store) +} + +// NewAccountLoginAuditRepository 返回登录审计持久化适配器。 +func (d *Dependencies) NewAccountLoginAuditRepository() *AccountLoginAuditRepository { + return NewAccountLoginAuditRepository(d.store) +} + +// NewAccountTaskRepository 返回账号自动化任务适配器。 +func (d *Dependencies) NewAccountTaskRepository() *AccountTaskRepository { + return NewAccountTaskRepository(d.store) +} + +// NewAdminRepository 返回管理员用户与统计适配器。 +func (d *Dependencies) NewAdminRepository() adminapp.Repository { + return NewAdminRepository(d.store) +} + +// NewChatSendingApplication 装配聊天应用服务,聊天持久化 Store 不泄露给 HTTP 层。 +func (d *Dependencies) NewChatSendingApplication(service *domainchat.Service, manager *account.Manager, client func() MTOPClient) *chatapp.Service { + return NewChatSendingApplication(service, d.store, manager, client) +} + +// NewNotificationUncertainRepository 返回通知不确定态查询适配器。 +func (d *Dependencies) NewNotificationUncertainRepository() notificationsapp.Repository { + return NewNotificationUncertainRepository(d.store) +} + +// NewNotificationChannelRepository 返回通知渠道和账号绑定适配器。 +func (d *Dependencies) NewNotificationChannelRepository() notificationsapp.ChannelRepository { + return NewNotificationChannelRepository(d.store) +} + +// NewAnalyticsRepository 返回订单分析只读适配器。 +func (d *Dependencies) NewAnalyticsRepository() *AnalyticsRepository { + return NewAnalyticsRepository(d.store) +} + +// NewCardsRepository 返回卡券库存适配器。 +func (d *Dependencies) NewCardsRepository() *CardsRepository { return NewCardsRepository(d.store) } + +// NewDefaultReplyRepository 返回默认回复适配器。 +func (d *Dependencies) NewDefaultReplyRepository() *DefaultReplyRepository { + return NewDefaultReplyRepository(d.store) +} + +// NewKeywordRepository 返回关键词和指定商品回复适配器。 +func (d *Dependencies) NewKeywordRepository() *KeywordRepository { + return NewKeywordRepository(d.store) +} + +// NewTransactionRepository 返回应用事务执行适配器。 +func (d *Dependencies) NewTransactionRepository() *TransactionRepository { + return NewTransactionRepository(d.store) +} + +// NewDatabaseHealth 返回数据库健康检查适配器。 +func (d *Dependencies) NewDatabaseHealth() *DatabaseHealth { return NewDatabaseHealth(d.store) } + +// NewReconciliationService 返回订单补偿扫描服务;它仅由 Server 生命周期调用。 +func (d *Dependencies) NewReconciliationService(logger *slog.Logger) *reconciliation.Service { + return reconciliation.New(d.store, logger) +} diff --git a/internal/adapter/settings_repository.go b/internal/adapter/settings_repository.go new file mode 100644 index 0000000..f4d0084 --- /dev/null +++ b/internal/adapter/settings_repository.go @@ -0,0 +1,247 @@ +package adapter + +import ( + "context" + "errors" + "strings" + + settingsapp "xianyu-go/internal/application/settings" + "xianyu-go/internal/db" +) + +// SettingsRepository 将系统、用户和账号 AI 设置数据库模型适配为应用层 Port。 +type SettingsRepository struct { + // store 保存数据库聚合入口,仅由适配器访问数据库模型。 + store *db.Store +} + +// NewSettingsRepository 构造设置数据库适配器。 +func NewSettingsRepository(store *db.Store) *SettingsRepository { + // repository 保存设置用例所需的数据库入口。 + repository := &SettingsRepository{store: store} + return repository +} + +// IsSensitiveSettingKey 判断设置键是否属于数据库维护的敏感白名单。 +func (r *SettingsRepository) IsSensitiveSettingKey(key string) bool { + if r == nil { + return false + } + return db.IsSensitiveSettingKey(key) +} + +// SensitiveSettingKeys 返回敏感设置键名,不返回任何敏感值。 +func (r *SettingsRepository) SensitiveSettingKeys() []string { + if r == nil { + return nil + } + return db.SensitiveSettingKeys() +} + +// PublicSystem 读取公开系统设置。 +func (r *SettingsRepository) PublicSystem(ctx context.Context) (map[string]string, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return nil, err + } + return r.store.Settings.Public(ctx) +} + +// RedactedSystem 读取已脱敏系统设置,敏感值只转换为 configured 标记。 +func (r *SettingsRepository) RedactedSystem(ctx context.Context) (map[string]string, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return nil, err + } + return r.store.Settings.Redacted(ctx) +} + +// GetSystem 读取一项系统设置,仅供应用层受控业务使用。 +func (r *SettingsRepository) GetSystem(ctx context.Context, key string) (string, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return "", err + } + return r.store.Settings.Get(ctx, key) +} + +// ReadSensitiveSystem 通过数据库现有 fail-closed 审计入口读取系统秘密。 +func (r *SettingsRepository) ReadSensitiveSystem(ctx context.Context, userID int64, key, action, resource string) (string, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return "", err + } + return r.store.ReadSensitiveSetting(ctx, userID, key, action, resource) +} + +// ApplySystemChanges 将应用层敏感变更命令转换为数据库模型并原子保存。 +func (r *SettingsRepository) ApplySystemChanges(ctx context.Context, values map[string]string, secrets map[string]settingsapp.SecretChange) error { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return err + } + // dbSecrets 保存转换后的数据库敏感设置命令。 + dbSecrets := make(map[string]db.SensitiveSettingChange, len(secrets)) + // key 是敏感设置键名;change 是应用层三态命令。 + for key, change := range secrets { + dbSecrets[key] = db.SensitiveSettingChange{Action: change.Action, Value: change.Value} + } + return r.store.Settings.ApplyChanges(ctx, values, dbSecrets) +} + +// SetSystem 保存一项普通系统设置。 +func (r *SettingsRepository) SetSystem(ctx context.Context, key, value string) error { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return err + } + return r.store.Settings.Set(ctx, key, value) +} + +// AddAudit 将应用层非敏感审计模型转换为数据库记录。 +func (r *SettingsRepository) AddAudit(ctx context.Context, record settingsapp.AuditRecord) error { + // err 表示审计存储未装配。 + if err := r.validateAudit(); err != nil { + return err + } + return r.store.SecurityAudit.Add(ctx, db.SecurityAuditLog{ + UserID: record.UserID, Action: record.Action, Resource: record.Resource, + Keys: record.Keys, Outcome: record.Outcome, + }) +} + +// ListUser 读取指定用户的全部偏好设置。 +func (r *SettingsRepository) ListUser(ctx context.Context, userID int64) (map[string]string, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return nil, err + } + return r.store.UserSettings.AllForUser(ctx, userID) +} + +// GetUser 读取指定用户的一项偏好设置。 +func (r *SettingsRepository) GetUser(ctx context.Context, userID int64, key string) (string, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return "", err + } + return r.store.UserSettings.GetForUser(ctx, userID, key) +} + +// SetUser 保存指定用户的一项偏好设置。 +func (r *SettingsRepository) SetUser(ctx context.Context, userID int64, key, value string) error { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return err + } + return r.store.UserSettings.SetForUser(ctx, userID, key, value) +} + +// CheckOwnership 查询账号所属用户,不读取或解密任何账号凭证。 +func (r *SettingsRepository) CheckOwnership(ctx context.Context, userID int64, cookieID string) (int64, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return 0, err + } + // owned、err 保存非敏感账号归属结果及查询错误。 + owned, err := r.store.Cookies.ExistsOwned(ctx, userID, strings.TrimSpace(cookieID)) + if err != nil { + return 0, err + } + if owned { + return userID, nil + } + // ownerID、err 保存跨用户账号所有者标识及查询错误。 + ownerID, err := r.store.Cookies.GetOwnerID(ctx, strings.TrimSpace(cookieID)) + if err != nil { + if errors.Is(err, db.ErrNotFound) { + return 0, settingsapp.ErrAccountNotFound + } + return 0, err + } + return ownerID, nil +} + +// ListAIReply 查询用户范围内的账号 AI 设置摘要,数据库层不会读取 API 密钥。 +func (r *SettingsRepository) ListAIReply(ctx context.Context, userID int64) ([]settingsapp.AIReplySettings, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return nil, err + } + // records、err 保存数据库 AI 设置摘要及查询错误。 + records, err := r.store.AIReply.ListForUser(ctx, userID) + if err != nil { + return nil, err + } + // result 保存转换后的应用 AI 设置摘要。 + result := make([]settingsapp.AIReplySettings, 0, len(records)) + // record 是当前待转换的数据库 AI 设置摘要。 + for _, record := range records { + result = append(result, aiReplyModel(record)) + } + return result, nil +} + +// GetAIReply 从用户范围摘要中读取单个账号,避免解密或传递账号 API 密钥。 +func (r *SettingsRepository) GetAIReply(ctx context.Context, userID int64, cookieID string) (settingsapp.AIReplySettings, error) { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return settingsapp.AIReplySettings{}, err + } + // records、err 保存数据库 AI 设置摘要及查询错误。 + records, err := r.store.AIReply.ListForUser(ctx, userID) + if err != nil { + return settingsapp.AIReplySettings{}, err + } + // record 是当前待匹配的账号 AI 设置摘要。 + for _, record := range records { + if record.CookieID == cookieID { + return aiReplyModel(record), nil + } + } + return settingsapp.AIReplySettings{}, settingsapp.ErrConfigNotFound +} + +// UpsertAIReply 将账号 AI 设置转换为数据库模型并保存。 +func (r *SettingsRepository) UpsertAIReply(ctx context.Context, cookieID string, settings settingsapp.AIReplySettings) error { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return err + } + return r.store.AIReply.UpsertSettings(ctx, cookieID, db.AIReplySettings{ + CookieID: cookieID, AIEnabled: settings.AIEnabled, + MaxDiscountPercent: settings.MaxDiscountPercent, MaxDiscountAmount: settings.MaxDiscountAmount, + MaxBargainRounds: settings.MaxBargainRounds, CustomPrompts: settings.CustomPrompts, + }) +} + +// validate 检查设置适配器及其数据库子仓储是否完整装配。 +func (r *SettingsRepository) validate() error { + if r == nil || r.store == nil || r.store.Settings == nil || r.store.UserSettings == nil || r.store.AIReply == nil || r.store.Cookies == nil { + return errors.New("设置数据库适配器未初始化") + } + return nil +} + +// validateAudit 检查敏感设置审计所需的独立存储,避免普通设置被无关依赖阻断。 +func (r *SettingsRepository) validateAudit() error { + // err 表示设置数据库适配器未装配。 + if err := r.validate(); err != nil { + return err + } + if r.store.SecurityAudit == nil { + return errors.New("敏感访问审计未初始化") + } + return nil +} + +// aiReplyModel 将不含 API 密钥的数据库摘要转换为应用模型。 +func aiReplyModel(record db.AIReplySettings) settingsapp.AIReplySettings { + return settingsapp.AIReplySettings{ + CookieID: record.CookieID, AIEnabled: record.AIEnabled, + MaxDiscountPercent: record.MaxDiscountPercent, MaxDiscountAmount: record.MaxDiscountAmount, + MaxBargainRounds: record.MaxBargainRounds, CustomPrompts: record.CustomPrompts, + } +} + +var _ settingsapp.Repository = (*SettingsRepository)(nil) diff --git a/internal/adapter/transaction.go b/internal/adapter/transaction.go new file mode 100644 index 0000000..d581f0a --- /dev/null +++ b/internal/adapter/transaction.go @@ -0,0 +1,52 @@ +package adapter + +import ( + "context" + "database/sql" + "errors" + + "xianyu-go/internal/db" +) + +// TransactionRepository 将数据库事务生命周期适配为 Server 的最小执行端口。 +type TransactionRepository struct { + // store 保存数据库聚合入口,仅在事务适配器内部使用。 + store *db.Store +} + +// NewTransactionRepository 创建数据库事务适配器。 +func NewTransactionRepository(store *db.Store) *TransactionRepository { + return &TransactionRepository{store: store} +} + +// WithTransaction 创建、提交或回滚一个数据库事务。 +func (repository *TransactionRepository) WithTransaction(ctx context.Context, work func(*sql.Tx) error) error { + if repository == nil || repository.store == nil || repository.store.DB == nil { + return errors.New("事务 repository 未初始化") + } + if work == nil { + return errors.New("事务工作函数不能为空") + } + // tx 和 beginErr 保存事务创建结果及错误。 + tx, beginErr := repository.store.DB.BeginTx(ctx, nil) + if beginErr != nil { + return beginErr + } + // committed 标识事务是否已经提交,避免提交失败后重复处理回滚。 + committed := false + defer func() { + if !committed { + _ = tx.Rollback() + } + }() + // workErr 保存事务工作函数返回的业务错误。 + if workErr := work(tx); workErr != nil { + return workErr + } + // commitErr 保存事务提交错误。 + if commitErr := tx.Commit(); commitErr != nil { + return commitErr + } + committed = true + return nil +} diff --git a/internal/adapter/transaction_test.go b/internal/adapter/transaction_test.go new file mode 100644 index 0000000..85a8e78 --- /dev/null +++ b/internal/adapter/transaction_test.go @@ -0,0 +1,33 @@ +package adapter + +import ( + "context" + "database/sql" + "testing" + + "xianyu-go/internal/db" +) + +// TestTransactionRepositoryRejectsMissingDependencies 验证事务适配器缺少数据库或工作函数时快速失败。 +func TestTransactionRepositoryRejectsMissingDependencies(t *testing.T) { + // repository 保存缺少数据库的事务适配器。 + repository := NewTransactionRepository(nil) + // err 保存缺少数据库时的错误。 + if err := repository.WithTransaction(context.Background(), func(*sql.Tx) error { return nil }); err == nil { + t.Fatal("缺少数据库时事务不应伪装成功") + } + // err 保存缺少数据库和工作函数时的错误。 + if err := NewTransactionRepository(nil).WithTransaction(context.Background(), nil); err == nil { + t.Fatal("缺少数据库和工作函数时事务不应伪装成功") + } + // database、dialect 和 openErr 保存最小 SQLite 数据库装配结果。 + database, dialect, openErr := db.Open(context.Background(), t.TempDir()+"/transaction.db") + if openErr != nil { + t.Fatalf("打开测试数据库失败: %v", openErr) + } + defer database.Close() + // err 保存有效数据库但缺少工作函数时的错误。 + if err := NewTransactionRepository(db.NewStore(database, dialect)).WithTransaction(context.Background(), nil); err == nil { + t.Fatal("缺少事务工作函数时不应伪装成功") + } +} diff --git a/internal/application/account/authentication_service.go b/internal/application/account/authentication_service.go new file mode 100644 index 0000000..adcf8fa --- /dev/null +++ b/internal/application/account/authentication_service.go @@ -0,0 +1,123 @@ +package account + +import ( + "context" + "errors" +) + +// ErrPasswordMismatch 表示当前密码未通过校验,调用方应返回认证失败而不是基础设施错误。 +var ErrPasswordMismatch = errors.New("密码错误") + +// ErrUsernameTaken 表示新的用户名已经被其他用户占用。 +var ErrUsernameTaken = errors.New("用户名已存在") + +// AuthUser 是认证用例返回的非敏感用户身份,不包含密码哈希或邮箱等持久化字段。 +type AuthUser struct { + // ID 是本地用户的稳定身份标识,用于创建会话和归属校验。 + ID int64 + // Username 是登录用户名和会话展示名称。 + Username string + // IsAdmin 表示用户是否拥有管理员权限。 + IsAdmin bool +} + +// AuthenticationRepository 定义认证用例需要的最小用户与会话端口。 +type AuthenticationRepository interface { + // IsSystemInitialized 判断系统是否已经存在管理员账号。 + IsSystemInitialized(context.Context) (bool, error) + // InitializeAdmin 创建或重置管理员账号,并返回本次是否新建。 + InitializeAdmin(context.Context, string, string) (bool, error) + // UsernameByEmail 按邮箱取得登录用户名,不向应用层返回完整用户记录。 + UsernameByEmail(context.Context, string) (string, error) + // VerifyPassword 校验用户密码并返回非敏感身份;密码错误返回 ErrPasswordMismatch 或 ok=false。 + VerifyPassword(context.Context, string, string) (AuthUser, bool, error) + // UpdatePassword 更新指定用户名的密码并撤销旧会话。 + UpdatePassword(context.Context, string, string) (bool, error) + // UpdateCredentials 原子更新用户名及可选密码,并撤销旧会话。 + UpdateCredentials(context.Context, int64, string, string) error + // CreateSession 为已经通过密码校验的用户创建会话。 + CreateSession(context.Context, AuthUser) (string, error) +} + +// AuthenticationService 编排登录、初始化、密码修改和登录凭据更新,不依赖 HTTP 或数据库模型。 +type AuthenticationService struct { + // repository 提供用户密码与会话的窄持久化能力。 + repository AuthenticationRepository +} + +// NewAuthenticationService 构造认证应用服务并校验必需的持久化端口。 +func NewAuthenticationService(repository AuthenticationRepository) (*AuthenticationService, error) { + if repository == nil { + return nil, errors.New("认证 repository 未初始化") + } + return &AuthenticationService{repository: repository}, nil +} + +// IsSystemInitialized 返回系统是否已完成管理员初始化。 +func (s *AuthenticationService) IsSystemInitialized(ctx context.Context) (bool, error) { + if s == nil || s.repository == nil { + return false, errors.New("认证服务未初始化") + } + return s.repository.IsSystemInitialized(ctx) +} + +// InitializeAdmin 创建或重置管理员账号;初始化并发控制由 HTTP 层保留。 +func (s *AuthenticationService) InitializeAdmin(ctx context.Context, email, password string) (bool, error) { + if s == nil || s.repository == nil { + return false, errors.New("认证服务未初始化") + } + return s.repository.InitializeAdmin(ctx, email, password) +} + +// UsernameByEmail 取得邮箱对应的登录用户名,未找到时原样返回 repository 错误。 +func (s *AuthenticationService) UsernameByEmail(ctx context.Context, email string) (string, error) { + if s == nil || s.repository == nil { + return "", errors.New("认证服务未初始化") + } + return s.repository.UsernameByEmail(ctx, email) +} + +// Login 校验用户名密码并在成功后创建会话;认证失败返回空会话和 nil 错误以兼容旧 HTTP 行为。 +func (s *AuthenticationService) Login(ctx context.Context, username, password string) (string, *AuthUser, error) { + if s == nil || s.repository == nil { + return "", nil, errors.New("认证服务未初始化") + } + // user、matched、verifyErr 保存密码校验得到的身份、匹配结果和基础设施错误。 + user, matched, verifyErr := s.repository.VerifyPassword(ctx, username, password) + if verifyErr != nil { + return "", nil, verifyErr + } + if !matched { + return "", nil, nil + } + // sessionID、sessionErr 保存持久化会话的结果,密码不会进入会话端口。 + sessionID, sessionErr := s.repository.CreateSession(ctx, user) + if sessionErr != nil { + return "", nil, sessionErr + } + return sessionID, &user, nil +} + +// VerifyPassword 校验当前用户密码并返回非敏感身份,供改密和凭据更新复用。 +func (s *AuthenticationService) VerifyPassword(ctx context.Context, username, password string) (AuthUser, bool, error) { + if s == nil || s.repository == nil { + return AuthUser{}, false, errors.New("认证服务未初始化") + } + return s.repository.VerifyPassword(ctx, username, password) +} + +// UpdatePassword 保存新密码并撤销旧会话,返回值保持数据库层“用户是否存在”的兼容语义。 +func (s *AuthenticationService) UpdatePassword(ctx context.Context, username, password string) (bool, error) { + if s == nil || s.repository == nil { + return false, errors.New("认证服务未初始化") + } + return s.repository.UpdatePassword(ctx, username, password) +} + +// UpdateCredentials 原子保存用户名及可选密码,并将用户名冲突转换为应用层稳定错误。 +func (s *AuthenticationService) UpdateCredentials(ctx context.Context, userID int64, username, password string) error { + if s == nil || s.repository == nil { + return errors.New("认证服务未初始化") + } + return s.repository.UpdateCredentials(ctx, userID, username, password) +} diff --git a/internal/application/account/authentication_service_test.go b/internal/application/account/authentication_service_test.go new file mode 100644 index 0000000..19375df --- /dev/null +++ b/internal/application/account/authentication_service_test.go @@ -0,0 +1,182 @@ +package account + +import ( + "context" + "errors" + "testing" +) + +// authenticationRepositoryFake 是认证应用服务测试使用的可控持久化端口替身。 +type authenticationRepositoryFake struct { + // initialized、initializedErr 保存系统初始化查询结果及错误。 + initialized bool + initializedErr error + // initCreated、initErr 保存管理员初始化结果及错误。 + initCreated bool + initErr error + // emailUsername、emailErr 保存邮箱查询结果及错误。 + emailUsername string + emailErr error + // verifyUser、verifyMatched、verifyErr 保存密码校验结果及错误。 + verifyUser AuthUser + verifyMatched bool + verifyErr error + // sessionID、sessionErr 保存会话创建结果及错误。 + sessionID string + sessionErr error + // updatePasswordResult、updatePasswordErr 保存密码更新结果及错误。 + updatePasswordResult bool + updatePasswordErr error + // updateCredentialsErr 保存登录凭据更新错误。 + updateCredentialsErr error +} + +// IsSystemInitialized 返回测试预置的初始化状态。 +func (f *authenticationRepositoryFake) IsSystemInitialized(context.Context) (bool, error) { + return f.initialized, f.initializedErr +} + +// InitializeAdmin 返回测试预置的管理员初始化结果。 +func (f *authenticationRepositoryFake) InitializeAdmin(context.Context, string, string) (bool, error) { + return f.initCreated, f.initErr +} + +// UsernameByEmail 返回测试预置的邮箱映射结果。 +func (f *authenticationRepositoryFake) UsernameByEmail(context.Context, string) (string, error) { + return f.emailUsername, f.emailErr +} + +// VerifyPassword 返回测试预置的密码校验结果。 +func (f *authenticationRepositoryFake) VerifyPassword(context.Context, string, string) (AuthUser, bool, error) { + return f.verifyUser, f.verifyMatched, f.verifyErr +} + +// UpdatePassword 返回测试预置的密码更新结果。 +func (f *authenticationRepositoryFake) UpdatePassword(context.Context, string, string) (bool, error) { + return f.updatePasswordResult, f.updatePasswordErr +} + +// UpdateCredentials 返回测试预置的登录凭据更新错误。 +func (f *authenticationRepositoryFake) UpdateCredentials(context.Context, int64, string, string) error { + return f.updateCredentialsErr +} + +// CreateSession 返回测试预置的会话创建结果。 +func (f *authenticationRepositoryFake) CreateSession(context.Context, AuthUser) (string, error) { + return f.sessionID, f.sessionErr +} + +// TestNewAuthenticationServiceRequiresRepository 验证认证服务拒绝缺少持久化端口。 +func TestNewAuthenticationServiceRequiresRepository(t *testing.T) { + // service、serviceErr 保存缺少 repository 时的构造结果。 + service, serviceErr := NewAuthenticationService(nil) + if service != nil || serviceErr == nil { + t.Fatalf("缺少 repository 应构造失败 service=%v err=%v", service, serviceErr) + } +} + +// TestAuthenticationServiceLoginBranches 覆盖登录成功、认证失败、校验错误和会话写入错误。 +func TestAuthenticationServiceLoginBranches(t *testing.T) { + // sessionErr 是模拟会话写入失败的固定错误。 + sessionErr := errors.New("session unavailable") + // verifyErr 是模拟密码校验基础设施失败的固定错误。 + verifyErr := errors.New("verify unavailable") + // testCases 保存登录分支及其预期结果。 + testCases := []struct { + // name 是当前分支的可读名称。 + name string + // repository 是当前分支使用的认证端口替身。 + repository *authenticationRepositoryFake + // wantSession 表示预期返回的会话 ID。 + wantSession string + // wantUser 表示预期返回的非敏感用户身份是否存在。 + wantUser bool + // wantErr 表示预期返回的错误。 + wantErr error + }{ + {name: "success", repository: &authenticationRepositoryFake{ + verifyUser: AuthUser{ID: 7, Username: "admin", IsAdmin: true}, verifyMatched: true, sessionID: "sid-1", + }, wantSession: "sid-1", wantUser: true}, + {name: "mismatch", repository: &authenticationRepositoryFake{}, wantErr: nil}, + {name: "verify error", repository: &authenticationRepositoryFake{verifyErr: verifyErr}, wantErr: verifyErr}, + {name: "session error", repository: &authenticationRepositoryFake{ + verifyUser: AuthUser{ID: 7, Username: "admin"}, verifyMatched: true, sessionErr: sessionErr, + }, wantErr: sessionErr}, + } + // testCase 表示当前遍历到的登录分支测试参数。 + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + // service、serviceErr 保存当前分支的认证服务构造结果。 + service, serviceErr := NewAuthenticationService(testCase.repository) + if serviceErr != nil { + t.Fatalf("构造认证服务失败: %v", serviceErr) + } + // sessionID、user、loginErr 保存当前分支的登录结果。 + sessionID, user, loginErr := service.Login(context.Background(), "admin", "password") + if !errors.Is(loginErr, testCase.wantErr) || sessionID != testCase.wantSession || (user != nil) != testCase.wantUser { + t.Fatalf("登录结果 session=%q user=%+v err=%v", sessionID, user, loginErr) + } + }) + } +} + +// TestAuthenticationServiceDelegatesAccountOperations 验证初始化、邮箱查询和改密操作保持端口结果。 +func TestAuthenticationServiceDelegatesAccountOperations(t *testing.T) { + // repository 是预置全部成功结果的认证端口替身。 + repository := &authenticationRepositoryFake{ + initialized: true, initCreated: true, emailUsername: "admin", verifyUser: AuthUser{ID: 7}, verifyMatched: true, + updatePasswordResult: true, + } + // service、serviceErr 保存认证应用服务构造结果。 + service, serviceErr := NewAuthenticationService(repository) + if serviceErr != nil { + t.Fatalf("构造认证服务失败: %v", serviceErr) + } + // initialized、initializedErr 保存初始化状态查询结果。 + initialized, initializedErr := service.IsSystemInitialized(context.Background()) + if initializedErr != nil || !initialized { + t.Fatalf("初始化状态异常 initialized=%v err=%v", initialized, initializedErr) + } + // created、createErr 保存管理员初始化结果。 + created, createErr := service.InitializeAdmin(context.Background(), "admin@example.com", "password") + if createErr != nil || !created { + t.Fatalf("管理员初始化异常 created=%v err=%v", created, createErr) + } + // username、usernameErr 保存邮箱映射结果。 + username, usernameErr := service.UsernameByEmail(context.Background(), "admin@example.com") + if usernameErr != nil || username != "admin" { + t.Fatalf("邮箱登录名异常 username=%q err=%v", username, usernameErr) + } + // user、matched、verifyErr 保存当前密码校验结果。 + user, matched, verifyErr := service.VerifyPassword(context.Background(), "admin", "password") + if verifyErr != nil || !matched || user.ID != 7 { + t.Fatalf("密码校验异常 user=%+v matched=%v err=%v", user, matched, verifyErr) + } + // updated、updateErr 保存密码更新结果。 + updated, updateErr := service.UpdatePassword(context.Background(), "admin", "new-password") + if updateErr != nil || !updated { + t.Fatalf("密码更新异常 updated=%v err=%v", updated, updateErr) + } + // credentialsErr 保存登录凭据更新结果。 + if credentialsErr := service.UpdateCredentials(context.Background(), 7, "operator", "new-password"); credentialsErr != nil { + t.Fatalf("登录凭据更新异常: %v", credentialsErr) + } +} + +// TestAuthenticationServicePreservesCredentialErrors 验证认证服务不吞掉底层更新错误。 +func TestAuthenticationServicePreservesCredentialErrors(t *testing.T) { + // updateErr 是模拟凭据更新失败的固定错误。 + updateErr := errors.New("credential update unavailable") + // repository 是返回凭据更新错误的认证端口替身。 + repository := &authenticationRepositoryFake{updateCredentialsErr: updateErr} + // service、serviceErr 保存认证应用服务构造结果。 + service, serviceErr := NewAuthenticationService(repository) + if serviceErr != nil { + t.Fatalf("构造认证服务失败: %v", serviceErr) + } + // credentialsErr 保存应用服务透传的凭据更新错误。 + credentialsErr := service.UpdateCredentials(context.Background(), 7, "operator", "password") + if !errors.Is(credentialsErr, updateErr) { + t.Fatalf("凭据更新错误未透传 got=%v want=%v", credentialsErr, updateErr) + } +} diff --git a/internal/application/account/credential_repository.go b/internal/application/account/credential_repository.go new file mode 100644 index 0000000..abbb5d3 --- /dev/null +++ b/internal/application/account/credential_repository.go @@ -0,0 +1,45 @@ +package account + +import ( + "context" + "errors" +) + +// ErrCredentialNotFound 表示平台凭证查询目标账号不存在;调用方无需依赖数据库错误类型。 +var ErrCredentialNotFound = errors.New("平台凭证账号不存在") + +// CredentialDetail 是账号凭证流程需要的最小平台视图;不包含登录用户名、密码或其他秘密。 +type CredentialDetail struct { + // ID 是账号稳定标识,用于凭证更新和运行时关联。 + ID string + // UserID 是账号所属本地用户标识,用于所有权复核。 + UserID int64 + // Value 是仅在平台调用边界短暂存在的 Cookie 明文,禁止进入日志、HTTP DTO 或长期应用状态。 + Value string + // MetadataJSON 是由数据库适配器管理的加密 Cookie 元数据,不应由 Server 解析或序列化。 + MetadataJSON string + // ShowBrowser 表示平台登录流程是否允许显示浏览器。 + ShowBrowser bool + // LastRefreshAt 是客户端乐观冲突检查使用的最近刷新时间,单位为 Unix 秒。 + LastRefreshAt int64 +} + +// CredentialRepository 定义账号 Cookie 登录与平台运行态更新所需的最小持久化端口。 +type CredentialRepository interface { + // LockCredentials 串行化同一账号的凭证写入和平台资料会话。 + LockCredentials(string) func() + // CreateCookieOwned 原子校验账号归属并创建 Cookie;明文只在适配器内部进入加密存储。 + CreateCookieOwned(context.Context, string, string, int64) error + // LoadPlatformDetail 读取平台调用所需的窄视图,不读取登录密码。 + LoadPlatformDetail(context.Context, string) (*CredentialDetail, error) + // UpdateFlatCookieOwned 更新扁平 Cookie 并清除旧的完整快照。 + UpdateFlatCookieOwned(context.Context, *CredentialDetail, string) error + // UpdateRenewalCookie 保存平台返回的 Cookie 与 metadata;明文只在凭证适配器内短暂存在。 + UpdateRenewalCookie(context.Context, string, string, string, int64) error + // ClearTokens 清理凭证变化后失效的旧连接 Token。 + ClearTokens(context.Context, string) error + // GetStatus 查询账号是否启用;数据库故障按停用处理。 + GetStatus(context.Context, string) bool + // UpdateProfile 保存不含凭证的账号展示资料。 + UpdateProfile(context.Context, string, string, string) error +} diff --git a/internal/application/account/delete_service.go b/internal/application/account/delete_service.go index 6a953fa..ff32398 100644 --- a/internal/application/account/delete_service.go +++ b/internal/application/account/delete_service.go @@ -9,8 +9,8 @@ import ( // ErrDeleteConflict 表示账号运行时尚未收束,删除操作不会覆盖仍存活的实例。 var ErrDeleteConflict = errors.New("账号正在停止,请稍后重试") -// DeleteRepository 定义账号删除用例所需的最小非敏感持久化端口。 -type DeleteRepository interface { +// DeleteSummaryRepository 定义账号删除用例所需的最小非敏感持久化端口。 +type DeleteSummaryRepository interface { // GetOwnedSummary 按用户和账号联合查询非敏感摘要,用于删除前归属确认。 GetOwnedSummary(context.Context, int64, string) (Summary, error) // DeleteOwned 在基础设施边界再次确认归属后删除账号及其关联数据。 @@ -30,13 +30,13 @@ type DeleteRuntime interface { // DeleteService 编排账号归属校验、运行时 fencing 和关联数据删除。 type DeleteService struct { // repository 提供非敏感账号查询和按归属删除能力。 - repository DeleteRepository + repository DeleteSummaryRepository // runtime 提供可选的账号运行时停止能力;为空时仅执行持久化删除。 runtime DeleteRuntime } // NewDeleteService 构造账号删除应用服务并校验必需的持久化端口。 -func NewDeleteService(repository DeleteRepository, runtime DeleteRuntime) (*DeleteService, error) { +func NewDeleteService(repository DeleteSummaryRepository, runtime DeleteRuntime) (*DeleteService, error) { if repository == nil { return nil, errors.New("账号删除 repository 未初始化") } diff --git a/internal/application/account/login_audit.go b/internal/application/account/login_audit.go new file mode 100644 index 0000000..9689163 --- /dev/null +++ b/internal/application/account/login_audit.go @@ -0,0 +1,162 @@ +package account + +import ( + "context" + "errors" + "strings" + "time" +) + +const ( + // LoginMethodManual 表示用户直接录入或更新 Cookie 的登录方式。 + LoginMethodManual = "manual" + // LoginMethodPassword 表示账号密码登录方式。 + LoginMethodPassword = "password" + // LoginMethodQRScan 表示扫码登录方式。 + LoginMethodQRScan = "qr_scan" + // LoginStatusSuccess 表示登录审计成功状态。 + LoginStatusSuccess = "success" +) + +var ( + // ErrLoginAuditUnavailable 表示登录审计服务缺少必需的持久化端口。 + ErrLoginAuditUnavailable = errors.New("账号登录审计服务未初始化") +) + +// LoginAuditLog 是登录审计写入模型,不携带 Cookie、Token 或登录密码。 +type LoginAuditLog struct { + // AccountID 是产生登录事件的账号稳定标识。 + AccountID string + // UserID 是触发登录操作的本地用户标识。 + UserID int64 + // Method 是归一化后的登录方式。 + Method string + // Status 是登录尝试的结果状态。 + Status string + // Message 是面向运维审计的非敏感结果摘要。 + Message string + // TriggerReason 是由登录方式推导出的触发原因。 + TriggerReason string + // FailureReason 是可选的稳定失败分类。 + FailureReason string + // OccurredAt 是 Unix 秒时间戳,用于保持数据库审计记录的时间顺序。 + OccurredAt int64 +} + +// SuccessfulLoginInput 是登录凭证写入成功后的审计输入,不包含任何凭证内容。 +type SuccessfulLoginInput struct { + // AccountID 是刚完成登录的账号稳定标识。 + AccountID string + // UserID 是当前登录操作所属的本地用户标识。 + UserID int64 + // Method 是调用方提供的登录方式或兼容别名。 + Method string + // Message 是写入审计日志的非敏感成功摘要。 + Message string + // OccurredAt 是可选的 Unix 秒时间戳;零值由服务使用当前时间填充。 + OccurredAt int64 +} + +// LoginAuditRepository 定义登录成功审计所需的最小持久化端口。 +type LoginAuditRepository interface { + // MarkLogin 保存账号最近一次成功登录方式和时间。 + MarkLogin(context.Context, string, string, int64) error + // SetStatusWithReason 在登录成功后启用账号并保存状态原因。 + SetStatusWithReason(context.Context, string, bool, string) error + // AddLoginLog 写入不含敏感凭证的登录审计记录。 + AddLoginLog(context.Context, LoginAuditLog) error +} + +// LoginAuditService 编排登录成功后的方式记录、账号启用和审计日志写入。 +type LoginAuditService struct { + // repository 提供登录审计所需的三项窄持久化能力。 + repository LoginAuditRepository +} + +// NewLoginAuditService 构造登录审计应用服务。 +func NewLoginAuditService(repository LoginAuditRepository) *LoginAuditService { + return &LoginAuditService{repository: repository} +} + +// RecordSuccessfulLogin 记录成功登录并按登录方式启用账号;后续写入失败不会泄露凭证。 +func (s *LoginAuditService) RecordSuccessfulLogin(ctx context.Context, input SuccessfulLoginInput) error { + if s == nil || s.repository == nil { + return ErrLoginAuditUnavailable + } + if strings.TrimSpace(input.AccountID) == "" || strings.TrimSpace(input.Method) == "" { + return nil + } + // method 是审计和账号状态更新共用的稳定登录方式。 + method := NormalizeLoginMethod(input.Method) + // occurredAt 是本次成功登录的审计时间;调用方可注入固定时间以保证重放一致。 + occurredAt := input.OccurredAt + if occurredAt == 0 { + occurredAt = time.Now().Unix() + } + // markErr 表示最近登录方式持久化失败;失败时不应继续伪造成功状态或日志。 + if markErr := s.repository.MarkLogin(ctx, input.AccountID, method, occurredAt); markErr != nil { + return markErr + } + // writeErrors 收集独立写入阶段的错误,同时保证状态写入失败时仍尝试保存审计日志。 + var writeErrors []error + if method == LoginMethodPassword || method == LoginMethodQRScan { + // statusErr 表示登录成功后启用账号失败,但不阻止继续留下审计日志。 + if statusErr := s.repository.SetStatusWithReason(ctx, input.AccountID, true, ""); statusErr != nil { + writeErrors = append(writeErrors, statusErr) + } + } + // log 是由应用层字段组成的审计记录,数据库模型转换留在适配器内。 + log := LoginAuditLog{ + AccountID: input.AccountID, + UserID: input.UserID, + Method: method, + Status: LoginStatusSuccess, + Message: truncateLoginMessage(input.Message, 500), + TriggerReason: loginTriggerReason(method), + OccurredAt: occurredAt, + } + // logErr 表示成功登录审计日志写入失败,需要与账号状态错误一起返回。 + if logErr := s.repository.AddLoginLog(ctx, log); logErr != nil { + writeErrors = append(writeErrors, logErr) + } + return errors.Join(writeErrors...) +} + +// NormalizeLoginMethod 将兼容的登录方式别名归一化为稳定审计值。 +func NormalizeLoginMethod(method string) string { + switch strings.ToLower(strings.TrimSpace(method)) { + case "", "manual", "cookie", "manual_cookie": + return LoginMethodManual + case "password", "password_login": + return LoginMethodPassword + case "qr", "qr_login", "qr_scan": + return LoginMethodQRScan + default: + return strings.ToLower(strings.TrimSpace(method)) + } +} + +// loginTriggerReason 将稳定登录方式转换为审计展示原因。 +func loginTriggerReason(method string) string { + switch NormalizeLoginMethod(method) { + case LoginMethodManual: + return "手动Cookie录入" + case LoginMethodPassword: + return "账号密码登录" + case LoginMethodQRScan: + return "扫码登录" + default: + return "" + } +} + +// truncateLoginMessage 限制审计摘要长度,避免外部错误文本膨胀持久化记录。 +func truncateLoginMessage(message string, limit int) string { + if limit <= 0 { + return "" + } + if len(message) <= limit { + return message + } + return message[:limit] +} diff --git a/internal/application/account/login_audit_test.go b/internal/application/account/login_audit_test.go new file mode 100644 index 0000000..d0b32c4 --- /dev/null +++ b/internal/application/account/login_audit_test.go @@ -0,0 +1,121 @@ +package account + +import ( + "context" + "errors" + "testing" +) + +// fakeLoginAuditRepository 记录登录审计应用服务调用并注入各阶段错误。 +type fakeLoginAuditRepository struct { + // markErr、statusErr、logErr 分别模拟登录方式、账号状态和审计日志写入失败。 + markErr error + statusErr error + logErr error + // markCalls、statusCalls、logs 保存各持久化阶段的调用结果。 + markCalls int + statusCalls int + logs []LoginAuditLog +} + +// MarkLogin 记录最近一次成功登录方式写入请求。 +func (r *fakeLoginAuditRepository) MarkLogin(_ context.Context, _ string, _ string, _ int64) error { + r.markCalls++ + return r.markErr +} + +// SetStatusWithReason 记录登录成功后的账号启用请求。 +func (r *fakeLoginAuditRepository) SetStatusWithReason(_ context.Context, _ string, _ bool, _ string) error { + r.statusCalls++ + return r.statusErr +} + +// AddLoginLog 保存应用层登录审计模型,供测试核对敏感字段未被引入。 +func (r *fakeLoginAuditRepository) AddLoginLog(_ context.Context, log LoginAuditLog) error { + r.logs = append(r.logs, log) + return r.logErr +} + +// TestLoginAuditServiceRequiresRepository 验证缺少持久化端口时服务返回明确错误。 +func TestLoginAuditServiceRequiresRepository(t *testing.T) { + // service 是没有仓储端口的零值审计服务。 + service := NewLoginAuditService(nil) + // recordErr 保存缺少依赖时的执行错误。 + recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", Method: LoginMethodManual}) + if !errors.Is(recordErr, ErrLoginAuditUnavailable) { + t.Fatalf("缺少审计仓储时错误=%v", recordErr) + } +} + +// TestLoginAuditServiceManualSuccessWritesLog 验证手动登录只记录方式和审计日志,不重复启用账号。 +func TestLoginAuditServiceManualSuccessWritesLog(t *testing.T) { + // repository 是记录持久化调用的审计仓储替身。 + repository := &fakeLoginAuditRepository{} + // service 是使用测试仓储构造的应用服务。 + service := NewLoginAuditService(repository) + // recordErr 保存固定时间的手动登录审计结果。 + recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", UserID: 7, Method: "cookie", Message: "登录成功", OccurredAt: 42}) + if recordErr != nil { + t.Fatalf("记录手动登录失败: %v", recordErr) + } + if repository.markCalls != 1 || repository.statusCalls != 0 || len(repository.logs) != 1 { + t.Fatalf("持久化阶段调用异常: %+v", repository) + } + if repository.logs[0].Method != LoginMethodManual || repository.logs[0].TriggerReason != "手动Cookie录入" || repository.logs[0].OccurredAt != 42 { + t.Fatalf("登录审计模型异常: %+v", repository.logs[0]) + } +} + +// TestLoginAuditServicePasswordEnablesAccount 验证密码和扫码登录成功后会启用账号并记录日志。 +func TestLoginAuditServicePasswordEnablesAccount(t *testing.T) { + // repository 是记录账号状态与日志写入的审计仓储替身。 + repository := &fakeLoginAuditRepository{} + // service 是使用测试仓储构造的应用服务。 + service := NewLoginAuditService(repository) + // recordErr 保存密码登录成功的审计结果。 + recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", UserID: 7, Method: "password_login"}) + if recordErr != nil { + t.Fatalf("记录密码登录失败: %v", recordErr) + } + if repository.statusCalls != 1 || len(repository.logs) != 1 || repository.logs[0].Method != LoginMethodPassword { + t.Fatalf("密码登录启用与日志调用异常: %+v", repository) + } +} + +// TestLoginAuditServiceJoinsIndependentWriteFailures 验证状态与日志独立失败时保留两类错误。 +func TestLoginAuditServiceJoinsIndependentWriteFailures(t *testing.T) { + // statusErr、logErr 是两个相互独立的持久化故障。 + statusErr := errors.New("启用账号失败") + // logErr 表示登录审计日志独立写入失败。 + logErr := errors.New("写入审计失败") + // repository 注入两个独立故障,确认服务仍尝试写日志。 + repository := &fakeLoginAuditRepository{statusErr: statusErr, logErr: logErr} + // service 是使用故障仓储构造的应用服务。 + service := NewLoginAuditService(repository) + // recordErr 保存合并后的审计错误。 + recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", Method: LoginMethodQRScan}) + if !errors.Is(recordErr, statusErr) || !errors.Is(recordErr, logErr) { + t.Fatalf("应保留状态和日志双重错误: %v", recordErr) + } + if len(repository.logs) != 1 { + t.Fatal("状态写入失败后仍应尝试记录审计日志") + } +} + +// TestLoginAuditServiceStopsAfterMarkFailure 验证最近登录方式写入失败时不会伪造后续成功记录。 +func TestLoginAuditServiceStopsAfterMarkFailure(t *testing.T) { + // markErr 是最近登录方式写入失败。 + markErr := errors.New("记录登录方式失败") + // repository 注入方式写入故障。 + repository := &fakeLoginAuditRepository{markErr: markErr} + // service 是使用故障仓储构造的应用服务。 + service := NewLoginAuditService(repository) + // recordErr 保存方式写入失败结果。 + recordErr := service.RecordSuccessfulLogin(context.Background(), SuccessfulLoginInput{AccountID: "acc1", Method: LoginMethodManual}) + if !errors.Is(recordErr, markErr) { + t.Fatalf("应返回方式写入错误: %v", recordErr) + } + if repository.statusCalls != 0 || len(repository.logs) != 0 { + t.Fatal("方式写入失败时不应继续伪造成功状态或日志") + } +} diff --git a/internal/application/account/login_service.go b/internal/application/account/login_service.go index d36649d..58baf18 100644 --- a/internal/application/account/login_service.go +++ b/internal/application/account/login_service.go @@ -80,7 +80,7 @@ func (s *LoginService) CreateCookie(ctx context.Context, input CreateCookieInput return writeErr } // method 是归一化后的登录方式,供审计和运行时适配器保持统一语义。 - method := normalizeLoginMethod(input.LoginMethod) + method := NormalizeLoginMethod(input.LoginMethod) s.lifecycle.AfterSuccessfulLogin(ctx, input.UserID, input.AccountID, method) return nil } @@ -104,22 +104,8 @@ func (s *LoginService) UpdateCookie(ctx context.Context, input UpdateCookieInput // method 是归一化后的登录方式;更新凭证未声明登录方式时必须保持普通替换,不写入登录审计。 method := "" if strings.TrimSpace(input.LoginMethod) != "" { - method = normalizeLoginMethod(input.LoginMethod) + method = NormalizeLoginMethod(input.LoginMethod) } s.lifecycle.AfterSuccessfulLogin(ctx, input.UserID, input.AccountID, method) return nil } - -// normalizeLoginMethod 将兼容的登录方式别名归一化为审计使用的稳定值。 -func normalizeLoginMethod(method string) string { - switch strings.ToLower(strings.TrimSpace(method)) { - case "", "manual", "cookie", "manual_cookie": - return "manual" - case "password", "password_login": - return "password" - case "qr", "qr_login", "qr_scan": - return "qr_scan" - default: - return strings.ToLower(strings.TrimSpace(method)) - } -} diff --git a/internal/application/account/long_login_service.go b/internal/application/account/long_login_service.go new file mode 100644 index 0000000..e3a68dd --- /dev/null +++ b/internal/application/account/long_login_service.go @@ -0,0 +1,68 @@ +package account + +import ( + "context" + "errors" +) + +// ErrLongLoginPlatform 表示长登录平台请求失败;响应 Cookie 仍可能已经被适配器持久化。 +var ErrLongLoginPlatform = errors.New("长登录平台请求失败") + +// LongLoginResult 是长登录设置接口的非敏感结果,不携带平台 Cookie 或响应头。 +type LongLoginResult struct { + // CanOpenLongLogin 表示平台是否允许当前账号使用长登录。 + CanOpenLongLogin bool + // Enabled 表示平台当前是否已开启长登录。 + Enabled bool +} + +// LongLoginPort 定义长登录平台请求及凭证持久化所需的最小端口。 +type LongLoginPort interface { + // QueryLongLogin 查询指定账号的长登录状态,并在适配器内处理响应 Cookie。 + QueryLongLogin(context.Context, string) (LongLoginResult, error) + // SetLongLogin 更新指定账号的长登录开关,并在适配器内处理响应 Cookie。 + SetLongLogin(context.Context, string, bool) (LongLoginResult, error) +} + +// LongLoginService 编排长登录设置的账号归属校验和平台操作。 +type LongLoginService struct { + // repository 提供不解密凭证的账号归属查询能力。 + repository ProfileSummaryRepository + // port 承担平台请求、Cookie 快照合并和凭证持久化。 + port LongLoginPort +} + +// NewLongLoginService 构造长登录应用服务并校验必需端口。 +func NewLongLoginService(repository ProfileSummaryRepository, port LongLoginPort) (*LongLoginService, error) { + if repository == nil { + return nil, errors.New("长登录账号摘要 repository 未初始化") + } + if port == nil { + return nil, errors.New("长登录平台端口未初始化") + } + return &LongLoginService{repository: repository, port: port}, nil +} + +// Query 查询当前用户拥有账号的长登录状态。 +func (s *LongLoginService) Query(ctx context.Context, userID int64, accountID string) (LongLoginResult, error) { + if s == nil || s.repository == nil || s.port == nil { + return LongLoginResult{}, errors.New("长登录服务未初始化") + } + // summary 保存归属校验使用的非敏感账号摘要。 + if _, err := s.repository.GetOwnedSummary(ctx, userID, accountID); err != nil { + return LongLoginResult{}, err + } + return s.port.QueryLongLogin(ctx, accountID) +} + +// Set 更新当前用户拥有账号的长登录开关。 +func (s *LongLoginService) Set(ctx context.Context, userID int64, accountID string, enabled bool) (LongLoginResult, error) { + if s == nil || s.repository == nil || s.port == nil { + return LongLoginResult{}, errors.New("长登录服务未初始化") + } + // summary 保存归属校验使用的非敏感账号摘要。 + if _, err := s.repository.GetOwnedSummary(ctx, userID, accountID); err != nil { + return LongLoginResult{}, err + } + return s.port.SetLongLogin(ctx, accountID, enabled) +} diff --git a/internal/application/account/long_login_service_test.go b/internal/application/account/long_login_service_test.go new file mode 100644 index 0000000..df88427 --- /dev/null +++ b/internal/application/account/long_login_service_test.go @@ -0,0 +1,72 @@ +package account + +import ( + "context" + "errors" + "testing" +) + +// longLoginSummaryRepositoryFake 是长登录用例测试使用的非敏感摘要仓储替身。 +type longLoginSummaryRepositoryFake struct { + // summary 保存归属校验成功时返回的账号摘要。 + summary Summary + // err 保存摘要查询失败时返回的错误。 + err error +} + +// GetOwnedSummary 返回预设的账号摘要或归属错误。 +func (f longLoginSummaryRepositoryFake) GetOwnedSummary(context.Context, int64, string) (Summary, error) { + return f.summary, f.err +} + +// longLoginPortFake 是长登录用例测试使用的平台端口替身。 +type longLoginPortFake struct { + // result 保存平台请求成功时返回的非敏感状态。 + result LongLoginResult + // calls 记录平台调用次数,用于确认归属失败不会访问平台。 + calls int +} + +// QueryLongLogin 返回预设的长登录查询结果。 +func (f *longLoginPortFake) QueryLongLogin(context.Context, string) (LongLoginResult, error) { + f.calls++ + return f.result, nil +} + +// SetLongLogin 返回预设的长登录设置结果。 +func (f *longLoginPortFake) SetLongLogin(context.Context, string, bool) (LongLoginResult, error) { + f.calls++ + return f.result, nil +} + +// TestLongLoginServiceChecksOwnershipAndMapsResult 验证长登录用例先校验归属,再返回脱敏状态。 +func TestLongLoginServiceChecksOwnershipAndMapsResult(t *testing.T) { + // port 保存平台端口替身及调用计数。 + port := &longLoginPortFake{result: LongLoginResult{CanOpenLongLogin: true, Enabled: true}} + // service、serviceErr 保存长登录应用服务及其装配错误。 + service, serviceErr := NewLongLoginService(longLoginSummaryRepositoryFake{summary: Summary{ID: "account-1"}}, port) + if serviceErr != nil { + t.Fatal(serviceErr) + } + // result、callErr 保存长登录查询结果和平台调用错误。 + result, callErr := service.Query(context.Background(), 1, "account-1") + if callErr != nil || result != (LongLoginResult{CanOpenLongLogin: true, Enabled: true}) || port.calls != 1 { + t.Fatalf("result=%+v err=%v calls=%d", result, callErr, port.calls) + } +} + +// TestLongLoginServiceStopsOnOwnershipError 验证账号归属失败时不会调用平台端口。 +func TestLongLoginServiceStopsOnOwnershipError(t *testing.T) { + // port 保存平台端口替身及调用计数。 + port := &longLoginPortFake{} + // service、serviceErr 保存长登录应用服务及其装配错误。 + service, serviceErr := NewLongLoginService(longLoginSummaryRepositoryFake{err: ErrForbidden}, port) + if serviceErr != nil { + t.Fatal(serviceErr) + } + // callErr 保存归属校验返回的应用错误。 + _, callErr := service.Set(context.Background(), 1, "account-1", true) + if !errors.Is(callErr, ErrForbidden) || port.calls != 0 { + t.Fatalf("err=%v calls=%d", callErr, port.calls) + } +} diff --git a/internal/application/account/profile_service.go b/internal/application/account/profile_service.go index 1e937b7..b0a6e4c 100644 --- a/internal/application/account/profile_service.go +++ b/internal/application/account/profile_service.go @@ -24,6 +24,24 @@ type Summary struct { Nickname string // AvatarURL 是本地缓存的平台头像地址,用于资料刷新失败时的展示兜底。 AvatarURL string + // AutoConfirm 表示账号是否启用自动确认收货。 + AutoConfirm bool + // PauseDuration 是账号暂停时长,单位为分钟。 + PauseDuration int + // PausedUntil 是暂停结束时间的 Unix 秒;零值表示当前未暂停。 + PausedUntil int64 + // Username 是账号关联的登录用户名,不包含登录密码。 + Username string + // ShowBrowser 表示密码登录流程是否允许显示浏览器。 + ShowBrowser bool + // LastRefreshAt 是最近一次资料刷新时间,单位为 Unix 秒。 + LastRefreshAt int64 + // LoginMethod 是最近一次成功登录方式,不包含凭证内容。 + LoginMethod string + // LastLoginAt 是最近一次成功登录时间,单位为 Unix 秒。 + LastLoginAt int64 + // CreatedAt 是账号记录创建时间的数据库字符串。 + CreatedAt string } // ProfileInput 是平台资料刷新端口的输入,携带已通过归属校验的账号摘要。 @@ -48,8 +66,8 @@ type ProfileResult struct { ErrorMessage string } -// SummaryRepository 定义资料刷新用例读取账号归属和摘要所需的最小端口。 -type SummaryRepository interface { +// ProfileSummaryRepository 定义资料刷新用例读取账号归属和摘要所需的最小端口。 +type ProfileSummaryRepository interface { // GetOwnedSummary 按用户和账号联合查询非敏感摘要;不存在或越权时返回错误。 GetOwnedSummary(context.Context, int64, string) (Summary, error) } @@ -63,13 +81,13 @@ type ProfilePort interface { // ProfileService 编排账号归属校验、平台资料刷新和可展示结果转换。 type ProfileService struct { // repository 提供不解密凭证的账号摘要查询能力。 - repository SummaryRepository + repository ProfileSummaryRepository // profilePort 承担平台调用、凭证会话更新和资料持久化适配。 profilePort ProfilePort } // NewProfileService 构造资料刷新应用服务并校验必需端口。 -func NewProfileService(repository SummaryRepository, profilePort ProfilePort) (*ProfileService, error) { +func NewProfileService(repository ProfileSummaryRepository, profilePort ProfilePort) (*ProfileService, error) { if repository == nil { return nil, errors.New("账号资料摘要 repository 未初始化") } diff --git a/internal/application/account/profile_service_test.go b/internal/application/account/profile_service_test.go index c8aacfa..181c3c4 100644 --- a/internal/application/account/profile_service_test.go +++ b/internal/application/account/profile_service_test.go @@ -46,7 +46,7 @@ func TestNewProfileServiceRequiresPorts(t *testing.T) { // name 是当前构造失败场景名称。 name string // repository 是当前场景使用的摘要端口。 - repository SummaryRepository + repository ProfileSummaryRepository // profilePort 是当前场景使用的平台端口。 profilePort ProfilePort }{ diff --git a/internal/application/account/qr_login_service.go b/internal/application/account/qr_login_service.go index 84a6cc7..c71edda 100644 --- a/internal/application/account/qr_login_service.go +++ b/internal/application/account/qr_login_service.go @@ -12,6 +12,9 @@ var ErrQRLoginIncomplete = errors.New("扫码结果缺少账号标识或 cookies // ErrQRLoginAccountMismatch 表示扫码得到的平台账号与待重新授权账号不一致。 var ErrQRLoginAccountMismatch = errors.New("扫码账号与待重新授权账号不一致") +// ErrAlreadyExists 表示扫码创建账号时目标标识已被并发请求占用。 +var ErrAlreadyExists = errors.New("账号已存在") + // CookieSnapshot 是浏览器返回的单个 Cookie 快照;明文值只在当前凭证适配端口调用期间存在。 type CookieSnapshot struct { // Name 是浏览器 Cookie 名称。 diff --git a/internal/application/account/settings_service.go b/internal/application/account/settings_service.go new file mode 100644 index 0000000..fce1f59 --- /dev/null +++ b/internal/application/account/settings_service.go @@ -0,0 +1,228 @@ +package account + +import ( + "context" + "errors" +) + +// SettingsUpdateInput 是账号编辑用例的输入;Password 为 nil 时保留数据库中的既有密码。 +type SettingsUpdateInput struct { + // UserID 是当前认证用户的本地身份标识,用于数据库边界的归属复核。 + UserID int64 + // AccountID 是待更新的闲鱼账号稳定标识。 + AccountID string + // Cookie 是可选的新 Cookie 明文,只在数据库适配器调用期间短暂存在。 + Cookie *string + // Remark 是可选的账号备注更新值。 + Remark *string + // AutoConfirm 是可选的自动确认发货开关。 + AutoConfirm *bool + // PauseDuration 是可选的暂停时长,单位为分钟;零表示立即恢复。 + PauseDuration *int + // Username 是可选的密码登录用户名更新值。 + Username *string + // Password 是可选的密码登录秘密;空字符串用于明确清除密码。 + Password *string + // ShowBrowser 是可选的密码登录浏览器显示开关。 + ShowBrowser *bool + // ChannelIDs 是可选的通知渠道绑定集合;空切片表示解绑全部渠道。 + ChannelIDs *[]int64 +} + +// LoginInfoUpdateInput 是账号登录信息用例的输入,不暴露既有密码读取能力。 +type LoginInfoUpdateInput struct { + // UserID 是当前认证用户的本地身份标识。 + UserID int64 + // AccountID 是待更新账号的稳定标识。 + AccountID string + // Username 是登录用户名;该接口保持旧 HTTP API 的空字符串覆盖语义。 + Username string + // Password 是可选的新密码;nil 表示保留既有密码,空字符串表示清除密码。 + Password *string + // ShowBrowser 表示登录时是否允许显示浏览器。 + ShowBrowser bool +} + +// PauseState 是账号暂停查询的非敏感结果。 +type PauseState struct { + // Duration 是账号配置的暂停时长,单位为分钟。 + Duration int + // PausedUntil 是暂停截止时间的 Unix 秒;零表示当前没有截止时间。 + PausedUntil int64 + // Paused 表示当前时间是否仍处于暂停窗口内。 + Paused bool +} + +// SettingsResult 是账号设置写入后的业务结果。 +type SettingsResult struct { + // PausedUntil 是写入后暂停截止时间的 Unix 秒。 + PausedUntil int64 + // RuntimeError 是持久化成功后运行时重启失败的诊断信息;不会回滚数据库写入。 + RuntimeError error + // TokenCleanupError 是 Cookie 写入成功后清理旧连接凭证的错误;不会回滚账号设置。 + TokenCleanupError error +} + +// StatusResult 是账号启停写入后的业务结果。 +type StatusResult struct { + // RuntimeError 是状态写入成功后运行时启停失败的诊断信息。 + RuntimeError error +} + +// SettingsRepository 定义账号设置用例需要的最小持久化端口。 +type SettingsRepository interface { + // LockCredentials 串行化同一账号的敏感设置写入;调用方必须及时释放返回的函数。 + LockCredentials(string) func() + // UpdateSettings 原子更新账号设置并按 UserID 复核账号归属。 + UpdateSettings(context.Context, SettingsUpdateInput) (int64, error) + // UpdateLoginInfo 原子更新用户名、密码和浏览器显示设置并按 UserID 复核归属。 + UpdateLoginInfo(context.Context, LoginInfoUpdateInput) error + // SetStatusOwned 更新账号启用状态并按 UserID 复核归属。 + SetStatusOwned(context.Context, int64, string, bool, string) error + // StatusOwned 查询指定用户账号的启用状态,不读取凭证明文。 + StatusOwned(context.Context, int64, string) (bool, error) + // SetPauseOwned 更新账号暂停时长并按 UserID 复核归属。 + SetPauseOwned(context.Context, int64, string, int) (int64, error) + // GetPauseOwned 查询指定用户账号的暂停状态,不读取凭证明文。 + GetPauseOwned(context.Context, int64, string) (PauseState, error) + // ClearTokens 清理 Cookie 变更后失效的旧连接凭证。 + ClearTokens(context.Context, string) error +} + +// SettingsRuntime 定义账号设置变更后运行实例的最小控制端口。 +type SettingsRuntime interface { + // Restart 在账号启用且 Cookie 变化后重新加载运行实例。 + Restart(context.Context, string) error + // Stop 在账号停用后停止运行实例。 + Stop(string) +} + +// SettingsService 编排账号设置、登录信息、状态和暂停用例,不依赖 HTTP 或数据库模型。 +type SettingsService struct { + // repository 提供账号设置的窄持久化能力。 + repository SettingsRepository + // runtime 提供可选的账号运行实例控制能力。 + runtime SettingsRuntime +} + +// NewSettingsService 构造账号设置应用服务并校验必需的持久化端口。 +func NewSettingsService(repository SettingsRepository, runtime SettingsRuntime) (*SettingsService, error) { + if repository == nil { + return nil, errors.New("账号设置 repository 未初始化") + } + return &SettingsService{repository: repository, runtime: runtime}, nil +} + +// UpdateSettings 原子保存账号设置;Cookie 变化后的运行时重启在释放凭证锁后执行。 +func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpdateInput) (SettingsResult, error) { + if s == nil || s.repository == nil { + return SettingsResult{}, errors.New("账号设置服务未初始化") + } + if input.AccountID == "" { + return SettingsResult{}, errors.New("缺少账号 ID") + } + // unlock 负责释放本次账号设置写入的凭证锁。 + unlock := s.repository.LockCredentials(input.AccountID) + // pausedUntil、updateErr 保存设置事务返回的暂停截止时间和错误。 + pausedUntil, updateErr := s.repository.UpdateSettings(ctx, input) + unlock() + if updateErr != nil { + return SettingsResult{}, updateErr + } + // result 保存设置写入及后续运行时处理结果。 + result := SettingsResult{PausedUntil: pausedUntil} + if input.Cookie != nil { + // tokenErr 记录 Cookie 替换后清理旧连接凭证的错误;主设置写入已成功,不能回滚。 + tokenErr := s.repository.ClearTokens(ctx, input.AccountID) + result.TokenCleanupError = tokenErr + } + if input.Cookie != nil && s.runtime != nil { + // enabled 表示写入成功后账号的最新启用状态;状态读取失败不覆盖已成功的设置写入。 + enabled, statusErr := s.repository.StatusOwned(ctx, input.UserID, input.AccountID) + if statusErr == nil && enabled { + result.RuntimeError = s.runtime.Restart(ctx, input.AccountID) + } + } + return result, nil +} + +// UpdateLoginInfo 保存账号用户名、密码和浏览器显示设置;既有密码不会被应用层读取。 +func (s *SettingsService) UpdateLoginInfo(ctx context.Context, input LoginInfoUpdateInput) error { + if s == nil || s.repository == nil { + return errors.New("账号设置服务未初始化") + } + if input.AccountID == "" { + return errors.New("缺少账号 ID") + } + // unlock 负责释放登录信息写入期间持有的凭证锁。 + unlock := s.repository.LockCredentials(input.AccountID) + defer unlock() + return s.repository.UpdateLoginInfo(ctx, input) +} + +// SetStatus 更新账号启用状态并在持久化成功后控制运行实例。 +func (s *SettingsService) SetStatus(ctx context.Context, userID int64, accountID string, enabled bool) (StatusResult, error) { + if s == nil || s.repository == nil { + return StatusResult{}, errors.New("账号设置服务未初始化") + } + if accountID == "" { + return StatusResult{}, errors.New("缺少账号 ID") + } + // reason 由应用层统一产生,避免 HTTP 层决定持久化状态原因。 + reason := "" + if !enabled { + reason = "manual" + } + // unlock 负责释放账号状态写入期间持有的凭证锁。 + unlock := s.repository.LockCredentials(accountID) + // statusErr 保存账号状态持久化错误。 + statusErr := s.repository.SetStatusOwned(ctx, userID, accountID, enabled, reason) + unlock() + if statusErr != nil { + return StatusResult{}, statusErr + } + // result 保存状态写入后运行时启停的结果。 + result := StatusResult{} + if s.runtime != nil { + if enabled { + result.RuntimeError = s.runtime.Restart(ctx, accountID) + } else { + s.runtime.Stop(accountID) + } + } + return result, nil +} + +// SetAutoConfirm 更新账号自动确认发货开关。 +func (s *SettingsService) SetAutoConfirm(ctx context.Context, userID int64, accountID string, enabled bool) (SettingsResult, error) { + return s.UpdateSettings(ctx, SettingsUpdateInput{UserID: userID, AccountID: accountID, AutoConfirm: &enabled}) +} + +// SetRemark 更新账号备注。 +func (s *SettingsService) SetRemark(ctx context.Context, userID int64, accountID, remark string) (SettingsResult, error) { + return s.UpdateSettings(ctx, SettingsUpdateInput{UserID: userID, AccountID: accountID, Remark: &remark}) +} + +// SetPause 更新账号暂停时长;零值会立即唤醒待执行任务。 +func (s *SettingsService) SetPause(ctx context.Context, userID int64, accountID string, duration int) (SettingsResult, error) { + if s == nil || s.repository == nil { + return SettingsResult{}, errors.New("账号设置服务未初始化") + } + if accountID == "" { + return SettingsResult{}, errors.New("缺少账号 ID") + } + // pausedUntil、pauseErr 保存暂停写入返回的截止时间和错误。 + pausedUntil, pauseErr := s.repository.SetPauseOwned(ctx, userID, accountID, duration) + return SettingsResult{PausedUntil: pausedUntil}, pauseErr +} + +// GetPause 查询账号暂停配置及当前暂停状态。 +func (s *SettingsService) GetPause(ctx context.Context, userID int64, accountID string) (PauseState, error) { + if s == nil || s.repository == nil { + return PauseState{}, errors.New("账号设置服务未初始化") + } + if accountID == "" { + return PauseState{}, errors.New("缺少账号 ID") + } + return s.repository.GetPauseOwned(ctx, userID, accountID) +} diff --git a/internal/application/account/settings_service_test.go b/internal/application/account/settings_service_test.go new file mode 100644 index 0000000..2584597 --- /dev/null +++ b/internal/application/account/settings_service_test.go @@ -0,0 +1,176 @@ +package account + +import ( + "context" + "errors" + "testing" +) + +// fakeSettingsRepository 记录账号设置应用服务对持久化端口的调用。 +type fakeSettingsRepository struct { + // updateResult 是账号设置写入后返回的暂停截止时间。 + updateResult int64 + // updateErr 是账号设置写入错误。 + updateErr error + // status 是账号当前是否启用。 + status bool + // statusErr 是账号状态查询错误。 + statusErr error + // lockCalls 是凭证锁获取次数。 + lockCalls int + // unlockCalls 是凭证锁释放次数。 + unlockCalls int + // statusWrites 是状态写入次数。 + statusWrites int + // clearTokensErr 是清理旧连接凭证时返回的预置错误。 + clearTokensErr error +} + +// LockCredentials 记录凭证锁的获取和释放。 +func (f *fakeSettingsRepository) LockCredentials(string) func() { + f.lockCalls++ + return func() { f.unlockCalls++ } +} + +// UpdateSettings 返回预置的账号设置写入结果。 +func (f *fakeSettingsRepository) UpdateSettings(context.Context, SettingsUpdateInput) (int64, error) { + return f.updateResult, f.updateErr +} + +// UpdateLoginInfo 模拟登录信息保存成功。 +func (f *fakeSettingsRepository) UpdateLoginInfo(context.Context, LoginInfoUpdateInput) error { + return nil +} + +// SetStatusOwned 记录状态写入并返回预置错误。 +func (f *fakeSettingsRepository) SetStatusOwned(context.Context, int64, string, bool, string) error { + f.statusWrites++ + return nil +} + +// StatusOwned 返回预置的账号启用状态。 +func (f *fakeSettingsRepository) StatusOwned(context.Context, int64, string) (bool, error) { + return f.status, f.statusErr +} + +// SetPauseOwned 返回预置的暂停截止时间。 +func (f *fakeSettingsRepository) SetPauseOwned(context.Context, int64, string, int) (int64, error) { + return f.updateResult, nil +} + +// GetPauseOwned 返回未暂停的默认状态。 +func (f *fakeSettingsRepository) GetPauseOwned(context.Context, int64, string) (PauseState, error) { + return PauseState{}, nil +} + +// ClearTokens 模拟 Cookie 更新后清理旧连接凭证。 +func (f *fakeSettingsRepository) ClearTokens(context.Context, string) error { return f.clearTokensErr } + +// fakeSettingsRuntime 记录账号运行实例控制调用。 +type fakeSettingsRuntime struct { + // restartCalls 是运行实例重启次数。 + restartCalls int + // stopCalls 是运行实例停止次数。 + stopCalls int + // restartErr 是预置的重启错误。 + restartErr error +} + +// Restart 记录重启并返回预置错误。 +func (f *fakeSettingsRuntime) Restart(context.Context, string) error { + f.restartCalls++ + return f.restartErr +} + +// Stop 记录运行实例停止。 +func (f *fakeSettingsRuntime) Stop(string) { f.stopCalls++ } + +// TestSettingsServiceRestartsAfterCookieWrite 验证 Cookie 写入释放凭证锁后才重启运行实例。 +func TestSettingsServiceRestartsAfterCookieWrite(t *testing.T) { + // repository 保存当前测试的伪持久化端口。 + repository := &fakeSettingsRepository{updateResult: 123, status: true} + // runtime 保存当前测试的伪运行时端口。 + runtime := &fakeSettingsRuntime{} + // service 保存待验证的账号设置应用服务。 + // service、err 保存账号设置应用服务及其装配错误。 + service, err := NewSettingsService(repository, runtime) + if err != nil { + t.Fatalf("NewSettingsService: %v", err) + } + // cookie 保存本次模拟写入的明文 Cookie,仅存在测试输入作用域。 + cookie := "cookie" + // result、err 保存 Cookie 设置后的运行时结果和用例错误。 + result, err := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "a1", Cookie: &cookie}) + if err != nil || result.PausedUntil != 123 || runtime.restartCalls != 1 { + t.Fatalf("UpdateSettings result=%+v err=%v restart=%d", result, err, runtime.restartCalls) + } + if repository.lockCalls != 1 || repository.unlockCalls != 1 { + t.Fatalf("credential lock calls=%d/%d", repository.lockCalls, repository.unlockCalls) + } +} + +// TestSettingsServiceKeepsPersistenceSuccessOnRuntimeFailure 验证运行时重启失败不会伪装成数据库写入失败。 +func TestSettingsServiceKeepsPersistenceSuccessOnRuntimeFailure(t *testing.T) { + // repository 保存启用账号的伪持久化端口。 + repository := &fakeSettingsRepository{status: true} + // runtime 保存返回重启错误的伪运行时端口。 + runtime := &fakeSettingsRuntime{restartErr: errors.New("restart failed")} + // service 保存待验证的账号设置应用服务。 + // service、err 保存账号设置应用服务及其装配错误。 + service, err := NewSettingsService(repository, runtime) + if err != nil { + t.Fatalf("NewSettingsService: %v", err) + } + // cookie 保存本次模拟写入的明文 Cookie。 + cookie := "cookie" + // result、err 保存重启失败时的三态结果和用例错误。 + result, err := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "a1", Cookie: &cookie}) + if err != nil || result.RuntimeError == nil { + t.Fatalf("UpdateSettings result=%+v err=%v", result, err) + } +} + +// TestSettingsServiceContinuesRuntimeAfterTokenCleanupFailure 验证旧 Token 清理失败不会阻止 Cookie 写入后的运行时重启。 +func TestSettingsServiceContinuesRuntimeAfterTokenCleanupFailure(t *testing.T) { + // repository 保存 Cookie 写入成功但 Token 清理失败的伪持久化端口。 + repository := &fakeSettingsRepository{status: true, clearTokensErr: errors.New("token cleanup failed")} + // runtime 保存运行实例重启调用记录。 + runtime := &fakeSettingsRuntime{} + // service、err 保存账号设置应用服务及其装配错误。 + service, err := NewSettingsService(repository, runtime) + if err != nil { + t.Fatalf("NewSettingsService: %v", err) + } + // cookie 保存本次模拟写入的 Cookie 输入。 + cookie := "cookie" + // result、err 保存 Token 清理失败时的三态结果和用例错误。 + result, err := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "a1", Cookie: &cookie}) + if err != nil || result.TokenCleanupError == nil || runtime.restartCalls != 1 { + t.Fatalf("UpdateSettings result=%+v err=%v restart=%d", result, err, runtime.restartCalls) + } +} + +// TestSettingsServiceStatusControlsRuntime 验证启停状态写入后分别控制运行实例。 +func TestSettingsServiceStatusControlsRuntime(t *testing.T) { + // repository 保存状态写入调用记录。 + repository := &fakeSettingsRepository{} + // runtime 保存运行实例控制调用记录。 + runtime := &fakeSettingsRuntime{} + // service 保存待验证的账号设置应用服务。 + // service、err 保存账号设置应用服务及其装配错误。 + service, err := NewSettingsService(repository, runtime) + if err != nil { + t.Fatalf("NewSettingsService: %v", err) + } + // err 保存启用账号并重启运行实例的用例错误。 + if _, err := service.SetStatus(context.Background(), 7, "a1", true); err != nil || runtime.restartCalls != 1 { + t.Fatalf("enable err=%v restart=%d", err, runtime.restartCalls) + } + // err 保存停用账号并停止运行实例的用例错误。 + if _, err := service.SetStatus(context.Background(), 7, "a1", false); err != nil || runtime.stopCalls != 1 { + t.Fatalf("disable err=%v stop=%d", err, runtime.stopCalls) + } + if repository.statusWrites != 2 { + t.Fatalf("status writes=%d", repository.statusWrites) + } +} diff --git a/internal/application/account/summary_service.go b/internal/application/account/summary_service.go new file mode 100644 index 0000000..312b13f --- /dev/null +++ b/internal/application/account/summary_service.go @@ -0,0 +1,200 @@ +package account + +import ( + "context" + "errors" +) + +// AccountSummary 是账号列表与所有权用例使用的非敏感账号摘要,不包含 Cookie、密码或加密 metadata。 +type AccountSummary struct { + // ID 是闲鱼账号的稳定标识。 + ID string + // UserID 是账号所属的本地用户标识。 + UserID int64 + // AutoConfirm 表示账号是否启用自动确认收货。 + AutoConfirm bool + // Remark 是用户为账号设置的备注。 + Remark string + // PauseDuration 是账号暂停时长,单位为分钟。 + PauseDuration int + // PausedUntil 是暂停结束时间的 Unix 秒;零表示当前没有暂停截止时间。 + PausedUntil int64 + // Username 是账号关联的登录用户名,不包含登录密码。 + Username string + // ShowBrowser 表示密码登录流程是否允许显示浏览器。 + ShowBrowser bool + // Nickname 是平台账号昵称缓存。 + Nickname string + // AvatarURL 是平台账号头像缓存地址。 + AvatarURL string + // LastRefreshAt 是最近一次资料刷新时间的 Unix 秒。 + LastRefreshAt int64 + // LoginMethod 是最近一次成功登录方式。 + LoginMethod string + // LastLoginAt 是最近一次成功登录时间的 Unix 秒。 + LastLoginAt int64 + // CreatedAt 是账号记录创建时间的数据库字符串。 + CreatedAt string +} + +// AdminAccountSummary 是管理员账号列表使用的非敏感摘要。 +type AdminAccountSummary struct { + // ID 是闲鱼账号的稳定标识。 + ID string + // UserID 是账号所属的本地用户标识。 + UserID int64 + // Remark 是用户为账号设置的备注。 + Remark string + // CreatedAt 是账号记录创建时间的数据库字符串。 + CreatedAt string + // Owner 是账号所属用户的展示名。 + Owner string + // Enabled 表示账号当前是否启用。 + Enabled bool +} + +// AccountSummaryRepository 定义账号摘要和所有权用例需要的最小持久化端口。 +type AccountSummaryRepository interface { + // ListOwnedIDs 返回指定用户拥有的账号 ID,不读取凭证字段。 + ListOwnedIDs(context.Context, int64) ([]string, error) + // ListSummaries 返回指定用户的非敏感账号摘要列表。 + ListSummaries(context.Context, int64) ([]AccountSummary, error) + // GetOwnedSummary 返回指定用户拥有的单个非敏感账号摘要。 + GetOwnedSummary(context.Context, int64, string) (AccountSummary, error) + // ExistsOwned 判断账号是否属于指定用户,仅返回存在性结论。 + ExistsOwned(context.Context, int64, string) (bool, error) + // GetOwnerID 返回指定账号所属用户标识,不读取凭证字段。 + GetOwnerID(context.Context, string) (int64, error) + // StatusOwned 返回指定用户账号的启用状态,并在读取前复核归属。 + StatusOwned(context.Context, int64, string) (bool, error) +} + +// AdminSummaryRepository 定义管理员读取全局账号摘要所需的最小持久化端口。 +type AdminSummaryRepository interface { + // ListAdminSummaries 返回所有账号的非敏感管理员摘要。 + ListAdminSummaries(context.Context) ([]AdminAccountSummary, error) +} + +// SummaryService 编排账号摘要读取、所有权判断和管理员账号列表,不依赖 HTTP 或数据库模型。 +type SummaryService struct { + // repository 保存普通用户账号摘要与所有权查询端口。 + repository AccountSummaryRepository + // adminRepository 保存管理员全局账号摘要查询端口。 + adminRepository AdminSummaryRepository +} + +// NewSummaryService 构造账号摘要应用服务并校验普通用户查询端口。 +func NewSummaryService(repository AccountSummaryRepository, adminRepository AdminSummaryRepository) (*SummaryService, error) { + if repository == nil { + return nil, errors.New("账号摘要 repository 未初始化") + } + return &SummaryService{repository: repository, adminRepository: adminRepository}, nil +} + +// ListOwnedIDs 返回指定用户拥有的账号 ID;数据库适配器错误原样向上返回。 +func (s *SummaryService) ListOwnedIDs(ctx context.Context, userID int64) ([]string, error) { + // validationErr 表示当前用户身份或摘要服务状态无效。 + validationErr := s.validateUser(userID) + if validationErr != nil { + return nil, validationErr + } + return s.repository.ListOwnedIDs(ctx, userID) +} + +// ListSummaries 返回指定用户的非敏感账号摘要列表。 +func (s *SummaryService) ListSummaries(ctx context.Context, userID int64) ([]AccountSummary, error) { + // validationErr 表示当前用户身份或摘要服务状态无效。 + validationErr := s.validateUser(userID) + if validationErr != nil { + return nil, validationErr + } + return s.repository.ListSummaries(ctx, userID) +} + +// GetOwnedSummary 返回指定用户拥有的单个账号摘要;不会读取或解密凭证。 +func (s *SummaryService) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (AccountSummary, error) { + // validationErr 表示账号摘要请求的用户或账号标识无效。 + validationErr := s.validateRequest(userID, accountID) + if validationErr != nil { + return AccountSummary{}, validationErr + } + return s.repository.GetOwnedSummary(ctx, userID, accountID) +} + +// ExistsOwned 返回账号是否属于指定用户;查询只返回存在性结论,不读取或解密凭证。 +func (s *SummaryService) ExistsOwned(ctx context.Context, userID int64, accountID string) (bool, error) { + // validationErr 表示账号归属请求的用户或账号标识无效。 + validationErr := s.validateRequest(userID, accountID) + if validationErr != nil { + return false, validationErr + } + return s.repository.ExistsOwned(ctx, userID, accountID) +} + +// StatusOwned 返回指定用户账号的启用状态;归属和数据库错误均向上返回。 +func (s *SummaryService) StatusOwned(ctx context.Context, userID int64, accountID string) (bool, error) { + // validationErr 表示账号状态请求的用户或账号标识无效。 + validationErr := s.validateRequest(userID, accountID) + if validationErr != nil { + return false, validationErr + } + return s.repository.StatusOwned(ctx, userID, accountID) +} + +// RequireOwnership 校验账号是否属于用户,并区分账号不存在、越权和基础设施故障。 +func (s *SummaryService) RequireOwnership(ctx context.Context, userID int64, accountID string) error { + // validationErr 表示账号所有权请求的用户或账号标识无效。 + validationErr := s.validateRequest(userID, accountID) + if validationErr != nil { + return validationErr + } + // owned、queryErr 保存联合所有权查询结果及其基础设施错误。 + owned, queryErr := s.repository.ExistsOwned(ctx, userID, accountID) + if queryErr != nil { + return queryErr + } + if owned { + return nil + } + // ownerID、ownerErr 用于区分账号不存在和账号属于其他用户。 + ownerID, ownerErr := s.repository.GetOwnerID(ctx, accountID) + if ownerErr != nil { + return ownerErr + } + if ownerID != userID { + return ErrForbidden + } + return ErrNotFound +} + +// ListAdminSummaries 返回管理员账号摘要;管理员端口未装配时明确失败。 +func (s *SummaryService) ListAdminSummaries(ctx context.Context) ([]AdminAccountSummary, error) { + if s == nil || s.adminRepository == nil { + return nil, errors.New("管理员账号摘要 repository 未初始化") + } + return s.adminRepository.ListAdminSummaries(ctx) +} + +// validateUser 校验所有权查询必须使用真实用户身份,拒绝管理员隐式用户零值。 +func (s *SummaryService) validateUser(userID int64) error { + if s == nil || s.repository == nil { + return errors.New("账号摘要服务未初始化") + } + if userID <= 0 { + return errors.New("账号用户身份无效") + } + return nil +} + +// validateRequest 校验账号摘要查询的用户身份和账号标识。 +func (s *SummaryService) validateRequest(userID int64, accountID string) error { + // validationErr 表示账号摘要请求的用户身份无效。 + validationErr := s.validateUser(userID) + if validationErr != nil { + return validationErr + } + if accountID == "" { + return errors.New("缺少账号 ID") + } + return nil +} diff --git a/internal/application/account/summary_service_test.go b/internal/application/account/summary_service_test.go new file mode 100644 index 0000000..078789e --- /dev/null +++ b/internal/application/account/summary_service_test.go @@ -0,0 +1,174 @@ +package account + +import ( + "context" + "errors" + "testing" +) + +// summaryRepositoryFake 是账号摘要应用服务测试用的可控持久化端口替身。 +type summaryRepositoryFake struct { + // ids 是待返回的账号 ID 列表。 + ids []string + // summaries 是待返回的普通用户账号摘要。 + summaries []AccountSummary + // adminSummaries 是待返回的管理员账号摘要。 + adminSummaries []AdminAccountSummary + // summary 是待返回的单个账号摘要。 + summary AccountSummary + // ownerID 是待返回的账号所有者。 + ownerID int64 + // owned 是待返回的联合所有权结论。 + owned bool + // listErr、summaryErr、ownedErr、ownerErr、statusErr 模拟各查询阶段错误。 + listErr error + summaryErr error + ownedErr error + ownerErr error + statusErr error + // enabled 是待返回的账号启用状态。 + enabled bool +} + +// ListOwnedIDs 返回测试预置的账号 ID 列表或列表错误。 +func (f *summaryRepositoryFake) ListOwnedIDs(context.Context, int64) ([]string, error) { + return f.ids, f.listErr +} + +// ListSummaries 返回测试预置的账号摘要或列表错误。 +func (f *summaryRepositoryFake) ListSummaries(context.Context, int64) ([]AccountSummary, error) { + return f.summaries, f.listErr +} + +// GetOwnedSummary 返回测试预置的账号摘要或摘要错误。 +func (f *summaryRepositoryFake) GetOwnedSummary(context.Context, int64, string) (AccountSummary, error) { + return f.summary, f.summaryErr +} + +// ExistsOwned 返回测试预置的所有权结论或查询错误。 +func (f *summaryRepositoryFake) ExistsOwned(context.Context, int64, string) (bool, error) { + return f.owned, f.ownedErr +} + +// GetOwnerID 返回测试预置的账号所有者或查询错误。 +func (f *summaryRepositoryFake) GetOwnerID(context.Context, string) (int64, error) { + return f.ownerID, f.ownerErr +} + +// StatusOwned 返回测试预置的启用状态或查询错误。 +func (f *summaryRepositoryFake) StatusOwned(context.Context, int64, string) (bool, error) { + return f.enabled, f.statusErr +} + +// ListAdminSummaries 返回测试预置的管理员账号摘要或查询错误。 +func (f *summaryRepositoryFake) ListAdminSummaries(context.Context) ([]AdminAccountSummary, error) { + return f.adminSummaries, f.listErr +} + +// TestSummaryServiceValidatesInputs 验证账号摘要服务拒绝无效用户和空账号标识。 +func TestSummaryServiceValidatesInputs(t *testing.T) { + // service 是使用可控摘要端口构造的应用服务。 + service, err := NewSummaryService(&summaryRepositoryFake{}, &summaryRepositoryFake{}) + if err != nil { + t.Fatalf("构造摘要服务失败: %v", err) + } + // _, listErr 保存无效用户列表查询的验证错误。 + if _, listErr := service.ListOwnedIDs(context.Background(), 0); listErr == nil { + t.Fatal("无效用户 ID 不应读取账号列表") + } + // _, summaryErr 保存空账号摘要查询的验证错误。 + if _, summaryErr := service.GetOwnedSummary(context.Background(), 7, ""); summaryErr == nil { + t.Fatal("空账号 ID 不应读取账号摘要") + } +} + +// TestSummaryServicePropagatesReadAndAdminErrors 验证摘要服务不吞掉各读取阶段错误。 +func TestSummaryServicePropagatesReadAndAdminErrors(t *testing.T) { + // readErr 是底层摘要查询模拟的基础设施故障。 + readErr := errors.New("摘要读取失败") + // repository 是返回读取故障的摘要端口替身。 + repository := &summaryRepositoryFake{listErr: readErr, summaryErr: readErr, ownedErr: readErr, statusErr: readErr} + // service 是绑定故障端口的应用服务。 + service, err := NewSummaryService(repository, repository) + if err != nil { + t.Fatalf("构造摘要服务失败: %v", err) + } + // _, listErr 保存摘要列表读取的底层错误。 + if _, listErr := service.ListSummaries(context.Background(), 7); !errors.Is(listErr, readErr) { + t.Fatalf("列表错误未保留: %v", listErr) + } + // _, summaryErr 保存单个账号摘要读取的底层错误。 + if _, summaryErr := service.GetOwnedSummary(context.Background(), 7, "acc1"); !errors.Is(summaryErr, readErr) { + t.Fatalf("单项摘要错误未保留: %v", summaryErr) + } + // _, ownedErr 保存账号归属查询的底层错误。 + if _, ownedErr := service.ExistsOwned(context.Background(), 7, "acc1"); !errors.Is(ownedErr, readErr) { + t.Fatalf("归属错误未保留: %v", ownedErr) + } + // _, statusErr 保存账号状态读取的底层错误。 + if _, statusErr := service.StatusOwned(context.Background(), 7, "acc1"); !errors.Is(statusErr, readErr) { + t.Fatalf("状态错误未保留: %v", statusErr) + } + // _, adminErr 保存管理员摘要读取的底层错误。 + if _, adminErr := service.ListAdminSummaries(context.Background()); !errors.Is(adminErr, readErr) { + t.Fatalf("管理员摘要错误未保留: %v", adminErr) + } +} + +// TestSummaryServiceRequireOwnershipDistinguishesResults 验证所有权服务区分本人、越权、不存在和查询故障。 +func TestSummaryServiceRequireOwnershipDistinguishesResults(t *testing.T) { + // cases 覆盖所有权判断的四种结果,并确保越权不会读取敏感数据。 + cases := []struct { + // name 是当前所有权场景名称。 + name string + // repository 是当前场景使用的摘要端口替身。 + repository *summaryRepositoryFake + // wantErr 是期望的稳定应用错误;nil 表示归属通过。 + wantErr error + }{ + {name: "owned", repository: &summaryRepositoryFake{owned: true}, wantErr: nil}, + {name: "forbidden", repository: &summaryRepositoryFake{ownerID: 8}, wantErr: ErrForbidden}, + {name: "missing", repository: &summaryRepositoryFake{ownerErr: ErrNotFound}, wantErr: ErrNotFound}, + {name: "query-failure", repository: &summaryRepositoryFake{ownedErr: errors.New("exists 查询失败")}, wantErr: errors.New("exists 查询失败")}, + } + // testCase 表示当前正在验证的所有权场景。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // service 是当前场景的账号摘要应用服务。 + service, err := NewSummaryService(testCase.repository, testCase.repository) + if err != nil { + t.Fatalf("构造摘要服务失败: %v", err) + } + // gotErr 保存应用服务返回的所有权结果。 + gotErr := service.RequireOwnership(context.Background(), 7, "acc1") + if testCase.wantErr == nil { + if gotErr != nil { + t.Fatalf("本人账号不应失败: %v", gotErr) + } + return + } + if gotErr == nil || gotErr.Error() != testCase.wantErr.Error() { + t.Fatalf("所有权错误=%v,期望=%v", gotErr, testCase.wantErr) + } + }) + } +} + +// TestNewSummaryServiceRequiresRepository 验证摘要服务拒绝缺失普通用户端口,但允许管理员端口按需缺省。 +func TestNewSummaryServiceRequiresRepository(t *testing.T) { + // adminRepository 是满足管理员摘要能力的测试端口。 + adminRepository := &summaryRepositoryFake{} + // _, missingRepositoryErr 保存缺少普通用户端口时的构造错误。 + if _, missingRepositoryErr := NewSummaryService(nil, adminRepository); missingRepositoryErr == nil { + t.Fatal("缺少普通用户摘要端口时应构造失败") + } + // service 是仅装配普通用户端口的应用服务。 + service, err := NewSummaryService(adminRepository, nil) + if err != nil { + t.Fatalf("管理员端口可选时构造失败: %v", err) + } + // _, missingAdminErr 保存缺少管理员端口时的调用错误。 + if _, missingAdminErr := service.ListAdminSummaries(context.Background()); missingAdminErr == nil { + t.Fatal("未装配管理员端口时不应伪装成功") + } +} diff --git a/internal/application/admin/service.go b/internal/application/admin/service.go new file mode 100644 index 0000000..fe29a4c --- /dev/null +++ b/internal/application/admin/service.go @@ -0,0 +1,98 @@ +// Package admin 提供管理员用户与全局统计的应用用例,不依赖 HTTP 或数据库模型。 +package admin + +import ( + "context" + "errors" +) + +// ErrInvalidUser 表示请求没有提供有效的管理员身份。 +var ErrInvalidUser = errors.New("管理员身份无效") + +// ErrSelfDelete 表示管理员试图删除当前会话对应的用户。 +var ErrSelfDelete = errors.New("不能删除当前登录用户") + +// UserSummary 是管理员用户列表使用的非敏感摘要。 +type UserSummary struct { + // ID 是用户稳定标识。 + ID int64 + // Username 是用户登录名。 + Username string + // Email 是用户联系邮箱。 + Email string + // IsActive 表示用户是否启用。 + IsActive bool + // IsAdmin 表示用户是否拥有管理员权限。 + IsAdmin bool + // CreatedAt 是用户创建时间文本。 + CreatedAt string + // CookieCount 是用户拥有的账号数量。 + CookieCount int +} + +// Stats 是管理员仪表盘的全局聚合结果。 +type Stats struct { + // TotalUsers 是用户总数。 + TotalUsers int64 + // TotalCookies 是账号总数。 + TotalCookies int64 + // ActiveCookies 是启用账号总数。 + ActiveCookies int64 + // TotalCards 是卡券组总数。 + TotalCards int64 + // TotalKeywords 是关键词规则总数。 + TotalKeywords int64 + // TotalOrders 是未删除订单总数。 + TotalOrders int64 +} + +// Repository 定义管理员用例需要的最小持久化能力。 +type Repository interface { + // ListUsers 返回不包含密码和凭证的用户摘要。 + ListUsers(context.Context) ([]UserSummary, error) + // DeleteUser 删除用户及其由数据库层管理的关联资源。 + DeleteUser(context.Context, int64) error + // Stats 返回管理员仪表盘聚合计数。 + Stats(context.Context) (Stats, error) +} + +// Service 编排管理员用户管理和仪表盘查询。 +type Service struct { + // repository 保存管理员用例的窄持久化端口。 + repository Repository +} + +// NewService 构造管理员应用服务。 +func NewService(repository Repository) *Service { + return &Service{repository: repository} +} + +// ListUsers 查询管理员用户摘要。 +func (s *Service) ListUsers(ctx context.Context) ([]UserSummary, error) { + if s == nil || s.repository == nil { + return nil, errors.New("管理员服务未初始化") + } + return s.repository.ListUsers(ctx) +} + +// DeleteUser 删除目标用户;服务层拒绝删除当前会话用户,避免 HTTP 层重复实现规则。 +func (s *Service) DeleteUser(ctx context.Context, currentUserID, targetUserID int64) error { + if currentUserID <= 0 || targetUserID <= 0 { + return ErrInvalidUser + } + if currentUserID == targetUserID { + return ErrSelfDelete + } + if s == nil || s.repository == nil { + return errors.New("管理员服务未初始化") + } + return s.repository.DeleteUser(ctx, targetUserID) +} + +// Stats 查询管理员仪表盘统计。 +func (s *Service) Stats(ctx context.Context) (Stats, error) { + if s == nil || s.repository == nil { + return Stats{}, errors.New("管理员服务未初始化") + } + return s.repository.Stats(ctx) +} diff --git a/internal/application/admin/service_test.go b/internal/application/admin/service_test.go new file mode 100644 index 0000000..d1c6362 --- /dev/null +++ b/internal/application/admin/service_test.go @@ -0,0 +1,117 @@ +package admin + +import ( + "context" + "errors" + "testing" +) + +// adminRepositoryStub 保存管理员应用服务测试中的可控仓储行为和调用记录。 +type adminRepositoryStub struct { + // listResult 保存用户列表返回值。 + listResult []UserSummary + // listErr 保存用户列表错误。 + listErr error + // deleteErr 保存用户删除错误。 + deleteErr error + // statsResult 保存统计返回值。 + statsResult Stats + // statsErr 保存统计错误。 + statsErr error + // deletedUserID 保存最后一次删除的目标用户。 + deletedUserID int64 +} + +// ListUsers 返回测试预置的用户摘要。 +func (r *adminRepositoryStub) ListUsers(context.Context) ([]UserSummary, error) { + return r.listResult, r.listErr +} + +// DeleteUser 记录删除目标并返回测试预置错误。 +func (r *adminRepositoryStub) DeleteUser(_ context.Context, userID int64) error { + r.deletedUserID = userID + return r.deleteErr +} + +// Stats 返回测试预置的仪表盘统计。 +func (r *adminRepositoryStub) Stats(context.Context) (Stats, error) { + return r.statsResult, r.statsErr +} + +// TestServiceListUsersAndStats 验证管理员摘要与统计成功、错误和空服务分支。 +func TestServiceListUsersAndStats(t *testing.T) { + // expectedUsers、expectedStats 保存成功路径的应用模型结果。 + expectedUsers := []UserSummary{{ID: 7, Username: "admin"}} + // expectedStats 保存成功路径的统计应用模型结果。 + expectedStats := Stats{TotalUsers: 2, TotalOrders: 3} + // repository 保存成功路径测试仓储。 + repository := &adminRepositoryStub{listResult: expectedUsers, statsResult: expectedStats} + // service 保存待验证的管理员应用服务。 + service := NewService(repository) + // users、usersErr 保存用户摘要查询结果。 + users, usersErr := service.ListUsers(context.Background()) + if usersErr != nil || len(users) != 1 || users[0].ID != 7 { + t.Fatalf("用户摘要查询异常 users=%v err=%v", users, usersErr) + } + // stats、statsErr 保存统计查询结果。 + stats, statsErr := service.Stats(context.Background()) + if statsErr != nil || stats.TotalOrders != 3 { + t.Fatalf("统计查询异常 stats=%+v err=%v", stats, statsErr) + } + // listFailure、statsFailure 保存基础设施错误分支。 + listFailure := errors.New("list failed") + // statsFailure、failureService 保存统计错误和组合错误仓储服务。 + statsFailure := errors.New("stats failed") + // failureService 保存返回基础设施错误的管理员应用服务。 + failureService := NewService(&adminRepositoryStub{listErr: listFailure, statsErr: statsFailure}) + if !errors.Is(mustListUsers(failureService), listFailure) || !errors.Is(mustStats(failureService), statsFailure) { + t.Fatal("管理员查询错误未原样返回") + } + // err 保存空管理员服务的装配错误。 + if _, err := (*Service)(nil).ListUsers(context.Background()); err == nil { + t.Fatal("空管理员服务应拒绝用户列表查询") + } +} + +// mustListUsers 将列表错误转换为便于测试断言的 error。 +func mustListUsers(service *Service) error { + // err 保存管理员列表查询错误。 + _, err := service.ListUsers(context.Background()) + return err +} + +// mustStats 将统计错误转换为便于测试断言的 error。 +func mustStats(service *Service) error { + // err 保存管理员统计查询错误。 + _, err := service.Stats(context.Background()) + return err +} + +// TestServiceDeleteUser 验证无效身份、自删、成功删除和仓储失败分支。 +func TestServiceDeleteUser(t *testing.T) { + // repository 保存可记录删除调用的测试仓储。 + repository := &adminRepositoryStub{} + // service 保存待验证的管理员应用服务。 + service := NewService(repository) + if !errors.Is(service.DeleteUser(context.Background(), 0, 2), ErrInvalidUser) { + t.Fatal("无效当前用户应被拒绝") + } + if !errors.Is(service.DeleteUser(context.Background(), 1, 1), ErrSelfDelete) { + t.Fatal("删除当前用户应被拒绝") + } + // err 保存管理员删除操作的错误。 + if err := service.DeleteUser(context.Background(), 1, 2); err != nil || repository.deletedUserID != 2 { + t.Fatalf("删除成功路径异常 err=%v id=%d", err, repository.deletedUserID) + } + // deleteFailure 保存仓储删除失败结果。 + deleteFailure := errors.New("delete failed") + // err 保存删除仓储返回的错误。 + if err := NewService(&adminRepositoryStub{deleteErr: deleteFailure}).DeleteUser(context.Background(), 1, 2); !errors.Is(err, deleteFailure) { + t.Fatal("删除错误未原样返回") + } + // unavailableErr 保存空服务的装配错误。 + unavailableErr := (*Service)(nil).DeleteUser(context.Background(), 1, 2) + if unavailableErr == nil { + t.Fatal("空管理员服务应拒绝删除") + } +} diff --git a/internal/application/analytics/models.go b/internal/application/analytics/models.go new file mode 100644 index 0000000..9b3692b --- /dev/null +++ b/internal/application/analytics/models.go @@ -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) +} diff --git a/internal/application/analytics/service.go b/internal/application/analytics/service.go new file mode 100644 index 0000000..a968bb4 --- /dev/null +++ b/internal/application/analytics/service.go @@ -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 "" +} diff --git a/internal/application/analytics/service_test.go b/internal/application/analytics/service_test.go new file mode 100644 index 0000000..5a66359 --- /dev/null +++ b/internal/application/analytics/service_test.go @@ -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) + } +} diff --git a/internal/application/automation/account_tasks.go b/internal/application/automation/account_tasks.go new file mode 100644 index 0000000..f1d5dc4 --- /dev/null +++ b/internal/application/automation/account_tasks.go @@ -0,0 +1,175 @@ +// Package automation 提供自动化业务用例的纯应用层编排。 +package automation + +import ( + "context" + "errors" + "regexp" + "strings" +) + +// ErrUnavailable 表示账号任务运行所需的自动化中心尚未装配。 +var ErrUnavailable = errors.New("自动化中心未启用") + +// ErrInvalidTaskType 表示请求未使用受支持的账号任务类型。 +var ErrInvalidTaskType = errors.New("不支持的任务类型") + +// TaskAutoRate 表示自动评价任务。 +const TaskAutoRate = "auto_rate" + +// TaskAutoPolish 表示商品擦亮任务。 +const TaskAutoPolish = "auto_polish" + +// accountTaskTimePattern 校验擦亮任务每天执行的本地时间格式。 +var accountTaskTimePattern = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d$`) + +// AccountTaskSettings 是不含数据库模型的账号任务设置。 +type AccountTaskSettings struct { + // CookieID 是设置所属的账号标识。 + CookieID string `json:"account_id"` + // AutoRateEnabled 表示是否启用自动评价。 + AutoRateEnabled bool `json:"auto_rate_enabled"` + // RateContent 是自动评价使用的文字内容。 + RateContent string `json:"rate_content"` + // AutoPolishEnabled 表示是否启用商品擦亮。 + AutoPolishEnabled bool `json:"auto_polish_enabled"` + // PolishTime 是每天执行擦亮的本地时间,格式为 HH:mm。 + PolishTime string `json:"polish_time"` + // LastRateScanAt 是上次扫描待评价订单的 Unix 秒时间。 + LastRateScanAt int64 `json:"last_rate_scan_at"` + // LastPolishDate 是上次擦亮日期,使用 YYYY-MM-DD 格式。 + LastPolishDate string `json:"last_polish_date"` + // LastPolishAt 是上次擦亮完成的 Unix 秒时间。 + LastPolishAt int64 `json:"last_polish_at"` +} + +// AccountTaskRun 是面向应用层的账号任务运行记录。 +type AccountTaskRun struct { + // ID 是运行记录的持久化标识。 + ID int64 `json:"id"` + // RunKey 是用于幂等去重的运行键。 + RunKey string `json:"run_key"` + // CookieID 是运行所属的账号标识。 + CookieID string `json:"account_id"` + // TaskType 是账号任务类型。 + TaskType string `json:"task_type"` + // TargetID 是本次运行对应的平台对象标识。 + TargetID string `json:"target_id"` + // RunDate 是任务业务日期。 + RunDate string `json:"run_date"` + // Status 是运行当前状态。 + Status string `json:"status"` + // SuccessCount 是外部动作成功数量。 + SuccessCount int `json:"success_count"` + // FailedCount 是外部动作失败数量。 + FailedCount int `json:"failed_count"` + // ErrorMessage 是供人工核对的非敏感错误摘要。 + ErrorMessage string `json:"error_message"` + // NextRetryAt 是下一次重试的 Unix 秒时间。 + NextRetryAt int64 `json:"next_retry_at"` + // StartedAt 是运行开始的 Unix 秒时间。 + StartedAt int64 `json:"started_at"` + // FinishedAt 是运行结束的 Unix 秒时间。 + FinishedAt int64 `json:"finished_at"` +} + +// TaskSummary 是手动执行账号任务后的统计结果。 +type TaskSummary struct { + // TaskType 是本次执行的任务类型。 + TaskType string `json:"task_type"` + // Found 是发现的待处理对象数量。 + Found int `json:"found"` + // Success 是外部动作成功数量。 + Success int `json:"success"` + // Failed 是外部动作失败数量。 + Failed int `json:"failed"` + // Skipped 是因状态或幂等检查而跳过的数量。 + Skipped int `json:"skipped"` + // Message 是面向操作人员的非敏感执行说明。 + Message string `json:"message,omitempty"` +} + +// Repository 定义账号任务设置和历史记录所需的最小持久化能力。 +type Repository interface { + // GetSettings 读取账号任务设置,未创建设置时返回默认值。 + GetSettings(ctx context.Context, accountID string) (AccountTaskSettings, error) + // SaveSettings 保存账号任务设置。 + SaveSettings(ctx context.Context, settings AccountTaskSettings) error + // ListRuns 返回账号最近的任务运行记录。 + ListRuns(ctx context.Context, accountID string, limit int) ([]AccountTaskRun, error) +} + +// Runner 定义手动触发账号任务所需的运行能力。 +type Runner interface { + // RunAccountTask 执行指定账号的一个自动化任务。 + RunAccountTask(ctx context.Context, accountID, taskType string) (TaskSummary, error) +} + +// Service 编排账号任务的设置、历史和手动执行用例。 +type Service struct { + // repository 提供账号任务持久化能力。 + repository Repository + // runner 提供自动化中心的手动执行能力。 + runner Runner +} + +// NewService 构造账号任务应用服务。 +func NewService(repository Repository, runner Runner) *Service { + return &Service{repository: repository, runner: runner} +} + +// GetSettings 读取指定账号的账号任务设置。 +func (s *Service) GetSettings(ctx context.Context, accountID string) (AccountTaskSettings, error) { + if s == nil || s.repository == nil { + return AccountTaskSettings{}, errors.New("账号任务存储未初始化") + } + return s.repository.GetSettings(ctx, strings.TrimSpace(accountID)) +} + +// UpdateSettings 校验并保存账号任务设置,再读取数据库中的最终值。 +func (s *Service) UpdateSettings(ctx context.Context, settings AccountTaskSettings) (AccountTaskSettings, error) { + if s == nil || s.repository == nil { + return AccountTaskSettings{}, errors.New("账号任务存储未初始化") + } + settings.CookieID = strings.TrimSpace(settings.CookieID) + settings.RateContent = strings.TrimSpace(settings.RateContent) + if settings.CookieID == "" { + return AccountTaskSettings{}, errors.New("账号标识不能为空") + } + if settings.AutoRateEnabled && settings.RateContent == "" { + return AccountTaskSettings{}, errors.New("启用自动评价时评价内容不能为空") + } + if len([]rune(settings.RateContent)) > 500 { + return AccountTaskSettings{}, errors.New("评价内容不能超过 500 个字符") + } + if !accountTaskTimePattern.MatchString(settings.PolishTime) { + return AccountTaskSettings{}, errors.New("擦亮时间格式必须为 HH:mm") + } + // err 表示账号任务设置写入失败。 + if err := s.repository.SaveSettings(ctx, settings); err != nil { + return AccountTaskSettings{}, err + } + return s.repository.GetSettings(ctx, settings.CookieID) +} + +// ListRuns 查询指定账号最近的任务运行记录。 +func (s *Service) ListRuns(ctx context.Context, accountID string, limit int) ([]AccountTaskRun, error) { + if s == nil || s.repository == nil { + return nil, errors.New("账号任务存储未初始化") + } + if limit <= 0 || limit > 100 { + limit = 20 + } + return s.repository.ListRuns(ctx, strings.TrimSpace(accountID), limit) +} + +// Run 手动执行指定账号的账号任务。 +func (s *Service) Run(ctx context.Context, accountID, taskType string) (TaskSummary, error) { + if s == nil || s.runner == nil { + return TaskSummary{}, ErrUnavailable + } + if taskType != TaskAutoRate && taskType != TaskAutoPolish { + return TaskSummary{}, ErrInvalidTaskType + } + return s.runner.RunAccountTask(ctx, strings.TrimSpace(accountID), taskType) +} diff --git a/internal/application/automation/account_tasks_test.go b/internal/application/automation/account_tasks_test.go new file mode 100644 index 0000000..ce471d6 --- /dev/null +++ b/internal/application/automation/account_tasks_test.go @@ -0,0 +1,134 @@ +package automation + +import ( + "context" + "errors" + "strings" + "testing" +) + +// accountTaskRepositoryFake 保存账号任务应用服务测试所需的内存状态。 +type accountTaskRepositoryFake struct { + // settings 是按账号保存的任务设置。 + settings AccountTaskSettings + // runs 是待返回的历史运行记录。 + runs []AccountTaskRun + // saveErr 是保存设置时模拟的错误。 + saveErr error +} + +// GetSettings 返回测试设置。 +func (r *accountTaskRepositoryFake) GetSettings(context.Context, string) (AccountTaskSettings, error) { + return r.settings, nil +} + +// SaveSettings 保存测试设置。 +func (r *accountTaskRepositoryFake) SaveSettings(_ context.Context, settings AccountTaskSettings) error { + if r.saveErr != nil { + return r.saveErr + } + r.settings = settings + return nil +} + +// ListRuns 返回测试运行记录并保留调用上限。 +func (r *accountTaskRepositoryFake) ListRuns(_ context.Context, _ string, limit int) ([]AccountTaskRun, error) { + if len(r.runs) > limit { + return r.runs[:limit], nil + } + return r.runs, nil +} + +// accountTaskRunnerFake 保存手动执行调用参数。 +type accountTaskRunnerFake struct { + // summary 是模拟的任务结果。 + summary TaskSummary + // accountID 是最近一次执行的账号标识。 + accountID string + // taskType 是最近一次执行的任务类型。 + taskType string +} + +// RunAccountTask 记录并返回测试任务结果。 +func (r *accountTaskRunnerFake) RunAccountTask(_ context.Context, accountID, taskType string) (TaskSummary, error) { + r.accountID = accountID + r.taskType = taskType + return r.summary, nil +} + +// TestServiceUpdateSettings 验证设置规范化、校验和最终值读取。 +func TestServiceUpdateSettings(t *testing.T) { + // repository 保存测试用例的设置状态。 + repository := &accountTaskRepositoryFake{} + // service 是待验证的账号任务应用服务。 + service := NewService(repository, nil) + // stored 保存校验通过后的最终设置。 + stored, err := service.UpdateSettings(context.Background(), AccountTaskSettings{ + CookieID: " account-1 ", AutoRateEnabled: true, RateContent: " 交易愉快 ", PolishTime: "03:00", + }) + if err != nil { + t.Fatal(err) + } + if stored.CookieID != "account-1" || stored.RateContent != "交易愉快" { + t.Fatalf("设置未按应用规则规范化: %+v", stored) + } + // saveErr 表示测试仓储未预置保存失败。 + if saveErr := repository.saveErr; saveErr != nil { + t.Fatal(err) + } +} + +// TestServiceRejectsInvalidSettings 验证非法设置不会进入仓储。 +func TestServiceRejectsInvalidSettings(t *testing.T) { + // cases 保存需要拒绝的输入及稳定错误片段。 + cases := []struct { + // name 是测试分支名称。 + name string + // settings 是待校验的设置。 + settings AccountTaskSettings + // want 是错误信息中应包含的业务提示。 + want string + }{ + {name: "missing content", settings: AccountTaskSettings{CookieID: "a", AutoRateEnabled: true, PolishTime: "03:00"}, want: "评价内容不能为空"}, + {name: "invalid time", settings: AccountTaskSettings{CookieID: "a", PolishTime: "3:00"}, want: "格式必须"}, + } + // testCase 是当前待验证的非法账号任务设置分支。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // repository 保存当前分支的持久化假对象。 + repository := &accountTaskRepositoryFake{} + // err 保存非法设置返回的校验错误。 + _, err := NewService(repository, nil).UpdateSettings(context.Background(), testCase.settings) + if err == nil || !strings.Contains(err.Error(), testCase.want) { + t.Fatalf("错误=%v,期望包含=%q", err, testCase.want) + } + }) + } +} + +// TestServiceRunValidatesTypeAndPropagatesRunner 验证任务类型校验和执行摘要透传。 +func TestServiceRunValidatesTypeAndPropagatesRunner(t *testing.T) { + // runner 保存手动任务执行替身。 + runner := &accountTaskRunnerFake{summary: TaskSummary{TaskType: TaskAutoRate, Success: 2}} + // service 是绑定执行替身的应用服务。 + service := NewService(nil, runner) + // summary 保存合法任务的结果。 + summary, err := service.Run(context.Background(), "account-1", TaskAutoRate) + if err != nil || summary.Success != 2 { + t.Fatalf("执行结果错误: summary=%+v err=%v", summary, err) + } + if runner.accountID != "account-1" || runner.taskType != TaskAutoRate { + t.Fatalf("执行参数错误: account=%q task=%q", runner.accountID, runner.taskType) + } + // invalidErr 保存非法任务类型返回的应用层错误。 + if invalidErr := serviceRunInvalid(service); !errors.Is(invalidErr, ErrInvalidTaskType) { + t.Fatalf("非法任务类型错误=%v", err) + } +} + +// serviceRunInvalid 返回非法任务类型错误,保持主测试只关注应用服务契约。 +func serviceRunInvalid(service *Service) error { + // err 表示应用服务拒绝未知任务类型的契约错误。 + _, err := service.Run(context.Background(), "account-1", "unknown") + return err +} diff --git a/internal/application/automation/credential_wake.go b/internal/application/automation/credential_wake.go new file mode 100644 index 0000000..b19f60c --- /dev/null +++ b/internal/application/automation/credential_wake.go @@ -0,0 +1,40 @@ +// Package automation 提供自动化业务用例的纯应用层编排。 +package automation + +import ( + "context" + "errors" + "strings" +) + +// CredentialWakeRepository 定义凭证恢复后唤醒账号任务所需的最小端口。 +type CredentialWakeRepository interface { + // WakeCredentialBlocked 唤醒指定账号因凭证失效而暂停的自动化任务。 + WakeCredentialBlocked(context.Context, string) error +} + +// CredentialWakeService 编排凭证恢复后的自动化任务唤醒,不依赖数据库或 HTTP 类型。 +type CredentialWakeService struct { + // repository 提供自动化任务唤醒的持久化能力。 + repository CredentialWakeRepository +} + +// NewCredentialWakeService 构造凭证恢复唤醒应用服务并校验依赖。 +func NewCredentialWakeService(repository CredentialWakeRepository) (*CredentialWakeService, error) { + if repository == nil { + return nil, errors.New("凭证恢复唤醒 repository 未初始化") + } + return &CredentialWakeService{repository: repository}, nil +} + +// WakeCredentialBlocked 唤醒指定账号的凭证阻塞任务,并拒绝空账号标识。 +func (s *CredentialWakeService) WakeCredentialBlocked(ctx context.Context, accountID string) error { + if s == nil || s.repository == nil { + return errors.New("凭证恢复唤醒服务未初始化") + } + accountID = strings.TrimSpace(accountID) + if accountID == "" { + return errors.New("账号标识不能为空") + } + return s.repository.WakeCredentialBlocked(ctx, accountID) +} diff --git a/internal/application/automation/credential_wake_test.go b/internal/application/automation/credential_wake_test.go new file mode 100644 index 0000000..22b8e7b --- /dev/null +++ b/internal/application/automation/credential_wake_test.go @@ -0,0 +1,59 @@ +package automation + +import ( + "context" + "errors" + "testing" +) + +// credentialWakeRepositoryFake 是凭证恢复唤醒应用服务测试用的可控端口替身。 +type credentialWakeRepositoryFake struct { + // accountID 保存最近一次收到的账号标识。 + accountID string + // wakeErr 保存模拟的持久化唤醒错误。 + wakeErr error +} + +// WakeCredentialBlocked 记录唤醒请求并返回预置错误。 +func (f *credentialWakeRepositoryFake) WakeCredentialBlocked(_ context.Context, accountID string) error { + f.accountID = accountID + return f.wakeErr +} + +// TestCredentialWakeServiceValidatesAndForwards 验证凭证恢复唤醒的输入、转发和错误传播。 +func TestCredentialWakeServiceValidatesAndForwards(t *testing.T) { + // repository 是接收应用层唤醒请求的测试端口。 + repository := &credentialWakeRepositoryFake{} + // service 是绑定测试端口的凭证恢复唤醒服务。 + // err 保存应用服务构造错误。 + service, err := NewCredentialWakeService(repository) + if err != nil { + t.Fatalf("构造唤醒服务失败: %v", err) + } + // err 表示归一化账号标识后的唤醒调用错误。 + if err := service.WakeCredentialBlocked(context.Background(), " acc1 "); err != nil { + t.Fatalf("唤醒账号失败: %v", err) + } + if repository.accountID != "acc1" { + t.Fatalf("账号标识未归一化: %q", repository.accountID) + } + // err 表示空账号标识被应用层拒绝的错误结果。 + if err := service.WakeCredentialBlocked(context.Background(), " "); err == nil { + t.Fatal("空账号标识不应调用唤醒端口") + } + // wakeErr 是底层任务状态写入故障。 + wakeErr := errors.New("唤醒写入失败") + repository.wakeErr = wakeErr + // err 表示底层任务状态写入故障向应用层传播的结果。 + if err := service.WakeCredentialBlocked(context.Background(), "acc1"); !errors.Is(err, wakeErr) { + t.Fatalf("唤醒错误未传播: %v", err) + } +} + +// TestNewCredentialWakeServiceRequiresRepository 验证凭证恢复唤醒服务拒绝缺失端口。 +func TestNewCredentialWakeServiceRequiresRepository(t *testing.T) { + // _, err 保存缺少持久化端口时的构造错误。 + if _, err := NewCredentialWakeService(nil); err == nil { + t.Fatal("缺少唤醒 repository 时不应构造成功") + } +} diff --git a/internal/application/automation/publish_rules.go b/internal/application/automation/publish_rules.go new file mode 100644 index 0000000..a0bcc0f --- /dev/null +++ b/internal/application/automation/publish_rules.go @@ -0,0 +1,28 @@ +package automation + +import "context" + +// PublishRuleRepository 定义批量发布成功后幂等准备自动化规则所需的最小持久化能力。 +type PublishRuleRepository interface { + // EnsurePublishRule 确保同一发布商品的自动化规则只创建一次。 + EnsurePublishRule(ctx context.Context, input RuleInput) error +} + +// PublishRuleService 编排发布成功后的自动化规则幂等准备,不依赖 HTTP 或数据库模型。 +type PublishRuleService struct { + // repository 保存调用方注入的发布自动化规则持久化端口。 + repository PublishRuleRepository +} + +// NewPublishRuleService 构造批量发布自动化规则应用服务。 +func NewPublishRuleService(repository PublishRuleRepository) *PublishRuleService { + return &PublishRuleService{repository: repository} +} + +// Ensure 确保发布自动化规则存在,并保留适配器返回的底层错误语义。 +func (s *PublishRuleService) Ensure(ctx context.Context, input RuleInput) error { + if s == nil || s.repository == nil { + return ErrInvalidInput + } + return s.repository.EnsurePublishRule(ctx, input) +} diff --git a/internal/application/automation/publish_rules_test.go b/internal/application/automation/publish_rules_test.go new file mode 100644 index 0000000..ae5f956 --- /dev/null +++ b/internal/application/automation/publish_rules_test.go @@ -0,0 +1,64 @@ +package automation + +import ( + "context" + "errors" + "testing" +) + +// publishRuleRepositoryFake 保存发布自动化规则应用服务测试所需的最小仓储替身。 +type publishRuleRepositoryFake struct { + // input 保存最近一次幂等准备收到的规则输入。 + input RuleInput + // calls 记录幂等准备被调用的次数。 + calls int + // err 是仓储替身需要返回的预设错误。 + err error +} + +// EnsurePublishRule 记录发布规则输入并返回预设错误。 +func (f *publishRuleRepositoryFake) EnsurePublishRule(_ context.Context, input RuleInput) error { + f.input = input + f.calls++ + return f.err +} + +// TestPublishRuleServiceForwardsInput 验证发布规则应用服务只编排端口调用并保留输入。 +func TestPublishRuleServiceForwardsInput(t *testing.T) { + // repository 是记录应用服务调用的仓储替身。 + repository := &publishRuleRepositoryFake{} + // service 是绑定测试仓储的发布规则应用服务。 + service := NewPublishRuleService(repository) + // input 是代表批量发布结果的最小自动化规则输入。 + input := RuleInput{UserID: 7, CookieID: "account-1", ItemID: "item-1", Name: "付款后自动发货", TriggerType: TriggerOrderPaid, Actions: []ActionInput{{ActionType: ActionConfirmShipment, Enabled: true, SortOrder: 1}}} + // err 保存应用服务调用结果。 + err := service.Ensure(context.Background(), input) + if err != nil { + t.Fatal(err) + } + if repository.calls != 1 || repository.input.UserID != input.UserID || repository.input.Actions[0].ActionType != ActionConfirmShipment { + t.Fatalf("应用服务未完整转发规则输入: calls=%d input=%+v", repository.calls, repository.input) + } +} + +// TestPublishRuleServicePropagatesRepositoryError 验证发布规则准备失败不会被应用层吞掉。 +func TestPublishRuleServicePropagatesRepositoryError(t *testing.T) { + // expectedErr 是仓储端模拟的持久化故障。 + expectedErr := errors.New("database unavailable") + // service 是绑定故障仓储的发布规则应用服务。 + service := NewPublishRuleService(&publishRuleRepositoryFake{err: expectedErr}) + // err 保存应用服务返回的持久化错误。 + err := service.Ensure(context.Background(), RuleInput{UserID: 1}) + if !errors.Is(err, expectedErr) { + t.Fatalf("应透传仓储错误,err=%v", err) + } +} + +// TestPublishRuleServiceRejectsMissingRepository 验证缺少发布规则持久化端口时返回参数错误。 +func TestPublishRuleServiceRejectsMissingRepository(t *testing.T) { + // err 保存缺少仓储时的应用服务错误。 + err := NewPublishRuleService(nil).Ensure(context.Background(), RuleInput{UserID: 1}) + if !errors.Is(err, ErrInvalidInput) { + t.Fatalf("缺少仓储应返回参数错误,err=%v", err) + } +} diff --git a/internal/application/automation/rules.go b/internal/application/automation/rules.go new file mode 100644 index 0000000..4a5dede --- /dev/null +++ b/internal/application/automation/rules.go @@ -0,0 +1,441 @@ +package automation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" +) + +// ErrRuleNotFound 表示规则不存在或不属于当前用户。 +var ErrRuleNotFound = errors.New("自动化规则不存在") + +// ErrRuleActive 表示规则仍有待处理运行,不能直接删除。 +var ErrRuleActive = errors.New("规则仍有待处理的自动化运行") + +// TriggerOrderPaid 表示付款后触发器。 +const TriggerOrderPaid = "order_paid" + +// TriggerBuyerReviewed 表示买家评价后触发器。 +const TriggerBuyerReviewed = "buyer_reviewed" + +// TriggerReviewMissingTimeout 表示超时未评价触发器。 +const TriggerReviewMissingTimeout = "review_missing_timeout" + +// ActionConfirmShipment 表示确认发货动作。 +const ActionConfirmShipment = "confirm_shipment" + +// ActionSendCard 表示发送卡密动作。 +const ActionSendCard = "send_card" + +// ActionSendText 表示发送文本动作。 +const ActionSendText = "send_text" + +// ActionDraft 是 HTTP/应用边界使用的自动化动作输入。 +type ActionDraft struct { + // ActionType 是动作类型。 + ActionType string + // CardID 是发送卡密动作使用的卡密组标识。 + CardID int64 + // DeliveryCount 是动作发送数量。 + DeliveryCount int + // MessageTemplate 是发送文本动作的文案。 + MessageTemplate string + // DelaySeconds 是动作执行前的延迟秒数。 + DelaySeconds int + // ConfigJSON 是动作扩展配置 JSON 对象。 + ConfigJSON string + // Enabled 表示动作是否启用。 + Enabled *bool + // SortOrder 是动作在规则中的顺序。 + SortOrder int +} + +// RuleDraft 是创建或更新自动化规则的业务输入。 +type RuleDraft struct { + // CookieID 是规则所属账号标识。 + CookieID string + // ItemID 是可选的商品标识。 + ItemID string + // Name 是规则显示名称。 + Name string + // TriggerType 是规则触发类型。 + TriggerType string + // Enabled 表示规则是否启用。 + Enabled bool + // Priority 是规则匹配优先级。 + Priority int + // ConfigJSON 是规则扩展配置 JSON 对象。 + ConfigJSON string + // Actions 是规则包含的动作列表。 + Actions []ActionDraft +} + +// RuleInput 是通过校验并可交给仓储写入的规则模型。 +type RuleInput struct { + // UserID 是规则所属用户。 + UserID int64 + // CookieID 是规则所属账号标识。 + CookieID string + // ItemID 是可选的商品标识。 + ItemID string + // Name 是规则显示名称。 + Name string + // TriggerType 是规则触发类型。 + TriggerType string + // Enabled 表示规则是否启用。 + Enabled bool + // Priority 是规则匹配优先级。 + Priority int + // ConfigJSON 是规则扩展配置 JSON 对象。 + ConfigJSON string + // Actions 是经过规范化的动作列表。 + Actions []ActionInput +} + +// ActionInput 是经过校验并可持久化的自动化动作。 +type ActionInput struct { + // ActionType 是动作类型。 + ActionType string + // CardID 是发送卡密动作使用的卡密组标识。 + CardID int64 + // DeliveryCount 是动作发送数量。 + DeliveryCount int + // MessageTemplate 是发送文本动作的文案。 + MessageTemplate string + // DelaySeconds 是动作执行前的延迟秒数。 + DelaySeconds int + // ConfigJSON 是动作扩展配置 JSON 对象。 + ConfigJSON string + // Enabled 表示动作是否启用。 + Enabled bool + // SortOrder 是动作在规则中的顺序。 + SortOrder int +} + +// Rule 是返回给 HTTP 适配层的非数据库规则模型。 +type Rule struct { + // ID 是规则持久化标识。 + ID int64 + // CookieID 是规则所属账号标识。 + CookieID string + // ItemID 是可选的商品标识。 + ItemID string + // ItemTitle 是商品标题摘要。 + ItemTitle string + // Name 是规则显示名称。 + Name string + // TriggerType 是规则触发类型。 + TriggerType string + // Enabled 表示规则是否启用。 + Enabled bool + // Priority 是规则匹配优先级。 + Priority int + // ConfigJSON 是规则扩展配置。 + ConfigJSON string + // Actions 是规则动作列表。 + Actions []Action + // CreatedAt 是规则创建时间文本。 + CreatedAt string + // UpdatedAt 是规则更新时间文本。 + UpdatedAt string +} + +// Action 是返回给 HTTP 适配层的非数据库动作模型。 +type Action struct { + // ID 是动作持久化标识。 + ID int64 + // ActionType 是动作类型。 + ActionType string + // CardID 是关联卡密组标识。 + CardID int64 + // CardName 是关联卡密组名称。 + CardName string + // DeliveryCount 是动作发送数量。 + DeliveryCount int + // MessageTemplate 是发送文本文案。 + MessageTemplate string + // DelaySeconds 是动作延迟秒数。 + DelaySeconds int + // ConfigJSON 是动作扩展配置。 + ConfigJSON string + // Enabled 表示动作是否启用。 + Enabled bool + // SortOrder 是动作顺序。 + SortOrder int +} + +// RuleFilter 是用户范围规则分页查询条件。 +type RuleFilter struct { + // UserID 是查询所属用户。 + UserID int64 + // CookieID 是可选账号过滤条件。 + CookieID string + // TriggerType 是可选触发类型过滤条件。 + TriggerType string + // Enabled 是可选启用状态过滤条件。 + Enabled *bool + // Search 是规则名称或商品搜索词。 + Search string + // Limit 是分页大小。 + Limit int + // Offset 是分页偏移量。 + Offset int +} + +// CardInfo 是规则校验所需的最小卡密组信息。 +type CardInfo struct { + // Type 是卡密组类型。 + Type string +} + +// RuleRepository 定义规则持久化所需的窄接口。 +type RuleRepository interface { + // ListForUser 返回用户全部规则。 + ListForUser(ctx context.Context, userID int64) ([]Rule, error) + // ListPageForUser 返回用户规则分页和总数。 + ListPageForUser(ctx context.Context, filter RuleFilter) ([]Rule, int, error) + // CountByTriggerForUser 返回用户规则触发类型统计。 + CountByTriggerForUser(ctx context.Context, filter RuleFilter) (map[string]int, error) + // Create 创建规则并返回标识。 + Create(ctx context.Context, input RuleInput) (int64, error) + // Update 更新用户拥有的规则。 + Update(ctx context.Context, userID, ruleID int64, input RuleInput) error + // Delete 删除用户拥有的规则。 + Delete(ctx context.Context, userID, ruleID int64) error +} + +// RuleOwnership 定义规则校验所需的账号、商品和卡密组归属能力。 +type RuleOwnership interface { + // OwnsAccount 判断账号是否属于用户。 + OwnsAccount(ctx context.Context, userID int64, accountID string) (bool, error) + // OwnsItem 判断商品是否属于用户账号。 + OwnsItem(ctx context.Context, userID int64, accountID, itemID string) (bool, error) + // GetCard 返回用户拥有的卡密组类型。 + GetCard(ctx context.Context, userID, cardID int64) (CardInfo, error) +} + +// RuleService 编排自动化规则校验、分页和持久化。 +type RuleService struct { + // repository 提供规则持久化能力。 + repository RuleRepository + // ownership 提供规则输入的归属与卡密组校验能力。 + ownership RuleOwnership +} + +// NewRuleService 构造自动化规则应用服务。 +func NewRuleService(repository RuleRepository, ownership RuleOwnership) *RuleService { + return &RuleService{repository: repository, ownership: ownership} +} + +// ListForUser 查询用户全部自动化规则。 +func (s *RuleService) ListForUser(ctx context.Context, userID int64) ([]Rule, error) { + if s == nil || s.repository == nil || userID <= 0 { + return nil, ErrInvalidInput + } + return s.repository.ListForUser(ctx, userID) +} + +// ListPageForUser 查询用户自动化规则分页并归一化分页参数。 +func (s *RuleService) ListPageForUser(ctx context.Context, filter RuleFilter) ([]Rule, int, error) { + if s == nil || s.repository == nil || filter.UserID <= 0 { + return nil, 0, ErrInvalidInput + } + if filter.Limit <= 0 || filter.Limit > 100 { + filter.Limit = 10 + } + if filter.Offset < 0 { + filter.Offset = 0 + } + return s.repository.ListPageForUser(ctx, filter) +} + +// CountByTriggerForUser 查询用户规则触发类型统计。 +func (s *RuleService) CountByTriggerForUser(ctx context.Context, filter RuleFilter) (map[string]int, error) { + if s == nil || s.repository == nil || filter.UserID <= 0 { + return nil, ErrInvalidInput + } + return s.repository.CountByTriggerForUser(ctx, filter) +} + +// Normalize 校验并规范化 HTTP 边界传入的规则草稿。 +func (s *RuleService) Normalize(ctx context.Context, userID int64, draft RuleDraft) (RuleInput, error) { + if s == nil || s.repository == nil || s.ownership == nil || userID <= 0 { + return RuleInput{}, ErrInvalidInput + } + draft.CookieID = strings.TrimSpace(draft.CookieID) + draft.ItemID = strings.TrimSpace(draft.ItemID) + draft.Name = strings.TrimSpace(draft.Name) + draft.TriggerType = strings.TrimSpace(draft.TriggerType) + if draft.TriggerType != TriggerOrderPaid && draft.TriggerType != TriggerBuyerReviewed && draft.TriggerType != TriggerReviewMissingTimeout { + return RuleInput{}, errors.New("不支持的触发类型") + } + // owned 表示账号是否归当前用户所有;err 表示归属查询失败。 + owned, err := s.ownership.OwnsAccount(ctx, userID, draft.CookieID) + if err != nil { + return RuleInput{}, err + } + if !owned { + return RuleInput{}, errors.New("账号不存在或不属于当前用户") + } + if draft.ItemID != "" { + owned, err = s.ownership.OwnsItem(ctx, userID, draft.CookieID, draft.ItemID) + if err != nil { + return RuleInput{}, err + } + if !owned { + return RuleInput{}, errors.New("商品不属于当前用户") + } + } + if draft.Priority <= 0 { + draft.Priority = 100 + } + if draft.ConfigJSON == "" { + draft.ConfigJSON = "{}" + } + if !isJSONObject(draft.ConfigJSON) { + return RuleInput{}, errors.New("规则配置必须是 JSON 对象") + } + if len(draft.Actions) == 0 { + return RuleInput{}, errors.New("至少需要一个自动化动作") + } + if draft.Name == "" { + draft.Name = defaultRuleName(draft.TriggerType, draft.ItemID) + } + // actions 保存规范化后的动作;三个布尔值记录启用动作类型,供规则完整性校验使用。 + actions := make([]ActionInput, 0, len(draft.Actions)) + // hasSendCard 表示是否存在启用的发卡动作。 + hasSendCard := false + // hasSendText 表示是否存在启用的文本动作。 + hasSendText := false + // hasConfirmShipment 表示是否存在启用的确认发货动作。 + hasConfirmShipment := false + // index 是当前动作在草稿中的位置;draftAction 是待校验和规范化的动作。 + for index, draftAction := range draft.Actions { + // enabled 表示当前动作是否参与运行;未提供时默认启用。 + enabled := true + if draftAction.Enabled != nil { + enabled = *draftAction.Enabled + } + draftAction.ActionType = strings.TrimSpace(draftAction.ActionType) + switch draftAction.ActionType { + case ActionConfirmShipment: + hasConfirmShipment = hasConfirmShipment || enabled + case ActionSendCard: + if draftAction.CardID <= 0 { + return RuleInput{}, errors.New("发送卡密动作必须选择卡密组") + } + // card 是归属校验通过的卡密摘要;cardErr 表示卡密读取或归属校验失败。 + card, cardErr := s.ownership.GetCard(ctx, userID, draftAction.CardID) + if cardErr != nil { + if !errors.Is(cardErr, ErrRuleNotFound) { + return RuleInput{}, cardErr + } + return RuleInput{}, errors.New("卡密组不存在或不属于当前用户") + } + if card.Type == "api" { + return RuleInput{}, errors.New("API 卡密暂不支持自动发货,请选择文本、批量数据或图片卡密") + } + hasSendCard = hasSendCard || enabled + case ActionSendText: + if strings.TrimSpace(draftAction.MessageTemplate) == "" { + return RuleInput{}, errors.New("发送文本动作必须填写文案") + } + hasSendText = hasSendText || enabled + default: + return RuleInput{}, errors.New("不支持的动作类型") + } + if draftAction.DeliveryCount <= 0 { + draftAction.DeliveryCount = 1 + } + if draftAction.DelaySeconds < 0 || draftAction.DelaySeconds > 3600 { + return RuleInput{}, errors.New("动作延时必须在 0 到 3600 秒之间") + } + if draftAction.ConfigJSON == "" { + draftAction.ConfigJSON = "{}" + } + if !isJSONObject(draftAction.ConfigJSON) { + return RuleInput{}, errors.New("动作配置必须是 JSON 对象") + } + actions = append(actions, ActionInput{ActionType: draftAction.ActionType, CardID: draftAction.CardID, + DeliveryCount: draftAction.DeliveryCount, MessageTemplate: draftAction.MessageTemplate, + DelaySeconds: draftAction.DelaySeconds, ConfigJSON: draftAction.ConfigJSON, Enabled: enabled, + SortOrder: firstRuleNonZero(draftAction.SortOrder, index+1)}) + } + switch draft.TriggerType { + case TriggerOrderPaid: + if !hasSendCard { + return RuleInput{}, errors.New("付款后自动发货至少需要一个已启用的发送卡密动作") + } + case TriggerBuyerReviewed: + if hasConfirmShipment { + return RuleInput{}, errors.New("评价后规则不能包含确认发货动作") + } + if !hasSendCard && !hasSendText { + return RuleInput{}, errors.New("评价后规则至少需要一个已启用的发送动作") + } + case TriggerReviewMissingTimeout: + if hasConfirmShipment || hasSendCard { + return RuleInput{}, errors.New("求评价规则只能发送文本") + } + if !hasSendText { + return RuleInput{}, errors.New("求评价规则至少需要一个已启用的文本动作") + } + } + return RuleInput{UserID: userID, CookieID: draft.CookieID, ItemID: draft.ItemID, Name: draft.Name, + TriggerType: draft.TriggerType, Enabled: draft.Enabled, Priority: draft.Priority, + ConfigJSON: draft.ConfigJSON, Actions: actions}, nil +} + +// Create 创建已校验的自动化规则。 +func (s *RuleService) Create(ctx context.Context, input RuleInput) (int64, error) { + if s == nil || s.repository == nil { + return 0, ErrInvalidInput + } + return s.repository.Create(ctx, input) +} + +// Update 更新用户拥有的自动化规则。 +func (s *RuleService) Update(ctx context.Context, userID, ruleID int64, input RuleInput) error { + if s == nil || s.repository == nil || userID <= 0 || ruleID <= 0 { + return ErrInvalidInput + } + return s.repository.Update(ctx, userID, ruleID, input) +} + +// Delete 删除用户拥有的自动化规则。 +func (s *RuleService) Delete(ctx context.Context, userID, ruleID int64) error { + if s == nil || s.repository == nil || userID <= 0 || ruleID <= 0 { + return ErrInvalidInput + } + return s.repository.Delete(ctx, userID, ruleID) +} + +// isJSONObject 判断配置是否为 JSON 对象。 +func isJSONObject(raw string) bool { + // value 是 JSON 对象解析结果,仅用于确认配置顶层类型,不保存业务状态。 + var value map[string]any + return json.Unmarshal([]byte(raw), &value) == nil +} + +// defaultRuleName 根据触发类型和商品标识生成默认规则名称。 +func defaultRuleName(triggerType, itemID string) string { + // name 是按触发类型选择的默认显示名称,必要时再附加商品标识。 + name := map[string]string{TriggerOrderPaid: "付款后自动发货", TriggerBuyerReviewed: "评价后发送赠品", TriggerReviewMissingTimeout: "超时未评价求评价"}[triggerType] + if name == "" { + name = "自动化规则" + } + if strings.TrimSpace(itemID) != "" { + return fmt.Sprintf("%s - %s", name, strings.TrimSpace(itemID)) + } + return name +} + +// firstRuleNonZero 返回动作顺序或其默认下标。 +func firstRuleNonZero(value, fallback int) int { + if value != 0 { + return value + } + return fallback +} diff --git a/internal/application/automation/rules_test.go b/internal/application/automation/rules_test.go new file mode 100644 index 0000000..8ee288b --- /dev/null +++ b/internal/application/automation/rules_test.go @@ -0,0 +1,184 @@ +package automation + +import ( + "context" + "errors" + "strings" + "testing" +) + +// ruleRepositoryFake 保存规则应用服务测试所需的最小仓储替身。 +type ruleRepositoryFake struct { + // created 保存最近一次创建输入。 + created RuleInput + // listedFilter 保存最近一次分页查询条件。 + listedFilter RuleFilter +} + +// ListForUser 返回空规则列表。 +func (r *ruleRepositoryFake) ListForUser(context.Context, int64) ([]Rule, error) { return nil, nil } + +// ListPageForUser 记录分页条件并返回空结果。 +func (r *ruleRepositoryFake) ListPageForUser(_ context.Context, filter RuleFilter) ([]Rule, int, error) { + r.listedFilter = filter + return nil, 0, nil +} + +// CountByTriggerForUser 返回空触发统计。 +func (r *ruleRepositoryFake) CountByTriggerForUser(context.Context, RuleFilter) (map[string]int, error) { + return map[string]int{}, nil +} + +// Create 记录规则输入并返回固定标识。 +func (r *ruleRepositoryFake) Create(_ context.Context, input RuleInput) (int64, error) { + r.created = input + return 7, nil +} + +// Update 接受测试更新调用。 +func (r *ruleRepositoryFake) Update(context.Context, int64, int64, RuleInput) error { return nil } + +// Delete 接受测试删除调用。 +func (r *ruleRepositoryFake) Delete(context.Context, int64, int64) error { return nil } + +// ruleOwnershipFake 保存规则归属和卡密组测试结果。 +type ruleOwnershipFake struct { + // cardType 是卡密组类型。 + cardType string + // accountErr 是账号归属查询需要返回的基础设施错误。 + accountErr error + // itemErr 是商品归属查询需要返回的基础设施错误。 + itemErr error + // cardErr 是卡密组查询需要返回的基础设施错误。 + cardErr error +} + +// OwnsAccount 返回账号归属通过。 +func (r *ruleOwnershipFake) OwnsAccount(context.Context, int64, string) (bool, error) { + if r.accountErr != nil { + return false, r.accountErr + } + return true, nil +} + +// OwnsItem 返回商品归属通过。 +func (r *ruleOwnershipFake) OwnsItem(context.Context, int64, string, string) (bool, error) { + if r.itemErr != nil { + return false, r.itemErr + } + return true, nil +} + +// GetCard 返回预设卡密组类型。 +func (r *ruleOwnershipFake) GetCard(context.Context, int64, int64) (CardInfo, error) { + if r.cardErr != nil { + return CardInfo{}, r.cardErr + } + if r.cardType == "" { + return CardInfo{Type: "data"}, nil + } + return CardInfo{Type: r.cardType}, nil +} + +// TestRuleServiceNormalizePropagatesOwnershipErrors 验证归属端口的基础设施错误不会伪装成用户输入错误。 +func TestRuleServiceNormalizePropagatesOwnershipErrors(t *testing.T) { + // backendErr 是归属查询模拟的底层数据库故障。 + backendErr := errors.New("database unavailable") + // cases 保存不同归属阶段及其预期错误。 + cases := []struct { + // name 是当前归属阶段测试名称。 + name string + // ownership 是注入指定底层故障的归属替身。 + ownership *ruleOwnershipFake + // draft 是触发当前归属查询的最小规则草稿。 + draft RuleDraft + }{ + {name: "account", ownership: &ruleOwnershipFake{accountErr: backendErr}, draft: RuleDraft{CookieID: "account-1", TriggerType: TriggerOrderPaid}}, + {name: "item", ownership: &ruleOwnershipFake{itemErr: backendErr}, draft: RuleDraft{CookieID: "account-1", ItemID: "item-1", TriggerType: TriggerOrderPaid}}, + {name: "card", ownership: &ruleOwnershipFake{cardErr: backendErr}, draft: RuleDraft{CookieID: "account-1", TriggerType: TriggerOrderPaid, Actions: []ActionDraft{{ActionType: ActionSendCard, CardID: 1}}}}, + } + // testCase 是当前归属阶段及预期底层错误的测试样例。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // service 是当前底层故障场景使用的规则应用服务。 + service := NewRuleService(&ruleRepositoryFake{}, testCase.ownership) + // _, err 保存规范化过程中透传的底层错误。 + _, err := service.Normalize(context.Background(), 42, testCase.draft) + if !errors.Is(err, backendErr) { + t.Fatalf("应透传底层错误,err=%v", err) + } + }) + } +} + +// TestRuleServiceNormalizeAppliesDefaults 验证规则输入规范化和默认值。 +func TestRuleServiceNormalizeAppliesDefaults(t *testing.T) { + // repository 保存规范化后的规则输入。 + repository := &ruleRepositoryFake{} + // service 是绑定测试端口的规则应用服务。 + service := NewRuleService(repository, &ruleOwnershipFake{}) + // enabled 保存动作的启用状态指针。 + enabled := true + // input 保存规范化后的规则输入。 + input, err := service.Normalize(context.Background(), 42, RuleDraft{ + CookieID: " account-1 ", TriggerType: TriggerOrderPaid, Actions: []ActionDraft{{ + ActionType: ActionSendCard, CardID: 9, Enabled: &enabled, + }}, + }) + if err != nil { + t.Fatal(err) + } + if input.CookieID != "account-1" || input.Priority != 100 || input.Name == "" || input.Actions[0].DeliveryCount != 1 { + t.Fatalf("规则默认值错误: %+v", input) + } +} + +// TestRuleServiceRejectsInvalidAction 验证不支持的动作和 API 卡密被拒绝。 +func TestRuleServiceRejectsInvalidAction(t *testing.T) { + // cases 保存非法规则输入和预期错误。 + cases := []struct { + // name 是测试分支名称。 + name string + // ownership 是当前分支的卡密组替身。 + ownership *ruleOwnershipFake + // draft 是待校验规则。 + draft RuleDraft + // want 是预期错误片段。 + want string + }{ + {name: "unknown action", ownership: &ruleOwnershipFake{}, draft: RuleDraft{CookieID: "a", TriggerType: TriggerBuyerReviewed, Actions: []ActionDraft{{ActionType: "unknown"}}}, want: "不支持的动作"}, + {name: "api card", ownership: &ruleOwnershipFake{cardType: "api"}, draft: RuleDraft{CookieID: "a", TriggerType: TriggerOrderPaid, Actions: []ActionDraft{{ActionType: ActionSendCard, CardID: 1}}}, want: "API 卡密"}, + } + // testCase 是当前非法规则分支及其预期错误的测试样例。 + for _, testCase /* testCase 是当前非法规则分支及其预期错误的测试样例。 */ := range cases { + t.Run(testCase.name, func(t *testing.T) { + // service 是当前非法规则分支使用的应用服务。 + service := NewRuleService(&ruleRepositoryFake{}, testCase.ownership) + // _, err 保存规则校验错误。 + _, err := service.Normalize(context.Background(), 42, testCase.draft) + if err == nil || !containsRuleError(err, testCase.want) { + t.Fatalf("错误=%v,期望包含=%q", err, testCase.want) + } + }) + } +} + +// TestRuleServiceNormalizesPageLimit 验证分页大小和偏移量被应用层归一化。 +func TestRuleServiceNormalizesPageLimit(t *testing.T) { + // repository 保存分页调用条件。 + repository := &ruleRepositoryFake{} + // service 是待验证的规则应用服务。 + service /* service 是待验证的规则应用服务。 */ := NewRuleService(repository, &ruleOwnershipFake{}) + // err 表示分页查询归一化后的仓储调用结果。 + if _, _, err := service.ListPageForUser(context.Background(), RuleFilter{UserID: 1, Limit: 0, Offset: -2}); err != nil { + t.Fatal(err) + } + if repository.listedFilter.Limit != 10 || repository.listedFilter.Offset != 0 { + t.Fatalf("分页归一化错误: %+v", repository.listedFilter) + } +} + +// containsRuleError 判断规则校验错误是否包含指定业务提示。 +func containsRuleError(err error, want string) bool { + return err != nil && want != "" && strings.Contains(err.Error(), want) +} diff --git a/internal/application/automation/service.go b/internal/application/automation/service.go new file mode 100644 index 0000000..5fe269f --- /dev/null +++ b/internal/application/automation/service.go @@ -0,0 +1,107 @@ +// Package automation 提供自动化异常运维查询与人工处理用例,不依赖 HTTP 或数据库模型。 +package automation + +import ( + "context" + "errors" + "strings" +) + +// ErrInvalidInput 表示自动化异常用例缺少有效的用户或持久化端口。 +var ErrInvalidInput = errors.New("自动化异常参数无效") + +// ErrNotFound 表示异常记录不存在、已处理或不属于当前用户。 +var ErrNotFound = errors.New("自动化异常不存在或已处理") + +// ErrInvalidDeferredResolution 表示延期任务只能执行重试或驳回处理。 +var ErrInvalidDeferredResolution = errors.New("处理方式必须是 retry 或 dismiss") + +// RunIssue 是需要人工处理的自动化运行非敏感摘要。 +type RunIssue struct { + // ID 是自动化运行的稳定标识。 + ID int64 + // CookieID 是关联账号标识,不包含 Cookie 内容。 + CookieID string + // OrderID 是关联订单标识。 + OrderID string + // TriggerType 是触发该运行的事件类型。 + TriggerType string + // ErrorMessage 是运行进入人工处理状态时记录的原因。 + ErrorMessage string + // IssueKind 是应用层根据运行事实归类的异常类型。 + IssueKind string + // AllowedResolutions 是当前异常允许的人工处理动作。 + AllowedResolutions []string + // ActionCursor 是下一步动作在计划中的位置。 + ActionCursor int + // SentCount 是已经确认成功的外部动作数量。 + SentCount int + // UpdatedAt 是运行状态最近更新的时间文本。 + UpdatedAt string +} + +// DeferredIssue 是需要人工处理的延期任务非敏感摘要。 +type DeferredIssue struct { + // ID 是延期任务的稳定标识。 + ID int64 + // CookieID 是关联账号标识,不包含 Cookie 内容。 + CookieID string + // TriggerType 是触发延期任务的事件类型。 + TriggerType string + // ErrorMessage 是任务进入死信状态时记录的原因。 + ErrorMessage string + // AttemptCount 是任务已经尝试执行的次数。 + AttemptCount int + // UpdatedAt 是任务状态最近更新的时间文本。 + UpdatedAt string +} + +// IssueRepository 定义自动化异常用例所需的最小持久化能力。 +type IssueRepository interface { + // ListIssues 按用户归属查询异常运行和死信延期任务摘要。 + ListIssues(ctx context.Context, userID int64) ([]RunIssue, []DeferredIssue, error) + // ResolveRunIssue 按用户归属执行异常运行的人工处理动作。 + ResolveRunIssue(ctx context.Context, userID, runID int64, resolution string) error + // ResolveDeferredIssue 按用户归属重试或删除死信延期任务。 + ResolveDeferredIssue(ctx context.Context, userID, taskID int64, retry bool) error +} + +// IssueService 编排自动化异常查询与人工处理,不持有 HTTP 请求或数据库连接。 +type IssueService struct { + // repository 保存调用方注入的最小自动化异常持久化端口。 + repository IssueRepository +} + +// NewIssueService 构造自动化异常应用服务;空端口会在调用时返回参数错误。 +func NewIssueService(repository IssueRepository) *IssueService { + return &IssueService{repository: repository} +} + +// ListIssues 查询当前用户有权查看的异常运行和死信延期任务摘要。 +func (s *IssueService) ListIssues(ctx context.Context, userID int64) ([]RunIssue, []DeferredIssue, error) { + if s == nil || s.repository == nil || userID <= 0 { + return nil, nil, ErrInvalidInput + } + return s.repository.ListIssues(ctx, userID) +} + +// ResolveRunIssue 处理异常运行;resolution 的允许值由持久化端口依据运行事实判定。 +func (s *IssueService) ResolveRunIssue(ctx context.Context, userID, runID int64, resolution string) error { + if s == nil || s.repository == nil || userID <= 0 || runID <= 0 { + return ErrInvalidInput + } + return s.repository.ResolveRunIssue(ctx, userID, runID, strings.TrimSpace(resolution)) +} + +// ResolveDeferredIssue 处理死信延期任务,并将 retry/dismiss 转换为端口使用的布尔语义。 +func (s *IssueService) ResolveDeferredIssue(ctx context.Context, userID, taskID int64, resolution string) error { + if s == nil || s.repository == nil || userID <= 0 || taskID <= 0 { + return ErrInvalidInput + } + // normalizedResolution 保存去除空白后的人工处理动作,避免兼容客户端的首尾空格改变语义。 + normalizedResolution := strings.TrimSpace(resolution) + if normalizedResolution != "retry" && normalizedResolution != "dismiss" { + return ErrInvalidDeferredResolution + } + return s.repository.ResolveDeferredIssue(ctx, userID, taskID, normalizedResolution == "retry") +} diff --git a/internal/application/automation/service_test.go b/internal/application/automation/service_test.go new file mode 100644 index 0000000..a10ab28 --- /dev/null +++ b/internal/application/automation/service_test.go @@ -0,0 +1,140 @@ +package automation + +import ( + "context" + "errors" + "testing" +) + +// fakeIssueRepository 保存自动化异常应用服务测试使用的端口调用记录和预设结果。 +type fakeIssueRepository struct { + // runs 是模拟返回的异常运行摘要。 + runs []RunIssue + // tasks 是模拟返回的死信延期任务摘要。 + tasks []DeferredIssue + // listErr 是模拟异常列表查询失败。 + listErr error + // runErr 是模拟异常运行处理失败。 + runErr error + // taskErr 是模拟延期任务处理失败。 + taskErr error + // listedUserID 保存最近一次列表查询的用户归属。 + listedUserID int64 + // resolvedRun 保存最近一次异常运行处理参数。 + resolvedRun struct { + // userID 是处理请求所属用户。 + userID int64 + // runID 是待处理运行标识。 + runID int64 + // resolution 是人工处理动作。 + resolution string + } + // resolvedTask 保存最近一次延期任务处理参数。 + resolvedTask struct { + // userID 是处理请求所属用户。 + userID int64 + // taskID 是待处理延期任务标识。 + taskID int64 + // retry 表示是否重新放回待执行队列。 + retry bool + } +} + +// ListIssues 返回预设异常摘要并记录用户归属。 +func (f *fakeIssueRepository) ListIssues(_ context.Context, userID int64) ([]RunIssue, []DeferredIssue, error) { + f.listedUserID = userID + return f.runs, f.tasks, f.listErr +} + +// ResolveRunIssue 返回预设错误并记录异常运行处理参数。 +func (f *fakeIssueRepository) ResolveRunIssue(_ context.Context, userID, runID int64, resolution string) error { + f.resolvedRun.userID, f.resolvedRun.runID, f.resolvedRun.resolution = userID, runID, resolution + return f.runErr +} + +// ResolveDeferredIssue 返回预设错误并记录延期任务处理参数。 +func (f *fakeIssueRepository) ResolveDeferredIssue(_ context.Context, userID, taskID int64, retry bool) error { + f.resolvedTask.userID, f.resolvedTask.taskID, f.resolvedTask.retry = userID, taskID, retry + return f.taskErr +} + +// TestServiceListIssuesDelegatesUserScope 验证异常列表查询保留用户归属并返回非敏感应用模型。 +func TestServiceListIssuesDelegatesUserScope(t *testing.T) { + // repository 是记录调用参数的自动化异常测试端口。 + repository := &fakeIssueRepository{ + runs: []RunIssue{{ID: 7, CookieID: "account-1", IssueKind: "partial_failure"}}, + tasks: []DeferredIssue{{ID: 8, CookieID: "account-1", AttemptCount: 3}}, + } + // service 是待验证的自动化异常应用服务。 + service := NewIssueService(repository) + // runs、tasks、err 保存应用服务返回的异常摘要和错误。 + runs, tasks, err := service.ListIssues(context.Background(), 42) + if err != nil || repository.listedUserID != 42 { + t.Fatalf("list result=%+v tasks=%+v user=%d err=%v", runs, tasks, repository.listedUserID, err) + } + if len(runs) != 1 || runs[0].IssueKind != "partial_failure" || len(tasks) != 1 || tasks[0].AttemptCount != 3 { + t.Fatalf("应用摘要未按预期返回: runs=%+v tasks=%+v", runs, tasks) + } +} + +// TestServiceResolveRunTrimsAndPropagates 验证异常运行处理动作会裁剪空白并保留端口错误。 +func TestServiceResolveRunTrimsAndPropagates(t *testing.T) { + // expectedErr 是模拟持久化处理失败的错误哨兵。 + expectedErr := errors.New("resolve failed") + // repository 是记录异常运行处理参数的测试端口。 + repository := &fakeIssueRepository{runErr: expectedErr} + // service 是待验证的自动化异常应用服务。 + service := NewIssueService(repository) + // err 保存应用服务返回的处理错误。 + err := service.ResolveRunIssue(context.Background(), 42, 7, " cancel ") + if !errors.Is(err, expectedErr) || repository.resolvedRun.resolution != "cancel" || repository.resolvedRun.userID != 42 || repository.resolvedRun.runID != 7 { + t.Fatalf("resolve run params=%+v err=%v", repository.resolvedRun, err) + } +} + +// TestServiceResolveDeferredValidatesAndMapsResolution 验证延期任务只接受 retry/dismiss 并正确转换重试语义。 +func TestServiceResolveDeferredValidatesAndMapsResolution(t *testing.T) { + // repository 是记录延期任务处理参数的测试端口。 + repository := &fakeIssueRepository{} + // service 是待验证的自动化异常应用服务。 + service := NewIssueService(repository) + if // err 保存重试处理结果。 + err := service.ResolveDeferredIssue(context.Background(), 42, 8, " retry "); err != nil || !repository.resolvedTask.retry { + t.Fatalf("retry resolution params=%+v err=%v", repository.resolvedTask, err) + } + if // err 保存驳回处理结果。 + err := service.ResolveDeferredIssue(context.Background(), 42, 8, "dismiss"); err != nil || repository.resolvedTask.retry { + t.Fatalf("dismiss resolution params=%+v err=%v", repository.resolvedTask, err) + } + // invalidErr 保存不支持处理动作的应用层校验错误。 + invalidErr := service.ResolveDeferredIssue(context.Background(), 42, 8, "continue") + if !errors.Is(invalidErr, ErrInvalidDeferredResolution) { + t.Fatalf("invalid resolution err=%v", invalidErr) + } +} + +// TestServiceRejectsInvalidScope 验证无效用户或资源标识不会触发持久化端口。 +func TestServiceRejectsInvalidScope(t *testing.T) { + // repository 是记录调用次数的自动化异常测试端口。 + repository := &fakeIssueRepository{} + // service 是待验证的自动化异常应用服务。 + service := NewIssueService(repository) + // listErr 保存无效用户列表查询返回的参数错误。 + _, _, listErr := service.ListIssues(context.Background(), 0) + if !errors.Is(listErr, ErrInvalidInput) { + t.Fatalf("invalid list scope err=%v", listErr) + } + // runErr 保存无效运行标识返回的参数错误。 + runErr := service.ResolveRunIssue(context.Background(), 1, 0, "cancel") + if !errors.Is(runErr, ErrInvalidInput) { + t.Fatalf("invalid run scope err=%v", runErr) + } + // taskErr 保存无效延迟任务标识返回的参数错误。 + taskErr := service.ResolveDeferredIssue(context.Background(), 1, 0, "retry") + if !errors.Is(taskErr, ErrInvalidInput) { + t.Fatalf("invalid task scope err=%v", taskErr) + } + if repository.listedUserID != 0 || repository.resolvedRun.runID != 0 || repository.resolvedTask.taskID != 0 { + t.Fatal("无效标识不应调用持久化端口") + } +} diff --git a/internal/application/cards/service.go b/internal/application/cards/service.go new file mode 100644 index 0000000..9b5c7fa --- /dev/null +++ b/internal/application/cards/service.go @@ -0,0 +1,300 @@ +// Package cards 定义卡券 CRUD 用例、业务模型和消费者侧持久化 Port。 +// 本包不依赖 HTTP、数据库模型或其他基础设施实现。 +package cards + +import ( + "context" + "errors" + "strings" +) + +// ErrInvalidUser 表示调用方未提供有效的用户身份。 +var ErrInvalidUser = errors.New("卡券用户身份无效") + +// ErrInvalidCardID 表示调用方未提供有效的卡券组标识。 +var ErrInvalidCardID = errors.New("卡券ID无效") + +// ErrNotFound 表示卡券组不存在。 +var ErrNotFound = errors.New("卡券不存在") + +// ErrForbidden 表示卡券组存在但不属于当前用户。 +var ErrForbidden = errors.New("无权操作该卡密组") + +// ErrUnsupportedAPIType 表示当前自动发货链路不允许新建或转换为 API 卡券。 +var ErrUnsupportedAPIType = errors.New("API 卡密暂不支持自动发货") + +// ErrNotDataType 表示只有 data 类型卡券组允许追加逐行卡密。 +var ErrNotDataType = errors.New("只有 data(批量卡密)类型支持追加卡密") + +// ValidationError 表示卡券输入不满足稳定的业务约束。 +type ValidationError struct { + // Message 是可由 HTTP 边界直接展示的稳定校验提示,不包含基础设施细节。 + Message string +} + +// Error 返回卡券业务校验提示。 +func (e *ValidationError) Error() string { + if e == nil { + return "卡券输入校验失败" + } + return e.Message +} + +// Card 是应用层使用的完整卡券组模型,与数据库行和 HTTP DTO 解耦。 +type Card struct { + // ID 是卡券组的持久化标识。 + ID int64 + // Name 是用户可见的卡券组名称。 + Name string + // Type 是 text、data、image 或历史兼容的 api 类型。 + Type string + // APIConfig 是历史 API 卡券配置;当前仅允许读取或更新既有 API 卡券。 + APIConfig string + // TextContent 是 text 类型自动发货时发送的文本内容。 + TextContent string + // DataContent 是 data 类型尚未消费的逐行卡密库存。 + DataContent string + // ImageURL 是 image 类型自动发货时发送的图片地址。 + ImageURL string + // Description 是用户维护的卡券组说明。 + Description string + // Enabled 表示自动化规则是否可以使用该卡券组。 + Enabled bool + // DelaySeconds 是自动发货前的延迟秒数,范围为 0 到 3600。 + DelaySeconds int + // IsMultiSpec 表示卡券组是否只匹配指定商品规格。 + IsMultiSpec bool + // SpecName 是多规格匹配使用的规格名称。 + SpecName string + // SpecValue 是多规格匹配使用的规格值。 + SpecValue string + // UserID 是拥有该卡券组的本地用户标识。 + UserID int64 +} + +// Draft 是创建或更新卡券组时允许提交的业务字段。 +type Draft struct { + // Name 是用户可见的卡券组名称。 + Name string + // Type 是 text、data、image 或历史兼容的 api 类型。 + Type string + // APIConfig 是历史 API 卡券配置;新建 API 卡券仍被业务规则禁止。 + APIConfig string + // TextContent 是 text 类型必须提供的非空发货内容。 + TextContent string + // DataContent 是 data 类型必须提供的非空逐行库存。 + DataContent string + // ImageURL 是 image 类型必须提供的非空图片地址。 + ImageURL string + // Description 是用户维护的卡券组说明。 + Description string + // Enabled 表示保存后是否允许自动化规则使用该卡券组。 + Enabled bool + // DelaySeconds 是自动发货前的延迟秒数,范围为 0 到 3600。 + DelaySeconds int + // IsMultiSpec 表示卡券组是否只匹配指定商品规格。 + IsMultiSpec bool + // SpecName 是多规格匹配使用的规格名称。 + SpecName string + // SpecValue 是多规格匹配使用的规格值。 + SpecValue string +} + +// Repository 定义卡券 CRUD 用例所需的最小持久化能力。 +type Repository interface { + // ListForUser 按稳定顺序返回指定用户拥有的全部卡券组。 + ListForUser(ctx context.Context, userID int64) ([]Card, error) + // Get 按标识读取卡券组;资源缺失时返回 ErrNotFound。 + Get(ctx context.Context, cardID int64) (Card, error) + // Create 持久化已校验且带所有者的卡券组,并返回新标识。 + Create(ctx context.Context, card Card) (int64, error) + // Update 覆盖指定卡券组的可编辑字段,但不得改变所有者。 + Update(ctx context.Context, card Card) error + // Delete 删除指定卡券组及数据库约束允许级联清理的关联数据。 + Delete(ctx context.Context, cardID int64) error + // AppendData 向 data 类型卡券组追加逐行卡密,并返回新增行数。 + AppendData(ctx context.Context, cardID int64, content string) (int, error) +} + +// Service 编排卡券输入校验、用户归属和 CRUD 持久化。 +type Service struct { + // repository 保存卡券用例依赖的窄持久化 Port。 + repository Repository +} + +// NewService 创建卡券应用服务;空仓储会在调用时返回明确装配错误。 +func NewService(repository Repository) *Service { + return &Service{repository: repository} +} + +// List 查询 userID 拥有的全部卡券组;仓储错误原样返回。 +func (s *Service) List(ctx context.Context, userID int64) ([]Card, error) { + // err 表示用户身份或应用仓储未满足执行条件的错误。 + if err := s.validateUser(userID); err != nil { + return nil, err + } + return s.repository.ListForUser(ctx, userID) +} + +// Get 查询 cardID 并校验其属于 userID;不存在、越权和仓储故障使用不同错误语义。 +func (s *Service) Get(ctx context.Context, userID, cardID int64) (Card, error) { + // err 表示用户身份或应用仓储未满足执行条件的错误。 + if err := s.validateUser(userID); err != nil { + return Card{}, err + } + return s.ownedCard(ctx, userID, cardID) +} + +// ExistsOwned 判断卡券组是否属于指定用户;基础设施错误与越权错误仍返回给调用方区分处理。 +func (s *Service) ExistsOwned(ctx context.Context, userID, cardID int64) (bool, error) { + // err 表示用户身份、卡券标识或归属查询错误。 + if err := s.validateUser(userID); err != nil { + return false, err + } + if cardID <= 0 { + return false, ErrInvalidCardID + } + // _, err 丢弃非敏感卡券详情,只保留归属判断结果。 + if _, err := s.ownedCard(ctx, userID, cardID); err != nil { + return false, err + } + return true, nil +} + +// Create 校验 draft 并以 userID 为所有者创建卡券组,返回新标识。 +func (s *Service) Create(ctx context.Context, userID int64, draft Draft) (int64, error) { + // err 表示用户身份或应用仓储未满足执行条件的错误。 + if err := s.validateUser(userID); err != nil { + return 0, err + } + // err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。 + if err := validateDraft(draft); err != nil { + return 0, err + } + if draft.Type == "api" { + return 0, ErrUnsupportedAPIType + } + return s.repository.Create(ctx, cardFromDraft(0, userID, draft)) +} + +// Update 校验 draft 和所有权后更新 cardID;既有 API 卡券可继续编辑,但其他类型不能转换为 API。 +func (s *Service) Update(ctx context.Context, userID, cardID int64, draft Draft) error { + // err 表示用户身份或应用仓储未满足执行条件的错误。 + if err := s.validateUser(userID); err != nil { + return err + } + // err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。 + if err := validateDraft(draft); err != nil { + return err + } + // existing 是已经通过当前用户归属校验的卡券组。 + existing, err := s.ownedCard(ctx, userID, cardID) + if err != nil { + return err + } + if draft.Type == "api" && existing.Type != "api" { + return ErrUnsupportedAPIType + } + return s.repository.Update(ctx, cardFromDraft(existing.ID, existing.UserID, draft)) +} + +// Delete 校验 cardID 归属后删除卡券组;删除仓储错误原样返回。 +func (s *Service) Delete(ctx context.Context, userID, cardID int64) error { + // err 表示用户身份或应用仓储未满足执行条件的错误。 + if err := s.validateUser(userID); err != nil { + return err + } + // err 表示卡券不存在、越权或读取卡券时的基础设施错误。 + if _, err := s.ownedCard(ctx, userID, cardID); err != nil { + return err + } + return s.repository.Delete(ctx, cardID) +} + +// AppendData 校验卡券归属和类型后追加逐行库存,拒绝空内容和越权操作。 +func (s *Service) AppendData(ctx context.Context, userID, cardID int64, content string) (int, error) { + // err 表示用户身份或应用仓储未满足执行条件的错误。 + if err := s.validateUser(userID); err != nil { + return 0, err + } + content = strings.TrimSpace(content) + if content == "" { + return 0, &ValidationError{Message: "内容为空"} + } + // card、err 保存已通过当前用户归属校验的卡券组及读取错误。 + card, err := s.ownedCard(ctx, userID, cardID) + if err != nil { + return 0, err + } + if card.Type != "data" { + return 0, ErrNotDataType + } + return s.repository.AppendData(ctx, cardID, content) +} + +// validateUser 检查应用服务及用户身份是否具备执行卡券用例的条件。 +func (s *Service) validateUser(userID int64) error { + if s == nil || s.repository == nil { + return errors.New("卡券 repository 未初始化") + } + if userID <= 0 { + return ErrInvalidUser + } + return nil +} + +// ownedCard 读取 cardID 并验证 userID 所有权,不将数据库故障降级为资源缺失。 +func (s *Service) ownedCard(ctx context.Context, userID, cardID int64) (Card, error) { + if cardID <= 0 { + return Card{}, ErrInvalidCardID + } + // card 是持久化层返回的完整卡券组。 + card, err := s.repository.Get(ctx, cardID) + if err != nil { + return Card{}, err + } + if card.UserID != userID { + return Card{}, ErrForbidden + } + return card, nil +} + +// validateDraft 校验类型、必填内容和延迟范围,保持创建与更新使用同一套规则。 +func validateDraft(draft Draft) error { + if draft.Name == "" || draft.Type == "" { + return &ValidationError{Message: "名称和类型不能为空"} + } + switch draft.Type { + case "text", "data", "image", "api": + default: + return &ValidationError{Message: "类型必须为 text、data、image 或 api"} + } + if draft.DelaySeconds < 0 || draft.DelaySeconds > 3600 { + return &ValidationError{Message: "延时发货必须在 0 到 3600 秒之间"} + } + switch draft.Type { + case "text": + if strings.TrimSpace(draft.TextContent) == "" { + return &ValidationError{Message: "文本卡密内容不能为空"} + } + case "data": + if strings.TrimSpace(draft.DataContent) == "" { + return &ValidationError{Message: "数据卡密内容不能为空"} + } + case "image": + if strings.TrimSpace(draft.ImageURL) == "" { + return &ValidationError{Message: "图片卡密 URL 不能为空"} + } + } + return nil +} + +// cardFromDraft 把已校验输入与不可由请求覆盖的标识、所有者组合为持久化模型。 +func cardFromDraft(cardID, userID int64, draft Draft) Card { + return Card{ + ID: cardID, Name: draft.Name, Type: draft.Type, APIConfig: draft.APIConfig, + TextContent: draft.TextContent, DataContent: draft.DataContent, ImageURL: draft.ImageURL, + Description: draft.Description, Enabled: draft.Enabled, DelaySeconds: draft.DelaySeconds, + IsMultiSpec: draft.IsMultiSpec, SpecName: draft.SpecName, SpecValue: draft.SpecValue, UserID: userID, + } +} diff --git a/internal/application/cards/service_test.go b/internal/application/cards/service_test.go new file mode 100644 index 0000000..7527673 --- /dev/null +++ b/internal/application/cards/service_test.go @@ -0,0 +1,301 @@ +package cards + +import ( + "context" + "errors" + "reflect" + "testing" +) + +// cardRepositoryStub 记录应用服务对卡券持久化 Port 的调用,并允许测试注入各阶段结果。 +type cardRepositoryStub struct { + // cards 是列表查询返回的卡券组。 + cards []Card + // card 是单卡查询返回的卡券组。 + card Card + // listErr、getErr、createErr、updateErr、deleteErr 和 appendErr 分别控制各持久化阶段的失败结果。 + listErr, getErr, createErr, updateErr, deleteErr, appendErr error + // createdID 是创建成功时返回的稳定标识。 + createdID int64 + // listedUserID 是列表查询收到的用户标识。 + listedUserID int64 + // gotCardID 是单卡查询收到的卡券标识。 + gotCardID int64 + // createdCard 和 updatedCard 是创建、更新阶段收到的应用模型。 + createdCard, updatedCard Card + // deletedCardID 是删除阶段收到的卡券标识。 + deletedCardID int64 + // appendedCardID 和 appendedContent 是追加库存阶段收到的标识与内容。 + appendedCardID int64 + appendedContent string + // appendedCount 是追加成功时返回的有效库存行数。 + appendedCount int +} + +// ListForUser 返回预设列表并记录用户隔离条件。 +func (r *cardRepositoryStub) ListForUser(_ context.Context, userID int64) ([]Card, error) { + r.listedUserID = userID + return r.cards, r.listErr +} + +// Get 返回预设卡券并记录查询标识。 +func (r *cardRepositoryStub) Get(_ context.Context, cardID int64) (Card, error) { + r.gotCardID = cardID + return r.card, r.getErr +} + +// Create 记录待创建卡券并返回预设标识或错误。 +func (r *cardRepositoryStub) Create(_ context.Context, card Card) (int64, error) { + r.createdCard = card + return r.createdID, r.createErr +} + +// Update 记录待更新卡券并返回预设错误。 +func (r *cardRepositoryStub) Update(_ context.Context, card Card) error { + r.updatedCard = card + return r.updateErr +} + +// Delete 记录待删除卡券标识并返回预设错误。 +func (r *cardRepositoryStub) Delete(_ context.Context, cardID int64) error { + r.deletedCardID = cardID + return r.deleteErr +} + +// AppendData 记录追加库存请求,并返回预设行数或错误。 +func (r *cardRepositoryStub) AppendData(_ context.Context, cardID int64, content string) (int, error) { + r.appendedCardID = cardID + r.appendedContent = content + return r.appendedCount, r.appendErr +} + +// TestServiceListAndGet 验证列表隔离、详情归属和查询错误边界。 +func TestServiceListAndGet(t *testing.T) { + // repository 是本测试共享的可观测持久化替身。 + repository := &cardRepositoryStub{cards: []Card{{ID: 3, UserID: 7}}, card: Card{ID: 3, UserID: 7}} + // service 是绑定替身仓储的卡券应用服务。 + service := NewService(repository) + // ctx 是本测试使用的非取消上下文。 + ctx := context.Background() + // cards、listErr 保存列表用例结果。 + cards, listErr := service.List(ctx, 7) + if listErr != nil || repository.listedUserID != 7 || !reflect.DeepEqual(cards, repository.cards) { + t.Fatalf("列表结果异常 cards=%+v user=%d err=%v", cards, repository.listedUserID, listErr) + } + // card、getErr 保存详情用例结果。 + card, getErr := service.Get(ctx, 7, 3) + if getErr != nil || card.ID != 3 || repository.gotCardID != 3 { + t.Fatalf("详情结果异常 card=%+v queried=%d err=%v", card, repository.gotCardID, getErr) + } + // infraErr 是用于验证数据库故障不会伪装成资源缺失的错误。 + infraErr := errors.New("database unavailable") + repository.getErr = infraErr + // err 表示详情查询透传的基础设施错误。 + if _, err := service.Get(ctx, 7, 3); !errors.Is(err, infraErr) { + t.Fatalf("基础设施错误应原样返回,err=%v", err) + } + repository.getErr = nil + repository.card.UserID = 8 + // err 表示跨用户详情查询返回的所有权错误。 + if _, err := service.Get(ctx, 7, 3); !errors.Is(err, ErrForbidden) { + t.Fatalf("跨用户详情应拒绝,err=%v", err) + } +} + +// TestServiceCreateValidation 验证创建输入规则、API 类型限制和所有者写入。 +func TestServiceCreateValidation(t *testing.T) { + // repository 是记录创建输入的持久化替身。 + repository := &cardRepositoryStub{createdID: 19} + // service 是待验证的卡券应用服务。 + service := NewService(repository) + // valid 是覆盖全部可编辑字段的合法文本卡券输入。 + valid := Draft{Name: "文本卡", Type: "text", TextContent: "CODE", Description: "说明", Enabled: true, DelaySeconds: 9, IsMultiSpec: true, SpecName: "颜色", SpecValue: "蓝"} + // createdID、createErr 保存创建结果。 + createdID, createErr := service.Create(context.Background(), 7, valid) + if createErr != nil || createdID != 19 { + t.Fatalf("创建结果异常 id=%d err=%v", createdID, createErr) + } + if repository.createdCard.UserID != 7 || repository.createdCard.Name != valid.Name || repository.createdCard.ID != 0 { + t.Fatalf("创建模型未正确绑定所有者:%+v", repository.createdCard) + } + // testCase 是当前待验证的非法输入及期望错误。 + for _, testCase := range []struct { + // name 是失败场景名称。 + name string + // draft 是当前场景提交的卡券输入。 + draft Draft + // want 是期望出现的稳定错误文本。 + want string + }{ + {name: "missing-name", draft: Draft{Type: "text", TextContent: "x"}, want: "名称和类型不能为空"}, + {name: "invalid-type", draft: Draft{Name: "x", Type: "unknown"}, want: "类型必须为 text、data、image 或 api"}, + {name: "invalid-delay", draft: Draft{Name: "x", Type: "text", TextContent: "x", DelaySeconds: 3601}, want: "延时发货必须在 0 到 3600 秒之间"}, + {name: "empty-text", draft: Draft{Name: "x", Type: "text", TextContent: " "}, want: "文本卡密内容不能为空"}, + {name: "empty-data", draft: Draft{Name: "x", Type: "data", DataContent: "\n"}, want: "数据卡密内容不能为空"}, + {name: "empty-image", draft: Draft{Name: "x", Type: "image", ImageURL: ""}, want: "图片卡密 URL 不能为空"}, + } { + t.Run(testCase.name, func(t *testing.T) { + // err 是当前非法输入返回的业务校验结果。 + _, err := service.Create(context.Background(), 7, testCase.draft) + // validationError 用于确认错误保留业务校验类型。 + var validationError *ValidationError + if !errors.As(err, &validationError) || err.Error() != testCase.want { + t.Fatalf("校验错误不匹配 err=%v want=%q", err, testCase.want) + } + }) + } + // err 表示创建 API 卡券时的业务限制错误。 + if _, err := service.Create(context.Background(), 7, Draft{Name: "API", Type: "api"}); !errors.Is(err, ErrUnsupportedAPIType) { + t.Fatalf("新建 API 卡券应拒绝,err=%v", err) + } +} + +// TestServiceUpdateAndDeleteOwnership 验证更新、删除不会接受请求覆盖所有者,并覆盖 API 转换限制与错误阶段。 +func TestServiceUpdateAndDeleteOwnership(t *testing.T) { + // updateErr 是更新持久化失败的预设错误。 + updateErr := errors.New("update failed") + // repository 是当前测试的持久化替身,卡券归属于用户 7。 + repository := &cardRepositoryStub{card: Card{ID: 5, UserID: 7, Type: "text"}, updateErr: updateErr} + // service 是待验证的卡券应用服务。 + service := NewService(repository) + // draft 是合法的文本卡券更新输入。 + draft := Draft{Name: "new", Type: "text", TextContent: "value", Enabled: true} + // err 表示更新卡券组时透传的持久化错误。 + if err := service.Update(context.Background(), 7, 5, draft); !errors.Is(err, updateErr) { + t.Fatalf("更新错误应原样返回,err=%v", err) + } + if repository.updatedCard.ID != 5 || repository.updatedCard.UserID != 7 || repository.updatedCard.Name != "new" { + t.Fatalf("更新模型未保留标识和所有者:%+v", repository.updatedCard) + } + // err 表示非 API 卡券转换为 API 类型时的业务错误。 + if err := service.Update(context.Background(), 7, 5, Draft{Name: "api", Type: "api"}); !errors.Is(err, ErrUnsupportedAPIType) { + t.Fatalf("非 API 卡券转换为 API 应拒绝,err=%v", err) + } + repository.updateErr = nil + repository.card.Type = "api" + // err 表示既有 API 卡券继续编辑时的更新结果。 + if err := service.Update(context.Background(), 7, 5, Draft{Name: "legacy", Type: "api"}); err != nil { + t.Fatalf("既有 API 卡券应允许继续编辑,err=%v", err) + } + repository.card.UserID = 8 + // err 表示跨用户删除卡券时的所有权错误。 + if err := service.Delete(context.Background(), 7, 5); !errors.Is(err, ErrForbidden) || repository.deletedCardID != 0 { + t.Fatalf("跨用户删除应在持久化前拒绝,deleted=%d err=%v", repository.deletedCardID, err) + } + repository.card.UserID = 7 + // deleteErr 是删除阶段持久化失败的预设错误。 + deleteErr := errors.New("delete failed") + repository.deleteErr = deleteErr + // err 表示删除卡券组时透传的持久化错误。 + if err := service.Delete(context.Background(), 7, 5); !errors.Is(err, deleteErr) || repository.deletedCardID != 5 { + t.Fatalf("删除错误或标识不匹配,deleted=%d err=%v", repository.deletedCardID, err) + } +} + +// TestServiceRejectsInvalidDependenciesAndIdentifiers 验证空仓储、无效用户和无效卡券标识均在持久化前失败。 +func TestServiceRejectsInvalidDependenciesAndIdentifiers(t *testing.T) { + // err 表示空仓储依赖导致的应用服务装配错误。 + if _, err := NewService(nil).List(context.Background(), 1); err == nil { + t.Fatal("空仓储应返回装配错误") + } + // repository 是用于确认非法参数不会产生有效查询的持久化替身。 + repository := &cardRepositoryStub{} + // service 是绑定替身仓储的卡券应用服务。 + service := NewService(repository) + // err 表示无效用户身份导致的业务参数错误。 + if _, err := service.Get(context.Background(), 0, 1); !errors.Is(err, ErrInvalidUser) { + t.Fatalf("无效用户应拒绝,err=%v", err) + } + // err 表示无效卡券标识导致的业务参数错误。 + if _, err := service.Get(context.Background(), 1, 0); !errors.Is(err, ErrInvalidCardID) { + t.Fatalf("无效卡券标识应拒绝,err=%v", err) + } +} + +// TestServiceExistsOwned 验证批量发布使用的卡券归属查询在成功、越权、缺失和基础设施故障时保持可区分错误。 +func TestServiceExistsOwned(t *testing.T) { + // repository 是返回指定卡券详情的持久化替身。 + repository := &cardRepositoryStub{card: Card{ID: 8, UserID: 7}} + // service 是绑定归属查询替身仓储的卡券应用服务。 + service := NewService(repository) + // exists、err 保存当前用户成功查询卡券归属的结果。 + exists, err := service.ExistsOwned(context.Background(), 7, 8) + if err != nil || !exists { + t.Fatalf("归属查询应成功,exists=%t err=%v", exists, err) + } + // repository.card 切换为其他用户,验证越权不会被误报为存在。 + repository.card.UserID = 9 + // exists、err 保存越权查询的结果。 + exists, err = service.ExistsOwned(context.Background(), 7, 8) + if exists || !errors.Is(err, ErrForbidden) { + t.Fatalf("越权卡券应拒绝,exists=%t err=%v", exists, err) + } + // repository.card 恢复当前用户,随后注入资源缺失错误。 + repository.card.UserID = 7 + repository.getErr = ErrNotFound + // exists、err 保存资源缺失查询的结果。 + exists, err = service.ExistsOwned(context.Background(), 7, 8) + if exists || !errors.Is(err, ErrNotFound) { + t.Fatalf("缺失卡券应返回未找到,exists=%t err=%v", exists, err) + } + // infraErr 是用于验证数据库故障不会被归一化为资源缺失的错误。 + infraErr := errors.New("card ownership unavailable") + repository.getErr = infraErr + // exists、err 保存基础设施故障查询的结果。 + exists, err = service.ExistsOwned(context.Background(), 7, 8) + if exists || !errors.Is(err, infraErr) { + t.Fatalf("基础设施错误应原样返回,exists=%t err=%v", exists, err) + } +} + +// TestServiceAppendData 验证追加库存的输入、归属、类型和持久化错误边界。 +func TestServiceAppendData(t *testing.T) { + // repository 是记录追加请求并提供卡券归属的持久化替身。 + repository := &cardRepositoryStub{ + card: Card{ID: 8, UserID: 7, Type: "data"}, + appendedCount: 2, + } + // service 是绑定追加库存替身仓储的应用服务。 + service := NewService(repository) + // added、addErr 保存成功追加的有效行数和错误。 + added, addErr := service.AppendData(context.Background(), 7, 8, " A\nB ") + if addErr != nil || added != 2 || repository.appendedCardID != 8 || repository.appendedContent != "A\nB" { + t.Fatalf("追加结果异常 added=%d err=%v id=%d content=%q", added, addErr, repository.appendedCardID, repository.appendedContent) + } + // err 表示空内容在查询卡券前返回的稳定校验错误。 + if _, err := service.AppendData(context.Background(), 7, 8, " \n "); !errors.As(err, new(*ValidationError)) { + t.Fatalf("空内容应返回校验错误,err=%v", err) + } + // repository.card.UserID 切换为其他用户,验证所有权边界不会调用追加仓储。 + repository.card.UserID = 9 + repository.appendedCardID = 0 + // err 表示跨用户库存追加被所有权检查拒绝的业务错误。 + if _, err := service.AppendData(context.Background(), 7, 8, "C"); !errors.Is(err, ErrForbidden) || repository.appendedCardID != 0 { + t.Fatalf("跨用户追加应拒绝且不写入,id=%d err=%v", repository.appendedCardID, err) + } + // repository.card 恢复为当前用户但标记为非 data 类型,验证类型约束。 + repository.card.UserID = 7 + repository.card.Type = "text" + // err 表示非 data 卡券无法追加逐行库存的类型错误。 + if _, err := service.AppendData(context.Background(), 7, 8, "C"); !errors.Is(err, ErrNotDataType) { + t.Fatalf("非 data 类型应拒绝,err=%v", err) + } + // getErr 是资源读取阶段返回的缺失错误,追加不得触发写入。 + repository.card.Type = "data" + repository.getErr = ErrNotFound + repository.appendedCardID = 0 + // err 表示资源读取阶段发现卡券不存在时返回的稳定错误。 + if _, err := service.AppendData(context.Background(), 7, 8, "C"); !errors.Is(err, ErrNotFound) || repository.appendedCardID != 0 { + t.Fatalf("不存在卡券应返回未找到且不写入,id=%d err=%v", repository.appendedCardID, err) + } + repository.getErr = nil + // infraErr 是追加阶段的基础设施故障,服务应原样透传。 + infraErr := errors.New("append unavailable") + repository.appendErr = infraErr + // err 表示库存持久化端口返回的基础设施错误。 + if _, err := service.AppendData(context.Background(), 7, 8, "C"); !errors.Is(err, infraErr) { + t.Fatalf("追加基础设施错误应透传,err=%v", err) + } +} + +var _ Repository = (*cardRepositoryStub)(nil) diff --git a/internal/application/chat/send.go b/internal/application/chat/send.go index aa73db9..564e2a2 100644 --- a/internal/application/chat/send.go +++ b/internal/application/chat/send.go @@ -77,13 +77,18 @@ type ImageUploader interface { } // NewWithSending 创建同时支持历史查询和实时发送的聊天应用服务。 -func NewWithSending(repository Repository, outgoing OutgoingRepository, senders SenderProvider, uploader ImageUploader) *Service { - return &Service{ +func NewWithSending(repository Repository, outgoing OutgoingRepository, senders SenderProvider, uploader ImageUploader, identity ...IdentityResolver) *Service { + // service 保存聊天历史、发送和平台身份能力的统一应用服务。 + service := &Service{ repository: repository, outgoing: outgoing, senders: senders, uploader: uploader, } + if len(identity) > 0 { + service.identityResolver = identity[0] + } + return service } // SendText 创建并发送一条文字消息,失败时尽力保留本地 failed 状态。 diff --git a/internal/application/chat/service.go b/internal/application/chat/service.go index 46215aa..a26d201 100644 --- a/internal/application/chat/service.go +++ b/internal/application/chat/service.go @@ -5,11 +5,16 @@ import ( "context" "errors" "strings" + "sync" + "time" ) // ErrInvalidInput 表示聊天历史查询缺少必要的非敏感标识。 var ErrInvalidInput = errors.New("聊天历史查询参数无效") +// ErrSessionUnavailable 表示会话清理、归属或身份持久化端口未装配。 +var ErrSessionUnavailable = errors.New("聊天会话服务未启用") + // Message 是聊天历史用例对外暴露的非敏感消息模型。 type Message struct { // ID 是本地消息主键。 @@ -60,6 +65,21 @@ type Session struct { UnreadCount int } +// Identity 是平台身份查询返回的非敏感展示信息。 +type Identity struct { + // BuyerName 是平台返回的买家展示名称。 + BuyerName string + // BuyerAvatar 是平台返回的买家头像地址。 + BuyerAvatar string +} + +// IdentityResolver 定义聊天应用获取平台会话展示身份的最小能力。 +// 凭证读取、平台请求和凭证刷新均由适配器内部完成,应用层只接收展示字段。 +type IdentityResolver interface { + // Resolve 根据账号和聊天会话查询非敏感的买家展示身份。 + Resolve(ctx context.Context, accountID, chatID string) (Identity, error) +} + // Page 是聊天历史查询的分页结果。 type Page struct { // Messages 是按时间正序排列的当前页消息。 @@ -78,6 +98,20 @@ type Repository interface { ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]Session, error) } +// SessionRepository 定义会话列表之外的清理、身份写入和账号归属能力。 +type SessionRepository interface { + // Repository 提供聊天消息和会话列表查询能力。 + Repository + // DeleteEmptySessions 删除指定账号中没有有效消息的空会话壳。 + DeleteEmptySessions(ctx context.Context, accountID string) error + // UpdateSessionIdentity 更新会话的买家展示名称和头像。 + UpdateSessionIdentity(ctx context.Context, accountID, chatID, buyerID, buyerName, buyerAvatar string) error + // ExistsOwned 判断账号是否归属于指定用户,只返回存在性,不返回敏感字段。 + ExistsOwned(ctx context.Context, userID int64, accountID string) (bool, error) + // MarkRead 将指定用户拥有的会话未读数归零。 + MarkRead(ctx context.Context, userID int64, accountID, chatID string) error +} + // Service 编排聊天历史查询,不持有 HTTP 请求或数据库连接。 type Service struct { // repository 保存由调用方注入的最小持久化端口。 @@ -88,6 +122,8 @@ type Service struct { senders SenderProvider // uploader 保存图片上传的平台适配端口。 uploader ImageUploader + // identityResolver 保存平台身份查询端口,凭证只在适配器内部短暂存在。 + identityResolver IdentityResolver } // New 创建聊天历史应用服务;空端口会导致构造结果不可用。 @@ -95,6 +131,11 @@ func New(repository Repository) *Service { return &Service{repository: repository} } +// NewWithIdentity 创建支持平台会话身份补全的聊天应用服务。 +func NewWithIdentity(repository Repository, resolver IdentityResolver) *Service { + return &Service{repository: repository, identityResolver: resolver} +} + // ListStoredMessages 查询当前用户有权访问的本地聊天历史。 // userID 用于归属过滤,accountID/chatID 定位账号和会话,beforeID 控制向更早消息翻页,limit 控制页大小; // 返回的 Page 只含非敏感消息和会话摘要,底层端口错误原样返回。 @@ -123,3 +164,176 @@ func (s *Service) ListStoredMessages(ctx context.Context, userID int64, accountI } return Page{Messages: messages, Session: session, HasMore: len(messages) == limit}, nil } + +// ListSessions 查询当前用户有权访问的账号会话摘要。 +func (s *Service) ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]Session, error) { + accountID = strings.TrimSpace(accountID) + if s == nil || s.repository == nil || userID <= 0 || accountID == "" { + return nil, ErrInvalidInput + } + // sessions 和 err 保存带用户归属的会话摘要及查询错误。 + sessions, err := s.repository.ListSessions(ctx, userID, accountID, limit) + if err != nil { + return nil, err + } + return sessions, nil +} + +// FindSession 查询指定账号下的单个会话;找不到时返回零值且不视为错误。 +func (s *Service) FindSession(ctx context.Context, userID int64, accountID, chatID string) (Session, error) { + chatID = strings.TrimSpace(chatID) + if chatID == "" { + return Session{}, ErrInvalidInput + } + // sessions 和 err 保存会话摘要列表及查询错误。 + sessions, err := s.ListSessions(ctx, userID, accountID, 500) + if err != nil { + return Session{}, err + } + // session 保存匹配到的会话摘要。 + var session Session + // candidate 表示当前遍历到的会话摘要。 + for _, candidate := range sessions { + if candidate.ChatID == chatID { + session = candidate + break + } + } + return session, nil +} + +// CleanupEmptySessions 清理平台分页产生的无效空会话壳。 +func (s *Service) CleanupEmptySessions(ctx context.Context, accountID string) error { + accountID = strings.TrimSpace(accountID) + if s == nil || s.repository == nil || accountID == "" { + return ErrInvalidInput + } + // repository 保存支持会话维护操作的窄端口。 + repository, ok := s.repository.(SessionRepository) + if !ok { + return ErrSessionUnavailable + } + return repository.DeleteEmptySessions(ctx, accountID) +} + +// OwnsAccount 查询当前用户是否拥有指定账号,不读取或解密账号凭证。 +func (s *Service) OwnsAccount(ctx context.Context, userID int64, accountID string) (bool, error) { + accountID = strings.TrimSpace(accountID) + if s == nil || s.repository == nil || userID <= 0 || accountID == "" { + return false, ErrInvalidInput + } + // repository 保存支持账号归属查询的窄端口。 + repository, ok := s.repository.(SessionRepository) + if !ok { + return false, ErrSessionUnavailable + } + return repository.ExistsOwned(ctx, userID, accountID) +} + +// MarkRead 将当前用户拥有的指定会话标记为已读;底层端口只接收非敏感标识。 +func (s *Service) MarkRead(ctx context.Context, userID int64, accountID, chatID string) error { + accountID = strings.TrimSpace(accountID) + chatID = strings.TrimSpace(chatID) + if s == nil || s.repository == nil || userID <= 0 || accountID == "" || chatID == "" { + return ErrInvalidInput + } + // repository 保存支持会话已读更新的窄端口。 + repository, ok := s.repository.(SessionRepository) + if !ok { + return ErrSessionUnavailable + } + return repository.MarkRead(ctx, userID, accountID, chatID) +} + +// ResolveSessionIdentity 补全单个会话展示身份并尽力保存到本地。 +// 平台查询错误会原样返回,但已获得的会话摘要仍会返回给调用方。 +func (s *Service) ResolveSessionIdentity(ctx context.Context, session Session) (Session, error) { + if s == nil || s.repository == nil || strings.TrimSpace(session.AccountID) == "" || strings.TrimSpace(session.ChatID) == "" { + return session, ErrInvalidInput + } + // resolveErr 保存平台身份查询失败,供 HTTP 层决定是否触发会话恢复。 + var resolveErr error + if session.BuyerID != "1400" && s.identityResolver != nil { + // identity 和 err 保存平台适配器返回的非敏感身份及调用错误。 + identity, err := s.identityResolver.Resolve(ctx, session.AccountID, session.ChatID) + if err != nil { + resolveErr = err + } else { + // name 是去除空白后的平台买家名称。 + if name := strings.TrimSpace(identity.BuyerName); name != "" { + session.BuyerName = name + } + // avatar 是去除空白后的平台买家头像地址。 + if avatar := strings.TrimSpace(identity.BuyerAvatar); avatar != "" { + session.BuyerAvatar = avatar + } + } + } + // repository 保存会话身份更新所需的窄端口。 + if repository, ok := s.repository.(SessionRepository); ok { + // _ 表示身份缓存更新失败不应覆盖旧 handler 的展示容错语义。 + _ = repository.UpdateSessionIdentity(ctx, session.AccountID, session.ChatID, session.BuyerID, session.BuyerName, session.BuyerAvatar) + } + return session, resolveErr +} + +// RefreshSessionIdentities 并发补全会话列表身份,保留首个失败以供调用方处理过期会话。 +func (s *Service) RefreshSessionIdentities(ctx context.Context, accountID string, sessions []Session) ([]Session, error) { + accountID = strings.TrimSpace(accountID) + if s == nil || s.repository == nil || accountID == "" { + return sessions, ErrInvalidInput + } + if s.identityResolver == nil { + return sessions, nil + } + // result 复制输入列表,避免异步身份补全修改 handler 持有的外部切片。 + result := append([]Session(nil), sessions...) + // jobs 保存待补全的会话下标。 + jobs := make(chan int) + // workers 保存身份补全工作器的完成状态。 + var workers sync.WaitGroup + // once 保证只记录第一个平台查询错误。 + var once sync.Once + // firstErr 保存第一个平台查询错误。 + var firstErr error + // workerCount 是固定的并发度,避免单个账号的联系人数量放大 goroutine 数量。 + workerCount := 8 + // worker 表示当前启动的身份补全工作器序号。 + for worker := 0; worker < workerCount; worker++ { + workers.Add(1) + go func() { + defer workers.Done() + // index 表示当前待处理会话在结果切片中的下标。 + for index := range jobs { + // identityCtx 和 cancel 限制单个联系人平台查询的最长时间。 + identityCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + // updated 和 err 保存身份补全后的会话及平台查询错误。 + updated, err := s.ResolveSessionIdentity(identityCtx, result[index]) + cancel() + result[index] = updated + if err != nil { + once.Do(func() { firstErr = err }) + } + } + }() + } + // queueDone 表示是否因为父上下文取消而提前停止投递。 + queueDone := false + // index 表示当前排队会话在结果切片中的下标。 + for index := range result { + if result[index].BuyerID == "1400" { + continue + } + select { + case jobs <- index: + case <-ctx.Done(): + queueDone = true + } + if queueDone { + break + } + } + close(jobs) + workers.Wait() + return result, firstErr +} diff --git a/internal/application/chat/service_test.go b/internal/application/chat/service_test.go index 1e27aba..a1c3e0f 100644 --- a/internal/application/chat/service_test.go +++ b/internal/application/chat/service_test.go @@ -20,6 +20,20 @@ type fakeRepository struct { userID int64 // allowedUserID 是允许读取测试账号的用户 ID;其他用户模拟归属拒绝。 allowedUserID int64 + // deleteErr 是模拟空会话清理失败的错误。 + deleteErr error + // updateErr 是模拟会话身份缓存写入失败的错误。 + updateErr error + // owned 是模拟账号归属查询结果。 + owned bool + // ownedErr 是模拟账号归属查询失败的错误。 + ownedErr error + // updatedSessions 保存最近写入的会话身份,供断言应用端口调用参数。 + updatedSessions []Session + // markReadErr 表示会话已读状态更新需要返回的错误。 + markReadErr error + // markReadCalls 记录会话已读状态更新次数,避免测试误判未调用端口。 + markReadCalls int } // ListMessages 返回测试消息,并记录用户归属参数。 @@ -36,6 +50,54 @@ func (r *fakeRepository) ListSessions(_ context.Context, _ int64, _ string, _ in return r.sessions, r.sessionErr } +// DeleteEmptySessions 返回预设清理结果并记录端口已被调用。 +func (r *fakeRepository) DeleteEmptySessions(_ context.Context, _ string) error { + return r.deleteErr +} + +// UpdateSessionIdentity 记录应用层请求保存的会话身份。 +func (r *fakeRepository) UpdateSessionIdentity(_ context.Context, accountID, chatID, buyerID, buyerName, buyerAvatar string) error { + r.updatedSessions = append(r.updatedSessions, Session{AccountID: accountID, ChatID: chatID, BuyerID: buyerID, BuyerName: buyerName, BuyerAvatar: buyerAvatar}) + return r.updateErr +} + +// ExistsOwned 返回预设账号归属结果。 +func (r *fakeRepository) ExistsOwned(_ context.Context, _ int64, _ string) (bool, error) { + return r.owned, r.ownedErr +} + +// MarkRead 记录会话已读更新并返回预设错误。 +func (r *fakeRepository) MarkRead(_ context.Context, _ int64, _, _ string) error { + r.markReadCalls++ + return r.markReadErr +} + +// fakeIdentityResolver 返回预设平台展示身份,不接触真实凭证或网络。 +type fakeIdentityResolver struct { + // identity 是模拟平台返回的展示身份。 + identity Identity + // err 是模拟平台身份查询失败的错误。 + err error +} + +// historyOnlyRepository 仅实现历史读取端口,用于验证可选会话维护能力缺失时的错误。 +type historyOnlyRepository struct{} + +// ListMessages 返回空历史,满足历史读取端口的测试替身契约。 +func (historyOnlyRepository) ListMessages(context.Context, int64, string, string, int64, int) ([]Message, error) { + return nil, nil +} + +// ListSessions 返回空会话列表,满足历史读取端口的测试替身契约。 +func (historyOnlyRepository) ListSessions(context.Context, int64, string, int) ([]Session, error) { + return nil, nil +} + +// Resolve 返回预设的非敏感身份结果。 +func (r fakeIdentityResolver) Resolve(_ context.Context, _, _ string) (Identity, error) { + return r.identity, r.err +} + // TestListStoredMessagesUsesUserScopedPort 验证查询会把用户 ID 传到归属端口并组装分页结果。 func TestListStoredMessagesUsesUserScopedPort(t *testing.T) { // repository 是带有一条消息和会话摘要的测试端口。 @@ -58,7 +120,7 @@ func TestListStoredMessagesUsesUserScopedPort(t *testing.T) { // TestListStoredMessagesRejectsInvalidIdentity 验证无效用户或账号标识会在访问端口前失败。 func TestListStoredMessagesRejectsInvalidIdentity(t *testing.T) { // service 是不应被调用的测试服务。 - service := New(&fakeRepository{}) + service := New(historyOnlyRepository{}) // testCase 表示当前待验证的无效身份场景。 for _, testCase := range []struct { // name 是当前无效输入场景名称。 @@ -132,3 +194,91 @@ func TestListStoredMessagesDoesNotCrossUserBoundary(t *testing.T) { t.Fatalf("cross-user error = %v", err) } } + +// TestSessionPortCoversCleanupOwnershipAndIdentity 验证会话维护和身份补全都通过应用端口完成。 +func TestSessionPortCoversCleanupOwnershipAndIdentity(t *testing.T) { + // repository 是记录端口调用的测试仓储。 + repository := &fakeRepository{owned: true} + // service 是带平台身份替身的聊天应用服务。 + service := NewWithIdentity(repository, fakeIdentityResolver{identity: Identity{BuyerName: "买家新名", BuyerAvatar: "avatar-new"}}) + // err 表示清理空会话时的应用层错误。 + if err := service.CleanupEmptySessions(context.Background(), "account-1"); err != nil { + t.Fatalf("CleanupEmptySessions() error = %v", err) + } + // owned 和 err 保存账号归属端口结果。 + owned, err := service.OwnsAccount(context.Background(), 8, "account-1") + if err != nil || !owned { + t.Fatalf("OwnsAccount() = %v, %v", owned, err) + } + // resolved 和 resolveErr 保存身份补全后的会话及平台错误。 + resolved, resolveErr := service.ResolveSessionIdentity(context.Background(), Session{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1"}) + if resolveErr != nil || resolved.BuyerName != "买家新名" || len(repository.updatedSessions) != 1 { + t.Fatalf("ResolveSessionIdentity() = %+v, %v; updates=%+v", resolved, resolveErr, repository.updatedSessions) + } +} + +// TestSessionPortPreservesIdentityErrorAndCachedSession 验证平台身份失败时仍保留会话并返回错误供恢复流程处理。 +func TestSessionPortPreservesIdentityErrorAndCachedSession(t *testing.T) { + // wantErr 是模拟平台会话失效的错误。 + wantErr := errors.New("session expired") + // repository 是接收身份缓存写入的测试仓储。 + repository := &fakeRepository{} + // service 是返回平台错误的聊天应用服务。 + service := NewWithIdentity(repository, fakeIdentityResolver{err: wantErr}) + // session 和 err 保存身份失败后的会话及错误。 + session, err := service.ResolveSessionIdentity(context.Background(), Session{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "旧名称"}) + if !errors.Is(err, wantErr) || session.BuyerName != "旧名称" || len(repository.updatedSessions) != 1 { + t.Fatalf("session=%+v err=%v updates=%+v", session, err, repository.updatedSessions) + } +} + +// TestRefreshSessionIdentitiesKeepsOfficialSessionAndUpdatesPeers 验证批量身份补全保持闲小蜜会话并更新普通联系人。 +func TestRefreshSessionIdentitiesKeepsOfficialSessionAndUpdatesPeers(t *testing.T) { + // repository 是记录身份缓存写入的测试仓储。 + repository := &fakeRepository{} + // service 是返回统一买家身份的批量补全服务。 + service := NewWithIdentity(repository, fakeIdentityResolver{identity: Identity{BuyerName: "批量名称", BuyerAvatar: "批量头像"}}) + // sessions 是包含普通联系人和官方会话的测试列表。 + sessions := []Session{ + {AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1"}, + {AccountID: "account-1", ChatID: "chat-official", BuyerID: "1400", BuyerName: "闲小蜜"}, + } + // refreshed 和 refreshErr 保存批量补全结果及首个错误。 + refreshed, refreshErr := service.RefreshSessionIdentities(context.Background(), "account-1", sessions) + if refreshErr != nil || refreshed[0].BuyerName != "批量名称" || refreshed[1].BuyerName != "闲小蜜" || len(repository.updatedSessions) != 1 { + t.Fatalf("refreshed=%+v err=%v updates=%+v", refreshed, refreshErr, repository.updatedSessions) + } +} + +// TestSessionPortRejectsMissingCapabilities 验证未装配会话维护能力时不会伪装成成功。 +func TestSessionPortRejectsMissingCapabilities(t *testing.T) { + // service 是只实现历史查询的应用服务。 + service := New(historyOnlyRepository{}) + // err 保存缺失会话维护端口时的应用错误。 + err := service.CleanupEmptySessions(context.Background(), "account-1") + if !errors.Is(err, ErrSessionUnavailable) { + t.Fatalf("CleanupEmptySessions() error = %v, want %v", err, ErrSessionUnavailable) + } +} + +// TestMarkReadValidatesAndPropagatesPortErrors 验证已读用例的输入校验、能力缺失和底层错误分支。 +func TestMarkReadValidatesAndPropagatesPortErrors(t *testing.T) { + // wantErr 是模拟会话已读写入失败的稳定错误。 + wantErr := errors.New("mark read failed") + // repository 是记录已读调用并返回预设错误的测试端口。 + repository := &fakeRepository{markReadErr: wantErr} + // service 是使用会话维护端口构造的聊天应用服务。 + service := New(repository) + // err 保存有效请求透传的底层错误。 + if err := service.MarkRead(context.Background(), 7, " account-1 ", " chat-1 "); !errors.Is(err, wantErr) || repository.markReadCalls != 1 { + t.Fatalf("MarkRead() error=%v calls=%d", err, repository.markReadCalls) + } + // invalidErr 保存空会话标识返回的应用输入错误。 + if invalidErr := service.MarkRead(context.Background(), 7, "account-1", ""); !errors.Is(invalidErr, ErrInvalidInput) { + t.Fatalf("invalid MarkRead() error=%v", invalidErr) + } + // unavailableErr 保存仅实现历史读取端口时的能力缺失错误。 + if unavailableErr := New(historyOnlyRepository{}).MarkRead(context.Background(), 7, "account-1", "chat-1"); !errors.Is(unavailableErr, ErrSessionUnavailable) { + t.Fatalf("unavailable MarkRead() error=%v", unavailableErr) + } +} diff --git a/internal/application/defaultreply/service.go b/internal/application/defaultreply/service.go new file mode 100644 index 0000000..e643a7c --- /dev/null +++ b/internal/application/defaultreply/service.go @@ -0,0 +1,154 @@ +// Package defaultreply 定义默认回复配置用例及其消费者侧持久化 Port。 +// 本包不依赖 HTTP、数据库模型或具体基础设施实现。 +package defaultreply + +import ( + "context" + "errors" +) + +// ErrInvalidUser 表示调用方没有提供有效的本地用户身份。 +var ErrInvalidUser = errors.New("默认回复用户身份无效") + +// ErrInvalidCookieID 表示调用方没有提供有效的账号标识。 +var ErrInvalidCookieID = errors.New("默认回复账号标识无效") + +// ErrAccountNotFound 表示目标账号不存在。 +var ErrAccountNotFound = errors.New("默认回复账号不存在") + +// ErrForbidden 表示目标账号存在但不属于当前用户。 +var ErrForbidden = errors.New("无权操作该账号的默认回复") + +// ErrConfigNotFound 表示账号存在但尚未保存默认回复配置。 +var ErrConfigNotFound = errors.New("默认回复配置不存在") + +// Reply 是默认回复配置的应用层模型,不携带数据库或 HTTP 细节。 +type Reply struct { + // Enabled 表示是否启用默认回复。 + Enabled bool + // ReplyContent 是默认回复使用的文字内容。 + ReplyContent string + // ReplyImageURL 是默认回复使用的图片地址。 + ReplyImageURL string + // ReplyOnce 表示同一聊天是否只发送一次默认回复。 + ReplyOnce bool +} + +// Summary 是按用户列出的默认回复配置及其账号标识。 +type Summary struct { + // CookieID 是默认回复所属账号的稳定标识。 + CookieID string + // Reply 是该账号的默认回复配置。 + Reply Reply +} + +// AccountOwnership 是账号所有权 Port 返回的非敏感结果。 +type AccountOwnership struct { + // OwnerID 是账号所属本地用户标识;账号不存在时 Port 应返回 ErrAccountNotFound。 + OwnerID int64 +} + +// Repository 定义默认回复用例所需的最小持久化能力。 +type Repository interface { + // CheckOwnership 查询账号所有者,不读取或解密任何凭证字段。 + CheckOwnership(ctx context.Context, userID int64, cookieID string) (AccountOwnership, error) + // Get 读取账号的默认回复配置;未配置时返回 ErrConfigNotFound。 + Get(ctx context.Context, cookieID string) (Reply, error) + // Upsert 保存或覆盖账号的默认回复配置。 + Upsert(ctx context.Context, cookieID string, reply Reply) error + // ListForUser 查询指定用户全部账号的默认回复配置。 + ListForUser(ctx context.Context, userID int64) ([]Summary, error) + // Delete 删除账号的默认回复配置。 + Delete(ctx context.Context, cookieID string) error + // ClearRecords 删除账号的默认回复投递记录。 + ClearRecords(ctx context.Context, cookieID string) error +} + +// Service 编排默认回复的用户归属校验、配置读写和记录清理。 +type Service struct { + // repository 保存调用方注入的默认回复持久化 Port。 + repository Repository +} + +// NewService 创建默认回复应用服务。 +func NewService(repository Repository) *Service { + // service 保存调用方提供的持久化 Port,实际调用时会校验其是否为空。 + service := &Service{repository: repository} + return service +} + +// Get 读取指定用户账号的默认回复配置,并区分账号不存在与尚未配置。 +func (s *Service) Get(ctx context.Context, userID int64, cookieID string) (Reply, error) { + // err 表示输入、所有权或持久化查询失败的原因。 + if err := s.ensureOwned(ctx, userID, cookieID); err != nil { + return Reply{}, err + } + return s.repository.Get(ctx, cookieID) +} + +// Upsert 校验账号归属后保存默认回复配置。 +func (s *Service) Upsert(ctx context.Context, userID int64, cookieID string, reply Reply) error { + // err 表示输入、所有权或持久化写入失败的原因。 + if err := s.ensureOwned(ctx, userID, cookieID); err != nil { + return err + } + return s.repository.Upsert(ctx, cookieID, reply) +} + +// List 查询指定用户拥有的全部默认回复配置。 +func (s *Service) List(ctx context.Context, userID int64) ([]Summary, error) { + // err 表示服务装配或用户身份校验失败的原因。 + if err := s.validateUser(userID); err != nil { + return nil, err + } + return s.repository.ListForUser(ctx, userID) +} + +// Delete 校验账号归属后删除默认回复配置。 +func (s *Service) Delete(ctx context.Context, userID int64, cookieID string) error { + // err 表示输入、所有权或持久化删除失败的原因。 + if err := s.ensureOwned(ctx, userID, cookieID); err != nil { + return err + } + return s.repository.Delete(ctx, cookieID) +} + +// ClearRecords 校验账号归属后清空默认回复投递记录。 +func (s *Service) ClearRecords(ctx context.Context, userID int64, cookieID string) error { + // err 表示输入、所有权或持久化清理失败的原因。 + if err := s.ensureOwned(ctx, userID, cookieID); err != nil { + return err + } + return s.repository.ClearRecords(ctx, cookieID) +} + +// validateUser 检查应用服务依赖和用户身份,避免无效请求进入 Port。 +func (s *Service) validateUser(userID int64) error { + if s == nil || s.repository == nil { + return errors.New("默认回复 repository 未初始化") + } + if userID <= 0 { + return ErrInvalidUser + } + return nil +} + +// ensureOwned 统一执行账号标识校验和非敏感所有权判断。 +func (s *Service) ensureOwned(ctx context.Context, userID int64, cookieID string) error { + // err 表示服务装配或用户身份校验失败的原因。 + if err := s.validateUser(userID); err != nil { + return err + } + if cookieID == "" { + return ErrInvalidCookieID + } + // ownership 保存 Port 返回的账号所有者信息,不包含 Cookie 或登录秘密。 + ownership, err := s.repository.CheckOwnership(ctx, userID, cookieID) + if err != nil { + return err + } + if ownership.OwnerID != userID { + return ErrForbidden + } + return nil +} diff --git a/internal/application/defaultreply/service_test.go b/internal/application/defaultreply/service_test.go new file mode 100644 index 0000000..c77208a --- /dev/null +++ b/internal/application/defaultreply/service_test.go @@ -0,0 +1,180 @@ +package defaultreply + +import ( + "context" + "errors" + "testing" +) + +// fakeRepository 是默认回复服务测试使用的最小内存 Port。 +type fakeRepository struct { + // ownership 保存模拟的账号所有权结果。 + ownership AccountOwnership + // ownershipErr 保存模拟的所有权查询错误。 + ownershipErr error + // reply 保存模拟的默认回复配置。 + reply Reply + // getErr 保存模拟的默认回复查询错误。 + getErr error + // listed 保存模拟的默认回复列表。 + listed []Summary + // listErr 保存模拟的默认回复列表查询错误。 + listErr error + // mutationErr 保存模拟的写入、删除或清理错误。 + mutationErr error + // mutationCookieID 保存最近一次写操作的账号标识。 + mutationCookieID string +} + +// CheckOwnership 返回测试预设的账号所有权结果。 +func (f *fakeRepository) CheckOwnership(context.Context, int64, string) (AccountOwnership, error) { + return f.ownership, f.ownershipErr +} + +// Get 返回测试预设的默认回复配置或查询错误。 +func (f *fakeRepository) Get(context.Context, string) (Reply, error) { + return f.reply, f.getErr +} + +// Upsert 保存最近一次写入的账号标识并返回预设错误。 +func (f *fakeRepository) Upsert(_ context.Context, cookieID string, _ Reply) error { + f.mutationCookieID = cookieID + return f.mutationErr +} + +// ListForUser 返回测试预设的默认回复列表或查询错误。 +func (f *fakeRepository) ListForUser(context.Context, int64) ([]Summary, error) { + return f.listed, f.listErr +} + +// Delete 保存最近一次删除的账号标识并返回预设错误。 +func (f *fakeRepository) Delete(_ context.Context, cookieID string) error { + f.mutationCookieID = cookieID + return f.mutationErr +} + +// ClearRecords 保存最近一次清理的账号标识并返回预设错误。 +func (f *fakeRepository) ClearRecords(_ context.Context, cookieID string) error { + f.mutationCookieID = cookieID + return f.mutationErr +} + +// TestServiceOwnershipAndConfigErrors 验证服务区分跨用户、账号缺失和配置缺失。 +func TestServiceOwnershipAndConfigErrors(t *testing.T) { + // ctx 是本测试所有应用调用使用的非取消上下文。 + ctx := context.Background() + // accountMissing 是模拟账号不存在的持久化错误。 + accountMissing := errors.New("账号查询失败") + // cases 是覆盖所有权和配置错误语义的表驱动场景。 + cases := []struct { + // name 是场景名称。 + name string + // repository 是当前场景使用的内存 Port。 + repository *fakeRepository + // wantErr 是期望返回的稳定应用错误。 + wantErr error + }{ + {name: "cross-user", repository: &fakeRepository{ownership: AccountOwnership{OwnerID: 2}}, wantErr: ErrForbidden}, + {name: "missing-account", repository: &fakeRepository{ownershipErr: ErrAccountNotFound}, wantErr: ErrAccountNotFound}, + {name: "missing-config", repository: &fakeRepository{ownership: AccountOwnership{OwnerID: 1}, getErr: ErrConfigNotFound}, wantErr: ErrConfigNotFound}, + {name: "storage-error", repository: &fakeRepository{ownership: AccountOwnership{OwnerID: 1}, getErr: accountMissing}, wantErr: accountMissing}, + } + // item 是当前遍历的错误语义场景。 + for _, item := range cases { + t.Run(item.name, func(t *testing.T) { + // service 是使用当前场景内存 Port 的应用服务。 + service := NewService(item.repository) + // _, err 保存默认回复读取结果及错误。 + _, err := service.Get(ctx, 1, "account-1") + if !errors.Is(err, item.wantErr) { + t.Fatalf("错误=%v,期望=%v", err, item.wantErr) + } + }) + } +} + +// TestServiceMutationsRequireOwnership 验证所有写操作均先执行账号归属校验。 +func TestServiceMutationsRequireOwnership(t *testing.T) { + // ctx 是本测试所有应用调用使用的非取消上下文。 + ctx := context.Background() + // repository 是账号归属当前用户的内存 Port。 + repository := &fakeRepository{ownership: AccountOwnership{OwnerID: 7}} + // service 是使用内存 Port 的默认回复应用服务。 + service := NewService(repository) + // reply 是待保存的默认回复应用模型。 + reply := Reply{Enabled: true, ReplyContent: "你好", ReplyOnce: true} + // upsertErr 表示保存默认回复的执行结果。 + upsertErr := service.Upsert(ctx, 7, "account-7", reply) + if upsertErr != nil || repository.mutationCookieID != "account-7" { + t.Fatalf("保存结果 err=%v cookie=%q", upsertErr, repository.mutationCookieID) + } + // deleteErr 表示删除默认回复的执行结果。 + deleteErr := service.Delete(ctx, 7, "account-7") + if deleteErr != nil || repository.mutationCookieID != "account-7" { + t.Fatalf("删除结果 err=%v cookie=%q", deleteErr, repository.mutationCookieID) + } + // clearErr 表示清空投递记录的执行结果。 + clearErr := service.ClearRecords(ctx, 7, "account-7") + if clearErr != nil || repository.mutationCookieID != "account-7" { + t.Fatalf("清理结果 err=%v cookie=%q", clearErr, repository.mutationCookieID) + } + // repository.ownership 保存跨用户归属结果,验证写操作不会继续调用 Port。 + repository.ownership = AccountOwnership{OwnerID: 9} + // forbiddenErr 表示跨用户保存返回的错误。 + forbiddenErr := service.Upsert(ctx, 7, "account-9", reply) + if !errors.Is(forbiddenErr, ErrForbidden) { + t.Fatalf("跨用户保存错误=%v,期望=%v", forbiddenErr, ErrForbidden) + } +} + +// TestServiceInputValidation 验证无效服务依赖、用户和账号标识会被拒绝。 +func TestServiceInputValidation(t *testing.T) { + // ctx 是本测试使用的非取消上下文。 + ctx := context.Background() + // invalidCases 是需要在 Port 前拦截的输入场景。 + invalidCases := []struct { + // name 是场景名称。 + name string + // service 是待验证的应用服务实例。 + service *Service + // userID 是当前场景使用的用户身份。 + userID int64 + // cookieID 是当前场景使用的账号标识。 + cookieID string + // wantErr 是期望的稳定校验错误。 + wantErr error + }{ + {name: "nil-service", service: NewService(nil), userID: 1, cookieID: "a", wantErr: errors.New("默认回复 repository 未初始化")}, + {name: "invalid-user", service: NewService(&fakeRepository{}), userID: 0, cookieID: "a", wantErr: ErrInvalidUser}, + {name: "invalid-account", service: NewService(&fakeRepository{}), userID: 1, cookieID: "", wantErr: ErrInvalidCookieID}, + } + // item 是当前遍历的输入校验场景。 + for _, item := range invalidCases { + // _, err 保存当前场景的读取错误。 + _, err := item.service.Get(ctx, item.userID, item.cookieID) + if item.name == "nil-service" { + if err == nil || err.Error() != item.wantErr.Error() { + t.Fatalf("场景=%s 错误=%v", item.name, err) + } + continue + } + if !errors.Is(err, item.wantErr) { + t.Fatalf("场景=%s 错误=%v,期望=%v", item.name, err, item.wantErr) + } + } +} + +// TestServiceListReturnsApplicationSummaries 验证列表结果保持应用模型而不是数据库模型。 +func TestServiceListReturnsApplicationSummaries(t *testing.T) { + // ctx 是本测试使用的非取消上下文。 + ctx := context.Background() + // repository 是返回单条默认回复摘要的内存 Port。 + repository := &fakeRepository{ownership: AccountOwnership{OwnerID: 3}, listed: []Summary{{CookieID: "account-3", Reply: Reply{Enabled: true, ReplyContent: "欢迎"}}}} + // result、err 保存列表查询结果及错误。 + result, err := NewService(repository).List(ctx, 3) + if err != nil || len(result) != 1 || result[0].Reply.ReplyContent != "欢迎" { + t.Fatalf("列表结果=%+v err=%v", result, err) + } +} + +var _ Repository = (*fakeRepository)(nil) diff --git a/internal/application/items/batch_local_publish.go b/internal/application/items/batch_local_publish.go new file mode 100644 index 0000000..bc6b5fc --- /dev/null +++ b/internal/application/items/batch_local_publish.go @@ -0,0 +1,228 @@ +package items + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + automationapp "xianyu-go/internal/application/automation" +) + +// ErrBatchLocalPublishUnavailable 表示批量发布成功后的本地收口服务未完成装配。 +var ErrBatchLocalPublishUnavailable = errors.New("批量发布本地收口服务未初始化") + +// BatchCompletionRepository 定义批量发布本地成功收口所需的最小批次端口。 +type BatchCompletionRepository interface { + // GetBatch 读取批次归属、状态和当前 worker 租约。 + GetBatch(context.Context, int64, string) (BatchInfo, error) + // MarkClaimedRowSuccess 只允许持有明细租约的 worker 保存成功结果。 + MarkClaimedRowSuccess(context.Context, int64, string, string, string, string) (bool, error) +} + +// BatchPublishedItem 是远端商品成功后保存到本地商品目录的非敏感模型。 +type BatchPublishedItem struct { + // CookieID 是商品所属账号标识。 + CookieID string + // ItemID 是平台商品标识。 + ItemID string + // ItemTitle 是平台确认后的商品标题。 + ItemTitle string + // ItemDescription 是批量发布时保存的商品描述。 + ItemDescription string + // ItemCategory 是平台确认后的类目标识。 + ItemCategory string + // ItemPrice 是平台确认后的价格文本。 + ItemPrice string + // ItemDetail 是供商品详情页使用的扩展 JSON。 + ItemDetail string + // MultiQuantityDelivery 表示库存大于一时是否启用多数量交付。 + MultiQuantityDelivery bool +} + +// BatchPublishedItemRepository 保存远端发布成功后的本地商品记录。 +type BatchPublishedItemRepository interface { + // UpsertPublishedItem 创建或更新本地商品记录。 + UpsertPublishedItem(context.Context, BatchPublishedItem) error +} + +// BatchLocalPublishService 编排远端成功后的本地商品、自动化规则和批次成功收口。 +type BatchLocalPublishService struct { + // completionRepository 负责复核批次租约并保存明细成功检查点。 + completionRepository BatchCompletionRepository + // itemRepository 负责保存非敏感本地商品目录记录。 + itemRepository BatchPublishedItemRepository + // ruleRepository 负责幂等创建发布后的自动化规则。 + ruleRepository automationapp.PublishRuleRepository +} + +// NewBatchLocalPublishService 构造批量发布本地收口服务并校验必需端口。 +func NewBatchLocalPublishService(completionRepository BatchCompletionRepository, itemRepository BatchPublishedItemRepository, ruleRepository automationapp.PublishRuleRepository) (*BatchLocalPublishService, error) { + if completionRepository == nil { + return nil, errors.New("批量发布批次收口端口不能为空") + } + if itemRepository == nil { + return nil, errors.New("批量发布商品收口端口不能为空") + } + if ruleRepository == nil { + return nil, errors.New("批量发布规则收口端口不能为空") + } + return &BatchLocalPublishService{completionRepository: completionRepository, itemRepository: itemRepository, ruleRepository: ruleRepository}, nil +} + +// Complete 保存远端成功后的本地状态;失败时返回后置错误以阻止不可逆远端动作重试。 +func (service *BatchLocalPublishService) Complete(ctx context.Context, userID int64, row BatchRow, workerToken string, result *BatchPublishResult) error { + if service == nil || service.completionRepository == nil || service.itemRepository == nil || service.ruleRepository == nil { + return errors.New("批量发布本地收口服务未初始化") + } + if result == nil || result.ItemID == "" { + return errors.New("发布商品接口未返回结果") + } + // batch、batchErr 保存当前批次状态及租约复核错误。 + batch, batchErr := service.completionRepository.GetBatch(ctx, userID, row.BatchID) + if batchErr != nil || batch.Status == "canceled" || batch.WorkerToken != workerToken { + return &PostPublishError{Err: context.Canceled} + } + // detail 保存商品详情页需要的非敏感扩展字段。 + detail := map[string]any{"item_image": result.ImageURL, "web_url": result.ItemURL, "category_name": result.CategoryName, "quantity": result.Quantity, "publish_raw": result.RawData} + // detailJSON 保存商品详情扩展字段的 JSON 表示。 + detailJSON, _ := json.Marshal(detail) + // itemErr 保存本地商品目录写入错误。 + itemErr := service.itemRepository.UpsertPublishedItem(ctx, BatchPublishedItem{ + CookieID: row.CookieID, ItemID: result.ItemID, ItemTitle: firstBatchResultTitle(result.Title, row.Title), + ItemDescription: row.Description, ItemCategory: result.CategoryID, ItemPrice: result.PriceText, + ItemDetail: string(detailJSON), MultiQuantityDelivery: row.Quantity > 1, + }) + if itemErr != nil { + return &PostPublishError{Err: fmt.Errorf("保存发布商品信息: %w", itemErr)} + } + // ruleErr 保存发布后自动化规则幂等写入错误。 + if ruleErr := service.ensureAutomationRules(ctx, userID, row, result); ruleErr != nil { + return &PostPublishError{Err: fmt.Errorf("创建发布商品自动化规则: %w", ruleErr)} + } + // rawJSON 保存平台原始结果,供批次明细恢复和详情查询使用。 + rawJSON, _ := json.Marshal(result.RawData) + // marked、markErr 保存当前 worker 的批次成功检查点结果。 + marked, markErr := service.completionRepository.MarkClaimedRowSuccess(ctx, row.ID, workerToken, result.ItemID, result.ItemURL, string(rawJSON)) + if markErr != nil { + return markErr + } + if !marked { + return ErrBatchLeaseLost + } + return nil +} + +// EnsureAutomationRules 将发布明细中的自动化配置幂等写入规则端口;兼容测试入口不触碰商品或批次状态。 +func (service *BatchLocalPublishService) EnsureAutomationRules(ctx context.Context, userID int64, row BatchRow, result *BatchPublishResult) error { + if service == nil || service.ruleRepository == nil { + return errors.New("批量发布规则收口端口未装配") + } + if result == nil || result.ItemID == "" { + return errors.New("发布商品接口未返回结果") + } + return service.ensureAutomationRules(ctx, userID, row, result) +} + +// batchPublishAutomationConfig 保存批量表格中的发布后自动化配置。 +type batchPublishAutomationConfig struct { + // PaidDelivery 保存付款后自动发货配置。 + PaidDelivery batchPublishCardAutomation `json:"paid_delivery"` + // ReviewGift 保存评价后赠品配置。 + ReviewGift batchPublishCardAutomation `json:"review_gift"` + // ReviewRequest 保存超时求评价配置。 + ReviewRequest batchPublishReviewRequest `json:"review_request"` +} + +// batchPublishCardAutomation 保存卡密动作开关和动作列表。 +type batchPublishCardAutomation struct { + // Enabled 表示该自动化规则是否启用。 + Enabled bool `json:"enabled"` + // Actions 保存按顺序发送的卡密动作。 + Actions []batchPublishCardAction `json:"actions"` +} + +// batchPublishCardAction 保存单个卡密发送动作的参数。 +type batchPublishCardAction struct { + // CardID 是卡密组标识。 + CardID int64 `json:"card_id"` + // DeliveryCount 是本动作发送的卡密数量。 + DeliveryCount int `json:"delivery_count"` + // DelaySeconds 是动作执行前的延迟秒数。 + DelaySeconds int `json:"delay_seconds"` +} + +// batchPublishReviewRequest 保存超时求评价规则参数。 +type batchPublishReviewRequest struct { + // Enabled 表示是否启用超时求评价。 + Enabled bool `json:"enabled"` + // AfterShippedHours 是发货后等待小时数。 + AfterShippedHours int `json:"after_shipped_hours"` + // Message 是发送给买家的求评价文案。 + Message string `json:"message"` + // MaxAttempts 是最大重试次数。 + MaxAttempts int `json:"max_attempts"` + // DelaySeconds 是消息发送前的延迟秒数。 + DelaySeconds int `json:"delay_seconds"` +} + +// ensureAutomationRules 将批量配置转换为应用规则并逐条幂等保存。 +func (service *BatchLocalPublishService) ensureAutomationRules(ctx context.Context, userID int64, row BatchRow, result *BatchPublishResult) error { + // config 保存批量明细中的自动化规则配置。 + var config batchPublishAutomationConfig + // err 表示批量明细自动化配置的 JSON 解析错误。 + if err := json.Unmarshal([]byte(row.AutomationJSON), &config); err != nil { + return err + } + // title 保存规则名称使用的平台标题或导入标题。 + title := firstBatchResultTitle(result.Title, row.Title) + if config.PaidDelivery.Enabled { + // actions 保存付款后自动发货规则的动作顺序。 + actions := make([]automationapp.ActionInput, 0, len(config.PaidDelivery.Actions)+1) + // index、action 保存当前卡密动作在配置中的顺序和内容。 + for index, action := range config.PaidDelivery.Actions { + // actionConfig 保存动作延迟策略的结构化配置。 + actionConfig, _ := json.Marshal(map[string]any{"delay_override": true}) + actions = append(actions, automationapp.ActionInput{ActionType: automationapp.ActionSendCard, CardID: action.CardID, DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds, ConfigJSON: string(actionConfig), Enabled: true, SortOrder: index + 1}) + } + actions = append(actions, automationapp.ActionInput{ActionType: automationapp.ActionConfirmShipment, Enabled: true, SortOrder: len(actions) + 1}) + // err 表示付款后自动发货规则的幂等写入错误。 + if err := service.ruleRepository.EnsurePublishRule(ctx, automationapp.RuleInput{UserID: userID, CookieID: row.CookieID, ItemID: result.ItemID, Name: "付款后自动发货 - " + title, TriggerType: automationapp.TriggerOrderPaid, Enabled: true, Priority: 100, ConfigJSON: "{}", Actions: actions}); err != nil { + return err + } + } + if config.ReviewGift.Enabled { + // actions 保存评价后赠品规则的动作顺序。 + actions := make([]automationapp.ActionInput, 0, len(config.ReviewGift.Actions)) + // index、action 保存当前卡密动作在配置中的顺序和内容。 + for index, action := range config.ReviewGift.Actions { + // actionConfig 保存动作延迟策略的结构化配置。 + actionConfig, _ := json.Marshal(map[string]any{"delay_override": true}) + actions = append(actions, automationapp.ActionInput{ActionType: automationapp.ActionSendCard, CardID: action.CardID, DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds, ConfigJSON: string(actionConfig), Enabled: true, SortOrder: index + 1}) + } + // err 表示评价赠品规则的幂等写入错误。 + if err := service.ruleRepository.EnsurePublishRule(ctx, automationapp.RuleInput{UserID: userID, CookieID: row.CookieID, ItemID: result.ItemID, Name: "评价后发送赠品 - " + title, TriggerType: automationapp.TriggerBuyerReviewed, Enabled: true, Priority: 100, ConfigJSON: "{}", Actions: actions}); err != nil { + return err + } + } + if config.ReviewRequest.Enabled { + // configJSON 保存超时求评价规则的小时数与最大尝试次数。 + configJSON, _ := json.Marshal(map[string]any{"after_shipped_hours": config.ReviewRequest.AfterShippedHours, "max_attempts": config.ReviewRequest.MaxAttempts}) + // err 表示超时求评价规则的幂等写入错误。 + if err := service.ruleRepository.EnsurePublishRule(ctx, automationapp.RuleInput{UserID: userID, CookieID: row.CookieID, ItemID: result.ItemID, Name: "超时未评价求评价 - " + title, TriggerType: automationapp.TriggerReviewMissingTimeout, Enabled: true, Priority: 100, ConfigJSON: string(configJSON), Actions: []automationapp.ActionInput{{ActionType: automationapp.ActionSendText, MessageTemplate: config.ReviewRequest.Message, DelaySeconds: config.ReviewRequest.DelaySeconds, Enabled: true, SortOrder: 1}}}); err != nil { + return err + } + } + return nil +} + +// firstBatchResultTitle 选择规则和本地商品使用的首个非空标题。 +func firstBatchResultTitle(values ...string) string { + // value 表示当前候选的商品标题文本。 + for _, value := range values { + if value != "" { + return value + } + } + return "" +} diff --git a/internal/application/items/batch_local_publish_test.go b/internal/application/items/batch_local_publish_test.go new file mode 100644 index 0000000..3275894 --- /dev/null +++ b/internal/application/items/batch_local_publish_test.go @@ -0,0 +1,133 @@ +package items + +import ( + "context" + "errors" + "testing" + + automationapp "xianyu-go/internal/application/automation" +) + +// batchCompletionRepositoryFake 保存批次收口测试所需的状态和调用记录。 +type batchCompletionRepositoryFake struct { + // batch 保存当前用户可见的批次状态。 + batch BatchInfo + // marked 保存成功检查点写入次数。 + marked int + // markErr 模拟成功检查点写入失败。 + markErr error +} + +// GetBatch 返回测试预置的批次状态。 +func (repository *batchCompletionRepositoryFake) GetBatch(context.Context, int64, string) (BatchInfo, error) { + return repository.batch, nil +} + +// MarkClaimedRowSuccess 记录成功检查点写入并返回预置错误。 +func (repository *batchCompletionRepositoryFake) MarkClaimedRowSuccess(_ context.Context, _ int64, _ string, _, _, _ string) (bool, error) { + repository.marked++ + if repository.markErr != nil { + return false, repository.markErr + } + return true, nil +} + +// batchPublishedItemRepositoryFake 保存本地商品写入测试结果。 +type batchPublishedItemRepositoryFake struct { + // item 保存最近一次写入的商品模型。 + item BatchPublishedItem + // err 模拟本地商品写入失败。 + err error +} + +// UpsertPublishedItem 记录商品写入并返回预置错误。 +func (repository *batchPublishedItemRepositoryFake) UpsertPublishedItem(_ context.Context, item BatchPublishedItem) error { + repository.item = item + return repository.err +} + +// batchPublishRuleRepositoryFake 保存自动化规则写入测试结果。 +type batchPublishRuleRepositoryFake struct { + // inputs 保存幂等规则写入请求。 + inputs []automationapp.RuleInput + // err 模拟规则写入失败。 + err error +} + +// EnsurePublishRule 记录规则请求并返回预置错误。 +func (repository *batchPublishRuleRepositoryFake) EnsurePublishRule(_ context.Context, input automationapp.RuleInput) error { + repository.inputs = append(repository.inputs, input) + return repository.err +} + +// TestBatchLocalPublishServiceCompletesLocalState 验证远端成功后的本地商品、规则和检查点收口顺序。 +func TestBatchLocalPublishServiceCompletesLocalState(t *testing.T) { + // completionRepository 保存租约状态和成功检查点记录。 + completionRepository := &batchCompletionRepositoryFake{batch: BatchInfo{Status: "running", WorkerToken: "worker"}} + // itemRepository 保存本地商品写入结果。 + itemRepository := &batchPublishedItemRepositoryFake{} + // ruleRepository 保存自动化规则写入结果。 + ruleRepository := &batchPublishRuleRepositoryFake{} + // service 是待验证的批量本地收口服务。 + service, err := NewBatchLocalPublishService(completionRepository, itemRepository, ruleRepository) + if err != nil { + t.Fatal(err) + } + // row 保存导入的商品和自动化配置。 + row := BatchRow{ID: 7, BatchID: "batch-1", CookieID: "cookie-1", Title: "导入标题", Description: "商品描述", Quantity: 2, AutomationJSON: `{"paid_delivery":{"enabled":true,"actions":[{"card_id":11,"delivery_count":2,"delay_seconds":3}]},"review_request":{"enabled":true,"after_shipped_hours":24,"message":"请评价","max_attempts":2,"delay_seconds":5}}`} + // result 保存平台返回的非敏感商品结果。 + result := &BatchPublishResult{ItemID: "item-1", ItemURL: "https://example/item-1", Title: "平台标题", PriceText: "12.00", CategoryID: "cat-1", RawData: map[string]any{"ok": true}} + // completeErr 保存本地收口结果。 + completeErr := service.Complete(context.Background(), 9, row, "worker", result) + if completeErr != nil { + t.Fatalf("本地收口失败: %v", completeErr) + } + if completionRepository.marked != 1 || itemRepository.item.ItemID != "item-1" || !itemRepository.item.MultiQuantityDelivery { + t.Fatalf("本地商品或检查点状态异常: marked=%d item=%+v", completionRepository.marked, itemRepository.item) + } + if len(ruleRepository.inputs) != 2 || ruleRepository.inputs[0].Actions[1].ActionType != automationapp.ActionConfirmShipment || ruleRepository.inputs[1].TriggerType != automationapp.TriggerReviewMissingTimeout { + t.Fatalf("自动化规则转换异常: %+v", ruleRepository.inputs) + } +} + +// TestBatchLocalPublishServiceRejectsLeaseLoss 验证租约丢失时不写入本地商品或成功检查点。 +func TestBatchLocalPublishServiceRejectsLeaseLoss(t *testing.T) { + // completionRepository 返回已转移到其他 worker 的批次租约。 + completionRepository := &batchCompletionRepositoryFake{batch: BatchInfo{Status: "running", WorkerToken: "other"}} + // itemRepository 保存本地商品写入调用次数的替身。 + itemRepository := &batchPublishedItemRepositoryFake{} + // ruleRepository 保存规则写入调用次数的替身。 + ruleRepository := &batchPublishRuleRepositoryFake{} + // service 是待验证的批量本地收口服务。 + service, err := NewBatchLocalPublishService(completionRepository, itemRepository, ruleRepository) + if err != nil { + t.Fatal(err) + } + // completeErr 保存租约丢失后的错误。 + completeErr := service.Complete(context.Background(), 9, BatchRow{BatchID: "batch-1", AutomationJSON: `{}`}, "worker", &BatchPublishResult{ItemID: "item-1"}) + if !errors.Is(completeErr, context.Canceled) || itemRepository.item.ItemID != "" || completionRepository.marked != 0 { + t.Fatalf("租约丢失处理异常: err=%v item=%+v marked=%d", completeErr, itemRepository.item, completionRepository.marked) + } +} + +// TestBatchLocalPublishServiceClassifiesPostWriteFailure 验证商品或规则写入失败会标记为不可自动重试的后置错误。 +func TestBatchLocalPublishServiceClassifiesPostWriteFailure(t *testing.T) { + // completionRepository 保存可用的当前 worker 租约。 + completionRepository := &batchCompletionRepositoryFake{batch: BatchInfo{Status: "running", WorkerToken: "worker"}} + // itemRepository 模拟数据库商品写入故障。 + itemRepository := &batchPublishedItemRepositoryFake{err: errors.New("商品数据库不可用")} + // ruleRepository 保存未被调用的规则写入替身。 + ruleRepository := &batchPublishRuleRepositoryFake{} + // service 是待验证的批量本地收口服务。 + service, err := NewBatchLocalPublishService(completionRepository, itemRepository, ruleRepository) + if err != nil { + t.Fatal(err) + } + // completeErr 保存本地写入失败后的错误。 + completeErr := service.Complete(context.Background(), 9, BatchRow{BatchID: "batch-1", AutomationJSON: `{}`}, "worker", &BatchPublishResult{ItemID: "item-1"}) + // postErr 保存后置本地收口错误的类型化视图。 + var postErr *PostPublishError + if !errors.As(completeErr, &postErr) || completionRepository.marked != 0 || len(ruleRepository.inputs) != 0 { + t.Fatalf("后置错误分类异常: err=%v marked=%d rules=%d", completeErr, completionRepository.marked, len(ruleRepository.inputs)) + } +} diff --git a/internal/application/items/batch_management.go b/internal/application/items/batch_management.go new file mode 100644 index 0000000..cce8a9c --- /dev/null +++ b/internal/application/items/batch_management.go @@ -0,0 +1,331 @@ +package items + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "strings" + "time" +) + +var ( + // ErrBatchNotFound 表示批次不存在或不属于当前用户。 + ErrBatchNotFound = errors.New("商品批量任务不存在") + // ErrBatchConflict 表示批次租约或状态发生并发冲突。 + ErrBatchConflict = errors.New("商品批量任务状态冲突") + // ErrBatchInvalidState 表示批次当前状态不允许执行请求操作。 + ErrBatchInvalidState = errors.New("商品批量任务状态不允许执行该操作") + // ErrBatchNoRows 表示批次没有可继续处理的明细行。 + ErrBatchNoRows = errors.New("商品批量任务没有可处理的明细行") +) + +// BatchDetails 是批次查询结果及其明细行的纯应用模型。 +type BatchDetails struct { + // Batch 是批次状态和非敏感展示字段。 + Batch BatchInfo + // Rows 是批次内按导入顺序排列的明细。 + Rows []BatchRow +} + +// BatchManagementRepository 定义批次管理用例所需的最小持久化端口。 +type BatchManagementRepository interface { + // GetBatch 查询指定用户拥有的批次。 + GetBatch(context.Context, int64, string) (BatchInfo, error) + // ClaimBatch 抢占批次 worker 租约。 + ClaimBatch(context.Context, string, string, int64) (bool, error) + // PendingRows 查询批次中可处理的明细。 + PendingRows(context.Context, string, bool) ([]BatchRow, error) + // FinalizeBatch 在没有可处理明细时收口批次。 + FinalizeBatch(context.Context, string, string) (string, bool, error) + // ListBatchesForUser 查询用户的批次摘要。 + ListBatchesForUser(context.Context, int64, int) ([]BatchInfo, error) + // ListBatchRows 查询指定批次的全部明细。 + ListBatchRows(context.Context, string) ([]BatchRow, error) + // RequestCancel 请求取消指定批次并返回当前 worker 状态。 + RequestCancel(context.Context, string) (string, bool, error) + // DeleteBatch 删除指定用户拥有的非运行批次及其上传文件。 + DeleteBatch(context.Context, int64, string) error + // ResetFailed 将可重试失败明细恢复为待处理状态。 + ResetFailed(context.Context, string) error + // RecountBatch 重算批次统计字段。 + RecountBatch(context.Context, string) error + // ExpiredUploadBatches 查询超过保留期限且仍记录上传目录的批次。 + ExpiredUploadBatches(context.Context, string, int) ([]BatchInfo, error) + // DeleteUpload 删除批次上传目录并清除持久化路径记录。 + DeleteUpload(context.Context, string, string) error + // FailClaimedBatch 释放当前 worker 持有的批次租约。 + FailClaimedBatch(context.Context, string, string) (bool, error) +} + +// BatchManagementRuntime 定义批次管理服务控制后台 worker 的最小端口。 +type BatchManagementRuntime interface { + // StartBatch 启动指定批次的后台 worker。 + StartBatch(int64, string, string) + // CancelBatch 请求停止指定批次的后台 worker。 + CancelBatch(string, string) +} + +// BatchManagementService 编排批次启动、查询、取消、删除和重试,不依赖 HTTP 或数据库模型。 +type BatchManagementService struct { + // repository 保存批次状态和明细。 + repository BatchManagementRepository + // runtime 控制已经声明租约的后台 worker。 + runtime BatchManagementRuntime + // now 提供当前时间,便于稳定测试租约判断。 + now func() time.Time + // tokenFactory 生成批次 worker 的租约令牌。 + tokenFactory func() string +} + +// NewBatchManagementService 构造批次管理服务并校验必需端口。 +func NewBatchManagementService(repository BatchManagementRepository, runtime BatchManagementRuntime) (*BatchManagementService, error) { + if repository == nil { + return nil, errors.New("批次管理 repository 未初始化") + } + // now 提供生产默认时间源,测试可通过构造后替换为固定时间。 + now := time.Now + // tokenFactory 提供生产默认租约令牌生成器,测试可通过构造后替换为固定值。 + tokenFactory := func() string { return randomBatchToken() } + return &BatchManagementService{repository: repository, runtime: runtime, now: now, tokenFactory: tokenFactory}, nil +} + +// StartBatch 校验批次状态、声明租约并启动后台 worker。 +func (s *BatchManagementService) StartBatch(ctx context.Context, userID int64, batchID string, lease time.Duration) (string, error) { + if s == nil || s.repository == nil || userID <= 0 || strings.TrimSpace(batchID) == "" { + return "", ErrBatchNotFound + } + // batch 保存当前用户可见的批次快照。 + batch, err := s.repository.GetBatch(ctx, userID, batchID) + if err != nil { + return "", ErrBatchNotFound + } + // now 保存本次请求使用的统一当前时间。 + now := s.now() + if batch.Status == "running" && batch.LeaseExpiresAt > now.UTC().Unix() { + return "", ErrBatchConflict + } + if batch.Status != "preview" && batch.Status != "pending" && batch.Status != "completed" && batch.Status != "running" { + return "", ErrBatchInvalidState + } + if lease <= 0 { + lease = 5 * time.Minute + } + // workerToken 保存本次批次租约令牌。 + workerToken := s.tokenFactory() + // claimed 表示数据库是否成功声明当前租约。 + claimed, err := s.repository.ClaimBatch(ctx, batch.ID, workerToken, now.UTC().Add(lease).Unix()) + if err != nil { + return "", err + } + if !claimed { + return "", ErrBatchConflict + } + // pending 保存租约声明后仍待处理的明细。 + pending, err := s.repository.PendingRows(ctx, batch.ID, false) + if err != nil { + // releaseErr 保存读取明细失败后的租约释放错误;主错误保持原始阶段信息。 + if releaseErr := s.releaseClaim(ctx, batch.ID, workerToken); releaseErr != nil { + return "", errors.Join(err, releaseErr) + } + return "", err + } + if len(pending) == 0 { + _, _, _ = s.repository.FinalizeBatch(ctx, batch.ID, workerToken) + return "", ErrBatchNoRows + } + if s.runtime == nil { + return batch.ID, nil + } + s.runtime.StartBatch(userID, batch.ID, workerToken) + return batch.ID, nil +} + +// ListBatches 查询用户的批次摘要。 +func (s *BatchManagementService) ListBatches(ctx context.Context, userID int64, limit int) ([]BatchInfo, error) { + if s == nil || s.repository == nil || userID <= 0 { + return nil, ErrBatchNotFound + } + return s.repository.ListBatchesForUser(ctx, userID, limit) +} + +// GetBatch 查询用户拥有的批次及其明细。 +func (s *BatchManagementService) GetBatch(ctx context.Context, userID int64, batchID string) (BatchDetails, error) { + if s == nil || s.repository == nil || userID <= 0 || strings.TrimSpace(batchID) == "" { + return BatchDetails{}, ErrBatchNotFound + } + // batch 保存用户归属校验后的批次。 + batch, err := s.repository.GetBatch(ctx, userID, batchID) + if err != nil { + return BatchDetails{}, ErrBatchNotFound + } + // rows 保存批次全部明细。 + rows, err := s.repository.ListBatchRows(ctx, batch.ID) + if err != nil { + return BatchDetails{}, err + } + return BatchDetails{Batch: batch, Rows: rows}, nil +} + +// CancelBatch 请求批次取消,并通知仍在运行的 worker。 +func (s *BatchManagementService) CancelBatch(ctx context.Context, userID int64, batchID string) (string, error) { + if s == nil || s.repository == nil || userID <= 0 || strings.TrimSpace(batchID) == "" { + return "", ErrBatchNotFound + } + // batch 用于先执行用户归属复核。 + if _, err := s.repository.GetBatch(ctx, userID, batchID); err != nil { + return "", ErrBatchNotFound + } + // workerToken、running 保存取消请求返回的 worker 状态。 + workerToken, running, err := s.repository.RequestCancel(ctx, batchID) + if err != nil { + return "", err + } + if running && s.runtime != nil { + s.runtime.CancelBatch(batchID, workerToken) + return "canceling", nil + } + return "canceled", nil +} + +// DeleteBatch 删除非运行批次及其上传文件。 +func (s *BatchManagementService) DeleteBatch(ctx context.Context, userID int64, batchID string) error { + if s == nil || s.repository == nil || userID <= 0 || strings.TrimSpace(batchID) == "" { + return ErrBatchNotFound + } + // batch 保存删除前的状态并完成用户归属校验。 + batch, err := s.repository.GetBatch(ctx, userID, batchID) + if err != nil { + return ErrBatchNotFound + } + if batch.Status == "running" || batch.Status == "canceling" { + return ErrBatchConflict + } + return s.repository.DeleteBatch(ctx, userID, batchID) +} + +// FailClaimedBatch 释放指定 worker 持有的批次租约,供异常退出补偿路径使用。 +func (s *BatchManagementService) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) { + if s == nil || s.repository == nil || strings.TrimSpace(batchID) == "" || strings.TrimSpace(workerToken) == "" { + return false, ErrBatchNotFound + } + return s.repository.FailClaimedBatch(ctx, batchID, workerToken) +} + +// CleanupExpiredUploads 清理超过七天保留期限的批次上传目录。 +func (s *BatchManagementService) CleanupExpiredUploads(ctx context.Context, now time.Time, limit int) error { + if s == nil || s.repository == nil { + return errors.New("批次管理 repository 未初始化") + } + if now.IsZero() { + now = s.now() + } + if limit <= 0 { + limit = 100 + } + // cutoff 保存上传目录保留期限的数据库时间文本。 + cutoff := now.UTC().Add(-7 * 24 * time.Hour).Format("2006-01-02 15:04:05") + // batches 保存待清理的批次快照;路径只交给 repository 处理,不向 HTTP 层暴露数据库模型。 + batches, err := s.repository.ExpiredUploadBatches(ctx, cutoff, limit) + if err != nil { + return err + } + // cleanupErr 汇总单个批次清理失败,确保一个坏目录不会阻止后续批次清理。 + var cleanupErr error + // batch 表示当前待清理上传目录的批次快照。 + for _, batch := range batches { + // err 表示清理循环检测到的上下文取消错误。 + if err := ctx.Err(); err != nil { + return err + } + // err 表示当前批次上传目录或数据库路径清理错误。 + if err := s.repository.DeleteUpload(ctx, batch.ID, batch.UploadDir); err != nil { + cleanupErr = errors.Join(cleanupErr, err) + } + } + return cleanupErr +} + +// RetryFailedBatch 重置失败明细、声明新租约并启动重试 worker。 +func (s *BatchManagementService) RetryFailedBatch(ctx context.Context, userID int64, batchID string, lease time.Duration) (string, error) { + if s == nil || s.repository == nil || userID <= 0 || strings.TrimSpace(batchID) == "" { + return "", ErrBatchNotFound + } + // batch 保存重试前的用户归属和租约状态。 + batch, err := s.repository.GetBatch(ctx, userID, batchID) + if err != nil { + return "", ErrBatchNotFound + } + // now 保存本次重试使用的统一当前时间。 + now := s.now() + if batch.Status == "running" && batch.LeaseExpiresAt > now.UTC().Unix() { + return "", ErrBatchConflict + } + if lease <= 0 { + lease = 5 * time.Minute + } + // workerToken 保存本次重试租约令牌。 + workerToken := s.tokenFactory() + // claimed 表示数据库是否成功声明重试租约。 + claimed, err := s.repository.ClaimBatch(ctx, batchID, workerToken, now.UTC().Add(lease).Unix()) + if err != nil { + return "", err + } + if !claimed { + return "", ErrBatchConflict + } + // resetErr 保存失败明细重置错误。 + if resetErr := s.repository.ResetFailed(ctx, batchID); resetErr != nil { + // releaseErr 保存失败重置失败后的租约释放错误;主错误保持重置阶段信息。 + if releaseErr := s.releaseClaim(ctx, batchID, workerToken); releaseErr != nil { + return "", errors.Join(resetErr, releaseErr) + } + return "", resetErr + } + // recountErr 保存失败明细重置后的批次统计错误;统计失败不能继续启动 worker。 + if recountErr := s.repository.RecountBatch(ctx, batchID); recountErr != nil { + // releaseErr 保存统计重算失败后的租约释放错误;主错误保持重算阶段信息。 + if releaseErr := s.releaseClaim(ctx, batchID, workerToken); releaseErr != nil { + return "", errors.Join(recountErr, releaseErr) + } + return "", recountErr + } + // pending 保存重置后可重试的明细。 + pending, err := s.repository.PendingRows(ctx, batchID, false) + if err != nil { + // releaseErr 保存读取重试明细失败后的租约释放错误;主错误保持查询阶段信息。 + if releaseErr := s.releaseClaim(ctx, batchID, workerToken); releaseErr != nil { + return "", errors.Join(err, releaseErr) + } + return "", err + } + if len(pending) == 0 { + _, _, _ = s.repository.FinalizeBatch(ctx, batchID, workerToken) + return "", ErrBatchNoRows + } + if s.runtime != nil { + s.runtime.StartBatch(userID, batchID, workerToken) + } + return batchID, nil +} + +// releaseClaim 释放批次管理服务已声明但尚未启动 worker 的租约。 +func (s *BatchManagementService) releaseClaim(ctx context.Context, batchID, workerToken string) error { + if s == nil || s.repository == nil { + return errors.New("批次管理 repository 未初始化") + } + // _, releaseErr 保存租约释放调用的结果;布尔值仅表示是否成功匹配租约。 + _, releaseErr := s.repository.FailClaimedBatch(ctx, batchID, workerToken) + return releaseErr +} + +// randomBatchToken 生成批次租约所需的不透明令牌;具体随机源由服务默认实现负责。 +func randomBatchToken() string { + // bytes 保存租约令牌的随机字节,令牌不携带用户或商品信息。 + bytes := make([]byte, 16) + // _, err 保存随机源读取结果;系统随机源失败时回退到时间戳以保持旧接口可用。 + if _, err := rand.Read(bytes); err == nil { + return hex.EncodeToString(bytes) + } + return time.Now().UTC().Format("20060102150405.000000000") +} diff --git a/internal/application/items/batch_management_test.go b/internal/application/items/batch_management_test.go new file mode 100644 index 0000000..0ceb0ad --- /dev/null +++ b/internal/application/items/batch_management_test.go @@ -0,0 +1,314 @@ +package items + +import ( + "context" + "errors" + "testing" + "time" +) + +// batchManagementRepositoryFake 保存批次管理用例测试所需的状态和调用记录。 +type batchManagementRepositoryFake struct { + // batch 是当前用户可见的批次。 + batch BatchInfo + // batches 是批次列表查询结果。 + batches []BatchInfo + // rows 是批次明细查询结果。 + rows []BatchRow + // pending 是待处理明细查询结果。 + pending []BatchRow + // err 是所有未单独配置方法的预置错误。 + err error + // claimed 表示租约抢占结果。 + claimed bool + // cancelToken 是取消请求返回的 worker 令牌。 + cancelToken string + // cancelRunning 表示取消请求时 worker 是否仍在运行。 + cancelRunning bool + // deleted 表示批次删除是否被调用。 + deleted bool + // resetFailedCalled 表示失败明细重置是否被调用。 + resetFailedCalled bool + // recountCalled 表示批次统计重算是否被调用。 + recountCalled bool + // finalized 表示无明细时批次是否被收口。 + finalized bool + // released 表示异常阶段是否释放了批次租约。 + released bool + // expiredUploads 保存过期上传批次查询结果。 + expiredUploads []BatchInfo + // deletedUploads 保存上传目录清理调用的批次标识。 + deletedUploads []string + // uploadCleanupErr 是上传目录清理预置错误。 + uploadCleanupErr error +} + +// GetBatch 返回预置批次或仓储错误。 +func (repository *batchManagementRepositoryFake) GetBatch(context.Context, int64, string) (BatchInfo, error) { + if repository.err != nil { + return BatchInfo{}, repository.err + } + return repository.batch, nil +} + +// ClaimBatch 返回预置租约抢占结果。 +func (repository *batchManagementRepositoryFake) ClaimBatch(context.Context, string, string, int64) (bool, error) { + if repository.err != nil { + return false, repository.err + } + return repository.claimed, nil +} + +// PendingRows 返回预置待处理明细。 +func (repository *batchManagementRepositoryFake) PendingRows(context.Context, string, bool) ([]BatchRow, error) { + if repository.err != nil { + return nil, repository.err + } + return repository.pending, nil +} + +// FinalizeBatch 记录无明细时的批次收口。 +func (repository *batchManagementRepositoryFake) FinalizeBatch(context.Context, string, string) (string, bool, error) { + repository.finalized = true + return "completed", true, nil +} + +// ListBatchesForUser 返回预置批次列表。 +func (repository *batchManagementRepositoryFake) ListBatchesForUser(context.Context, int64, int) ([]BatchInfo, error) { + if repository.err != nil { + return nil, repository.err + } + return repository.batches, nil +} + +// ListBatchRows 返回预置批次明细。 +func (repository *batchManagementRepositoryFake) ListBatchRows(context.Context, string) ([]BatchRow, error) { + if repository.err != nil { + return nil, repository.err + } + return repository.rows, nil +} + +// RequestCancel 返回预置取消状态。 +func (repository *batchManagementRepositoryFake) RequestCancel(context.Context, string) (string, bool, error) { + if repository.err != nil { + return "", false, repository.err + } + return repository.cancelToken, repository.cancelRunning, nil +} + +// DeleteBatch 记录批次删除调用。 +func (repository *batchManagementRepositoryFake) DeleteBatch(context.Context, int64, string) error { + repository.deleted = true + return repository.err +} + +// ResetFailed 记录失败明细重置调用。 +func (repository *batchManagementRepositoryFake) ResetFailed(context.Context, string) error { + repository.resetFailedCalled = true + return repository.err +} + +// RecountBatch 记录批次统计重算调用。 +func (repository *batchManagementRepositoryFake) RecountBatch(context.Context, string) error { + repository.recountCalled = true + return repository.err +} + +// ExpiredUploadBatches 返回预置的过期上传批次。 +func (repository *batchManagementRepositoryFake) ExpiredUploadBatches(context.Context, string, int) ([]BatchInfo, error) { + if repository.err != nil { + return nil, repository.err + } + return repository.expiredUploads, nil +} + +// DeleteUpload 记录上传目录清理调用并返回预置错误。 +func (repository *batchManagementRepositoryFake) DeleteUpload(_ context.Context, batchID, _ string) error { + repository.deletedUploads = append(repository.deletedUploads, batchID) + return repository.uploadCleanupErr +} + +// FailClaimedBatch 记录批次租约释放调用。 +func (repository *batchManagementRepositoryFake) FailClaimedBatch(context.Context, string, string) (bool, error) { + repository.released = true + return true, repository.err +} + +// batchManagementRuntimeFake 记录应用服务发出的 worker 控制命令。 +type batchManagementRuntimeFake struct { + // started 保存启动 worker 的参数。 + started []string + // canceled 保存取消 worker 的参数。 + canceled []string +} + +// StartBatch 记录批次 worker 启动。 +func (runtime *batchManagementRuntimeFake) StartBatch(userID int64, batchID, workerToken string) { + // command 保存便于断言的 worker 启动参数。 + command := batchID + ":" + workerToken + runtime.started = append(runtime.started, command) +} + +// CancelBatch 记录批次 worker 取消。 +func (runtime *batchManagementRuntimeFake) CancelBatch(batchID, workerToken string) { + // command 保存便于断言的 worker 取消参数。 + command := batchID + ":" + workerToken + runtime.canceled = append(runtime.canceled, command) +} + +// newBatchManagementServiceForTest 创建使用固定时间和令牌的批次管理服务。 +func newBatchManagementServiceForTest(t *testing.T, repository *batchManagementRepositoryFake, runtime *batchManagementRuntimeFake) *BatchManagementService { + // service、err 保存批次管理服务构造结果。 + service, err := NewBatchManagementService(repository, runtime) + if err != nil { + t.Fatalf("NewBatchManagementService error: %v", err) + } + service.now = func() time.Time { return time.Unix(100, 0).UTC() } + service.tokenFactory = func() string { return "worker-fixed" } + return service +} + +// TestBatchManagementStartAndCancel 验证批次启动声明租约、启动 worker 和取消通知顺序。 +func TestBatchManagementStartAndCancel(t *testing.T) { + // repository、runtime 和 service 保存本测试的应用端口替身。 + repository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "batch-1", Status: "preview"}, claimed: true, pending: []BatchRow{{ID: 1}}} + // runtime 保存批次 worker 控制调用记录。 + runtime := &batchManagementRuntimeFake{} + // service 保存固定时间和租约令牌的批次管理服务。 + service := newBatchManagementServiceForTest(t, repository, runtime) + // batchID、startErr 保存批次启动结果。 + batchID, startErr := service.StartBatch(context.Background(), 7, "batch-1", time.Minute) + if startErr != nil || batchID != "batch-1" || len(runtime.started) != 1 || runtime.started[0] != "batch-1:worker-fixed" { + t.Fatalf("start result=%q err=%v runtime=%+v", batchID, startErr, runtime) + } + repository.cancelToken = "worker-fixed" + repository.cancelRunning = true + // status、cancelErr 保存批次取消结果。 + status, cancelErr := service.CancelBatch(context.Background(), 7, "batch-1") + if cancelErr != nil || status != "canceling" || len(runtime.canceled) != 1 || runtime.canceled[0] != "batch-1:worker-fixed" { + t.Fatalf("cancel result=%q err=%v runtime=%+v", status, cancelErr, runtime) + } +} + +// TestBatchManagementRejectsConflictAndNoRows 验证活动租约与空批次均不会启动 worker。 +func TestBatchManagementRejectsConflictAndNoRows(t *testing.T) { + // activeRepository 保存仍在有效租约内的批次。 + activeRepository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "active", Status: "running", LeaseExpiresAt: 200}, claimed: true, pending: []BatchRow{{ID: 1}}} + // activeRuntime 保存活动租约测试的运行时替身。 + activeRuntime := &batchManagementRuntimeFake{} + // activeService 保存活动租约测试的批次管理服务。 + activeService := newBatchManagementServiceForTest(t, activeRepository, activeRuntime) + // activeErr 保存活动租约拒绝结果。 + _, activeErr := activeService.StartBatch(context.Background(), 7, "active", time.Minute) + if !errors.Is(activeErr, ErrBatchConflict) { + t.Fatalf("active error=%v", activeErr) + } + // emptyRepository 保存已经没有可处理明细的批次。 + emptyRepository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "empty", Status: "preview"}, claimed: true} + // emptyRuntime 保存空批次测试的运行时替身。 + emptyRuntime := &batchManagementRuntimeFake{} + // emptyService 保存空批次测试的批次管理服务。 + emptyService := newBatchManagementServiceForTest(t, emptyRepository, emptyRuntime) + // _, emptyErr 保存空批次启动结果。 + _, emptyErr := emptyService.StartBatch(context.Background(), 7, "empty", time.Minute) + if !errors.Is(emptyErr, ErrBatchNoRows) || !emptyRepository.finalized || len(emptyRuntime.started) != 0 { + t.Fatalf("empty result err=%v finalized=%v runtime=%+v", emptyErr, emptyRepository.finalized, emptyRuntime) + } +} + +// TestBatchManagementListGetDelete 验证批次列表、明细查询和删除状态约束。 +func TestBatchManagementListGetDelete(t *testing.T) { + // repository 保存查询和删除测试数据。 + repository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "batch-1", Status: "completed"}, batches: []BatchInfo{{ID: "batch-1"}}, rows: []BatchRow{{ID: 2, Status: "failed"}}} + // service 保存批次管理应用服务。 + service := newBatchManagementServiceForTest(t, repository, &batchManagementRuntimeFake{}) + // batches、listErr 保存用户批次列表结果。 + batches, listErr := service.ListBatches(context.Background(), 7, 20) + if listErr != nil || len(batches) != 1 || batches[0].ID != "batch-1" { + t.Fatalf("list result=%+v err=%v", batches, listErr) + } + // details、getErr 保存批次及明细查询结果。 + details, getErr := service.GetBatch(context.Background(), 7, "batch-1") + if getErr != nil || details.Batch.ID != "batch-1" || len(details.Rows) != 1 { + t.Fatalf("get result=%+v err=%v", details, getErr) + } + // deleteErr 保存批次删除结果。 + deleteErr := service.DeleteBatch(context.Background(), 7, "batch-1") + if deleteErr != nil || !repository.deleted { + t.Fatalf("delete err=%v deleted=%v", deleteErr, repository.deleted) + } + // runningRepository 保存运行中批次,验证删除会被拒绝。 + runningRepository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "running", Status: "running"}} + // runningService 保存运行中批次测试的应用服务。 + runningService := newBatchManagementServiceForTest(t, runningRepository, &batchManagementRuntimeFake{}) + // runningErr 保存运行中批次删除结果。 + runningErr := runningService.DeleteBatch(context.Background(), 7, "running") + if !errors.Is(runningErr, ErrBatchConflict) { + t.Fatalf("running delete error=%v", runningErr) + } +} + +// TestBatchManagementFailClaimedBatch 验证异常退出路径只释放匹配的批次租约。 +func TestBatchManagementFailClaimedBatch(t *testing.T) { + // repository 保存租约释放调用记录。 + repository := &batchManagementRepositoryFake{} + // service 保存批次管理应用服务。 + service := newBatchManagementServiceForTest(t, repository, &batchManagementRuntimeFake{}) + // released、releaseErr 保存有效租约释放结果。 + released, releaseErr := service.FailClaimedBatch(context.Background(), "batch-1", "worker-1") + if releaseErr != nil || !released || !repository.released { + t.Fatalf("release result=%v err=%v repository=%+v", released, releaseErr, repository) + } + // invalidReleased、invalidErr 保存缺少租约标识时的拒绝结果。 + invalidReleased, invalidErr := service.FailClaimedBatch(context.Background(), "", "worker-1") + if invalidReleased || !errors.Is(invalidErr, ErrBatchNotFound) { + t.Fatalf("invalid release result=%v err=%v", invalidReleased, invalidErr) + } +} + +// TestBatchManagementRetryFailed 验证失败明细重置、统计重算和重试 worker 启动。 +func TestBatchManagementRetryFailed(t *testing.T) { + // repository、runtime 和 service 保存重试测试依赖。 + repository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "batch-retry", Status: "completed"}, claimed: true, pending: []BatchRow{{ID: 3}}} + // runtime 保存重试 worker 控制调用记录。 + runtime := &batchManagementRuntimeFake{} + // service 保存固定时间和租约令牌的批次管理服务。 + service := newBatchManagementServiceForTest(t, repository, runtime) + // batchID、retryErr 保存失败重试结果。 + batchID, retryErr := service.RetryFailedBatch(context.Background(), 7, "batch-retry", time.Minute) + if retryErr != nil || batchID != "batch-retry" || !repository.resetFailedCalled || !repository.recountCalled || len(runtime.started) != 1 { + t.Fatalf("retry result=%q err=%v repository=%+v runtime=%+v", batchID, retryErr, repository, runtime) + } +} + +// TestBatchManagementCleanupExpiredUploads 验证过期目录清理的成功、失败聚合与取消语义。 +func TestBatchManagementCleanupExpiredUploads(t *testing.T) { + // repository 保存过期批次和清理错误替身。 + repository := &batchManagementRepositoryFake{expiredUploads: []BatchInfo{{ID: "expired-1", UploadDir: "/tmp/one"}, {ID: "expired-2", UploadDir: "/tmp/two"}}} + // service 保存固定时间的批次管理服务。 + service := newBatchManagementServiceForTest(t, repository, &batchManagementRuntimeFake{}) + // cleanupErr 保存成功清理结果。 + cleanupErr := service.CleanupExpiredUploads(context.Background(), time.Unix(200, 0), 2) + if cleanupErr != nil || len(repository.deletedUploads) != 2 { + t.Fatalf("cleanup result err=%v calls=%v", cleanupErr, repository.deletedUploads) + } + + // repository.uploadCleanupErr 验证单个目录失败不会阻止后续目录处理。 + repository.uploadCleanupErr = errors.New("目录清理失败") + repository.deletedUploads = nil + cleanupErr = service.CleanupExpiredUploads(context.Background(), time.Unix(200, 0), 2) + if cleanupErr == nil || len(repository.deletedUploads) != 2 { + t.Fatalf("cleanup failure err=%v calls=%v", cleanupErr, repository.deletedUploads) + } + + // canceledContext 验证清理循环尊重取消信号。 + canceledContext, cancel := context.WithCancel(context.Background()) + cancel() + repository.uploadCleanupErr = nil + repository.deletedUploads = nil + cleanupErr = service.CleanupExpiredUploads(canceledContext, time.Unix(200, 0), 2) + if !errors.Is(cleanupErr, context.Canceled) { + t.Fatalf("canceled cleanup err=%v", cleanupErr) + } +} diff --git a/internal/application/items/batch_preview.go b/internal/application/items/batch_preview.go new file mode 100644 index 0000000..746196c --- /dev/null +++ b/internal/application/items/batch_preview.go @@ -0,0 +1,881 @@ +package items + +import ( + "archive/zip" + "bytes" + "context" + "encoding/csv" + "encoding/xml" + "errors" + "fmt" + "io" + "path/filepath" + "strconv" + "strings" +) + +// ErrBatchPreviewNoRows 表示表格没有可供预检的商品行。 +var ErrBatchPreviewNoRows = errors.New("表格中没有有效数据行") + +// BatchPreviewCategory 是批量预检使用的纯应用类目模型。 +type BatchPreviewCategory struct { + // CatID 是平台类目标识。 + CatID string `json:"cat_id"` + // CatName 是平台类目名称。 + CatName string `json:"cat_name"` + // ChannelCatID 是平台频道类目标识。 + ChannelCatID string `json:"channel_cat_id,omitempty"` + // TBCatID 是可选的淘宝类目标识。 + TBCatID string `json:"tb_cat_id,omitempty"` +} + +// BatchPreviewCardAction 是单条自动发货卡券动作。 +type BatchPreviewCardAction struct { + // CardID 是卡券组标识。 + CardID int64 `json:"card_id"` + // DeliveryCount 是每件商品发送的卡密数量。 + DeliveryCount int `json:"delivery_count"` + // DelaySeconds 是发送动作的延迟秒数。 + DelaySeconds int `json:"delay_seconds"` +} + +// BatchPreviewCardAutomation 是自动发货卡券配置。 +type BatchPreviewCardAutomation struct { + // Enabled 表示是否启用该自动发货规则。 + Enabled bool `json:"enabled"` + // Actions 是按顺序执行的卡券动作。 + Actions []BatchPreviewCardAction `json:"actions"` + // ParseError 是原始动作文本的解析错误。 + ParseError string `json:"-"` +} + +// BatchPreviewReviewRequest 是求评价自动化配置。 +type BatchPreviewReviewRequest struct { + // Enabled 表示是否启用求评价规则。 + Enabled bool `json:"enabled"` + // AfterShippedHours 是发货后的等待小时数。 + AfterShippedHours int `json:"after_shipped_hours"` + // Message 是发送给买家的求评价文案。 + Message string `json:"message"` + // MaxAttempts 是最多提醒次数。 + MaxAttempts int `json:"max_attempts"` + // DelaySeconds 是提醒动作的延迟秒数。 + DelaySeconds int `json:"delay_seconds"` +} + +// BatchPreviewAutomation 是发布后自动化配置。 +type BatchPreviewAutomation struct { + // PaidDelivery 是付款后自动发货配置。 + PaidDelivery BatchPreviewCardAutomation `json:"paid_delivery"` + // ReviewGift 是评价后赠品配置。 + ReviewGift BatchPreviewCardAutomation `json:"review_gift"` + // ReviewRequest 是超时求评价配置。 + ReviewRequest BatchPreviewReviewRequest `json:"review_request"` +} + +// BatchPreviewRow 是表格一行经归一化和校验后的应用模型。 +type BatchPreviewRow struct { + // RowNo 是原始表格中的稳定行号,从表头后一行开始计数。 + RowNo int + // CookieID 是执行发布的账号标识。 + CookieID string + // Title 是商品标题。 + Title string + // Description 是商品描述;为空时回退为标题。 + Description string + // Price 是商品售价文本。 + Price string + // OriginalPrice 是商品原价文本。 + OriginalPrice string + // Quantity 是商品库存数量。 + Quantity int + // PostageMode 是归一化后的邮费模式。 + PostageMode string + // Postage 是固定邮费文本。 + Postage string + // Images 是商品图片引用列表。 + Images []string + // Category 是行指定或批次兜底类目。 + Category BatchPreviewCategory + // Automation 是发布后自动化配置。 + Automation BatchPreviewAutomation + // Errors 是该行所有可展示的预检错误。 + Errors []string + // Raw 是归一化前的原始字段副本。 + Raw map[string]any +} + +// BatchPreviewInput 是批量预检应用服务的输入。 +type BatchPreviewInput struct { + // UserID 是发起预检的用户标识。 + UserID int64 + // DefaultCookieID 是未指定账号行使用的默认账号。 + DefaultCookieID string + // UploadDir 是本地图片引用校验使用的受控目录。 + UploadDir string + // FallbackCategory 是未指定行类目使用的批次兜底类目。 + FallbackCategory BatchPreviewCategory + // Rows 是表格解析得到的字段行。 + Rows []map[string]any +} + +// BatchPreviewOwnershipPort 定义预检所需的非敏感归属查询。 +type BatchPreviewOwnershipPort interface { + // CookieOwned 判断账号是否属于指定用户。 + CookieOwned(context.Context, int64, string) (bool, error) + // CardOwned 判断卡券组是否属于指定用户。 + CardOwned(context.Context, int64, int64) (bool, error) +} + +// BatchPreviewImagePort 定义本地图片引用的安全校验能力。 +type BatchPreviewImagePort interface { + // ValidateImageReference 校验本地图片引用是否位于受控目录。 + ValidateImageReference(string, string) error +} + +// BatchPreviewService 负责表格行归一化和与基础设施无关的预检规则。 +type BatchPreviewService struct { + // ownership 提供账号和卡券的非敏感归属查询。 + ownership BatchPreviewOwnershipPort + // images 提供本地图片引用安全校验。 + images BatchPreviewImagePort +} + +// CookieOwned 判断账号是否属于用户,供 HTTP 适配器复核批次默认账号。 +func (service *BatchPreviewService) CookieOwned(ctx context.Context, userID int64, cookieID string) (bool, error) { + if service == nil || service.ownership == nil { + return false, errors.New("批量预检服务未初始化") + } + return service.ownership.CookieOwned(ctx, userID, strings.TrimSpace(cookieID)) +} + +// NewBatchPreviewService 创建批量预检服务并校验必需 Port。 +func NewBatchPreviewService(ownership BatchPreviewOwnershipPort, images BatchPreviewImagePort) (*BatchPreviewService, error) { + if ownership == nil { + return nil, errors.New("批量预检归属端口不能为空") + } + if images == nil { + return nil, errors.New("批量预检图片端口不能为空") + } + return &BatchPreviewService{ownership: ownership, images: images}, nil +} + +// ParseSheet 将 CSV、TSV 或 XLSX 字节解析为归一化字段映射。 +func ParseSheet(raw []byte, filename string, maxRows int) ([]map[string]any, error) { + if len(bytes.TrimSpace(raw)) == 0 { + return nil, errors.New("导入内容为空") + } + switch strings.ToLower(filepath.Ext(filename)) { + case ".xlsx": + return parseXLSXSheet(raw, maxRows) + case ".csv": + return parseDelimitedSheet(raw, ',', maxRows) + case ".tsv": + return parseDelimitedSheet(raw, '\t', maxRows) + case ".xls": + return nil, errors.New("暂不支持旧版 .xls,请另存为 .xlsx 或 CSV 后导入") + default: + return parseDelimitedSheet(raw, ',', maxRows) + } +} + +// Preview 归一化并校验所有表格行,保留逐行错误而不中断其他行。 +func (service *BatchPreviewService) Preview(ctx context.Context, input BatchPreviewInput) ([]BatchPreviewRow, error) { + if service == nil || service.ownership == nil || service.images == nil { + return nil, errors.New("批量预检服务未初始化") + } + if len(input.Rows) == 0 { + return nil, ErrBatchPreviewNoRows + } + // result 保存所有逐行预检结果。 + result := make([]BatchPreviewRow, 0, len(input.Rows)) + // index 和 fields 分别表示表格行索引及其字段。 + for index, fields := range input.Rows { + // row 保存当前归一化后的预检行。 + row := service.parseRow(ctx, input, index, fields) + result = append(result, row) + } + return result, nil +} + +// parseRow 将一条原始字段映射转换为应用行并执行所有确定性校验。 +func (service *BatchPreviewService) parseRow(ctx context.Context, input BatchPreviewInput, index int, fields map[string]any) BatchPreviewRow { + // row 保存当前输入映射转换出的应用行。 + row := BatchPreviewRow{ + RowNo: index + 2, CookieID: firstString(fields, "cookie_id", "账号ID", "账号id", "账号"), + Title: firstString(fields, "title", "标题", "商品标题", "商品名称"), + Description: firstString(fields, "description", "描述", "商品描述", "商品详情"), + Price: firstString(fields, "price", "价格", "商品价格"), OriginalPrice: firstString(fields, "original_price", "原价"), + PostageMode: firstString(fields, "postage_mode", "邮费模式"), Postage: firstString(fields, "postage", "邮费"), Raw: fields, + } + if row.CookieID == "" { + row.CookieID = input.DefaultCookieID + } + if row.Description == "" { + row.Description = row.Title + } + if row.PostageMode == "" { + row.PostageMode = "free" + } + row.PostageMode = normalizePostageMode(row.PostageMode) + row.Quantity = parseIntDefault(firstString(fields, "quantity", "库存", "数量"), 1) + row.Category = parseCategory(fields, input.FallbackCategory) + row.Automation = parseAutomation(fields) + row.Images = splitImageReferences(firstString(fields, "images", "image", "图片", "商品图片")) + if hasCategoryFields(fields) && (row.Category.CatID == "" || row.Category.CatName == "" || row.Category.ChannelCatID == "") { + row.Errors = append(row.Errors, "指定行类目时必须同时填写类目ID、类目名称和频道类目ID") + } + service.validateRow(ctx, input, &row) + return row +} + +// validateRow 将归属、金额、库存、图片和自动化规则错误写入当前行。 +func (service *BatchPreviewService) validateRow(ctx context.Context, input BatchPreviewInput, row *BatchPreviewRow) { + if row.CookieID == "" { + row.Errors = append(row.Errors, "缺少账号ID") + } else { // owned 和 err 表示账号归属查询结果。 + owned, err := service.ownership.CookieOwned(ctx, input.UserID, row.CookieID) + if err != nil || !owned { + row.Errors = append(row.Errors, "账号不存在或不属于当前用户") + } + } + if strings.TrimSpace(row.Title) == "" { + row.Errors = append(row.Errors, "缺少标题") + } + // cents 和 err 表示售价的分值及解析错误。 + if cents, err := parseMoneyCents(row.Price); err != nil || cents <= 0 { + row.Errors = append(row.Errors, "价格必须大于 0") + } + if strings.TrimSpace(row.OriginalPrice) != "" { + // cents 和 err 表示原价的分值及解析错误。 + if cents, err := parseMoneyCents(row.OriginalPrice); err != nil || cents <= 0 { + row.Errors = append(row.Errors, "原价格式错误") + } + } + if row.Quantity <= 0 { + row.Errors = append(row.Errors, "库存必须大于 0") + } + if row.PostageMode != "free" && row.PostageMode != "fixed" { + row.Errors = append(row.Errors, "邮费模式必须是 free 或 fixed") + } + if row.PostageMode == "fixed" { + // cents 和 err 表示固定邮费的分值及解析错误。 + if cents, err := parseMoneyCents(row.Postage); err != nil || cents < 0 { + row.Errors = append(row.Errors, "固定邮费格式错误") + } + } + if len(row.Images) == 0 { + row.Errors = append(row.Errors, "缺少图片") + } + if len(row.Images) > 9 { + row.Errors = append(row.Errors, "商品图片最多 9 张") + } + // reference 表示当前待校验的图片引用。 + for _, reference := range row.Images { + // err 表示图片引用安全校验错误。 + if err := service.images.ValidateImageReference(input.UploadDir, reference); err != nil { + row.Errors = append(row.Errors, err.Error()) + } + } + row.Errors = append(row.Errors, service.validateAutomation(ctx, input.UserID, row.Automation)...) +} + +// validateAutomation 校验卡券归属、动作范围和求评价配置。 +func (service *BatchPreviewService) validateAutomation(ctx context.Context, userID int64, config BatchPreviewAutomation) []string { + // errorsFound 保存当前行的自动化校验提示。 + var errorsFound []string + // validateCards 校验一组卡券动作及其用户归属。 + validateCards := func(cardConfig BatchPreviewCardAutomation, label string) { + if !cardConfig.Enabled { + return + } + if cardConfig.ParseError != "" { + errorsFound = append(errorsFound, label+cardConfig.ParseError) + return + } + if len(cardConfig.Actions) == 0 { + errorsFound = append(errorsFound, label+"需要至少配置一条发货内容") + return + } + // index 和 action 分别表示动作下标及动作配置。 + for index, action := range cardConfig.Actions { + // prefix 是当前动作的用户可见错误前缀。 + prefix := fmt.Sprintf("%s第%d项", label, index+1) + // owned 和 err 表示卡券归属查询结果。 + owned, err := service.ownership.CardOwned(ctx, userID, action.CardID) + if err != nil || !owned { + errorsFound = append(errorsFound, prefix+"卡密组不存在或不属于当前用户") + } + if action.DeliveryCount <= 0 { + errorsFound = append(errorsFound, prefix+"每件份数必须大于0") + } + if action.DelaySeconds < 0 || action.DelaySeconds > 3600 { + errorsFound = append(errorsFound, prefix+"延迟秒必须在 0 到 3600 之间") + } + } + } + validateCards(config.PaidDelivery, "付款发货") + validateCards(config.ReviewGift, "评价赠品") + if config.ReviewRequest.Enabled { + if config.ReviewRequest.AfterShippedHours <= 0 { + errorsFound = append(errorsFound, "求评价等待小时必须大于 0") + } + if strings.TrimSpace(config.ReviewRequest.Message) == "" { + errorsFound = append(errorsFound, "求评价文案不能为空") + } + if config.ReviewRequest.MaxAttempts <= 0 { + errorsFound = append(errorsFound, "求评价最多次数必须大于 0") + } + } + return errorsFound +} + +// parseDelimitedSheet 解析带逗号或制表符分隔的表格内容。 +func parseDelimitedSheet(raw []byte, delimiter rune, maxRows int) ([]map[string]any, error) { + // reader 负责读取分隔符表格。 + reader := csv.NewReader(bytes.NewReader(raw)) + reader.Comma = delimiter + reader.FieldsPerRecord = -1 + reader.LazyQuotes = true + // header 和 err 表示表头及读取错误。 + header, err := reader.Read() + if err != nil { + return nil, fmt.Errorf("解析表格失败: %w", err) + } + // keys 保存归一化后的表头名称。 + keys := normalizeHeaders(header) + // rows 保存非空数据行。 + rows := make([]map[string]any, 0, 64) + // seenDataRow 表示是否读取到表头之后的记录。 + seenDataRow := false + for { + // record 和 readErr 表示当前记录及其读取错误。 + record, readErr := reader.Read() + if readErr == io.EOF { + break + } + if readErr != nil { + return nil, fmt.Errorf("解析表格失败: %w", readErr) + } + seenDataRow = true + // row 和 nonEmpty 表示当前字段映射及是否包含数据。 + row, nonEmpty := rowMap(keys, record) + if !nonEmpty { + continue + } + rows = append(rows, row) + if maxRows > 0 && len(rows) > maxRows { + return nil, fmt.Errorf("单次最多解析 %d 行数据", maxRows) + } + } + if !seenDataRow { + return nil, errors.New("表格至少需要表头和一行数据") + } + return rows, nil +} + +// parseXLSXSheet 解析 XLSX 第一张工作表中的单元格文本。 +func parseXLSXSheet(raw []byte, maxRows int) ([]map[string]any, error) { + // archive 和 err 表示 XLSX 压缩包及打开错误。 + archive, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + return nil, fmt.Errorf("解析 xlsx 失败: %w", err) + } + // shared 和 err 表示共享字符串表及读取错误。 + shared, err := xlsxSharedStrings(archive) + if err != nil { + return nil, err + } + // sheet 保存第一张工作表的压缩文件。 + var sheet *zip.File + // file 表示当前遍历到的压缩包条目。 + for _, file := range archive.File { + if strings.HasPrefix(file.Name, "xl/worksheets/sheet") && strings.HasSuffix(file.Name, ".xml") { + sheet = file + break + } + } + if sheet == nil { + return nil, errors.New("xlsx 中未找到工作表") + } + // part 和 err 表示工作表 XML 内容及读取错误。 + part, err := readXLSXPart(sheet) + if err != nil { + return nil, err + } + // worksheet 保存反序列化后的工作表结构。 + var worksheet xlsxWorksheet + // err 表示工作表 XML 反序列化错误。 + if err := xml.Unmarshal(part, &worksheet); err != nil { + return nil, fmt.Errorf("解析工作表失败: %w", err) + } + // rows 保存工作表的文本行。 + rows := make([][]string, 0, len(worksheet.SheetData.Rows)) + // sheetRow 表示当前工作表行。 + for _, sheetRow := range worksheet.SheetData.Rows { + // values 保存当前行按列展开的文本值。 + values := []string{} + // cell 表示当前行的单元格。 + for _, cell := range sheetRow.Cells { + // index 表示单元格的零基列号。 + index := xlsxCellIndex(cell.Ref) + for len(values) <= index { + values = append(values, "") + } + values[index] = xlsxCellValue(cell, shared) + } + rows = append(rows, values) + } + if len(rows) < 2 { + return nil, errors.New("xlsx 至少需要表头和一行数据") + } + // keys 保存归一化后的表头名称。 + keys := normalizeHeaders(rows[0]) + // result 保存非空的应用字段行。 + result := make([]map[string]any, 0, len(rows)-1) + // values 表示当前数据行的单元格文本。 + for _, values := range rows[1:] { + // row 和 nonEmpty 表示当前字段映射及是否包含数据。 + row, nonEmpty := rowMap(keys, values) + if nonEmpty { + result = append(result, row) + } + } + if maxRows > 0 && len(result) > maxRows { + return nil, fmt.Errorf("单次最多解析 %d 行数据", maxRows) + } + return result, nil +} + +// xlsxWorksheet 保存 XLSX 工作表结构。 +type xlsxWorksheet struct { + // SheetData 是工作表中的行集合。 + SheetData struct { + // Rows 是工作表行集合。 + Rows []xlsxRow `xml:"row"` + } `xml:"sheetData"` +} + +// xlsxRow 保存一行 XLSX 单元格。 +type xlsxRow struct { + // Cells 是当前行的非空单元格集合。 + Cells []xlsxCell `xml:"c"` +} + +// xlsxCell 保存 XLSX 单元格原始值。 +type xlsxCell struct { + // Ref 是单元格引用,如 A1。 + Ref string `xml:"r,attr"` + // Type 是 XLSX 单元格类型。 + Type string `xml:"t,attr"` + // Value 是普通或共享字符串值。 + Value string `xml:"v"` + // InlineStr 是内联字符串值。 + InlineStr string `xml:"is>t"` +} + +// xlsxSST 保存 XLSX 共享字符串表。 +type xlsxSST struct { + // Items 是共享字符串条目。 + Items []struct { + // Inner 是富文本条目的 XML 内容。 + Inner string `xml:",innerxml"` + } `xml:"si"` +} + +// xlsxSharedStrings 读取 XLSX 共享字符串表。 +func xlsxSharedStrings(archive *zip.Reader) ([]string, error) { + // file 表示当前遍历到的共享字符串压缩条目。 + for _, file := range archive.File { + if file.Name != "xl/sharedStrings.xml" { + continue + } + // raw 和 err 表示共享字符串 XML 内容及读取错误。 + raw, err := readXLSXPart(file) + if err != nil { + return nil, err + } + // table 保存反序列化后的共享字符串表。 + var table xlsxSST + // err 表示共享字符串 XML 反序列化错误。 + if err := xml.Unmarshal(raw, &table); err != nil { + return nil, err + } + // values 保存可直接引用的共享字符串。 + values := make([]string, 0, len(table.Items)) + // item 表示当前共享字符串条目。 + for _, item := range table.Items { + values = append(values, xmlCharData(item.Inner)) + } + return values, nil + } + return nil, nil +} + +// readXLSXPart 读取单个 XLSX XML 部件并限制其大小。 +func readXLSXPart(file *zip.File) ([]byte, error) { + // reader 和 err 表示 XML 部件读取器及打开错误。 + reader, err := file.Open() + if err != nil { + return nil, err + } + defer reader.Close() + // maxXMLPartBytes 限制单个 XML 部件的内存读取规模,并保持上传解析的 32 MiB 上限。 + const maxXMLPartBytes = 32 << 20 + // raw 和 err 表示 XML 部件内容及读取错误。 + raw, err := io.ReadAll(io.LimitReader(reader, maxXMLPartBytes+1)) + if err != nil { + return nil, err + } + if len(raw) > maxXMLPartBytes { + return nil, fmt.Errorf("xlsx 内部 XML 超过 %d MiB", maxXMLPartBytes>>20) + } + return raw, nil +} + +// xlsxCellValue 按单元格类型提取可用于预检的文本值。 +func xlsxCellValue(cell xlsxCell, shared []string) string { + switch cell.Type { + case "s": + // index 表示共享字符串表中的索引。 + index, _ := strconv.Atoi(strings.TrimSpace(cell.Value)) + if index >= 0 && index < len(shared) { + return shared[index] + } + case "inlineStr": + return strings.TrimSpace(cell.InlineStr) + } + return strings.TrimSpace(cell.Value) +} + +// xlsxCellIndex 将 XLSX 单元格引用转换为零基列索引。 +func xlsxCellIndex(reference string) int { + // index 保存转换后的列索引。 + index := 0 + // char 表示单元格引用中的当前列字符。 + for _, char := range reference { + if char < 'A' || char > 'Z' { + break + } + index = index*26 + int(char-'A'+1) + } + if index == 0 { + return 0 + } + return index - 1 +} + +// xmlCharData 从富文本 XML 中拼接所有字符数据。 +func xmlCharData(inner string) string { + // decoder 负责读取富文本 XML 字符数据。 + decoder := xml.NewDecoder(strings.NewReader("" + inner + "")) + // parts 保存拼接前的字符片段。 + var parts []string + for { + // token 和 err 表示当前 XML 令牌及读取错误。 + token, err := decoder.Token() + if err != nil { + break + } + // character 和 ok 表示字符数据及类型判断结果。 + if character, ok := token.(xml.CharData); ok { + parts = append(parts, string(character)) + } + } + return strings.Join(parts, "") +} + +// normalizeHeaders 将用户表头映射为稳定的应用字段名。 +func normalizeHeaders(headers []string) []string { + // keys 保存归一化后的字段名。 + keys := make([]string, len(headers)) + // index 和 header 表示表头下标及原始文本。 + for index, header := range headers { + keys[index] = normalizeHeader(header) + } + return keys +} + +// rowMap 将一行单元格按表头映射为字符串字段。 +func rowMap(keys, values []string) (map[string]any, bool) { + // result 保存表头到单元格值的映射。 + result := map[string]any{} + // nonEmpty 表示当前行是否包含有效文本。 + nonEmpty := false + // index 和 key 表示当前列下标及归一化字段名。 + for index, key := range keys { + if key == "" || index >= len(values) { + continue + } + // value 保存当前单元格的裁剪后文本。 + value := strings.TrimSpace(values[index]) + if value != "" { + nonEmpty = true + } + result[key] = value + } + return result, nonEmpty +} + +// normalizeHeader 将中英文表头归一化为应用字段名。 +func normalizeHeader(header string) string { + // value 保存去除空白和分隔符后的表头文本。 + value := strings.ToLower(strings.TrimSpace(header)) + value = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(value) + switch value { + case "cookieid", "账号id", "账号", "闲鱼账号": + return "cookie_id" + case "title", "itemtitle", "标题", "商品标题", "商品名称": + return "title" + case "description", "desc", "itemdescription", "描述", "商品描述", "商品详情": + return "description" + case "price", "itemprice", "价格", "商品价格": + return "price" + case "originalprice", "原价": + return "original_price" + case "quantity", "库存", "数量": + return "quantity" + case "postagemode", "邮费模式": + return "postage_mode" + case "postage", "邮费": + return "postage" + case "images", "image", "图片", "商品图片": + return "images" + case "categoryid", "catid", "类目id", "商品类目id": + return "category_id" + case "categoryname", "catname", "类目名称", "商品类目名称", "类目": + return "category_name" + case "channelcategoryid", "channelcatid", "频道类目id": + return "channel_category_id" + case "tbcategoryid", "tbcatid", "淘宝类目id": + return "tb_category_id" + case "paiddeliveryenabled", "付款发货启用", "付款后自动发货": + return "paid_delivery_enabled" + case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密": + return "paid_delivery_contents" + case "reviewgiftenabled", "评价赠品启用", "评价后发送赠品": + return "review_gift_enabled" + case "reviewgiftcontents", "评价赠品内容", "评价后发送的卡密": + return "review_gift_contents" + case "reviewrequestenabled", "求评价启用", "超时未评价时提醒": + return "review_request_enabled" + case "reviewrequestafterhours", "求评价等待小时", "发货几小时后提醒": + return "review_request_after_hours" + case "reviewrequestmessage", "求评价文案", "提醒内容": + return "review_request_message" + case "reviewrequestmaxattempts", "求评价最多次数", "最多提醒几次": + return "review_request_max_attempts" + case "reviewrequestdelayseconds", "求评价延迟秒": + return "review_request_delay_seconds" + default: + return strings.TrimSpace(header) + } +} + +// firstString 从字段映射中返回首个非空字符串。 +func firstString(fields map[string]any, keys ...string) string { + // key 表示当前候选字段名。 + for _, key := range keys { + // value 和 ok 表示字段原始值及是否存在。 + if value, ok := fields[key]; ok { + // text 保存字段的字符串表示。 + text := stringValue(value) + if strings.TrimSpace(text) != "" { + return strings.TrimSpace(text) + } + } + } + return "" +} + +// stringValue 将常见表格值转换为文本。 +func stringValue(value any) string { + // typed 保存类型断言后的常见表格值。 + switch typed := value.(type) { + case nil: + return "" + case string: + return typed + case float64: + return strconv.FormatFloat(typed, 'f', -1, 64) + case float32: + return strconv.FormatFloat(float64(typed), 'f', -1, 32) + case int: + return strconv.Itoa(typed) + case int64: + return strconv.FormatInt(typed, 10) + case bool: + return strconv.FormatBool(typed) + default: + return fmt.Sprint(typed) + } +} + +// parseIntDefault 将数字文本转换为整数,失败时返回默认值。 +func parseIntDefault(raw string, fallback int) int { + if strings.TrimSpace(raw) == "" { + return fallback + } + // value 和 err 表示解析后的数字及转换错误。 + value, err := strconv.ParseFloat(strings.TrimSpace(raw), 64) + if err != nil { + return fallback + } + return int(value) +} + +// normalizePostageMode 将用户邮费模式映射为平台使用的稳定值。 +func normalizePostageMode(raw string) string { + // value 保存归一化前的邮费模式文本。 + value := strings.ToLower(strings.TrimSpace(raw)) + switch value { + case "包邮", "free_shipping": + return "free" + case "固定邮费", "一口价邮费": + return "fixed" + default: + return value + } +} + +// parseCategory 解析行类目并在未指定时使用批次兜底类目。 +func parseCategory(fields map[string]any, fallback BatchPreviewCategory) BatchPreviewCategory { + // category 保存行指定或兜底前的类目配置。 + category := BatchPreviewCategory{CatID: firstString(fields, "category_id", "类目ID", "商品类目ID"), CatName: firstString(fields, "category_name", "类目名称", "商品类目名称", "类目"), ChannelCatID: firstString(fields, "channel_category_id", "频道类目ID"), TBCatID: firstString(fields, "tb_category_id", "淘宝类目ID")} + if category.CatID == "" && category.CatName == "" && category.ChannelCatID == "" && category.TBCatID == "" { + return fallback + } + return category +} + +// hasCategoryFields 判断原始行是否显式提供了类目字段。 +func hasCategoryFields(fields map[string]any) bool { + return firstString(fields, "category_id", "类目ID", "商品类目ID") != "" || firstString(fields, "category_name", "类目名称", "商品类目名称", "类目") != "" || firstString(fields, "channel_category_id", "频道类目ID") != "" || firstString(fields, "tb_category_id", "淘宝类目ID") != "" +} + +// parseAutomation 解析表格中的自动化配置文本。 +func parseAutomation(fields map[string]any) BatchPreviewAutomation { + // paidActions 和 paidError 表示付款发货动作及解析错误。 + paidActions, paidError := parseCardActions(firstString(fields, "paid_delivery_contents", "付款发货内容")) + // reviewActions 和 reviewError 表示评价赠品动作及解析错误。 + reviewActions, reviewError := parseCardActions(firstString(fields, "review_gift_contents", "评价赠品内容")) + return BatchPreviewAutomation{ + PaidDelivery: BatchPreviewCardAutomation{Enabled: parseBool(firstString(fields, "paid_delivery_enabled", "付款发货启用")), Actions: paidActions, ParseError: paidError}, + ReviewGift: BatchPreviewCardAutomation{Enabled: parseBool(firstString(fields, "review_gift_enabled", "评价赠品启用")), Actions: reviewActions, ParseError: reviewError}, + ReviewRequest: BatchPreviewReviewRequest{Enabled: parseBool(firstString(fields, "review_request_enabled", "求评价启用")), AfterShippedHours: parseIntDefault(firstString(fields, "review_request_after_hours", "求评价等待小时"), 72), Message: firstString(fields, "review_request_message", "求评价文案"), MaxAttempts: parseIntDefault(firstString(fields, "review_request_max_attempts", "求评价最多次数"), 1), DelaySeconds: parseIntDefault(firstString(fields, "review_request_delay_seconds", "求评价延迟秒"), 0)}, + } +} + +// parseCardActions 解析卡券组 ID、数量和延迟秒组成的动作文本。 +func parseCardActions(raw string) ([]BatchPreviewCardAction, string) { + // entries 保存按分隔符拆出的卡券动作文本。 + entries := strings.FieldsFunc(strings.TrimSpace(raw), func(char rune) bool { return char == ';' || char == ';' || char == '\n' || char == '\r' }) + if len(entries) == 0 { + return nil, "" + } + // actions 保存解析后的卡券动作。 + actions := make([]BatchPreviewCardAction, 0, len(entries)) + // index 和 entry 表示动作序号及原始动作文本。 + for index, entry := range entries { + // parts 保存动作的 ID、数量和延迟字段。 + parts := strings.Split(strings.ReplaceAll(strings.TrimSpace(entry), ":", ":"), ":") + if len(parts) < 1 || len(parts) > 3 || strings.TrimSpace(parts[0]) == "" { + return nil, fmt.Sprintf("第%d项格式错误,应为 卡密组ID:每件份数:延迟秒", index+1) + } + // cardID 和 err 表示卡券组标识及解析错误。 + cardID, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64) + if err != nil || cardID <= 0 { + return nil, fmt.Sprintf("第%d项卡密组ID无效", index+1) + } + // count 和 delay 保存默认的每件数量及延迟秒数。 + count, delay := 1, 0 + if len(parts) >= 2 && strings.TrimSpace(parts[1]) != "" { + count, err = strconv.Atoi(strings.TrimSpace(parts[1])) + if err != nil || count <= 0 { + return nil, fmt.Sprintf("第%d项每件份数必须大于0", index+1) + } + } + if len(parts) == 3 && strings.TrimSpace(parts[2]) != "" { + delay, err = strconv.Atoi(strings.TrimSpace(parts[2])) + if err != nil || delay < 0 { + return nil, fmt.Sprintf("第%d项延迟秒不能小于0", index+1) + } + } + actions = append(actions, BatchPreviewCardAction{CardID: cardID, DeliveryCount: count, DelaySeconds: delay}) + } + return actions, "" +} + +// parseBool 将常见真值文本转换为布尔值。 +func parseBool(raw string) bool { + switch strings.ToLower(strings.TrimSpace(raw)) { + case "1", "true", "yes", "y", "on", "是", "开启", "启用": + return true + default: + return false + } +} + +// splitImageReferences 将分号或换行分隔的图片引用转换为列表。 +func splitImageReferences(raw string) []string { + // value 保存统一使用分号分隔的图片引用文本。 + value := strings.ReplaceAll(strings.ReplaceAll(raw, "\n", ";"), ";", ";") + // parts 保存拆分后的原始图片引用。 + parts := strings.Split(value, ";") + // result 保存去除空白后的图片引用。 + result := make([]string, 0, len(parts)) + // part 表示当前原始图片引用。 + for _, part := range parts { + // text 表示当前图片引用的裁剪文本。 + if text := strings.TrimSpace(part); text != "" { + result = append(result, text) + } + } + return result +} + +// parseMoneyCents 将金额文本转换为分值并拒绝超过两位小数的输入。 +func parseMoneyCents(raw string) (int64, error) { + // value 保存移除货币符号后的金额文本。 + value := strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(raw), "¥"), "¥") + if value == "" { + return 0, nil + } + // sign 保存金额正负号。 + sign := int64(1) + if strings.HasPrefix(value, "-") { + sign, value = -1, strings.TrimPrefix(value, "-") + } else { + value = strings.TrimPrefix(value, "+") + } + // parts 保存整数和小数部分。 + parts := strings.Split(value, ".") + if len(parts) > 2 { + return 0, errors.New("金额格式错误") + } + // yuan 和 err 表示整数元及解析错误。 + yuan, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64) + if err != nil { + return 0, err + } + // frac 保存最多两位的小数部分。 + frac := "" + if len(parts) == 2 { + frac = strings.TrimSpace(parts[1]) + if len(frac) > 2 { + return 0, errors.New("金额最多支持两位小数") + } + } + for len(frac) < 2 { + frac += "0" + } + // cents 保存最终的分值结果。 + cents := int64(0) + if frac != "" { + cents, err = strconv.ParseInt(frac, 10, 64) + if err != nil { + return 0, err + } + } + return sign * (yuan*100 + cents), nil +} diff --git a/internal/application/items/batch_preview_persistence.go b/internal/application/items/batch_preview_persistence.go new file mode 100644 index 0000000..2fd1c6f --- /dev/null +++ b/internal/application/items/batch_preview_persistence.go @@ -0,0 +1,94 @@ +package items + +import ( + "context" + "errors" +) + +// BatchPreviewPersistenceBatch 是预检批次的非敏感持久化元数据。 +type BatchPreviewPersistenceBatch struct { + // ID 是后续启动发布任务使用的批次标识。 + ID string + // UserID 是发起批次导入的用户标识。 + UserID int64 + // DefaultCookieID 是未指定账号行使用的默认账号。 + DefaultCookieID string + // Filename 是用户上传的原始表格文件名。 + Filename string + // UploadDir 是受控上传目录,供后续 worker 读取图片。 + UploadDir string + // Location 是批次统一使用的发货地。 + Location Location + // Status 是创建时的批次状态。 + Status string +} + +// BatchPreviewPersistenceRepository 定义预检批次落库所需的最小数据库端口。 +type BatchPreviewPersistenceRepository interface { + // CreateBatch 在一个持久化边界内创建批次和全部明细。 + CreateBatch(context.Context, BatchPreviewPersistenceBatch, []BatchPreviewRow) error + // RecountBatch 重算批次的成功和失败统计。 + RecountBatch(context.Context, string) error +} + +// BatchPreviewPersistenceResult 是预检接口返回的应用层结果。 +type BatchPreviewPersistenceResult struct { + // Success 表示预检结果已成功持久化。 + Success bool + // PreviewID 是后续启动批量发布使用的批次标识。 + PreviewID string + // Total 是预检行总数。 + Total int + // Valid 是没有校验错误的行数。 + Valid int + // Invalid 是包含校验错误的行数。 + Invalid int + // Rows 是逐行预检结果。 + Rows []BatchPreviewRow +} + +// BatchPreviewPersistenceService 负责预检结果计数和批次落库编排。 +type BatchPreviewPersistenceService struct { + // repository 提供数据库批次写入能力。 + repository BatchPreviewPersistenceRepository +} + +// NewBatchPreviewPersistenceService 创建预检持久化应用服务。 +func NewBatchPreviewPersistenceService(repository BatchPreviewPersistenceRepository) (*BatchPreviewPersistenceService, error) { + if repository == nil { + return nil, errors.New("预检持久化端口不能为空") + } + return &BatchPreviewPersistenceService{repository: repository}, nil +} + +// Persist 持久化逐行预检结果并返回兼容前端的应用模型。 +func (service *BatchPreviewPersistenceService) Persist(ctx context.Context, batch BatchPreviewPersistenceBatch, rows []BatchPreviewRow) (BatchPreviewPersistenceResult, error) { + if service == nil || service.repository == nil { + return BatchPreviewPersistenceResult{}, errors.New("预检持久化服务未初始化") + } + if len(rows) == 0 { + return BatchPreviewPersistenceResult{}, ErrBatchPreviewNoRows + } + // valid 和 invalid 保存预检通过与失败的行数。 + valid := 0 + // invalid 保存包含校验错误的预检行数。 + invalid := 0 + // row 表示当前参与统计的预检行。 + for _, row := range rows { + if len(row.Errors) == 0 { + valid++ + } else { + invalid++ + } + } + if batch.Status == "" { + batch.Status = "preview" + } + // err 表示批次及明细写入错误。 + if err := service.repository.CreateBatch(ctx, batch, rows); err != nil { + return BatchPreviewPersistenceResult{}, errors.Join(errors.New("保存预检结果失败"), err) + } + // recountErr 保存统计重算结果;旧接口在批次已写入后仍返回预检成功,因此保留该兼容语义。 + _ = service.repository.RecountBatch(ctx, batch.ID) + return BatchPreviewPersistenceResult{Success: true, PreviewID: batch.ID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: rows}, nil +} diff --git a/internal/application/items/batch_preview_test.go b/internal/application/items/batch_preview_test.go new file mode 100644 index 0000000..6004f54 --- /dev/null +++ b/internal/application/items/batch_preview_test.go @@ -0,0 +1,160 @@ +package items + +import ( + "context" + "errors" + "strings" + "testing" +) + +// batchPreviewOwnershipFake 是批量预检使用的账号与卡券归属替身。 +type batchPreviewOwnershipFake struct { + // cookieOwned 表示允许通过预检的账号标识。 + cookieOwned string + // cardOwned 表示允许通过预检的卡券组标识。 + cardOwned int64 + // err 模拟归属查询故障。 + err error +} + +// CookieOwned 返回预置的账号归属结果。 +func (fake batchPreviewOwnershipFake) CookieOwned(_ context.Context, _ int64, cookieID string) (bool, error) { + return cookieID == fake.cookieOwned, fake.err +} + +// CardOwned 返回预置的卡券组归属结果。 +func (fake batchPreviewOwnershipFake) CardOwned(_ context.Context, _ int64, cardID int64) (bool, error) { + return cardID == fake.cardOwned, fake.err +} + +// batchPreviewImageFake 是批量预检使用的图片引用校验替身。 +type batchPreviewImageFake struct { + // invalid 保存应被拒绝的图片引用。 + invalid string +} + +// ValidateImageReference 拒绝预置的图片引用并接受其他引用。 +func (fake batchPreviewImageFake) ValidateImageReference(_ string, reference string) error { + if reference == fake.invalid { + return errors.New("图片文件不存在: " + reference) + } + return nil +} + +// TestParseSheetNormalizesCSV 验证 CSV 表头、字段和行上限归一化。 +func TestParseSheetNormalizesCSV(t *testing.T) { + // rows 和 err 表示解析后的字段行及解析错误。 + rows, err := ParseSheet([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,a.png\n"), "products.csv", 2) + if err != nil { + t.Fatalf("ParseSheet() error = %v", err) + } + if len(rows) != 1 || rows[0]["cookie_id"] != "acc1" || rows[0]["title"] != "商品A" { + t.Fatalf("ParseSheet() rows = %#v", rows) + } +} + +// TestParseSheetRejectsEmptyAndUnsupportedInput 验证空输入、旧版 XLS 和表头缺行错误。 +func TestParseSheetRejectsEmptyAndUnsupportedInput(t *testing.T) { + // cases 保存不同无效表格输入。 + cases := []struct { + // name 是当前输入场景名称。 + name string + // raw 是待解析的表格内容。 + raw []byte + // filename 是用于选择解析器的文件名。 + filename string + }{ + {name: "empty", raw: []byte(" \n"), filename: "x.csv"}, + {name: "xls", raw: []byte("x"), filename: "x.xls"}, + {name: "header-only", raw: []byte("标题,价格\n"), filename: "x.csv"}, + } + // testCase 表示当前无效输入样例。 + for _, testCase := range cases { + // err 表示当前样例的解析错误。 + if _, err := ParseSheet(testCase.raw, testCase.filename, 0); err == nil { + t.Errorf("ParseSheet(%s) expected error", testCase.name) + } + } +} + +// TestBatchPreviewValidatesBusinessRules 验证预检服务的归属、金额、类目、图片和自动化规则。 +func TestBatchPreviewValidatesBusinessRules(t *testing.T) { + // service 和 err 表示批量预检服务及构造错误。 + service, err := NewBatchPreviewService(batchPreviewOwnershipFake{cookieOwned: "acc1", cardOwned: 9}, batchPreviewImageFake{invalid: "missing.png"}) + if err != nil { + t.Fatalf("NewBatchPreviewService() error = %v", err) + } + // rows 和 err 表示逐行预检结果及执行错误。 + rows, err := service.Preview(context.Background(), BatchPreviewInput{ + UserID: 7, DefaultCookieID: "acc1", UploadDir: "/tmp/uploads", + FallbackCategory: BatchPreviewCategory{CatID: "5001", CatName: "虚拟商品", ChannelCatID: "6001"}, + Rows: []map[string]any{ + {"标题": "商品A", "价格": "12.50", "图片": "a.png", "付款发货启用": "true", "付款发货内容": "9:2:10"}, + {"账号ID": "other", "标题": "", "价格": "0", "库存": "0", "图片": "missing.png", "类目ID": "1"}, + }, + }) + if err != nil { + t.Fatalf("Preview() error = %v", err) + } + if len(rows) != 2 { + t.Fatalf("Preview() rows = %#v", rows) + } + if len(rows[0].Errors) != 0 || rows[0].CookieID != "acc1" || rows[0].Category.CatID != "5001" || len(rows[0].Automation.PaidDelivery.Actions) != 1 { + t.Fatalf("valid row = %#v", rows[0]) + } + // joined 保存无效行的拼接错误文本。 + joined := strings.Join(rows[1].Errors, "|") + // expected 表示当前必须出现的错误片段。 + for _, expected := range []string{"账号不存在或不属于当前用户", "缺少标题", "价格必须大于 0", "库存必须大于 0", "图片文件不存在", "指定行类目时必须同时填写"} { + if !strings.Contains(joined, expected) { + t.Errorf("invalid row errors %q missing %q", joined, expected) + } + } +} + +// TestBatchPreviewParsesMultipleAutomationActions 验证应用层保留多条卡密动作和开关语义。 +func TestBatchPreviewParsesMultipleAutomationActions(t *testing.T) { + // service 和 err 表示批量预检服务及构造错误。 + service, err := NewBatchPreviewService(batchPreviewOwnershipFake{cookieOwned: "acc1", cardOwned: 101}, batchPreviewImageFake{}) + if err != nil { + t.Fatalf("NewBatchPreviewService() error = %v", err) + } + // rows 和 previewErr 表示应用层解析后的逐行结果。 + rows, previewErr := service.Preview(context.Background(), BatchPreviewInput{ + UserID: 7, DefaultCookieID: "acc1", UploadDir: "/tmp/uploads", + Rows: []map[string]any{{"标题": "商品", "价格": "1", "图片": "a.png", "付款发货启用": "是", "付款发货内容": "101:1:0;102:2:3"}}, + }) + if previewErr != nil || len(rows) != 1 { + t.Fatalf("Preview() rows=%#v err=%v", rows, previewErr) + } + // actions 保存应用层解析出的付款发货动作顺序和参数。 + actions := rows[0].Automation.PaidDelivery.Actions + if len(actions) != 2 || actions[0].CardID != 101 || actions[1].DeliveryCount != 2 || actions[1].DelaySeconds != 3 { + t.Fatalf("parsed actions=%#v", actions) + } +} + +// TestBatchPreviewRejectsMissingPorts 验证服务构造时拒绝缺失基础设施 Port。 +func TestBatchPreviewRejectsMissingPorts(t *testing.T) { + // images 和 ownership 是缺失 Port 检查使用的替身。 + images := batchPreviewImageFake{} + // ownership 是账号与卡券归属查询替身。 + ownership := batchPreviewOwnershipFake{} + // err 表示缺失归属 Port 的构造结果。 + if _, err := NewBatchPreviewService(nil, images); err == nil { + t.Error("missing ownership port should fail") + } + // err 表示缺失图片 Port 的构造结果。 + if _, err := NewBatchPreviewService(ownership, nil); err == nil { + t.Error("missing image port should fail") + } + // service 和 err 表示完整 Port 构造结果。 + service, err := NewBatchPreviewService(ownership, images) + if err != nil { + t.Fatalf("NewBatchPreviewService() error = %v", err) + } + // err 表示空输入的预检错误。 + if _, err := service.Preview(context.Background(), BatchPreviewInput{}); !errors.Is(err, ErrBatchPreviewNoRows) { + t.Fatalf("empty preview error = %v", err) + } +} diff --git a/internal/application/items/batch_publish.go b/internal/application/items/batch_publish.go index 7804435..c06bd80 100644 --- a/internal/application/items/batch_publish.go +++ b/internal/application/items/batch_publish.go @@ -17,6 +17,8 @@ type BatchRow struct { ID int64 // BatchID 是所属批次标识。 BatchID string + // RowNo 是导入文件中的稳定行号,用于保持发布顺序和导出结果对应关系。 + RowNo int // CookieID 是执行发布的账号标识。 CookieID string // Title 是商品标题。 @@ -45,6 +47,18 @@ type BatchRow struct { ItemID string // ItemURL 是已知的平台商品地址。 ItemURL string + // Status 是明细当前状态,供管理查询和 worker 过滤使用。 + Status string + // ErrorMessage 是最近一次失败的用户可见原因,不包含凭证内容。 + ErrorMessage string + // FailureKind 是失败分类,用于区分可重试、校验失败和远端结果不确定。 + FailureKind string + // WorkerToken 是当前处理租约令牌,仅用于适配器状态复核。 + WorkerToken string + // CreatedAt 是明细创建时间文本,沿用数据库时间格式。 + CreatedAt string + // UpdatedAt 是明细最近更新时间文本,沿用数据库时间格式。 + UpdatedAt string } // BatchInfo 是批量发布状态收口所需的非敏感批次信息。 @@ -57,10 +71,26 @@ type BatchInfo struct { Status string // WorkerToken 是当前租约令牌。 WorkerToken string + // DefaultCookieID 是未指定账号行使用的默认发布账号。 + DefaultCookieID string + // Filename 是用户上传的原始表格文件名。 + Filename string // UploadDir 是批次上传文件的受控目录。 UploadDir string // LocationJSON 是批次统一发货地配置的 JSON。 LocationJSON string + // TotalCount 是批次明细总数。 + TotalCount int + // SuccessCount 是已成功发布的明细数。 + SuccessCount int + // FailedCount 是已失败的明细数。 + FailedCount int + // LeaseExpiresAt 是当前 worker 租约的 Unix 秒时间戳。 + LeaseExpiresAt int64 + // CreatedAt 是批次创建时间文本,沿用数据库时间格式。 + CreatedAt string + // UpdatedAt 是批次最近更新时间文本,沿用数据库时间格式。 + UpdatedAt string } // BatchRepository 是批量发布 worker 所需的最小持久化端口。 @@ -95,6 +125,88 @@ type BatchPublisher interface { PublishRow(context.Context, int64, BatchRow, string) error } +// PostPublishError 表示平台发布成功后,响应 Cookie 或本地后置步骤未能完成。 +// 该错误会阻止当前行自动重试,避免重复创建远端商品。 +type PostPublishError struct { + // Err 保存不含凭证内容的后置处理错误。 + Err error +} + +// Error 返回后置处理错误文本。 +func (e *PostPublishError) Error() string { + if e == nil || e.Err == nil { + return "批量发布后置处理失败" + } + return e.Err.Error() +} + +// Unwrap 暴露后置处理的原始错误供分类逻辑检查。 +func (e *PostPublishError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + +// UncertainRemotePublishError 表示远端请求结果未知且检查点未可靠保存。 +// 该错误禁止自动重试,必须由用户核对平台商品状态。 +type UncertainRemotePublishError struct { + // Err 保存远端结果不确定的原因,不得包含 Cookie 明文。 + Err error +} + +// Error 返回远端结果不确定的错误文本。 +func (e *UncertainRemotePublishError) Error() string { + if e == nil || e.Err == nil { + return "远端发布结果未知" + } + return e.Err.Error() +} + +// Unwrap 暴露远端结果不确定的原始错误。 +func (e *UncertainRemotePublishError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + +// BatchPublishResult 是批量平台端口返回的非敏感商品结果。 +type BatchPublishResult struct { + // ItemID 是平台商品标识。 + ItemID string + // ItemURL 是平台商品地址。 + ItemURL string + // Title 是平台确认后的商品标题。 + Title string + // PriceText 是平台确认后的价格文本。 + PriceText string + // CategoryID 是平台确认后的类目标识。 + CategoryID string + // CategoryName 是平台确认后的类目名称。 + CategoryName string + // ImageURL 是平台返回的主图地址。 + ImageURL string + // Quantity 是平台确认后的库存数量。 + Quantity int + // RawData 是平台原始结果的结构化数据,仅用于受控本地持久化。 + RawData map[string]any +} + +// BatchPublishOutcome 是批量平台端口的结果及响应 Cookie 后置错误。 +type BatchPublishOutcome struct { + // Result 是平台商品结果;重试已保存远端结果的行也会提供该字段。 + Result *BatchPublishResult + // ResponseCookieErr 是发布成功后 Cookie 会话写回失败,不包含 Cookie 内容。 + ResponseCookieErr error +} + +// BatchPublishPort 定义单行批量远端发布能力;凭证和平台 DTO 由适配器内部处理。 +type BatchPublishPort interface { + // PublishRemoteRow 执行远端发布并保存远端检查点,不负责商品自动化规则。 + PublishRemoteRow(context.Context, int64, BatchRow, string) (BatchPublishOutcome, error) +} + // FailureClassifier 将发布错误转换为用户可见消息和稳定失败分类。 type FailureClassifier func(error, string) (string, string) @@ -190,13 +302,17 @@ func (runner *BatchRunner) Run(ctx context.Context, userID int64, batchID, worke } // rowErr 保存当前商品发布及本地结果落库错误。 if rowErr := runner.publisher.PublishRow(ctx, userID, row, workerToken); rowErr != nil { + // statusCtx、statusCancel 让外部动作已返回后的失败事实写入不受请求取消影响,并限制补偿等待时间。 + statusCtx, statusCancel := statusContext(ctx) // status 保存失败分类所需的批次状态。 - status, _ := runner.repository.BatchStatus(ctx, batchID) + status, _ := runner.repository.BatchStatus(statusCtx, batchID) // message、failureKind 保存用户可见失败信息和稳定分类。 message, failureKind := runner.options.ClassifyFailure(rowErr, status) // marked、markErr 保存失败状态是否成功写入及其错误。 - marked, markErr := runner.repository.MarkClaimedRowFailed(ctx, row.ID, workerToken, message, failureKind) + marked, markErr := runner.repository.MarkClaimedRowFailed(statusCtx, row.ID, workerToken, message, failureKind) + statusCancel() if markErr != nil || !marked { + runner.finishInterrupted(ctx, userID, batchID, workerToken) return fmt.Errorf("保存批量发布失败状态失败: %w", firstNonNil(markErr, ErrBatchLeaseLost)) } if runner.options.IsSessionExpired(rowErr) { @@ -204,8 +320,15 @@ func (runner *BatchRunner) Run(ctx context.Context, userID int64, batchID, worke return rowErr } } + // recountCtx、recountCancel 让失败明细或外部动作完成后的本地统计重算不受请求取消影响。 + recountCtx, recountCancel := statusContext(ctx) // recountErr 保存批次统计重算错误。 - if recountErr := runner.repository.RecountBatch(ctx, batchID); recountErr != nil { + recountErr := runner.repository.RecountBatch(recountCtx, batchID) + recountCancel() + if recountErr != nil { + if ctx.Err() != nil { + runner.finishInterrupted(ctx, userID, batchID, workerToken) + } return recountErr } if rowIndex < len(rows)-1 { diff --git a/internal/application/items/batch_publish_test.go b/internal/application/items/batch_publish_test.go index 550c9f1..8a7721f 100644 --- a/internal/application/items/batch_publish_test.go +++ b/internal/application/items/batch_publish_test.go @@ -45,7 +45,11 @@ func (r *batchRunnerRepository) BatchStatus(_ context.Context, _ string) (string } // MarkClaimedRowFailed 记录失败消息。 -func (r *batchRunnerRepository) MarkClaimedRowFailed(_ context.Context, rowID int64, _, message, _ string) (bool, error) { +func (r *batchRunnerRepository) MarkClaimedRowFailed(ctx context.Context, rowID int64, _, message, _ string) (bool, error) { + // err 表示状态补偿 Context 已被取消的原因。 + if err := ctx.Err(); err != nil { + return false, err + } if r.failed == nil { r.failed = make(map[int64]string) } diff --git a/internal/application/items/batch_recovery.go b/internal/application/items/batch_recovery.go new file mode 100644 index 0000000..32e57c6 --- /dev/null +++ b/internal/application/items/batch_recovery.go @@ -0,0 +1,149 @@ +package items + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "strconv" + "time" +) + +// BatchRecoveryRepository 定义批量发布恢复扫描器所需的最小状态端口。 +type BatchRecoveryRepository interface { + // RecoverableBatches 查询租约已过期或进程中断后可接管的批次。 + RecoverableBatches(context.Context, int64, int) ([]BatchInfo, error) + // FinalizeExpiredCancellation 收口已过期的取消请求。 + FinalizeExpiredCancellation(context.Context, string, int64) (bool, error) + // ClaimBatch 抢占批次恢复租约。 + ClaimBatch(context.Context, string, string, int64) (bool, error) + // ResetInterrupted 只重置确认由进程中断造成的失败明细。 + ResetInterrupted(context.Context, string) error + // RecountBatch 重算批次当前统计。 + RecountBatch(context.Context, string) error + // PendingRows 查询接管后仍需处理的明细。 + PendingRows(context.Context, string, bool) ([]BatchRow, error) + // FinalizeBatch 在接管后没有待处理明细时收口批次。 + FinalizeBatch(context.Context, string, string) (string, bool, error) + // FailClaimedBatch 释放恢复初始化阶段失败的批次租约。 + FailClaimedBatch(context.Context, string, string) (bool, error) +} + +// BatchWorkerStarter 是恢复服务启动批量 worker 的生命周期回调。 +// 回调由 Server 提供,因此应用服务不持有 HTTP Server、锁或取消映射。 +type BatchWorkerStarter func(context.Context, int64, string, string) + +// BatchRecoveryOptions 配置恢复扫描器的租约、时钟、令牌和 worker 回调。 +type BatchRecoveryOptions struct { + // LeaseDuration 是恢复后重新声明的批次租约时长。 + LeaseDuration time.Duration + // NewWorkerToken 生成本次恢复 worker 的租约令牌。 + NewWorkerToken func() string + // Now 返回当前时间,用于计算租约和查询截止时间。 + Now func() time.Time + // StartWorker 在批次准备完成后启动实际发布 worker。 + StartWorker BatchWorkerStarter +} + +// BatchRecoveryService 编排过期批次接管,不依赖 HTTP、数据库模型或平台实现。 +type BatchRecoveryService struct { + // repository 保存恢复扫描所需的批次状态端口。 + repository BatchRecoveryRepository + // options 保存恢复扫描的时间和生命周期策略。 + options BatchRecoveryOptions +} + +// NewBatchRecoveryService 创建批量恢复服务并校验必需依赖。 +func NewBatchRecoveryService(repository BatchRecoveryRepository, options BatchRecoveryOptions) (*BatchRecoveryService, error) { + if repository == nil { + return nil, errors.New("批量恢复仓储端口不能为空") + } + if options.StartWorker == nil { + return nil, errors.New("批量恢复 worker 回调不能为空") + } + if options.LeaseDuration <= 0 { + options.LeaseDuration = 5 * time.Minute + } + if options.NewWorkerToken == nil { + options.NewWorkerToken = randomBatchWorkerToken + } + if options.Now == nil { + options.Now = time.Now + } + return &BatchRecoveryService{repository: repository, options: options}, nil +} + +// Recover 扫描并接管可恢复批次;单个批次失败时继续处理其他批次。 +func (service *BatchRecoveryService) Recover(ctx context.Context) error { + if service == nil || service.repository == nil || service.options.StartWorker == nil { + return errors.New("批量恢复服务未初始化") + } + // now 保存本轮扫描的当前 Unix 秒,确保查询和租约计算使用同一时间基准。 + now := service.options.Now().UTC() + // batches 保存数据库返回的可恢复批次快照。 + batches, err := service.repository.RecoverableBatches(ctx, now.Unix(), 20) + if err != nil { + return err + } + // batch 表示当前待接管的批次快照。 + for _, batch := range batches { + if ctx.Err() != nil { + return ctx.Err() + } + if batch.Status == "canceling" { + // cancelNow 保存取消请求收口所使用的当前 Unix 秒。 + cancelNow := service.options.Now().UTC().Unix() + _, _ = service.repository.FinalizeExpiredCancellation(ctx, batch.ID, cancelNow) + continue + } + // workerToken 保存本轮接管使用的批次租约令牌。 + workerToken := service.options.NewWorkerToken() + if workerToken == "" { + continue + } + // leaseExpiresAt 保存恢复 worker 的租约截止 Unix 秒。 + leaseExpiresAt := service.options.Now().UTC().Add(service.options.LeaseDuration).Unix() + // claimed 表示当前进程是否成功接管批次。 + claimed, claimErr := service.repository.ClaimBatch(ctx, batch.ID, workerToken, leaseExpiresAt) + if claimErr != nil || !claimed { + continue + } + // resetErr 保存恢复前重置进程中断明细的错误。 + if resetErr := service.repository.ResetInterrupted(ctx, batch.ID); resetErr != nil { + service.releaseClaimedBatch(ctx, batch.ID, workerToken) + continue + } + // 统计重算失败不阻断恢复;随后 PendingRows 查询仍是是否启动 worker 的权威结果, + // 与原有恢复扫描器先尽力重算再继续接管的兼容语义一致。 + _ = service.repository.RecountBatch(ctx, batch.ID) + // pending 保存恢复后仍可交给 worker 的商品明细。 + pending, pendingErr := service.repository.PendingRows(ctx, batch.ID, false) + if pendingErr != nil { + service.releaseClaimedBatch(ctx, batch.ID, workerToken) + continue + } + if len(pending) == 0 { + _, _, _ = service.repository.FinalizeBatch(ctx, batch.ID, workerToken) + continue + } + service.options.StartWorker(ctx, batch.UserID, batch.ID, workerToken) + } + return nil +} + +// releaseClaimedBatch 在恢复初始化失败时释放当前 worker 的批次租约。 +func (service *BatchRecoveryService) releaseClaimedBatch(ctx context.Context, batchID, workerToken string) { + // released 和 err 保存租约释放结果;恢复扫描器不应因单批次补偿失败阻塞其他批次。 + _, _ = service.repository.FailClaimedBatch(ctx, batchID, workerToken) +} + +// randomBatchWorkerToken 生成不携带业务信息的恢复 worker 令牌。 +func randomBatchWorkerToken() string { + // buffer 保存随机令牌的二进制内容。 + buffer := make([]byte, 16) + // err 保存系统随机源读取令牌时的错误。 + if _, err := rand.Read(buffer); err != nil { + return "recovery-" + strconv.FormatInt(time.Now().UTC().UnixNano(), 36) + } + return hex.EncodeToString(buffer) +} diff --git a/internal/application/items/batch_recovery_test.go b/internal/application/items/batch_recovery_test.go new file mode 100644 index 0000000..b417843 --- /dev/null +++ b/internal/application/items/batch_recovery_test.go @@ -0,0 +1,204 @@ +package items + +import ( + "context" + "errors" + "testing" + "time" +) + +// batchRecoveryRepositoryFake 记录恢复服务对批次租约端口的调用顺序。 +type batchRecoveryRepositoryFake struct { + // batches 保存本轮扫描返回的批次。 + batches []BatchInfo + // pending 保存每个批次接管后可处理的明细数量。 + pending map[string][]BatchRow + // scanErr 模拟恢复批次查询失败。 + scanErr error + // resetErr 模拟中断明细重置失败。 + resetErr error + // pendingErr 模拟接管后明细查询失败。 + pendingErr error + // claimed 保存成功接管的批次租约参数。 + claimed []batchRecoveryClaim + // released 保存初始化失败后释放的批次租约参数。 + released []batchRecoveryClaim + // canceled 保存过期取消请求的批次标识。 + canceled []string + // finalized 保存没有待处理明细的批次标识。 + finalized []string +} + +// batchRecoveryClaim 保存一次批次租约抢占或释放调用。 +type batchRecoveryClaim struct { + // batchID 是批次标识。 + batchID string + // workerToken 是 worker 租约令牌。 + workerToken string + // leaseExpiresAt 是租约截止 Unix 秒。 + leaseExpiresAt int64 +} + +// RecoverableBatches 返回预置的可恢复批次。 +func (repository *batchRecoveryRepositoryFake) RecoverableBatches(_ context.Context, _ int64, _ int) ([]BatchInfo, error) { + if repository.scanErr != nil { + return nil, repository.scanErr + } + return repository.batches, nil +} + +// FinalizeExpiredCancellation 记录过期取消请求的收口。 +func (repository *batchRecoveryRepositoryFake) FinalizeExpiredCancellation(_ context.Context, batchID string, _ int64) (bool, error) { + repository.canceled = append(repository.canceled, batchID) + return true, nil +} + +// ClaimBatch 记录批次租约抢占并允许测试继续执行。 +func (repository *batchRecoveryRepositoryFake) ClaimBatch(_ context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) { + repository.claimed = append(repository.claimed, batchRecoveryClaim{batchID: batchID, workerToken: workerToken, leaseExpiresAt: leaseExpiresAt}) + return true, nil +} + +// ResetInterrupted 返回预置的中断明细重置结果。 +func (repository *batchRecoveryRepositoryFake) ResetInterrupted(_ context.Context, _ string) error { + return repository.resetErr +} + +// RecountBatch 表示测试仓储已经完成统计重算。 +func (repository *batchRecoveryRepositoryFake) RecountBatch(_ context.Context, _ string) error { + return nil +} + +// PendingRows 返回指定批次接管后的待处理明细。 +func (repository *batchRecoveryRepositoryFake) PendingRows(_ context.Context, batchID string, _ bool) ([]BatchRow, error) { + if repository.pendingErr != nil { + return nil, repository.pendingErr + } + return repository.pending[batchID], nil +} + +// FinalizeBatch 记录没有待处理明细的批次收口。 +func (repository *batchRecoveryRepositoryFake) FinalizeBatch(_ context.Context, batchID, _ string) (string, bool, error) { + repository.finalized = append(repository.finalized, batchID) + return "completed", true, nil +} + +// FailClaimedBatch 记录恢复初始化失败后的租约释放。 +func (repository *batchRecoveryRepositoryFake) FailClaimedBatch(_ context.Context, batchID, workerToken string) (bool, error) { + repository.released = append(repository.released, batchRecoveryClaim{batchID: batchID, workerToken: workerToken}) + return true, nil +} + +// TestBatchRecoveryClaimsPendingBatch 验证恢复服务接管并启动仍有待处理明细的批次。 +func TestBatchRecoveryClaimsPendingBatch(t *testing.T) { + // fixedNow 保存可复现的恢复扫描时间。 + fixedNow := time.Date(2026, 8, 16, 8, 0, 0, 0, time.UTC) + // repository 保存一个仍需恢复的批次和一条待处理明细。 + repository := &batchRecoveryRepositoryFake{ + batches: []BatchInfo{{ID: "batch-1", UserID: 7, Status: "running"}}, + pending: map[string][]BatchRow{"batch-1": {{ID: 11}}}, + } + // startedUserID、startedBatchID 和 startedToken 保存生命周期边界收到的 worker 参数。 + var startedUserID int64 + // startedBatchID 和 startedToken 保存恢复服务启动的批次标识与租约令牌。 + var startedBatchID, startedToken string + // service 保存使用固定时钟和令牌的恢复应用服务。 + service, err := NewBatchRecoveryService(repository, BatchRecoveryOptions{ + LeaseDuration: 5 * time.Minute, + NewWorkerToken: func() string { return "worker-1" }, + Now: func() time.Time { return fixedNow }, + StartWorker: func(_ context.Context, userID int64, batchID, workerToken string) { + startedUserID, startedBatchID, startedToken = userID, batchID, workerToken + }, + }) + if err != nil { + t.Fatalf("创建恢复服务失败: %v", err) + } + // err 保存恢复扫描的执行错误。 + if err := service.Recover(context.Background()); err != nil { + t.Fatalf("执行恢复扫描失败: %v", err) + } + if len(repository.claimed) != 1 || repository.claimed[0].batchID != "batch-1" || repository.claimed[0].workerToken != "worker-1" { + t.Fatalf("批次租约抢占异常:%+v", repository.claimed) + } + if repository.claimed[0].leaseExpiresAt != fixedNow.Add(5*time.Minute).Unix() { + t.Fatalf("租约截止时间异常:%d", repository.claimed[0].leaseExpiresAt) + } + if startedUserID != 7 || startedBatchID != "batch-1" || startedToken != "worker-1" { + t.Fatalf("worker 启动参数异常:user=%d batch=%s token=%s", startedUserID, startedBatchID, startedToken) + } +} + +// TestBatchRecoveryFinalizesCancelingAndEmptyBatches 验证取消和空批次分支不会启动 worker。 +func TestBatchRecoveryFinalizesCancelingAndEmptyBatches(t *testing.T) { + // repository 保存一个取消中的批次和一个已无待处理明细的批次。 + repository := &batchRecoveryRepositoryFake{ + batches: []BatchInfo{{ID: "canceling", Status: "canceling"}, {ID: "empty", Status: "running"}}, + pending: map[string][]BatchRow{"empty": nil}, + } + // startedCount 统计恢复服务启动 worker 的次数。 + startedCount := 0 + // service 保存测试用的恢复应用服务。 + service, err := NewBatchRecoveryService(repository, BatchRecoveryOptions{ + NewWorkerToken: func() string { return "worker" }, + StartWorker: func(context.Context, int64, string, string) { startedCount++ }, + }) + if err != nil { + t.Fatalf("创建恢复服务失败: %v", err) + } + // err 保存恢复扫描的执行错误。 + if err := service.Recover(context.Background()); err != nil { + t.Fatalf("执行恢复扫描失败: %v", err) + } + if len(repository.canceled) != 1 || repository.canceled[0] != "canceling" { + t.Fatalf("取消批次未收口:%v", repository.canceled) + } + if len(repository.finalized) != 1 || repository.finalized[0] != "empty" { + t.Fatalf("空批次未收口:%v", repository.finalized) + } + if startedCount != 0 { + t.Fatalf("空批次不应启动 worker:%d", startedCount) + } +} + +// TestBatchRecoveryReleasesClaimWhenResetFails 验证接管后重置失败会释放租约。 +func TestBatchRecoveryReleasesClaimWhenResetFails(t *testing.T) { + // repository 模拟接管后无法重置进程中断明细。 + repository := &batchRecoveryRepositoryFake{ + batches: []BatchInfo{{ID: "batch-1", Status: "running"}}, + resetErr: errors.New("reset failed"), + } + // service 保存只验证租约释放的恢复服务。 + service, err := NewBatchRecoveryService(repository, BatchRecoveryOptions{ + NewWorkerToken: func() string { return "worker-1" }, + StartWorker: func(context.Context, int64, string, string) {}, + }) + if err != nil { + t.Fatalf("创建恢复服务失败: %v", err) + } + // err 保存恢复扫描的执行错误。 + if err := service.Recover(context.Background()); err != nil { + t.Fatalf("单批次初始化失败不应阻断扫描:%v", err) + } + if len(repository.released) != 1 || repository.released[0].batchID != "batch-1" || repository.released[0].workerToken != "worker-1" { + t.Fatalf("初始化失败后未释放租约:%+v", repository.released) + } +} + +// TestBatchRecoveryReportsScanFailure 验证恢复批次查询失败会返回全局错误。 +func TestBatchRecoveryReportsScanFailure(t *testing.T) { + // scanErr 保存恢复批次查询的基础设施错误。 + scanErr := errors.New("scan failed") + // repository 保存预置的查询错误。 + repository := &batchRecoveryRepositoryFake{scanErr: scanErr} + // service 保存可执行恢复扫描的服务。 + service, err := NewBatchRecoveryService(repository, BatchRecoveryOptions{StartWorker: func(context.Context, int64, string, string) {}}) + if err != nil { + t.Fatalf("创建恢复服务失败: %v", err) + } + // runErr 保存恢复扫描返回的查询错误。 + runErr := service.Recover(context.Background()) + if !errors.Is(runErr, scanErr) { + t.Fatalf("恢复扫描错误=%v,期望=%v", runErr, scanErr) + } +} diff --git a/internal/application/items/catalog.go b/internal/application/items/catalog.go new file mode 100644 index 0000000..a73f666 --- /dev/null +++ b/internal/application/items/catalog.go @@ -0,0 +1,81 @@ +package items + +import ( + "context" + "errors" +) + +// ErrCatalogNotFound 表示请求的本地商品不存在。 +var ErrCatalogNotFound = errors.New("商品不存在") + +// CatalogItem 是商品读取用例使用的非敏感商品模型。 +type CatalogItem struct { + // ID 是本地商品记录标识。 + ID int64 + // CookieID 是商品所属账号标识。 + CookieID string + // ItemID 是平台商品标识。 + ItemID string + // ItemTitle 是商品标题。 + ItemTitle string + // ItemDescription 是商品描述。 + ItemDescription string + // ItemCategory 是平台商品类目标识。 + ItemCategory string + // ItemPrice 是商品价格文本。 + ItemPrice string + // ItemDetail 是商品扩展详情 JSON。 + ItemDetail string + // IsMultiSpec 表示商品是否启用多规格交付。 + IsMultiSpec bool + // MultiQuantityDelivery 表示商品是否启用多数量交付。 + MultiQuantityDelivery bool +} + +// CatalogRepository 定义商品列表和详情读取所需的最小持久化能力。 +type CatalogRepository interface { + // ListForUser 查询用户范围内的商品,可按账号筛选。 + ListForUser(context.Context, int64, string) ([]CatalogItem, error) + // ListByCookie 查询指定账号下的商品。 + ListByCookie(context.Context, string) ([]CatalogItem, error) + // Get 查询指定账号下的单个商品。 + Get(context.Context, string, string) (CatalogItem, error) +} + +// CatalogService 编排商品列表和详情读取用例。 +type CatalogService struct { + // repository 保存商品读取适配器。 + repository CatalogRepository +} + +// NewCatalogService 创建商品读取应用服务并校验必需端口。 +func NewCatalogService(repository CatalogRepository) (*CatalogService, error) { + if repository == nil { + return nil, errors.New("商品读取仓储端口不能为空") + } + return &CatalogService{repository: repository}, nil +} + +// ListForUser 返回当前用户可见的商品列表。 +func (service *CatalogService) ListForUser(ctx context.Context, userID int64, cookieID string) ([]CatalogItem, error) { + if service == nil || service.repository == nil { + return nil, errors.New("商品读取服务未初始化") + } + return service.repository.ListForUser(ctx, userID, cookieID) +} + +// ListByCookie 返回指定账号下的商品列表。 +func (service *CatalogService) ListByCookie(ctx context.Context, cookieID string) ([]CatalogItem, error) { + if service == nil || service.repository == nil { + return nil, errors.New("商品读取服务未初始化") + } + return service.repository.ListByCookie(ctx, cookieID) +} + +// Get 返回指定账号下的商品详情。 +func (service *CatalogService) Get(ctx context.Context, cookieID, itemID string) (CatalogItem, error) { + if service == nil || service.repository == nil { + return CatalogItem{}, errors.New("商品读取服务未初始化") + } + return service.repository.Get(ctx, cookieID, itemID) +} diff --git a/internal/application/items/catalog_mutation.go b/internal/application/items/catalog_mutation.go new file mode 100644 index 0000000..acfa362 --- /dev/null +++ b/internal/application/items/catalog_mutation.go @@ -0,0 +1,144 @@ +package items + +import ( + "context" + "errors" +) + +// CatalogWriteInput 是创建或完整保存本地商品所需的应用层输入。 +type CatalogWriteInput struct { + // ItemID 是平台商品标识,也是账号范围内的业务唯一键。 + ItemID string + // ItemTitle 是商品标题。 + ItemTitle string + // ItemDescription 是商品描述。 + ItemDescription string + // ItemCategory 是平台商品类目标识。 + ItemCategory string + // ItemPrice 是商品价格文本。 + ItemPrice string + // ItemDetail 是商品扩展详情 JSON。 + ItemDetail string + // IsMultiSpec 表示商品是否启用多规格交付。 + IsMultiSpec bool + // MultiQuantityDelivery 表示商品是否启用多数量交付。 + MultiQuantityDelivery bool +} + +// CatalogPatchInput 是更新本地商品时的可选字段集合;nil 表示保留旧值。 +type CatalogPatchInput struct { + // ItemTitle 是待更新的商品标题;nil 表示保留原值。 + ItemTitle *string + // ItemDescription 是待更新的商品描述;nil 表示保留原值。 + ItemDescription *string + // ItemCategory 是待更新的商品类目标识;nil 表示保留原值。 + ItemCategory *string + // ItemPrice 是待更新的商品价格文本;nil 表示保留原值。 + ItemPrice *string + // ItemDetail 是待更新的商品扩展详情;nil 表示保留原值。 + ItemDetail *string + // IsMultiSpec 是待更新的多规格开关;nil 表示保留原值。 + IsMultiSpec *bool + // MultiQuantityDelivery 是待更新的多数量交付开关;nil 表示保留原值。 + MultiQuantityDelivery *bool +} + +// CatalogMutationRepository 定义本地商品写入和开关变更所需的最小持久化能力。 +type CatalogMutationRepository interface { + // Get 读取更新操作需要的现有商品记录。 + Get(context.Context, string, string) (CatalogItem, error) + // Upsert 创建或完整保存本地商品记录。 + Upsert(context.Context, string, CatalogWriteInput) error + // Delete 逻辑删除商品及其商品级自动化规则。 + Delete(context.Context, string, string) error + // SetMultiSpec 设置商品多规格开关。 + SetMultiSpec(context.Context, string, string, bool) error + // SetMultiQuantity 设置商品多数量交付开关。 + SetMultiQuantity(context.Context, string, string, bool) error +} + +// CatalogMutationService 编排本地商品创建、更新、删除和交付开关变更。 +type CatalogMutationService struct { + // repository 保存商品写入适配器。 + repository CatalogMutationRepository +} + +// NewCatalogMutationService 创建商品写应用服务并校验必需端口。 +func NewCatalogMutationService(repository CatalogMutationRepository) (*CatalogMutationService, error) { + if repository == nil { + return nil, errors.New("商品写入仓储端口不能为空") + } + return &CatalogMutationService{repository: repository}, nil +} + +// Create 创建或恢复指定账号下的本地商品记录。 +func (service *CatalogMutationService) Create(ctx context.Context, cookieID string, input CatalogWriteInput) error { + if service == nil || service.repository == nil { + return errors.New("商品写入服务未初始化") + } + return service.repository.Upsert(ctx, cookieID, input) +} + +// Update 读取现有商品、合并局部字段并保存完整记录。 +func (service *CatalogMutationService) Update(ctx context.Context, cookieID, itemID string, patch CatalogPatchInput) error { + if service == nil || service.repository == nil { + return errors.New("商品写入服务未初始化") + } + // existing、err 保存更新前的商品记录及查询错误。 + existing, err := service.repository.Get(ctx, cookieID, itemID) + if err != nil { + return err + } + // input 保存合并后的完整商品写入模型。 + input := CatalogWriteInput{ + ItemID: itemID, ItemTitle: existing.ItemTitle, ItemDescription: existing.ItemDescription, + ItemCategory: existing.ItemCategory, ItemPrice: existing.ItemPrice, ItemDetail: existing.ItemDetail, + IsMultiSpec: existing.IsMultiSpec, MultiQuantityDelivery: existing.MultiQuantityDelivery, + } + if patch.ItemTitle != nil { + input.ItemTitle = *patch.ItemTitle + } + if patch.ItemDescription != nil { + input.ItemDescription = *patch.ItemDescription + } + if patch.ItemCategory != nil { + input.ItemCategory = *patch.ItemCategory + } + if patch.ItemPrice != nil { + input.ItemPrice = *patch.ItemPrice + } + if patch.ItemDetail != nil { + input.ItemDetail = *patch.ItemDetail + } + if patch.IsMultiSpec != nil { + input.IsMultiSpec = *patch.IsMultiSpec + } + if patch.MultiQuantityDelivery != nil { + input.MultiQuantityDelivery = *patch.MultiQuantityDelivery + } + return service.repository.Upsert(ctx, cookieID, input) +} + +// Delete 逻辑删除指定账号下的本地商品。 +func (service *CatalogMutationService) Delete(ctx context.Context, cookieID, itemID string) error { + if service == nil || service.repository == nil { + return errors.New("商品写入服务未初始化") + } + return service.repository.Delete(ctx, cookieID, itemID) +} + +// SetMultiSpec 更新指定商品的多规格交付开关。 +func (service *CatalogMutationService) SetMultiSpec(ctx context.Context, cookieID, itemID string, enabled bool) error { + if service == nil || service.repository == nil { + return errors.New("商品写入服务未初始化") + } + return service.repository.SetMultiSpec(ctx, cookieID, itemID, enabled) +} + +// SetMultiQuantity 更新指定商品的多数量交付开关。 +func (service *CatalogMutationService) SetMultiQuantity(ctx context.Context, cookieID, itemID string, enabled bool) error { + if service == nil || service.repository == nil { + return errors.New("商品写入服务未初始化") + } + return service.repository.SetMultiQuantity(ctx, cookieID, itemID, enabled) +} diff --git a/internal/application/items/catalog_mutation_test.go b/internal/application/items/catalog_mutation_test.go new file mode 100644 index 0000000..b9b77e8 --- /dev/null +++ b/internal/application/items/catalog_mutation_test.go @@ -0,0 +1,109 @@ +package items + +import ( + "context" + "errors" + "testing" +) + +// catalogMutationRepositoryStub 是商品写应用服务测试使用的可控仓储替身。 +type catalogMutationRepositoryStub struct { + // item 保存当前账号下的商品记录。 + item CatalogItem + // getErr 保存读取现有商品时的预设错误。 + getErr error + // upsertErr 保存完整商品写入时的预设错误。 + upsertErr error + // upsertInput 保存最后一次收到的完整写入模型。 + upsertInput CatalogWriteInput + // deleteErr 保存逻辑删除时的预设错误。 + deleteErr error + // multiSpecErr 保存多规格开关更新时的预设错误。 + multiSpecErr error + // multiQuantityErr 保存多数量开关更新时的预设错误。 + multiQuantityErr error +} + +// Get 返回测试预设的商品记录或读取错误。 +func (repository *catalogMutationRepositoryStub) Get(context.Context, string, string) (CatalogItem, error) { + return repository.item, repository.getErr +} + +// Upsert 保存测试收到的完整商品写入模型。 +func (repository *catalogMutationRepositoryStub) Upsert(_ context.Context, _ string, input CatalogWriteInput) error { + repository.upsertInput = input + return repository.upsertErr +} + +// Delete 返回测试预设的逻辑删除错误。 +func (repository *catalogMutationRepositoryStub) Delete(context.Context, string, string) error { + return repository.deleteErr +} + +// SetMultiSpec 返回测试预设的多规格更新错误。 +func (repository *catalogMutationRepositoryStub) SetMultiSpec(context.Context, string, string, bool) error { + return repository.multiSpecErr +} + +// SetMultiQuantity 返回测试预设的多数量更新错误。 +func (repository *catalogMutationRepositoryStub) SetMultiQuantity(context.Context, string, string, bool) error { + return repository.multiQuantityErr +} + +// TestCatalogMutationServiceUpdateMergesExplicitAndOmittedFields 验证局部更新保留未提交字段并允许显式清空或关闭。 +func TestCatalogMutationServiceUpdateMergesExplicitAndOmittedFields(t *testing.T) { + // repository 保存待验证的现有商品及写入记录。 + repository := &catalogMutationRepositoryStub{item: CatalogItem{ + ItemID: "item-1", ItemTitle: "旧标题", ItemDescription: "旧描述", ItemCategory: "旧类目", + ItemPrice: "1.00", ItemDetail: "旧详情", IsMultiSpec: true, MultiQuantityDelivery: true, + }} + // service 保存绑定测试仓储的商品写应用服务。 + service, err := NewCatalogMutationService(repository) + if err != nil { + t.Fatalf("NewCatalogMutationService error: %v", err) + } + // emptyDescription、disabledMultiSpec 保存显式清空和关闭开关的更新值。 + emptyDescription := "" + // disabledMultiSpec 保存显式关闭多规格交付的更新值。 + disabledMultiSpec := false + // updateErr 保存商品局部更新结果。 + updateErr := service.Update(context.Background(), "account-1", "item-1", CatalogPatchInput{ItemDescription: &emptyDescription, IsMultiSpec: &disabledMultiSpec}) + if updateErr != nil { + t.Fatalf("Update error: %v", updateErr) + } + // got 保存应用服务合并后的完整写入模型。 + got := repository.upsertInput + if got.ItemID != "item-1" || got.ItemTitle != "旧标题" || got.ItemDescription != "" || got.ItemCategory != "旧类目" || got.ItemPrice != "1.00" || got.ItemDetail != "旧详情" || got.IsMultiSpec || !got.MultiQuantityDelivery { + t.Fatalf("Update merge result=%+v", got) + } +} + +// TestCatalogMutationServicePropagatesReadAndWriteErrors 验证商品写入应用服务不吞掉仓储错误。 +func TestCatalogMutationServicePropagatesReadAndWriteErrors(t *testing.T) { + // readErr 是更新读取阶段的底层错误。 + readErr := errors.New("读取失败") + // readRepository 保存读取失败的测试仓储。 + readRepository := &catalogMutationRepositoryStub{getErr: readErr} + // readService 保存绑定读取失败仓储的应用服务。 + readService, err := NewCatalogMutationService(readRepository) + if err != nil { + t.Fatalf("NewCatalogMutationService read error: %v", err) + } + // updateErr 保存商品更新读取阶段的错误。 + if updateErr := readService.Update(context.Background(), "account-1", "item-1", CatalogPatchInput{}); !errors.Is(updateErr, readErr) { + t.Fatalf("Update read error=%v want %v", updateErr, readErr) + } + // writeErr 是完整商品写入阶段的底层错误。 + writeErr := errors.New("写入失败") + // writeRepository 保存写入失败的测试仓储。 + writeRepository := &catalogMutationRepositoryStub{upsertErr: writeErr} + // writeService 保存绑定写入失败仓储的应用服务。 + writeService, err := NewCatalogMutationService(writeRepository) + if err != nil { + t.Fatalf("NewCatalogMutationService write error: %v", err) + } + // createErr 保存商品创建阶段的写入错误。 + if createErr := writeService.Create(context.Background(), "account-1", CatalogWriteInput{ItemID: "item-1"}); !errors.Is(createErr, writeErr) { + t.Fatalf("Create write error=%v want %v", createErr, writeErr) + } +} diff --git a/internal/application/items/catalog_test.go b/internal/application/items/catalog_test.go new file mode 100644 index 0000000..4e5dacd --- /dev/null +++ b/internal/application/items/catalog_test.go @@ -0,0 +1,72 @@ +package items + +import ( + "context" + "errors" + "testing" +) + +// catalogRepositoryStub 保存商品读取端口的预设结果。 +type catalogRepositoryStub struct { + // items 保存列表结果。 + items []CatalogItem + // item 保存详情结果。 + item CatalogItem + // err 保存底层错误。 + err error +} + +// ListForUser 返回预设的用户商品列表。 +func (stub catalogRepositoryStub) ListForUser(context.Context, int64, string) ([]CatalogItem, error) { + return stub.items, stub.err +} + +// ListByCookie 返回预设的账号商品列表。 +func (stub catalogRepositoryStub) ListByCookie(context.Context, string) ([]CatalogItem, error) { + return stub.items, stub.err +} + +// Get 返回预设的商品详情。 +func (stub catalogRepositoryStub) Get(context.Context, string, string) (CatalogItem, error) { + return stub.item, stub.err +} + +// TestCatalogServiceDelegatesReads 验证商品读取服务转发列表与详情结果。 +func TestCatalogServiceDelegatesReads(t *testing.T) { + // wantItem 保存测试期望的商品模型。 + wantItem := CatalogItem{CookieID: "account-1", ItemID: "item-1"} + // service 和 err 保存商品读取服务及构造错误。 + service, err := NewCatalogService(catalogRepositoryStub{items: []CatalogItem{wantItem}, item: wantItem}) + if err != nil { + t.Fatalf("NewCatalogService() error=%v", err) + } + // items 和 err 保存用户范围读取结果及错误。 + items, err := service.ListForUser(context.Background(), 7, "account-1") + if err != nil || len(items) != 1 || items[0].ItemID != wantItem.ItemID { + t.Fatalf("ListForUser() items=%v error=%v", items, err) + } + // item 和 err 保存商品详情读取结果及错误。 + item, err := service.Get(context.Background(), "account-1", "item-1") + if err != nil || item.ItemID != wantItem.ItemID { + t.Fatalf("Get() item=%v error=%v", item, err) + } +} + +// TestCatalogServicePropagatesErrors 验证商品读取服务不吞底层错误。 +func TestCatalogServicePropagatesErrors(t *testing.T) { + // wantErr 保存底层仓储返回的错误。 + wantErr := errors.New("catalog unavailable") + // service 和 err 保存商品读取服务及构造错误。 + service, err := NewCatalogService(catalogRepositoryStub{err: wantErr}) + if err != nil { + t.Fatalf("NewCatalogService() error=%v", err) + } + // callErr 保存账号范围读取错误。 + if _, callErr := service.ListByCookie(context.Background(), "account-1"); !errors.Is(callErr, wantErr) { + t.Fatalf("ListByCookie() error=%v want=%v", callErr, wantErr) + } + // callErr 保存详情读取错误。 + if _, callErr := service.Get(context.Background(), "account-1", "item-1"); !errors.Is(callErr, wantErr) { + t.Fatalf("Get() error=%v want=%v", callErr, wantErr) + } +} diff --git a/internal/application/items/category_recommendation.go b/internal/application/items/category_recommendation.go new file mode 100644 index 0000000..ed1324c --- /dev/null +++ b/internal/application/items/category_recommendation.go @@ -0,0 +1,53 @@ +package items + +import ( + "context" + "errors" + "strings" +) + +// ErrCategoryUnsupported 表示当前平台客户端没有实现类目推荐能力。 +var ErrCategoryUnsupported = errors.New("当前 MTOP 客户端不支持类目推荐") + +// ErrCategoryUnrecognized 表示平台没有返回完整可发布类目。 +var ErrCategoryUnrecognized = errors.New("未能自动识别商品类目,请调整标题或图片后重试") + +// ErrCategoryCredentialChanged 表示远端调用前后的账号凭证发生并发变化。 +var ErrCategoryCredentialChanged = errors.New("账号凭证已变化,请重试") + +// ErrCategoryPersistence 表示平台响应中的账号会话无法安全写回。 +var ErrCategoryPersistence = errors.New("保存账号登录状态失败") + +// CategoryRecommendationPort 定义类目推荐用例所需的平台能力。 +type CategoryRecommendationPort interface { + // RecommendCategory 根据用户账号和关键词返回应用层类目。 + RecommendCategory(context.Context, int64, string, string) (BatchPreviewCategory, error) +} + +// CategoryRecommendationService 编排类目推荐输入校验和平台端口调用。 +type CategoryRecommendationService struct { + // port 提供平台类目推荐及会话持久化能力。 + port CategoryRecommendationPort +} + +// NewCategoryRecommendationService 创建类目推荐应用服务。 +func NewCategoryRecommendationService(port CategoryRecommendationPort) (*CategoryRecommendationService, error) { + if port == nil { + return nil, errors.New("类目推荐端口不能为空") + } + return &CategoryRecommendationService{port: port}, nil +} + +// Recommend 校验账号和关键词后调用类目推荐端口。 +func (service *CategoryRecommendationService) Recommend(ctx context.Context, userID int64, cookieID, keyword string) (BatchPreviewCategory, error) { + if service == nil || service.port == nil { + return BatchPreviewCategory{}, errors.New("类目推荐服务未初始化") + } + if userID <= 0 || strings.TrimSpace(cookieID) == "" { + return BatchPreviewCategory{}, ErrCategoryCredentialChanged + } + if strings.TrimSpace(keyword) == "" { + return BatchPreviewCategory{}, errors.New("类目关键词不能为空") + } + return service.port.RecommendCategory(ctx, userID, strings.TrimSpace(cookieID), strings.TrimSpace(keyword)) +} diff --git a/internal/application/items/category_recommendation_test.go b/internal/application/items/category_recommendation_test.go new file mode 100644 index 0000000..399ac5b --- /dev/null +++ b/internal/application/items/category_recommendation_test.go @@ -0,0 +1,99 @@ +package items + +import ( + "context" + "errors" + "testing" +) + +// categoryRecommendationPortStub 记录应用层类目推荐调用。 +type categoryRecommendationPortStub struct { + // category 保存端口返回的测试类目。 + category BatchPreviewCategory + // err 保存端口返回的测试错误。 + err error + // calls 保存端口被调用次数。 + calls int +} + +// RecommendCategory 返回预设类目并记录调用次数。 +func (stub *categoryRecommendationPortStub) RecommendCategory(context.Context, int64, string, string) (BatchPreviewCategory, error) { + stub.calls++ + return stub.category, stub.err +} + +// TestCategoryRecommendationServiceDelegatesValidatedInput 验证应用服务转发合法输入。 +func TestCategoryRecommendationServiceDelegatesValidatedInput(t *testing.T) { + // port 保存可控的类目推荐端口。 + port := &categoryRecommendationPortStub{category: BatchPreviewCategory{CatID: "1", CatName: "资料"}} + // service 保存待测试的应用服务。 + service, err := NewCategoryRecommendationService(port) + if err != nil { + t.Fatalf("构造服务失败: %v", err) + } + // category 保存应用服务返回的类目结果。 + category, err := service.Recommend(context.Background(), 1, " acc ", " 资料 ") + if err != nil || category.CatID != "1" || port.calls != 1 { + t.Fatalf("类目推荐结果异常: category=%+v err=%v calls=%d", category, err, port.calls) + } +} + +// TestCategoryRecommendationServiceRejectsInvalidInput 验证空输入不会调用基础设施端口。 +func TestCategoryRecommendationServiceRejectsInvalidInput(t *testing.T) { + // port 保存不应被调用的测试端口。 + port := &categoryRecommendationPortStub{} + // service 保存待测试的应用服务。 + service, err := NewCategoryRecommendationService(port) + if err != nil { + t.Fatalf("构造服务失败: %v", err) + } + // invalidErr 保存空关键词导致的校验错误。 + _, invalidErr := service.Recommend(context.Background(), 1, "acc", " ") + if invalidErr == nil || port.calls != 0 { + t.Fatalf("空关键词校验异常: err=%v calls=%d", invalidErr, port.calls) + } +} + +// TestBatchPreviewPersistenceServiceCountsAndPropagatesErrors 验证预检计数及落库错误传播。 +func TestBatchPreviewPersistenceServiceCountsAndPropagatesErrors(t *testing.T) { + // repository 保存测试用的预检持久化端口。 + repository := &batchPreviewPersistenceRepositoryStub{} + // service 保存待测试的预检持久化服务。 + service, err := NewBatchPreviewPersistenceService(repository) + if err != nil { + t.Fatalf("构造服务失败: %v", err) + } + // rows 保存一条有效行和一条校验失败行。 + rows := []BatchPreviewRow{{RowNo: 2}, {RowNo: 3, Errors: []string{"标题为空"}}} + // result 保存预检持久化结果。 + result, err := service.Persist(context.Background(), BatchPreviewPersistenceBatch{ID: "batch-1"}, rows) + if err != nil || result.Valid != 1 || result.Invalid != 1 || repository.created.ID != "batch-1" { + t.Fatalf("预检结果异常: result=%+v err=%v batch=%+v", result, err, repository.created) + } + // expectedErr 保存模拟的数据库错误。 + expectedErr := errors.New("db down") + repository.err = expectedErr + _, err = service.Persist(context.Background(), BatchPreviewPersistenceBatch{ID: "batch-2"}, rows) + if !errors.Is(err, expectedErr) { + t.Fatalf("数据库错误未传播: %v", err) + } +} + +// batchPreviewPersistenceRepositoryStub 是预检持久化服务的内存端口替身。 +type batchPreviewPersistenceRepositoryStub struct { + // created 保存最近一次创建的批次元数据。 + created BatchPreviewPersistenceBatch + // err 保存模拟的创建错误。 + err error +} + +// CreateBatch 记录批次并返回预设错误。 +func (stub *batchPreviewPersistenceRepositoryStub) CreateBatch(_ context.Context, batch BatchPreviewPersistenceBatch, _ []BatchPreviewRow) error { + stub.created = batch + return stub.err +} + +// RecountBatch 返回预检统计重算成功。 +func (*batchPreviewPersistenceRepositoryStub) RecountBatch(context.Context, string) error { + return nil +} diff --git a/internal/application/items/single_publish.go b/internal/application/items/single_publish.go index d837403..a379437 100644 --- a/internal/application/items/single_publish.go +++ b/internal/application/items/single_publish.go @@ -8,6 +8,58 @@ import ( "strings" ) +// PublishErrorCode 表示平台发布失败的稳定业务分类。 +type PublishErrorCode string + +const ( + // PublishErrorUnknown 表示平台返回了未细分的发布失败。 + PublishErrorUnknown PublishErrorCode = "publish_failed" + // PublishErrorTokenExpired 表示平台会话已过期。 + PublishErrorTokenExpired PublishErrorCode = "auth_expired" + // PublishErrorStockPermissionMissing 表示账号缺少库存发布权限。 + PublishErrorStockPermissionMissing PublishErrorCode = "stock_permission_missing" +) + +// PublishError 保存平台发布失败的稳定分类和脱敏文本,不暴露平台包类型。 +type PublishError struct { + // Code 是供 HTTP 层映射状态码的稳定业务分类。 + Code PublishErrorCode + // Ret 是平台返回的脱敏错误文本片段。 + Ret []string + // Body 是平台返回的脱敏响应摘要。 + Body string + // Err 保留基础设施错误链,供适配器和恢复流程继续判断。 + Err error +} + +// Error 返回平台错误文本,优先使用平台返回的业务描述。 +func (e *PublishError) Error() string { + if e == nil { + return string(PublishErrorUnknown) + } + if len(e.Ret) > 0 { + return strings.Join(e.Ret, "; ") + } + if e.Body != "" { + if len(e.Body) > 240 { + return e.Body[:240] + "..." + } + return e.Body + } + if e.Code == "" { + return string(PublishErrorUnknown) + } + return string(e.Code) +} + +// Unwrap 保留适配器底层错误链而不要求应用层依赖平台类型。 +func (e *PublishError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + // Image 是商品发布所需的图片内容;图片字节只在当前用例生命周期内由端口消费。 type Image struct { // Filename 是上传到平台时使用的原始文件名。 diff --git a/internal/application/items/single_publish_test.go b/internal/application/items/single_publish_test.go index d18b292..990bf74 100644 --- a/internal/application/items/single_publish_test.go +++ b/internal/application/items/single_publish_test.go @@ -3,6 +3,7 @@ package items import ( "context" "errors" + "strings" "testing" ) @@ -87,3 +88,24 @@ func TestNewServiceRejectsMissingPort(t *testing.T) { t.Fatal("缺少仓储端口时应返回错误") } } + +// TestPublishErrorFormatsStableMessages 验证应用发布错误覆盖平台描述、长响应截断和默认分类。 +func TestPublishErrorFormatsStableMessages(t *testing.T) { + // shortErr 是带平台业务描述片段的应用错误。 + shortErr := &PublishError{Code: PublishErrorStockPermissionMissing, Ret: []string{"库存权限缺失"}} + if shortErr.Error() != "库存权限缺失" { + t.Fatalf("业务描述错误文本异常: %q", shortErr.Error()) + } + // longBody 是超过 HTTP 错误摘要上限的平台响应文本。 + longBody := strings.Repeat("x", 241) + // bodyErr 是仅携带响应正文的应用错误。 + bodyErr := &PublishError{Body: longBody} + if len(bodyErr.Error()) != 243 || !strings.HasSuffix(bodyErr.Error(), "...") { + t.Fatalf("长响应未按边界截断: len=%d", len(bodyErr.Error())) + } + // plainErr 是未细分分类的应用错误。 + plainErr := &PublishError{} + if plainErr.Error() != string(PublishErrorUnknown) { + t.Fatalf("默认发布错误分类异常: %q", plainErr.Error()) + } +} diff --git a/internal/application/items/sync.go b/internal/application/items/sync.go new file mode 100644 index 0000000..0643ab6 --- /dev/null +++ b/internal/application/items/sync.go @@ -0,0 +1,155 @@ +package items + +import ( + "context" + "errors" + "strings" +) + +// SyncErrorKind 标识商品同步失败发生的基础设施阶段。 +type SyncErrorKind string + +const ( + // SyncErrorPlatform 表示平台商品接口或详情探测失败。 + SyncErrorPlatform SyncErrorKind = "platform" + // SyncErrorPersistence 表示凭证或商品本地持久化失败。 + SyncErrorPersistence SyncErrorKind = "persistence" + // SyncErrorCredential 表示账号凭证在同步期间发生并发变化。 + SyncErrorCredential SyncErrorKind = "credential" +) + +var ( + // ErrSyncInvalidUser 表示请求缺少有效的当前用户身份。 + ErrSyncInvalidUser = errors.New("商品同步用户无效") + // ErrSyncInvalidCookie 表示请求缺少有效的账号标识。 + ErrSyncInvalidCookie = errors.New("商品同步账号无效") + // ErrSyncNotOwned 表示当前用户无权访问指定账号。 + ErrSyncNotOwned = errors.New("无权限操作该账号") +) + +// SyncError 保留同步失败阶段,同时隐藏底层数据库和平台实现类型。 +type SyncError struct { + // Kind 表示错误发生的平台、凭证或持久化阶段。 + Kind SyncErrorKind + // Err 保存供日志和错误链判断的底层原因。 + Err error +} + +// Error 返回不包含敏感凭证的同步错误文本。 +func (e *SyncError) Error() string { + if e == nil || e.Err == nil { + return "商品同步失败" + } + return e.Err.Error() +} + +// Unwrap 暴露底层错误以支持 errors.Is 和 errors.As。 +func (e *SyncError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + +// SyncQuery 描述一次商品同步请求的业务参数。 +type SyncQuery struct { + // UserID 是当前认证用户的本地标识。 + UserID int64 + // CookieID 是平台账号的稳定标识。 + CookieID string + // PageNumber 是分页同步请求的平台页码;全量同步忽略该字段。 + PageNumber int + // PageSize 是平台单页大小;非正值由适配器使用默认值。 + PageSize int + // MaxPages 是全量同步允许读取的最大页数;非正值表示不设上限。 + MaxPages int +} + +// SyncAllResult 是全量同步成功后的稳定应用结果。 +type SyncAllResult struct { + // TotalCount 是平台本次返回的商品总数。 + TotalCount int + // TotalPages 是平台本次实际读取的页数。 + TotalPages int + // SavedCount 是本地成功写入或更新的商品数。 + SavedCount int + // DeletedCount 是本地被标记删除的商品数。 + DeletedCount int +} + +// SyncPageResult 是分页同步成功后的稳定应用结果。 +type SyncPageResult struct { + // PageNumber 是平台实际返回的页码。 + PageNumber int + // PageSize 是平台实际使用的单页大小。 + PageSize int + // CurrentCount 是本页返回的商品数。 + CurrentCount int + // SavedCount 是本页成功写入或更新的商品数。 + SavedCount int +} + +// SyncRepository 是商品同步用例所需的最小基础设施 Port。 +type SyncRepository interface { + // OwnsAccount 判断当前用户是否拥有指定平台账号,不读取或解密凭证。 + OwnsAccount(context.Context, int64, string) (bool, error) + // SyncAll 从平台读取账号全集并完成本地 reconcile。 + SyncAll(context.Context, SyncQuery) (SyncAllResult, error) + // SyncPage 从平台读取指定页并保存本页商品。 + SyncPage(context.Context, SyncQuery) (SyncPageResult, error) +} + +// SyncService 编排全量和分页商品同步用例,不依赖 HTTP、数据库或平台 SDK。 +type SyncService struct { + // repository 提供商品同步使用的窄基础设施 Port。 + repository SyncRepository +} + +// NewSyncService 构造商品同步应用服务。 +func NewSyncService(repository SyncRepository) *SyncService { + return &SyncService{repository: repository} +} + +// SyncAll 校验用户输入后执行商品全集同步。 +func (s *SyncService) SyncAll(ctx context.Context, query SyncQuery) (SyncAllResult, error) { + if query.UserID <= 0 { + return SyncAllResult{}, ErrSyncInvalidUser + } + if strings.TrimSpace(query.CookieID) == "" { + return SyncAllResult{}, ErrSyncInvalidCookie + } + if s == nil || s.repository == nil { + return SyncAllResult{}, &SyncError{Kind: SyncErrorPersistence, Err: errors.New("商品同步 repository 未初始化")} + } + // owned、ownershipErr 保存当前用户的非敏感账号归属判断结果。 + owned, ownershipErr := s.repository.OwnsAccount(ctx, query.UserID, query.CookieID) + if ownershipErr != nil { + return SyncAllResult{}, ownershipErr + } + if !owned { + return SyncAllResult{}, ErrSyncNotOwned + } + return s.repository.SyncAll(ctx, query) +} + +// SyncPage 校验用户输入后执行指定页商品同步。 +func (s *SyncService) SyncPage(ctx context.Context, query SyncQuery) (SyncPageResult, error) { + if query.UserID <= 0 { + return SyncPageResult{}, ErrSyncInvalidUser + } + if strings.TrimSpace(query.CookieID) == "" { + return SyncPageResult{}, ErrSyncInvalidCookie + } + if s == nil || s.repository == nil { + return SyncPageResult{}, &SyncError{Kind: SyncErrorPersistence, Err: errors.New("商品同步 repository 未初始化")} + } + // owned、ownershipErr 保存当前用户的非敏感账号归属判断结果。 + owned, ownershipErr := s.repository.OwnsAccount(ctx, query.UserID, query.CookieID) + if ownershipErr != nil { + return SyncPageResult{}, ownershipErr + } + if !owned { + return SyncPageResult{}, ErrSyncNotOwned + } + return s.repository.SyncPage(ctx, query) +} diff --git a/internal/application/items/sync_test.go b/internal/application/items/sync_test.go new file mode 100644 index 0000000..104bd07 --- /dev/null +++ b/internal/application/items/sync_test.go @@ -0,0 +1,129 @@ +package items + +import ( + "context" + "errors" + "testing" +) + +// syncRepositoryFake 是隔离应用服务测试的商品同步 Port 桩。 +type syncRepositoryFake struct { + // owned 表示桩返回的账号归属结果。 + owned bool + // ownershipErr 保存归属查询错误。 + ownershipErr error + // allResult 保存全量同步桩的结果。 + allResult SyncAllResult + // pageResult 保存分页同步桩的结果。 + pageResult SyncPageResult + // err 保存桩返回的错误。 + err error + // allQuery 保存最近一次全量查询。 + allQuery SyncQuery + // pageQuery 保存最近一次分页查询。 + pageQuery SyncQuery +} + +// OwnsAccount 返回预设的账号归属结果。 +func (f *syncRepositoryFake) OwnsAccount(_ context.Context, _ int64, _ string) (bool, error) { + return f.owned, f.ownershipErr +} + +// SyncAll 记录全量查询并返回预设结果。 +func (f *syncRepositoryFake) SyncAll(_ context.Context, query SyncQuery) (SyncAllResult, error) { + f.allQuery = query + return f.allResult, f.err +} + +// SyncPage 记录分页查询并返回预设结果。 +func (f *syncRepositoryFake) SyncPage(_ context.Context, query SyncQuery) (SyncPageResult, error) { + f.pageQuery = query + return f.pageResult, f.err +} + +// TestSyncServiceForwardsQueries 验证应用服务只校验输入并转发业务查询。 +func TestSyncServiceForwardsQueries(t *testing.T) { + // repository 保存本次测试使用的 Port 桩。 + repository := &syncRepositoryFake{owned: true, allResult: SyncAllResult{TotalCount: 2}, pageResult: SyncPageResult{SavedCount: 1}} + // service 保存本次测试使用的应用服务。 + service := NewSyncService(repository) + // query 保存需要传入应用服务的业务查询。 + query := SyncQuery{UserID: 7, CookieID: "acc1", PageNumber: 2, PageSize: 10, MaxPages: 3} + // allResult、err 保存全量同步结果和错误。 + allResult, err := service.SyncAll(context.Background(), query) + if err != nil || allResult.TotalCount != 2 || repository.allQuery != query { + t.Fatalf("all result=%+v err=%v query=%+v", allResult, err, repository.allQuery) + } + // pageResult、err 保存分页同步结果和错误。 + pageResult, err := service.SyncPage(context.Background(), query) + if err != nil || pageResult.SavedCount != 1 || repository.pageQuery != query { + t.Fatalf("page result=%+v err=%v query=%+v", pageResult, err, repository.pageQuery) + } +} + +// TestSyncServiceRejectsInvalidInput 验证用户和账号参数在进入基础设施前被拒绝。 +func TestSyncServiceRejectsInvalidInput(t *testing.T) { + // cases 保存需要覆盖的无效输入及期望错误。 + cases := []struct { + // name 是测试场景名称。 + name string + // query 是待校验的同步查询。 + query SyncQuery + // wantErr 是期望的稳定错误。 + wantErr error + }{ + {name: "invalid-user", query: SyncQuery{CookieID: "acc1"}, wantErr: ErrSyncInvalidUser}, + {name: "invalid-cookie", query: SyncQuery{UserID: 1}, wantErr: ErrSyncInvalidCookie}, + } + // testCase 表示当前输入场景。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // err 是本次校验返回的错误。 + _, err := NewSyncService(&syncRepositoryFake{}).SyncAll(context.Background(), testCase.query) + if !errors.Is(err, testCase.wantErr) { + t.Fatalf("err=%v want=%v", err, testCase.wantErr) + } + }) + } +} + +// TestSyncServicePreservesErrorKind 验证应用服务保留平台和持久化错误阶段。 +func TestSyncServicePreservesErrorKind(t *testing.T) { + // platformErr 是模拟平台失败的阶段错误。 + platformErr := &SyncError{Kind: SyncErrorPlatform, Err: errors.New("平台失败")} + // persistenceErr 是模拟持久化失败的阶段错误。 + persistenceErr := &SyncError{Kind: SyncErrorPersistence, Err: errors.New("保存失败")} + // cases 保存需要透传的阶段错误。 + cases := []struct { + // name 是测试场景名称。 + name string + // err 是 Port 返回的错误。 + err error + // wantKind 是期望保留的阶段。 + wantKind SyncErrorKind + }{ + {name: "platform", err: platformErr, wantKind: SyncErrorPlatform}, + {name: "persistence", err: persistenceErr, wantKind: SyncErrorPersistence}, + } + // testCase 表示当前阶段错误场景。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // result、err 保存 Port 调用结果。 + _, err := NewSyncService(&syncRepositoryFake{owned: true, err: testCase.err}).SyncAll(context.Background(), SyncQuery{UserID: 1, CookieID: "acc1"}) + // stageErr 保存可识别的阶段错误。 + var stageErr *SyncError + if !errors.As(err, &stageErr) || stageErr.Kind != testCase.wantKind { + t.Fatalf("err=%v stage=%+v", err, stageErr) + } + }) + } +} + +// TestSyncServiceRejectsUnownedAccount 验证应用服务在读取平台凭证前拒绝跨用户账号。 +func TestSyncServiceRejectsUnownedAccount(t *testing.T) { + // err 保存跨用户账号应返回的归属错误。 + _, err := NewSyncService(&syncRepositoryFake{owned: false}).SyncPage(context.Background(), SyncQuery{UserID: 1, CookieID: "other"}) + if !errors.Is(err, ErrSyncNotOwned) { + t.Fatalf("err=%v want=%v", err, ErrSyncNotOwned) + } +} diff --git a/internal/application/keywords/service.go b/internal/application/keywords/service.go new file mode 100644 index 0000000..16c6715 --- /dev/null +++ b/internal/application/keywords/service.go @@ -0,0 +1,295 @@ +// Package keywords 提供关键词回复和指定商品回复的应用层用例。 +// 本包只依赖消费者定义的持久化 Port,不依赖 HTTP、数据库模型或具体数据库实现。 +package keywords + +import ( + "context" + "errors" + "strings" +) + +// ErrInvalidInput 表示关键词回复用例缺少有效的用户、账号或请求参数。 +var ErrInvalidInput = errors.New("关键词回复参数无效") + +// ErrInvalidUser 表示调用方没有提供正数用户标识。 +var ErrInvalidUser = errors.New("关键词回复用户身份无效") + +// ErrNotFound 表示目标账号、关键词或指定商品回复不存在。 +var ErrNotFound = errors.New("关键词回复不存在") + +// ErrForbidden 表示目标资源存在但不属于当前用户。 +var ErrForbidden = errors.New("无权操作该关键词回复") + +// ValidationError 表示可安全展示给 HTTP 调用方的稳定输入错误。 +type ValidationError struct { + // Message 是不包含数据库或凭证信息的用户提示。 + Message string +} + +// Error 返回稳定的输入错误提示。 +func (e *ValidationError) Error() string { + if e == nil || e.Message == "" { + return "关键词回复输入无效" + } + return e.Message +} + +// Keyword 是关键词回复的应用层模型,不携带数据库连接或敏感凭证。 +type Keyword struct { + // ID 是关键词规则的持久化标识。 + ID int64 + // CookieID 是规则所属账号标识。 + CookieID string + // Keyword 是触发匹配文本。 + Keyword string + // Reply 是文字回复内容。 + Reply string + // ItemID 是可选的商品范围标识。 + ItemID string + // Type 是 text 或 image 回复类型。 + Type string + // ImageURL 是 image 类型回复使用的图片地址。 + ImageURL string +} + +// Draft 是创建、更新或批量替换关键词规则的业务输入。 +type Draft struct { + // Keyword 是触发匹配文本。 + Keyword string + // Reply 是文字回复内容。 + Reply string + // ItemID 是可选的商品范围标识。 + ItemID string + // Type 是 text 或 image 回复类型;空值按 text 处理。 + Type string + // ImageURL 是 image 类型回复使用的图片地址。 + ImageURL string +} + +// ItemReply 是指定商品回复的应用层模型。 +type ItemReply struct { + // ItemID 是指定商品标识。 + ItemID string + // CookieID 是回复所属账号标识。 + CookieID string + // ReplyContent 是商品命中后的回复正文。 + ReplyContent string +} + +// Repository 定义关键词用例所需的最小持久化能力。 +// userID 必须由实现用于归属隔离,避免应用层把跨用户资源交给数据库操作。 +type Repository interface { + // List 返回指定用户账号的关键词规则。 + List(ctx context.Context, userID int64, cookieID string) ([]Keyword, error) + // Add 创建一条已规范化的关键词规则。 + Add(ctx context.Context, userID int64, cookieID string, draft Draft) (int64, error) + // Replace 删除并重建指定用户账号的全部关键词规则。 + Replace(ctx context.Context, userID int64, cookieID string, drafts []Draft) error + // Update 更新指定用户账号中的关键词规则。 + Update(ctx context.Context, userID int64, cookieID string, id int64, draft Draft) error + // DeleteByID 按持久化标识删除指定用户账号中的关键词规则。 + DeleteByID(ctx context.Context, userID int64, cookieID string, id int64) error + // DeleteByIndex 按稳定 ID 顺序的零基索引删除规则。 + DeleteByIndex(ctx context.Context, userID int64, cookieID string, index int) error + // ListItemReplies 返回指定用户全部账号的商品回复。 + ListItemReplies(ctx context.Context, userID int64) ([]ItemReply, error) + // GetItemReply 读取指定用户账号和商品的回复。 + GetItemReply(ctx context.Context, userID int64, cookieID, itemID string) (ItemReply, error) + // SetItemReply 覆盖指定用户账号和商品的回复。 + SetItemReply(ctx context.Context, userID int64, cookieID, itemID, content string) error + // DeleteItemReply 删除指定用户账号和商品的回复。 + DeleteItemReply(ctx context.Context, userID int64, cookieID, itemID string) error +} + +// Service 编排关键词输入校验、账号归属和持久化操作。 +type Service struct { + // repository 保存由适配器实现的最小关键词持久化 Port。 + repository Repository +} + +// NewService 创建关键词回复应用服务。 +func NewService(repository Repository) *Service { + return &Service{repository: repository} +} + +// List 查询指定用户账号的全部关键词规则。 +func (s *Service) List(ctx context.Context, userID int64, cookieID string) ([]Keyword, error) { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return nil, err + } + return s.repository.List(ctx, userID, cookieID) +} + +// Add 校验并创建一条关键词规则。 +func (s *Service) Add(ctx context.Context, userID int64, cookieID string, draft Draft) (int64, error) { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return 0, err + } + // normalized、err 保存规范化后的规则输入及校验结果。 + normalized, err := normalizeDraft(draft) + if err != nil { + return 0, err + } + return s.repository.Add(ctx, userID, cookieID, normalized) +} + +// Replace 校验并原子替换指定账号的全部关键词规则。 +func (s *Service) Replace(ctx context.Context, userID int64, cookieID string, drafts []Draft) error { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return err + } + // normalized 保存全部通过校验的批量规则输入。 + normalized := make([]Draft, 0, len(drafts)) + // draft 表示当前待规范化的批量规则输入。 + for _, draft := range drafts { + // item、err 保存规范化规则及校验结果。 + item, err := normalizeDraft(draft) + if err != nil { + return err + } + normalized = append(normalized, item) + } + return s.repository.Replace(ctx, userID, cookieID, normalized) +} + +// Update 校验并更新指定 ID 的关键词规则。 +func (s *Service) Update(ctx context.Context, userID int64, cookieID string, id int64, draft Draft) error { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return err + } + if id <= 0 { + return &ValidationError{Message: "无效关键词ID"} + } + // normalized、err 保存规范化后的规则输入及校验结果。 + normalized, err := normalizeDraft(draft) + if err != nil { + return err + } + return s.repository.Update(ctx, userID, cookieID, id, normalized) +} + +// DeleteByID 删除指定 ID 的关键词规则。 +func (s *Service) DeleteByID(ctx context.Context, userID int64, cookieID string, id int64) error { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return err + } + if id <= 0 { + return &ValidationError{Message: "无效关键词ID"} + } + return s.repository.DeleteByID(ctx, userID, cookieID, id) +} + +// DeleteByIndex 按规则列表中的零基索引删除关键词。 +func (s *Service) DeleteByIndex(ctx context.Context, userID int64, cookieID string, index int) error { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return err + } + if index < 0 { + return &ValidationError{Message: "无效关键词索引"} + } + return s.repository.DeleteByIndex(ctx, userID, cookieID, index) +} + +// ListItemReplies 查询当前用户拥有账号的指定商品回复。 +func (s *Service) ListItemReplies(ctx context.Context, userID int64) ([]ItemReply, error) { + // err 表示服务依赖或用户身份校验结果。 + if err := s.validateUser(userID); err != nil { + return nil, err + } + return s.repository.ListItemReplies(ctx, userID) +} + +// GetItemReply 查询指定商品回复;不存在时返回 ErrNotFound。 +func (s *Service) GetItemReply(ctx context.Context, userID int64, cookieID, itemID string) (ItemReply, error) { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return ItemReply{}, err + } + if strings.TrimSpace(itemID) == "" { + return ItemReply{}, &ValidationError{Message: "商品ID不能为空"} + } + return s.repository.GetItemReply(ctx, userID, cookieID, itemID) +} + +// SetItemReply 校验商品标识并覆盖指定商品回复。 +func (s *Service) SetItemReply(ctx context.Context, userID int64, cookieID, itemID, content string) error { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return err + } + if strings.TrimSpace(itemID) == "" { + return &ValidationError{Message: "商品ID不能为空"} + } + return s.repository.SetItemReply(ctx, userID, cookieID, itemID, content) +} + +// DeleteItemReply 删除指定商品回复。 +func (s *Service) DeleteItemReply(ctx context.Context, userID int64, cookieID, itemID string) error { + // err 表示服务依赖、用户身份或账号标识校验结果。 + if err := s.validate(userID, cookieID); err != nil { + return err + } + if strings.TrimSpace(itemID) == "" { + return &ValidationError{Message: "商品ID不能为空"} + } + return s.repository.DeleteItemReply(ctx, userID, cookieID, itemID) +} + +// validate 检查服务依赖、用户身份和账号标识。 +func (s *Service) validate(userID int64, cookieID string) error { + // err 表示服务依赖或用户身份校验结果。 + if err := s.validateUser(userID); err != nil { + return err + } + if s.repository == nil || strings.TrimSpace(cookieID) == "" { + return ErrInvalidInput + } + return nil +} + +// validateUser 检查服务依赖和用户身份。 +func (s *Service) validateUser(userID int64) error { + if s == nil || s.repository == nil { + return ErrInvalidInput + } + if userID <= 0 { + return ErrInvalidUser + } + return nil +} + +// normalizeDraft 统一回复类型和内容字段,并拒绝不完整输入。 +func normalizeDraft(draft Draft) (Draft, error) { + draft.Keyword = strings.TrimSpace(draft.Keyword) + draft.Type = strings.ToLower(strings.TrimSpace(draft.Type)) + draft.ItemID = strings.TrimSpace(draft.ItemID) + draft.Reply = strings.TrimSpace(draft.Reply) + draft.ImageURL = strings.TrimSpace(draft.ImageURL) + if draft.Keyword == "" { + return Draft{}, &ValidationError{Message: "keyword 必填"} + } + if draft.Type == "" { + draft.Type = "text" + } + switch draft.Type { + case "text": + if draft.Reply == "" { + return Draft{}, &ValidationError{Message: "文字回复内容不能为空"} + } + draft.ImageURL = "" + case "image": + if draft.ImageURL == "" { + return Draft{}, &ValidationError{Message: "图片回复 URL 不能为空"} + } + draft.Reply = "" + default: + return Draft{}, &ValidationError{Message: "回复类型必须是 text 或 image"} + } + return draft, nil +} diff --git a/internal/application/keywords/service_test.go b/internal/application/keywords/service_test.go new file mode 100644 index 0000000..a207e4b --- /dev/null +++ b/internal/application/keywords/service_test.go @@ -0,0 +1,197 @@ +package keywords + +import ( + "context" + "errors" + "testing" +) + +// keywordRepositoryFake 保存关键词服务测试所需的可控端口行为。 +type keywordRepositoryFake struct { + // addErr 是创建操作返回的错误。 + addErr error + // addedDraft 保存最近一次创建输入。 + addedDraft Draft + // listRows 是列表操作返回的规则。 + listRows []Keyword + // listErr 是列表操作返回的错误。 + listErr error + // replaceErr 是批量替换返回的错误。 + replaceErr error + // updateErr 是更新返回的错误。 + updateErr error + // deleteErr 是删除返回的错误。 + deleteErr error + // itemRows 是商品回复列表。 + itemRows []ItemReply + // itemErr 是商品回复操作返回的错误。 + itemErr error +} + +// List 实现测试仓储的关键词列表端口。 +func (f *keywordRepositoryFake) List(context.Context, int64, string) ([]Keyword, error) { + return f.listRows, f.listErr +} + +// Add 实现测试仓储的关键词创建端口。 +func (f *keywordRepositoryFake) Add(_ context.Context, _ int64, _ string, draft Draft) (int64, error) { + f.addedDraft = draft + return 9, f.addErr +} + +// Replace 实现测试仓储的关键词批量替换端口。 +func (f *keywordRepositoryFake) Replace(context.Context, int64, string, []Draft) error { + return f.replaceErr +} + +// Update 实现测试仓储的关键词更新端口。 +func (f *keywordRepositoryFake) Update(context.Context, int64, string, int64, Draft) error { + return f.updateErr +} + +// DeleteByID 实现测试仓储的关键词 ID 删除端口。 +func (f *keywordRepositoryFake) DeleteByID(context.Context, int64, string, int64) error { + return f.deleteErr +} + +// DeleteByIndex 实现测试仓储的关键词索引删除端口。 +func (f *keywordRepositoryFake) DeleteByIndex(context.Context, int64, string, int) error { + return f.deleteErr +} + +// ListItemReplies 实现测试仓储的商品回复列表端口。 +func (f *keywordRepositoryFake) ListItemReplies(context.Context, int64) ([]ItemReply, error) { + return f.itemRows, f.itemErr +} + +// GetItemReply 实现测试仓储的商品回复读取端口。 +func (f *keywordRepositoryFake) GetItemReply(context.Context, int64, string, string) (ItemReply, error) { + if f.itemErr != nil { + return ItemReply{}, f.itemErr + } + if len(f.itemRows) == 0 { + return ItemReply{}, ErrNotFound + } + return f.itemRows[0], nil +} + +// SetItemReply 实现测试仓储的商品回复写入端口。 +func (f *keywordRepositoryFake) SetItemReply(context.Context, int64, string, string, string) error { + return f.itemErr +} + +// DeleteItemReply 实现测试仓储的商品回复删除端口。 +func (f *keywordRepositoryFake) DeleteItemReply(context.Context, int64, string, string) error { + return f.itemErr +} + +// TestServiceNormalizesAndCreatesKeyword 验证成功创建会规范化输入并传给仓储。 +func TestServiceNormalizesAndCreatesKeyword(t *testing.T) { + // repository 是本测试使用的可控关键词仓储。 + repository := &keywordRepositoryFake{} + // service 是待验证的关键词应用服务。 + service := NewService(repository) + // id、err 保存创建结果。 + id, err := service.Add(context.Background(), 7, "account-1", Draft{Keyword: " 价格 ", Reply: " 50元 ", Type: "TEXT"}) + if err != nil || id != 9 { + t.Fatalf("创建失败 id=%d err=%v", id, err) + } + if repository.addedDraft.Keyword != "价格" || repository.addedDraft.Reply != "50元" || repository.addedDraft.Type != "text" { + t.Fatalf("输入未规范化: %+v", repository.addedDraft) + } +} + +// TestServiceRejectsInvalidInput 验证用户、账号、关键词和类型参数在仓储调用前被拒绝。 +func TestServiceRejectsInvalidInput(t *testing.T) { + // cases 是覆盖关键参数边界的服务调用集合。 + cases := []struct { + // name 是子测试名称。 + name string + // call 是待验证的服务调用。 + call func(*Service) error + }{ + {name: "invalid user", call: func(service *Service) error { + // err 表示无效用户调用返回的参数错误。 + _, err := service.Add(context.Background(), 0, "account", Draft{Keyword: "k", Reply: "r"}) + return err + }}, + {name: "invalid account", call: func(service *Service) error { + // err 表示空账号标识调用返回的参数错误。 + _, err := service.Add(context.Background(), 1, "", Draft{Keyword: "k", Reply: "r"}) + return err + }}, + {name: "missing keyword", call: func(service *Service) error { + // err 表示缺少关键词调用返回的校验错误。 + _, err := service.Add(context.Background(), 1, "account", Draft{Reply: "r"}) + return err + }}, + {name: "missing image", call: func(service *Service) error { + // err 表示图片规则缺少图片地址的校验错误。 + _, err := service.Add(context.Background(), 1, "account", Draft{Keyword: "k", Type: "image"}) + return err + }}, + {name: "unsupported type", call: func(service *Service) error { + // err 表示不支持的回复类型校验错误。 + _, err := service.Add(context.Background(), 1, "account", Draft{Keyword: "k", Type: "api", Reply: "r"}) + return err + }}, + } + // testCase 表示当前待验证的参数边界。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // err 是当前参数调用返回的错误。 + err := testCase.call(NewService(&keywordRepositoryFake{})) + if err == nil { + t.Fatal("无效参数应返回错误") + } + }) + } +} + +// TestServicePreservesOwnershipAndInfrastructureErrors 验证仓储返回的跨用户和基础设施错误不被吞掉。 +func TestServicePreservesOwnershipAndInfrastructureErrors(t *testing.T) { + // backendErr 是模拟数据库故障的哨兵错误。 + backendErr := errors.New("database unavailable") + // cases 是不同底层错误阶段的服务调用集合。 + cases := []struct { + // name 是子测试名称。 + name string + // repository 是返回当前错误的仓储。 + repository *keywordRepositoryFake + // want 是期望的错误。 + want error + }{ + {name: "forbidden", repository: &keywordRepositoryFake{listErr: ErrForbidden}, want: ErrForbidden}, + {name: "infrastructure", repository: &keywordRepositoryFake{listErr: backendErr}, want: backendErr}, + } + // testCase 表示当前待验证的错误边界。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // err 是列表服务返回的错误。 + _, err := NewService(testCase.repository).List(context.Background(), 1, "account") + if !errors.Is(err, testCase.want) { + t.Fatalf("err=%v want=%v", err, testCase.want) + } + }) + } +} + +// TestServiceItemReplyValidationAndPropagation 验证指定商品回复参数校验及底层错误传播。 +func TestServiceItemReplyValidationAndPropagation(t *testing.T) { + // backendErr 是模拟商品回复数据库故障的哨兵错误。 + backendErr := errors.New("item reply unavailable") + // repository 是返回底层故障的测试仓储。 + repository := &keywordRepositoryFake{itemErr: backendErr} + // service 是待验证的关键词应用服务。 + service := NewService(repository) + // err 表示空商品标识返回的校验错误。 + if err := service.SetItemReply(context.Background(), 1, "account", "", "reply"); err == nil { + t.Fatal("空商品 ID 应被拒绝") + } + // err 表示商品回复持久化阶段返回的基础设施错误。 + if err := service.SetItemReply(context.Background(), 1, "account", "item", "reply"); !errors.Is(err, backendErr) { + t.Fatalf("基础设施错误未透传: %v", err) + } +} + +var _ Repository = (*keywordRepositoryFake)(nil) diff --git a/internal/application/notifications/channels.go b/internal/application/notifications/channels.go index cbfa063..d77e656 100644 --- a/internal/application/notifications/channels.go +++ b/internal/application/notifications/channels.go @@ -210,6 +210,14 @@ func (s *ChannelService) DeleteChannel(ctx context.Context, userID, channelID in return s.repository.DeleteChannel(ctx, channelID, userID) } +// OwnsChannel 查询渠道是否属于指定用户;只返回归属结论,不读取渠道配置。 +func (s *ChannelService) OwnsChannel(ctx context.Context, userID, channelID int64) (bool, error) { + if s == nil || s.repository == nil || userID <= 0 || channelID <= 0 { + return false, ErrChannelInvalidInput + } + return s.repository.OwnsChannel(ctx, channelID, userID) +} + // TestChannel 校验渠道归属并发送固定格式测试通知;body 不包含渠道配置或凭证。 func (s *ChannelService) TestChannel(ctx context.Context, userID, channelID int64, now time.Time) error { if s == nil || s.repository == nil || userID <= 0 || channelID <= 0 { diff --git a/internal/application/notifications/channels_test.go b/internal/application/notifications/channels_test.go index feb8a00..47cf477 100644 --- a/internal/application/notifications/channels_test.go +++ b/internal/application/notifications/channels_test.go @@ -167,6 +167,43 @@ func TestChannelServiceRejectsOwnershipAndStorageFailures(t *testing.T) { } } +// TestChannelServiceOwnsChannelKeepsRepositoryBoundary 验证渠道归属查询只透传非敏感结论和存储错误。 +func TestChannelServiceOwnsChannelKeepsRepositoryBoundary(t *testing.T) { + // cases 描述成功、越权、存储失败和非法输入四类归属结果。 + cases := []struct { + name string + repository *channelRepositoryStub + userID int64 + channelID int64 + want bool + wantErr error + }{ + {name: "owned", repository: &channelRepositoryStub{ownedChannel: true}, userID: 7, channelID: 1, want: true}, + {name: "not owned", repository: &channelRepositoryStub{ownedChannel: false}, userID: 7, channelID: 1}, + {name: "storage error", repository: &channelRepositoryStub{err: errors.New("storage failed")}, userID: 7, channelID: 1, wantErr: errors.New("storage failed")}, + {name: "invalid user", repository: &channelRepositoryStub{ownedChannel: true}, userID: 0, channelID: 1, wantErr: ErrChannelInvalidInput}, + } + // testCase 表示当前验证的渠道归属边界场景。 + for _, testCase := range cases { + // service 是使用当前场景持久化替身的通知渠道服务。 + service := NewChannelService(testCase.repository, nil) + // exists、ownershipErr 保存应用层归属结果。 + exists, ownershipErr := service.OwnsChannel(context.Background(), testCase.userID, testCase.channelID) + if exists != testCase.want { + t.Fatalf("%s: 归属结果=%v,期望=%v", testCase.name, exists, testCase.want) + } + if testCase.wantErr != nil { + if ownershipErr == nil || ownershipErr.Error() != testCase.wantErr.Error() { + t.Fatalf("%s: 错误=%v,期望=%v", testCase.name, ownershipErr, testCase.wantErr) + } + continue + } + if ownershipErr != nil { + t.Fatalf("%s: 意外错误=%v", testCase.name, ownershipErr) + } + } +} + // TestChannelServiceTestSendUsesSafeBody 验证测试发送只生成固定正文,不携带渠道配置。 func TestChannelServiceTestSendUsesSafeBody(t *testing.T) { // repository 是允许渠道归属且不返回敏感配置的端口替身。 diff --git a/internal/application/orders/manual_ship_service.go b/internal/application/orders/manual_ship_service.go index f5102c8..740ab65 100644 --- a/internal/application/orders/manual_ship_service.go +++ b/internal/application/orders/manual_ship_service.go @@ -70,6 +70,13 @@ type ManualShipRepository interface { UpsertOrder(ctx context.Context, orderID string, options UpsertOptions) error } +// ReconciliationRecorder 定义外部订单动作成功后创建补偿记录的最小应用 Port。 +// 该接口由订单应用层声明,由基础设施适配器实现,避免应用层暴露数据库模型。 +type ReconciliationRecorder interface { + // RecordReconciliation 创建外部成功、本地状态待补偿的记录。 + RecordReconciliation(ctx context.Context, orderID, cookieID, kind, message string) (string, error) +} + // ManualShipRuntime 定义手动发货访问平台、自动化、运行时和补偿能力的最小 Port。 type ManualShipRuntime interface { // MTopAvailable 判断平台客户端是否已装配。 @@ -86,8 +93,8 @@ type ManualShipRuntime interface { 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) + // ReconciliationRecorder 嵌入外部动作成功后的补偿记录能力。 + ReconciliationRecorder // ReportPersistenceFailure 记录本地订单状态持久化失败。 ReportPersistenceFailure(orderID string, err error) } diff --git a/internal/application/settings/service.go b/internal/application/settings/service.go new file mode 100644 index 0000000..434523f --- /dev/null +++ b/internal/application/settings/service.go @@ -0,0 +1,405 @@ +// Package settings 提供系统、用户和账号 AI 设置的应用层用例。 +// 本包只依赖消费者定义的 Port,不感知 HTTP、数据库模型或具体网络实现。 +package settings + +import ( + "context" + "errors" + "sort" + "strings" +) + +// ErrInvalidUser 表示调用方没有提供有效的本地用户标识。 +var ErrInvalidUser = errors.New("设置用户标识无效") + +// ErrAccountNotFound 表示目标账号不存在。 +var ErrAccountNotFound = errors.New("设置账号不存在") + +// ErrForbidden 表示目标账号属于其他用户。 +var ErrForbidden = errors.New("无权操作该账号设置") + +// ErrConfigNotFound 表示账号存在但尚未保存 AI 回复设置。 +var ErrConfigNotFound = errors.New("AI 回复设置不存在") + +// SecretChange 描述敏感系统设置的显式三态变更命令。 +type SecretChange struct { + // Action 是 retain、replace 或 clear 之一。 + Action string + // Value 是 replace 操作要保存的新秘密。 + Value string +} + +// AIReplySettings 是不携带模型地址、API 密钥等系统秘密的账号级 AI 设置。 +type AIReplySettings struct { + // CookieID 是设置所属账号的稳定标识。 + CookieID string + // AIEnabled 表示账号 AI 回复是否启用。 + AIEnabled bool + // MaxDiscountPercent 是允许的最大折扣比例。 + MaxDiscountPercent int + // MaxDiscountAmount 是允许的最大折扣金额。 + MaxDiscountAmount int + // MaxBargainRounds 是允许的最大砍价轮次。 + MaxBargainRounds int + // CustomPrompts 是账号自定义提示词。 + CustomPrompts string +} + +// AuditRecord 是敏感设置访问审计的非敏感应用模型。 +type AuditRecord struct { + // UserID 是执行敏感操作的本地用户标识。 + UserID int64 + // Action 是敏感操作类型。 + Action string + // Resource 是被访问的业务资源。 + Resource string + // Keys 是涉及的敏感设置键名,不包含键值。 + Keys []string + // Outcome 是审计结果,例如 accepted。 + Outcome string +} + +// Repository 定义设置用例所需的最小持久化和审计能力。 +type Repository interface { + // IsSensitiveSettingKey 判断设置键是否属于敏感白名单。 + IsSensitiveSettingKey(key string) bool + // SensitiveSettingKeys 返回敏感设置键名,不返回任何秘密值。 + SensitiveSettingKeys() []string + // PublicSystem 返回无需认证展示的系统设置。 + PublicSystem(ctx context.Context) (map[string]string, error) + // RedactedSystem 返回管理员可见但已脱敏的系统设置。 + RedactedSystem(ctx context.Context) (map[string]string, error) + // GetSystem 读取指定系统设置;仅应用服务内部用于受控业务操作。 + GetSystem(ctx context.Context, key string) (string, error) + // ReadSensitiveSystem 审计后读取指定敏感系统设置。 + ReadSensitiveSystem(ctx context.Context, userID int64, key, action, resource string) (string, error) + // ApplySystemChanges 原子保存普通设置和敏感变更命令。 + ApplySystemChanges(ctx context.Context, values map[string]string, secrets map[string]SecretChange) error + // SetSystem 保存一项普通系统设置。 + SetSystem(ctx context.Context, key, value string) error + // AddAudit 写入不包含秘密值的访问审计。 + AddAudit(ctx context.Context, record AuditRecord) error + // ListUser 返回指定用户的全部用户设置。 + ListUser(ctx context.Context, userID int64) (map[string]string, error) + // GetUser 返回指定用户的一项设置;不存在时返回空值。 + GetUser(ctx context.Context, userID int64, key string) (string, error) + // SetUser 保存指定用户的一项设置。 + SetUser(ctx context.Context, userID int64, key, value string) error + // CheckOwnership 返回账号的非敏感所有者标识。 + CheckOwnership(ctx context.Context, userID int64, cookieID string) (int64, error) + // ListAIReply 返回用户范围内的账号 AI 设置摘要。 + ListAIReply(ctx context.Context, userID int64) ([]AIReplySettings, error) + // GetAIReply 返回指定用户账号的 AI 设置摘要。 + GetAIReply(ctx context.Context, userID int64, cookieID string) (AIReplySettings, error) + // UpsertAIReply 保存指定账号的 AI 设置摘要。 + UpsertAIReply(ctx context.Context, cookieID string, settings AIReplySettings) error +} + +// ModelClient 定义读取远端 AI 模型列表所需的最小网络能力。 +type ModelClient interface { + // Fetch 获取指定 AI 服务地址的模型名称,调用方不得把 API 密钥写入日志或响应。 + Fetch(ctx context.Context, baseURL, apiKey string) ([]string, error) +} + +// Service 编排设置读取、校验、审计和持久化,不依赖 HTTP 或数据库类型。 +type Service struct { + // repository 提供设置持久化与敏感访问审计能力。 + repository Repository + // modelClient 提供远端模型目录读取能力。 + modelClient ModelClient +} + +// IsSensitiveSettingKey 判断 HTTP 兼容层中的设置键是否属于敏感白名单。 +func (s *Service) IsSensitiveSettingKey(key string) bool { + return s != nil && s.repository != nil && s.repository.IsSensitiveSettingKey(key) +} + +// NewService 构造设置应用服务。 +func NewService(repository Repository, modelClient ModelClient) *Service { + // service 保存调用方提供的设置 Port 与模型客户端。 + service := &Service{repository: repository, modelClient: modelClient} + return service +} + +// PublicSystem 读取公开系统设置。 +func (s *Service) PublicSystem(ctx context.Context) (map[string]string, error) { + // err 表示设置 Port 未装配或公开设置读取失败。 + if err := s.validateRepository(); err != nil { + return nil, err + } + return s.repository.PublicSystem(ctx) +} + +// GetSystem 返回管理员可见的系统设置,并先记录完整敏感键白名单的读取审计。 +func (s *Service) GetSystem(ctx context.Context, userID int64) (map[string]string, error) { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return nil, err + } + // keys 是本次管理员读取需要审计的敏感键名集合。 + keys := s.repository.SensitiveSettingKeys() + // err 表示敏感设置读取审计写入失败。 + if err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.read", Resource: "system_settings", Keys: keys}); err != nil { + return nil, err + } + return s.repository.RedactedSystem(ctx) +} + +// ApplySystemChanges 校验并原子保存系统设置,敏感命令写入前必须完成审计。 +func (s *Service) ApplySystemChanges(ctx context.Context, userID int64, values map[string]string, secrets map[string]SecretChange) error { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return err + } + if len(values) == 0 && len(secrets) == 0 { + return errors.New("设置不能为空") + } + // err 表示普通设置值违反敏感键或键名约束。 + if err := s.validateValues(values); err != nil { + return err + } + // keys 保存待写入审计记录的敏感设置键名。 + keys := make([]string, 0, len(secrets)) + // key 是待审计的敏感设置键;change 是对应的三态命令。 + for key, change := range secrets { + if !s.repository.IsSensitiveSettingKey(key) || !validSecretAction(change) { + return errors.New("敏感设置命令无效") + } + if change.Action == "replace" && strings.TrimSpace(change.Value) == "" { + return errors.New("敏感设置命令无效") + } + keys = append(keys, key) + } + if len(keys) > 0 { + // err 表示敏感设置写入审计失败。 + if err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.write", Resource: "system_settings", Keys: keys}); err != nil { + return err + } + } + return s.repository.ApplySystemChanges(ctx, values, secrets) +} + +// SetSystem 保存单项系统设置,并把敏感设置的三态命令统一交给应用层校验。 +func (s *Service) SetSystem(ctx context.Context, userID int64, key, value, action string) error { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return err + } + key = strings.TrimSpace(key) + if key == "" || len(key) > 100 { + return errors.New("设置键无效") + } + if s.repository.IsSensitiveSettingKey(key) { + // change 是敏感设置的显式三态命令。 + change := SecretChange{Action: action, Value: value} + if !validSecretAction(change) || change.Action == "replace" && strings.TrimSpace(change.Value) == "" { + return errors.New("敏感设置命令无效") + } + // err 表示敏感设置写入审计失败。 + if err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.write", Resource: "system_settings", Keys: []string{key}}); err != nil { + return err + } + return s.repository.ApplySystemChanges(ctx, nil, map[string]SecretChange{key: change}) + } + return s.repository.SetSystem(ctx, key, value) +} + +// ListUser 读取当前用户的全部偏好设置。 +func (s *Service) ListUser(ctx context.Context, userID int64) (map[string]string, error) { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return nil, err + } + return s.repository.ListUser(ctx, userID) +} + +// GetUser 读取当前用户的一项偏好设置。 +func (s *Service) GetUser(ctx context.Context, userID int64, key string) (string, error) { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return "", err + } + return s.repository.GetUser(ctx, userID, strings.TrimSpace(key)) +} + +// SetUser 保存当前用户的一项偏好设置。 +func (s *Service) SetUser(ctx context.Context, userID int64, key, value string) error { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return err + } + key = strings.TrimSpace(key) + if key == "" || len(key) > 100 { + return errors.New("设置键无效") + } + return s.repository.SetUser(ctx, userID, key, value) +} + +// ListAIReply 查询当前用户账号的 AI 设置摘要。 +func (s *Service) ListAIReply(ctx context.Context, userID int64) ([]AIReplySettings, error) { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return nil, err + } + return s.repository.ListAIReply(ctx, userID) +} + +// GetAIReply 查询账号 AI 设置,并区分账号不存在和未配置设置。 +func (s *Service) GetAIReply(ctx context.Context, userID int64, cookieID string) (AIReplySettings, error) { + // err 表示账号归属校验失败。 + if err := s.ensureOwned(ctx, userID, cookieID); err != nil { + return AIReplySettings{}, err + } + return s.repository.GetAIReply(ctx, userID, strings.TrimSpace(cookieID)) +} + +// UpsertAIReply 校验账号归属和数值边界后保存 AI 设置。 +func (s *Service) UpsertAIReply(ctx context.Context, userID int64, cookieID string, settings AIReplySettings) error { + // err 表示账号归属校验失败。 + if err := s.ensureOwned(ctx, userID, cookieID); err != nil { + return err + } + if settings.MaxDiscountPercent < 0 || settings.MaxDiscountPercent > 100 { + return errors.New("最大折扣比例必须在 0 到 100 之间") + } + if settings.MaxDiscountAmount < 0 { + return errors.New("最大折扣金额不能小于 0") + } + if settings.MaxBargainRounds < 1 || settings.MaxBargainRounds > 10 { + return errors.New("最大砍价轮次必须在 1 到 10 之间") + } + settings.CookieID = strings.TrimSpace(cookieID) + return s.repository.UpsertAIReply(ctx, settings.CookieID, settings) +} + +// ListAIModels 读取远端模型目录,API 密钥使用前必须经过受控读取或审计。 +func (s *Service) ListAIModels(ctx context.Context, userID int64, baseURL, apiKey string) ([]string, error) { + // err 表示设置 Port 未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return nil, err + } + if s.modelClient == nil { + return nil, errors.New("AI 模型客户端未初始化") + } + baseURL = strings.TrimSpace(baseURL) + if baseURL == "" { + // err 表示系统 AI 地址读取失败。 + var err error + baseURL, err = s.repository.GetSystem(ctx, "ai_api_url") + if err != nil { + return nil, err + } + } + if baseURL == "" { + baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1" + } + apiKey = strings.TrimSpace(apiKey) + if apiKey == "" { + // err 表示敏感 API 密钥读取或审计失败。 + var err error + apiKey, err = s.repository.ReadSensitiveSystem(ctx, userID, "ai_api_key", "settings.use", "ai_models") + if err != nil { + return nil, err + } + } else if // err 表示外部传入 API 密钥的使用审计失败。 + err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.use", Resource: "ai_models", Keys: []string{"ai_api_key"}}); err != nil { + return nil, err + } + return s.modelClient.Fetch(ctx, baseURL, apiKey) +} + +// validateRepository 检查应用服务的基础设施 Port 是否已装配。 +func (s *Service) validateRepository() error { + if s == nil || s.repository == nil { + return errors.New("设置 repository 未初始化") + } + return nil +} + +// validateUser 检查设置服务及用户身份,避免无效身份进入数据库 Port。 +func (s *Service) validateUser(userID int64) error { + // err 表示设置 Port 未装配。 + if err := s.validateRepository(); err != nil { + return err + } + if userID <= 0 { + return ErrInvalidUser + } + return nil +} + +// ensureOwned 统一执行用户身份和非敏感账号所有权校验。 +func (s *Service) ensureOwned(ctx context.Context, userID int64, cookieID string) error { + // err 表示设置服务未装配或用户身份无效。 + if err := s.validateUser(userID); err != nil { + return err + } + cookieID = strings.TrimSpace(cookieID) + if cookieID == "" { + return ErrAccountNotFound + } + // ownerID、err 保存非敏感账号所有者标识及查询错误。 + ownerID, err := s.repository.CheckOwnership(ctx, userID, cookieID) + if err != nil { + return err + } + if ownerID != userID { + return ErrForbidden + } + return nil +} + +// validateValues 校验批量普通设置键值,阻止敏感值进入普通参数。 +func (s *Service) validateValues(values map[string]string) error { + // key 是待校验的普通设置键名。 + for key := range values { + key = strings.TrimSpace(key) + if key == "" || len(key) > 100 { + return errors.New("设置键无效") + } + if s.repository.IsSensitiveSettingKey(key) { + return errors.New("敏感设置必须放入 secrets 命令") + } + } + return nil +} + +// validSecretAction 判断敏感设置命令是否具有受支持的三态语义。 +func validSecretAction(change SecretChange) bool { + switch change.Action { + case "retain", "replace", "clear": + return true + default: + return false + } +} + +// audit 写入排序去重后的敏感设置键名,确保审计内容不包含秘密值。 +func (s *Service) audit(ctx context.Context, record AuditRecord) error { + if len(record.Keys) == 0 { + return nil + } + // normalizedKeys 保存排序去重后的键名。 + normalizedKeys := make([]string, 0, len(record.Keys)) + // seen 保存已经加入审计记录的键名。 + seen := make(map[string]struct{}, len(record.Keys)) + // key 是当前待规范化的敏感设置键名。 + for _, key := range record.Keys { + key = strings.TrimSpace(key) + if key == "" { + continue + } + // exists 表示键名是否已经加入当前审计记录。 + if _, exists := seen[key]; exists { + continue + } + seen[key] = struct{}{} + normalizedKeys = append(normalizedKeys, key) + } + sort.Strings(normalizedKeys) + record.Keys = normalizedKeys + if record.Outcome == "" { + record.Outcome = "accepted" + } + return s.repository.AddAudit(ctx, record) +} diff --git a/internal/application/settings/service_test.go b/internal/application/settings/service_test.go new file mode 100644 index 0000000..94ce94d --- /dev/null +++ b/internal/application/settings/service_test.go @@ -0,0 +1,238 @@ +package settings + +import ( + "context" + "errors" + "strings" + "testing" +) + +// settingsRepositoryFake 是设置应用服务测试使用的内存 Port。 +type settingsRepositoryFake struct { + // sensitiveKeys 保存测试环境允许的敏感设置键。 + sensitiveKeys []string + // audits 保存收到的非敏感审计记录。 + audits []AuditRecord + // auditErr 模拟敏感审计存储故障。 + auditErr error + // values 保存最近一次系统设置普通值。 + values map[string]string + // secrets 保存最近一次系统设置敏感命令。 + secrets map[string]SecretChange + // ownerID 保存账号所有者标识。 + ownerID int64 + // aiSettings 保存账号 AI 设置摘要。 + aiSettings map[string]AIReplySettings + // systemValues 保存系统设置读取值。 + systemValues map[string]string +} + +// IsSensitiveSettingKey 判断测试设置键是否属于敏感集合。 +func (r *settingsRepositoryFake) IsSensitiveSettingKey(key string) bool { + // candidate 是测试敏感键集合中的当前候选值。 + for _, candidate := range r.sensitiveKeys { + if candidate == key { + return true + } + } + return false +} + +// SensitiveSettingKeys 返回测试敏感设置键名。 +func (r *settingsRepositoryFake) SensitiveSettingKeys() []string { + return append([]string(nil), r.sensitiveKeys...) +} + +// PublicSystem 返回测试公开设置。 +func (r *settingsRepositoryFake) PublicSystem(context.Context) (map[string]string, error) { + return map[string]string{"theme_color": "blue"}, nil +} + +// RedactedSystem 返回测试脱敏设置。 +func (r *settingsRepositoryFake) RedactedSystem(context.Context) (map[string]string, error) { + return map[string]string{"ai_api_key_configured": "true"}, nil +} + +// GetSystem 返回测试系统设置。 +func (r *settingsRepositoryFake) GetSystem(_ context.Context, key string) (string, error) { + return r.systemValues[key], nil +} + +// ReadSensitiveSystem 返回测试敏感设置值并模拟数据库已完成审计。 +func (r *settingsRepositoryFake) ReadSensitiveSystem(_ context.Context, _ int64, _, _, _ string) (string, error) { + return "stored-secret", nil +} + +// ApplySystemChanges 保存测试系统设置变更。 +func (r *settingsRepositoryFake) ApplySystemChanges(_ context.Context, values map[string]string, secrets map[string]SecretChange) error { + r.values = values + r.secrets = secrets + return nil +} + +// SetSystem 保存测试单项系统设置。 +func (r *settingsRepositoryFake) SetSystem(_ context.Context, key, value string) error { + if r.systemValues == nil { + r.systemValues = make(map[string]string) + } + r.systemValues[key] = value + return nil +} + +// AddAudit 保存测试审计记录。 +func (r *settingsRepositoryFake) AddAudit(_ context.Context, record AuditRecord) error { + if r.auditErr != nil { + return r.auditErr + } + r.audits = append(r.audits, record) + return nil +} + +// ListUser 返回测试用户设置。 +func (r *settingsRepositoryFake) ListUser(context.Context, int64) (map[string]string, error) { + return map[string]string{"theme": "dark"}, nil +} + +// GetUser 返回测试用户单项设置。 +func (r *settingsRepositoryFake) GetUser(context.Context, int64, string) (string, error) { + return "dark", nil +} + +// SetUser 保存测试用户单项设置。 +func (r *settingsRepositoryFake) SetUser(context.Context, int64, string, string) error { return nil } + +// CheckOwnership 返回测试账号所有者。 +func (r *settingsRepositoryFake) CheckOwnership(context.Context, int64, string) (int64, error) { + if r.ownerID == 0 { + return 0, ErrAccountNotFound + } + return r.ownerID, nil +} + +// ListAIReply 返回测试账号 AI 设置列表。 +func (r *settingsRepositoryFake) ListAIReply(context.Context, int64) ([]AIReplySettings, error) { + // result 保存测试账号 AI 设置列表。 + result := make([]AIReplySettings, 0, len(r.aiSettings)) + // setting 是当前待复制的测试账号 AI 设置。 + for _, setting := range r.aiSettings { + result = append(result, setting) + } + return result, nil +} + +// GetAIReply 返回测试账号 AI 设置。 +func (r *settingsRepositoryFake) GetAIReply(_ context.Context, _ int64, cookieID string) (AIReplySettings, error) { + // setting、ok 保存测试账号 AI 设置及是否存在。 + setting, ok := r.aiSettings[cookieID] + if !ok { + return AIReplySettings{}, ErrConfigNotFound + } + return setting, nil +} + +// UpsertAIReply 保存测试账号 AI 设置。 +func (r *settingsRepositoryFake) UpsertAIReply(_ context.Context, cookieID string, setting AIReplySettings) error { + if r.aiSettings == nil { + r.aiSettings = make(map[string]AIReplySettings) + } + r.aiSettings[cookieID] = setting + return nil +} + +// modelClientFake 是 AI 模型客户端测试替身。 +type modelClientFake struct { + // calls 保存收到的端点和密钥,测试只比较是否传递,不输出秘密。 + calls int +} + +// Fetch 返回固定模型列表并记录调用次数。 +func (c *modelClientFake) Fetch(context.Context, string, string) ([]string, error) { + c.calls++ + return []string{"qwen-plus"}, nil +} + +// TestServiceApplySystemChangesAuditsSecrets 验证敏感系统设置写入先审计再进入 Port。 +func TestServiceApplySystemChangesAuditsSecrets(t *testing.T) { + // repository 保存测试设置 Port。 + repository := &settingsRepositoryFake{sensitiveKeys: []string{"ai_api_key"}} + // service 保存待测试的设置应用服务。 + service := NewService(repository, nil) + // err 表示敏感系统设置写入结果。 + err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"theme_color": "blue"}, map[string]SecretChange{"ai_api_key": {Action: "replace", Value: "secret"}}) + if err != nil { + t.Fatalf("apply settings: %v", err) + } + if len(repository.audits) != 1 || repository.audits[0].Action != "settings.write" || repository.audits[0].Keys[0] != "ai_api_key" { + t.Fatalf("unexpected audit records: %+v", repository.audits) + } + // forwarded 表示敏感命令是否完整传递到 Port;断言失败时不输出秘密值。 + forwarded, ok := repository.secrets["ai_api_key"] + if !ok || forwarded.Action != "replace" || forwarded.Value != "secret" { + t.Fatalf("secret command was not forwarded: action=%q present=%t", forwarded.Action, ok) + } +} + +// TestServiceRejectsSensitivePlainValue 验证敏感键不能通过普通设置值写入。 +func TestServiceRejectsSensitivePlainValue(t *testing.T) { + // repository 保存测试设置 Port。 + repository := &settingsRepositoryFake{sensitiveKeys: []string{"ai_api_key"}} + // service 保存待测试的设置应用服务。 + service := NewService(repository, nil) + // err 表示错误的普通敏感值写入结果。 + err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"ai_api_key": "secret"}, nil) + if err == nil || !strings.Contains(err.Error(), "敏感设置") { + t.Fatalf("sensitive plain value should fail: %v", err) + } +} + +// TestServiceAIReplyOwnershipAndValidation 验证账号 AI 设置的归属和数值约束。 +func TestServiceAIReplyOwnershipAndValidation(t *testing.T) { + // repository 保存测试账号所有者及配置。 + repository := &settingsRepositoryFake{ownerID: 7, aiSettings: make(map[string]AIReplySettings)} + // service 保存待测试的设置应用服务。 + service := NewService(repository, nil) + // forbiddenErr 保存跨用户更新返回的权限错误。 + if forbiddenErr := service.UpsertAIReply(context.Background(), 8, "acc1", AIReplySettings{MaxDiscountPercent: 1, MaxDiscountAmount: 1, MaxBargainRounds: 1}); !errors.Is(forbiddenErr, ErrForbidden) { + t.Fatalf("cross-user update error=%v", forbiddenErr) + } + // invalidErr 保存非法折扣边界返回的校验错误。 + if invalidErr := service.UpsertAIReply(context.Background(), 7, "acc1", AIReplySettings{MaxDiscountPercent: 101, MaxDiscountAmount: 1, MaxBargainRounds: 1}); invalidErr == nil { + t.Fatal("invalid discount should fail") + } +} + +// TestServiceListAIModelsAuditsExplicitKey 验证外部传入 API 密钥也必须留下使用审计。 +func TestServiceListAIModelsAuditsExplicitKey(t *testing.T) { + // repository 保存测试系统设置 Port。 + repository := &settingsRepositoryFake{systemValues: map[string]string{"ai_api_url": "https://example.test/v1"}} + // client 保存模型目录测试客户端。 + client := &modelClientFake{} + // service 保存待测试的设置应用服务。 + service := NewService(repository, client) + // models、err 保存模型目录结果和调用错误。 + models, err := service.ListAIModels(context.Background(), 7, "https://example.test/v1", "provided-secret") + if err != nil || len(models) != 1 || client.calls != 1 { + t.Fatalf("models=%v err=%v calls=%d", models, err, client.calls) + } + if len(repository.audits) != 1 || repository.audits[0].Resource != "ai_models" { + t.Fatalf("missing model access audit: %+v", repository.audits) + } +} + +// TestServiceListAIModelsFailsClosedWhenAuditUnavailable 验证模型请求不会绕过敏感密钥审计。 +func TestServiceListAIModelsFailsClosedWhenAuditUnavailable(t *testing.T) { + // repository 保存会返回审计故障的设置 Port。 + repository := &settingsRepositoryFake{auditErr: errors.New("audit unavailable")} + // client 保存模型目录测试客户端。 + client := &modelClientFake{} + // service 保存待测试的设置应用服务。 + service := NewService(repository, client) + // models、err 保存审计失败时的模型结果和错误。 + models, err := service.ListAIModels(context.Background(), 7, "https://example.test/v1", "provided-secret") + if err == nil || models != nil || client.calls != 0 { + t.Fatalf("audit failure should stop model request: models=%v err=%v calls=%d", models, err, client.calls) + } +} + +var _ Repository = (*settingsRepositoryFake)(nil) +var _ ModelClient = (*modelClientFake)(nil) diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 49f0d68..6f914f5 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -165,6 +165,22 @@ func SessionFromContext(ctx context.Context) *db.Session { return v } +// SessionIdentity 是 HTTP 应用层读取当前用户身份所需的最小会话视图,不暴露数据库会话字段。 +type SessionIdentity struct { + // UserID 是当前认证用户的稳定数据库标识,仅用于应用层归属和授权判断。 + UserID int64 +} + +// IdentityFromContext 从请求上下文提取最小用户身份;未认证或上下文没有会话时返回 nil。 +func IdentityFromContext(ctx context.Context) *SessionIdentity { + // session 保存认证中间件注入的完整会话,仅在认证包内部读取并裁剪为最小身份视图。 + session := SessionFromContext(ctx) + if session == nil { + return nil + } + return &SessionIdentity{UserID: session.UserID} +} + // InitAdmin 创建或重置 admin 管理员账号,是 cmd/server -init-admin 与 // cmd/init-admin 共用的公共入口。返回 created=true 表示新建 admin, // false 表示重置已存在 admin 的密码。邮箱仅在新建时使用。 diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go index 40136fa..8f64815 100644 --- a/internal/auth/auth_test.go +++ b/internal/auth/auth_test.go @@ -76,6 +76,26 @@ func TestLoginAndMiddleware(t *testing.T) { } } +// TestIdentityFromContextReturnsMinimalUserView 验证通用 HTTP 辅助只接收用户标识而不暴露完整数据库会话。 +func TestIdentityFromContextReturnsMinimalUserView(t *testing.T) { + // ctx 保存包含完整会话的测试上下文,模拟认证中间件已经完成会话解析。 + ctx := WithSession(context.Background(), &db.Session{UserID: 42, Username: "admin", IsAdmin: true}) + // identity 保存认证包裁剪后的最小用户身份视图。 + identity := IdentityFromContext(ctx) + if identity == nil || identity.UserID != 42 { + t.Fatalf("身份视图异常: %+v", identity) + } +} + +// TestIdentityFromContextReturnsNilWithoutSession 验证未认证请求不会伪造用户身份。 +func TestIdentityFromContextReturnsNilWithoutSession(t *testing.T) { + // identity 保存无会话上下文经过认证包裁剪后的结果,应保持为空。 + identity := IdentityFromContext(context.Background()) + if identity != nil { + t.Fatalf("无会话时应返回 nil,得到 %+v", identity) + } +} + // TestRequireAuthAndAdmin 负责TestRequireAuthAndAdmin相关处理。 func TestRequireAuthAndAdmin(t *testing.T) { // svc、cleanup 保存svc、cleanup,供当前处理流程使用 diff --git a/internal/automation/account_tasks.go b/internal/automation/account_tasks.go index 8a5de28..06b79aa 100644 --- a/internal/automation/account_tasks.go +++ b/internal/automation/account_tasks.go @@ -231,8 +231,11 @@ func (c *accountTaskCoordinator) finishAccountTaskRun(ctx context.Context, runKe } // quarantineMessage 说明外部动作结果已经产生但本地状态未能正常收口,禁止系统自动重放。 quarantineMessage := fmt.Sprintf("账号任务外部动作结果可能已执行,但运行状态保存失败,请人工核对,禁止自动重放: %v", finishErr) - // quarantineErr 表示把运行记录转为人工核对状态时的数据库错误。 - quarantineErr := c.repository.FinishRun(ctx, runKey, "needs_review", success, failed, quarantineMessage, 0) + // quarantineCtx、cancel 确保人工核对状态写入不受已取消请求影响,并在函数返回时释放计时器。 + quarantineCtx, cancel := newAccountTaskCompensationContext(ctx) + defer cancel() + // quarantineErr 表示补偿上下文下写入 needs_review 隔离状态的数据库错误;该错误必须与首次收口失败一并返回。 + quarantineErr := c.repository.FinishRun(quarantineCtx, runKey, "needs_review", success, failed, quarantineMessage, 0) if quarantineErr != nil { return errors.Join( errAutomationNeedsReview, @@ -248,8 +251,11 @@ func (c *accountTaskCoordinator) finishAccountTaskRun(ctx context.Context, runKe func (c *accountTaskCoordinator) quarantineAccountTaskRun(ctx context.Context, runKey string, success, failed int, reason error) error { // quarantineMessage 将本地持久化故障转换为运维可识别的人工核对原因。 quarantineMessage := fmt.Sprintf("账号任务外部动作结果未知,请人工核对,禁止自动重放: %v", reason) - // quarantineErr 表示写入人工核对状态时的数据库错误。 - quarantineErr := c.repository.FinishRun(ctx, runKey, "needs_review", success, failed, quarantineMessage, 0) + // quarantineCtx、cancel 确保人工核对状态写入不受已取消请求影响,并在函数返回时释放计时器。 + quarantineCtx, cancel := newAccountTaskCompensationContext(ctx) + defer cancel() + // quarantineErr 表示补偿上下文下再次写入 needs_review 状态的数据库错误;它决定是否需要同时报告两次持久化失败。 + quarantineErr := c.repository.FinishRun(quarantineCtx, runKey, "needs_review", success, failed, quarantineMessage, 0) if quarantineErr != nil { return errors.Join( errAutomationNeedsReview, @@ -260,6 +266,11 @@ func (c *accountTaskCoordinator) quarantineAccountTaskRun(ctx context.Context, r return errors.Join(errAutomationNeedsReview, fmt.Errorf("账号任务本地持久化失败: %w", reason)) } +// newAccountTaskCompensationContext 基于调用方值域创建不受其取消影响的短时补偿上下文;返回的取消函数由调用方负责释放计时器。 +func newAccountTaskCompensationContext(parent context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.WithoutCancel(parent), 5*time.Second) +} + // runAutoRate 执行自动评价任务,并在明确的单值 Cookie 查询边界内调用平台 API。 func (c *accountTaskCoordinator) runAutoRate(ctx context.Context, settings db.AccountTaskSettings) (AccountTaskSummary, error) { // summary 保存summary,供当前处理流程使用 diff --git a/internal/automation/account_tasks_test.go b/internal/automation/account_tasks_test.go index c267e7a..a76629a 100644 --- a/internal/automation/account_tasks_test.go +++ b/internal/automation/account_tasks_test.go @@ -26,6 +26,21 @@ type fakeAccountTaskClient struct { polishErr error } +// cancelingAccountTaskClient 在评价动作已经返回成功前取消调用方上下文,用于验证补偿收口不会依赖已取消请求。 +type cancelingAccountTaskClient struct { + // fakeAccountTaskClient 提供除取消场景外的账号任务平台响应。 + *fakeAccountTaskClient + // cancel 负责模拟外部动作完成后请求生命周期结束。 + cancel context.CancelFunc +} + +// RateBuyer 在记录远端动作成功结果前取消调用方上下文。 +func (c *cancelingAccountTaskClient) RateBuyer(_ context.Context, cookiesStr, tradeID, feedback string) (*mtop.AccountTaskResult, error) { + c.rateCalls++ + c.cancel() + return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil +} + // FetchPendingRateOrders 负责FetchPendingRate订单列表相关处理。 func (f *fakeAccountTaskClient) FetchPendingRateOrders(context.Context, string, int, int) (*mtop.PendingRateResult, error) { f.pendingCalls++ @@ -173,6 +188,57 @@ func TestAccountTaskRateFinishAndQuarantineFailureJoinsErrors(t *testing.T) { } } +// TestAccountTaskRateCancellationQuarantinesAndBlocksRetry 验证外部评价成功后请求取消仍能隔离运行并阻止重复重试。 +func TestAccountTaskRateCancellationQuarantinesAndBlocksRetry(t *testing.T) { + // store 是当前测试使用的 SQLite 自动化存储。 + store, cleanup := newAutomationTestStore(t) + defer cleanup() + // setupCtx 是测试设置写入共用的数据库上下文。 + setupCtx := context.Background() + // settingsErr 表示写入自动评价设置时的数据库错误。 + if settingsErr := store.AccountTasks.Upsert(setupCtx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true, + RateContent: "交易愉快", PolishTime: "03:00"}); settingsErr != nil { + t.Fatal(settingsErr) + } + // requestCtx、cancel 模拟外部动作完成后被上层请求取消的生命周期。 + requestCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + // client 在评价动作返回成功前取消 requestCtx,并保留调用次数用于重试断言。 + client := &cancelingAccountTaskClient{ + fakeAccountTaskClient: &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-cancelled"}}}, + cancel: cancel, + } + // center 是待验证取消后补偿收口逻辑的自动化中心。 + center := New(store, testSenderProvider{sender: &testSender{}}, nil) + center.SetAccountTaskClient(client) + // runErr 保存外部评价已完成但调用方取消后的人工核对错误。 + _, runErr := center.RunAccountTask(requestCtx, "cid", TaskAutoRate) + if !errors.Is(runErr, errAutomationNeedsReview) || !strings.Contains(runErr.Error(), "保存账号任务运行结果失败") { + t.Fatalf("取消后的外部成功应隔离运行,err=%v", runErr) + } + if client.rateCalls != 1 { + t.Fatalf("首次外部评价调用次数=%d want 1", client.rateCalls) + } + // status、successCount 保存补偿收口后的任务状态和已确认成功数量。 + var status string + // successCount 保存数据库记录的外部评价成功数,用于确认取消请求未抹掉已经完成的动作结果。 + var successCount int + // queryErr 表示读取补偿状态时的数据库错误。 + queryErr := store.DB.QueryRowContext(context.Background(), `SELECT status,success_count FROM account_task_runs WHERE run_key=?`, + "rate:cid:order-cancelled").Scan(&status, &successCount) + if queryErr != nil { + t.Fatal(queryErr) + } + if status != "needs_review" || successCount != 1 { + t.Fatalf("取消后任务状态错误: status=%q success=%d", status, successCount) + } + // retrySummary、retryErr 保存新请求尝试重跑时的结果,确认人工核对状态不会被自动重放。 + retrySummary, retryErr := center.RunAccountTask(context.Background(), "cid", TaskAutoRate) + if retryErr != nil || retrySummary.Skipped != 1 || client.rateCalls != 1 { + t.Fatalf("人工核对任务不应自动重试: summary=%+v calls=%d err=%v", retrySummary, client.rateCalls, retryErr) + } +} + // TestAccountTaskPolishMarkFailureQuarantinesExternalSuccess 验证商品擦亮成功但日期索引写入失败时会隔离运行记录。 func TestAccountTaskPolishMarkFailureQuarantinesExternalSuccess(t *testing.T) { // store 是当前测试使用的 SQLite 自动化存储。 diff --git a/internal/db/migrations/mysql/00019_deferred_automation_tasks.sql b/internal/db/migrations/mysql/00019_deferred_automation_tasks.sql index 7cc4875..8009053 100644 --- a/internal/db/migrations/mysql/00019_deferred_automation_tasks.sql +++ b/internal/db/migrations/mysql/00019_deferred_automation_tasks.sql @@ -13,7 +13,7 @@ CREATE TABLE automation_pending_tasks ( created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, CONSTRAINT fk_pending_automation_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE -); +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE INDEX idx_automation_pending_due ON automation_pending_tasks(status, due_at, lease_expires_at); -- +goose Down diff --git a/internal/renewal/scheduler.go b/internal/renewal/scheduler.go index 9d919bb..3e2dfc2 100644 --- a/internal/renewal/scheduler.go +++ b/internal/renewal/scheduler.go @@ -71,6 +71,10 @@ type Scheduler struct { watchers sync.WaitGroup // runCancel 取消当前调度器派生的运行上下文;只有 Run 成功登记后才非空。 runCancel context.CancelFunc + // runStarted 标识 Run 是否已经登记并创建了调度器运行上下文。 + runStarted bool + // stopRequested 标识尚未启动时是否已经收到停止请求,防止停止与启动并发时重新逃逸。 + stopRequested bool } // RenewalNotifier 保存RenewalNotifier,供当前处理流程使用 @@ -113,6 +117,13 @@ func (s *Scheduler) Run(ctx context.Context) { // runCtx、cancel 将父生命周期转换为调度器私有的可主动停止上下文。 runCtx, cancel := context.WithCancel(ctx) s.mu.Lock() + if s.stopRequested { + s.mu.Unlock() + cancel() + return + } + // runStarted 标识调度器已进入可等待的运行状态。 + s.runStarted = true s.runCancel = cancel s.mu.Unlock() go func() { @@ -149,7 +160,21 @@ func (s *Scheduler) StopContext(ctx context.Context) error { s.mu.Lock() // cancel 是调度器运行上下文的取消函数快照,避免持锁执行取消回调。 cancel := s.runCancel + // runStarted 区分尚未启动的调度器,避免等待永远不会关闭的 done 通道。 + runStarted := s.runStarted + if !runStarted { + // stopRequested 将先停止与后续 Run 串行化,保证停止请求不会被并发启动绕过。 + if !s.stopRequested { + s.stopRequested = true + if s.done != nil { + close(s.done) + } + } + } s.mu.Unlock() + if !runStarted { + return nil + } if cancel != nil { cancel() } diff --git a/internal/renewal/scheduler_test.go b/internal/renewal/scheduler_test.go index e0732eb..3351d02 100644 --- a/internal/renewal/scheduler_test.go +++ b/internal/renewal/scheduler_test.go @@ -373,6 +373,51 @@ func TestRenewalSchedulerStopContextCancelsRun(t *testing.T) { } } +// TestRenewalSchedulerStopBeforeRunIsIdempotent 验证尚未启动的调度器停止不会永久等待,且后续 Run 不会逃逸启动。 +func TestRenewalSchedulerStopBeforeRunIsIdempotent(t *testing.T) { + // store、cleanup 保存调度器所需的本地测试数据库及其清理函数。 + store, cleanup := newSchedulerTestStore(t) + defer cleanup() + // scheduler 保存尚未启动、用于验证先停止后启动语义的续期调度器。 + scheduler := NewScheduler(store, nil, nil, nil) + // stopCtx、cancel 限制停止等待时间,防止回归测试在错误实现下永久阻塞。 + stopCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // err 表示尚未启动调度器首次停止的结果。 + if err := scheduler.StopContext(stopCtx); err != nil { + t.Fatalf("先停止尚未启动调度器失败: %v", err) + } + // repeatCtx、repeatCancel 验证重复停止保持幂等。 + repeatCtx, repeatCancel := context.WithTimeout(context.Background(), time.Second) + defer repeatCancel() + // err 表示尚未启动调度器重复停止的结果。 + if err := scheduler.StopContext(repeatCtx); err != nil { + t.Fatalf("重复停止尚未启动调度器失败: %v", err) + } + // scheduler.Run 不应在显式停止后创建运行 worker。 + scheduler.Run(context.Background()) + // waitCtx、waitCancel 验证停止信号已经完成登记且可立即等待。 + waitCtx, waitCancel := context.WithTimeout(context.Background(), time.Second) + defer waitCancel() + // err 表示先停止后的调度器等待结果。 + if err := scheduler.WaitContext(waitCtx); err != nil { + t.Fatalf("先停止后的 WaitContext 失败: %v", err) + } +} + +// TestRenewalSchedulerStopZeroValueIsNoop 验证零值调度器停止不会因缺少完成通道而 panic。 +func TestRenewalSchedulerStopZeroValueIsNoop(t *testing.T) { + // scheduler 保存未通过构造函数初始化、用于验证零值兼容性的调度器。 + scheduler := &Scheduler{} + // ctx、cancel 限制停止等待时间,防止回归测试在错误实现下永久阻塞。 + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // err 表示零值调度器的停止结果。 + if err := scheduler.StopContext(ctx); err != nil { + t.Fatalf("零值调度器停止失败: %v", err) + } +} + // TestPendingAPIRenewRestartFailureIsFinalFailure 负责TestPendingAPIRenewRestartFailureIsFinalFailure相关处理。 func TestPendingAPIRenewRestartFailureIsFinalFailure(t *testing.T) { // store、cleanup 保存store、cleanup,供当前处理流程使用 diff --git a/internal/server/account_login_repository.go b/internal/server/account_login_repository.go deleted file mode 100644 index 35c8e81..0000000 --- a/internal/server/account_login_repository.go +++ /dev/null @@ -1,270 +0,0 @@ -package server - -import ( - "context" - "errors" - "time" - - accountapp "xianyu-go/internal/application/account" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/cookierefresh" -) - -// accountLoginRepository 定义账号登录服务写入凭证、审计登录、更新资料和读取账号状态所需的最小能力。 -type accountLoginRepository interface { - // LockCredentials 串行化账号登录凭证变更。 - LockCredentials(accountID string) func() - // CreateCookieOwned 创建用户拥有的账号凭证。 - CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error - // LoadPlatformDetail 读取平台登录所需的最小账号视图。 - LoadPlatformDetail(ctx context.Context, accountID string) (*db.CookieDetail, error) - // UpdateFlatCookieOwned 更新用户拥有账号的扁平 Cookie。 - UpdateFlatCookieOwned(ctx context.Context, detail *db.CookieDetail, cookies string) error - // UpdateRenewalCookie 更新账号 Cookie 和 metadata。 - UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error - // ClearTokens 清理账号旧连接 Token。 - ClearTokens(ctx context.Context, accountID string) error - // GetStatus 返回账号是否启用。 - GetStatus(ctx context.Context, accountID string) bool - // MarkLogin 保存账号最近一次成功登录方式。 - MarkLogin(ctx context.Context, accountID, method string, at int64) error - // SetStatusWithReason 更新账号启用状态及禁用原因。 - SetStatusWithReason(ctx context.Context, accountID string, enabled bool, reason string) error - // AddLoginLog 写入账号登录审计记录。 - AddLoginLog(ctx context.Context, log db.AccountLoginLog) error - // UpdateProfile 保存账号展示资料。 - UpdateProfile(ctx context.Context, accountID, nickname, avatarURL string) error -} - -// storeAccountLoginRepository 将完整 Store 适配为账号登录服务窄 repository。 -type storeAccountLoginRepository struct { - // store 保存数据库聚合入口,仅在适配器内部使用。 - store *db.Store -} - -// storeAccountProfileRepository 将 Server 的摘要查询适配为账号应用层 Port。 -type storeAccountProfileRepository struct { - // store 提供账号摘要查询能力;凭证字段不会通过该适配器读取。 - store *db.Store -} - -// GetOwnedSummary 查询指定用户拥有的非敏感账号摘要。 -func (r storeAccountProfileRepository) GetOwnedSummary(ctx context.Context, userID int64, accountID string) (accountapp.Summary, error) { - // summary 保存数据库返回的非敏感账号摘要。 - summary, err := r.store.Cookies.GetSummaryOwned(ctx, userID, accountID) - if err != nil { - if errors.Is(err, db.ErrForbidden) { - return accountapp.Summary{}, accountapp.ErrForbidden - } - if errors.Is(err, db.ErrNotFound) { - // ownerID 和 ownerErr 用于区分不存在账号与跨用户账号,保持 HTTP 兼容状态码。 - ownerID, ownerErr := r.store.Cookies.GetOwnerID(ctx, accountID) - if ownerErr == nil && ownerID != userID { - return accountapp.Summary{}, accountapp.ErrForbidden - } - return accountapp.Summary{}, accountapp.ErrNotFound - } - return accountapp.Summary{}, err - } - return accountapp.Summary{ - ID: summary.ID, UserID: summary.UserID, Remark: summary.Remark, - Nickname: summary.Nickname, AvatarURL: summary.AvatarURL, - }, nil -} - -// DeleteOwned 在凭证锁内再次确认账号归属并删除账号,避免停止 fencing 期间误删被替换账号。 -func (r storeAccountProfileRepository) DeleteOwned(ctx context.Context, userID int64, accountID string) error { - if r.store == nil || r.store.Cookies == nil { - return errors.New("账号删除存储未初始化") - } - // unlock 保护最终归属复核与删除之间的账号凭证状态,避免并发替换穿透删除边界。 - unlock := r.store.LockAccountCredentials(accountID) - defer unlock() - // summary、summaryErr 保存锁内的非敏感归属复核结果。 - if _, summaryErr := r.GetOwnedSummary(ctx, userID, accountID); summaryErr != nil { - return summaryErr - } - return r.store.Cookies.Delete(ctx, accountID) -} - -// LockCredentials 委托账号凭证锁。 -func (r storeAccountLoginRepository) LockCredentials(accountID string) func() { - return r.store.LockAccountCredentials(accountID) -} - -// CreateCookieOwned 委托账号凭证创建。 -func (r storeAccountLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error { - return r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID) -} - -// LoadPlatformDetail 委托平台账号视图查询并转换为 Server 内部模型。 -func (r storeAccountLoginRepository) LoadPlatformDetail(ctx context.Context, accountID string) (*db.CookieDetail, error) { - // data 和 err 保存平台运行视图查询结果。 - data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) - if err != nil { - return nil, err - } - // summary 只补充非敏感版本字段,避免为乐观冲突检查读取或解密登录密码。 - summary, summaryErr := r.store.Cookies.GetSummaryOwned(ctx, data.UserID, accountID) - if summaryErr != nil { - return nil, summaryErr - } - return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser, LastRefreshAt: summary.LastRefreshAt}, nil -} - -// UpdateFlatCookieOwned 委托扁平 Cookie 更新并清除旧的完整 Cookie Jar 快照。 -func (r storeAccountLoginRepository) UpdateFlatCookieOwned(ctx context.Context, detail *db.CookieDetail, cookies string) error { - if detail == nil { - return db.ErrNotFound - } - // metadata 保存移除完整 Cookie Jar 快照后的元数据。 - metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) - return r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()) -} - -// FindAccount 只读取扫码登录所需的账号归属,不解密 Cookie、密码或 metadata。 -func (r storeAccountLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) { - // ownerID 保存数据库返回的账号所属用户标识。 - ownerID, err := r.store.Cookies.GetOwnerID(ctx, accountID) - if err != nil { - if errors.Is(err, db.ErrNotFound) { - return accountapp.QRLoginAccount{}, accountapp.ErrNotFound - } - return accountapp.QRLoginAccount{}, err - } - return accountapp.QRLoginAccount{ID: accountID, UserID: ownerID}, nil -} - -// UpdateQRCookieFlatOwned 更新扫码登录账号的扁平 Cookie,并清除旧的完整快照。 -func (r storeAccountLoginRepository) UpdateQRCookieFlatOwned(ctx context.Context, accountID, cookies string) error { - // detail 保存平台运行视图;该窄视图只在凭证适配器内部读取 metadata。 - detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) - if err != nil { - return err - } - // metadata 保存移除旧快照后的加密 metadata 文本。 - metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) - return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()) -} - -// UpdateQRCookieSnapshotOwned 更新扫码 Cookie,并把完整快照合并进加密 metadata。 -func (r storeAccountLoginRepository) UpdateQRCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error { - // detail 保存平台运行视图;完整 metadata 不向应用服务层泄露。 - detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) - if err != nil { - return err - } - // browserSnapshot 保存转换后的浏览器 Cookie 快照,仅在数据库适配器内使用。 - browserSnapshot := make([]cookierefresh.BrowserCookie, 0, len(snapshot)) - // snapshotEntry 表示当前待转换的应用层 Cookie 快照。 - for _, snapshotEntry := range snapshot { - browserSnapshot = append(browserSnapshot, cookierefresh.BrowserCookie{ - Name: snapshotEntry.Name, Value: snapshotEntry.Value, Domain: snapshotEntry.Domain, - Path: snapshotEntry.Path, Expires: snapshotEntry.Expires, HTTPOnly: snapshotEntry.HTTPOnly, - Secure: snapshotEntry.Secure, SameSite: snapshotEntry.SameSite, PartitionKey: snapshotEntry.PartitionKey, - }) - } - // metadata 保存快照合并后的加密 metadata 文本。 - metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, browserSnapshot) - return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()) -} - -// UpdateRenewalCookie 委托 Cookie 与 metadata 更新。 -func (r storeAccountLoginRepository) UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error { - return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, at) -} - -// ClearTokens 委托账号 Token 清理;未启用 Token repository 时保持兼容空操作。 -func (r storeAccountLoginRepository) ClearTokens(ctx context.Context, accountID string) error { - if r.store.Tokens == nil { - return nil - } - return r.store.Tokens.Clear(ctx, accountID) -} - -// GetStatus 委托账号启用状态查询。 -func (r storeAccountLoginRepository) GetStatus(ctx context.Context, accountID string) bool { - return r.store.Cookies.GetStatus(ctx, accountID) -} - -// MarkLogin 委托账号最近一次成功登录方式保存。 -func (r storeAccountLoginRepository) MarkLogin(ctx context.Context, accountID, method string, at int64) error { - return r.store.Cookies.MarkLogin(ctx, accountID, method, at) -} - -// SetStatusWithReason 委托账号启用状态更新。 -func (r storeAccountLoginRepository) SetStatusWithReason(ctx context.Context, accountID string, enabled bool, reason string) error { - return r.store.Cookies.SetStatusWithReason(ctx, accountID, enabled, reason) -} - -// AddLoginLog 委托账号登录审计记录写入;未启用审计 repository 时保持兼容空操作。 -func (r storeAccountLoginRepository) AddLoginLog(ctx context.Context, log db.AccountLoginLog) error { - if r.store.LoginLogs == nil { - return nil - } - return r.store.LoginLogs.Add(ctx, log) -} - -// UpdateProfile 委托账号展示资料更新。 -func (r storeAccountLoginRepository) UpdateProfile(ctx context.Context, accountID, nickname, avatarURL string) error { - return r.store.Cookies.UpdateProfile(ctx, accountID, nickname, avatarURL) -} - -// newStoreAccountLoginRepository 从完整 Store 构造账号登录服务窄 repository。 -func newStoreAccountLoginRepository(store *db.Store) accountLoginRepository { - if store == nil || store.Cookies == nil { - return nil - } - return storeAccountLoginRepository{store: store} -} - -// newStoreQRLoginRepository 从完整 Store 构造扫码登录应用服务所需的窄凭证端口。 -func newStoreQRLoginRepository(store *db.Store) accountapp.QRLoginRepository { - if store == nil || store.Cookies == nil { - return nil - } - return storeQRLoginRepository{store: store} -} - -// storeQRLoginRepository 将 Store 的扫码凭证能力限制在应用服务定义的窄端口内。 -type storeQRLoginRepository struct { - // store 提供数据库凭证读写能力,仅在本适配器内部访问。 - store *db.Store -} - -// LockCredentials 串行化扫码登录对同一账号的凭证变更。 -func (r storeQRLoginRepository) LockCredentials(accountID string) func() { - return r.store.LockAccountCredentials(accountID) -} - -// FindAccount 只返回账号存在性和归属,不读取 Cookie、密码或 metadata。 -func (r storeQRLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) { - return storeAccountLoginRepository(r).FindAccount(ctx, accountID) -} - -// CreateCookieOwned 创建扫码登录得到的新账号 Cookie。 -func (r storeQRLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error { - return r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID) -} - -// UpdateFlatCookieOwned 更新已有账号的扁平 Cookie,并清除完整快照。 -func (r storeQRLoginRepository) UpdateFlatCookieOwned(ctx context.Context, accountID, cookies string) error { - return storeAccountLoginRepository(r).UpdateQRCookieFlatOwned(ctx, accountID, cookies) -} - -// UpdateCookieSnapshotOwned 更新 Cookie 并合并完整浏览器快照。 -func (r storeQRLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error { - return storeAccountLoginRepository(r).UpdateQRCookieSnapshotOwned(ctx, accountID, cookies, snapshot) -} - -// ClearTokens 清理扫码登录前遗留的旧连接 Token。 -func (r storeQRLoginRepository) ClearTokens(ctx context.Context, accountID string) error { - // clearErr 保存旧连接 Token 清理结果;凭证已成功写入时该错误不阻断扫码登录。 - return storeAccountLoginRepository(r).ClearTokens(ctx, accountID) -} - -// 确保 Store 适配器始终覆盖账号登录服务所需的全部能力。 -var _ accountLoginRepository = storeAccountLoginRepository{} - -// 确保扫码凭证适配器始终覆盖应用服务定义的最小端口。 -var _ accountapp.QRLoginRepository = storeQRLoginRepository{} diff --git a/internal/server/account_login_repository_boundary_test.go b/internal/server/account_login_repository_boundary_test.go new file mode 100644 index 0000000..cd85cf6 --- /dev/null +++ b/internal/server/account_login_repository_boundary_test.go @@ -0,0 +1,22 @@ +package server + +import ( + "context" + "testing" +) + +// TestServerCookieWriterRejectsMissingRepository 验证 Server 凭证写入适配器缺少 Port 时快速失败。 +func TestServerCookieWriterRejectsMissingRepository(t *testing.T) { + // writer 模拟请求边界持有明文 Cookie 但尚未完成凭证 Port 装配的状态。 + writer := serverCookieWriter{cookies: "sid=short-lived"} + // createErr 保存新增账号写入的装配错误。 + createErr := writer.CreateOwnedCookie(context.Background(), "cid", 1) + if createErr == nil { + t.Fatal("缺少凭证 Port 时新增 Cookie 不应伪装成功") + } + // updateErr 保存既有账号更新的装配错误。 + updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", 1, 0) + if updateErr == nil { + t.Fatal("缺少凭证 Port 时更新 Cookie 不应伪装成功") + } +} diff --git a/internal/server/account_login_service.go b/internal/server/account_login_service.go index 2389f42..87db470 100644 --- a/internal/server/account_login_service.go +++ b/internal/server/account_login_service.go @@ -8,9 +8,8 @@ import ( "sync" "time" + "xianyu-go/internal/adapter" accountapp "xianyu-go/internal/application/account" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/protocol" ) // accountLoginService 是账号登录相关应用服务,负责凭证写入、登录审计、资料刷新和运行时重启编排。 @@ -18,7 +17,9 @@ type accountLoginService struct { // server 提供账号存储、运行时管理器和扫码会话持久化依赖。 server *Server // repository 提供账号登录服务所需的最小凭证持久化能力。 - repository accountLoginRepository + repository accountapp.CredentialRepository + // summaryRepository 提供不解密凭证的账号摘要和归属查询能力。 + summaryRepository accountapp.AccountSummaryRepository // createApplication 提供已迁移的手动 Cookie 登录应用用例。 createApplication *accountapp.LoginService // qrApplication 提供扫码成功凭证持久化应用用例;会话幂等状态仍由 Server 适配器拥有。 @@ -45,7 +46,7 @@ func (p serverLoginLifecyclePort) AfterSuccessfulLogin(ctx context.Context, user // serverCookieWriter 将本次请求中的明文 Cookie 限制在 Server 基础设施适配器内。 type serverCookieWriter struct { // repository 提供凭证锁、写入和旧 Token 清理能力。 - repository accountLoginRepository + repository accountapp.CredentialRepository // cookies 保存当前请求明文 Cookie;仅在 CreateOwnedCookie 调用期间使用,不进入应用层模型。 cookies string // logger 提供旧 Token 清理失败的脱敏日志能力。 @@ -87,7 +88,7 @@ func (w serverCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID str return loadErr } if detail == nil || detail.UserID != userID { - return db.ErrForbidden + return accountapp.ErrForbidden } if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision { return accountapp.ErrCredentialConflict @@ -108,49 +109,13 @@ func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService, return accountapp.NewLoginService(serverLoginLifecyclePort{server: server}) } -// newAccountQRLoginApplication 构造扫码登录应用服务及其凭证、生命周期适配器。 -func newAccountQRLoginApplication(server *Server) (*accountapp.QRLoginService, error) { - return accountapp.NewQRLoginService(newStoreQRLoginRepository(server.Store), serverQRLoginLifecycle{server: server}) -} - -// serverAccountProfilePort 将平台资料刷新适配为账号应用层 Port。 -type serverAccountProfilePort struct { - // server 提供平台会话、凭证锁、资料保存和运行时同步能力。 - server *Server -} - -// RefreshProfile 执行平台资料刷新,并把平台结果转换为应用层 DTO。 -func (p serverAccountProfilePort) RefreshProfile(ctx context.Context, input accountapp.ProfileInput) (accountapp.ProfileResult, error) { - // detail 是兼容 Server 资料刷新器所需的非敏感账号摘要模型。 - detail := &db.CookieDetail{ - ID: input.Summary.ID, UserID: input.Summary.UserID, - Remark: input.Summary.Remark, Nickname: input.Summary.Nickname, - AvatarURL: input.Summary.AvatarURL, - } - // nickname、avatarURL 和 profileErr 保存平台资料刷新后的展示结果。 - nickname, avatarURL, profileErr := p.server.refreshAccountProfile(ctx, detail) - return accountapp.ProfileResult{ - AccountID: input.AccountID, Nickname: nickname, - AvatarURL: avatarURL, ErrorMessage: profileErr, - }, nil -} - -// newAccountProfileApplication 从 Server 的数据库和平台能力构造账号资料应用服务。 -func newAccountProfileApplication(server *Server) (*accountapp.ProfileService, error) { - // repository 是只返回非敏感摘要的数据库适配器。 - repository := storeAccountProfileRepository{store: server.Store} - // profilePort 是负责平台请求和资料持久化的 Server 适配器。 - profilePort := serverAccountProfilePort{server: server} - return accountapp.NewProfileService(repository, profilePort) -} - // accountLoginApplication 返回当前 Server 绑定的账号登录应用服务。 func (s *Server) accountLoginApplication() *accountLoginService { return s.applicationServiceSet().accountLogin } // accountLoginRepositoryForServer 返回当前 Server 装配的账号登录持久化边界。 -func (s *Server) accountLoginRepositoryForServer() accountLoginRepository { +func (s *Server) accountLoginRepositoryForServer() accountapp.CredentialRepository { return s.accountLoginApplication().repository } @@ -253,21 +218,13 @@ func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userI // cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。 cookies := qrString(result, "cookies") // cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。 - cookieSnapshot, snapshotComplete := qrCookieSnapshot(result) + cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result) // scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。 - scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"])) + scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), adapter.AccountIDFromCookie(cookies))) // input 保存转换后的纯应用扫码登录输入;Cookie 只交给凭证端口消费。 input := accountapp.QRLoginInput{UserID: userID, ScannedAccountID: scannedAccountID, TargetAccountID: targetAccountID, Cookies: cookies} if snapshotComplete { - input.Snapshot = make([]accountapp.CookieSnapshot, 0, len(cookieSnapshot)) - // cookie 保存当前浏览器 Cookie 快照,转换后不再依赖平台 DTO。 - for _, cookie := range cookieSnapshot { - input.Snapshot = append(input.Snapshot, accountapp.CookieSnapshot{ - Name: cookie.Name, Value: cookie.Value, Domain: cookie.Domain, Path: cookie.Path, - Expires: cookie.Expires, HTTPOnly: cookie.HTTPOnly, Secure: cookie.Secure, - SameSite: cookie.SameSite, PartitionKey: cookie.PartitionKey, - }) - } + input.Snapshot = cookieSnapshot } // resultValue 保存应用服务返回的非敏感持久化结果。 resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input) @@ -281,7 +238,7 @@ func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userI if errors.Is(persistErr, accountapp.ErrForbidden) { return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户") } - if errors.Is(persistErr, db.ErrAlreadyExists) { + if errors.Is(persistErr, accountapp.ErrAlreadyExists) { return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态") } return qrLoginPersistence{}, persistErr @@ -300,9 +257,15 @@ func (svc *accountLoginService) refreshAndRestartAccount(ctx context.Context, us // s 是当前账号登录应用服务依赖的 Server。 s := svc.server // detail 和 err 保存资料摘要查询结果。 - detail, err := s.loadCookieSummaryDetail(ctx, userID, accountID) + _, err := svc.summaryRepository.GetOwnedSummary(ctx, userID, accountID) if err == nil { - s.refreshAccountProfile(ctx, detail) + // profileResult、profileErr 保存登录成功后的资料刷新结果;失败仅记录,不阻断运行时重启。 + profileResult, profileErr := s.accountProfileApplication().RefreshProfile(ctx, userID, accountID) + if profileErr != nil && s.Logger != nil { + s.Logger.Warn("登录后刷新账号资料失败", "cookie_id", accountID, "err", profileErr) + } else if profileResult.ErrorMessage != "" && s.Logger != nil { + s.Logger.Warn("登录后刷新账号资料返回业务错误", "cookie_id", accountID, "err", profileResult.ErrorMessage) + } } if s.Manager != nil && svc.repository.GetStatus(ctx, accountID) { // err 表示账号运行时重启错误。 diff --git a/internal/server/account_summary_handlers_test.go b/internal/server/account_summary_handlers_test.go new file mode 100644 index 0000000..732717d --- /dev/null +++ b/internal/server/account_summary_handlers_test.go @@ -0,0 +1,87 @@ +package server + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" +) + +// TestRequireCookieOwnershipPreservesHTTPCompatibility 验证账号所有权辅助函数保留未登录、越权、缺失和成功状态码。 +func TestRequireCookieOwnershipPreservesHTTPCompatibility(t *testing.T) { + // srv、store、cleanup 保存当前测试使用的 HTTP 服务和数据库。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // ctx 是本测试共用的数据库上下文。 + ctx := context.Background() + // _, createErr 保存第二个用户创建错误;用户主键随后从查询得到。 + _, createErr := store.Users.Create(ctx, "summary-other", "summary-other@example.com", "pw") + if createErr != nil { + t.Fatalf("创建第二用户失败: %v", createErr) + } + // other、otherLookupErr 保存第二个用户及读取错误。 + other, otherLookupErr := store.Users.GetByUsername(ctx, "summary-other") + if otherLookupErr != nil { + t.Fatalf("读取第二用户失败: %v", otherLookupErr) + } + // saveErr 保存第二个用户账号的创建错误。 + if saveErr := store.Cookies.Save(ctx, "other-account", "unb=other", other.ID); saveErr != nil { + t.Fatalf("创建第二用户账号失败: %v", saveErr) + } + // cases 覆盖所有权辅助函数的 HTTP 兼容分支。 + cases := []struct { + // name 是当前 HTTP 所有权场景名称。 + name string + // session 是请求上下文中的认证会话;nil 表示未登录。 + session *db.Session + // accountID 是待校验账号标识。 + accountID string + // wantStatus 是预期错误响应状态;成功场景为 0。 + wantStatus int + // wantOwned 表示预期的所有权结论。 + wantOwned bool + }{ + {name: "unauthenticated", accountID: "acc1", wantStatus: http.StatusUnauthorized}, + {name: "owned", session: &db.Session{UserID: 1}, accountID: "acc1", wantOwned: true}, + {name: "forbidden", session: &db.Session{UserID: 1}, accountID: "other-account", wantStatus: http.StatusForbidden}, + {name: "missing", session: &db.Session{UserID: 1}, accountID: "missing-account", wantStatus: http.StatusNotFound}, + } + // testCase 表示当前正在验证的 HTTP 所有权场景。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // request 是注入测试会话后的所有权请求。 + request := httptest.NewRequest(http.MethodGet, "/items", nil) + if testCase.session != nil { + request = request.WithContext(auth.WithSession(request.Context(), testCase.session)) + } + // recorder 捕获所有权辅助函数的 HTTP 错误响应。 + recorder := httptest.NewRecorder() + // owned 保存应用 Port 返回的所有权结论。 + owned := srv.requireCookieOwnership(recorder, request, testCase.accountID) + if owned != testCase.wantOwned { + t.Fatalf("owned=%v,期望=%v", owned, testCase.wantOwned) + } + if testCase.wantStatus != 0 && recorder.Code != testCase.wantStatus { + t.Fatalf("status=%d,期望=%d body=%s", recorder.Code, testCase.wantStatus, recorder.Body.String()) + } + }) + } +} + +// TestLoadCookieSummaryDetailUsesNonSensitiveApplicationModel 验证 Server 摘要兼容模型不携带 Cookie 或密码。 +func TestLoadCookieSummaryDetailUsesNonSensitiveApplicationModel(t *testing.T) { + // srv、cleanup 保存当前测试使用的 HTTP 服务。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // detail、loadErr 保存应用 Port 返回的非敏感摘要及读取错误。 + detail, loadErr := srv.loadCookieSummaryDetail(context.Background(), 1, "acc1") + if loadErr != nil { + t.Fatalf("读取账号摘要失败: %v", loadErr) + } + if detail.ID != "acc1" || detail.UserID != 1 { + t.Fatalf("摘要模型不完整: %+v", detail) + } +} diff --git a/internal/server/account_task_application_adapter.go b/internal/server/account_task_application_adapter.go new file mode 100644 index 0000000..8ee19eb --- /dev/null +++ b/internal/server/account_task_application_adapter.go @@ -0,0 +1,36 @@ +package server + +import automationapp "xianyu-go/internal/application/automation" + +// newApplicationAccountTaskSettingsResponse 将应用层账号任务设置转换为 HTTP DTO。 +func newApplicationAccountTaskSettingsResponse(settings automationapp.AccountTaskSettings) accountTaskSettingsResponse { + return accountTaskSettingsResponse{ + AccountID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent, + AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime, + LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt, + } +} + +// newApplicationAccountTaskRunResponses 批量转换应用层账号任务运行记录。 +func newApplicationAccountTaskRunResponses(runs []automationapp.AccountTaskRun) []accountTaskRunResponse { + // result 保存待写入响应的账号任务运行 DTO。 + result := make([]accountTaskRunResponse, 0, len(runs)) + // run 是当前待转换的应用层运行记录。 + for _, run := range runs { + result = append(result, accountTaskRunResponse{ + ID: run.ID, RunKey: run.RunKey, AccountID: run.CookieID, TaskType: run.TaskType, + TargetID: run.TargetID, RunDate: run.RunDate, Status: run.Status, SuccessCount: run.SuccessCount, + FailedCount: run.FailedCount, ErrorMessage: run.ErrorMessage, NextRetryAt: run.NextRetryAt, + StartedAt: run.StartedAt, FinishedAt: run.FinishedAt, + }) + } + return result +} + +// newApplicationAccountTaskSummaryResponse 将应用层账号任务摘要转换为 HTTP DTO。 +func newApplicationAccountTaskSummaryResponse(summary automationapp.TaskSummary) accountTaskSummaryResponse { + return accountTaskSummaryResponse{ + TaskType: summary.TaskType, Found: summary.Found, Success: summary.Success, + Failed: summary.Failed, Skipped: summary.Skipped, Message: summary.Message, + } +} diff --git a/internal/server/account_task_handlers.go b/internal/server/account_task_handlers.go index 54d6bda..5c95de3 100644 --- a/internal/server/account_task_handlers.go +++ b/internal/server/account_task_handlers.go @@ -3,18 +3,13 @@ package server import ( "errors" "net/http" - "regexp" "strings" "github.com/go-chi/chi/v5" - "xianyu-go/internal/automation" - "xianyu-go/internal/db" + automationapp "xianyu-go/internal/application/automation" ) -// accountTaskTimePattern 保存账号任务时间Pattern,供当前处理流程使用 -var accountTaskTimePattern = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d$`) - // mountAccountTasks 负责mount账号任务列表相关处理。 func (s *Server) mountAccountTasks(r chi.Router) { r.Get("/api/account-tasks/{cid}", s.getAccountTaskSettings) @@ -32,12 +27,12 @@ func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request) return } // settings、err 保存settings、err,供当前处理流程使用 - settings, err := s.communicationApplication().GetAccountTaskSettings(r.Context(), cid) + settings, err := s.accountTaskApplication().GetSettings(r.Context(), cid) if err != nil { writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败") return } - writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(settings)) + writeJSON(w, http.StatusOK, newApplicationAccountTaskSettingsResponse(settings)) } // updateAccountTaskSettings 负责update账号任务设置相关处理。 @@ -49,13 +44,15 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques return } // input 保存input,供当前处理流程使用 - var input db.AccountTaskSettings + var input automationapp.AccountTaskSettings if decodeJSON(r, &input) != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } // stored、err 保存stored、err,供当前处理流程使用 - stored, err := s.communicationApplication().UpdateAccountTaskSettings(r.Context(), accountTaskUpdateInput{CookieID: cid, Settings: input}) + input.CookieID = cid + // stored、err 保存应用服务规范化后的设置及写入错误。 + stored, err := s.accountTaskApplication().UpdateSettings(r.Context(), input) if err != nil { if strings.Contains(err.Error(), "不能为空") || strings.Contains(err.Error(), "不能超过") || strings.Contains(err.Error(), "格式必须") { writeErr(w, http.StatusBadRequest, err.Error()) @@ -64,7 +61,7 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques } return } - writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(stored)) + writeJSON(w, http.StatusOK, newApplicationAccountTaskSettingsResponse(stored)) } // listAccountTaskRuns 负责list账号任务运行记录相关处理。 @@ -76,12 +73,12 @@ func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) { return } // runs、err 保存runs、err,供当前处理流程使用 - runs, err := s.communicationApplication().ListAccountTaskRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20)) + runs, err := s.accountTaskApplication().ListRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20)) if err != nil { writeErr(w, http.StatusInternalServerError, "读取任务记录失败") return } - writeJSON(w, http.StatusOK, accountTaskRunsResponse{Runs: newAccountTaskRunResponses(runs)}) + writeJSON(w, http.StatusOK, accountTaskRunsResponse{Runs: newApplicationAccountTaskRunResponses(runs)}) } // runAccountTask 负责运行账号任务相关处理。 @@ -97,22 +94,26 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) { return } // input 保存input,供当前处理流程使用 - var input struct { - TaskType string `json:"task_type"` - } - if decodeJSON(r, &input) != nil || (input.TaskType != automation.TaskAutoRate && input.TaskType != automation.TaskAutoPolish) { + var input accountTaskRunRequest + if decodeJSON(r, &input) != nil || (input.TaskType != automationapp.TaskAutoRate && input.TaskType != automationapp.TaskAutoPolish) { writeErr(w, http.StatusBadRequest, "不支持的任务类型") return } // summary、err 保存summary、err,供当前处理流程使用 - summary, err := s.communicationApplication().RunAccountTask(r.Context(), cid, input.TaskType) + summary, err := s.accountTaskApplication().Run(r.Context(), cid, input.TaskType) if err != nil { - if errors.Is(err, errCommunicationUnavailable) { + if errors.Is(err, automationapp.ErrUnavailable) { writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用") return } writeErr(w, http.StatusBadGateway, err.Error()) return } - writeJSON(w, http.StatusOK, accountTaskRunResponseEnvelope{Success: true, Summary: newAccountTaskSummaryResponse(summary)}) + writeJSON(w, http.StatusOK, accountTaskRunResponseEnvelope{Success: true, Summary: newApplicationAccountTaskSummaryResponse(summary)}) +} + +// accountTaskRunRequest 是手动执行账号任务的具名 HTTP 请求 DTO。 +type accountTaskRunRequest struct { + // TaskType 是要求执行的账号任务类型。 + TaskType string `json:"task_type"` } diff --git a/internal/server/admin_auth_test.go b/internal/server/admin_auth_test.go index d414c46..c76e082 100644 --- a/internal/server/admin_auth_test.go +++ b/internal/server/admin_auth_test.go @@ -296,9 +296,9 @@ func TestChangeAdminPasswordShortNewPassword(t *testing.T) { // TestChangeAdminPasswordNonAdmin 非 admin 403。 func TestChangeAdminPasswordNonAdmin(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() - srv.Store.Users.Create(context.Background(), "user2", "u2@e.com", "pw") + store.Users.Create(context.Background(), "user2", "u2@e.com", "pw") // h 保存h,供当前处理流程使用 h := srv.Router() // body 保存请求体,供当前处理流程使用 diff --git a/internal/server/admin_handlers.go b/internal/server/admin_handlers.go index 51c0e17..71ca05d 100644 --- a/internal/server/admin_handlers.go +++ b/internal/server/admin_handlers.go @@ -1,10 +1,12 @@ package server import ( + "errors" "net/http" "strconv" "github.com/go-chi/chi/v5" + adminapp "xianyu-go/internal/application/admin" ) // mountAdminReal 管理员端点。 @@ -18,7 +20,7 @@ func (s *Server) mountAdminReal(r chi.Router) { // adminListUsers 负责adminList用户列表相关处理。 func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) { // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.Store.Admin.ListUsers(r.Context()) + rows, err := s.applicationServiceSet().admin.ListUsers(r.Context()) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -44,21 +46,23 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "无效用户ID") return } - // 不允许删除自己。 + // 不允许删除自己;应用服务统一执行该业务规则。 sess := authSess(r) - if sess.UserID == uid { - writeErr(w, http.StatusBadRequest, "不能删除当前登录用户") - return - } if s.Manager != nil { - if accountIDs, listErr := s.Store.Cookies.ListOwnedIDs(r.Context(), uid); listErr == nil { // accountIDs 是待停止的账号 ID。 + // accountIDs、listErr 保存应用服务返回的待停止账号 ID 列表及查询错误。 + if accountIDs, listErr := s.accountSummaryApplication().ListOwnedIDs(r.Context(), uid); listErr == nil { + // cookieID 表示待停止运行实例的账号标识。 for _, cookieID := range accountIDs { s.Manager.Stop(cookieID) } } } - if // err 保存err,供当前处理流程使用 - err := s.Store.Users.Delete(r.Context(), uid); err != nil { + // err 保存管理员删除应用用例的执行结果。 + if err := s.applicationServiceSet().admin.DeleteUser(r.Context(), sess.UserID, uid); err != nil { + if errors.Is(err, adminapp.ErrSelfDelete) { + writeErr(w, http.StatusBadRequest, "不能删除当前登录用户") + return + } writeErr(w, http.StatusInternalServerError, "删除失败") return } @@ -67,8 +71,8 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) { // adminListCookies 负责adminListCookies相关处理。 func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) { - // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.Store.Admin.ListCookies(r.Context()) + // rows、err 保存应用服务返回的管理员账号摘要及查询错误。 + rows, err := s.accountSummaryApplication().ListAdminSummaries(r.Context()) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -80,7 +84,7 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) { out = append(out, adminCookieResponse{ ID: row.ID, UserID: row.UserID, Remark: row.Remark, CreatedAt: row.CreatedAt, Owner: row.Owner, - Enabled: s.Store.Cookies.GetStatus(r.Context(), row.ID), + Enabled: row.Enabled, }) } writeJSON(w, http.StatusOK, out) @@ -89,7 +93,7 @@ func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) { // adminStats 负责adminStats相关处理。 func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) { // stats 是管理员仪表盘的数据库聚合结果。 - stats, err := s.Store.Admin.Stats(r.Context()) + stats, err := s.applicationServiceSet().admin.Stats(r.Context()) if err != nil { writeErr(w, http.StatusInternalServerError, "统计数据失败") return diff --git a/internal/server/analytics_handlers.go b/internal/server/analytics_handlers.go index 9d6f32c..5c5f6a0 100644 --- a/internal/server/analytics_handlers.go +++ b/internal/server/analytics_handlers.go @@ -2,83 +2,64 @@ package server import ( "net/http" - "strconv" - "strings" "time" "github.com/go-chi/chi/v5" + analyticsapp "xianyu-go/internal/application/analytics" "xianyu-go/internal/auth" - "xianyu-go/internal/db" ) -// mountAnalyticsReal 订单分析端点(仪表盘 BI 报表用)。 +// analyticsApplication 返回当前 Server 绑定的订单分析应用服务。 +func (s *Server) analyticsApplication() *analyticsapp.Service { + return s.applicationServiceSet().analytics +} + +// mountAnalyticsReal 挂载订单分析端点(仪表盘 BI 报表使用)。 func (s *Server) mountAnalyticsReal(r chi.Router) { r.Get("/dashboard/stats", s.dashboardStats) r.Get("/analytics/orders", s.orderAnalytics) r.Get("/analytics/orders/valid", s.validOrders) } -// dashboardStats 返回当前登录用户的数据概览。管理员全局统计仍由 /admin/stats 提供, -// 避免普通用户访问管理员接口,也避免把全局资源数和用户自己的订单收益混在一起。 -// dashboardStats 负责dashboardStats相关处理。 +// dashboardStats 返回当前登录用户的数据概览;管理员全局统计由 /admin/stats 提供。 func (s *Server) dashboardStats(w http.ResponseWriter, r *http.Request) { // sess 是当前请求的认证会话。 sess := auth.SessionFromContext(r.Context()) - // result 和 err 是订单分析应用服务返回的仪表盘摘要。 + // result 和 err 是订单分析应用服务返回的仪表盘摘要及错误。 result, err := s.analyticsApplication().DashboardStats(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "统计数据失败") return } - writeJSON(w, http.StatusOK, result) + writeJSON(w, http.StatusOK, dashboardStatsResponseFromApplication(result)) } -// 有效订单状态只统计以下几种。 -var validOrderStatuses = []string{"pending_ship", "paid", "2", "shipped", "3", "completed", "4", "11"} - // orderAnalytics 汇总指定日期范围内的收益以及按日、状态、城市和商品分布。 func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) { // sess 是当前请求的认证会话。 sess := auth.SessionFromContext(r.Context()) - // startDate、endDate 和 location 是订单分析的日期范围及时区参数。 - startDate := r.URL.Query().Get("start_date") - // endDate 保存结束日期,供当前处理流程使用 - endDate := r.URL.Query().Get("end_date") - // location 保存地址,供当前处理流程使用 - location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes")) - // where 和 params 是按用户、日期和状态归一化后的查询条件。 - where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location) - // amountClean 和 amountFilter 是按数据库方言生成的金额过滤条件。 - amountClean, amountFilter := analyticsQueryAmountFilter(s.Store, "amount") - // result 和 err 是订单分析应用服务返回的具名统计结果。 - result, err := s.analyticsApplication().OrderAnalytics(r.Context(), analyticsQuery{ - Where: where, Params: analyticsQueryParamsCopy(params), AmountClean: amountClean, AmountFilter: amountFilter, Location: location, - }) + // query 是从 HTTP 查询参数映射出的订单分析用例请求。 + query := analyticsapp.Query{ + UserID: sess.UserID, StartDate: r.URL.Query().Get("start_date"), EndDate: r.URL.Query().Get("end_date"), + Location: analyticsapp.LocationFromOffset(r.URL.Query().Get("timezone_offset_minutes")), + } + // result 和 err 是订单分析应用服务返回的统计结果及错误。 + result, err := s.analyticsApplication().OrderAnalytics(r.Context(), query) if err != nil { - writeErr(w, http.StatusInternalServerError, analyticsErrorMessage(err)) + writeErr(w, http.StatusInternalServerError, analyticsapp.ErrorMessage(err)) return } - writeJSON(w, http.StatusOK, result) + writeJSON(w, http.StatusOK, orderAnalyticsResponseFromApplication(result)) } -// validOrders 有效订单明细列表(用于统计中的订单明细)。 +// validOrders 返回有效订单明细分页结果。 func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) { // sess 是当前请求的认证会话。 sess := auth.SessionFromContext(r.Context()) - // startDate、endDate 和 location 是有效订单的日期范围及时区参数。 - startDate := r.URL.Query().Get("start_date") - // endDate 保存结束日期,供当前处理流程使用 - endDate := r.URL.Query().Get("end_date") - // location 保存地址,供当前处理流程使用 - location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes")) - // where 和 params 是按用户、日期和状态归一化后的查询条件。 - where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location) - // amountClean 和 amountFilter 是按数据库方言生成的金额过滤条件。 - amountClean, amountFilter := analyticsQueryAmountFilter(s.Store, "orders.amount") // page 和 pageSize 是已经限制在安全范围内的分页参数。 page := atoiDefault(r.URL.Query().Get("page"), 1) - // pageSize 保存每页数量,供当前处理流程使用 + // pageSize 是每页返回的最大订单数量。 pageSize := atoiDefault(r.URL.Query().Get("page_size"), 500) if page < 1 { page = 1 @@ -86,120 +67,79 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) { if pageSize < 1 || pageSize > 500 { pageSize = 500 } - // result 和 err 是订单分析应用服务返回的分页结果。 - result, err := s.analyticsApplication().ValidOrders(r.Context(), analyticsQuery{ - Where: where, Params: analyticsQueryParamsCopy(params), AmountClean: amountClean, AmountFilter: amountFilter, - }, page, pageSize) + // query 是从 HTTP 查询参数映射出的有效订单用例请求。 + query := analyticsapp.Query{ + UserID: sess.UserID, StartDate: r.URL.Query().Get("start_date"), EndDate: r.URL.Query().Get("end_date"), + Location: analyticsapp.LocationFromOffset(r.URL.Query().Get("timezone_offset_minutes")), + } + // result 和 err 是订单分析应用服务返回的分页结果及错误。 + result, err := s.analyticsApplication().ValidOrders(r.Context(), query, page, pageSize) if err != nil { - writeErr(w, http.StatusInternalServerError, analyticsErrorMessage(err)) + writeErr(w, http.StatusInternalServerError, analyticsapp.ErrorMessage(err)) return } - writeJSON(w, http.StatusOK, result) + writeJSON(w, http.StatusOK, validOrdersResponseFromApplication(result)) } -// buildAnalyticsWhere 构建 WHERE 子句(user_id 经 cookies 关联过滤 + 日期 + 状态)。 -// 返回 (whereClause, params),whereClause 已含 WHERE 前缀。 -// buildAnalyticsWhere 负责buildAnalyticsWhere相关处理。 -func buildAnalyticsWhere(startDate, endDate string, userID int64, statuses []string, location *time.Location) (string, []any) { - // conds 保存conds,供当前处理流程使用 - conds := []string{"orders.deleted_at IS NULL"} - // params 保存params,供当前处理流程使用 - params := []any{} - if startDate != "" { - conds = append(conds, "orders.created_at >= ?") - params = append(params, analyticsDateBoundary(startDate, false, location)) - } - if endDate != "" { - conds = append(conds, "orders.created_at < ?") - params = append(params, analyticsDateBoundary(endDate, true, location)) - } - if userID != 0 { - conds = append(conds, "EXISTS (SELECT 1 FROM cookies WHERE cookies.id = orders.cookie_id AND cookies.user_id = ?)") - params = append(params, userID) - } - if len(statuses) > 0 { - // ph 保存ph,供当前处理流程使用 - ph := strings.Repeat("?,", len(statuses)) - ph = strings.TrimSuffix(ph, ",") - conds = append(conds, "orders.order_status IN ("+ph+")") - // s 表示当前遍历过程中的s - for _, s := range statuses { - params = append(params, s) - } - } - // where 保存where,供当前处理流程使用 - where := "" - if len(conds) > 0 { - where = "WHERE " + strings.Join(conds, " AND ") - } - // 后续 AND 需要前置空格。 - if where != "" { - where += " " - } - return where, params -} - -// analyticsDateBoundary 负责analytics日期Boundary相关处理。 +// analyticsDateBoundary 保留日期边界测试使用的应用层转换入口。 func analyticsDateBoundary(raw string, endExclusive bool, location *time.Location) string { - if location == nil { - location = time.Local - } - // t、err 保存t、err,供当前处理流程使用 - t, err := time.ParseInLocation("2006-01-02", strings.TrimSpace(raw), location) - if err != nil { - return raw - } - if endExclusive { - t = t.AddDate(0, 0, 1) - } - return t.UTC().Format("2006-01-02 15:04:05") + return analyticsapp.DateBoundary(raw, endExclusive, location) } -// analyticsLocation 负责analytics地址相关处理。 -func analyticsLocation(rawOffset string) *time.Location { - // offset、err 保存offset、err,供当前处理流程使用 - 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) -} - -// analyticsAmountExpression 负责analyticsAmountExpression相关处理。 -func analyticsAmountExpression(dialect db.Dialect, column string) string { - // clean 保存clean,供当前处理流程使用 - clean := `TRIM(REPLACE(REPLACE(` + column + `, '¥', ''), ',', ''))` - switch dialect { - case db.DialectPostgres: - return `CASE WHEN ` + clean + ` ~ '^[0-9]+([.][0-9]+)?$' THEN CAST(` + clean + ` AS DOUBLE PRECISION) END` - case db.DialectMySQL: - return `CASE WHEN ` + clean + ` REGEXP '^[0-9]+([.][0-9]+)?$' THEN CAST(` + clean + ` AS DOUBLE) END` - default: - return `CASE WHEN ` + clean + ` GLOB '[0-9]*' AND ` + clean + ` NOT GLOB '*[^0-9.]*' AND ` + clean + ` NOT GLOB '*.*.*' AND ` + clean + ` NOT LIKE '%.' THEN CAST(` + clean + ` AS REAL) END` +// dashboardStatsResponseFromApplication 将应用摘要映射为 HTTP DTO。 +func dashboardStatsResponseFromApplication(result analyticsapp.DashboardStats) dashboardStatsResponse { + return dashboardStatsResponse{ + TotalCookies: result.TotalCookies, ActiveCookies: result.ActiveCookies, TotalCards: result.TotalCards, + AvailableCardStock: result.AvailableCardStock, TotalKeywords: result.TotalKeywords, TotalOrders: result.TotalOrders, } } -// parseAnalyticsDBTime 负责parseAnalyticsDB时间相关处理。 -func parseAnalyticsDBTime(raw string) time.Time { - // layout 表示当前遍历过程中的layout - for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339, "2006-01-02T15:04:05Z07:00"} { - if // t、err 保存t、err,供当前处理流程使用 - t, err := time.ParseInLocation(layout, strings.TrimSpace(raw), time.UTC); err == nil { - return t - } +// orderAnalyticsResponseFromApplication 将应用统计映射为 HTTP DTO。 +func orderAnalyticsResponseFromApplication(result analyticsapp.OrderAnalytics) orderAnalyticsResponse { + // dailyStats 是应用层按日结果对应的传输 DTO 列表。 + dailyStats := make([]analyticsDailyStatsResponse, 0, len(result.DailyStats)) + // item 是当前按日统计结果。 + for _, item := range result.DailyStats { + dailyStats = append(dailyStats, analyticsDailyStatsResponse{Date: item.Date, OrderCount: item.OrderCount, Amount: item.Amount}) + } + // statusStats 是应用层按状态结果对应的传输 DTO 列表。 + statusStats := make([]analyticsStatusStatsResponse, 0, len(result.StatusStats)) + // item 是当前按状态统计结果。 + for _, item := range result.StatusStats { + statusStats = append(statusStats, analyticsStatusStatsResponse{Status: item.Status, Count: item.Count, Amount: item.Amount}) + } + // cityStats 是应用层按城市结果对应的传输 DTO 列表。 + cityStats := make([]analyticsCityStatsResponse, 0, len(result.CityStats)) + // item 是当前按城市统计结果。 + for _, item := range result.CityStats { + cityStats = append(cityStats, analyticsCityStatsResponse{City: item.City, OrderCount: item.OrderCount, TotalAmount: item.TotalAmount}) + } + // itemStats 是应用层按商品结果对应的传输 DTO 列表。 + itemStats := make([]analyticsItemStatsResponse, 0, len(result.ItemStats)) + // item 是当前按商品统计结果。 + for _, item := range result.ItemStats { + itemStats = append(itemStats, analyticsItemStatsResponse{ItemID: item.ItemID, OrderCount: item.OrderCount, TotalAmount: item.TotalAmount, AvgAmount: item.AvgAmount}) + } + return orderAnalyticsResponse{ + RevenueStats: analyticsRevenueStatsResponse{ + TotalOrders: result.RevenueStats.TotalOrders, TotalAmount: result.RevenueStats.TotalAmount, + AvgAmount: result.RevenueStats.AvgAmount, UniqueBuyers: result.RevenueStats.UniqueBuyers, UniqueItems: result.RevenueStats.UniqueItems, + }, + DailyStats: dailyStats, StatusStats: statusStats, CityStats: cityStats, ItemStats: itemStats, } - return time.Time{} } -// parseAnalyticsAmount 负责parseAnalyticsAmount相关处理。 -func parseAnalyticsAmount(raw string) float64 { - raw = strings.TrimSpace(strings.NewReplacer("¥", "", ",", "").Replace(raw)) - // value 保存值,供当前处理流程使用 - value, _ := strconv.ParseFloat(raw, 64) - return value -} - -// round2 负责round2相关处理。 -func round2(f float64) float64 { - return float64(int(f*100+0.5)) / 100 +// validOrdersResponseFromApplication 将应用分页结果映射为 HTTP DTO。 +func validOrdersResponseFromApplication(result analyticsapp.ValidOrders) validOrdersResponse { + // orders 是应用层有效订单对应的传输 DTO 列表。 + orders := make([]validOrderResponse, 0, len(result.Orders)) + // item 是当前有效订单应用模型。 + for _, item := range result.Orders { + orders = append(orders, validOrderResponse{ + OrderID: item.OrderID, ItemID: item.ItemID, BuyerID: item.BuyerID, ItemTitle: item.ItemTitle, + ItemImage: item.ItemImage, Quantity: item.Quantity, Amount: item.Amount, OrderStatus: item.OrderStatus, + Status: item.Status, CookieID: item.CookieID, CreatedAt: item.CreatedAt, + }) + } + return validOrdersResponse{Orders: orders, Total: result.Total, Page: result.Page, PageSize: result.PageSize, Truncated: result.Truncated} } diff --git a/internal/server/analytics_repository.go b/internal/server/analytics_repository.go deleted file mode 100644 index 6295182..0000000 --- a/internal/server/analytics_repository.go +++ /dev/null @@ -1,57 +0,0 @@ -package server - -import ( - "context" - "database/sql" - - "xianyu-go/internal/db" -) - -// analyticsRepository 定义分析服务执行只读 SQL、读取卡密库存和获取数据库方言所需的最小能力。 -type analyticsRepository interface { - // QueryRowContext 执行返回单行结果的分析查询。 - QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row - // QueryContext 执行返回多行结果的分析查询。 - QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) - // ListCardsForUser 返回用户拥有的卡密组。 - ListCardsForUser(ctx context.Context, userID int64) ([]db.CardFull, error) - // Dialect 返回当前数据库方言。 - Dialect() db.Dialect -} - -// storeAnalyticsRepository 将完整 Store 适配为分析服务窄 repository。 -type storeAnalyticsRepository struct { - // store 保存数据库聚合入口,仅在适配器内部使用。 - store *db.Store -} - -// QueryRowContext 委托单行分析查询。 -func (r storeAnalyticsRepository) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { - return r.store.Analytics.QueryRowContext(ctx, query, args...) -} - -// QueryContext 委托多行分析查询。 -func (r storeAnalyticsRepository) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { - return r.store.Analytics.QueryContext(ctx, query, args...) -} - -// ListCardsForUser 委托用户卡密组查询。 -func (r storeAnalyticsRepository) ListCardsForUser(ctx context.Context, userID int64) ([]db.CardFull, error) { - return r.store.Cards.AllForUser(ctx, userID) -} - -// Dialect 返回 Store 使用的数据库方言。 -func (r storeAnalyticsRepository) Dialect() db.Dialect { - return r.store.Dialect -} - -// newStoreAnalyticsRepository 从完整 Store 构造分析服务窄 repository。 -func newStoreAnalyticsRepository(store *db.Store) analyticsRepository { - if store == nil || store.Analytics == nil || store.Cards == nil { - return nil - } - return storeAnalyticsRepository{store: store} -} - -// 确保 Store 适配器始终覆盖分析服务所需的全部能力。 -var _ analyticsRepository = storeAnalyticsRepository{} diff --git a/internal/server/analytics_service.go b/internal/server/analytics_service.go deleted file mode 100644 index c8ffe3d..0000000 --- a/internal/server/analytics_service.go +++ /dev/null @@ -1,397 +0,0 @@ -package server - -import ( - "context" - "errors" - "sort" - "strings" - "time" - - "xianyu-go/internal/db" -) - -// analyticsQuery 描述订单分析查询已经归一化的数据库过滤条件。 -type analyticsQuery struct { - // Where 是包含 WHERE 前缀的订单过滤子句。 - Where string - // Params 是 Where 对应的数据库参数。 - Params []any - // AmountClean 是按数据库方言生成的金额表达式。 - AmountClean string - // AmountFilter 是排除非法金额后的附加条件。 - AmountFilter string - // Location 是用户选择的本地时区。 - Location *time.Location -} - -// analyticsStage 标识订单分析失败的查询阶段。 -type analyticsStage string - -const ( - // analyticsStageRevenue 表示收益汇总查询失败。 - analyticsStageRevenue analyticsStage = "revenue" - // analyticsStageDaily 表示每日统计查询失败。 - analyticsStageDaily analyticsStage = "daily" - // analyticsStageStatus 表示状态统计查询失败。 - analyticsStageStatus analyticsStage = "status" - // analyticsStageCity 表示城市统计查询失败。 - analyticsStageCity analyticsStage = "city" - // analyticsStageItem 表示商品统计查询失败。 - analyticsStageItem analyticsStage = "item" - // analyticsStageValidCount 表示有效订单总数查询失败。 - analyticsStageValidCount analyticsStage = "valid_count" - // analyticsStageValidRows 表示有效订单明细查询失败。 - analyticsStageValidRows analyticsStage = "valid_rows" -) - -// analyticsServiceError 保留订单分析失败阶段,供 HTTP 层映射兼容错误消息。 -type analyticsServiceError struct { - // stage 是失败的查询阶段。 - stage analyticsStage - // err 是底层数据库错误。 - err error -} - -// Error 返回订单分析错误文本。 -func (e *analyticsServiceError) Error() string { return e.err.Error() } - -// Unwrap 暴露底层数据库错误。 -func (e *analyticsServiceError) Unwrap() error { return e.err } - -// analyticsService 承载订单分析的数据库编排,不依赖 HTTP 请求或响应对象。 -type analyticsService struct { - // repository 提供分析查询、卡密库存和数据库方言能力。 - repository analyticsRepository -} - -// DashboardStats 查询当前用户的数据概览和可用卡密库存。 -func (svc *analyticsService) DashboardStats(ctx context.Context, userID int64) (dashboardStatsResponse, error) { - // counts 保存仪表盘各项计数。 - counts := map[string]int64{"total_cookies": 0, "active_cookies": 0, "total_cards": 0, "available_card_stock": 0, "total_keywords": 0, "total_orders": 0} - // queries 保存用户范围内的固定统计查询。 - queries := []struct { - query string - key string - }{ - {`SELECT COUNT(*) FROM cookies WHERE user_id=?`, "total_cookies"}, - {`SELECT COUNT(*) FROM cards WHERE user_id=?`, "total_cards"}, - {`SELECT COUNT(*) FROM keywords k WHERE EXISTS (SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`, "total_keywords"}, - {`SELECT COUNT(*) FROM orders o WHERE o.deleted_at IS NULL AND EXISTS (SELECT 1 FROM cookies c WHERE c.id=o.cookie_id AND c.user_id=?)`, "total_orders"}, - } - // item 是当前固定统计查询。 - for _, item := range queries { - // count 是当前统计项的数据库结果。 - var count int64 - // err 是当前统计项查询错误。 - if err := svc.repository.QueryRowContext(ctx, item.query, userID).Scan(&count); err != nil { - return dashboardStatsResponse{}, err - } - counts[item.key] = count - } - // activeCookies 是没有明确禁用记录的账号数量。 - var activeCookies int64 - // err 是活跃账号统计查询错误。 - if err := svc.repository.QueryRowContext(ctx, ` - SELECT COUNT(*) FROM cookies c WHERE c.user_id=? - AND NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0) - `, userID).Scan(&activeCookies); err != nil { - return dashboardStatsResponse{}, err - } - counts["active_cookies"] = activeCookies - // cards 和 err 是当前用户的卡密组列表及查询错误。 - cards, err := svc.repository.ListCardsForUser(ctx, userID) - if err != nil { - return dashboardStatsResponse{}, err - } - // card 是当前遍历到的卡密组。 - for _, card := range cards { - if !card.Enabled || card.Type != "data" { - continue - } - // line 是卡密组内容中的一行卡密。 - for _, line := range strings.Split(strings.ReplaceAll(card.DataContent, "\r\n", "\n"), "\n") { - if strings.TrimSpace(line) != "" { - counts["available_card_stock"]++ - } - } - } - return dashboardStatsResponse{TotalCookies: counts["total_cookies"], ActiveCookies: counts["active_cookies"], TotalCards: counts["total_cards"], AvailableCardStock: counts["available_card_stock"], TotalKeywords: counts["total_keywords"], TotalOrders: counts["total_orders"]}, nil -} - -// analyticsApplication 返回当前 Server 绑定的订单分析应用服务。 -func (s *Server) analyticsApplication() *analyticsService { - return s.applicationServiceSet().analytics -} - -// OrderAnalytics 查询收益及按日、状态、城市和商品维度聚合的订单分析结果。 -func (svc *analyticsService) OrderAnalytics(ctx context.Context, query analyticsQuery) (orderAnalyticsResponse, error) { - // amountFilter 是已经排除非法金额的查询条件。 - amountFilter := query.AmountFilter - // revenue 保存订单收益汇总结果。 - var revenue analyticsRevenueStatsResponse - // err 是收益汇总查询错误。 - if err := svc.repository.QueryRowContext(ctx, ` - SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0), - COALESCE(AVG(`+query.AmountClean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id) - FROM orders `+query.Where+amountFilter, query.Params...).Scan( - &revenue.TotalOrders, &revenue.TotalAmount, &revenue.AvgAmount, &revenue.UniqueBuyers, &revenue.UniqueItems); err != nil { - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageRevenue, err: err} - } - - // daily 保存按用户本地日期聚合的统计结果。 - daily := make([]analyticsDailyStatsResponse, 0) - // rows 和 err 是每日统计查询结果集及错误。 - rows, err := svc.repository.QueryContext(ctx, ` - SELECT order_id,amount,created_at FROM orders `+query.Where+amountFilter, query.Params...) - if err != nil { - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageDaily, err: err} - } - // dailyValue 保存同一天的订单数和金额累计值。 - type dailyValue struct { - count int - amount float64 - } - // dailyMap 按日期聚合订单数据,避免依赖数据库方言的日期函数。 - dailyMap := map[string]dailyValue{} - for rows.Next() { - // orderID、amountRaw 和 createdAt 是当前订单的原始字段。 - var orderID, amountRaw, createdAt string - if rows.Scan(&orderID, &amountRaw, &createdAt) != nil { - continue - } - // created 是转换后的订单创建时间。 - created := parseAnalyticsDBTime(createdAt) - if created.IsZero() { - continue - } - // date 是订单在用户时区中的日期。 - if query.Location != nil { - created = created.In(query.Location) - } - // date 是订单在用户时区中的日期。 - date := created.Format("2006-01-02") - // value 是当前日期的累计统计值。 - value := dailyMap[date] - value.count++ - value.amount += parseAnalyticsAmount(amountRaw) - dailyMap[date] = value - } - // err 是每日统计游标迭代错误。 - if err := rows.Err(); err != nil { - _ = rows.Close() - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageDaily, err: err} - } - _ = rows.Close() - // 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, analyticsDailyStatsResponse{Date: date, OrderCount: value.count, Amount: round2(value.amount)}) - } - - // statusStats 保存按订单状态聚合的结果。 - statusStats := make([]analyticsStatusStatsResponse, 0) - // statusValue 保存单个状态的累计统计值。 - type statusValue struct { - count int - amount float64 - } - // statusMap 按归一化状态聚合订单数据。 - statusMap := map[string]statusValue{} - // rows 和 err 是状态统计查询结果集及错误。 - rows, err = svc.repository.QueryContext(ctx, ` - SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0) - FROM orders `+query.Where+amountFilter+` - GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, query.Params...) - if err != nil { - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageStatus, err: err} - } - for rows.Next() { - // status、count 和 amount 是当前状态的数据库聚合值。 - var status string - // count 和 amount 是当前状态的订单数和金额。 - var count int - // amount 是当前状态的订单金额。 - var amount float64 - if rows.Scan(&status, &count, &amount) == nil { - status = db.NormalizeOrderStatus(status) - // value 是当前状态的累计统计值。 - value := statusMap[status] - value.count += count - value.amount += amount - statusMap[status] = value - } - } - // err 是状态统计游标迭代错误。 - if err := rows.Err(); err != nil { - _ = rows.Close() - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageStatus, err: err} - } - _ = rows.Close() - // 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, analyticsStatusStatsResponse{Status: status, Count: value.count, Amount: round2(value.amount)}) - } - - // cityStats 保存按收货城市聚合的结果。 - cityStats := make([]analyticsCityStatsResponse, 0) - // rows 和 err 是城市统计查询结果集及错误。 - rows, err = svc.repository.QueryContext(ctx, ` - SELECT receiver_city, COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0) - FROM orders `+query.Where+amountFilter+` - AND receiver_city IS NOT NULL AND receiver_city != '' - GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, query.Params...) - if err != nil { - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageCity, err: err} - } - for rows.Next() { - // city、count 和 amount 是当前城市的数据库聚合值。 - var city string - // count 和 amount 是当前城市的订单数和金额。 - var count int - // amount 是当前城市的订单金额。 - var amount float64 - if rows.Scan(&city, &count, &amount) == nil { - cityStats = append(cityStats, analyticsCityStatsResponse{City: city, OrderCount: count, TotalAmount: round2(amount)}) - } - } - // err 是城市统计游标迭代错误。 - if err := rows.Err(); err != nil { - _ = rows.Close() - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageCity, err: err} - } - _ = rows.Close() - - // itemStats 保存按商品标识聚合的排行结果。 - itemStats := make([]analyticsItemStatsResponse, 0) - // rows 和 err 是商品统计查询结果集及错误。 - rows, err = svc.repository.QueryContext(ctx, ` - SELECT item_id, COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0), COALESCE(AVG(`+query.AmountClean+`),0) - FROM orders `+query.Where+amountFilter+` - AND item_id IS NOT NULL AND item_id != '' - GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, query.Params...) - if err != nil { - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageItem, err: err} - } - for rows.Next() { - // itemID、count、total 和 average 是当前商品的数据库聚合值。 - var itemID string - // count、total 和 average 是当前商品的订单数、总金额和平均金额。 - var count int - // total 和 average 是当前商品的总金额和平均金额。 - var total, average float64 - if rows.Scan(&itemID, &count, &total, &average) == nil { - itemStats = append(itemStats, analyticsItemStatsResponse{ItemID: itemID, OrderCount: count, TotalAmount: round2(total), AvgAmount: round2(average)}) - } - } - // err 是商品统计游标迭代错误。 - if err := rows.Err(); err != nil { - _ = rows.Close() - return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageItem, err: err} - } - _ = rows.Close() - return orderAnalyticsResponse{ - RevenueStats: analyticsRevenueStatsResponse{ - 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 *analyticsService) ValidOrders(ctx context.Context, query analyticsQuery, page, pageSize int) (validOrdersResponse, error) { - // amountFilter 是已经排除非法金额的查询条件。 - amountFilter := query.AmountFilter - // total 是符合筛选条件的订单总数。 - var total int - // err 是有效订单总数查询错误。 - if err := svc.repository.QueryRowContext(ctx, `SELECT COUNT(*) FROM orders `+query.Where+amountFilter, query.Params...).Scan(&total); err != nil { - return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidCount, err: err} - } - // queryParams 是分页查询附加的 LIMIT/OFFSET 参数。 - queryParams := append(append([]any{}, query.Params...), pageSize, (page-1)*pageSize) - // rows 和 err 是有效订单明细查询结果集及错误。 - rows, err := svc.repository.QueryContext(ctx, ` - SELECT orders.order_id, COALESCE(orders.item_id,''), COALESCE(item_info.item_title,''), - COALESCE(item_info.item_detail,''), COALESCE(orders.buyer_id,''), COALESCE(orders.quantity,'1'), - orders.amount, COALESCE(orders.order_status,'unknown'), COALESCE(orders.cookie_id,''), orders.created_at - FROM orders LEFT JOIN item_info ON item_info.cookie_id=orders.cookie_id AND item_info.item_id=orders.item_id - `+query.Where+amountFilter+` ORDER BY orders.created_at DESC LIMIT ? OFFSET ?`, queryParams...) - if err != nil { - return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidRows, err: err} - } - defer rows.Close() - // out 是有效订单响应列表。 - out := make([]validOrderResponse, 0) - for rows.Next() { - // orderID、itemID、itemTitle、itemDetail、buyerID、quantity、amount、status、cookieID 和 createdAt 是订单字段。 - var orderID, itemID, itemTitle, itemDetail, buyerID, quantity, amount, status, cookieID, createdAt string - if rows.Scan(&orderID, &itemID, &itemTitle, &itemDetail, &buyerID, &quantity, &amount, &status, &cookieID, &createdAt) == nil { - status = db.NormalizeOrderStatus(status) - out = append(out, validOrderResponse{OrderID: orderID, ItemID: itemID, BuyerID: buyerID, ItemTitle: itemTitle, ItemImage: itemImageFromDetail(itemDetail), Quantity: quantity, Amount: amount, OrderStatus: status, Status: status, CookieID: cookieID, CreatedAt: createdAt}) - } - } - // err 是有效订单游标迭代错误。 - if err := rows.Err(); err != nil { - return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidRows, err: err} - } - return validOrdersResponse{Orders: out, Total: total, Page: page, PageSize: pageSize, Truncated: (page-1)*pageSize+len(out) < total}, nil -} - -// analyticsStageOf 读取分析服务错误阶段。 -func analyticsStageOf(err error) (analyticsStage, bool) { - // serviceErr 是带查询阶段的应用服务错误。 - var serviceErr *analyticsServiceError - if !errors.As(err, &serviceErr) { - return "", false - } - return serviceErr.stage, true -} - -// analyticsErrorMessage 将分析服务阶段映射为原有 HTTP 错误消息。 -func analyticsErrorMessage(err error) string { - // stage 是应用服务错误对应的查询阶段。 - switch stage, _ := analyticsStageOf(err); stage { - case analyticsStageRevenue: - return "查询收益统计失败" - case analyticsStageDaily: - return "查询每日统计失败" - case analyticsStageStatus: - return "查询状态统计失败" - case analyticsStageCity: - return "查询城市统计失败" - case analyticsStageItem: - return "查询商品统计失败" - default: - return "查询失败" - } -} - -// analyticsQueryAmountFilter 根据订单分析查询构造金额过滤条件。 -func analyticsQueryAmountFilter(store *db.Store, column string) (string, string) { - // clean 是按数据库方言清洗后的金额表达式。 - clean := analyticsAmountExpression(store.Dialect, column) - return clean, " AND " + clean + " IS NOT NULL" -} - -// analyticsQueryParamsCopy 复制查询参数,避免服务层修改 handler 持有的切片。 -func analyticsQueryParamsCopy(params []any) []any { - return append([]any(nil), params...) -} diff --git a/internal/server/api_contract.go b/internal/server/api_contract.go index 6fab303..dca965c 100644 --- a/internal/server/api_contract.go +++ b/internal/server/api_contract.go @@ -6,7 +6,7 @@ import ( "github.com/go-chi/chi/v5/middleware" - "xianyu-go/internal/db" + accountapp "xianyu-go/internal/application/account" "xianyu-go/internal/httpapi" ) @@ -98,7 +98,7 @@ func writeErrDetails(w http.ResponseWriter, status int, code, msg, requestID str // writeCredentialVerificationError 将当前密码校验失败区分为认证失败或内部故障。 func writeCredentialVerificationError(w http.ResponseWriter, err error) { - if errors.Is(err, db.ErrPasswordMismatch) { + if errors.Is(err, accountapp.ErrPasswordMismatch) { writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "") return } diff --git a/internal/server/api_contract_test.go b/internal/server/api_contract_test.go index 081797c..8095291 100644 --- a/internal/server/api_contract_test.go +++ b/internal/server/api_contract_test.go @@ -152,14 +152,14 @@ func assertUnifiedAPIError(t *testing.T, handler http.Handler, method, path, bod // TestAPIContractRemainingAuthenticationErrors 验证初始化和密码凭据错误统一使用非 2xx 响应。 func TestAPIContractRemainingAuthenticationErrors(t *testing.T) { // srv 是用于验证剩余认证错误边界的 HTTP 测试服务。 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // handler 是当前测试使用的完整路由树。 handler := srv.Router() // sessionCookie 是管理员登录后得到的认证会话。 sessionCookie := loginHelper(t, handler) // created 表示用于验证用户名冲突的占位用户是否成功创建。 - created, createErr := srv.Store.Users.Create(context.Background(), "taken-user", "taken@example.com", "pw") + created, createErr := store.Users.Create(context.Background(), "taken-user", "taken@example.com", "pw") if createErr != nil || !created { t.Fatalf("create conflict user: created=%v err=%v", created, createErr) } diff --git a/internal/server/application_services.go b/internal/server/application_services.go index 4434166..31c0abe 100644 --- a/internal/server/application_services.go +++ b/internal/server/application_services.go @@ -1,33 +1,71 @@ package server import ( + "context" + + "xianyu-go/internal/adapter" accountapp "xianyu-go/internal/application/account" + adminapp "xianyu-go/internal/application/admin" + analyticsapp "xianyu-go/internal/application/analytics" + automationapp "xianyu-go/internal/application/automation" + cardsapp "xianyu-go/internal/application/cards" chatapp "xianyu-go/internal/application/chat" + defaultreplyapp "xianyu-go/internal/application/defaultreply" itemapp "xianyu-go/internal/application/items" + keywordsapp "xianyu-go/internal/application/keywords" notificationsapp "xianyu-go/internal/application/notifications" orderapp "xianyu-go/internal/application/orders" + settingsapp "xianyu-go/internal/application/settings" ) // applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。 type applicationServices struct { // orders 是订单 HTTP 适配器;业务服务集合由应用层统一构造。 orders *orderHTTPAdapter - // itemPublish 是商品发布应用服务。 - itemPublish *itemPublishService // itemSinglePublish 是仅负责单商品发布用例的纯应用服务。 itemSinglePublish *itemapp.Service // itemBatchRunner 是商品批量发布 worker 的应用层编排器。 itemBatchRunner *itemapp.BatchRunner + // itemBatchRecovery 是过期批量发布任务的租约接管应用服务。 + itemBatchRecovery *itemapp.BatchRecoveryService + // itemBatchPreview 是商品批量发布表格预检应用服务。 + itemBatchPreview *itemapp.BatchPreviewService + // itemBatchManagement 是商品批次查询、取消和重试应用服务。 + itemBatchManagement *itemapp.BatchManagementService + // itemCategoryRecommendation 是商品类目推荐应用服务。 + itemCategoryRecommendation *itemapp.CategoryRecommendationService + // itemBatchPreviewPersistence 是预检结果持久化应用服务。 + itemBatchPreviewPersistence *itemapp.BatchPreviewPersistenceService + // itemBatchLocalPublish 是远端发布成功后的本地商品与规则收口服务。 + itemBatchLocalPublish *itemapp.BatchLocalPublishService + // itemSync 是商品全量和分页同步应用服务。 + itemSync *itemapp.SyncService + // itemCatalog 是商品列表和详情读取应用服务。 + itemCatalog *itemapp.CatalogService + // itemCatalogMutation 是商品创建、更新、删除和交付开关应用服务。 + itemCatalogMutation *itemapp.CatalogMutationService // accountLogin 是账号登录应用服务。 accountLogin *accountLoginService + // authentication 是用户会话、密码校验和登录凭据应用服务。 + authentication *accountapp.AuthenticationService + // loginAudit 是登录成功审计应用服务,负责方式归一化和账号启用编排。 + loginAudit *accountapp.LoginAuditService // passwordLogin 是密码登录策略应用服务;当前只返回关闭策略,不保存登录秘密或会话。 passwordLogin *accountapp.PasswordLoginService // accountDelete 是账号删除应用服务,负责停止 fencing 和归属复核后的持久化删除。 accountDelete *accountapp.DeleteService // accountProfile 是账号资料刷新应用服务。 accountProfile *accountapp.ProfileService - // communication 是聊天、通知和账号任务应用服务。 - communication *communicationService + // accountLongLogin 是账号长登录设置应用服务。 + accountLongLogin *accountapp.LongLoginService + // accountSettings 是账号设置、登录信息、启停和暂停应用服务。 + accountSettings *accountapp.SettingsService + // accountSummaries 是账号摘要、所有权和管理员账号列表应用服务。 + accountSummaries *accountapp.SummaryService + // accountTasks 是账号任务设置、历史和手动执行应用服务。 + accountTasks *automationapp.Service + // credentialWake 是凭证恢复后唤醒自动化任务的应用服务。 + credentialWake *automationapp.CredentialWakeService // chat 是聊天历史查询应用服务,负责用户归属和分页编排。 chat *chatapp.Service // uncertainNotifications 是通知不确定状态运维查询应用服务。 @@ -35,37 +73,126 @@ type applicationServices struct { // notificationChannels 是通知渠道 CRUD 与账号绑定应用服务。 notificationChannels *notificationsapp.ChannelService // analytics 是订单分析应用服务。 - analytics *analyticsService + analytics *analyticsapp.Service + // automationIssues 是自动化异常查询与人工处理应用服务。 + automationIssues *automationapp.IssueService + // automationRules 是自动化规则校验、分页和持久化应用服务。 + automationRules *automationapp.RuleService + // cards 是卡券 CRUD、输入校验和所有权编排应用服务。 + cards *cardsapp.Service + // publishAutomationRules 是批量发布成功后幂等准备自动化规则的应用服务。 + publishAutomationRules *automationapp.PublishRuleService + // defaultReplies 是默认回复配置与投递记录应用服务。 + defaultReplies *defaultreplyapp.Service + // keywords 是关键词规则与指定商品回复应用服务。 + keywords *keywordsapp.Service + // settings 是系统、用户和账号 AI 设置应用服务。 + settings *settingsapp.Service + // admin 是管理员用户管理与全局统计应用服务。 + admin *adminapp.Service } // newApplicationServices 为指定 Server 装配全部应用服务实例。 func newApplicationServices(server *Server) *applicationServices { // orderRepository 保存订单应用服务共享的基础设施适配器。 - orderRepository := newStoreOrderRepository(server.Store) + orderRepository := server.dependencies.NewOrderRepository() + // orderReconciliation 保存订单补偿写入应用 Port 的数据库适配器。 + orderReconciliation := server.dependencies.NewOrderReconciliationRepository() // orderRuntime 保存订单服务共享的运行时能力适配器。 - orderRuntime := newServerOrderRuntime(server) + orderRuntime := newServerOrderRuntime(server, orderReconciliation) // orderServices 保存应用层统一构造的订单业务服务集合。 - orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, newStoreOrderRefreshJobRepository(server.Store), refreshOrderChunkSize) + orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.dependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize) // accountProfile 保存账号资料刷新用例的构造结果。 - accountProfile, profileErr := newAccountProfileApplication(server) + // accountRepository 提供账号登录、资料摘要和删除共用的数据库适配器。 + accountRepository := server.dependencies.NewAccountLoginRepository() + // accountProfile 由应用层服务编排平台资料刷新与非敏感摘要持久化。 + accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, server.recoverExpiredMTOPSession, server.Logger)) if profileErr != nil { panic(profileErr) } + // accountLongLogin 由适配器承载平台调用、Cookie 快照合并和凭证写回。 + accountLongLogin, longLoginErr := accountapp.NewLongLoginService( + accountRepository, + adapter.NewLongLoginAdapter(accountRepository, func() adapter.LongLoginClient { return server.CookieRenew }, server.updateRunningCookie, server.Logger), + ) + if longLoginErr != nil { + panic(longLoginErr) + } + // accountSettings 由独立适配器承载账号设置写入与敏感登录信息更新。 + var settingsRuntime accountapp.SettingsRuntime + if server.Manager != nil { + settingsRuntime = server.Manager + } + // accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。 + accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.dependencies.NewAccountSettingsRepository(), settingsRuntime) + if accountSettingsErr != nil { + panic(accountSettingsErr) + } + // accountSummaryRepository 保存普通用户与管理员共用的摘要查询适配器。 + accountSummaryRepository := server.dependencies.NewAccountSummaryRepository() + // accountSummaries、accountSummariesErr 保存账号摘要应用服务及其装配错误。 + accountSummaries, accountSummariesErr := accountapp.NewSummaryService(accountSummaryRepository, accountSummaryRepository) + if accountSummariesErr != nil { + panic(accountSummariesErr) + } + // credentialWake 负责将凭证恢复后的任务唤醒写入收口到适配器。 + credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(server.dependencies.NewAutomationCredentialWakeRepository()) + if credentialWakeErr != nil { + panic(credentialWakeErr) + } // deleteRuntime 是可选的账号运行时端口;显式保持 nil,避免把 nil *Manager 装入非空接口后触发 panic。 var deleteRuntime accountapp.DeleteRuntime if server.Manager != nil { deleteRuntime = server.Manager } // accountDelete 是账号删除用例的构造结果,运行时端口可为空以兼容无 Manager 的测试 Server。 - accountDelete, deleteErr := accountapp.NewDeleteService(storeAccountProfileRepository{store: server.Store}, deleteRuntime) + accountDelete, deleteErr := accountapp.NewDeleteService(accountRepository, deleteRuntime) if deleteErr != nil { panic(deleteErr) } + // itemBatchPublish 是批量远端发布适配器,图片安全回调由 Server 装配时注入。 + itemBatchPublish := server.dependencies.NewItemBatchPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) { + server.recoverExpiredMTOPSession(ctx, cookieID, err) + }, readBatchImageFile, downloadImageURL) + // itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。 + itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService( + server.dependencies.NewItemBatchRepository(), + server.dependencies.NewItemCatalogRepository(), + server.dependencies.NewAutomationRepository(), + ) + if itemBatchLocalPublishErr != nil { + panic(itemBatchLocalPublishErr) + } // itemBatchRunner 是批量发布 worker 的构造结果,失败表示必需端口装配错误。 - itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server) + itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server, itemBatchPublish, itemBatchLocalPublish) if batchRunnerErr != nil { panic(batchRunnerErr) } + // itemBatchRecovery 负责恢复扫描的批次状态编排,worker 启动仍由 Server 生命周期边界提供。 + itemBatchRecovery, batchRecoveryErr := itemapp.NewBatchRecoveryService( + server.dependencies.NewItemBatchRepository(), + itemapp.BatchRecoveryOptions{ + LeaseDuration: publishBatchLease, + StartWorker: func(ctx context.Context, userID int64, batchID, workerToken string) { + server.startPublishBatchWorker(ctx, userID, batchID, workerToken) + }, + }, + ) + if batchRecoveryErr != nil { + panic(batchRecoveryErr) + } + // itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。 + itemBatchPreviewPort := server.dependencies.NewItemBatchPreviewPort() + // itemBatchPreview 是批量发布预检应用服务的构造结果。 + itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort) + if itemBatchPreviewErr != nil { + panic(itemBatchPreviewErr) + } + // itemBatchManagement 是批次管理应用服务的构造结果。 + itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.dependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server}) + if itemBatchManagementErr != nil { + panic(itemBatchManagementErr) + } // accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。 accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(server) if accountLoginCreateErr != nil { @@ -73,50 +200,231 @@ func newApplicationServices(server *Server) *applicationServices { } // accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。 var accountQRLogin *accountapp.QRLoginService - if server.Store != nil { + if server.dependencies != nil { // accountQRLoginErr 保存扫码应用服务装配失败原因。 var accountQRLoginErr error - accountQRLogin, accountQRLoginErr = newAccountQRLoginApplication(server) + accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.dependencies.NewQRLoginRepository(), serverQRLoginLifecycle{server: server}) if accountQRLoginErr != nil { panic(accountQRLoginErr) } } + // automationRepository 复用同一个数据库适配器,保持自动化异常与规则查询的基础设施边界一致。 + automationRepository := server.dependencies.NewAutomationRepository() + // settingsService 统一装配设置数据库与远端模型目录适配器。 + settingsService := settingsapp.NewService(server.dependencies.NewSettingsRepository(), adapter.NewAIModelClient()) + // adminService 负责管理员用户与仪表盘查询,HTTP 层只做 DTO 映射。 + adminService := adminapp.NewService(server.dependencies.NewAdminRepository()) + // itemCatalogRepository 是商品读写用例共用的数据库适配器。 + itemCatalogRepository := server.dependencies.NewItemCatalogRepository() + // itemCatalog 是商品列表和详情读取用例的应用服务。 + itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository) + if itemCatalogErr != nil { + panic(itemCatalogErr) + } + // itemCatalogMutation 是商品写入用例的应用服务。 + itemCatalogMutation, itemCatalogMutationErr := itemapp.NewCatalogMutationService(itemCatalogRepository) + if itemCatalogMutationErr != nil { + panic(itemCatalogMutationErr) + } + // itemPublishPort 是单商品与批量发布共享的平台凭证适配器。 + itemPublishPort := server.dependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) { + server.recoverExpiredMTOPSession(ctx, cookieID, err) + }) + // itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。 + itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort) + if itemCategoryRecommendationErr != nil { + panic(itemCategoryRecommendationErr) + } + // itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。 + itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.dependencies.NewItemBatchRepository()) + if itemBatchPreviewPersistenceErr != nil { + panic(itemBatchPreviewPersistenceErr) + } + // itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。 + itemSinglePublish, itemSinglePublishErr := itemapp.NewService( + itemPublishPort, + server.dependencies.NewItemPublishRepository(), + ) + if itemSinglePublishErr != nil { + panic(itemSinglePublishErr) + } return &applicationServices{ - orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository}, - itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)}, - itemSinglePublish: newItemPublishApplication(server), - itemBatchRunner: itemBatchRunner, - accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate, qrApplication: accountQRLogin}, + orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository}, + itemSinglePublish: itemSinglePublish, + itemBatchRunner: itemBatchRunner, + itemBatchRecovery: itemBatchRecovery, + itemBatchPreview: itemBatchPreview, + itemBatchManagement: itemBatchManagement, + itemCategoryRecommendation: itemCategoryRecommendation, + itemBatchPreviewPersistence: itemBatchPreviewPersistence, + itemBatchLocalPublish: itemBatchLocalPublish, + itemSync: itemapp.NewSyncService(server.dependencies.NewItemSyncRepository(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) { + server.recoverExpiredMTOPSession(ctx, cookieID, err) + })), + itemCatalog: itemCatalog, + itemCatalogMutation: itemCatalogMutation, + accountLogin: &accountLoginService{server: server, repository: accountRepository, summaryRepository: accountSummaryRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin}, + authentication: newAuthenticationApplication(server), + loginAudit: accountapp.NewLoginAuditService(server.dependencies.NewAccountLoginAuditRepository()), passwordLogin: accountapp.NewPasswordLoginService(), accountDelete: accountDelete, accountProfile: accountProfile, - communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)}, + accountLongLogin: accountLongLogin, + accountSettings: accountSettings, + accountSummaries: accountSummaries, + accountTasks: automationapp.NewService(server.dependencies.NewAccountTaskRepository(), adapter.NewAccountTaskRunner(server.automation)), + credentialWake: credentialWake, chat: newChatSendingApplication(server), - uncertainNotifications: notificationsapp.New(newStoreNotificationUncertainRepository(server.Store)), - notificationChannels: notificationsapp.NewChannelService(newStoreNotificationChannelRepository(server.Store), server.notifier), - analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)}, + uncertainNotifications: notificationsapp.New(server.dependencies.NewNotificationUncertainRepository()), + notificationChannels: notificationsapp.NewChannelService(server.dependencies.NewNotificationChannelRepository(), server.notifier), + analytics: analyticsapp.NewService(server.dependencies.NewAnalyticsRepository()), + automationRules: automationapp.NewRuleService(automationRepository, automationRepository), + cards: cardsapp.NewService(server.dependencies.NewCardsRepository()), + publishAutomationRules: automationapp.NewPublishRuleService(automationRepository), + automationIssues: automationapp.NewIssueService(automationRepository), + defaultReplies: defaultreplyapp.NewService(server.dependencies.NewDefaultReplyRepository()), + keywords: keywordsapp.NewService(server.dependencies.NewKeywordRepository()), + settings: settingsService, + admin: adminService, } } +// newAuthenticationApplication 构造用户认证应用服务及其数据库适配器。 +func newAuthenticationApplication(server *Server) *accountapp.AuthenticationService { + // authentication、authenticationErr 保存认证应用服务及其装配错误。 + authentication, authenticationErr := accountapp.NewAuthenticationService(server.dependencies.NewAuthenticationRepository()) + if authenticationErr != nil { + panic(authenticationErr) + } + return authentication +} + +// itemCatalogApplication 返回当前 Server 绑定的商品读取应用服务。 +func (s *Server) itemCatalogApplication() *itemapp.CatalogService { + return s.applicationServiceSet().itemCatalog +} + +// itemSinglePublishApplication 返回当前 Server 绑定的单商品发布应用服务。 +func (s *Server) itemSinglePublishApplication() *itemapp.Service { + return s.applicationServiceSet().itemSinglePublish +} + +// itemCatalogMutationApplication 返回当前 Server 绑定的商品写入应用服务。 +func (s *Server) itemCatalogMutationApplication() *itemapp.CatalogMutationService { + return s.applicationServiceSet().itemCatalogMutation +} + +// itemSyncApplication 返回当前 Server 绑定的商品同步应用服务。 +func (s *Server) itemSyncApplication() *itemapp.SyncService { + return s.applicationServiceSet().itemSync +} + +// cardsApplication 返回当前 Server 绑定的卡券 CRUD 应用服务。 +func (s *Server) cardsApplication() *cardsapp.Service { + return s.applicationServiceSet().cards +} + +// accountTaskApplication 返回当前 Server 绑定的账号任务应用服务。 +func (s *Server) accountTaskApplication() *automationapp.Service { + return s.applicationServiceSet().accountTasks +} + +// credentialWakeApplication 返回当前 Server 绑定的凭证恢复唤醒应用服务。 +func (s *Server) credentialWakeApplication() *automationapp.CredentialWakeService { + return s.applicationServiceSet().credentialWake +} + +// automationIssuesApplication 返回当前 Server 绑定的自动化异常应用服务。 +func (s *Server) automationIssuesApplication() *automationapp.IssueService { + return s.applicationServiceSet().automationIssues +} + +// automationRulesApplication 返回当前 Server 绑定的自动化规则应用服务。 +func (s *Server) automationRulesApplication() *automationapp.RuleService { + return s.applicationServiceSet().automationRules +} + // itemBatchRunnerApplication 返回当前 Server 绑定的批量发布 worker 编排器。 func (s *Server) itemBatchRunnerApplication() *itemapp.BatchRunner { return s.applicationServiceSet().itemBatchRunner } +// itemBatchRecoveryApplication 返回当前 Server 绑定的批量恢复应用服务。 +func (s *Server) itemBatchRecoveryApplication() *itemapp.BatchRecoveryService { + return s.applicationServiceSet().itemBatchRecovery +} + +// itemBatchPreviewApplication 返回当前 Server 绑定的批量预检应用服务。 +func (s *Server) itemBatchPreviewApplication() *itemapp.BatchPreviewService { + return s.applicationServiceSet().itemBatchPreview +} + +// itemBatchManagementApplication 返回当前 Server 绑定的批次管理应用服务。 +func (s *Server) itemBatchManagementApplication() *itemapp.BatchManagementService { + return s.applicationServiceSet().itemBatchManagement +} + +// itemCategoryRecommendationApplication 返回商品类目推荐应用服务。 +func (s *Server) itemCategoryRecommendationApplication() *itemapp.CategoryRecommendationService { + return s.applicationServiceSet().itemCategoryRecommendation +} + +// itemBatchPreviewPersistenceApplication 返回预检结果持久化应用服务。 +func (s *Server) itemBatchPreviewPersistenceApplication() *itemapp.BatchPreviewPersistenceService { + return s.applicationServiceSet().itemBatchPreviewPersistence +} + // accountProfileApplication 返回当前 Server 绑定的账号资料应用服务。 func (s *Server) accountProfileApplication() *accountapp.ProfileService { return s.applicationServiceSet().accountProfile } +// accountLongLoginApplication 返回当前 Server 绑定的长登录应用服务。 +func (s *Server) accountLongLoginApplication() *accountapp.LongLoginService { + return s.applicationServiceSet().accountLongLogin +} + +// accountSettingsApplication 返回当前 Server 绑定的账号设置应用服务。 +func (s *Server) accountSettingsApplication() *accountapp.SettingsService { + return s.applicationServiceSet().accountSettings +} + +// authenticationApplication 返回当前 Server 绑定的用户认证应用服务。 +func (s *Server) authenticationApplication() *accountapp.AuthenticationService { + return s.applicationServiceSet().authentication +} + +// accountSummaryApplication 返回当前 Server 绑定的账号摘要应用服务。 +func (s *Server) accountSummaryApplication() *accountapp.SummaryService { + return s.applicationServiceSet().accountSummaries +} + // accountDeleteApplication 返回当前 Server 绑定的账号删除应用服务。 func (s *Server) accountDeleteApplication() *accountapp.DeleteService { return s.applicationServiceSet().accountDelete } +// loginAuditApplication 返回当前 Server 绑定的登录成功审计应用服务。 +func (s *Server) loginAuditApplication() *accountapp.LoginAuditService { + return s.applicationServiceSet().loginAudit +} + +// settingsApplication 返回当前 Server 绑定的设置应用服务。 +func (s *Server) settingsApplication() *settingsapp.Service { + return s.applicationServiceSet().settings +} + // applicationServiceSet 返回当前 Server 的应用服务集合,并兼容测试 Server。 func (s *Server) applicationServiceSet() *applicationServices { + if s == nil { + return &applicationServices{} + } if s.applications != nil { return s.applications } + if s.dependencies == nil { + // accountLogin 仅用于零值 Server 的输入校验测试,不触发任何持久化访问。 + return &applicationServices{accountLogin: &accountLoginService{server: s}} + } return newApplicationServices(s) } diff --git a/internal/server/application_services_test.go b/internal/server/application_services_test.go index ea66f65..d518f40 100644 --- a/internal/server/application_services_test.go +++ b/internal/server/application_services_test.go @@ -12,13 +12,13 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) { } // services 是统一应用服务集合。 services := srv.applicationServiceSet() - if services.orders == nil || services.itemPublish == nil || services.itemSinglePublish == nil || services.accountLogin == nil || services.passwordLogin == nil || services.accountDelete == nil || services.communication == nil || services.analytics == nil { + if services.orders == nil || services.itemSinglePublish == nil || services.itemCatalog == nil || services.itemCatalogMutation == nil || services.accountLogin == nil || services.authentication == nil || services.loginAudit == nil || services.passwordLogin == nil || services.accountDelete == nil || services.accountSettings == nil || services.analytics == nil || services.publishAutomationRules == nil || services.defaultReplies == nil || services.keywords == nil { t.Fatal("应用服务集合存在未装配的服务") } if services.orders.services == nil || services.orders.services.List == nil || services.orders.services.Detail == nil || services.orders.services.Refresh == nil || services.orders.services.RefreshJobs == nil { t.Fatal("订单应用服务应由应用层 ServiceSet 完整装配") } - if srv.orders() != services.orders || srv.itemPublishApplication() != services.itemPublish || srv.accountLoginApplication() != services.accountLogin || srv.communicationApplication() != services.communication || srv.analyticsApplication() != services.analytics { + if srv.orders() != services.orders || srv.itemCatalogApplication() != services.itemCatalog || srv.itemCatalogMutationApplication() != services.itemCatalogMutation || srv.accountLoginApplication() != services.accountLogin || srv.analyticsApplication() != services.analytics || srv.defaultReplyApplication() != services.defaultReplies || srv.keywordApplication() != services.keywords { t.Fatal("应用服务访问器未返回统一装配实例") } } diff --git a/internal/server/auth_handlers.go b/internal/server/auth_handlers.go index fd19462..ec25a9b 100644 --- a/internal/server/auth_handlers.go +++ b/internal/server/auth_handlers.go @@ -8,8 +8,8 @@ import ( "time" "unicode/utf8" + accountapp "xianyu-go/internal/application/account" "xianyu-go/internal/auth" - "xianyu-go/internal/db" ) // loginRequest 是登录请求体。 @@ -53,7 +53,7 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) { defer s.initializationMu.Unlock() // initialized、err 保存initialized、err,供当前处理流程使用 - initialized, err := s.Store.Users.IsSystemInitialized(r.Context()) + initialized, err := s.authenticationApplication().IsSystemInitialized(r.Context()) if err != nil { writeErr(w, http.StatusInternalServerError, "检查系统初始化状态失败") return @@ -64,13 +64,13 @@ func (s *Server) initialize(w http.ResponseWriter, r *http.Request) { } if // err 保存err,供当前处理流程使用 - _, err := auth.InitAdmin(r.Context(), s.Store, "admin@example.com", req.Password); err != nil { + _, err := s.authenticationApplication().InitializeAdmin(r.Context(), "admin@example.com", req.Password); err != nil { writeErr(w, http.StatusInternalServerError, "初始化管理员失败") return } // 初始化完成后立即建立会话,用户无需再手动输入一次 admin 账号和密码。 - sid, user, err := s.Auth.Login(r.Context(), "admin", req.Password) + sid, user, err := s.authenticationApplication().Login(r.Context(), "admin", req.Password) if err != nil || user == nil || sid == "" { writeErr(w, http.StatusInternalServerError, "初始化完成,但自动登录失败,请使用 admin 账号登录") return @@ -108,7 +108,7 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) { switch { case req.Username != "" && req.Password != "": // sid、user、err 保存sid、user、err,供当前处理流程使用 - sid, user, err := s.Auth.Login(r.Context(), req.Username, req.Password) + sid, user, err := s.authenticationApplication().Login(r.Context(), req.Username, req.Password) if err != nil || user == nil || sid == "" { s.loginLimiter.failure(clientIP, principal, time.Now()) writeErrCode(w, http.StatusUnauthorized, "authentication_failed", @@ -125,16 +125,16 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, resp) return case req.Email != "" && req.Password != "": - // user、err 保存user、err,供当前处理流程使用 - user, err := s.Store.Users.GetByEmail(r.Context(), req.Email) - if err != nil || user == nil { + // username、err 保存邮箱映射得到的登录用户名和查询错误,供当前处理流程使用 + username, err := s.authenticationApplication().UsernameByEmail(r.Context(), req.Email) + if err != nil || username == "" { s.loginLimiter.failure(clientIP, principal, time.Now()) writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "邮箱或密码错误", "") return } // sid、loginUser、lerr 保存sid、loginUser、lerr,供当前处理流程使用 - sid, loginUser, lerr := s.Auth.Login(r.Context(), user.Username, req.Password) + sid, loginUser, lerr := s.authenticationApplication().Login(r.Context(), username, req.Password) if lerr != nil || loginUser == nil || sid == "" { s.loginLimiter.failure(clientIP, principal, time.Now()) writeErrCode(w, http.StatusUnauthorized, "authentication_failed", @@ -160,7 +160,7 @@ func (s *Server) verify(w http.ResponseWriter, r *http.Request) { // ctx 保存ctx,供当前处理流程使用 ctx := r.Context() // initialized 保存initialized,供当前处理流程使用 - initialized, _ := s.Store.Users.IsSystemInitialized(ctx) + initialized, _ := s.authenticationApplication().IsSystemInitialized(ctx) // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(ctx) if sess != nil { @@ -215,13 +215,13 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) { return } // 校验当前密码。 - user, ok, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword) - if !ok || user == nil { + _, ok, _ := s.authenticationApplication().VerifyPassword(ctx, sess.Username, req.CurrentPassword) + if !ok { writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "") return } if // err 保存err,供当前处理流程使用 - _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil { + _, err := s.authenticationApplication().UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil { writeErr(w, http.StatusInternalServerError, "更新失败") return } @@ -253,14 +253,14 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusUnauthorized, "未授权访问") return } - // user 保存用户,供当前处理流程使用 - user, _, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword) - if user == nil { + // ok 保存当前密码是否匹配,应用层不会向 HTTP 层暴露密码哈希。 + _, ok, _ := s.authenticationApplication().VerifyPassword(ctx, sess.Username, req.CurrentPassword) + if !ok { writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "") return } if // err 保存err,供当前处理流程使用 - _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil { + _, err := s.authenticationApplication().UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil { writeErr(w, http.StatusInternalServerError, "更新失败") return } @@ -308,18 +308,18 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) { return } // user、ok、err 保存user、ok、err,供当前处理流程使用 - user, ok, err := s.Store.Users.VerifyAndUpgrade(r.Context(), sess.Username, req.CurrentPassword) + user, ok, err := s.authenticationApplication().VerifyPassword(r.Context(), sess.Username, req.CurrentPassword) if err != nil { writeCredentialVerificationError(w, err) return } - if !ok || user == nil || user.ID != sess.UserID { + if !ok || user.ID != sess.UserID { writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "") return } if // err 保存err,供当前处理流程使用 - err := s.Store.Users.UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil { - if errors.Is(err, db.ErrUsernameTaken) { + err := s.authenticationApplication().UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil { + if errors.Is(err, accountapp.ErrUsernameTaken) { writeErrCode(w, http.StatusConflict, "username_taken", "用户名已被占用", "") return } diff --git a/internal/server/automation_handlers.go b/internal/server/automation_handlers.go index 80d7e5a..8bb75aa 100644 --- a/internal/server/automation_handlers.go +++ b/internal/server/automation_handlers.go @@ -1,7 +1,6 @@ package server import ( - "encoding/json" "errors" "net/http" "strconv" @@ -9,9 +8,8 @@ import ( "github.com/go-chi/chi/v5" + automationapp "xianyu-go/internal/application/automation" "xianyu-go/internal/auth" - "xianyu-go/internal/automation" - "xianyu-go/internal/db" ) // mountAutomation 负责mount自动化相关处理。 @@ -30,12 +28,45 @@ func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) { // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) // runs、tasks、err 保存runs、tasks、err,供当前处理流程使用 - runs, tasks, err := s.Store.Automation.ListIssues(r.Context(), sess.UserID) + runs, tasks, err := s.automationIssuesApplication().ListIssues(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询自动化异常任务失败") return } - writeJSON(w, http.StatusOK, automationIssuesResponse{Runs: runs, PendingTasks: tasks}) + writeJSON(w, http.StatusOK, automationIssuesResponse{ + Runs: automationRunIssueDTOs(runs), + PendingTasks: deferredAutomationIssueDTOs(tasks), + }) +} + +// automationRunIssueDTOs 将应用层自动化运行摘要转换为 HTTP DTO,避免响应直接暴露应用内部模型。 +func automationRunIssueDTOs(issues []automationapp.RunIssue) []automationRunIssueDTO { + // result 是待写入响应的自动化运行 DTO 列表。 + result := make([]automationRunIssueDTO, 0, len(issues)) + // issue 是当前待转换的应用层运行异常摘要。 + for _, issue := range issues { + result = append(result, automationRunIssueDTO{ + ID: issue.ID, CookieID: issue.CookieID, OrderID: issue.OrderID, + TriggerType: issue.TriggerType, ErrorMessage: issue.ErrorMessage, + IssueKind: issue.IssueKind, AllowedResolutions: issue.AllowedResolutions, + ActionCursor: issue.ActionCursor, SentCount: issue.SentCount, UpdatedAt: issue.UpdatedAt, + }) + } + return result +} + +// deferredAutomationIssueDTOs 将应用层延期任务摘要转换为 HTTP DTO。 +func deferredAutomationIssueDTOs(issues []automationapp.DeferredIssue) []deferredAutomationIssueDTO { + // result 是待写入响应的延期任务 DTO 列表。 + result := make([]deferredAutomationIssueDTO, 0, len(issues)) + // issue 是当前待转换的应用层延期异常摘要。 + for _, issue := range issues { + result = append(result, deferredAutomationIssueDTO{ + ID: issue.ID, CookieID: issue.CookieID, TriggerType: issue.TriggerType, + ErrorMessage: issue.ErrorMessage, AttemptCount: issue.AttemptCount, UpdatedAt: issue.UpdatedAt, + }) + } + return result } // resolveAutomationRun 负责resolve自动化运行相关处理。 @@ -58,8 +89,8 @@ func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) { // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) if // err 保存err,供当前处理流程使用 - err := s.Store.Automation.ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil { - if errors.Is(err, db.ErrNotFound) { + err := s.automationIssuesApplication().ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil { + if errors.Is(err, automationapp.ErrNotFound) { writeErr(w, http.StatusNotFound, "异常运行不存在或已处理") return } @@ -82,402 +113,20 @@ func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Re Resolution string `json:"resolution"` } if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil || (req.Resolution != "retry" && req.Resolution != "dismiss") { + err := decodeJSON(r, &req); err != nil { writeErr(w, http.StatusBadRequest, "处理方式必须是 retry 或 dismiss") return } // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) if // err 保存err,供当前处理流程使用 - err := s.Store.Automation.ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution == "retry"); err != nil { + err := s.automationIssuesApplication().ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution); err != nil { + if errors.Is(err, automationapp.ErrInvalidDeferredResolution) { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } writeErr(w, http.StatusNotFound, "异常任务不存在或已处理") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } - -// automationActionRequest 保存自动化动作请求,供当前处理流程使用 -type automationActionRequest struct { - ActionType string `json:"action_type"` - CardID int64 `json:"card_id"` - DeliveryCount int `json:"delivery_count"` - MessageTemplate string `json:"message_template"` - DelaySeconds int `json:"delay_seconds"` - ConfigJSON string `json:"config_json"` - Enabled *bool `json:"enabled"` - SortOrder int `json:"sort_order"` -} - -// automationRuleRequest 保存自动化规则请求,供当前处理流程使用 -type automationRuleRequest struct { - CookieID string `json:"cookie_id"` - ItemID string `json:"item_id"` - Name string `json:"name"` - TriggerType string `json:"trigger_type"` - Enabled bool `json:"enabled"` - Priority int `json:"priority"` - ConfigJSON string `json:"config_json"` - Actions []automationActionRequest `json:"actions"` -} - -// listAutomationRules 负责list自动化规则列表相关处理。 -func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - // query 保存查询,供当前处理流程使用 - query := r.URL.Query() - // paginated 保存paginated,供当前处理流程使用 - _, paginated := query["page"] - if !paginated { - // rules、err 保存rules、err,供当前处理流程使用 - rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID) - if err != nil { - writeErr(w, http.StatusInternalServerError, "查询自动化规则失败") - return - } - writeJSON(w, http.StatusOK, automationRulesJSON(rules)) - return - } - - // page 保存页码,供当前处理流程使用 - page := atoiDefault(query.Get("page"), 1) - // pageSize 保存每页数量,供当前处理流程使用 - pageSize := atoiDefault(query.Get("page_size"), 10) - if page < 1 { - page = 1 - } - if pageSize < 1 { - pageSize = 10 - } - if pageSize > 100 { - pageSize = 100 - } - // cookieID 保存登录凭证ID,供当前处理流程使用 - cookieID := strings.TrimSpace(query.Get("cookie_id")) - if cookieID != "" { - if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) { - writeErr(w, http.StatusForbidden, "无权限操作该账号") - return - } - } - // triggerType 保存trigger类型,供当前处理流程使用 - triggerType := strings.TrimSpace(query.Get("trigger_type")) - if triggerType != "" { - switch triggerType { - case automation.TriggerOrderPaid, automation.TriggerBuyerReviewed, automation.TriggerReviewMissingTimeout: - default: - writeErr(w, http.StatusBadRequest, "不支持的触发类型") - return - } - } - // enabled 保存启用状态,供当前处理流程使用 - var enabled *bool - if // rawEnabled 保存原始启用状态,供当前处理流程使用 - rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" { - // value、parseErr 保存value、parseErr,供当前处理流程使用 - value, parseErr := strconv.ParseBool(rawEnabled) - if parseErr != nil { - writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false") - return - } - enabled = &value - } - - // rules、total、err 保存rules、total、err,供当前处理流程使用 - rules, total, err := s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{ - UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled, - Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize, - }) - if err != nil { - writeErr(w, http.StatusInternalServerError, "查询自动化规则失败") - return - } - // filter 保存filter,供当前处理流程使用 - filter := db.AutomationRuleListFilter{ - UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled, - Search: query.Get("search"), - } - // triggerCounts、err 保存triggerCounts、err,供当前处理流程使用 - triggerCounts, err := s.Store.Automation.CountByTriggerForUser(r.Context(), filter) - if err != nil { - writeErr(w, http.StatusInternalServerError, "统计自动化规则失败") - return - } - // totalPages 保存总数Pages,供当前处理流程使用 - totalPages := (total + pageSize - 1) / pageSize - if totalPages > 0 && page > totalPages { - page = totalPages - rules, _, err = s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{ - UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled, - Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize, - }) - if err != nil { - writeErr(w, http.StatusInternalServerError, "查询自动化规则失败") - return - } - } - writeJSON(w, http.StatusOK, automationRulePageResponse{ - Success: true, Data: automationRulesJSON(rules), Total: total, Page: page, - PageSize: pageSize, TotalPages: totalPages, TriggerCounts: triggerCounts, - }) -} - -// automationRulesJSON 负责自动化规则列表JSON相关处理。 -func automationRulesJSON(rules []db.AutomationRule) []automationRuleResponse { - // out 保存out,供当前处理流程使用 - out := make([]automationRuleResponse, 0, len(rules)) - // rule 表示当前遍历过程中的规则 - for _, rule := range rules { - // actions 保存动作列表,供当前处理流程使用 - actions := make([]automationActionResponse, 0, len(rule.Actions)) - // action 表示当前遍历过程中的动作 - for _, action := range rule.Actions { - actions = append(actions, automationActionResponse{ - ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, CardName: action.CardName, - DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate, - DelaySeconds: action.DelaySeconds, ConfigJSON: action.ConfigJSON, Enabled: action.Enabled, - SortOrder: action.SortOrder, - }) - } - out = append(out, automationRuleResponse{ - ID: rule.ID, CookieID: rule.CookieID, ItemID: rule.ItemID, ItemTitle: rule.ItemTitle, - Name: rule.Name, TriggerType: rule.TriggerType, Enabled: rule.Enabled, Priority: rule.Priority, - ConfigJSON: rule.ConfigJSON, Actions: actions, CreatedAt: rule.CreatedAt, UpdatedAt: rule.UpdatedAt, - }) - } - return out -} - -// createAutomationRule 创建自动化规则并返回数值主键 DTO。 -func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - // req 保存req,供当前处理流程使用 - var req automationRuleRequest - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil { - writeErr(w, http.StatusBadRequest, "请求格式错误") - return - } - // in、err 保存in、err,供当前处理流程使用 - in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req) - if err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - // id、err 保存id、err,供当前处理流程使用 - id, err := s.Store.Automation.Create(r.Context(), in) - if err != nil { - writeErr(w, http.StatusInternalServerError, "创建自动化规则失败") - return - } - writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id}) -} - -// updateAutomationRule 负责update自动化规则相关处理。 -func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) { - // ruleID、err 保存规则ID、err,供当前处理流程使用 - ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64) - if err != nil { - writeErr(w, http.StatusBadRequest, "无效规则ID") - return - } - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - // req 保存req,供当前处理流程使用 - var req automationRuleRequest - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil { - writeErr(w, http.StatusBadRequest, "请求格式错误") - return - } - // in、err 保存in、err,供当前处理流程使用 - in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req) - if err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - if // err 保存err,供当前处理流程使用 - err := s.Store.Automation.Update(r.Context(), sess.UserID, ruleID, in); err != nil { - if err == db.ErrNotFound { - writeErr(w, http.StatusNotFound, "自动化规则不存在") - return - } - writeErr(w, http.StatusInternalServerError, "更新自动化规则失败") - return - } - writeJSON(w, http.StatusOK, operationResponse{Success: true}) -} - -// deleteAutomationRule 负责delete自动化规则相关处理。 -func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) { - // ruleID、err 保存规则ID、err,供当前处理流程使用 - ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64) - if err != nil { - writeErr(w, http.StatusBadRequest, "无效规则ID") - return - } - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - if // err 保存err,供当前处理流程使用 - err := s.Store.Automation.Delete(r.Context(), sess.UserID, ruleID); err != nil { - if err == db.ErrNotFound { - writeErr(w, http.StatusNotFound, "自动化规则不存在") - return - } - if errors.Is(err, db.ErrAutomationRunActive) { - writeErr(w, http.StatusConflict, "规则仍有运行中或待人工处理的任务,处理完成后才能删除") - return - } - writeErr(w, http.StatusInternalServerError, "删除自动化规则失败") - return - } - writeJSON(w, http.StatusOK, operationResponse{Success: true}) -} - -// normalizeAutomationRuleRequest 负责normalize自动化规则请求相关处理。 -func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, req automationRuleRequest) (db.AutomationRuleInput, error) { - req.CookieID = strings.TrimSpace(req.CookieID) - req.ItemID = strings.TrimSpace(req.ItemID) - req.Name = strings.TrimSpace(req.Name) - req.TriggerType = strings.TrimSpace(req.TriggerType) - switch req.TriggerType { - case automation.TriggerOrderPaid, automation.TriggerBuyerReviewed, automation.TriggerReviewMissingTimeout: - default: - return db.AutomationRuleInput{}, errStr("不支持的触发类型") - } - if req.CookieID == "" || !s.cookieOwnedByUser(r.Context(), userID, req.CookieID) { - return db.AutomationRuleInput{}, errStr("账号不存在或不属于当前用户") - } - if req.ItemID != "" && !s.itemOwnedByUser(r, userID, req.CookieID, req.ItemID) { - return db.AutomationRuleInput{}, errStr("商品不属于当前用户") - } - if req.Priority <= 0 { - req.Priority = 100 - } - // config 保存配置,供当前处理流程使用 - config := req.ConfigJSON - if config == "" { - config = "{}" - } - if !isJSONObject(config) { - return db.AutomationRuleInput{}, errStr("规则配置必须是 JSON 对象") - } - if len(req.Actions) == 0 { - return db.AutomationRuleInput{}, errStr("至少需要一个自动化动作") - } - if req.Name == "" { - req.Name = defaultAutomationRuleName(req.TriggerType, req.ItemID) - } - // actions 保存动作列表,供当前处理流程使用 - actions := make([]db.AutomationActionInput, 0, len(req.Actions)) - // hasSendCard、hasSendText、hasConfirmShipment 保存hasSendCard、hasSendText、hasConfirmShipment,供当前处理流程使用 - hasSendCard, hasSendText, hasConfirmShipment := false, false, false - // i、act 表示当前遍历过程中的i、act - for i, act := range req.Actions { - // enabled 保存启用状态,供当前处理流程使用 - enabled := true - if act.Enabled != nil { - enabled = *act.Enabled - } - act.ActionType = strings.TrimSpace(act.ActionType) - switch act.ActionType { - case automation.ActionConfirmShipment: - hasConfirmShipment = hasConfirmShipment || enabled - case automation.ActionSendCard: - if act.CardID <= 0 { - return db.AutomationRuleInput{}, errStr("发送卡密动作必须选择卡密组") - } - // card、cardErr 保存card、cardErr,供当前处理流程使用 - card, cardErr := s.Store.Cards.Get(r.Context(), act.CardID) - if cardErr != nil || card.UserID != userID { - return db.AutomationRuleInput{}, errStr("卡密组不存在或不属于当前用户") - } - if card.Type == "api" { - return db.AutomationRuleInput{}, errStr("API 卡密暂不支持自动发货,请选择文本、批量数据或图片卡密") - } - hasSendCard = hasSendCard || enabled - case automation.ActionSendText: - if strings.TrimSpace(act.MessageTemplate) == "" { - return db.AutomationRuleInput{}, errStr("发送文本动作必须填写文案") - } - hasSendText = hasSendText || enabled - default: - return db.AutomationRuleInput{}, errStr("不支持的动作类型") - } - if act.DeliveryCount <= 0 { - act.DeliveryCount = 1 - } - if act.DelaySeconds < 0 || act.DelaySeconds > 3600 { - return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 3600 秒之间") - } - if act.ConfigJSON == "" { - act.ConfigJSON = "{}" - } - if !isJSONObject(act.ConfigJSON) { - return db.AutomationRuleInput{}, errStr("动作配置必须是 JSON 对象") - } - actions = append(actions, db.AutomationActionInput{ - ActionType: act.ActionType, CardID: act.CardID, DeliveryCount: act.DeliveryCount, - MessageTemplate: act.MessageTemplate, DelaySeconds: act.DelaySeconds, ConfigJSON: act.ConfigJSON, - Enabled: enabled, SortOrder: firstNonZero(act.SortOrder, i+1), - }) - } - switch req.TriggerType { - case automation.TriggerOrderPaid: - if !hasSendCard { - return db.AutomationRuleInput{}, errStr("付款后自动发货至少需要一个已启用的发送卡密动作") - } - case automation.TriggerBuyerReviewed: - if hasConfirmShipment { - return db.AutomationRuleInput{}, errStr("评价后规则不能包含确认发货动作") - } - if !hasSendCard && !hasSendText { - return db.AutomationRuleInput{}, errStr("评价后规则至少需要一个已启用的发送动作") - } - case automation.TriggerReviewMissingTimeout: - if hasConfirmShipment || hasSendCard { - return db.AutomationRuleInput{}, errStr("求评价规则只能发送文本") - } - if !hasSendText { - return db.AutomationRuleInput{}, errStr("求评价规则至少需要一个已启用的文本动作") - } - } - return db.AutomationRuleInput{ - UserID: userID, CookieID: req.CookieID, ItemID: req.ItemID, Name: req.Name, - TriggerType: req.TriggerType, Enabled: req.Enabled, Priority: req.Priority, - ConfigJSON: config, Actions: actions, - }, nil -} - -// defaultAutomationRuleName 负责default自动化规则名称相关处理。 -func defaultAutomationRuleName(triggerType, itemID string) string { - // name 保存名称,供当前处理流程使用 - name := map[string]string{ - automation.TriggerOrderPaid: "付款后自动发货", - automation.TriggerBuyerReviewed: "评价后发送赠品", - automation.TriggerReviewMissingTimeout: "超时未评价求评价", - }[triggerType] - if name == "" { - name = "自动化规则" - } - if strings.TrimSpace(itemID) != "" { - return name + " - " + strings.TrimSpace(itemID) - } - return name -} - -// isJSONObject 负责isJSONObject相关处理。 -func isJSONObject(s string) bool { - // m 保存m,供当前处理流程使用 - var m map[string]any - return json.Unmarshal([]byte(s), &m) == nil -} - -// firstNonZero 负责firstNonZero相关处理。 -func firstNonZero(v, fallback int) int { - if v != 0 { - return v - } - return fallback -} diff --git a/internal/server/automation_issue_port_test.go b/internal/server/automation_issue_port_test.go new file mode 100644 index 0000000..79cd4f5 --- /dev/null +++ b/internal/server/automation_issue_port_test.go @@ -0,0 +1,49 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestAutomationIssuePortHTTPErrorBranches 验证 issue 应用 Port 接入后的 SQLite HTTP 错误分支。 +func TestAutomationIssuePortHTTPErrorBranches(t *testing.T) { + // srv、cleanup 保存真实 SQLite 测试服务及清理函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 保存挂载认证和自动化 issue 路由的 HTTP 处理器。 + handler := srv.Router() + // sessionCookie 保存测试管理员的认证会话。 + sessionCookie := loginHelper(t, handler) + + // invalidResolutionRequest 保存不支持处理动作的请求。 + invalidResolutionRequest := httptest.NewRequest(http.MethodPost, "/automation-pending-tasks/1/resolve", strings.NewReader(`{"resolution":"continue"}`)) + invalidResolutionRequest.AddCookie(sessionCookie) + // invalidResolutionResponse 捕获非法处理动作的响应。 + invalidResolutionResponse := httptest.NewRecorder() + handler.ServeHTTP(invalidResolutionResponse, invalidResolutionRequest) + if invalidResolutionResponse.Code != http.StatusBadRequest || !strings.Contains(invalidResolutionResponse.Body.String(), "retry") { + t.Fatalf("非法延迟任务处理动作响应异常: status=%d body=%s", invalidResolutionResponse.Code, invalidResolutionResponse.Body.String()) + } + + // missingRunRequest 保存不存在自动化运行的处理请求。 + missingRunRequest := httptest.NewRequest(http.MethodPost, "/automation-runs/999999/resolve", strings.NewReader(`{"resolution":"cancel"}`)) + missingRunRequest.AddCookie(sessionCookie) + // missingRunResponse 捕获不存在运行的响应。 + missingRunResponse := httptest.NewRecorder() + handler.ServeHTTP(missingRunResponse, missingRunRequest) + if missingRunResponse.Code != http.StatusNotFound { + t.Fatalf("不存在自动化运行响应异常: status=%d body=%s", missingRunResponse.Code, missingRunResponse.Body.String()) + } + + // listRequest 保存 SQLite issue 列表查询请求。 + listRequest := httptest.NewRequest(http.MethodGet, "/automation-issues", nil) + listRequest.AddCookie(sessionCookie) + // listResponse 捕获 SQLite issue 列表响应。 + listResponse := httptest.NewRecorder() + handler.ServeHTTP(listResponse, listRequest) + if listResponse.Code != http.StatusOK || !strings.Contains(listResponse.Body.String(), `"runs"`) || !strings.Contains(listResponse.Body.String(), `"pending_tasks"`) { + t.Fatalf("自动化 issue 列表响应异常: status=%d body=%s", listResponse.Code, listResponse.Body.String()) + } +} diff --git a/internal/server/automation_rule_handlers.go b/internal/server/automation_rule_handlers.go new file mode 100644 index 0000000..7cc4c78 --- /dev/null +++ b/internal/server/automation_rule_handlers.go @@ -0,0 +1,295 @@ +package server + +import ( + "encoding/json" + "errors" + "net/http" + "strconv" + "strings" + + "github.com/go-chi/chi/v5" + + automationapp "xianyu-go/internal/application/automation" + "xianyu-go/internal/auth" +) + +// automationActionRequest 保存自动化动作请求,供当前处理流程使用 +type automationActionRequest struct { + ActionType string `json:"action_type"` + CardID int64 `json:"card_id"` + DeliveryCount int `json:"delivery_count"` + MessageTemplate string `json:"message_template"` + DelaySeconds int `json:"delay_seconds"` + ConfigJSON string `json:"config_json"` + Enabled *bool `json:"enabled"` + SortOrder int `json:"sort_order"` +} + +// automationRuleRequest 保存自动化规则请求,供当前处理流程使用 +type automationRuleRequest struct { + CookieID string `json:"cookie_id"` + ItemID string `json:"item_id"` + Name string `json:"name"` + TriggerType string `json:"trigger_type"` + Enabled bool `json:"enabled"` + Priority int `json:"priority"` + ConfigJSON string `json:"config_json"` + Actions []automationActionRequest `json:"actions"` +} + +// listAutomationRules 负责list自动化规则列表相关处理。 +func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) { + // sess 保存sess,供当前处理流程使用 + sess := auth.SessionFromContext(r.Context()) + // query 保存查询,供当前处理流程使用 + query := r.URL.Query() + // paginated 保存paginated,供当前处理流程使用 + _, paginated := query["page"] + if !paginated { + // rules、err 保存rules、err,供当前处理流程使用 + rules, err := s.automationRulesApplication().ListForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询自动化规则失败") + return + } + writeJSON(w, http.StatusOK, automationRulesJSON(rules)) + return + } + + // page 保存页码,供当前处理流程使用 + page := atoiDefault(query.Get("page"), 1) + // pageSize 保存每页数量,供当前处理流程使用 + pageSize := atoiDefault(query.Get("page_size"), 10) + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 10 + } + if pageSize > 100 { + pageSize = 100 + } + // cookieID 保存登录凭证ID,供当前处理流程使用 + cookieID := strings.TrimSpace(query.Get("cookie_id")) + if cookieID != "" { + if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) { + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return + } + } + // triggerType 保存trigger类型,供当前处理流程使用 + triggerType := strings.TrimSpace(query.Get("trigger_type")) + if triggerType != "" { + switch triggerType { + case automationapp.TriggerOrderPaid, automationapp.TriggerBuyerReviewed, automationapp.TriggerReviewMissingTimeout: + default: + writeErr(w, http.StatusBadRequest, "不支持的触发类型") + return + } + } + // enabled 保存启用状态,供当前处理流程使用 + var enabled *bool + if // rawEnabled 保存原始启用状态,供当前处理流程使用 + rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" { + // value、parseErr 保存value、parseErr,供当前处理流程使用 + value, parseErr := strconv.ParseBool(rawEnabled) + if parseErr != nil { + writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false") + return + } + enabled = &value + } + + // rules、total、err 保存rules、total、err,供当前处理流程使用 + rules, total, err := s.automationRulesApplication().ListPageForUser(r.Context(), automationapp.RuleFilter{ + UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled, + Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize, + }) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询自动化规则失败") + return + } + // filter 保存filter,供当前处理流程使用 + filter := automationapp.RuleFilter{ + UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled, + Search: query.Get("search"), + } + // triggerCounts、err 保存triggerCounts、err,供当前处理流程使用 + triggerCounts, err := s.automationRulesApplication().CountByTriggerForUser(r.Context(), filter) + if err != nil { + writeErr(w, http.StatusInternalServerError, "统计自动化规则失败") + return + } + // totalPages 保存总数Pages,供当前处理流程使用 + totalPages := (total + pageSize - 1) / pageSize + if totalPages > 0 && page > totalPages { + page = totalPages + rules, _, err = s.automationRulesApplication().ListPageForUser(r.Context(), automationapp.RuleFilter{ + UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled, + Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize, + }) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询自动化规则失败") + return + } + } + writeJSON(w, http.StatusOK, automationRulePageResponse{ + Success: true, Data: automationRulesJSON(rules), Total: total, Page: page, + PageSize: pageSize, TotalPages: totalPages, TriggerCounts: triggerCounts, + }) +} + +// automationRulesJSON 负责自动化规则列表JSON相关处理。 +func automationRulesJSON(rules []automationapp.Rule) []automationRuleResponse { + // out 保存out,供当前处理流程使用 + out := make([]automationRuleResponse, 0, len(rules)) + // rule 表示当前遍历过程中的规则 + for _, rule := range rules { + // actions 保存动作列表,供当前处理流程使用 + actions := make([]automationActionResponse, 0, len(rule.Actions)) + // action 表示当前遍历过程中的动作 + for _, action := range rule.Actions { + actions = append(actions, automationActionResponse{ + ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, CardName: action.CardName, + DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate, + DelaySeconds: action.DelaySeconds, ConfigJSON: action.ConfigJSON, Enabled: action.Enabled, + SortOrder: action.SortOrder, + }) + } + out = append(out, automationRuleResponse{ + ID: rule.ID, CookieID: rule.CookieID, ItemID: rule.ItemID, ItemTitle: rule.ItemTitle, + Name: rule.Name, TriggerType: rule.TriggerType, Enabled: rule.Enabled, Priority: rule.Priority, + ConfigJSON: rule.ConfigJSON, Actions: actions, CreatedAt: rule.CreatedAt, UpdatedAt: rule.UpdatedAt, + }) + } + return out +} + +// createAutomationRule 创建自动化规则并返回数值主键 DTO。 +func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) { + // sess 保存sess,供当前处理流程使用 + sess := auth.SessionFromContext(r.Context()) + // req 保存req,供当前处理流程使用 + var req automationRuleRequest + if // err 保存err,供当前处理流程使用 + err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + // in、err 保存in、err,供当前处理流程使用 + in, err := s.automationRulesApplication().Normalize(r.Context(), sess.UserID, automationRuleDraft(req)) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + // id、err 保存id、err,供当前处理流程使用 + id, err := s.automationRulesApplication().Create(r.Context(), in) + if err != nil { + writeErr(w, http.StatusInternalServerError, "创建自动化规则失败") + return + } + writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id}) +} + +// updateAutomationRule 负责update自动化规则相关处理。 +func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) { + // ruleID、err 保存规则ID、err,供当前处理流程使用 + ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效规则ID") + return + } + // sess 保存sess,供当前处理流程使用 + sess := auth.SessionFromContext(r.Context()) + // req 保存req,供当前处理流程使用 + var req automationRuleRequest + if // err 保存err,供当前处理流程使用 + err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + // in、err 保存in、err,供当前处理流程使用 + in, err := s.automationRulesApplication().Normalize(r.Context(), sess.UserID, automationRuleDraft(req)) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if // err 保存err,供当前处理流程使用 + err := s.automationRulesApplication().Update(r.Context(), sess.UserID, ruleID, in); err != nil { + if errors.Is(err, automationapp.ErrRuleNotFound) { + writeErr(w, http.StatusNotFound, "自动化规则不存在") + return + } + writeErr(w, http.StatusInternalServerError, "更新自动化规则失败") + return + } + writeJSON(w, http.StatusOK, operationResponse{Success: true}) +} + +// deleteAutomationRule 负责delete自动化规则相关处理。 +func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) { + // ruleID、err 保存规则ID、err,供当前处理流程使用 + ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效规则ID") + return + } + // sess 保存sess,供当前处理流程使用 + sess := auth.SessionFromContext(r.Context()) + if // err 保存err,供当前处理流程使用 + err := s.automationRulesApplication().Delete(r.Context(), sess.UserID, ruleID); err != nil { + if errors.Is(err, automationapp.ErrRuleNotFound) { + writeErr(w, http.StatusNotFound, "自动化规则不存在") + return + } + if errors.Is(err, automationapp.ErrRuleActive) { + writeErr(w, http.StatusConflict, "规则仍有运行中或待人工处理的任务,处理完成后才能删除") + return + } + writeErr(w, http.StatusInternalServerError, "删除自动化规则失败") + return + } + writeJSON(w, http.StatusOK, operationResponse{Success: true}) +} + +// automationRuleDraft 将 HTTP 请求转换为应用层规则草稿。 +func automationRuleDraft(req automationRuleRequest) automationapp.RuleDraft { + // actions 保存转换后的应用层动作草稿,不携带数据库模型。 + actions := make([]automationapp.ActionDraft, 0, len(req.Actions)) + // action 是当前待转换的 HTTP 动作请求。 + for _, action := range req.Actions { + actions = append(actions, automationapp.ActionDraft{ActionType: action.ActionType, CardID: action.CardID, + DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate, DelaySeconds: action.DelaySeconds, + ConfigJSON: action.ConfigJSON, Enabled: action.Enabled, SortOrder: action.SortOrder}) + } + return automationapp.RuleDraft{CookieID: req.CookieID, ItemID: req.ItemID, Name: req.Name, TriggerType: req.TriggerType, + Enabled: req.Enabled, Priority: req.Priority, ConfigJSON: req.ConfigJSON, Actions: actions} +} + +// defaultAutomationRuleName 保留旧测试和兼容调用所需的默认名称函数。 +func defaultAutomationRuleName(triggerType, itemID string) string { + // name 保存按触发类型选择的默认规则名称,必要时附加商品标识。 + name := map[string]string{automationapp.TriggerOrderPaid: "付款后自动发货", automationapp.TriggerBuyerReviewed: "评价后发送赠品", automationapp.TriggerReviewMissingTimeout: "超时未评价求评价"}[triggerType] + if name == "" { + name = "自动化规则" + } + if strings.TrimSpace(itemID) != "" { + return name + " - " + strings.TrimSpace(itemID) + } + return name +} + +// isJSONObject 保留规则配置测试需要的 JSON 对象判断。 +func isJSONObject(raw string) bool { + // value 保存 JSON 对象解析结果,仅用于判断配置顶层类型。 + var value map[string]any + return json.Unmarshal([]byte(raw), &value) == nil +} + +// firstNonZero 保留旧兼容调用的非零回退行为。 +func firstNonZero(value, fallback int) int { + if value != 0 { + return value + } + return fallback +} diff --git a/internal/server/card_application_handlers_test.go b/internal/server/card_application_handlers_test.go new file mode 100644 index 0000000..81c36c9 --- /dev/null +++ b/internal/server/card_application_handlers_test.go @@ -0,0 +1,135 @@ +package server + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + cardsapp "xianyu-go/internal/application/cards" + "xianyu-go/internal/db" +) + +// TestCardApplicationEndpointsEnforceOwnership 验证详情、更新和删除均由应用服务执行用户隔离。 +func TestCardApplicationEndpointsEnforceOwnership(t *testing.T) { + // server、store、cleanup 保存测试 HTTP 服务、SQLite 存储和资源释放函数。 + server, store, cleanup := newTestServer(t) + defer cleanup() + // ctx 是创建跨用户数据夹具时使用的非取消上下文。 + ctx := context.Background() + // created、createUserErr 保存卡券所有者创建结果及数据库错误。 + created, createUserErr := store.Users.Create(ctx, "card-owner", "card-owner@example.com", "pw") + if createUserErr != nil || !created { + t.Fatalf("创建卡券所有者失败 created=%v err=%v", created, createUserErr) + } + // owner、ownerErr 保存新用户详情及查询错误。 + owner, ownerErr := store.Users.GetByUsername(ctx, "card-owner") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // cardID、createCardErr 保存属于新用户的卡券标识及创建错误。 + cardID, createCardErr := store.Cards.Create(ctx, &db.CardFull{Name: "他人卡券", Type: "text", TextContent: "SECRET", Enabled: true, UserID: owner.ID}) + if createCardErr != nil { + t.Fatal(createCardErr) + } + // handler 是包含认证中间件和卡券路由的测试处理器。 + handler := server.Router() + // adminCookie 是不拥有测试卡券的管理员会话 Cookie。 + adminCookie := loginHelper(t, handler) + // testCase 是当前待验证的跨用户 HTTP 操作。 + for _, testCase := range []struct { + // name 是测试子场景名称。 + name string + // method 是请求使用的 HTTP 方法。 + method string + // body 是更新操作使用的请求体;其他操作为空。 + body string + }{ + {name: "get", method: http.MethodGet}, + {name: "update", method: http.MethodPut, body: `{"name":"篡改","type":"text","text_content":"X","enabled":true}`}, + {name: "delete", method: http.MethodDelete}, + } { + t.Run(testCase.name, func(t *testing.T) { + // request 是当前跨用户访问请求。 + request := httptest.NewRequest(testCase.method, "/cards/"+strconv.FormatInt(cardID, 10), strings.NewReader(testCase.body)) + request.AddCookie(adminCookie) + // response 记录当前请求的 HTTP 状态和统一错误响应。 + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("跨用户操作应返回 403,status=%d body=%s", response.Code, response.Body.String()) + } + }) + } + // remaining、remainingErr 保存跨用户删除尝试后的数据库卡券记录及错误。 + remaining, remainingErr := store.Cards.Get(ctx, cardID) + if remainingErr != nil || remaining.UserID != owner.ID || remaining.Name != "他人卡券" { + t.Fatalf("跨用户操作不得修改或删除卡券,card=%+v err=%v", remaining, remainingErr) + } +} + +// TestCardApplicationEndpointsTreatNonPositiveIDAsMissing 验证数字格式合法但非正数的标识保持 404 兼容语义。 +func TestCardApplicationEndpointsTreatNonPositiveIDAsMissing(t *testing.T) { + // server、cleanup 保存测试 HTTP 服务和资源释放函数。 + server, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是包含认证中间件和卡券路由的测试处理器。 + handler := server.Router() + // sessionCookie 是管理员登录后的认证 Cookie。 + sessionCookie := loginHelper(t, handler) + // testCase 是当前待验证的卡券操作和请求体。 + for _, testCase := range []struct { + // name 是测试子场景名称。 + name string + // method 是请求使用的 HTTP 方法。 + method string + // body 是更新操作使用的合法请求体。 + body string + }{ + {name: "get", method: http.MethodGet}, + {name: "update", method: http.MethodPut, body: `{"name":"不存在","type":"text","text_content":"X","enabled":true}`}, + {name: "delete", method: http.MethodDelete}, + } { + t.Run(testCase.name, func(t *testing.T) { + // request 是使用零值卡券标识的认证请求。 + request := httptest.NewRequest(testCase.method, "/cards/0", strings.NewReader(testCase.body)) + request.AddCookie(sessionCookie) + // response 记录资源缺失兼容响应。 + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusNotFound { + t.Fatalf("非正数卡券标识应返回 404,status=%d body=%s", response.Code, response.Body.String()) + } + }) + } +} + +// TestWriteCardReadErrorClassification 验证读取错误分别映射为 404、403 和 500。 +func TestWriteCardReadErrorClassification(t *testing.T) { + // testCase 是当前应用错误与期望 HTTP 状态的映射。 + for _, testCase := range []struct { + // name 是错误分类子场景名称。 + name string + // err 是应用服务返回给 HTTP 边界的错误。 + err error + // wantStatus 是期望写入的 HTTP 状态码。 + wantStatus int + }{ + {name: "not-found", err: cardsapp.ErrNotFound, wantStatus: http.StatusNotFound}, + {name: "invalid-numeric-id", err: cardsapp.ErrInvalidCardID, wantStatus: http.StatusNotFound}, + {name: "forbidden", err: cardsapp.ErrForbidden, wantStatus: http.StatusForbidden}, + {name: "infrastructure", err: errors.New("database unavailable"), wantStatus: http.StatusInternalServerError}, + } { + t.Run(testCase.name, func(t *testing.T) { + // response 记录错误映射函数写入的状态和统一响应体。 + response := httptest.NewRecorder() + writeCardReadError(response, testCase.err) + if response.Code != testCase.wantStatus { + t.Fatalf("错误状态不匹配 got=%d want=%d body=%s", response.Code, testCase.wantStatus, response.Body.String()) + } + }) + } +} diff --git a/internal/server/card_batch_handlers.go b/internal/server/card_batch_handlers.go index 5e6f7ad..006fdc0 100644 --- a/internal/server/card_batch_handlers.go +++ b/internal/server/card_batch_handlers.go @@ -1,6 +1,7 @@ package server import ( + "errors" "fmt" "net/http" "strconv" @@ -8,8 +9,8 @@ import ( "github.com/go-chi/chi/v5" + cardsapp "xianyu-go/internal/application/cards" "xianyu-go/internal/auth" - "xianyu-go/internal/db" ) // maxCardBatchRows 保存max卡密批次Rows,供当前处理流程使用 @@ -31,8 +32,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) { sess := auth.SessionFromContext(r.Context()) // 表格最大 5 MiB(卡密组定义都很小)。 r.Body = http.MaxBytesReader(w, r.Body, maxCardBatchUploadBytes) - if // err 保存err,供当前处理流程使用 - err := r.ParseMultipartForm(maxCardBatchUploadBytes); err != nil { + // err 表示解析 multipart 表单时遇到的格式或大小限制错误。 + if err := r.ParseMultipartForm(maxCardBatchUploadBytes); err != nil { writeErr(w, http.StatusBadRequest, "解析上传文件失败") return } @@ -114,8 +115,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) { continue } - // cf 保存cf,供当前处理流程使用 - cf := &db.CardFull{ + // draft 保存当前表格行转换出的应用卡券草稿。 + draft := cardsapp.Draft{ Name: name, Type: cardType, Description: firstImportString(m, "description", "描述"), @@ -124,23 +125,22 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) { IsMultiSpec: parseLooseBool(firstImportString(m, "is_multi_spec", "多规格")), SpecName: firstImportString(m, "spec_name", "规格名"), SpecValue: firstImportString(m, "spec_value", "规格值"), - UserID: sess.UserID, } - if // v 保存v,供当前处理流程使用 - v := firstImportString(m, "enabled", "启用"); v != "" { - cf.Enabled = parseLooseBool(v) + // v 保存表格行提供的可选启用状态文本。 + if v := firstImportString(m, "enabled", "启用"); v != "" { + draft.Enabled = parseLooseBool(v) } switch cardType { case "text": - cf.TextContent = content + draft.TextContent = content case "data": - cf.DataContent = content + draft.DataContent = content case "image": - cf.ImageURL = content + draft.ImageURL = content } - // id、err 保存id、err,供当前处理流程使用 - id, err := s.Store.Cards.Create(r.Context(), cf) + // id、err 保存应用服务创建的卡券标识及逐行错误。 + id, err := s.cardsApplication().Create(r.Context(), sess.UserID, draft) if err != nil { results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "创建失败: " + err.Error()}) failed++ @@ -161,47 +161,42 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) { // appendCardData 往 data 类型卡密组追加卡密号(按行)。 func (s *Server) appendCardData(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 + // sess 保存认证中间件注入的当前用户会话。 sess := auth.SessionFromContext(r.Context()) - // id、err 保存id、err,供当前处理流程使用 - id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) - if err != nil { + // id、parseErr 保存路径中的卡券标识及数字解析错误。 + id, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) + if parseErr != nil { writeErr(w, http.StatusBadRequest, "无效卡券ID") return } - // req 保存req,供当前处理流程使用 - var req struct { - Content string `json:"content"` - } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil { + // req 保存具名 DTO 解码后的追加库存请求。 + var req cardAppendRequest + // decodeErr 表示追加请求 JSON 的解码错误。 + if decodeErr := decodeJSON(r, &req); decodeErr != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // content 保存内容,供当前处理流程使用 + // content 保存去除首尾空白后的待追加卡密内容。 content := strings.TrimSpace(req.Content) if content == "" { writeErr(w, http.StatusBadRequest, "内容为空") return } - // cf、err 保存cf、err,供当前处理流程使用 - cf, err := s.Store.Cards.Get(r.Context(), id) + // added、err 保存应用服务追加的库存行数及业务或持久化错误。 + added, err := s.cardsApplication().AppendData(r.Context(), sess.UserID, id, content) if err != nil { - writeErr(w, http.StatusNotFound, "卡券不存在") - return - } - if cf.UserID != sess.UserID { - writeErr(w, http.StatusForbidden, "无权操作该卡密组") - return - } - if cf.Type != "data" { - writeErr(w, http.StatusBadRequest, "只有 data(批量卡密)类型支持追加卡密") - return - } - // added、err 保存added、err,供当前处理流程使用 - added, err := s.Store.Cards.AppendBatchData(r.Context(), id, content) - if err != nil { - writeErr(w, http.StatusInternalServerError, "追加失败: "+err.Error()) + // validationErr 用于识别可以直接返回客户端的稳定校验提示。 + var validationErr *cardsapp.ValidationError + switch { + case errors.Is(err, cardsapp.ErrNotFound): + writeErr(w, http.StatusNotFound, "卡券不存在") + case errors.Is(err, cardsapp.ErrForbidden): + writeErr(w, http.StatusForbidden, "无权操作该卡密组") + case errors.Is(err, cardsapp.ErrNotDataType), errors.As(err, &validationErr): + writeErr(w, http.StatusBadRequest, err.Error()) + default: + writeErr(w, http.StatusInternalServerError, "追加失败: "+err.Error()) + } return } writeJSON(w, http.StatusOK, cardAppendResponse{Success: true, Added: added}) diff --git a/internal/server/card_handlers.go b/internal/server/card_handlers.go index 0fc8c55..7cc2dcf 100644 --- a/internal/server/card_handlers.go +++ b/internal/server/card_handlers.go @@ -1,17 +1,51 @@ package server import ( + "errors" "net/http" "strconv" - "strings" "github.com/go-chi/chi/v5" + cardsapp "xianyu-go/internal/application/cards" "xianyu-go/internal/auth" - "xianyu-go/internal/db" ) -// mountCardsReal 卡券 CRUD(真实实现)。发货规则已统一到 automation_rules。 +// cardMutationRequest 是卡券创建与更新接口共用的具名请求 DTO。 +type cardMutationRequest struct { + // Name 是用户可见的卡券组名称。 + Name string `json:"name"` + // Type 是 text、data、image 或历史兼容的 api 类型。 + Type string `json:"type"` + // APIConfig 是历史 API 卡券配置文本。 + APIConfig string `json:"api_config"` + // TextContent 是 text 类型自动发货时发送的文本内容。 + TextContent string `json:"text_content"` + // DataContent 是 data 类型尚未消费的逐行卡密库存。 + DataContent string `json:"data_content"` + // ImageURL 是 image 类型自动发货时发送的图片地址。 + ImageURL string `json:"image_url"` + // Description 是用户维护的卡券组说明。 + Description string `json:"description"` + // Enabled 表示保存后是否允许自动化规则使用该卡券组。 + Enabled bool `json:"enabled"` + // DelaySeconds 是自动发货前的延迟秒数。 + DelaySeconds int `json:"delay_seconds"` + // IsMultiSpec 表示卡券组是否只匹配指定商品规格。 + IsMultiSpec bool `json:"is_multi_spec"` + // SpecName 是多规格匹配使用的规格名称。 + SpecName string `json:"spec_name"` + // SpecValue 是多规格匹配使用的规格值。 + SpecValue string `json:"spec_value"` +} + +// cardAppendRequest 是 data 类型卡券追加库存接口的具名请求 DTO。 +type cardAppendRequest struct { + // Content 是待追加的逐行卡密文本,空行由数据库层按既有规则处理。 + Content string `json:"content"` +} + +// mountCardsReal 挂载卡券 CRUD、批量创建和库存追加路由;发货规则由 automation_rules 负责。 func (s *Server) mountCardsReal(r chi.Router) { r.Get("/cards", s.listCards) r.Post("/cards", s.createCard) @@ -23,12 +57,12 @@ func (s *Server) mountCardsReal(r chi.Router) { r.Delete("/cards/{card_id}", s.deleteCard) } -// listCards 负责list卡密列表相关处理。 +// listCards 将认证用户交给应用服务,并把卡券应用模型转换为 HTTP DTO。 func (s *Server) listCards(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - // cards、err 保存cards、err,供当前处理流程使用 - cards, err := s.Store.Cards.AllForUser(r.Context(), sess.UserID) + // session 是认证中间件注入的当前用户会话。 + session := auth.SessionFromContext(r.Context()) + // cards、err 保存应用服务返回的用户卡券列表及查询错误。 + cards, err := s.cardsApplication().List(r.Context(), session.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -36,176 +70,141 @@ func (s *Server) listCards(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, newCardResponses(cards)) } -// getCard 负责get卡密相关处理。 +// getCard 解析路径标识并由应用服务统一校验资源存在性和用户归属。 func (s *Server) getCard(w http.ResponseWriter, r *http.Request) { - // id、err 保存id、err,供当前处理流程使用 - id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) - if err != nil { + // cardID、parseErr 保存路径中的卡券标识及数字解析错误。 + cardID, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) + if parseErr != nil { writeErr(w, http.StatusBadRequest, "无效卡券ID") return } - // cf、ok 保存cf、ok,供当前处理流程使用 - cf, ok := s.requireCardOwner(w, r, id) - if !ok { + // session 是认证中间件注入的当前用户会话。 + session := auth.SessionFromContext(r.Context()) + // card、err 保存应用服务返回的卡券组及所有权或查询错误。 + card, err := s.cardsApplication().Get(r.Context(), session.UserID, cardID) + if err != nil { + writeCardReadError(w, err) return } - writeJSON(w, http.StatusOK, newCardResponse(*cf)) + writeJSON(w, http.StatusOK, newCardResponse(card)) } -// createCard 负责create卡密相关处理。 +// createCard 解码 HTTP 请求,并由应用服务完成输入校验、类型限制和所有者写入。 func (s *Server) createCard(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - // cf、err 保存cf、err,供当前处理流程使用 - cf, err := decodeCard(r) + // draft、decodeErr 保存请求转换后的应用输入及 JSON 解码错误。 + draft, decodeErr := decodeCardDraft(r) + if decodeErr != nil { + writeErr(w, http.StatusBadRequest, decodeErr.Error()) + return + } + // session 是认证中间件注入的当前用户会话。 + session := auth.SessionFromContext(r.Context()) + // cardID、err 保存创建后的卡券标识及业务或持久化错误。 + cardID, err := s.cardsApplication().Create(r.Context(), session.UserID, draft) if err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) + // validationError 用于识别可直接返回客户端的稳定业务校验提示。 + var validationError *cardsapp.ValidationError + switch { + case errors.As(err, &validationError): + writeErr(w, http.StatusBadRequest, validationError.Error()) + case errors.Is(err, cardsapp.ErrUnsupportedAPIType): + writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建") + default: + writeErr(w, http.StatusInternalServerError, "创建失败") + } return } - cf.UserID = sess.UserID - if cf.Type == "api" { - writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建") - return - } - // id、err 保存id、err,供当前处理流程使用 - id, err := s.Store.Cards.Create(r.Context(), cf) - if err != nil { - writeErr(w, http.StatusInternalServerError, "创建失败") - return - } - writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id}) + writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: cardID}) } -// updateCard 负责update卡密相关处理。 +// updateCard 解码路径和请求体,并由应用服务完成输入校验、归属校验及更新。 func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) { - // id、err 保存id、err,供当前处理流程使用 - id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) - if err != nil { + // cardID、parseErr 保存路径中的卡券标识及数字解析错误。 + cardID, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) + if parseErr != nil { writeErr(w, http.StatusBadRequest, "无效卡券ID") return } - // cf、err 保存cf、err,供当前处理流程使用 - cf, err := decodeCard(r) + // draft、decodeErr 保存请求转换后的应用输入及 JSON 解码错误。 + draft, decodeErr := decodeCardDraft(r) + if decodeErr != nil { + writeErr(w, http.StatusBadRequest, decodeErr.Error()) + return + } + // session 是认证中间件注入的当前用户会话。 + session := auth.SessionFromContext(r.Context()) + // err 是应用服务返回的业务校验、所有权或持久化错误。 + err := s.cardsApplication().Update(r.Context(), session.UserID, cardID, draft) if err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - // existing、ok 保存existing、ok,供当前处理流程使用 - existing, ok := s.requireCardOwner(w, r, id) - if !ok { - return - } - if cf.Type == "api" && existing.Type != "api" { - writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能转换为该类型") - return - } - cf.ID = id - cf.UserID = existing.UserID - if // err 保存err,供当前处理流程使用 - err := s.Store.Cards.Update(r.Context(), cf); err != nil { - writeErr(w, http.StatusInternalServerError, "更新失败") + // validationError 用于识别可直接返回客户端的稳定业务校验提示。 + var validationError *cardsapp.ValidationError + switch { + case errors.As(err, &validationError): + writeErr(w, http.StatusBadRequest, validationError.Error()) + case errors.Is(err, cardsapp.ErrUnsupportedAPIType): + writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能转换为该类型") + case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID): + writeErr(w, http.StatusNotFound, "卡券不存在") + case errors.Is(err, cardsapp.ErrForbidden): + writeErr(w, http.StatusForbidden, "无权操作该卡密组") + default: + writeErr(w, http.StatusInternalServerError, "更新失败") + } return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// deleteCard 负责delete卡密相关处理。 +// deleteCard 解析路径标识,并由应用服务在归属校验后删除卡券组。 func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) { - // id、err 保存id、err,供当前处理流程使用 - id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) - if err != nil { + // cardID、parseErr 保存路径中的卡券标识及数字解析错误。 + cardID, parseErr := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) + if parseErr != nil { writeErr(w, http.StatusBadRequest, "无效卡券ID") return } - if // ok 保存ok,供当前处理流程使用 - _, ok := s.requireCardOwner(w, r, id); !ok { - return - } - if // err 保存err,供当前处理流程使用 - err := s.Store.Cards.Delete(r.Context(), id); err != nil { - writeErr(w, http.StatusInternalServerError, "删除失败") + // session 是认证中间件注入的当前用户会话。 + session := auth.SessionFromContext(r.Context()) + // err 是应用服务返回的资源、所有权或删除持久化错误。 + err := s.cardsApplication().Delete(r.Context(), session.UserID, cardID) + if err != nil { + switch { + case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID): + writeErr(w, http.StatusNotFound, "卡券不存在") + case errors.Is(err, cardsapp.ErrForbidden): + writeErr(w, http.StatusForbidden, "无权操作该卡密组") + default: + writeErr(w, http.StatusInternalServerError, "删除失败") + } return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// decodeCard 负责decode卡密相关处理。 -func decodeCard(r *http.Request) (*db.CardFull, error) { - // req 保存req,供当前处理流程使用 - var req struct { - Name string `json:"name"` - Type string `json:"type"` - APIConfig string `json:"api_config"` - TextContent string `json:"text_content"` - DataContent string `json:"data_content"` - ImageURL string `json:"image_url"` - Description string `json:"description"` - Enabled bool `json:"enabled"` - DelaySeconds int `json:"delay_seconds"` - IsMultiSpec bool `json:"is_multi_spec"` - SpecName string `json:"spec_name"` - SpecValue string `json:"spec_value"` +// decodeCardDraft 把具名 HTTP 请求 DTO 转换为应用输入;业务校验由应用服务统一负责。 +func decodeCardDraft(r *http.Request) (cardsapp.Draft, error) { + // request 是当前待解码的卡券创建或更新请求。 + var request cardMutationRequest + // err 表示请求 JSON 无法解码为卡券输入 DTO 的格式错误。 + if err := decodeJSON(r, &request); err != nil { + return cardsapp.Draft{}, err } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil { - return nil, err - } - if req.Name == "" || req.Type == "" { - return nil, errStr("名称和类型不能为空") - } - switch req.Type { - case "text", "data", "image", "api": - default: - return nil, errStr("类型必须为 text、data、image 或 api") - } - if req.DelaySeconds < 0 || req.DelaySeconds > 3600 { - return nil, errStr("延时发货必须在 0 到 3600 秒之间") - } - switch req.Type { - case "text": - if strings.TrimSpace(req.TextContent) == "" { - return nil, errStr("文本卡密内容不能为空") - } - case "data": - if strings.TrimSpace(req.DataContent) == "" { - return nil, errStr("数据卡密内容不能为空") - } - case "image": - if strings.TrimSpace(req.ImageURL) == "" { - return nil, errStr("图片卡密 URL 不能为空") - } - } - return &db.CardFull{ - Name: req.Name, Type: req.Type, APIConfig: req.APIConfig, TextContent: req.TextContent, - DataContent: req.DataContent, ImageURL: req.ImageURL, Description: req.Description, - Enabled: req.Enabled, DelaySeconds: req.DelaySeconds, IsMultiSpec: req.IsMultiSpec, - SpecName: req.SpecName, SpecValue: req.SpecValue, + return cardsapp.Draft{ + Name: request.Name, Type: request.Type, APIConfig: request.APIConfig, + TextContent: request.TextContent, DataContent: request.DataContent, ImageURL: request.ImageURL, + Description: request.Description, Enabled: request.Enabled, DelaySeconds: request.DelaySeconds, + IsMultiSpec: request.IsMultiSpec, SpecName: request.SpecName, SpecValue: request.SpecValue, }, nil } -// itemOwnedByUser 校验 cookieID 归属当前用户且其下存在 itemID 商品。 -// 由自动化规则校验复用(原 deliveryRuleItemOwned,发货规则删除后改名)。 -// itemOwnedByUser 负责商品OwnedBy用户相关处理。 -func (s *Server) itemOwnedByUser(r *http.Request, userID int64, cookieID, itemID string) bool { - if itemID == "" { - return true +// writeCardReadError 将详情查询的应用错误映射为既有 HTTP 状态和统一错误响应。 +func writeCardReadError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID): + writeErr(w, http.StatusNotFound, "卡券不存在") + case errors.Is(err, cardsapp.ErrForbidden): + writeErr(w, http.StatusForbidden, "无权操作该卡密组") + default: + writeErr(w, http.StatusInternalServerError, "查询失败") } - if cookieID == "" { - return false - } - owned, err := s.Store.Cookies.ExistsOwned(r.Context(), userID, cookieID) // owned 和 err 表示账号归属及查询错误。 - if err != nil || !owned { - return false - } - _, err = s.Store.Items.Get(r.Context(), cookieID, itemID) - return err == nil } - -// errStr 负责errStr相关处理。 -func errStr(s string) error { return &simpleError{s} } - -// simpleError 保存simple错误,供当前处理流程使用 -type simpleError struct{ msg string } - -// Error 负责错误相关处理。 -func (e *simpleError) Error() string { return e.msg } diff --git a/internal/server/chat_application.go b/internal/server/chat_application.go new file mode 100644 index 0000000..9491b01 --- /dev/null +++ b/internal/server/chat_application.go @@ -0,0 +1,14 @@ +package server + +import ( + "xianyu-go/internal/adapter" + chatapp "xianyu-go/internal/application/chat" +) + +// newChatSendingApplication 创建实时聊天应用服务,Server 仅负责注入运行时依赖。 +func newChatSendingApplication(server *Server) *chatapp.Service { + if server == nil { + return adapter.NewChatSendingApplication(nil, nil, nil, nil) + } + return server.dependencies.NewChatSendingApplication(server.chat, server.Manager, server.mtopClient) +} diff --git a/internal/server/chat_handlers.go b/internal/server/chat_handlers.go index 860f99f..b605055 100644 --- a/internal/server/chat_handlers.go +++ b/internal/server/chat_handlers.go @@ -14,10 +14,9 @@ import ( "github.com/coder/websocket/wsjson" "github.com/go-chi/chi/v5" + "xianyu-go/internal/adapter" chatapp "xianyu-go/internal/application/chat" "xianyu-go/internal/auth" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/mtop" ) // mountChat 负责mount聊天相关处理。 @@ -30,74 +29,6 @@ func (s *Server) mountChat(r chi.Router) { r.Get("/api/chat/ws", s.chatWebSocket) } -// storeChatApplicationRepository 将数据库聊天查询适配为应用层聊天端口。 -type storeChatApplicationRepository struct { - // store 保存数据库聚合入口,仅在适配器内执行窄聊天查询。 - store *db.Store -} - -// ListMessages 查询带用户归属条件的聊天消息,并转换为应用层模型。 -func (r storeChatApplicationRepository) ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]chatapp.Message, error) { - // rows 保存数据库返回的消息记录。 - rows, err := r.store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit) - if err != nil { - return nil, err - } - // messages 保存脱离数据库模型的应用层消息。 - messages := make([]chatapp.Message, 0, len(rows)) - // row 表示当前待转换的数据库聊天消息。 - for _, row := range rows { - messages = append(messages, chatapp.Message{ - ID: row.ID, AccountID: row.CookieID, ChatID: row.ChatID, MessageKey: row.MessageKey, - Direction: row.Direction, SenderID: row.SenderID, SenderName: row.SenderName, - MessageType: row.MessageType, Content: row.Content, Status: row.Status, SentAt: row.SentAt, - }) - } - return messages, nil -} - -// ListSessions 查询带用户归属条件的聊天会话,并转换为应用层模型。 -func (r storeChatApplicationRepository) ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]chatapp.Session, error) { - // rows 保存数据库返回的会话记录。 - rows, err := r.store.Chats.ListSessions(ctx, userID, accountID, limit) - if err != nil { - return nil, err - } - // sessions 保存脱离数据库模型的应用层会话摘要。 - sessions := make([]chatapp.Session, 0, len(rows)) - // row 表示当前待转换的数据库聊天会话。 - for _, row := range rows { - sessions = append(sessions, chatapp.Session{ - AccountID: row.CookieID, ChatID: row.ChatID, BuyerID: row.BuyerID, - BuyerName: row.BuyerName, BuyerAvatar: row.BuyerAvatar, ItemID: row.ItemID, - ItemTitle: row.ItemTitle, LastMessage: row.LastMessage, LastMessageAt: row.LastMessageAt, - UnreadCount: row.UnreadCount, - }) - } - return sessions, nil -} - -// newStoreChatApplicationRepository 创建聊天历史应用服务使用的数据库适配器。 -func newStoreChatApplicationRepository(store *db.Store) chatapp.Repository { - if store == nil || store.Chats == nil { - return nil - } - return storeChatApplicationRepository{store: store} -} - -// dbChatSessionFromApplication 将非敏感应用会话转换为平台身份适配器可消费的数据库形状。 -func dbChatSessionFromApplication(session chatapp.Session) db.ChatSession { - return db.ChatSession{ - CookieID: session.AccountID, ChatID: session.ChatID, BuyerID: session.BuyerID, - BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID, - ItemTitle: session.ItemTitle, LastMessage: session.LastMessage, LastMessageAt: session.LastMessageAt, - UnreadCount: session.UnreadCount, - } -} - -// 确保数据库适配器覆盖聊天历史应用端口的全部能力。 -var _ chatapp.Repository = storeChatApplicationRepository{} - // chatApplication 返回当前 Server 绑定的聊天历史应用服务。 func (s *Server) chatApplication() *chatapp.Service { return s.applicationServiceSet().chat @@ -121,8 +52,8 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) { var hasMore bool // nextCursor 保存next游标,供当前处理流程使用 var nextCursor int64 - if // err 保存err,供当前处理流程使用 - err := s.Store.Chats.DeleteEmptySessions(r.Context(), accountID); err != nil { + if // err 保存清理空会话的错误。 + err := s.chatApplication().CleanupEmptySessions(r.Context(), accountID); err != nil { writeErr(w, http.StatusInternalServerError, "清理无效聊天会话失败") return } @@ -152,88 +83,24 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) { } } } - // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, parsePositiveInt(r.URL.Query().Get("limit"), 200)) + // rows、err 保存应用层会话摘要及查询错误。 + rows, err := s.chatApplication().ListSessions(r.Context(), sess.UserID, accountID, parsePositiveInt(r.URL.Query().Get("limit"), 200)) if err != nil { writeErr(w, http.StatusInternalServerError, "读取聊天会话失败") return } if refresh { - if // cookieValue、cookieErr 保存登录凭证Value、cookieErr,供当前处理流程使用 - cookieValue, cookieErr := s.Store.Cookies.GetValue(r.Context(), accountID); cookieErr == nil { - // client、canResolve 保存client、canResolve,供当前处理流程使用 - client, canResolve := s.mtopClient().(interface { - FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error) - }) - if !canResolve { - writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor}) - return - } - // resolveCtx、resolveCancel 保存resolveCtx、resolve取消,供当前处理流程使用 - resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second) - defer resolveCancel() - // jobs 保存jobs,供当前处理流程使用 - jobs := make(chan int) - // workers 保存workers,供当前处理流程使用 - var workers sync.WaitGroup - // sessionOnce 保存会话Once,供当前处理流程使用 - var sessionOnce sync.Once - // sessionErr 保存会话Err,供当前处理流程使用 - var sessionErr error - for // worker 保存工作器,供当前处理流程使用 - worker := 0; worker < 8; worker++ { - workers.Add(1) - go func() { - defer workers.Done() - // index 表示当前遍历过程中的index - for index := range jobs { - // infoCtx、cancel 保存infoCtx、cancel,供当前处理流程使用 - infoCtx, cancel := context.WithTimeout(resolveCtx, 3*time.Second) - // info、infoErr 保存info、infoErr,供当前处理流程使用 - info, infoErr := client.FetchChatUserInfo(infoCtx, cookieValue, rows[index].ChatID) - cancel() - if mtop.IsSessionExpiredErr(infoErr) { - sessionOnce.Do(func() { - sessionErr = infoErr - resolveCancel() - }) - continue - } - if infoErr != nil || info == nil { - continue - } - if // nickname 保存nickname,供当前处理流程使用 - nickname := strings.TrimSpace(info.Nickname); nickname != "" { - rows[index].BuyerName = nickname - } - if info.AvatarURL != "" { - rows[index].BuyerAvatar = info.AvatarURL - } - _ = s.Store.Chats.UpdateSessionIdentity(resolveCtx, accountID, rows[index].ChatID, - rows[index].BuyerID, rows[index].BuyerName, rows[index].BuyerAvatar) - } - }() - } - queue: - // index 表示当前遍历过程中的index - for index := range rows { - if rows[index].BuyerID == "1400" { - continue - } - select { - case jobs <- index: - case <-resolveCtx.Done(): - break queue - } - } - close(jobs) - workers.Wait() - if sessionErr != nil { - s.recoverExpiredMTOPSession(r.Context(), accountID, sessionErr) - } + // resolveCtx 和 resolveCancel 限制联系人身份补全的总时长。 + resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second) + // refreshedRows 和 sessionErr 保存应用层身份补全结果及首个平台错误。 + refreshedRows, sessionErr := s.chatApplication().RefreshSessionIdentities(resolveCtx, accountID, rows) + resolveCancel() + rows = refreshedRows + if sessionErr != nil { + s.recoverExpiredMTOPSession(r.Context(), accountID, sessionErr) } } - writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor}) + writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOsFromApplication(rows), HasMore: hasMore, NextCursor: nextCursor}) } // sendChatImage 负责send聊天图片相关处理。 @@ -340,24 +207,19 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) { cancel() if fetchErr == nil { // sessions 保存sessions,供当前处理流程使用 - sessions, _ := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500) - // current 保存current,供当前处理流程使用 - var current db.ChatSession - // candidate 表示当前遍历过程中的candidate - for _, candidate := range sessions { - if candidate.ChatID == chatID { - current = candidate - break - } - } + current, _ := s.chatApplication().FindSession(r.Context(), sess.UserID, accountID, chatID) // page、saveErr 保存page、saveErr,供当前处理流程使用 - page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, current, body) + page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, adapter.ChatSessionFromApplication(current), body) if saveErr != nil { writeErr(w, http.StatusInternalServerError, "保存聊天历史失败") return } - current = s.resolveSelectedChatIdentity(r.Context(), accountID, current) - writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(page.Messages), HasMore: page.HasMore, NextCursor: page.NextCursor, Session: newChatSessionDTO(current)}) + // current 和 identityErr 保存身份补全后的会话及平台查询错误。 + current, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), current) + if identityErr != nil { + s.recoverExpiredMTOPSession(r.Context(), accountID, identityErr) + } + writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(adapter.ChatMessagesFromDB(page.Messages)), HasMore: page.HasMore, NextCursor: page.NextCursor, Session: newChatSessionDTOFromApplication(current)}) return } } @@ -370,43 +232,16 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) { return } // session 是应用层返回的非敏感会话摘要,供平台身份适配器补齐展示名称。 - session := dbChatSessionFromApplication(page.Session) + session := page.Session if session.ChatID != "" { - session = s.resolveSelectedChatIdentity(r.Context(), accountID, session) - } - writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(session)}) -} - -// resolveSelectedChatIdentity 负责resolveSelected聊天Identity相关处理。 -func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID string, session db.ChatSession) db.ChatSession { - if session.BuyerID != "1400" { - // cookies、cookieErr 保存cookies、cookieErr,供当前处理流程使用 - cookies, cookieErr := s.Store.Cookies.GetValue(ctx, accountID) - // client、supported 保存client、supported,供当前处理流程使用 - client, supported := s.mtopClient().(interface { - FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error) - }) - if cookieErr == nil && supported { - // resolveCtx、cancel 保存resolveCtx、cancel,供当前处理流程使用 - resolveCtx, cancel := context.WithTimeout(ctx, 5*time.Second) - // info、err 保存info、err,供当前处理流程使用 - info, err := client.FetchChatUserInfo(resolveCtx, cookies, session.ChatID) - cancel() - if err == nil && info != nil { - if // nickname 保存nickname,供当前处理流程使用 - nickname := strings.TrimSpace(info.Nickname); nickname != "" { - session.BuyerName = nickname - } - if info.AvatarURL != "" { - session.BuyerAvatar = info.AvatarURL - } - } else if err != nil { - s.recoverExpiredMTOPSession(ctx, accountID, err) - } + // resolved 和 identityErr 保存身份补全后的会话及平台查询错误。 + resolved, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), session) + if identityErr != nil { + s.recoverExpiredMTOPSession(r.Context(), accountID, identityErr) } + session = resolved } - _ = s.Store.Chats.UpdateSessionIdentity(ctx, accountID, session.ChatID, session.BuyerID, session.BuyerName, session.BuyerAvatar) - return session + writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTOFromApplication(session)}) } // sendChatMessageRequest 保存send聊天消息请求,供当前处理流程使用 @@ -481,10 +316,10 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusForbidden, "无权操作该账号") return } - // sess 保存sess,供当前处理流程使用 + // sess 保存当前认证用户,用于应用层归属隔离。 sess := auth.SessionFromContext(r.Context()) - if // err 保存err,供当前处理流程使用 - err := s.communicationApplication().MarkChatRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil { + if // err 保存应用层已读状态更新错误。 + err := s.chatApplication().MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil { writeErr(w, http.StatusInternalServerError, "更新已读状态失败") return } @@ -505,18 +340,20 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败") return } - defer unsubscribe() // conn、err 保存conn、err,供当前处理流程使用 conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover}) if err != nil { + unsubscribe() return } - defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }() // ctx、cancel 保存ctx、cancel,供当前处理流程使用 ctx, cancel := context.WithCancel(r.Context()) - defer cancel() conn.SetReadLimit(8 << 10) + // readerWG 等待读取 goroutine 在连接关闭后退出,避免请求返回时遗留后台任务。 + var readerWG sync.WaitGroup + readerWG.Add(1) go func() { + defer readerWG.Done() for { if // readErr 保存readErr,供当前处理流程使用 _, _, readErr := conn.Read(ctx); readErr != nil { @@ -525,6 +362,14 @@ func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) { } } }() + // cleanup 统一负责取消请求、关闭 WebSocket、等待读取任务和释放聊天订阅。 + cleanup := func() { + cancel() + _ = conn.Close(websocket.StatusNormalClosure, "") + readerWG.Wait() + unsubscribe() + } + defer cleanup() if // err 保存err,供当前处理流程使用 err := wsjson.Write(ctx, conn, map[string]any{"type": "ready", "at": time.Now().UTC().UnixMilli()}); err != nil { return @@ -549,7 +394,8 @@ func (s *Server) ownsAccount(r *http.Request, accountID string) bool { } // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) - owned, err := s.Store.Cookies.ExistsOwned(r.Context(), sess.UserID, accountID) // owned 和 err 表示账号归属及查询错误。 + // owned 和 err 表示聊天应用端口返回的账号归属及查询错误。 + owned, err := s.chatApplication().OwnsAccount(r.Context(), sess.UserID, accountID) return err == nil && owned } diff --git a/internal/server/communication_repository.go b/internal/server/communication_repository.go deleted file mode 100644 index 4cf9fbf..0000000 --- a/internal/server/communication_repository.go +++ /dev/null @@ -1,154 +0,0 @@ -package server - -import ( - "context" - - "xianyu-go/internal/db" -) - -// communicationRepository 定义通信应用服务隔离账号任务、通知绑定和聊天历史所需的最小持久化能力。 -type communicationRepository interface { - // GetAccountTaskSettings 读取账号任务设置。 - GetAccountTaskSettings(ctx context.Context, cookieID string) (db.AccountTaskSettings, error) - // UpsertAccountTaskSettings 保存账号任务设置。 - UpsertAccountTaskSettings(ctx context.Context, settings db.AccountTaskSettings) error - // ListAccountTaskRuns 查询账号任务运行记录。 - ListAccountTaskRuns(ctx context.Context, cookieID string, limit int) ([]db.AccountTaskRun, error) - // ListNotificationChannels 查询用户拥有的通知渠道。 - ListNotificationChannels(ctx context.Context, userID int64) ([]db.NotificationChannelRow, error) - // CreateNotificationChannel 创建通知渠道。 - CreateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow) (int64, error) - // UpdateNotificationChannel 更新用户拥有的通知渠道。 - UpdateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow, userID int64) error - // GetNotificationChannel 查询用户拥有的单个通知渠道。 - GetNotificationChannel(ctx context.Context, channelID, userID int64) (*db.NotificationChannelRow, error) - // DeleteNotificationChannel 删除用户拥有的通知渠道。 - DeleteNotificationChannel(ctx context.Context, channelID, userID int64) error - // GetNotificationChannelConfig 查询通知渠道发送配置。 - GetNotificationChannelConfig(ctx context.Context, channelID int64) (*db.NotificationChannel, error) - // ListNotificationBindings 查询用户账号通知绑定。 - ListNotificationBindings(ctx context.Context, userID int64) ([]db.NotificationBindingRow, error) - // SetNotificationBindings 覆盖保存账号通知绑定。 - SetNotificationBindings(ctx context.Context, cookieID string, channelIDs []int64) error - // GetNotificationBindingIDs 查询账号当前启用的通知渠道。 - GetNotificationBindingIDs(ctx context.Context, cookieID string) ([]int64, error) - // SetSingleNotificationBinding 更新单个通知绑定状态。 - SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error - // DeleteNotificationBinding 删除用户账号的一条通知绑定。 - DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error - // DeleteAccountNotificationBindings 删除用户账号的全部通知绑定。 - DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error - // GetCookieValue 读取账号 Cookie 明文。 - GetCookieValue(ctx context.Context, cookieID string) (string, error) - // UpdateCookieValue 更新已存在账号的 Cookie 明文。 - UpdateCookieValue(ctx context.Context, cookieID, value string) error - // MarkChatRead 将聊天会话标记为已读。 - MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error -} - -// storeCommunicationRepository 将完整 Store 适配为通信应用服务窄 repository。 -type storeCommunicationRepository struct { - // store 保存数据库聚合入口,仅在适配器内部使用。 - store *db.Store -} - -// GetAccountTaskSettings 委托账号任务设置查询。 -func (r storeCommunicationRepository) GetAccountTaskSettings(ctx context.Context, cookieID string) (db.AccountTaskSettings, error) { - return r.store.AccountTasks.Get(ctx, cookieID) -} - -// UpsertAccountTaskSettings 委托账号任务设置写入。 -func (r storeCommunicationRepository) UpsertAccountTaskSettings(ctx context.Context, settings db.AccountTaskSettings) error { - return r.store.AccountTasks.Upsert(ctx, settings) -} - -// ListAccountTaskRuns 委托账号任务运行记录查询。 -func (r storeCommunicationRepository) ListAccountTaskRuns(ctx context.Context, cookieID string, limit int) ([]db.AccountTaskRun, error) { - return r.store.AccountTasks.RecentRuns(ctx, cookieID, limit) -} - -// ListNotificationChannels 委托用户通知渠道查询。 -func (r storeCommunicationRepository) ListNotificationChannels(ctx context.Context, userID int64) ([]db.NotificationChannelRow, error) { - return r.store.Notifications.AllChannelsForUser(ctx, userID) -} - -// CreateNotificationChannel 委托通知渠道创建。 -func (r storeCommunicationRepository) CreateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow) (int64, error) { - return r.store.Notifications.CreateChannel(ctx, row) -} - -// UpdateNotificationChannel 委托通知渠道更新。 -func (r storeCommunicationRepository) UpdateNotificationChannel(ctx context.Context, row *db.NotificationChannelRow, userID int64) error { - return r.store.Notifications.UpdateChannelForUser(ctx, row, userID) -} - -// GetNotificationChannel 委托带用户归属的通知渠道查询。 -func (r storeCommunicationRepository) GetNotificationChannel(ctx context.Context, channelID, userID int64) (*db.NotificationChannelRow, error) { - return r.store.Notifications.GetChannelRowForUser(ctx, channelID, userID) -} - -// DeleteNotificationChannel 委托通知渠道删除。 -func (r storeCommunicationRepository) DeleteNotificationChannel(ctx context.Context, channelID, userID int64) error { - return r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID) -} - -// GetNotificationChannelConfig 委托通知渠道发送配置查询。 -func (r storeCommunicationRepository) GetNotificationChannelConfig(ctx context.Context, channelID int64) (*db.NotificationChannel, error) { - return r.store.Notifications.GetChannel(ctx, channelID) -} - -// ListNotificationBindings 委托通知绑定查询。 -func (r storeCommunicationRepository) ListNotificationBindings(ctx context.Context, userID int64) ([]db.NotificationBindingRow, error) { - return r.store.Notifications.ListBindingsForUser(ctx, userID) -} - -// SetNotificationBindings 委托通知绑定覆盖写入。 -func (r storeCommunicationRepository) SetNotificationBindings(ctx context.Context, cookieID string, channelIDs []int64) error { - return r.store.Notifications.SetBindings(ctx, cookieID, channelIDs) -} - -// GetNotificationBindingIDs 委托账号通知绑定查询。 -func (r storeCommunicationRepository) GetNotificationBindingIDs(ctx context.Context, cookieID string) ([]int64, error) { - return r.store.Notifications.AccountBindings(ctx, cookieID) -} - -// SetSingleNotificationBinding 委托单个通知绑定状态更新。 -func (r storeCommunicationRepository) SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error { - return r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled) -} - -// DeleteNotificationBinding 委托通知绑定删除。 -func (r storeCommunicationRepository) DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error { - return r.store.Notifications.DeleteBinding(ctx, userID, bindingID) -} - -// DeleteAccountNotificationBindings 委托账号通知绑定删除。 -func (r storeCommunicationRepository) DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error { - return r.store.Notifications.DeleteAccountBindings(ctx, userID, cookieID) -} - -// GetCookieValue 委托账号 Cookie 查询。 -func (r storeCommunicationRepository) GetCookieValue(ctx context.Context, cookieID string) (string, error) { - return r.store.Cookies.GetValue(ctx, cookieID) -} - -// UpdateCookieValue 委托账号 Cookie 更新。 -func (r storeCommunicationRepository) UpdateCookieValue(ctx context.Context, cookieID, value string) error { - return r.store.Cookies.UpdateValueExisting(ctx, cookieID, value) -} - -// MarkChatRead 委托聊天已读状态更新。 -func (r storeCommunicationRepository) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error { - return r.store.Chats.MarkRead(ctx, userID, accountID, chatID) -} - -// newStoreCommunicationRepository 从完整 Store 构造通信应用服务窄 repository。 -func newStoreCommunicationRepository(store *db.Store) communicationRepository { - if store == nil || store.AccountTasks == nil || store.Notifications == nil || store.Cookies == nil || store.Chats == nil { - return nil - } - return storeCommunicationRepository{store: store} -} - -// 确保 Store 适配器始终覆盖通信应用服务所需的全部能力。 -var _ communicationRepository = storeCommunicationRepository{} diff --git a/internal/server/communication_service.go b/internal/server/communication_service.go deleted file mode 100644 index 9df1dad..0000000 --- a/internal/server/communication_service.go +++ /dev/null @@ -1,381 +0,0 @@ -package server - -import ( - "context" - "errors" - "strings" - - "xianyu-go/internal/account" - chatapp "xianyu-go/internal/application/chat" - "xianyu-go/internal/automation" - domainchat "xianyu-go/internal/chat" - "xianyu-go/internal/db" - "xianyu-go/internal/engine" - "xianyu-go/internal/xianyu/mtop" -) - -var ( - // errCommunicationUnavailable 表示聊天或自动化依赖尚未初始化。 - errCommunicationUnavailable = errors.New("通信服务未启用") -) - -// communicationService 是聊天、账号任务和通知应用服务。 -type communicationService struct { - // server 提供数据库、聊天事件中心、账号运行时和通知器依赖。 - server *Server - // repository 提供账号任务、通知绑定和聊天历史的最小持久化能力。 - repository communicationRepository -} - -// accountTaskUpdateInput 是账号任务设置更新的业务输入。 -type accountTaskUpdateInput struct { - // CookieID 是账号标识。 - CookieID string - // Settings 是待保存的任务设置。 - Settings db.AccountTaskSettings -} - -// notificationBindingRow 是通知绑定列表的一行业务数据。 -type notificationBindingRow struct { - // ID 是绑定记录标识。 - ID int64 - // CookieID 是绑定账号标识。 - CookieID string - // ChannelID 是通知渠道标识。 - ChannelID int64 - // ChannelName 是通知渠道名称。 - ChannelName string - // Enabled 表示绑定是否启用。 - Enabled bool -} - -// communicationApplication 返回当前 Server 绑定的通信应用服务。 -func (s *Server) communicationApplication() *communicationService { - return s.applicationServiceSet().communication -} - -// GetAccountTaskSettings 读取指定账号的任务设置。 -func (svc *communicationService) GetAccountTaskSettings(ctx context.Context, cookieID string) (db.AccountTaskSettings, error) { - return svc.repository.GetAccountTaskSettings(ctx, cookieID) -} - -// UpdateAccountTaskSettings 校验并保存账号任务设置,然后返回数据库中的最终值。 -func (svc *communicationService) UpdateAccountTaskSettings(ctx context.Context, input accountTaskUpdateInput) (db.AccountTaskSettings, error) { - // settings 是规范化后的账号任务设置。 - settings := input.Settings - settings.CookieID = input.CookieID - settings.RateContent = strings.TrimSpace(settings.RateContent) - if settings.AutoRateEnabled && settings.RateContent == "" { - return db.AccountTaskSettings{}, errors.New("启用自动评价时评价内容不能为空") - } - if len([]rune(settings.RateContent)) > 500 { - return db.AccountTaskSettings{}, errors.New("评价内容不能超过 500 个字符") - } - if !accountTaskTimePattern.MatchString(settings.PolishTime) { - return db.AccountTaskSettings{}, errors.New("擦亮时间格式必须为 HH:mm") - } - // err 表示任务设置持久化错误。 - if err := svc.repository.UpsertAccountTaskSettings(ctx, settings); err != nil { - return db.AccountTaskSettings{}, err - } - return svc.repository.GetAccountTaskSettings(ctx, input.CookieID) -} - -// ListAccountTaskRuns 查询账号最近的任务执行记录。 -func (svc *communicationService) ListAccountTaskRuns(ctx context.Context, cookieID string, limit int) ([]db.AccountTaskRun, error) { - return svc.repository.ListAccountTaskRuns(ctx, cookieID, limit) -} - -// RunAccountTask 执行一次账号自动化任务并返回执行摘要。 -func (svc *communicationService) RunAccountTask(ctx context.Context, cookieID, taskType string) (automation.AccountTaskSummary, error) { - if svc.server.automation == nil { - return automation.AccountTaskSummary{}, errCommunicationUnavailable - } - return svc.server.automation.RunAccountTask(ctx, cookieID, taskType) -} - -// ListNotificationChannels 查询用户拥有的通知渠道。 -func (svc *communicationService) ListNotificationChannels(ctx context.Context, userID int64) ([]db.NotificationChannelRow, error) { - return svc.repository.ListNotificationChannels(ctx, userID) -} - -// CreateNotificationChannel 创建用户通知渠道。 -func (svc *communicationService) CreateNotificationChannel(ctx context.Context, row db.NotificationChannelRow) (int64, error) { - return svc.repository.CreateNotificationChannel(ctx, &row) -} - -// UpdateNotificationChannel 更新用户拥有的通知渠道。 -func (svc *communicationService) UpdateNotificationChannel(ctx context.Context, row db.NotificationChannelRow, userID int64) error { - return svc.repository.UpdateNotificationChannel(ctx, &row, userID) -} - -// GetNotificationChannel 查询用户拥有的单个通知渠道。 -func (svc *communicationService) GetNotificationChannel(ctx context.Context, channelID, userID int64) (*db.NotificationChannelRow, error) { - return svc.repository.GetNotificationChannel(ctx, channelID, userID) -} - -// DeleteNotificationChannel 删除用户拥有的通知渠道。 -func (svc *communicationService) DeleteNotificationChannel(ctx context.Context, channelID, userID int64) error { - return svc.repository.DeleteNotificationChannel(ctx, channelID, userID) -} - -// TestNotificationChannel 向用户拥有的通知渠道发送测试消息。 -func (svc *communicationService) TestNotificationChannel(ctx context.Context, channelID, userID int64, body string) error { - if svc.server.notifier == nil { - return errCommunicationUnavailable - } - // channel 和 err 保存通知渠道查询结果。 - channel, err := svc.repository.GetNotificationChannelConfig(ctx, channelID) - if err != nil { - return err - } - if channel == nil { - return db.ErrForbidden - } - // row 和 err 保存带用户归属的渠道查询结果。 - row, err := svc.repository.GetNotificationChannel(ctx, channelID, userID) - if err != nil { - return err - } - if row == nil { - return db.ErrForbidden - } - return svc.server.notifier.SendToChannel(channelID, body) -} - -// ListNotificationBindings 查询用户账号的通知绑定。 -func (svc *communicationService) ListNotificationBindings(ctx context.Context, userID int64) (map[string][]notificationBindingRow, error) { - // rows 和 err 保存绑定查询结果集。 - rows, err := svc.repository.ListNotificationBindings(ctx, userID) - if err != nil { - return nil, err - } - // result 是按账号分组的通知绑定列表。 - result := make(map[string][]notificationBindingRow) - // row 表示当前遍历过程中的row - for _, row := range rows { - // binding 保存当前扫描到的通知绑定记录。 - binding := notificationBindingRow{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled} - result[binding.CookieID] = append(result[binding.CookieID], binding) - } - return result, nil -} - -// SetNotificationBindings 覆盖保存账号的通知渠道绑定。 -func (svc *communicationService) SetNotificationBindings(ctx context.Context, cookieID string, channelIDs []int64) error { - return svc.repository.SetNotificationBindings(ctx, cookieID, channelIDs) -} - -// GetNotificationBindingIDs 查询账号当前启用的通知渠道标识。 -func (svc *communicationService) GetNotificationBindingIDs(ctx context.Context, cookieID string) ([]int64, error) { - return svc.repository.GetNotificationBindingIDs(ctx, cookieID) -} - -// SetSingleNotificationBinding 更新单个账号通知渠道的启用状态。 -func (svc *communicationService) SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error { - if !enabled { - return svc.repository.SetSingleNotificationBinding(ctx, cookieID, channelID, false) - } - return svc.repository.SetSingleNotificationBinding(ctx, cookieID, channelID, true) -} - -// DeleteNotificationBinding 删除用户账号下的一条通知绑定。 -func (svc *communicationService) DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error { - return svc.repository.DeleteNotificationBinding(ctx, userID, bindingID) -} - -// DeleteAccountNotificationBindings 删除用户账号的全部通知绑定。 -func (svc *communicationService) DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error { - return svc.repository.DeleteAccountNotificationBindings(ctx, userID, cookieID) -} - -// MarkChatRead 将指定聊天会话标记为已读。 -func (svc *communicationService) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error { - return svc.repository.MarkChatRead(ctx, userID, accountID, chatID) -} - -// storeChatOutgoingRepository 将领域聊天服务适配为实时发送应用端口。 -type storeChatOutgoingRepository struct { - // service 保存聊天消息幂等写入和实时事件发布能力。 - service *domainchat.Service -} - -// CreateOutgoing 创建文字消息并转换为应用层非敏感模型。 -func (r storeChatOutgoingRepository) CreateOutgoing(ctx context.Context, session chatapp.Session, text string) (chatapp.Message, error) { - if r.service == nil { - return chatapp.Message{}, chatapp.ErrUnavailable - } - // message、err 保存领域服务返回的消息及写入错误。 - message, err := r.service.CreateOutgoing(ctx, dbChatSessionFromApplication(session), text) - return applicationChatMessage(message), err -} - -// CreateOutgoingMedia 创建媒体消息并转换为应用层非敏感模型。 -func (r storeChatOutgoingRepository) CreateOutgoingMedia(ctx context.Context, session chatapp.Session, messageType, content string) (chatapp.Message, error) { - if r.service == nil { - return chatapp.Message{}, chatapp.ErrUnavailable - } - // message、err 保存领域服务返回的媒体消息及写入错误。 - message, err := r.service.CreateOutgoingMedia(ctx, dbChatSessionFromApplication(session), messageType, content) - return applicationChatMessage(message), err -} - -// SetOutgoingStatus 更新外发消息状态并转换为应用层非敏感模型。 -func (r storeChatOutgoingRepository) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (chatapp.Message, error) { - if r.service == nil { - return chatapp.Message{}, chatapp.ErrUnavailable - } - // message、err 保存领域服务返回的状态消息及更新错误。 - message, err := r.service.SetOutgoingStatus(ctx, accountID, key, status) - return applicationChatMessage(message), err -} - -// managerChatSenderProvider 将账号管理器适配为聊天应用的在线发送端口。 -type managerChatSenderProvider struct { - // manager 保存当前进程内的账号运行时管理器。 - manager *account.Manager -} - -// Sender 返回指定账号的在线发送能力。 -func (p managerChatSenderProvider) Sender(accountID string) (chatapp.Sender, bool) { - if p.manager == nil { - return nil, false - } - // sender、ok 保存账号管理器返回的运行时发送器及存在性。 - sender, ok := p.manager.GetInstance(accountID) - if !ok || sender == nil { - return nil, false - } - return managerChatSender{sender: sender}, true -} - -// managerChatSender 将自动化消息发送接口收敛为应用聊天端口,并注入幂等键上下文。 -type managerChatSender struct { - // sender 保存账号运行时提供的最小消息发送能力。 - sender automation.MessageSender -} - -// SendText 发送文字并将应用层幂等键传递给运行时旁路观察器。 -func (s managerChatSender) SendText(ctx context.Context, chatID, toUserID, text, messageKey string) error { - return s.sender.SendText(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, text) -} - -// SendImage 发送图片并将应用层幂等键传递给运行时接口。 -func (s managerChatSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, messageKey string) error { - return s.sender.SendImage(engine.WithOutgoingMessageKey(ctx, messageKey), chatID, toUserID, imageURL, cardID) -} - -// storeChatCredentialRepository 将账号 Cookie 仓储适配为图片发送端口。 -type storeChatCredentialRepository struct { - // store 保存数据库聚合入口,仅在凭证适配器内读取和更新 Cookie。 - store *db.Store -} - -// GetCookieValue 读取图片上传所需的账号凭证;调用方不得记录返回值。 -func (r storeChatCredentialRepository) GetCookieValue(ctx context.Context, accountID string) (string, error) { - if r.store == nil || r.store.Cookies == nil { - return "", chatapp.ErrUnavailable - } - return r.store.Cookies.GetValue(ctx, accountID) -} - -// UpdateCookieValue 保存图片上传后平台刷新的账号凭证。 -func (r storeChatCredentialRepository) UpdateCookieValue(ctx context.Context, accountID, cookieValue string) error { - if r.store == nil || r.store.Cookies == nil { - return chatapp.ErrUnavailable - } - return r.store.Cookies.UpdateValueExisting(ctx, accountID, cookieValue) -} - -// serverChatImageUploader 将 Server 当前 MTOP 客户端适配为图片上传端口。 -type serverChatImageUploader struct { - // server 提供可动态替换的 MTOP 客户端,便于测试注入平台替身。 - server *Server - // credentials 负责在平台刷新后持久化明文凭证,但不向应用层返回。 - credentials storeChatCredentialRepository - // manager 负责将刷新后的凭证同步到在线运行时。 - manager *account.Manager -} - -// UploadChatImage 在适配器内部读取和刷新凭证,只向应用层返回图片地址。 -func (u serverChatImageUploader) UploadChatImage(ctx context.Context, accountID, filename, contentType string, data []byte) (chatapp.ImageUpload, error) { - if u.server == nil { - return chatapp.ImageUpload{}, chatapp.ErrUnavailable - } - // cookieValue 和 err 保存平台调用所需的短暂明文凭证及读取错误,不得离开适配器。 - cookieValue, err := u.credentials.GetCookieValue(ctx, accountID) - if err != nil { - return chatapp.ImageUpload{}, err - } - // uploader、ok 保存 MTOP 图片上传能力及接口支持情况。 - uploader, ok := u.server.mtopClient().(interface { - UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error) - }) - if !ok { - return chatapp.ImageUpload{}, chatapp.ErrUnavailable - } - // upload、err 保存图片平台返回结果及调用错误。 - upload, err := uploader.UploadChatImage(ctx, cookieValue, filename, contentType, data) - if err != nil { - return chatapp.ImageUpload{}, err - } - if upload == nil { - return chatapp.ImageUpload{}, chatapp.ErrSend - } - if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookieValue { - // persistErr 保存刷新凭证的持久化错误;该错误必须反馈给调用方,避免静默丢失会话状态。 - if persistErr := u.credentials.UpdateCookieValue(ctx, accountID, upload.UpdatedCookies); persistErr != nil { - return chatapp.ImageUpload{}, persistErr - } - if u.manager != nil { - // sender、senderOK 保存刷新凭证同步到运行时的结果。 - sender, senderOK := u.manager.GetInstance(accountID) - if senderOK && sender != nil { - sender.UpdateCookie(upload.UpdatedCookies) - } - } - } - return chatapp.ImageUpload{URL: upload.URL}, nil -} - -// newChatSendingApplication 创建实时聊天发送应用服务及其 Server 适配器。 -func newChatSendingApplication(server *Server) *chatapp.Service { - // domainService 保存聊天领域服务;空值表示发送能力未装配。 - var domainService *domainchat.Service - if server != nil { - domainService = server.chat - } - // store 保存聊天适配器可用的数据库入口;空 Server 仍返回可安全调用的不可用服务。 - var store *db.Store - // manager 保存账号运行时管理器;空值表示无法发送平台消息。 - var manager *account.Manager - if server != nil { - store, manager = server.Store, server.Manager - } - return chatapp.NewWithSending( - newStoreChatApplicationRepository(store), - storeChatOutgoingRepository{service: domainService}, - managerChatSenderProvider{manager: manager}, - serverChatImageUploader{server: server, credentials: storeChatCredentialRepository{store: store}, manager: manager}, - ) -} - -// applicationChatMessage 将数据库消息转换为应用层模型;空指针保持零值。 -func applicationChatMessage(message *db.ChatMessage) chatapp.Message { - if message == nil { - return chatapp.Message{} - } - return chatapp.Message{ - ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID, MessageKey: message.MessageKey, - Direction: message.Direction, SenderID: message.SenderID, SenderName: message.SenderName, - MessageType: message.MessageType, Content: message.Content, Status: message.Status, SentAt: message.SentAt, - } -} - -// 确保各 Server 适配器覆盖聊天应用服务定义的最小端口。 -var ( - _ chatapp.OutgoingRepository = storeChatOutgoingRepository{} - _ chatapp.SenderProvider = managerChatSenderProvider{} - _ chatapp.Sender = managerChatSender{} - _ chatapp.ImageUploader = serverChatImageUploader{} -) diff --git a/internal/server/communication_service_test.go b/internal/server/communication_service_test.go index c8c1b2d..6fa1696 100644 --- a/internal/server/communication_service_test.go +++ b/internal/server/communication_service_test.go @@ -4,18 +4,17 @@ import ( "context" "testing" - "xianyu-go/internal/db" + automationapp "xianyu-go/internal/application/automation" ) -// TestCommunicationServiceUpdatesAccountTask 验证账号任务设置由通信应用服务校验并持久化。 -func TestCommunicationServiceUpdatesAccountTask(t *testing.T) { +// TestAccountTaskApplicationUpdatesSettings 验证账号任务设置由独立应用服务校验并持久化。 +func TestAccountTaskApplicationUpdatesSettings(t *testing.T) { // srv、store 和 cleanup 构造并释放测试服务。 srv, _, cleanup := newTestServer(t) defer cleanup() // settings 和 err 保存应用服务返回的最终任务设置。 - settings, err := srv.communicationApplication().UpdateAccountTaskSettings(context.Background(), accountTaskUpdateInput{ - CookieID: "acc1", - Settings: db.AccountTaskSettings{AutoRateEnabled: true, RateContent: " 好评 ", AutoPolishEnabled: false, PolishTime: "03:00"}, + settings, err := srv.accountTaskApplication().UpdateSettings(context.Background(), automationapp.AccountTaskSettings{ + CookieID: "acc1", AutoRateEnabled: true, RateContent: " 好评 ", AutoPolishEnabled: false, PolishTime: "03:00", }) if err != nil { t.Fatalf("UpdateAccountTaskSettings error: %v", err) @@ -25,14 +24,14 @@ func TestCommunicationServiceUpdatesAccountTask(t *testing.T) { } } -// TestCommunicationServiceRejectsInvalidAccountTask 验证账号任务业务校验不依赖 HTTP 请求。 -func TestCommunicationServiceRejectsInvalidAccountTask(t *testing.T) { +// TestAccountTaskApplicationRejectsInvalidSettings 验证账号任务业务校验不依赖 HTTP 请求。 +func TestAccountTaskApplicationRejectsInvalidSettings(t *testing.T) { // srv、store 和 cleanup 构造并释放测试服务。 srv, _, cleanup := newTestServer(t) defer cleanup() // err 保存无效任务设置的校验错误。 - _, err := srv.communicationApplication().UpdateAccountTaskSettings(context.Background(), accountTaskUpdateInput{ - CookieID: "acc1", Settings: db.AccountTaskSettings{AutoRateEnabled: true, PolishTime: "03:00"}, + _, err := srv.accountTaskApplication().UpdateSettings(context.Background(), automationapp.AccountTaskSettings{ + CookieID: "acc1", AutoRateEnabled: true, PolishTime: "03:00", }) if err == nil { t.Fatal("启用自动评价但没有内容应该失败") diff --git a/internal/server/cookie_handlers.go b/internal/server/cookie_handlers.go index 25d8fa9..0fbabd9 100644 --- a/internal/server/cookie_handlers.go +++ b/internal/server/cookie_handlers.go @@ -3,7 +3,6 @@ package server import ( "context" "errors" - "fmt" "net/http" "strings" "time" @@ -12,11 +11,9 @@ import ( "github.com/go-chi/chi/v5" accountapp "xianyu-go/internal/application/account" + automationapp "xianyu-go/internal/application/automation" "xianyu-go/internal/auth" - "xianyu-go/internal/db" "xianyu-go/internal/engine" - "xianyu-go/internal/xianyu/cookierefresh" - xrenew "xianyu-go/internal/xianyu/renew" ) // mountCookies 账号 cookie 管理端点。 @@ -45,47 +42,18 @@ func (s *Server) mountCookies(r chi.Router) { func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) { // cid 保存cid,供当前处理流程使用 cid := chi.URLParam(r, "cid") - // ownedDetail、ok 保存ownedDetail、ok,供当前处理流程使用 + // ownedDetail、ok 保存账号摘要和归属校验结果。 ownedDetail, ok := s.requireCookieOwner(w, r, cid) if !ok { return } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.Store.LockAccountCredentials(cid) - // detail、err 保存detail、err,供当前处理流程使用 - detail, err := s.loadCookiePlatformDetail(r.Context(), cid) - if err != nil || detail == nil || detail.UserID != ownedDetail.UserID { - credentialUnlock() - writeErr(w, http.StatusNotFound, "账号不存在") + // result 保存应用服务返回的不含凭证的长登录状态。 + result, err := s.accountLongLoginApplication().Query(r.Context(), ownedDetail.UserID, cid) + if err != nil { + s.writeLongLoginError(w, err) return } - // requestCookies 保存请求Cookies,供当前处理流程使用 - requestCookies := scopedCookieHeader(detail, xrenew.QueryLoginSettingsURL) - // result 保存结果,供当前处理流程使用 - var result *xrenew.LongLoginSettings - // requestErr 保存请求Err,供当前处理流程使用 - var requestErr error - if // snapshot、complete 保存snapshot、complete,供当前处理流程使用 - snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete { - result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies, snapshot) - } else { - result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies) - } - // credentialChanged、persistErr 保存credentialChanged、persistErr,供当前处理流程使用 - credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL) - credentialUnlock() - if persistErr != nil { - writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败") - return - } - if credentialChanged { - s.updateRunningCookie(r.Context(), cid, result.NewCookies) - } - if requestErr != nil { - writeErr(w, http.StatusBadGateway, requestErr.Error()) - return - } - writeJSON(w, http.StatusOK, result) + writeJSON(w, http.StatusOK, longLoginResponse{CanOpenLongLogin: result.CanOpenLongLogin, Enabled: result.Enabled}) } // setLongLoginSettings 负责setLong登录设置相关处理。 @@ -106,98 +74,30 @@ func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.Store.LockAccountCredentials(cid) - // detail、err 保存detail、err,供当前处理流程使用 - detail, err := s.loadCookiePlatformDetail(r.Context(), cid) - if err != nil || detail == nil || detail.UserID != ownedDetail.UserID { - credentialUnlock() + // result 保存应用服务返回的不含凭证的长登录状态。 + result, err := s.accountLongLoginApplication().Set(r.Context(), ownedDetail.UserID, cid, *req.Enabled) + if err != nil { + s.writeLongLoginError(w, err) + return + } + writeJSON(w, http.StatusOK, longLoginResponse{CanOpenLongLogin: result.CanOpenLongLogin, Enabled: result.Enabled}) +} + +// writeLongLoginError 将长登录应用错误映射为兼容现有客户端的 HTTP 状态。 +func (s *Server) writeLongLoginError(w http.ResponseWriter, err error) { + if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) || errors.Is(err, accountapp.ErrCredentialNotFound) { writeErr(w, http.StatusNotFound, "账号不存在") return } - // requestCookies 保存请求Cookies,供当前处理流程使用 - requestCookies := scopedCookieHeader(detail, xrenew.SetLoginSettingsURL) - // result 保存结果,供当前处理流程使用 - var result *xrenew.LongLoginSettings - // requestErr 保存请求Err,供当前处理流程使用 - var requestErr error - if // snapshot、complete 保存snapshot、complete,供当前处理流程使用 - snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete { - result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled, snapshot) - } else { - result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled) - } - // credentialChanged、persistErr 保存credentialChanged、persistErr,供当前处理流程使用 - credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL) - credentialUnlock() - if persistErr != nil { - writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败") + if errors.Is(err, accountapp.ErrLongLoginPlatform) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + writeErr(w, http.StatusBadGateway, err.Error()) return } - if credentialChanged { - s.updateRunningCookie(r.Context(), cid, result.NewCookies) - } - if requestErr != nil { - writeErr(w, http.StatusBadGateway, requestErr.Error()) + if strings.Contains(err.Error(), "平台") || strings.Contains(err.Error(), "HTTP") { + writeErr(w, http.StatusBadGateway, err.Error()) return } - writeJSON(w, http.StatusOK, result) -} - -// persistLongLoginCookies 必须在账号凭证锁内调用。它只更新持久化状态; -// 运行中实例的 Cookie 更新必须等调用方释放凭证锁后再执行。 -// persistLongLoginCookies 负责persistLong登录Cookies相关处理。 -func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) (bool, error) { - if result == nil || detail == nil { - return false, nil - } - // metadata 保存metadata,供当前处理流程使用 - metadata := detail.MetadataJSON - // snapshot、hasSnapshot 保存snapshot、hasSnapshot,供当前处理流程使用 - snapshot, hasSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) - if result.CookieSnapshotComplete { - snapshot = cookierefresh.NormalizeSnapshot(result.CookieSnapshot) - if snapshot == nil { - snapshot = []cookierefresh.BrowserCookie{} - } - result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest( - snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(), - ) - metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) - } else if hasSnapshot { - // 兼容非标准 Service 实现:只有未返回最终 Jar 时才按当前请求 URL - // 应用响应头;官方 Service 会在 SET→QUERY 间逐请求维护完整 Jar。 - snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), "https://goofish.com") - if snapshot == nil { - snapshot = []cookierefresh.BrowserCookie{} - } - result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest( - snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(), - ) - metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) - } else { - // 历史账号只有扁平 Cookie 时只能合并兼容值,不能凭空推断完整 - // Domain/Path/HttpOnly/PartitionKey 属性。 - result.NewCookies = xrenew.MergeSetCookies(detail.Value, result.SetCookies) - metadata = cookierefresh.MetadataWithoutSnapshot(metadata) - } - // credentialChanged 保存credentialChanged,供当前处理流程使用 - credentialChanged := result.NewCookies != detail.Value || metadata != detail.MetadataJSON - if !credentialChanged && len(result.SetCookies) == 0 { - return false, nil - } - if // err 保存err,供当前处理流程使用 - err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil { - s.Logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", err) - return false, err - } - if credentialChanged && s.Store.Tokens != nil { - if // err 保存err,供当前处理流程使用 - err := s.Store.Tokens.Clear(ctx, detail.ID); err != nil { - s.Logger.Warn("长登录 Cookie 保存后清理旧连接凭证失败", "cookie_id", detail.ID, "err", err) - } - } - return credentialChanged, nil + writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败") } // updateRunningCookie 负责updateRunning登录凭证相关处理。 @@ -216,30 +116,20 @@ func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string // wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。 func (s *Server) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) { - if s == nil || s.Store == nil || s.Store.Automation == nil { + if s == nil { + return + } + // service 提供凭证恢复后的自动化任务唤醒能力。 + service := s.credentialWakeApplication() + if service == nil { return } if // err 保存err,供当前处理流程使用 - err := s.Store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil { + err := service.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil { s.Logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err) } } -// scopedCookieHeader 负责scoped登录凭证Header相关处理。 -func scopedCookieHeader(detail *db.CookieDetail, requestURL string) string { - if detail == nil { - return "" - } - if // snapshot、ok 保存snapshot、ok,供当前处理流程使用 - snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok { - if // header、authoritative 保存header、authoritative,供当前处理流程使用 - header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now()); authoritative { - return header - } - } - return detail.Value -} - // updateCookieSettingsRequest 保存update登录凭证设置请求,供当前处理流程使用 type updateCookieSettingsRequest struct { Cookie *string `json:"cookie"` @@ -258,7 +148,7 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) { // cid 保存cid,供当前处理流程使用 cid := chi.URLParam(r, "cid") // detail、ok 保存detail、ok,供当前处理流程使用 - detail, ok := s.requireCookieSecretOwner(w, r, cid) + ownedDetail, ok := s.requireCookieOwner(w, r, cid) if !ok { return } @@ -286,91 +176,49 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) { return } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.Store.LockAccountCredentials(cid) - // latestDetail、err 保存latestDetail、err,供当前处理流程使用 - latestDetail, err := s.Store.Cookies.GetDetails(r.Context(), cid) - if err != nil || latestDetail == nil || latestDetail.UserID != detail.UserID { - credentialUnlock() - writeErr(w, http.StatusNotFound, "账号不存在") - return + // password 保存待写入的登录密码;nil 表示保留已有密码,空字符串指令表示清除密码。 + var password *string + if req.LoginPassword != nil && *req.LoginPassword != "" { + password = req.LoginPassword } - detail = latestDetail - - // input 保存input,供当前处理流程使用 - input := db.AccountSettingsUpdate{ - UserID: detail.UserID, - Value: req.Cookie, - Remark: req.Remark, - AutoConfirm: req.AutoConfirm, - PauseDuration: req.PauseDuration, - ChannelIDs: req.ChannelIDs, + if req.ClearPassword { + // clearedPassword 是明确清除登录密码的空值指令,不读取既有秘密。 + clearedPassword := "" + password = &clearedPassword } - // loginChanged 保存登录Changed,供当前处理流程使用 - loginChanged := req.Username != nil || req.LoginPassword != nil || req.ShowBrowser != nil || req.ClearPassword - if loginChanged { - // username 保存username,供当前处理流程使用 - username := detail.Username - if req.Username != nil { - username = *req.Username - } - // password 保存密码,供当前处理流程使用 - password := detail.Password - if req.LoginPassword != nil && *req.LoginPassword != "" { - password = *req.LoginPassword - } - if req.ClearPassword { - password = "" - } - // showBrowser 保存show浏览器,供当前处理流程使用 - showBrowser := detail.ShowBrowser - if req.ShowBrowser != nil { - showBrowser = *req.ShowBrowser - } - input.Username = &username - input.Password = &password - input.ShowBrowser = &showBrowser - } - // pausedUntil、err 保存pausedUntil、err,供当前处理流程使用 - pausedUntil, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, input) + // settingsResult、err 保存应用服务返回的暂停截止时间、补偿错误和主写入错误。 + settingsResult, err := s.accountSettingsApplication().UpdateSettings(r.Context(), accountapp.SettingsUpdateInput{ + UserID: ownedDetail.UserID, AccountID: cid, Cookie: req.Cookie, Remark: req.Remark, + AutoConfirm: req.AutoConfirm, PauseDuration: req.PauseDuration, Username: req.Username, + Password: password, ShowBrowser: req.ShowBrowser, ChannelIDs: req.ChannelIDs, + }) if err != nil { - credentialUnlock() switch { - case errors.Is(err, db.ErrForbidden): + case errors.Is(err, accountapp.ErrForbidden): writeErr(w, http.StatusForbidden, "账号设置包含无权限使用的资源") - case errors.Is(err, db.ErrNotFound): + case errors.Is(err, accountapp.ErrNotFound): writeErr(w, http.StatusNotFound, "账号不存在") default: writeErr(w, http.StatusBadRequest, err.Error()) } return } - if req.Cookie != nil { - // UpdateSettings 已在同一事务中写入 Cookie 并清除旧快照,不能再做 - // 第二次非原子覆盖。 - if s.Store.Tokens != nil { - if // err 保存err,供当前处理流程使用 - err := s.Store.Tokens.Clear(r.Context(), cid); err != nil { - s.Logger.Warn("账号设置保存后清理旧连接凭证失败", "cookie_id", cid, "err", err) - } - } + if settingsResult.TokenCleanupError != nil && s.Logger != nil { + s.Logger.Warn("账号设置保存后清理旧连接凭证失败", "cookie_id", cid, "err", settingsResult.TokenCleanupError) } - credentialUnlock() - if req.Cookie != nil && s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) { - if // err 保存err,供当前处理流程使用 - err := s.Manager.Restart(r.Context(), cid); err != nil { - s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", err) - } + if settingsResult.RuntimeError != nil && s.Logger != nil { + s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", settingsResult.RuntimeError) } writeJSON(w, http.StatusOK, cookieSettingsResponse{ - Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(), + Success: true, PausedUntil: settingsResult.PausedUntil, Paused: settingsResult.PausedUntil > time.Now().UTC().Unix(), }) } // listCookieRuntimeStatus 返回本地账号引擎状态,不请求闲鱼 API,可安全用于前端轮询。 func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) { - sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 - cookieIDs, err := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 和 err 是账号 ID 列表及查询错误。 + sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 + accountSummary := s.accountSummaryApplication() + cookieIDs, err := accountSummary.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 和 err 是账号 ID 列表及查询错误。 if err != nil { writeErr(w, http.StatusInternalServerError, "获取账号失败") return @@ -381,7 +229,8 @@ func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) } result := make(map[string]engine.RuntimeStatus, len(cookieIDs)) // result 是返回给前端的状态映射。 for _, cid := range cookieIDs { // cid 是当前账号 ID。 - if !s.Store.Cookies.GetStatus(r.Context(), cid) { + enabled, statusErr := accountSummary.StatusOwned(r.Context(), sess.UserID, cid) + if statusErr != nil || !enabled { result[cid] = engine.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()} continue } @@ -396,8 +245,8 @@ func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) // listCookies 列出当前用户的 cookie_id。 func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) { - sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 - ids, err := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // ids 和 err 是账号 ID 列表及查询错误。 + sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 + ids, err := s.accountSummaryApplication().ListOwnedIDs(r.Context(), sess.UserID) // ids 和 err 是账号 ID 列表及查询错误。 if err != nil { writeErrRequest(w, r, http.StatusInternalServerError, "获取账号失败") return @@ -407,19 +256,30 @@ func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) { // listCookieDetails 账号非敏感详情(不含 cookie 明文/密码,遵循 Fork 安全基线)。 func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) { - sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 - summaries, err := s.Store.Cookies.ListSummaries(r.Context(), sess.UserID) // summaries 和 err 是账号摘要及查询错误。 + sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 + summaries, err := s.accountSummaryApplication().ListSummaries(r.Context(), sess.UserID) // summaries 和 err 是账号摘要及查询错误。 if err != nil { writeErrRequest(w, r, http.StatusInternalServerError, "获取账号失败") return } result := make([]cookieSummaryResponse, 0, len(summaries)) // result 是非敏感详情响应列表。 for _, summary := range summaries { // summary 是当前账号的非敏感摘要。 - tasks, _ := s.Store.AccountTasks.Get(r.Context(), summary.ID) // tasks 是当前账号的自动化任务设置。 + // tasks 保存通过账号任务应用 Port 读取的非敏感任务设置。 + tasks := automationapp.AccountTaskSettings{CookieID: summary.ID} + // service 提供账号任务设置的应用层查询能力。 + if service := s.accountTaskApplication(); service != nil { + // loadedTasks、taskErr 保存应用层任务设置及读取错误;旧接口读取失败时仍保留默认值。 + loadedTasks, taskErr := service.GetSettings(r.Context(), summary.ID) + if taskErr == nil { + tasks = loadedTasks + } + } + // enabled、statusErr 保存当前账号启用状态及查询错误。 + enabled, statusErr := s.accountSummaryApplication().StatusOwned(r.Context(), sess.UserID, summary.ID) result = append(result, cookieSummaryResponse{ ID: summary.ID, HasCookie: true, - Enabled: s.Store.Cookies.GetStatus(r.Context(), summary.ID), + Enabled: statusErr == nil && enabled, AutoConfirm: summary.AutoConfirm, Remark: summary.Remark, PauseDuration: summary.PauseDuration, @@ -447,16 +307,27 @@ func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) { // getCookieDetails 单个账号非敏感详情。 func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) { - cid := chi.URLParam(r, "cid") // cid 是请求路径中的账号 ID。 - sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 - summary, err := s.Store.Cookies.GetSummaryOwned(r.Context(), sess.UserID, cid) // summary 和 err 是账号摘要及查询错误。 + cid := chi.URLParam(r, "cid") // cid 是请求路径中的账号 ID。 + sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。 + summary, err := s.accountSummaryApplication().GetOwnedSummary(r.Context(), sess.UserID, cid) // summary 和 err 是账号摘要及查询错误。 if err != nil { writeErr(w, http.StatusForbidden, "无权限操作该Cookie") return } - tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid) // tasks 是当前账号的自动化任务设置。 + // tasks 保存通过账号任务应用 Port 读取的非敏感任务设置。 + tasks := automationapp.AccountTaskSettings{CookieID: cid} + // service 提供账号任务设置的应用层查询能力。 + if service := s.accountTaskApplication(); service != nil { + // loadedTasks、taskErr 保存应用层任务设置及读取错误;旧接口读取失败时仍保留默认值。 + loadedTasks, taskErr := service.GetSettings(r.Context(), cid) + if taskErr == nil { + tasks = loadedTasks + } + } + // enabled、statusErr 保存当前账号启用状态及查询错误。 + enabled, statusErr := s.accountSummaryApplication().StatusOwned(r.Context(), sess.UserID, cid) writeJSON(w, http.StatusOK, cookieDetailResponse{ - ID: summary.ID, Enabled: s.Store.Cookies.GetStatus(r.Context(), cid), AutoConfirm: summary.AutoConfirm, + ID: summary.ID, Enabled: statusErr == nil && enabled, AutoConfirm: summary.AutoConfirm, Remark: summary.Remark, PauseDuration: summary.PauseDuration, PausedUntil: summary.PausedUntil, Paused: summary.PausedUntil > time.Now().UTC().Unix(), ShowBrowser: summary.ShowBrowser, Username: summary.Username, Nickname: cachedCookieSummaryNickname(summary), AvatarURL: summary.AvatarURL, @@ -540,11 +411,11 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) { sess := auth.SessionFromContext(r.Context()) if // err 保存err,供当前处理流程使用 err := s.accountLoginApplication().CreateCookie(r.Context(), accountLoginInput{AccountID: req.ID, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil { - if errors.Is(err, db.ErrForbidden) { + if errors.Is(err, accountapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户") return } - if errors.Is(err, db.ErrAlreadyExists) { + if errors.Is(err, accountapp.ErrAlreadyExists) { writeErr(w, http.StatusConflict, "该账号ID已存在,请使用更新账号功能") return } @@ -588,7 +459,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusConflict, err.Error()) return } - if errors.Is(err, db.ErrForbidden) { + if errors.Is(err, accountapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权限操作该账号") return } @@ -602,8 +473,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) { func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) { // cid 保存cid,供当前处理流程使用 cid := chi.URLParam(r, "cid") - // detail、ok 保存detail、ok,供当前处理流程使用 - detail, ok := s.requireCookieSecretOwner(w, r, cid) + // detail、ok 保存非敏感账号摘要和归属校验结果。 + detail, ok := s.requireCookieOwner(w, r, cid) if !ok { return } @@ -620,18 +491,20 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // password 保存密码,供当前处理流程使用 - password := req.Password - if password == "" { - password = req.LoginPassword + // password 保存待写入的登录密码;nil 表示兼容地保留既有密码。 + passwordValue := req.Password + if passwordValue == "" { + passwordValue = req.LoginPassword } - if req.ClearPassword { - password = "" - } else if password == "" && detail != nil { - password = detail.Password + // password 保存可选登录密码指针;nil 表示保留数据库中的既有秘密。 + var password *string + if passwordValue != "" || req.ClearPassword { + password = &passwordValue } - if // err 保存err,供当前处理流程使用 - err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil { + // err 保存应用层登录信息写入错误。 + if err := s.accountSettingsApplication().UpdateLoginInfo(r.Context(), accountapp.LoginInfoUpdateInput{ + UserID: detail.UserID, AccountID: cid, Username: req.Username, Password: password, ShowBrowser: req.ShowBrowser, + }); err != nil { writeErr(w, http.StatusInternalServerError, "更新失败") return } @@ -656,40 +529,22 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // reason 保存原因,供当前处理流程使用 - reason := "" - if !req.Enabled { - reason = db.DisableReasonManual - } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.Store.LockAccountCredentials(cid) - // latest、err 保存latest、err,供当前处理流程使用 - latest, err := s.loadCookiePlatformDetail(r.Context(), cid) - if err != nil || latest == nil || latest.UserID != ownedDetail.UserID { - credentialUnlock() - writeErr(w, http.StatusNotFound, "账号不存在") - return - } - if // err 保存err,供当前处理流程使用 - err := s.Store.Cookies.SetStatusWithReason(r.Context(), cid, req.Enabled, reason); err != nil { - credentialUnlock() + // result、err 保存应用层启停结果和持久化错误。 + result, err := s.accountSettingsApplication().SetStatus(r.Context(), ownedDetail.UserID, cid, req.Enabled) + if err != nil { + if errors.Is(err, accountapp.ErrForbidden) { + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return + } + if errors.Is(err, accountapp.ErrNotFound) { + writeErr(w, http.StatusNotFound, "账号不存在") + return + } writeErr(w, http.StatusInternalServerError, "更新失败") return } - credentialUnlock() - // 启停引擎实例。 - if s.Manager != nil { - if req.Enabled { - // 重启拉取最新 cookie。 - if _, e := s.loadCookiePlatformDetail(r.Context(), cid); e == nil { - if // err 保存err,供当前处理流程使用 - err := s.Manager.Restart(r.Context(), cid); err != nil { - s.Logger.Error("启用后重启账号失败", "cookie_id", cid, "err", err) - } - } - } else { - s.Manager.Stop(cid) - } + if result.RuntimeError != nil && s.Logger != nil { + s.Logger.Error("启停账号运行实例失败", "cookie_id", cid, "err", result.RuntimeError) } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } @@ -725,7 +580,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusForbidden, "无权限操作该账号") return } - if errors.Is(deleteErr, accountapp.ErrNotFound) || errors.Is(deleteErr, db.ErrNotFound) { + if errors.Is(deleteErr, accountapp.ErrNotFound) { writeErr(w, http.StatusNotFound, "账号不存在") return } @@ -735,7 +590,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) { } s.Logger.Info("账号已删除", "cookie_id", cid, - "nickname", cachedAccountNickname(ownedDetail), + "nickname", cachedAccountSummaryNickname(ownedDetail), "user_id", ownedDetail.UserID, ) writeJSON(w, http.StatusOK, operationResponse{Success: true}) @@ -757,12 +612,14 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。 + // sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。 sess := authSess(r) - if // err 保存err,供当前处理流程使用 - _, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{ - UserID: sess.UserID, AutoConfirm: &req.AutoConfirm, - }); err != nil { + if // err 保存应用层自动确认设置错误。 + _, err := s.accountSettingsApplication().SetAutoConfirm(r.Context(), sess.UserID, cid, req.AutoConfirm); err != nil { + if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) { + writeErr(w, http.StatusForbidden, "无权操作该账号") + return + } writeErr(w, http.StatusInternalServerError, "保存自动确认设置失败") return } @@ -797,12 +654,14 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。 + // sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。 sess := authSess(r) - if // err 保存err,供当前处理流程使用 - _, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{ - UserID: sess.UserID, Remark: &req.Remark, - }); err != nil { + if // err 保存应用层账号备注错误。 + _, err := s.accountSettingsApplication().SetRemark(r.Context(), sess.UserID, cid, req.Remark); err != nil { + if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) { + writeErr(w, http.StatusForbidden, "无权操作该账号") + return + } writeErr(w, http.StatusInternalServerError, "保存账号备注失败") return } @@ -829,14 +688,20 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request) writeErr(w, http.StatusBadRequest, "暂停时长必须在 0 到 1440 分钟之间") return } - // pausedUntil、err 保存pausedUntil、err,供当前处理流程使用 - pausedUntil, err := s.Store.Cookies.SetPause(r.Context(), cid, req.PauseDuration) + // sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。 + sess := authSess(r) + // result、err 保存应用层暂停设置结果和错误。 + result, err := s.accountSettingsApplication().SetPause(r.Context(), sess.UserID, cid, req.PauseDuration) if err != nil { + if errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrNotFound) { + writeErr(w, http.StatusForbidden, "无权操作该账号") + return + } writeErr(w, http.StatusInternalServerError, "保存暂停时长失败") return } writeJSON(w, http.StatusOK, cookieSettingsResponse{ - Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(), + Success: true, PausedUntil: result.PausedUntil, Paused: result.PausedUntil > time.Now().UTC().Unix(), }) } @@ -847,117 +712,24 @@ func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request) if !s.requireCookieOwnership(w, r, cid) { return } - // paused、pausedUntil 保存paused、pausedUntil,供当前处理流程使用 - paused, pausedUntil, _ := s.Store.Cookies.IsPaused(r.Context(), cid) + // sess 是当前请求的认证会话,用于让应用服务再次确认账号归属。 + sess := authSess(r) + // pauseState 保存应用层返回的非敏感暂停状态。 + pauseState, _ := s.accountSettingsApplication().GetPause(r.Context(), sess.UserID, cid) writeJSON(w, http.StatusOK, pauseDurationResponse{ - PauseDuration: s.Store.Cookies.GetPauseDuration(r.Context(), cid), PausedUntil: pausedUntil, Paused: paused, + PauseDuration: pauseState.Duration, PausedUntil: pauseState.PausedUntil, Paused: pauseState.Paused, }) } -// refreshAccountProfile 刷新账号平台资料并返回展示字段。 -// 该流程按需读取平台凭证,调用方负责所有权校验。 -// refreshAccountProfile 负责refresh账号Profile相关处理。 -func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail) (string, string, string) { - if d == nil { - return "", "", "" +// cachedAccountSummaryNickname 从非敏感应用摘要生成删除日志展示名,不构造或读取数据库凭证模型。 +func cachedAccountSummaryNickname(summary accountapp.AccountSummary) string { + if strings.TrimSpace(summary.Remark) != "" { + return strings.TrimSpace(summary.Remark) } - if s.MTop == nil { - return cachedAccountNickname(d), d.AvatarURL, "账号资料客户端未初始化" + if strings.TrimSpace(summary.Nickname) != "" { + return strings.TrimSpace(summary.Nickname) } - - // repository 提供资料刷新所需的凭证锁、平台视图和资料持久化能力。 - repository := s.accountLoginRepositoryForServer() - if repository == nil { - return cachedAccountNickname(d), d.AvatarURL, "账号登录持久化未初始化" - } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := repository.LockCredentials(d.ID) - // latest、latestErr 保存latest、latestErr,供当前处理流程使用 - latest, latestErr := repository.LoadPlatformDetail(ctx, d.ID) - if latestErr != nil || latest == nil || latest.UserID != d.UserID { - credentialUnlock() - if latestErr == nil { - latestErr = db.ErrNotFound - } - return cachedAccountNickname(d), d.AvatarURL, truncate(latestErr.Error(), 180) - } - // mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用 - mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest) - // profile、callErr 保存profile、callErr,供当前处理流程使用 - profile, callErr := s.MTop.FetchUserProfile(mtopCtx, latest.Value) - // runtimeCookie 保存runtime登录凭证,供当前处理流程使用 - runtimeCookie := "" - // runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用 - runtimeCookieChanged := false - // value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用 - value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession) - if persistErr != nil { - if s.Logger != nil { - s.Logger.Warn("保存账号资料响应 Cookie Jar 失败", "account", d.ID, "err", persistErr) - } - callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", persistErr)) - } else if handled { - if valueChanged { - runtimeCookie = value - runtimeCookieChanged = true - } - d.Value = value - } else if callErr == nil && profile != nil && profile.UpdatedCookies != "" && profile.UpdatedCookies != latest.Value { - // 注入 mock 或没有权威快照的历史账号继续沿用扁平 Cookie 路径; - // 该路径必须清除旧 snapshot,不能伪造完整 Jar。 - if // err 保存err,供当前处理流程使用 - err := repository.UpdateFlatCookieOwned(ctx, latest, profile.UpdatedCookies); err != nil { - if s.Logger != nil { - s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err) - } - callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", err)) - } else { - runtimeCookie = profile.UpdatedCookies - runtimeCookieChanged = true - d.Value = profile.UpdatedCookies - } - } - credentialUnlock() - if runtimeCookieChanged { - s.updateRunningCookie(ctx, d.ID, runtimeCookie) - } - if callErr != nil { - s.recoverExpiredMTOPSession(ctx, d.ID, callErr) - if s.Logger != nil { - s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", callErr) - } - return cachedAccountNickname(d), d.AvatarURL, truncate(callErr.Error(), 180) - } - if profile == nil { - return cachedAccountNickname(d), d.AvatarURL, "账号资料接口未返回结果" - } - - // apiNickname 保存apiNickname,供当前处理流程使用 - apiNickname := strings.TrimSpace(profile.Nickname) - // apiAvatarURL 保存apiAvatarURL,供当前处理流程使用 - apiAvatarURL := normalizeProfileAvatarURL(profile.AvatarURL) - if // err 保存err,供当前处理流程使用 - err := repository.UpdateProfile(ctx, d.ID, apiNickname, apiAvatarURL); err != nil && s.Logger != nil { - s.Logger.Warn("保存账号资料失败", "account", d.ID, "err", err) - } - if apiNickname == "" { - apiNickname = cachedAccountNickname(d) - } - if apiAvatarURL == "" { - apiAvatarURL = d.AvatarURL - } - return apiNickname, apiAvatarURL, "" -} - -// cachedAccountNickname 负责cached账号Nickname相关处理。 -func cachedAccountNickname(d *db.CookieDetail) string { - if strings.TrimSpace(d.Remark) != "" { - return strings.TrimSpace(d.Remark) - } - if strings.TrimSpace(d.Nickname) != "" { - return strings.TrimSpace(d.Nickname) - } - return "账号 " + truncate(d.ID, 6) + return "账号 " + truncate(summary.ID, 6) } // normalizeProfileAvatarURL 负责normalizeProfileAvatarURL相关处理。 @@ -984,7 +756,7 @@ func truncate(s string, n int) string { } // cachedCookieSummaryNickname 根据账号摘要生成展示名称,不依赖敏感凭证字段。 -func cachedCookieSummaryNickname(summary db.CookieSummary) string { +func cachedCookieSummaryNickname(summary accountapp.AccountSummary) string { if strings.TrimSpace(summary.Remark) != "" { return strings.TrimSpace(summary.Remark) } diff --git a/internal/server/cookie_handlers_test.go b/internal/server/cookie_handlers_test.go index a803a72..827fccf 100644 --- a/internal/server/cookie_handlers_test.go +++ b/internal/server/cookie_handlers_test.go @@ -12,12 +12,24 @@ import ( "testing" "time" + accountapp "xianyu-go/internal/application/account" "xianyu-go/internal/automation" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/cookierefresh" xrenew "xianyu-go/internal/xianyu/renew" ) +// cachedAccountNickname 保留测试对账号展示名兼容规则的独立验证,不参与生产 HTTP 路径。 +func cachedAccountNickname(d *db.CookieDetail) string { + if strings.TrimSpace(d.Remark) != "" { + return strings.TrimSpace(d.Remark) + } + if strings.TrimSpace(d.Nickname) != "" { + return strings.TrimSpace(d.Nickname) + } + return "账号 " + truncate(d.ID, 6) +} + // seedStaleCookieSnapshot 负责seedStale登录凭证Snapshot相关处理。 func seedStaleCookieSnapshot(t *testing.T, store *db.Store, cookieID string) { t.Helper() @@ -1172,6 +1184,11 @@ func TestCachedAccountNickname(t *testing.T) { if got != c.want { t.Errorf("cachedAccountNickname(remark=%q,nick=%q,id=%q)=%q want %q", c.remark, c.nickname, c.id, got, c.want) } + // summaryGot 保存非敏感应用摘要生成的展示名,验证摘要边界与兼容模型保持同样的日志语义。 + summaryGot := cachedAccountSummaryNickname(accountapp.AccountSummary{ID: c.id, Nickname: c.nickname, Remark: c.remark}) + if summaryGot != c.want { + t.Errorf("cachedAccountSummaryNickname(remark=%q,nick=%q,id=%q)=%q want %q", c.remark, c.nickname, c.id, summaryGot, c.want) + } } } diff --git a/internal/server/default_reply_application.go b/internal/server/default_reply_application.go new file mode 100644 index 0000000..ad4764c --- /dev/null +++ b/internal/server/default_reply_application.go @@ -0,0 +1,9 @@ +package server + +import defaultreplyapp "xianyu-go/internal/application/defaultreply" + +// defaultReplyApplication 返回默认回复应用服务。 +// 该方法在主装配集合接入前提供同一 Port 的兼容构造入口,后续由统一装配复用实例。 +func (s *Server) defaultReplyApplication() *defaultreplyapp.Service { + return s.applicationServiceSet().defaultReplies +} diff --git a/internal/server/default_reply_handlers.go b/internal/server/default_reply_handlers.go index 5b477bd..daa522a 100644 --- a/internal/server/default_reply_handlers.go +++ b/internal/server/default_reply_handlers.go @@ -1,12 +1,13 @@ package server import ( + "errors" "net/http" "github.com/go-chi/chi/v5" + defaultreplyapp "xianyu-go/internal/application/defaultreply" "xianyu-go/internal/auth" - "xianyu-go/internal/db" ) // btoi bool→int(SQLite 无原生 bool)。 @@ -40,69 +41,94 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) { // getDefaultReply 负责getDefault回复相关处理。 func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 + // cid 是路径中的默认回复所属账号标识。 cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。 + userID, ok := defaultReplyUserID(w, r) + if !ok { return } - // dr、err 保存dr、err,供当前处理流程使用 - dr, err := s.Store.DefaultReps.Get(r.Context(), cid) - if err != nil { + // reply、err 保存应用服务返回的默认回复模型及读取错误。 + reply, err := s.defaultReplyApplication().Get(r.Context(), userID, cid) + switch { + case errors.Is(err, defaultreplyapp.ErrConfigNotFound): writeJSON(w, http.StatusOK, defaultReplyResponse{Enabled: false, ReplyContent: "", ReplyOnce: false}) return + case errors.Is(err, defaultreplyapp.ErrAccountNotFound): + writeErr(w, http.StatusNotFound, "账号不存在") + return + case errors.Is(err, defaultreplyapp.ErrForbidden): + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return + case err != nil: + writeErr(w, http.StatusInternalServerError, "查询失败") + return } // 已保存默认回复通过具名 DTO 返回,单账号查询不填充 cookie_id。 - writeJSON(w, http.StatusOK, newDefaultReplyResponse("", *dr)) + writeJSON(w, http.StatusOK, newDefaultReplyResponse("", reply)) } // setDefaultReply 保存指定账号的默认回复配置。 func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) { // cid 是当前操作的账号标识。 cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。 + userID, ok := defaultReplyUserID(w, r) + if !ok { return } // req 是默认回复配置请求体。 - var req struct { - Enabled bool `json:"enabled"` - ReplyContent string `json:"reply_content"` - ReplyImageURL string `json:"reply_image_url"` - ReplyOnce bool `json:"reply_once"` - } - // err 是请求体解码错误。 - if err := decodeJSON(r, &req); err != nil { + var req defaultReplyMutationRequest + // decodeErr 表示请求体不是有效的默认回复 JSON。 + if decodeErr := decodeJSON(r, &req); decodeErr != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // err 是默认回复写入错误。 - err := s.Store.DefaultReps.Upsert(r.Context(), cid, db.DefaultReply{ + // err 表示默认回复应用服务写入失败的原因。 + err := s.defaultReplyApplication().Upsert(r.Context(), userID, cid, defaultreplyapp.Reply{ Enabled: req.Enabled, ReplyContent: req.ReplyContent, ReplyImageURL: req.ReplyImageURL, ReplyOnce: req.ReplyOnce, }) if err != nil { - writeErr(w, http.StatusInternalServerError, "保存失败") + writeDefaultReplyMutationError(w, err, "保存失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } +// defaultReplyMutationRequest 是默认回复配置写入接口的具名请求 DTO。 +type defaultReplyMutationRequest struct { + // Enabled 表示是否启用默认回复。 + Enabled bool `json:"enabled"` + // ReplyContent 是默认回复文字内容。 + ReplyContent string `json:"reply_content"` + // ReplyImageURL 是默认回复图片地址。 + ReplyImageURL string `json:"reply_image_url"` + // ReplyOnce 表示同一聊天是否只发送一次默认回复。 + ReplyOnce bool `json:"reply_once"` +} + // listDefaultReplies 查询当前用户的默认回复列表。 func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) { // sess 是当前登录用户会话。 sess := auth.SessionFromContext(r.Context()) - // rows 和 err 是当前用户的默认回复列表及查询错误。 - rows, err := s.Store.DefaultReps.ListForUser(r.Context(), sess.UserID) + if sess == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") + return + } + // rows 和 err 是当前用户的应用层默认回复列表及查询错误。 + rows, err := s.defaultReplyApplication().List(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return } // out 是默认回复列表响应。 var out []defaultReplyResponse - // row 表示当前遍历过程中的row + // row 表示当前遍历过程中的应用层默认回复摘要。 for _, row := range rows { out = append(out, defaultReplyResponse{ - CookieID: row.CookieID, Enabled: row.Enabled, ReplyContent: row.ReplyContent, ReplyOnce: row.ReplyOnce, - ReplyImageURL: row.ReplyImageURL, + CookieID: row.CookieID, Enabled: row.Reply.Enabled, ReplyContent: row.Reply.ReplyContent, + ReplyOnce: row.Reply.ReplyOnce, ReplyImageURL: row.Reply.ReplyImageURL, // 列表 DTO 保留账号标识,前端可直接建立按账号索引。 }) } @@ -113,22 +139,26 @@ func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) { func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) { // sess 是当前登录用户会话。 sess := auth.SessionFromContext(r.Context()) - // rows 和 err 是当前用户的默认回复列表及查询错误。 - rows, err := s.Store.DefaultReps.ListForUser(r.Context(), sess.UserID) + if sess == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") + return + } + // rows 和 err 是当前用户的应用层默认回复列表及查询错误。 + rows, err := s.defaultReplyApplication().List(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return } // out 是按账号标识索引的默认回复映射。 out := make(map[string]defaultReplyResponse) - // row 表示当前遍历过程中的row + // row 表示当前遍历过程中的应用层默认回复摘要。 for _, row := range rows { out[row.CookieID] = defaultReplyResponse{ CookieID: row.CookieID, - Enabled: row.Enabled, - ReplyContent: row.ReplyContent, - ReplyOnce: row.ReplyOnce, - ReplyImageURL: row.ReplyImageURL, + Enabled: row.Reply.Enabled, + ReplyContent: row.Reply.ReplyContent, + ReplyOnce: row.Reply.ReplyOnce, + ReplyImageURL: row.Reply.ReplyImageURL, // map 键与 cookie_id 同时保留,兼容旧前端索引方式。 } } @@ -139,13 +169,15 @@ func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) { func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) { // cid 是当前操作的账号标识。 cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。 + userID, ok := defaultReplyUserID(w, r) + if !ok { return } - // err 是默认回复删除错误。 - err := s.Store.DefaultReps.Delete(r.Context(), cid) + // err 表示默认回复应用服务删除失败的原因。 + err := s.defaultReplyApplication().Delete(r.Context(), userID, cid) if err != nil { - writeErr(w, http.StatusInternalServerError, "删除失败") + writeDefaultReplyMutationError(w, err, "删除失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) @@ -155,13 +187,38 @@ func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) { func (s *Server) clearDefaultReplyRecords(w http.ResponseWriter, r *http.Request) { // cid 是当前操作的账号标识。 cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // userID 表示认证会话中的当前用户,缺失会话时请求不具备业务身份。 + userID, ok := defaultReplyUserID(w, r) + if !ok { return } - // err 是默认回复记录清理错误。 - if err := s.Store.DefaultReps.ClearRecords(r.Context(), cid); err != nil { - writeErr(w, http.StatusInternalServerError, "清空失败") + // err 表示默认回复应用服务清理投递记录失败的原因。 + if err := s.defaultReplyApplication().ClearRecords(r.Context(), userID, cid); err != nil { + writeDefaultReplyMutationError(w, err, "清空失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } + +// defaultReplyUserID 从认证上下文读取当前用户,并统一处理缺失会话。 +func defaultReplyUserID(w http.ResponseWriter, r *http.Request) (int64, bool) { + // session 是认证中间件写入请求上下文的当前用户会话。 + session := auth.SessionFromContext(r.Context()) + if session == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") + return 0, false + } + return session.UserID, true +} + +// writeDefaultReplyMutationError 将默认回复应用错误映射为既有 HTTP 错误语义。 +func writeDefaultReplyMutationError(w http.ResponseWriter, err error, fallback string) { + switch { + case errors.Is(err, defaultreplyapp.ErrAccountNotFound): + writeErr(w, http.StatusNotFound, "账号不存在") + case errors.Is(err, defaultreplyapp.ErrForbidden): + writeErr(w, http.StatusForbidden, "无权限操作该账号") + default: + writeErr(w, http.StatusInternalServerError, fallback) + } +} diff --git a/internal/server/extras_test.go b/internal/server/extras_test.go index f7d8823..ac7462d 100644 --- a/internal/server/extras_test.go +++ b/internal/server/extras_test.go @@ -474,7 +474,7 @@ func TestOrderImportReportsPartialFailure(t *testing.T) { // TestAdminEndpoints 管理员统计 + 用户列表 + 非 admin 被拒。 func TestAdminEndpoints(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // h 保存h,供当前处理流程使用 h := srv.Router() @@ -512,7 +512,7 @@ func TestAdminEndpoints(t *testing.T) { } // 创建普通用户验证 admin 隔离。 - srv.Store.Users.Create(context.Background(), "user2", "u2@e.com", "pw") + store.Users.Create(context.Background(), "user2", "u2@e.com", "pw") // 普通用户不应能访问 admin(需单独登录验证,此处仅验证 admin 能看到)。 req3 := httptest.NewRequest(http.MethodGet, "/admin/users", nil) req3.AddCookie(cookie) diff --git a/internal/server/handler_errors_test.go b/internal/server/handler_errors_test.go index 8dbb06c..cb2e118 100644 --- a/internal/server/handler_errors_test.go +++ b/internal/server/handler_errors_test.go @@ -145,13 +145,13 @@ func TestProtectedEndpointsRequireAuth(t *testing.T) { // TestAdminEndpointRejectsNonAdmin 非 admin 用户访问管理端点应 403。 func TestAdminEndpointRejectsNonAdmin(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // h 保存h,供当前处理流程使用 h := srv.Router() // 创建普通用户并登录。 - srv.Store.Users.Create(context.Background(), "user2", "u2@e.com", "pw") + store.Users.Create(context.Background(), "user2", "u2@e.com", "pw") // body 保存请求体,供当前处理流程使用 body := `{"username":"user2","password":"pw"}` // req 保存req,供当前处理流程使用 diff --git a/internal/server/handlers_extra_test.go b/internal/server/handlers_extra_test.go index be9b933..ead65be 100644 --- a/internal/server/handlers_extra_test.go +++ b/internal/server/handlers_extra_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + itemapp "xianyu-go/internal/application/items" "xianyu-go/internal/db" ) @@ -207,14 +208,14 @@ func TestPublicHTTPClient(t *testing.T) { // TestPublishBatchToMap 批次转具名 DTO 序列化并校验状态计数。 func TestPublishBatchToMap(t *testing.T) { // batch 保存批次,供当前处理流程使用 - batch := &db.ItemPublishBatch{ID: "b1", Status: "running", Filename: "x.csv"} + batch := itemapp.BatchInfo{ID: "b1", Status: "running", Filename: "x.csv"} // rows 保存rows,供当前处理流程使用 - rows := []db.ItemPublishBatchRow{ + rows := []itemapp.BatchRow{ {ID: 1, RowNo: 1, CookieID: "c1", Title: "t1", Status: "pending", ImagesJSON: `["a.png"]`}, {ID: 2, RowNo: 2, CookieID: "c1", Title: "t2", Status: "running"}, } // m 保存m,供当前处理流程使用 - m := publishBatchToMap(batch, rows) + m := publishBatchApplicationToResponse(batch, rows) if m.ID != "b1" || m.Status != "running" { t.Fatalf("batch 字段异常: %+v", m) } diff --git a/internal/server/http_client_test.go b/internal/server/http_client_test.go deleted file mode 100644 index cfb87d0..0000000 --- a/internal/server/http_client_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package server - -import ( - "net/http" - "time" -) - -// init 负责init相关处理。 -func init() { - // 服务器单测通过 httptest 模拟 AI 端点;生产构造器仍使用 netguard。 - newSettingsOutboundHTTPClient = func(string) (*http.Client, error) { - return &http.Client{Timeout: 20 * time.Second}, nil - } -} diff --git a/internal/server/item_batch_local_application.go b/internal/server/item_batch_local_application.go new file mode 100644 index 0000000..6169c7e --- /dev/null +++ b/internal/server/item_batch_local_application.go @@ -0,0 +1,26 @@ +package server + +import ( + "context" + + itemapp "xianyu-go/internal/application/items" +) + +// newBatchLocalPublishService 返回构造阶段已完成依赖校验的批量本地收口应用服务。 +func (s *Server) newBatchLocalPublishService() (*itemapp.BatchLocalPublishService, error) { + if s == nil || s.applicationServiceSet() == nil || s.applicationServiceSet().itemBatchLocalPublish == nil { + return nil, itemapp.ErrBatchLocalPublishUnavailable + } + return s.applicationServiceSet().itemBatchLocalPublish, nil +} + +// createPublishAutomationRules 保留旧测试入口,但实际规则编排已由应用服务负责。 +func (s *Server) createPublishAutomationRules(ctx context.Context, userID int64, row itemapp.BatchRow, result *itemapp.BatchPublishResult) error { + // service 保存已装配的批量本地收口应用服务。 + service, err := s.newBatchLocalPublishService() + if err != nil { + return err + } + // applicationRow 只转换规则编排所需的非敏感字段。 + return service.EnsureAutomationRules(ctx, userID, row, result) +} diff --git a/internal/server/item_batch_management_application.go b/internal/server/item_batch_management_application.go new file mode 100644 index 0000000..0440fbe --- /dev/null +++ b/internal/server/item_batch_management_application.go @@ -0,0 +1,23 @@ +package server + +// serverBatchManagementRuntime 将批次管理应用端口接到 Server 的 worker 生命周期边界。 +type serverBatchManagementRuntime struct { + // server 保存批次 worker 启动与取消所需的 Server 生命周期入口。 + server *Server +} + +// StartBatch 启动已由应用服务声明租约的批量 worker。 +func (runtime serverBatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) { + if runtime.server == nil { + return + } + runtime.server.startPublishBatchWorker(runtime.server.lifecycleContext(), userID, batchID, workerToken) +} + +// CancelBatch 取消指定批次的后台 worker。 +func (runtime serverBatchManagementRuntime) CancelBatch(batchID, workerToken string) { + if runtime.server == nil { + return + } + runtime.server.cancelPublishBatch(batchID, workerToken) +} diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go index e59d6cd..2bab3fd 100644 --- a/internal/server/item_handlers.go +++ b/internal/server/item_handlers.go @@ -1,22 +1,18 @@ package server import ( - "context" "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" - "sync" - "time" "github.com/go-chi/chi/v5" + accountapp "xianyu-go/internal/application/account" itemapp "xianyu-go/internal/application/items" "xianyu-go/internal/auth" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/mtop" ) // mountItemsReal 物品端点(真实实现)。 @@ -102,10 +98,10 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, err.Error()) return } - // location 保存地址,供当前处理流程使用 - var location mtop.PublishLocation - // selectedLocation 保存selected地址,供当前处理流程使用 - var selectedLocation *mtop.PublishLocation + // location 保存带有 JSON 标签的 HTTP 发货地请求模型。 + var location itemPublishLocationRequest + // selectedLocation 保存解析成功、待转换为应用模型的发货地。 + var selectedLocation *itemPublishLocationRequest if // rawLocation 保存原始地址,供当前处理流程使用 rawLocation := strings.TrimSpace(r.FormValue("location")); rawLocation != "" { if // err 保存err,供当前处理流程使用 @@ -141,13 +137,13 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { res := outcome.Result if callErr != nil { // perr 保存perr,供当前处理流程使用 - var perr *mtop.PublishError + var perr *itemapp.PublishError if errors.As(callErr, &perr) { // status 保存状态,供当前处理流程使用 status := http.StatusBadGateway // msg 保存msg,供当前处理流程使用 msg := perr.Error() - if perr.Code == mtop.PublishErrorStockPermissionMissing { + if perr.Code == itemapp.PublishErrorStockPermissionMissing { status = http.StatusForbidden msg = "该账号没有库存发布权限,无法按库存数量发布商品" } @@ -181,136 +177,10 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { ItemImage: res.ImageURL, ItemTitle: res.Title, ItemPrice: res.PriceText, Quantity: res.Quantity, CategoryID: res.CategoryID, CategoryName: res.CategoryName, }) - - /* - 旧实现保留在版本控制历史中,当前单商品发布由 itemPublishService 统一处理。 - 服务边界保证 MTOP 调用、Cookie 更新和本地商品落库的顺序不变。 - */ - /*res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{ - Title: title, - Description: description, - PriceCents: priceCents, - OriginalPriceCents: origCents, - Quantity: quantity, - PostageMode: postageMode, - PostageCents: postageCents, - Virtual: true, - Location: selectedLocation, - Images: images, - }) - runtimeCookie := "" - runtimeCookieChanged := false - var responseCookieErr error - value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession) - if persistErr != nil { - s.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr) - responseCookieErr = persistErr - } else if handled { - if valueChanged { - runtimeCookie = value - runtimeCookieChanged = true - } - } else if callErr == nil && res != nil && res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue { - if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), cookieID, res.UpdatedCookies, userID); saveErr != nil { - s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", cookieID, "err", saveErr) - responseCookieErr = saveErr - } else { - runtimeCookie = res.UpdatedCookies - runtimeCookieChanged = true - } - } - credentialUnlock() - if runtimeCookieChanged { - s.updateRunningCookie(r.Context(), cookieID, runtimeCookie) - } - if callErr != nil { - if responseCookieErr != nil { - callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", responseCookieErr)) - } - s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr) - var perr *mtop.PublishError - if errors.As(callErr, &perr) { - status := http.StatusBadGateway - msg := perr.Error() - if perr.Code == mtop.PublishErrorStockPermissionMissing { - status = http.StatusForbidden - msg = "该账号没有库存发布权限,无法按库存数量发布商品" - } - writeErrCode( - w, - status, - string(perr.Code), - msg, - "") - return - } - writeErr(w, http.StatusBadGateway, callErr.Error()) - return - } - if res == nil || strings.TrimSpace(res.ItemID) == "" { - writeErrCode(w, http.StatusBadGateway, - "publish_result_missing_item_id", - "平台返回发布成功,但缺少商品 ID,无法确认发布结果", - "", - ) - return - } - detail := map[string]any{ - "item_image": res.ImageURL, - "web_url": res.ItemURL, - "category_name": res.CategoryName, - "quantity": res.Quantity, - "publish_raw": res.RawData, - } - detailJSON, _ := json.Marshal(detail) - if err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{ - CookieID: cookieID, - ItemID: res.ItemID, - ItemTitle: res.Title, - ItemDescription: description, - ItemCategory: res.CategoryID, - ItemPrice: res.PriceText, - ItemDetail: string(detailJSON), - MultiQuantityDelivery: quantity > 1, - }); err != nil { - if s.Logger != nil { - s.Logger.Error("平台已发布但保存本地商品失败", "cookie_id", cookieID, "item_id", res.ItemID, "err", err) - } - writeErrDetails( - w, - http.StatusInternalServerError, - "remote_published_local_save_failed", - "商品已在平台发布,但本地保存失败,请勿重复发布并根据商品 ID 人工核对", - "", - map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL}) - return - } - if responseCookieErr != nil { - writeErrDetails( - w, - http.StatusInternalServerError, - "remote_published_cookie_save_failed", - "商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录", - "", - map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL}) - return - } - writeJSON(w, http.StatusOK, itemPublishResponse{ - Success: true, Message: "商品发布成功", ItemID: res.ItemID, ItemURL: res.ItemURL, - ItemImage: res.ImageURL, ItemTitle: res.Title, ItemPrice: res.PriceText, Quantity: res.Quantity, - CategoryID: res.CategoryID, CategoryName: res.CategoryName, - })*/ - // 商品发布 DTO 保留历史客户端使用的字段名称和成功语义。 - // 平台发布结果与本地保存结果的失败分支仍通过统一错误 DTO 返回。 - // item_id 和 item_url 可用于发布后人工核对平台商品。 - // item_image 和 item_title 供前端列表即时展示。 - // quantity、category_id 和 category_name 保留平台回传信息。 - // 本次迁移不改变发布接口的 HTTP 状态码。 - // 后续版本化路径迁移继续复用该具名 DTO。 } // readPublishImages 负责read发布Images相关处理。 -func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) { +func readPublishImages(r *http.Request, maxImages int) ([]itemapp.Image, error) { if r.MultipartForm == nil || r.MultipartForm.File == nil { return nil, errors.New("至少上传 1 张商品图片") } @@ -326,7 +196,7 @@ func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, err return nil, fmt.Errorf("商品图片最多 %d 张", maxImages) } // images 保存images,供当前处理流程使用 - images := make([]mtop.PublishImage, 0, len(files)) + images := make([]itemapp.Image, 0, len(files)) // fh 表示当前遍历过程中的fh for _, fh := range files { // f、err 保存f、err,供当前处理流程使用 @@ -354,7 +224,7 @@ func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, err if !strings.HasPrefix(contentType, "image/") { return nil, errors.New("只能上传图片文件") } - images = append(images, mtop.PublishImage{Filename: fh.Filename, ContentType: contentType, Data: data}) + images = append(images, itemapp.Image{Filename: fh.Filename, ContentType: contentType, Data: data}) } return images, nil } @@ -404,6 +274,26 @@ func parseMoneyCents(raw string) (int64, error) { return sign * (yuan*100 + cents), nil } +// itemPublishLocationRequest 是发布接口接收的发货地 HTTP DTO;平台字段转换由发布应用端口负责。 +type itemPublishLocationRequest struct { + // Area 是发货地的区县名称。 + Area string `json:"area"` + // City 是发货地的城市名称。 + City string `json:"city"` + // DivisionID 是平台行政区划标识。 + DivisionID string `json:"division_id"` + // Longitude 是发货地经度。 + Longitude float64 `json:"longitude"` + // Latitude 是发货地纬度。 + Latitude float64 `json:"latitude"` + // POIID 是地图服务返回的兴趣点标识。 + POIID string `json:"poi_id"` + // POIName 是地图服务返回的兴趣点名称。 + POIName string `json:"poi_name"` + // Province 是发货地的省份名称。 + Province string `json:"province"` +} + // listItems 负责list商品列表相关处理。 func (s *Server) listItems(w http.ResponseWriter, r *http.Request) { // sess 保存sess,供当前处理流程使用 @@ -417,8 +307,8 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) { return } } - // items、err 保存用户范围商品查询结果及错误。 - items, err := s.Store.Items.ListForUser(r.Context(), sess.UserID, cookieID) + // items、err 保存应用层商品查询结果及错误。 + items, err := s.itemCatalogApplication().ListForUser(r.Context(), sess.UserID, cookieID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -432,498 +322,113 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, result) } -// syncItemsFromAccount 负责sync商品列表From账号相关处理。 -func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) { - // req 保存req,供当前处理流程使用 - var req struct { - CookieID string `json:"cookie_id"` - PageSize int `json:"page_size"` - MaxPages int `json:"max_pages"` - } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil || req.CookieID == "" { - writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数") - return - } - // userID、ok 保存用户ID、ok,供当前处理流程使用 - _, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID) - if !ok { - return - } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.Store.LockAccountCredentials(req.CookieID) - // latest、err 保存latest、err,供当前处理流程使用 - latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID) - if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { - credentialUnlock() - writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") - return - } - // cookieValue 保存登录凭证值,供当前处理流程使用 - cookieValue := latest.Value - if req.PageSize <= 0 { - req.PageSize = 20 - } - // ctx、cancel 保存ctx、cancel,供当前处理流程使用 - ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) - defer cancel() - // client 保存client,供当前处理流程使用 - client := s.mtopClient() - // mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用 - mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest) - // 账号凭证快照已读取完成;慢速商品列表请求不得继续持有共享凭证锁。 - credentialUnlock() - // res、callErr 保存res、callErr,供当前处理流程使用 - res, callErr := client.FetchAllItems(mtopCtx, cookieValue, req.PageSize, req.MaxPages) - // credentialUnlock 保存外部请求完成后重新进入凭证提交临界区的释放函数。 - credentialUnlock = s.Store.LockAccountCredentials(req.CookieID) - // latestAfterFetch、reloadErr 保存外部请求完成后的最新凭证快照及重读错误。 - latestAfterFetch, reloadErr := s.loadCookiePlatformDetail(r.Context(), req.CookieID) - if reloadErr != nil || latestAfterFetch == nil || latestAfterFetch.UserID != userID { - credentialUnlock() - writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") - return - } - // credentialSnapshotChanged 标记外部商品请求期间是否已有其他流程更新凭证。 - credentialSnapshotChanged := latestAfterFetch.Value != latest.Value || latestAfterFetch.MetadataJSON != latest.MetadataJSON - latest = latestAfterFetch - if callErr == nil && res == nil { - callErr = errors.New("商品列表接口未返回结果") - } - if callErr != nil { - // value、valueChanged、persistErr 保存value、valueChanged、persistErr,供当前处理流程使用 - value, valueChanged, _, persistErr := "", false, false, error(nil) - if !credentialSnapshotChanged { - value, valueChanged, _, persistErr = s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession) - } - credentialUnlock() - if persistErr != nil { - s.Logger.Error("保存商品同步响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr) - writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败") - return - } else if valueChanged { - s.updateRunningCookie(r.Context(), req.CookieID, value) - } - s.recoverExpiredMTOPSession(r.Context(), req.CookieID, callErr) - writeErr(w, http.StatusBadGateway, callErr.Error()) - return - } - // detailCookies 保存detailCookies,供当前处理流程使用 - detailCookies := cookieValue - if res.UpdatedCookies != "" { - detailCookies = res.UpdatedCookies - } - credentialUnlock() - // detailErr 保存规格探测结果及错误。 - detailErr := s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items) - credentialUnlock = s.Store.LockAccountCredentials(req.CookieID) - // latestAfterEnrich、enrichReloadErr 保存规格探测完成后的最新凭证快照及重读错误。 - latestAfterEnrich, enrichReloadErr := s.loadCookiePlatformDetail(r.Context(), req.CookieID) - if enrichReloadErr != nil || latestAfterEnrich == nil || latestAfterEnrich.UserID != userID { - credentialUnlock() - writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") - return - } - credentialSnapshotChanged = credentialSnapshotChanged || latestAfterEnrich.Value != latest.Value || latestAfterEnrich.MetadataJSON != latest.MetadataJSON - latest = latestAfterEnrich - // runtimeCookie 保存runtime登录凭证,供当前处理流程使用 - runtimeCookie := "" - // runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用 - runtimeCookieChanged := false - // value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用 - value, valueChanged, handled, persistErr := "", false, false, error(nil) - if !credentialSnapshotChanged { - value, valueChanged, handled, persistErr = s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession) - } - if persistErr != nil { - s.Logger.Error("保存商品同步响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr) - credentialUnlock() - writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败") - return - } else if handled { - if valueChanged { - runtimeCookie = value - runtimeCookieChanged = true - } - } else if !credentialSnapshotChanged && res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue { - if // saveErr 保存saveErr,供当前处理流程使用 - saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil { - s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr) - credentialUnlock() - writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败") - return - } else { - runtimeCookie = res.UpdatedCookies - runtimeCookieChanged = true - } - } - credentialUnlock() - if runtimeCookieChanged { - s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie) - } - if detailErr != nil { - s.recoverExpiredMTOPSession(r.Context(), req.CookieID, detailErr) - writeErr(w, http.StatusBadGateway, detailErr.Error()) - return - } - // syncResult、syncErr 保存syncResult、syncErr,供当前处理流程使用 - syncResult, syncErr := s.syncSyncedItems(r.Context(), req.CookieID, res.Items) - if syncErr != nil { - if s.Logger != nil { - s.Logger.Error("同步商品到本地失败", "cookie_id", req.CookieID, "err", syncErr) - } - writeErr(w, http.StatusInternalServerError, "保存商品同步结果失败") - return - } - writeJSON(w, http.StatusOK, itemSyncResponse{ - Success: true, - Message: "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(syncResult.Saved) + " 件,删除 " + strconv.Itoa(syncResult.Deleted) + " 件", - TotalCount: len(res.Items), TotalPages: res.TotalPages, SavedCount: syncResult.Saved, DeletedCount: syncResult.Deleted, - }) +// itemSyncRequest 是商品全量和分页同步接口共用的请求 DTO。 +type itemSyncRequest struct { + // CookieID 是待同步的平台账号标识。 + CookieID string `json:"cookie_id"` + // PageNumber 是分页同步的平台页码。 + PageNumber int `json:"page_number"` + // PageSize 是平台单页大小。 + PageSize int `json:"page_size"` + // MaxPages 是全量同步允许读取的最大页数。 + MaxPages int `json:"max_pages"` } -// syncItemsPageFromAccount 同步指定页商品并返回分页统计 DTO。 -// 该接口沿用现有凭证锁和 Cookie 持久化流程。 -// 分页成功响应使用 itemPageSyncResponse。 -// syncItemsPageFromAccount 负责sync商品列表页码From账号相关处理。 -func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request) { - // req 保存req,供当前处理流程使用 - var req struct { - CookieID string `json:"cookie_id"` - PageNumber int `json:"page_number"` - PageSize int `json:"page_size"` - } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil || req.CookieID == "" { +// syncItemsFromAccount 解析请求并调用商品全集同步应用服务。 +func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) { + // req 保存解码后的商品全集同步请求。 + var req itemSyncRequest + // err 保存商品全集同步请求解码失败的原因。 + if err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.CookieID) == "" { writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数") return } - // userID、ok 保存用户ID、ok,供当前处理流程使用 - _, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID) - if !ok { + // sess 保存认证中间件提供的当前用户会话。 + sess := auth.SessionFromContext(r.Context()) + // result、err 保存应用服务返回的全集同步结果及错误。 + result, err := s.itemSyncApplication().SyncAll(r.Context(), itemapp.SyncQuery{UserID: sess.UserID, CookieID: req.CookieID, PageSize: req.PageSize, MaxPages: req.MaxPages}) + if err != nil { + s.writeItemSyncError(w, err) return } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.Store.LockAccountCredentials(req.CookieID) - // latest、err 保存latest、err,供当前处理流程使用 - latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID) - if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { - credentialUnlock() - writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") + writeJSON(w, http.StatusOK, itemSyncResponse{Success: true, Message: "成功获取商品,共 " + strconv.Itoa(result.TotalCount) + " 件,保存 " + strconv.Itoa(result.SavedCount) + " 件,删除 " + strconv.Itoa(result.DeletedCount) + " 件", TotalCount: result.TotalCount, TotalPages: result.TotalPages, SavedCount: result.SavedCount, DeletedCount: result.DeletedCount}) +} + +// syncItemsPageFromAccount 解析请求并调用商品分页同步应用服务。 +func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request) { + // req 保存解码后的商品分页同步请求。 + var req itemSyncRequest + // err 保存商品分页同步请求解码失败的原因。 + if err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.CookieID) == "" { + writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数") return } - // cookieValue 保存登录凭证值,供当前处理流程使用 - cookieValue := latest.Value - // ctx、cancel 保存ctx、cancel,供当前处理流程使用 - ctx, cancel := context.WithTimeout(r.Context(), time.Minute) - defer cancel() - // client 保存client,供当前处理流程使用 - client := s.mtopClient() - // mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用 - mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest) - // res、callErr 保存res、callErr,供当前处理流程使用 - res, callErr := client.FetchItemsPage(mtopCtx, cookieValue, req.PageNumber, req.PageSize) - if callErr == nil && res == nil { - callErr = errors.New("商品列表接口未返回结果") + // sess 保存认证中间件提供的当前用户会话。 + sess := auth.SessionFromContext(r.Context()) + // result、err 保存应用服务返回的分页同步结果及错误。 + result, err := s.itemSyncApplication().SyncPage(r.Context(), itemapp.SyncQuery{UserID: sess.UserID, CookieID: req.CookieID, PageNumber: req.PageNumber, PageSize: req.PageSize}) + if err != nil { + s.writeItemSyncError(w, err) + return } - if callErr != nil { - // value、valueChanged、persistErr 保存value、valueChanged、persistErr,供当前处理流程使用 - value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession) - credentialUnlock() - if persistErr != nil { - s.Logger.Error("保存商品分页响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr) - writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败") - return - } else if valueChanged { - s.updateRunningCookie(r.Context(), req.CookieID, value) + writeJSON(w, http.StatusOK, itemPageSyncResponse{Success: true, Message: "成功获取第" + strconv.Itoa(result.PageNumber) + "页 " + strconv.Itoa(result.CurrentCount) + " 个商品", PageNumber: result.PageNumber, PageSize: result.PageSize, CurrentCount: result.CurrentCount, SavedCount: result.SavedCount}) +} + +// writeItemSyncError 将应用同步错误映射为稳定的 HTTP 状态和消息。 +func (s *Server) writeItemSyncError(w http.ResponseWriter, err error) { + if errors.Is(err, itemapp.ErrSyncNotOwned) { + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return + } + if errors.Is(err, itemapp.ErrSyncInvalidUser) || errors.Is(err, itemapp.ErrSyncInvalidCookie) { + writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数") + return + } + // stageErr 保存应用服务提供的同步阶段错误。 + var stageErr *itemapp.SyncError + if errors.As(err, &stageErr) { + switch stageErr.Kind { + case itemapp.SyncErrorCredential: + writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") + case itemapp.SyncErrorPersistence: + writeErr(w, http.StatusInternalServerError, "保存商品同步结果失败") + default: + writeErr(w, http.StatusBadGateway, stageErr.Error()) } - s.recoverExpiredMTOPSession(r.Context(), req.CookieID, callErr) - writeErr(w, http.StatusBadGateway, callErr.Error()) return } - // detailCookies 保存detailCookies,供当前处理流程使用 - detailCookies := cookieValue - if res.UpdatedCookies != "" { - detailCookies = res.UpdatedCookies - } - // detailErr 保存detailErr,供当前处理流程使用 - detailErr := s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items) - // runtimeCookie 保存runtime登录凭证,供当前处理流程使用 - runtimeCookie := "" - // runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用 - runtimeCookieChanged := false - // value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用 - value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession) - if persistErr != nil { - s.Logger.Error("保存商品分页响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr) - credentialUnlock() - writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败") - return - } else if handled { - if valueChanged { - runtimeCookie = value - runtimeCookieChanged = true - } - } else if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue { - if // saveErr 保存saveErr,供当前处理流程使用 - saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil { - s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr) - credentialUnlock() - writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败") - return - } else { - runtimeCookie = res.UpdatedCookies - runtimeCookieChanged = true - } - } - credentialUnlock() - if runtimeCookieChanged { - s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie) - } - if detailErr != nil { - s.recoverExpiredMTOPSession(r.Context(), req.CookieID, detailErr) - writeErr(w, http.StatusBadGateway, detailErr.Error()) - return - } - // saved 保存saved,供当前处理流程使用 - saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items) - writeJSON(w, http.StatusOK, itemPageSyncResponse{ - Success: true, Message: "成功获取第" + strconv.Itoa(res.PageNumber) + "页 " + strconv.Itoa(len(res.Items)) + " 个商品", - PageNumber: res.PageNumber, PageSize: res.PageSize, CurrentCount: len(res.Items), SavedCount: saved, - }) - // 分页同步 DTO 与全集同步 DTO 分离,避免不同统计语义混用。 - // page_number 和 page_size 描述平台请求页,current_count 描述实际返回数量。 - // saved_count 只统计本次写入本地的商品。 - // 失败仍由统一错误响应负责,不在成功 DTO 中嵌入错误别名。 + writeErr(w, http.StatusInternalServerError, "商品同步失败") } // cookieForCurrentUser 负责登录凭证ForCurrent用户相关处理。 func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) { // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) - value, err := s.Store.Cookies.GetValueOwned(r.Context(), sess.UserID, cookieID) // value 和 err 是单个 Cookie 明文及读取错误。 + // repository 提供平台请求所需的窄凭证视图,数据库解密和所有权读取均封装在 adapter。 + repository := s.accountLoginRepositoryForServer() + if repository == nil { + writeErr(w, http.StatusInternalServerError, "查询账号失败") + return "", 0, false + } + // detail 和 err 保存账号归属及 Cookie 可用性检查结果;明文仅在当前函数返回给已授权业务适配器。 + detail, err := repository.LoadPlatformDetail(r.Context(), cookieID) if err != nil { - if errors.Is(err, db.ErrNotFound) { + if errors.Is(err, accountapp.ErrCredentialNotFound) { writeErr(w, http.StatusForbidden, "无权限操作该账号") return "", 0, false } writeErr(w, http.StatusInternalServerError, "查询账号失败") return "", 0, false } - if value == "" { + if detail == nil || detail.UserID != sess.UserID { + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return "", 0, false + } + if detail.Value == "" { writeErr(w, http.StatusBadRequest, "账号 cookie 为空") return "", 0, false } - return value, sess.UserID, true -} - -// saveSyncedItems 以下历史同步流程保持原有行为。 -func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) int { - // saved 保存saved,供当前处理流程使用 - saved := 0 - // item 表示当前遍历过程中的商品 - for _, item := range items { - // priceText 保存price文本,供当前处理流程使用 - priceText := item.PriceText - if priceText == "" { - priceText = item.Price - } - // err 保存err,供当前处理流程使用 - err := s.Store.Items.UpsertBasic(ctx, &db.ItemInfoRow{ - CookieID: cookieID, - ItemID: item.ID, - ItemTitle: item.Title, - ItemDescription: "", - ItemCategory: item.CategoryID, - ItemPrice: priceText, - ItemDetail: item.ItemDetail, - }) - if err == nil { - if item.IsMultiSpec { - if // multiErr 保存multiErr,供当前处理流程使用 - multiErr := s.Store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil && s.Logger != nil { - s.Logger.Warn("保存商品多规格状态失败", "cookie_id", cookieID, "item_id", item.ID, "err", multiErr) - } - } - saved++ - } else if s.Logger != nil { - s.Logger.Warn("保存商品失败", "cookie_id", cookieID, "item_id", item.ID, "err", err) - } - } - return saved -} - -// syncSyncedItems 负责syncSynced商品列表相关处理。 -func (s *Server) syncSyncedItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) (db.ItemSyncResult, error) { - // rows 保存rows,供当前处理流程使用 - rows := make([]db.ItemInfoRow, 0, len(items)) - // item 表示当前遍历过程中的商品 - for _, item := range items { - // priceText 保存price文本,供当前处理流程使用 - priceText := item.PriceText - if priceText == "" { - priceText = item.Price - } - rows = append(rows, db.ItemInfoRow{ - CookieID: cookieID, - ItemID: item.ID, - ItemTitle: item.Title, - ItemCategory: item.CategoryID, - ItemPrice: priceText, - ItemDetail: item.ItemDetail, - IsMultiSpec: item.IsMultiSpec, - }) - } - return s.Store.Items.SyncFromRemote(ctx, cookieID, rows) -} - -// itemSpecProbeConcurrency 限制商品多规格远端探测的并发数,避免同步洪峰压垮平台接口。 -const itemSpecProbeConcurrency = 4 - -// itemSpecCacheTTL 定义商品多规格探测结果的短期缓存时长。 -const itemSpecCacheTTL = 10 * time.Minute - -// itemSpecCacheEntry 保存商品多规格结果及其过期时间。 -type itemSpecCacheEntry struct { - // isMultiSpec 表示商品是否包含多规格。 - isMultiSpec bool - // expiresAt 表示该缓存项失效的时间。 - expiresAt time.Time -} - -// itemSpecCacheKey 生成账号与商品组合的缓存键,避免不同账号同商品 ID 相互污染。 -func itemSpecCacheKey(cookieID, itemID string) string { - return cookieID + "\x00" + itemID -} - -// cachedItemSpec 读取未过期的商品多规格缓存。 -func (s *Server) cachedItemSpec(cookieID, itemID string) (bool, bool) { - if s == nil { - return false, false - } - s.itemSpecCacheMu.Lock() - defer s.itemSpecCacheMu.Unlock() - // key 表示账号与商品组合的缓存键。 - key := itemSpecCacheKey(cookieID, itemID) - // entry、exists 保存缓存项及其存在状态。 - entry, exists := s.itemSpecCache[key] - if !exists { - return false, false - } - if time.Now().After(entry.expiresAt) { - delete(s.itemSpecCache, key) - return false, false - } - return entry.isMultiSpec, true -} - -// cacheItemSpec 写入商品多规格结果并清理已过期缓存项。 -func (s *Server) cacheItemSpec(cookieID, itemID string, isMultiSpec bool) { - if s == nil || itemID == "" { - return - } - s.itemSpecCacheMu.Lock() - defer s.itemSpecCacheMu.Unlock() - if s.itemSpecCache == nil { - s.itemSpecCache = make(map[string]itemSpecCacheEntry) - } - // now 表示本次写入缓存的时间基准。 - now := time.Now() - // key、entry 分别表示缓存键及其缓存项。 - for key, entry := range s.itemSpecCache { - if now.After(entry.expiresAt) { - delete(s.itemSpecCache, key) - } - } - s.itemSpecCache[itemSpecCacheKey(cookieID, itemID)] = itemSpecCacheEntry{isMultiSpec: isMultiSpec, expiresAt: now.Add(itemSpecCacheTTL)} -} - -// enrichSyncedItemMultiSpec 批量读取本地标记并受限并发探测剩余商品的多规格状态。 -func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) error { - // fetcher、ok 保存fetcher、ok,供当前处理流程使用 - fetcher, ok := client.(mtop.ItemDetailFetcher) - if !ok { - return nil - } - // itemIDs 保存待批量读取本地多规格标记的商品标识。 - itemIDs := make([]string, 0, len(items)) - // item 表示当前同步返回的商品。 - for _, item := range items { - itemIDs = append(itemIDs, item.ID) - } - // localFlags、flagsErr 保存本地多规格标记及批量查询错误。 - localFlags, flagsErr := s.Store.Items.MultiSpecFlags(ctx, cookieID, itemIDs) - if flagsErr != nil && s.Logger != nil { - s.Logger.Warn("批量读取商品多规格标记失败,将继续远端探测", "cookie_id", cookieID, "err", flagsErr) - } - // candidates 保存需要访问远端接口的商品下标。 - candidates := make([]int, 0, len(items)) - // index 表示当前商品在同步列表中的下标。 - for index := range items { - if items[index].IsMultiSpec || localFlags[items[index].ID] { - items[index].IsMultiSpec = true - s.cacheItemSpec(cookieID, items[index].ID, true) - continue - } - // cachedValue、cached 表示当前商品是否命中短期探测缓存。 - cachedValue, cached := s.cachedItemSpec(cookieID, items[index].ID) - if cached { - items[index].IsMultiSpec = cachedValue - continue - } - candidates = append(candidates, index) - } - if len(candidates) == 0 { - return nil - } - // probeCtx、cancel 让 Session 过期时的其他探测尽快停止。 - probeCtx, cancel := context.WithCancel(ctx) - defer cancel() - // semaphore 限制同时进行的远端商品详情请求数。 - semaphore := make(chan struct{}, itemSpecProbeConcurrency) - // waitGroup 等待所有商品探测 goroutine 收束。 - var waitGroup sync.WaitGroup - // errorMu 保护 sessionErr 的并发写入。 - var errorMu sync.Mutex - // sessionErr 保存首个需要中断同步的 Session 过期错误。 - var sessionErr error - // index 表示当前需要远端探测的商品下标。 - for _, index := range candidates { - waitGroup.Add(1) - go func(index int) { - defer waitGroup.Done() - select { - case semaphore <- struct{}{}: - case <-probeCtx.Done(): - return - } - defer func() { <-semaphore }() - // isMultiSpec、err 保存当前商品远端探测结果及错误。 - isMultiSpec, err := fetcher.DetectItemMultiSpec(probeCtx, cookies, items[index].ID) - if err != nil { - if mtop.IsSessionExpiredErr(err) { - errorMu.Lock() - if sessionErr == nil { - sessionErr = err - cancel() - } - errorMu.Unlock() - return - } - if probeCtx.Err() != nil { - return - } - if s.Logger != nil { - s.Logger.Warn("识别商品多规格状态失败", "cookie_id", cookieID, "item_id", items[index].ID, "err", err) - } - return - } - s.cacheItemSpec(cookieID, items[index].ID, isMultiSpec) - items[index].IsMultiSpec = isMultiSpec - }(index) - } - waitGroup.Wait() - return sessionErr + return detail.Value, sess.UserID, true } // listItemsByCookie 负责list商品列表By登录凭证相关处理。 @@ -933,8 +438,8 @@ func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) { if !s.requireCookieOwnership(w, r, cid) { return } - // items、err 保存items、err,供当前处理流程使用 - items, err := s.Store.Items.AllForCookie(r.Context(), cid) + // items、err 保存应用层商品查询结果及错误。 + items, err := s.itemCatalogApplication().ListByCookie(r.Context(), cid) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -958,7 +463,7 @@ func (s *Server) getItem(w http.ResponseWriter, r *http.Request) { // itemID 保存商品ID,供当前处理流程使用 itemID := chi.URLParam(r, "item_id") // it、err 保存it、err,供当前处理流程使用 - it, err := s.Store.Items.Get(r.Context(), cid, itemID) + it, err := s.itemCatalogApplication().Get(r.Context(), cid, itemID) if err != nil { writeErr(w, http.StatusNotFound, "商品不存在") return @@ -970,6 +475,60 @@ func (s *Server) getItem(w http.ResponseWriter, r *http.Request) { }) } +// itemCreateRequest 是创建本地商品接口的请求 DTO。 +type itemCreateRequest struct { + // ItemID 是平台商品标识。 + ItemID string `json:"item_id"` + // ItemTitle 是商品标题。 + ItemTitle string `json:"item_title"` + // ItemDescription 是商品描述。 + ItemDescription string `json:"item_description"` + // ItemCategory 是平台商品类目标识。 + ItemCategory string `json:"item_category"` + // ItemPrice 是商品价格文本。 + ItemPrice string `json:"item_price"` + // ItemDetail 是商品扩展详情 JSON。 + ItemDetail string `json:"item_detail"` + // IsMultiSpec 表示是否启用多规格交付。 + IsMultiSpec bool `json:"is_multi_spec"` + // MultiQuantityDelivery 表示是否启用多数量交付。 + MultiQuantityDelivery bool `json:"multi_quantity_delivery"` + // IsMultiQtyShip 是历史客户端使用的多数量交付别名。 + IsMultiQtyShip bool `json:"is_multi_qty_ship"` +} + +// itemUpdateRequest 是局部更新本地商品接口的请求 DTO。 +type itemUpdateRequest struct { + // ItemTitle 是可选的商品标题。 + ItemTitle *string `json:"item_title"` + // ItemDescription 是可选的商品描述。 + ItemDescription *string `json:"item_description"` + // ItemCategory 是可选的商品类目标识。 + ItemCategory *string `json:"item_category"` + // ItemPrice 是可选的商品价格文本。 + ItemPrice *string `json:"item_price"` + // ItemDetail 是可选的商品扩展详情 JSON。 + ItemDetail *string `json:"item_detail"` + // IsMultiSpec 是可选的多规格交付开关。 + IsMultiSpec *bool `json:"is_multi_spec"` + // MultiQuantityDelivery 是可选的多数量交付开关。 + MultiQuantityDelivery *bool `json:"multi_quantity_delivery"` + // IsMultiQtyShip 是历史客户端使用的多数量交付开关别名。 + IsMultiQtyShip *bool `json:"is_multi_qty_ship"` +} + +// itemMultiSpecRequest 是更新商品多规格开关的请求 DTO。 +type itemMultiSpecRequest struct { + // IsMultiSpec 表示是否启用多规格交付。 + IsMultiSpec bool `json:"is_multi_spec"` +} + +// itemMultiQuantityRequest 是更新商品多数量交付开关的请求 DTO。 +type itemMultiQuantityRequest struct { + // MultiQuantityDelivery 表示是否启用多数量交付。 + MultiQuantityDelivery bool `json:"multi_quantity_delivery"` +} + // createItem 创建本地商品记录并返回统一操作结果。 func (s *Server) createItem(w http.ResponseWriter, r *http.Request) { // cid 保存cid,供当前处理流程使用 @@ -977,18 +536,8 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) { if !s.requireCookieOwnership(w, r, cid) { return } - // req 保存req,供当前处理流程使用 - var req struct { - ItemID string `json:"item_id"` - ItemTitle string `json:"item_title"` - ItemDescription string `json:"item_description"` - ItemCategory string `json:"item_category"` - ItemPrice string `json:"item_price"` - ItemDetail string `json:"item_detail"` - IsMultiSpec bool `json:"is_multi_spec"` - MultiQuantityDelivery bool `json:"multi_quantity_delivery"` - IsMultiQtyShip bool `json:"is_multi_qty_ship"` - } + // req 保存解码后的创建商品请求。 + var req itemCreateRequest if // err 保存err,供当前处理流程使用 err := decodeJSON(r, &req); err != nil || req.ItemID == "" { writeErr(w, http.StatusBadRequest, "缺少商品 ID") @@ -997,9 +546,9 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) { if req.MultiQuantityDelivery || req.IsMultiQtyShip { req.MultiQuantityDelivery = true } - if // err 保存err,供当前处理流程使用 - err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{ - CookieID: cid, ItemID: req.ItemID, ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription, + // err 保存商品创建应用服务返回的错误。 + if err := s.itemCatalogMutationApplication().Create(r.Context(), cid, itemapp.CatalogWriteInput{ + ItemID: req.ItemID, ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription, ItemCategory: req.ItemCategory, ItemPrice: req.ItemPrice, ItemDetail: req.ItemDetail, IsMultiSpec: req.IsMultiSpec, MultiQuantityDelivery: req.MultiQuantityDelivery, }); err != nil { @@ -1009,7 +558,7 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// updateItem 负责update商品相关处理。 +// updateItem 更新本地商品的部分字段并保留未提交字段。 func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) { // cid 保存cid,供当前处理流程使用 cid := chi.URLParam(r, "cookie_id") @@ -1018,70 +567,28 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) { } // itemID 保存商品ID,供当前处理流程使用 itemID := chi.URLParam(r, "item_id") - // req 保存req,供当前处理流程使用 - var req struct { - ItemTitle *string `json:"item_title"` - ItemDescription *string `json:"item_description"` - ItemCategory *string `json:"item_category"` - ItemPrice *string `json:"item_price"` - ItemDetail *string `json:"item_detail"` - IsMultiSpec *bool `json:"is_multi_spec"` - MultiQuantityDelivery *bool `json:"multi_quantity_delivery"` - IsMultiQtyShip *bool `json:"is_multi_qty_ship"` - } + // req 保存解码后的局部更新商品请求。 + var req itemUpdateRequest if // err 保存err,供当前处理流程使用 err := decodeJSON(r, &req); err != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // existing、err 保存existing、err,供当前处理流程使用 - existing, err := s.Store.Items.Get(r.Context(), cid, itemID) - if errors.Is(err, db.ErrNotFound) { - writeErr(w, http.StatusNotFound, "商品不存在") - return - } - if err != nil { - writeErr(w, http.StatusInternalServerError, "更新失败") - return - } - // row 保存row,供当前处理流程使用 - row := &db.ItemInfoRow{ - CookieID: cid, - ItemID: itemID, - ItemTitle: existing.ItemTitle, - ItemDescription: existing.ItemDescription, - ItemCategory: existing.ItemCategory, - ItemPrice: existing.ItemPrice, - ItemDetail: existing.ItemDetail, - IsMultiSpec: existing.IsMultiSpec, - MultiQuantityDelivery: existing.MultiQuantityDelivery, - } - if req.ItemTitle != nil { - row.ItemTitle = *req.ItemTitle - } - if req.ItemDescription != nil { - row.ItemDescription = *req.ItemDescription - } - if req.ItemCategory != nil { - row.ItemCategory = *req.ItemCategory - } - if req.ItemPrice != nil { - row.ItemPrice = *req.ItemPrice - } - if req.ItemDetail != nil { - row.ItemDetail = *req.ItemDetail - } - if req.IsMultiSpec != nil { - row.IsMultiSpec = *req.IsMultiSpec - } - if req.MultiQuantityDelivery != nil { - row.MultiQuantityDelivery = *req.MultiQuantityDelivery + // patch 保存 HTTP DTO 转换后的应用层局部更新输入。 + patch := itemapp.CatalogPatchInput{ + ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription, ItemCategory: req.ItemCategory, + ItemPrice: req.ItemPrice, ItemDetail: req.ItemDetail, IsMultiSpec: req.IsMultiSpec, + MultiQuantityDelivery: req.MultiQuantityDelivery, } if req.IsMultiQtyShip != nil { - row.MultiQuantityDelivery = *req.IsMultiQtyShip + patch.MultiQuantityDelivery = req.IsMultiQtyShip } - if // err 保存err,供当前处理流程使用 - err := s.Store.Items.Upsert(r.Context(), row); err != nil { + // err 保存商品更新应用服务返回的错误。 + if err := s.itemCatalogMutationApplication().Update(r.Context(), cid, itemID, patch); err != nil { + if errors.Is(err, itemapp.ErrCatalogNotFound) { + writeErr(w, http.StatusNotFound, "商品不存在") + return + } writeErr(w, http.StatusInternalServerError, "更新失败") return } @@ -1097,8 +604,8 @@ func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) { } // itemID 保存商品ID,供当前处理流程使用 itemID := chi.URLParam(r, "item_id") - if // err 保存err,供当前处理流程使用 - err := s.Store.Items.Delete(r.Context(), cid, itemID); err != nil { + // err 保存商品删除应用服务返回的错误。 + if err := s.itemCatalogMutationApplication().Delete(r.Context(), cid, itemID); err != nil { writeErr(w, http.StatusInternalServerError, "删除失败") return } @@ -1114,17 +621,15 @@ func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) { } // itemID 保存商品ID,供当前处理流程使用 itemID := chi.URLParam(r, "item_id") - // req 保存req,供当前处理流程使用 - var req struct { - IsMultiSpec bool `json:"is_multi_spec"` - } + // req 保存解码后的多规格开关请求。 + var req itemMultiSpecRequest if // err 保存err,供当前处理流程使用 err := decodeJSON(r, &req); err != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - if // err 保存err,供当前处理流程使用 - err := s.Store.Items.SetMultiSpec(r.Context(), cid, itemID, req.IsMultiSpec); err != nil { + // err 保存商品多规格应用服务返回的错误。 + if err := s.itemCatalogMutationApplication().SetMultiSpec(r.Context(), cid, itemID, req.IsMultiSpec); err != nil { writeErr(w, http.StatusInternalServerError, "更新失败") return } @@ -1140,24 +645,22 @@ func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) { } // itemID 保存商品ID,供当前处理流程使用 itemID := chi.URLParam(r, "item_id") - // req 保存req,供当前处理流程使用 - var req struct { - MultiQuantityDelivery bool `json:"multi_quantity_delivery"` - } + // req 保存解码后的多数量交付开关请求。 + var req itemMultiQuantityRequest if // err 保存err,供当前处理流程使用 err := decodeJSON(r, &req); err != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - if // err 保存err,供当前处理流程使用 - err := s.Store.Items.SetMultiQuantity(r.Context(), cid, itemID, req.MultiQuantityDelivery); err != nil { + // err 保存商品多数量应用服务返回的错误。 + if err := s.itemCatalogMutationApplication().SetMultiQuantity(r.Context(), cid, itemID, req.MultiQuantityDelivery); err != nil { writeErr(w, http.StatusInternalServerError, "更新失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -func itemToMap(it db.ItemInfoRow) itemListResponse { // itemToMap 将数据库商品行转换为商品列表 DTO。 +func itemToMap(it itemapp.CatalogItem) itemListResponse { // itemToMap 将应用商品模型转换为商品列表 DTO。 imageURL := itemImageFromDetail(it.ItemDetail) return itemListResponse{ ID: it.ID, CookieID: it.CookieID, ItemID: it.ItemID, ItemTitle: it.ItemTitle, diff --git a/internal/server/item_handlers_test.go b/internal/server/item_handlers_test.go index e5f84db..f62c0bb 100644 --- a/internal/server/item_handlers_test.go +++ b/internal/server/item_handlers_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "encoding/json" - "fmt" "io" "mime/multipart" "net/http" @@ -15,6 +14,7 @@ import ( "testing" "time" + itemapp "xianyu-go/internal/application/items" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/mtop" ) @@ -131,6 +131,44 @@ func buildPublishMultipart(t *testing.T, fields map[string]string) (*bytes.Buffe return &buf, mw.FormDataContentType() } +// TestReadPublishImagesReturnsApplicationModel 验证 HTTP 图片解析只输出应用层图片模型。 +func TestReadPublishImagesReturnsApplicationModel(t *testing.T) { + // body、contentType 保存带图片 multipart 请求体及其 MIME 类型。 + body, contentType := buildPublishMultipart(t, nil) + // request 是待解析的商品发布 HTTP 请求。 + request := httptest.NewRequest(http.MethodPost, "/items/publish", body) + request.Header.Set("Content-Type", contentType) + // parseErr 保存 multipart 解析错误。 + parseErr := request.ParseMultipartForm(1 << 20) + if parseErr != nil { + t.Fatalf("解析 multipart 失败: %v", parseErr) + } + // images、readErr 保存图片解析结果及错误。 + images, readErr := readPublishImages(request, 9) + if readErr != nil { + t.Fatalf("读取图片失败: %v", readErr) + } + if len(images) != 1 || images[0].Filename != "test.png" || images[0].ContentType != "image/png" || len(images[0].Data) == 0 { + t.Fatalf("图片应用模型异常: %+v", images) + } + // applicationImage 是显式检查返回值类型的应用层图片模型。 + applicationImage := itemapp.Image(images[0]) + if applicationImage.Filename != "test.png" { + t.Fatalf("图片未转换为应用模型: %+v", applicationImage) + } +} + +// TestReadPublishImagesRejectsMissingMultipart 验证缺少图片时保持稳定输入错误。 +func TestReadPublishImagesRejectsMissingMultipart(t *testing.T) { + // request 是没有 multipart 文件的商品发布请求。 + request := httptest.NewRequest(http.MethodPost, "/items/publish", strings.NewReader("")) + // images、readErr 保存缺少图片时的解析结果及错误。 + images, readErr := readPublishImages(request, 9) + if images != nil || readErr == nil || readErr.Error() != "至少上传 1 张商品图片" { + t.Fatalf("缺少图片错误异常: images=%v err=%v", images, readErr) + } +} + // TestPublishItemMissingCookieID 缺 cookie_id 应 400。 func TestPublishItemMissingCookieID(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 @@ -632,93 +670,6 @@ func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) { } } -// TestEnrichSyncedItemMultiSpecLimitsProbeConcurrency 验证商品多规格探测使用有界并发且覆盖全部候选商品。 -func TestEnrichSyncedItemMultiSpecLimitsProbeConcurrency(t *testing.T) { - // srv、store、cleanup 保存用于商品同步测试的服务、数据库和清理函数。 - srv, store, cleanup := newTestServer(t) - defer cleanup() - // stateMu 保护远端探测并发计数。 - var stateMu sync.Mutex - // active、maxActive 保存当前及观测到的最大远端探测并发数。 - active, maxActive := 0, 0 - // probeCalls 统计测试客户端收到的商品详情探测请求数。 - probeCalls := 0 - // client 是带并发计数的商品详情测试客户端。 - client := withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) { - if !strings.Contains(req.URL.String(), "mtop.taobao.idle.pc.detail") { - return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{}`)), Request: req}, nil - } - stateMu.Lock() - probeCalls++ - active++ - if active > maxActive { - maxActive = active - } - stateMu.Unlock() - time.Sleep(20 * time.Millisecond) - stateMu.Lock() - active-- - stateMu.Unlock() - return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"multiSKU":true,"skuDO":{"skuList":[{"id":"a"}]}}}`)), Request: req}, nil - })) - // items 保存等待探测的商品列表。 - items := make([]mtop.ItemListItem, 8) - // index 表示当前商品在测试列表中的下标。 - for index := range items { - items[index].ID = fmt.Sprintf("probe-%d", index) - } - // err 表示批量多规格探测错误。 - err := srv.enrichSyncedItemMultiSpec(context.Background(), client, "unb=1; _m_h5_tk=t_1;", "acc1", items) - if err != nil { - t.Fatalf("enrich multi spec: %v", err) - } - if maxActive > itemSpecProbeConcurrency { - t.Fatalf("probe concurrency=%d want <=%d", maxActive, itemSpecProbeConcurrency) - } - // index、item 分别表示商品下标和当前探测结果。 - for index, item := range items { - if !item.IsMultiSpec { - t.Fatalf("item %d was not marked multi spec", index) - } - } - // cachedItems 保存第二次调用使用的商品列表,验证命中跨请求缓存。 - cachedItems := make([]mtop.ItemListItem, 8) - // index 表示缓存测试商品下标。 - for index := range cachedItems { - cachedItems[index].ID = fmt.Sprintf("probe-%d", index) - } - // err 表示第二次商品多规格探测错误。 - if err := srv.enrichSyncedItemMultiSpec(context.Background(), client, "unb=1; _m_h5_tk=t_1;", "acc1", cachedItems); err != nil { - t.Fatalf("cached enrich multi spec: %v", err) - } - if probeCalls != 8 { - t.Fatalf("cached probe calls=%d want 8", probeCalls) - } - // flags、err 保存数据库批量标记查询结果及错误,确认本地查询未误报候选商品。 - flags, err := store.Items.MultiSpecFlags(context.Background(), "acc1", []string{"probe-0"}) - if err != nil || len(flags) != 0 { - t.Fatalf("unexpected local flags=%v err=%v", flags, err) - } -} - -// TestItemSpecCacheExpires 验证商品多规格缓存过期后不会继续返回旧值。 -func TestItemSpecCacheExpires(t *testing.T) { - // srv 是仅用于验证商品多规格缓存生命周期的服务实例。 - srv := &Server{itemSpecCache: map[string]itemSpecCacheEntry{ - itemSpecCacheKey("acc1", "item-1"): {isMultiSpec: true, expiresAt: time.Now().Add(-time.Second)}, - }} - // value、ok 保存过期缓存的读取结果。 - value, ok := srv.cachedItemSpec("acc1", "item-1") - if ok || value { - t.Fatalf("expired cache should miss: value=%v ok=%v", value, ok) - } - srv.cacheItemSpec("acc1", "item-1", false) - value, ok = srv.cachedItemSpec("acc1", "item-1") - if !ok || value { - t.Fatalf("fresh false cache mismatch: value=%v ok=%v", value, ok) - } -} - // TestSyncItemsFromAccountFail mtop 返回非成功 → 502。 func TestSyncItemsFromAccountFail(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 @@ -1000,6 +951,22 @@ func TestItemCRUD(t *testing.T) { if rec4.Code != 200 { t.Fatalf("multi-qty status=%d", rec4.Code) } + // multiSpecBody 保存多规格开关请求,验证独立开关端点仍经商品写应用服务落库。 + multiSpecBody := `{"is_multi_spec":false}` + // reqSpec 保存多规格开关请求。 + reqSpec := httptest.NewRequest(http.MethodPut, "/items/acc1/it-crud/multi-spec", strings.NewReader(multiSpecBody)) + reqSpec.AddCookie(cookie) + // recSpec 保存多规格开关响应。 + recSpec := httptest.NewRecorder() + h.ServeHTTP(recSpec, reqSpec) + if recSpec.Code != http.StatusOK { + t.Fatalf("multi-spec status=%d body=%s", recSpec.Code, recSpec.Body.String()) + } + // switched, switchErr 保存两个开关端点写入后的商品记录及读取错误。 + switched, switchErr := store.Items.Get(ctx, "acc1", "it-crud") + if switchErr != nil || switched.IsMultiSpec || !switched.MultiQuantityDelivery { + t.Fatalf("开关更新未完整落库: item=%+v err=%v", switched, switchErr) + } // 删除。 req5 := httptest.NewRequest(http.MethodDelete, "/items/acc1/it-crud", nil) @@ -1010,6 +977,10 @@ func TestItemCRUD(t *testing.T) { if rec5.Code != 200 { t.Fatalf("delete status=%d", rec5.Code) } + // deletedErr 保存删除后的详情读取结果,验证删除动作通过商品仓储的逻辑删除边界。 + if _, deletedErr := store.Items.Get(ctx, "acc1", "it-crud"); deletedErr == nil { + t.Fatal("删除后的商品不应继续出现在商品详情查询中") + } } // TestListItemsFiltersByOwnedAccount 负责TestList商品列表FiltersByOwned账号相关处理。 @@ -1081,7 +1052,7 @@ func TestItemGetNotFound(t *testing.T) { // TestCreateItem 新建商品。 func TestCreateItem(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // h 保存h,供当前处理流程使用 h := srv.Router() @@ -1089,7 +1060,7 @@ func TestCreateItem(t *testing.T) { cookie := loginHelper(t, h) // body 保存请求体,供当前处理流程使用 - body := `{"item_id":"new-item","item_title":"新商品","item_price":"10.00"}` + body := `{"item_id":"new-item","item_title":"新商品","item_price":"10.00","is_multi_qty_ship":true}` // req 保存req,供当前处理流程使用 req := httptest.NewRequest(http.MethodPost, "/items/acc1", strings.NewReader(body)) req.AddCookie(cookie) @@ -1099,6 +1070,14 @@ func TestCreateItem(t *testing.T) { if rec.Code != 200 { t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String()) } + // created、createErr 保存应用服务创建后的商品记录及读取错误。 + created, createErr := store.Items.Get(context.Background(), "acc1", "new-item") + if createErr != nil { + t.Fatalf("读取新建商品失败: %v", createErr) + } + if created.ItemTitle != "新商品" || created.ItemPrice != "10.00" || !created.MultiQuantityDelivery { + t.Fatalf("创建字段或历史别名归一化异常: %+v", created) + } } // TestCreateItemMissingID 缺商品 ID 400。 diff --git a/internal/server/item_publish_batch_handlers.go b/internal/server/item_publish_batch_handlers.go index 225dedb..1614085 100644 --- a/internal/server/item_publish_batch_handlers.go +++ b/internal/server/item_publish_batch_handlers.go @@ -16,11 +16,10 @@ import ( "github.com/go-chi/chi/v5" + "xianyu-go/internal/adapter" + accountapp "xianyu-go/internal/application/account" itemapp "xianyu-go/internal/application/items" "xianyu-go/internal/auth" - "xianyu-go/internal/automation" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/mtop" ) // maxPublishBatchRows 保存max发布批次Rows,供当前处理流程使用 @@ -58,61 +57,38 @@ type publishBatchPreviewRow struct { Price string `json:"price"` Quantity int `json:"quantity"` Images []string `json:"images"` - Category mtop.PublishCategory `json:"category"` + Category publishCategoryResponse `json:"category"` Automation publishAutomationConfig `json:"automation"` } -// publishBatchParsedRow 保存发布批次解析结果Row,供当前处理流程使用 -type publishBatchParsedRow struct { - RowNo int - CookieID string - Title string - Description string - Price string - OriginalPrice string - Quantity int - PostageMode string - Postage string - Images []string - Category mtop.PublishCategory - Automation publishAutomationConfig - Errors []string - Raw map[string]any -} - -// publishAutomationConfig 保存发布自动化配置,供当前处理流程使用 -type publishAutomationConfig struct { - PaidDelivery publishCardAutomation `json:"paid_delivery"` - ReviewGift publishCardAutomation `json:"review_gift"` - ReviewRequest publishReviewRequestCfg `json:"review_request"` -} - -// publishCardAutomation 保存发布卡密自动化,供当前处理流程使用 -type publishCardAutomation struct { - Enabled bool `json:"enabled"` - Actions []publishCardAction `json:"actions"` - ParseError string `json:"-"` -} - -// publishCardAction 保存发布卡密动作,供当前处理流程使用 -type publishCardAction struct { - CardID int64 `json:"card_id"` - DeliveryCount int `json:"delivery_count"` - DelaySeconds int `json:"delay_seconds"` -} - -// publishReviewRequestCfg 保存发布Review请求Cfg,供当前处理流程使用 -type publishReviewRequestCfg struct { - Enabled bool `json:"enabled"` - AfterShippedHours int `json:"after_shipped_hours"` - Message string `json:"message"` - MaxAttempts int `json:"max_attempts"` - DelaySeconds int `json:"delay_seconds"` -} - -// publishCategoryRecommender 保存发布分类Recommender,供当前处理流程使用 -type publishCategoryRecommender interface { - RecommendPublishCategory(ctx context.Context, cookiesStr, keyword string) (mtop.PublishCategory, string, error) +// publishBatchPreviewApplicationResponse 将应用预检结果映射为既有 HTTP DTO。 +func publishBatchPreviewApplicationResponse(result itemapp.BatchPreviewPersistenceResult) itemPublishBatchPreviewResponse { + // rows 保存兼容前端字段命名的逐行预检结果。 + rows := make([]publishBatchPreviewRow, 0, len(result.Rows)) + // row 表示当前待映射的应用预检行。 + for _, row := range result.Rows { + // previewRow 保存当前应用行对应的 HTTP 边界模型。 + previewRow := publishBatchPreviewRow{ + RowNo: row.RowNo, Valid: len(row.Errors) == 0, Errors: row.Errors, CookieID: row.CookieID, + Title: row.Title, Price: row.Price, Quantity: row.Quantity, Images: row.Images, + Category: publishCategoryResponse{CatID: row.Category.CatID, CatName: row.Category.CatName, ChannelCatID: row.Category.ChannelCatID, TBCatID: row.Category.TBCatID}, + Automation: publishAutomationConfig{ + PaidDelivery: publishCardAutomation{Enabled: row.Automation.PaidDelivery.Enabled, ParseError: row.Automation.PaidDelivery.ParseError}, + ReviewGift: publishCardAutomation{Enabled: row.Automation.ReviewGift.Enabled, ParseError: row.Automation.ReviewGift.ParseError}, + ReviewRequest: publishReviewRequestCfg{Enabled: row.Automation.ReviewRequest.Enabled, AfterShippedHours: row.Automation.ReviewRequest.AfterShippedHours, Message: row.Automation.ReviewRequest.Message, MaxAttempts: row.Automation.ReviewRequest.MaxAttempts, DelaySeconds: row.Automation.ReviewRequest.DelaySeconds}, + }, + } + // action 表示当前应用行中的付款发货动作。 + for _, action := range row.Automation.PaidDelivery.Actions { + previewRow.Automation.PaidDelivery.Actions = append(previewRow.Automation.PaidDelivery.Actions, publishCardAction{CardID: action.CardID, DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds}) + } + // action 表示当前应用行中的评价赠品动作。 + for _, action := range row.Automation.ReviewGift.Actions { + previewRow.Automation.ReviewGift.Actions = append(previewRow.Automation.ReviewGift.Actions, publishCardAction{CardID: action.CardID, DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds}) + } + rows = append(rows, previewRow) + } + return itemPublishBatchPreviewResponse{Success: result.Success, PreviewID: result.PreviewID, Total: result.Total, Valid: result.Valid, Invalid: result.Invalid, Rows: rows} } // recommendItemPublishCategory 解析类目关键词并返回平台推荐类目。 @@ -143,28 +119,28 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req return } // category、callErr 保存category、callErr,供当前处理流程使用 - category, callErr := s.itemPublishApplication().RecommendCategory(r.Context(), userID, req.CookieID, req.Keyword) + category, callErr := s.itemCategoryRecommendationApplication().Recommend(r.Context(), userID, req.CookieID, req.Keyword) if callErr != nil { - if strings.Contains(callErr.Error(), "当前 MTOP 客户端不支持") { + if errors.Is(callErr, itemapp.ErrCategoryUnsupported) { writeErr(w, http.StatusNotImplemented, callErr.Error()) return } - if strings.Contains(callErr.Error(), "账号凭证已变化") { + if errors.Is(callErr, itemapp.ErrCategoryCredentialChanged) { writeErr(w, http.StatusConflict, callErr.Error()) return } - if strings.Contains(callErr.Error(), "保存账号登录状态") { + if errors.Is(callErr, itemapp.ErrCategoryPersistence) { writeErr(w, http.StatusInternalServerError, callErr.Error()) return } - if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) { + if errors.Is(callErr, itemapp.ErrCategoryUnrecognized) { writeErr(w, http.StatusNotFound, "没有匹配到可发布类目,请换一个关键词") return } writeErr(w, http.StatusBadGateway, callErr.Error()) return } - writeJSON(w, http.StatusOK, categoryRecommendationResponse{Success: true, Category: category}) + writeJSON(w, http.StatusOK, categoryRecommendationResponse{Success: true, Category: publishCategoryResponse{CatID: category.CatID, CatName: category.CatName, ChannelCatID: category.ChannelCatID, TBCatID: category.TBCatID}}) } // previewItemPublishBatch 处理表格上传、图片归档和批量发布预检。 @@ -185,19 +161,25 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) writeErr(w, http.StatusBadRequest, "请选择默认发布账号") return } - if !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) { + // defaultOwned 和 ownershipErr 表示默认账号归属复核结果及基础设施错误。 + defaultOwned, ownershipErr := s.itemBatchPreviewApplication().CookieOwned(r.Context(), sess.UserID, defaultCookieID) + if ownershipErr != nil { + writeErr(w, http.StatusInternalServerError, "校验默认发布账号失败") + return + } + if !defaultOwned { writeErr(w, http.StatusForbidden, "默认账号不属于当前用户") return } // fallbackCategory 保存fallback分类,供当前处理流程使用 - fallbackCategory := mtop.PublishCategory{ + fallbackCategory := publishCategoryResponse{ CatID: strings.TrimSpace(r.FormValue("fallback_category_id")), CatName: strings.TrimSpace(r.FormValue("fallback_category_name")), ChannelCatID: strings.TrimSpace(r.FormValue("fallback_channel_category_id")), TBCatID: strings.TrimSpace(r.FormValue("fallback_tb_category_id")), } // batchLocation 保存批次地址,供当前处理流程使用 - var batchLocation mtop.PublishLocation + var batchLocation publishBatchLocation // locationJSON 保存地址JSON,供当前处理流程使用 locationJSON := strings.TrimSpace(r.FormValue("location")) if locationJSON != "" { @@ -287,7 +269,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) } // maps、err 保存maps、err,供当前处理流程使用 - maps, err := parsePublishSheetBytesWithLimit(sourceBytes, sourceName, maxPublishBatchRows) + maps, err := itemapp.ParseSheet(sourceBytes, sourceName, maxPublishBatchRows) if err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return @@ -296,15 +278,27 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) writeErr(w, http.StatusBadRequest, fmt.Sprintf("单个批次最多支持 %d 条商品", maxPublishBatchRows)) return } - // parsed 保存解析结果,供当前处理流程使用 - parsed := s.parsePublishRows(r.Context(), sess.UserID, defaultCookieID, uploadDir, fallbackCategory, maps) - // preview、err 保存preview、err,供当前处理流程使用 - preview, err := s.itemPublishApplication().PersistPreview(r.Context(), itemPublishPreviewInput{ - UserID: sess.UserID, BatchID: batchID, DefaultCookieID: defaultCookieID, - Filename: sourceName, UploadDir: uploadDir, Location: batchLocation, Rows: parsed, + // previewRows 保存应用服务归一化并校验后的逐行结果。 + previewRows, err := s.itemBatchPreviewApplication().Preview(r.Context(), itemapp.BatchPreviewInput{ + UserID: sess.UserID, DefaultCookieID: defaultCookieID, UploadDir: uploadDir, + FallbackCategory: itemapp.BatchPreviewCategory{CatID: fallbackCategory.CatID, CatName: fallbackCategory.CatName, ChannelCatID: fallbackCategory.ChannelCatID, TBCatID: fallbackCategory.TBCatID}, + Rows: maps, }) if err != nil { - if errors.Is(err, errItemPublishBatchNoRows) { + if errors.Is(err, itemapp.ErrBatchPreviewNoRows) { + writeErr(w, http.StatusBadRequest, "表格中没有有效数据行") + } else { + writeErr(w, http.StatusBadRequest, err.Error()) + } + return + } + // preview、err 保存预检结果持久化服务返回的应用模型及错误。 + preview, err := s.itemBatchPreviewPersistenceApplication().Persist(r.Context(), itemapp.BatchPreviewPersistenceBatch{ + ID: batchID, UserID: sess.UserID, DefaultCookieID: defaultCookieID, Filename: sourceName, + UploadDir: uploadDir, Location: itemapp.Location{Area: batchLocation.Area, City: batchLocation.City, DivisionID: batchLocation.DivisionID, Longitude: batchLocation.Longitude, Latitude: batchLocation.Latitude, POIID: batchLocation.POIID, POIName: batchLocation.POIName, Province: batchLocation.Province}, + }, previewRows) + if err != nil { + if errors.Is(err, itemapp.ErrBatchPreviewNoRows) { writeErr(w, http.StatusBadRequest, "表格中没有有效数据行") } else { writeErr(w, http.StatusInternalServerError, "保存预检结果失败") @@ -312,85 +306,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) return } keepUpload = true - writeJSON(w, http.StatusOK, preview) - /* - rows := make([]db.ItemPublishBatchRow, 0, len(parsed)) - previewRows := make([]publishBatchPreviewRow, 0, len(parsed)) - valid, invalid := 0, 0 - for _, p := range parsed { - isValid := len(p.Errors) == 0 - if isValid { - valid++ - } else { - invalid++ - } - imagesJSON, _ := json.Marshal(p.Images) - categoryJSON, _ := json.Marshal(p.Category) - automationJSON, _ := json.Marshal(p.Automation) - rawJSON, _ := json.Marshal(p.Raw) - status := "pending" - errMsg := "" - if !isValid { - status = "failed" - errMsg = strings.Join(p.Errors, ";") - } - rows = append(rows, db.ItemPublishBatchRow{ - RowNo: p.RowNo, - CookieID: p.CookieID, - Title: p.Title, - Description: p.Description, - Price: p.Price, - OriginalPrice: p.OriginalPrice, - Quantity: p.Quantity, - PostageMode: p.PostageMode, - Postage: p.Postage, - ImagesJSON: string(imagesJSON), - CategoryJSON: string(categoryJSON), - AutomationJSON: string(automationJSON), - Status: status, - ErrorMessage: errMsg, - FailureKind: map[bool]string{true: "", false: "validation"}[isValid], - RawJSON: string(rawJSON), - }) - previewRows = append(previewRows, publishBatchPreviewRow{ - RowNo: p.RowNo, - Valid: isValid, - Errors: p.Errors, - CookieID: p.CookieID, - Title: p.Title, - Price: p.Price, - Quantity: p.Quantity, - Images: p.Images, - Category: p.Category, - Automation: p.Automation, - }) - } - if len(rows) == 0 { - writeErr(w, http.StatusBadRequest, "表格中没有有效数据行") - return - } - if err := s.itemPublishRepositoryForServer().CreateBatch(r.Context(), &db.ItemPublishBatch{ - ID: batchID, - UserID: sess.UserID, - DefaultCookieID: defaultCookieID, - Filename: sourceName, - UploadDir: uploadDir, - LocationJSON: string(locationBytes), - Status: "preview", - }, rows); err != nil { - writeErr(w, http.StatusInternalServerError, "保存预检结果失败") - return - } - keepUpload = true - _ = s.itemPublishRepositoryForServer().RecountBatch(r.Context(), batchID) - // 预检响应保留逐行错误,客户端据此决定是否允许启动发布。 - // preview_id 是后续启动、轮询和放弃预检的稳定标识。 - // total、valid 和 invalid 继续使用旧统计口径。 - // rows 保留类目和自动化配置,避免前端重复解析上传表格。 - // 预检成功不代表远端商品已经发布。 - // 远端发布失败仍由批次明细状态表达。 - // 该 DTO 不改变上传目录清理和批次持久化时序。 - writeJSON(w, http.StatusOK, itemPublishBatchPreviewResponse{Success: true, PreviewID: batchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows})*/ + writeJSON(w, http.StatusOK, publishBatchPreviewApplicationResponse(preview)) } // startItemPublishBatch 启动指定批次的后台发布 worker。 @@ -417,16 +333,16 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) { return } // startedID、err 保存startedID、err,供当前处理流程使用 - startedID, err := s.itemPublishApplication().StartBatch(r.Context(), sess.UserID, batchID) + startedID, err := s.itemBatchManagementApplication().StartBatch(r.Context(), sess.UserID, batchID, publishBatchLease) if err != nil { switch { - case errors.Is(err, errItemPublishBatchNotFound): + case errors.Is(err, itemapp.ErrBatchNotFound): writeErr(w, http.StatusNotFound, "批量任务不存在") - case errors.Is(err, errItemPublishBatchConflict): + case errors.Is(err, itemapp.ErrBatchConflict): writeErr(w, http.StatusConflict, "任务正在由其他 worker 运行") - case errors.Is(err, errItemPublishBatchInvalidState): + case errors.Is(err, itemapp.ErrBatchInvalidState): writeErr(w, http.StatusBadRequest, "当前任务状态不能开始发布") - case errors.Is(err, errItemPublishBatchNoRows): + case errors.Is(err, itemapp.ErrBatchNoRows): writeErr(w, http.StatusBadRequest, "没有可发布的商品行") default: writeErr(w, http.StatusInternalServerError, "启动任务失败") @@ -443,11 +359,17 @@ func (s *Server) listItemPublishBatches(w http.ResponseWriter, r *http.Request) // limit 保存上限,供当前处理流程使用 limit := atoiDefault(r.URL.Query().Get("limit"), 20) // result、err 保存result、err,供当前处理流程使用 - result, err := s.itemPublishApplication().ListBatches(r.Context(), sess.UserID, limit) + batches, err := s.itemBatchManagementApplication().ListBatches(r.Context(), sess.UserID, limit) if err != nil { writeErr(w, http.StatusInternalServerError, "读取批量任务失败") return } + // result 保存应用批次转换后的兼容 HTTP 响应。 + result := make([]itemPublishBatchResponse, 0, len(batches)) + // batch 表示当前待转换的应用批次摘要。 + for _, batch := range batches { + result = append(result, publishBatchApplicationToResponse(batch, nil)) + } writeJSON(w, http.StatusOK, itemPublishBatchListResponse{Batches: result}) } @@ -458,16 +380,16 @@ func (s *Server) getItemPublishBatch(w http.ResponseWriter, r *http.Request) { // batchID 保存批次ID,供当前处理流程使用 batchID := chi.URLParam(r, "batch_id") // result、err 保存result、err,供当前处理流程使用 - result, err := s.itemPublishApplication().GetBatch(r.Context(), sess.UserID, batchID) + details, err := s.itemBatchManagementApplication().GetBatch(r.Context(), sess.UserID, batchID) if err != nil { - if errors.Is(err, errItemPublishBatchNotFound) { + if errors.Is(err, itemapp.ErrBatchNotFound) { writeErr(w, http.StatusNotFound, "批量任务不存在") } else { writeErr(w, http.StatusInternalServerError, "读取任务明细失败") } return } - writeJSON(w, http.StatusOK, result) + writeJSON(w, http.StatusOK, publishBatchApplicationToResponse(details.Batch, details.Rows)) } // cancelItemPublishBatch 请求取消指定批次并通知运行中的 worker。 @@ -477,11 +399,11 @@ func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request) // batchID 保存批次ID,供当前处理流程使用 batchID := chi.URLParam(r, "batch_id") // status、err 保存status、err,供当前处理流程使用 - status, err := s.itemPublishApplication().CancelBatch(r.Context(), sess.UserID, batchID) + status, err := s.itemBatchManagementApplication().CancelBatch(r.Context(), sess.UserID, batchID) if err != nil { - if errors.Is(err, errItemPublishBatchNotFound) { + if errors.Is(err, itemapp.ErrBatchNotFound) { writeErr(w, http.StatusNotFound, "批量任务不存在") - } else if errors.Is(err, errItemPublishBatchConflict) { + } else if errors.Is(err, itemapp.ErrBatchConflict) { writeErr(w, http.StatusConflict, "任务状态刚刚发生变化,请重试") } else { writeErr(w, http.StatusInternalServerError, "取消任务失败") @@ -498,20 +420,17 @@ func (s *Server) deleteItemPublishBatch(w http.ResponseWriter, r *http.Request) // batchID 保存批次ID,供当前处理流程使用 batchID := chi.URLParam(r, "batch_id") // uploadDir、err 保存uploadDir、err,供当前处理流程使用 - uploadDir, err := s.itemPublishApplication().DeleteBatch(r.Context(), sess.UserID, batchID) + err := s.itemBatchManagementApplication().DeleteBatch(r.Context(), sess.UserID, batchID) if err != nil { - if errors.Is(err, errItemPublishBatchNotFound) { + if errors.Is(err, itemapp.ErrBatchNotFound) { writeErr(w, http.StatusNotFound, "批量任务不存在") - } else if errors.Is(err, errItemPublishBatchConflict) { + } else if errors.Is(err, itemapp.ErrBatchConflict) { writeErr(w, http.StatusConflict, "运行中的任务不能删除,请先取消") } else { writeErr(w, http.StatusInternalServerError, "删除批量任务失败") } return } - if strings.TrimSpace(uploadDir) != "" { - _ = os.RemoveAll(uploadDir) - } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } @@ -522,13 +441,13 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ // batchID 保存批次ID,供当前处理流程使用 batchID := chi.URLParam(r, "batch_id") // startedID、err 保存startedID、err,供当前处理流程使用 - startedID, err := s.itemPublishApplication().RetryFailedBatch(r.Context(), sess.UserID, batchID) + startedID, err := s.itemBatchManagementApplication().RetryFailedBatch(r.Context(), sess.UserID, batchID, publishBatchLease) if err != nil { - if errors.Is(err, errItemPublishBatchNotFound) { + if errors.Is(err, itemapp.ErrBatchNotFound) { writeErr(w, http.StatusNotFound, "批量任务不存在") - } else if errors.Is(err, errItemPublishBatchConflict) { + } else if errors.Is(err, itemapp.ErrBatchConflict) { writeErr(w, http.StatusConflict, "任务正在运行,不能重复重试") - } else if errors.Is(err, errItemPublishBatchNoRows) { + } else if errors.Is(err, itemapp.ErrBatchNoRows) { writeErr(w, http.StatusBadRequest, "没有可重试的失败项") } else { writeErr(w, http.StatusInternalServerError, "启动重试失败") @@ -584,55 +503,9 @@ func (s *Server) StartPublishBatchRecovery(ctx context.Context) string { // recoverPublishBatchesOnce 负责recover发布批次列表Once相关处理。 func (s *Server) recoverPublishBatchesOnce(ctx context.Context) { - // batches、err 保存batches、err,供当前处理流程使用 - batches, err := s.itemPublishRepositoryForServer().RecoverableBatches(ctx, time.Now().UTC().Unix(), 20) - if err != nil { + // err 保存恢复扫描应用服务返回的全局查询错误。 + if err := s.itemBatchRecoveryApplication().Recover(ctx); err != nil && s.Logger != nil { s.Logger.Warn("扫描可恢复批量发布任务失败", "err", err) - return - } - // batch 表示当前遍历过程中的批次 - for _, batch := range batches { - if batch.Status == "canceling" { - _, _ = s.itemPublishRepositoryForServer().FinalizeExpiredCancellation(ctx, batch.ID, time.Now().UTC().Unix()) - continue - } - // workerToken 保存工作器令牌,供当前处理流程使用 - workerToken := randomHex(16) - // claimed、claimErr 保存claimed、claimErr,供当前处理流程使用 - claimed, claimErr := s.itemPublishRepositoryForServer().ClaimBatch(ctx, batch.ID, workerToken, time.Now().UTC().Add(publishBatchLease).Unix()) - if claimErr != nil || !claimed { - continue - } - if // err 保存err,供当前处理流程使用 - err := s.itemPublishRepositoryForServer().ResetInterrupted(ctx, batch.ID); err != nil { - s.failClaimedPublishBatch(batch.ID, workerToken) - continue - } - _ = s.itemPublishRepositoryForServer().RecountBatch(ctx, batch.ID) - // pending、pendingErr 保存pending、pendingErr,供当前处理流程使用 - pending, pendingErr := s.itemPublishRepositoryForServer().PendingRows(ctx, batch.ID, false) - if pendingErr != nil || len(pending) == 0 { - if pendingErr == nil { - _, _, _ = s.itemPublishRepositoryForServer().FinalizeBatch(ctx, batch.ID, workerToken) - } else { - s.failClaimedPublishBatch(batch.ID, workerToken) - } - continue - } - s.startPublishBatchWorker(ctx, batch.UserID, batch.ID, workerToken) - } -} - -// failClaimedPublishBatch 负责failClaimed发布批次相关处理。 -func (s *Server) failClaimedPublishBatch(batchID, workerToken string) { - // ctx、cancel 保存ctx、cancel,供当前处理流程使用 - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if // released、err 保存released、err,供当前处理流程使用 - released, err := s.itemPublishRepositoryForServer().FailClaimedBatch(ctx, batchID, workerToken); err != nil { - s.Logger.Warn("释放异常批量发布任务失败", "batch", batchID, "err", err) - } else if !released { - s.Logger.Debug("批量发布任务租约已转移,无需释放", "batch", batchID) } } @@ -642,18 +515,18 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R sess := auth.SessionFromContext(r.Context()) // batchID 保存批次ID,供当前处理流程使用 batchID := chi.URLParam(r, "batch_id") - // batch、err 保存batch、err,供当前处理流程使用 - batch, err := s.itemPublishRepositoryForServer().GetBatch(r.Context(), sess.UserID, batchID) + // details、err 保存应用服务返回的批次及明细。 + details, err := s.itemBatchManagementApplication().GetBatch(r.Context(), sess.UserID, batchID) if err != nil { - writeErr(w, http.StatusNotFound, "批量任务不存在") - return - } - // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.itemPublishRepositoryForServer().ListBatchRows(r.Context(), batch.ID) - if err != nil { - writeErr(w, http.StatusInternalServerError, "读取任务明细失败") + if errors.Is(err, itemapp.ErrBatchNotFound) { + writeErr(w, http.StatusNotFound, "批量任务不存在") + } else { + writeErr(w, http.StatusInternalServerError, "读取任务明细失败") + } return } + // rows 保存应用层批次明细,后续只负责转换为下载 DTO。 + rows := details.Rows // buf 保存buf,供当前处理流程使用 var buf bytes.Buffer buf.WriteString("\xEF\xBB\xBF") @@ -663,7 +536,7 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R // row 表示当前导出的批量明细行。 for _, row := range rows { // category 保存分类,供当前处理流程使用 - var category mtop.PublishCategory + var category publishCategoryResponse _ = json.Unmarshal([]byte(row.CategoryJSON), &category) _ = cw.Write([]string{ strconv.Itoa(row.RowNo), safeCSVCell(row.Status), safeCSVCell(row.CookieID), safeCSVCell(row.Title), safeCSVCell(row.Price), @@ -673,7 +546,7 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R } cw.Flush() // filename 保存filename,供当前处理流程使用 - filename := fmt.Sprintf("publish_result_%s.csv", batch.ID) + filename := fmt.Sprintf("publish_result_%s.csv", details.Batch.ID) w.Header().Set("Content-Type", "text/csv; charset=utf-8") w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filename)) _, _ = w.Write(buf.Bytes()) @@ -706,10 +579,14 @@ func publishBatchFailure(err error, batchStatus string) (string, string) { var postErr *postPublishError // uncertainErr 保存uncertainErr,供当前处理流程使用 var uncertainErr *uncertainRemotePublishError - if errors.As(err, &uncertainErr) { + // appUncertainErr 保存应用批量端口返回的远端不确定错误。 + var appUncertainErr *itemapp.UncertainRemotePublishError + // appPostErr 保存应用批量端口返回的后置处理错误。 + var appPostErr *itemapp.PostPublishError + if errors.As(err, &uncertainErr) || errors.As(err, &appUncertainErr) { failureKind = "uncertain_remote" message += ";远端结果未能可靠落库,禁止自动重试,请人工核对闲鱼商品列表" - } else if errors.As(err, &postErr) { + } else if errors.As(err, &postErr) || errors.As(err, &appPostErr) { failureKind = "post_publish" } if batchStatus == "canceled" || batchStatus == "canceling" { @@ -759,16 +636,22 @@ func (s *Server) cancelPublishBatch(batchID, workerToken string) bool { return true } -// publishStatusContext 负责发布状态上下文相关处理。 -func publishStatusContext(parent context.Context) (context.Context, context.CancelFunc) { - if parent != nil && parent.Err() == nil { - return context.WithTimeout(parent, 5*time.Second) +// completeBatchPublishOutcome 将远端结果交给应用服务完成本地状态收口。 +func (s *Server) completeBatchPublishOutcome(ctx context.Context, userID int64, localService *itemapp.BatchLocalPublishService, row itemapp.BatchRow, workerToken string, outcome itemapp.BatchPublishOutcome) error { + if localService == nil { + return errors.New("批量发布本地收口端口未装配") } - return context.WithTimeout(context.Background(), 5*time.Second) + if outcome.ResponseCookieErr != nil { + return &postPublishError{err: outcome.ResponseCookieErr} + } + if ctx.Err() != nil { + return &postPublishError{err: ctx.Err()} + } + return localService.Complete(ctx, userID, row, workerToken, outcome.Result) } -// finalPublishBatchStatus 负责final发布批次状态相关处理。 -func finalPublishBatchStatus(batch *db.ItemPublishBatch) string { +// finalPublishBatchStatus 根据应用批次统计返回兼容的最终状态。 +func finalPublishBatchStatus(batch *itemapp.BatchInfo) string { if batch == nil { return "failed" } @@ -781,572 +664,18 @@ func finalPublishBatchStatus(batch *db.ItemPublishBatch) string { return "completed" } -// publishBatchRow 负责发布批次Row相关处理。 -func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.Client, row db.ItemPublishBatchRow, workerToken string) error { - // batch、err 保存batch、err,供当前处理流程使用 - batch, err := s.itemPublishRepositoryForServer().GetBatch(ctx, userID, row.BatchID) - if err != nil { - return errors.New("批量任务不存在") - } - // location 保存地址,供当前处理流程使用 - var location mtop.PublishLocation - // locationJSON 保存地址JSON,供当前处理流程使用 +// publishBatchApplicationToResponse 将应用批次模型映射为现有 HTTP 响应 DTO。 +func publishBatchApplicationToResponse(batch itemapp.BatchInfo, rows []itemapp.BatchRow) itemPublishBatchResponse { + // locationJSON 保存批次发货地配置;空值时保持旧响应的空对象语义。 locationJSON := strings.TrimSpace(batch.LocationJSON) if locationJSON == "" { locationJSON = "{}" } - if // err 保存err,供当前处理流程使用 - err := json.Unmarshal([]byte(locationJSON), &location); err != nil { - return errors.New("批量任务发货地配置损坏,请重新创建任务") - } - // selectedLocation 保存selected地址,供当前处理流程使用 - var selectedLocation *mtop.PublishLocation - if strings.TrimSpace(location.DivisionID) != "" { - selectedLocation = &location - } - // cookieValue、err 保存登录凭证Value、err,供当前处理流程使用 - cookieValue, err := s.cookieValueForUser(ctx, userID, row.CookieID) - if err != nil { - return err - } - // priceCents、err 保存priceCents、err,供当前处理流程使用 - priceCents, err := parseMoneyCents(row.Price) - if err != nil || priceCents <= 0 { - return errors.New("商品价格必须大于 0") - } - // origCents 保存origCents,供当前处理流程使用 - origCents, _ := parseMoneyCents(row.OriginalPrice) - // postageCents 保存postageCents,供当前处理流程使用 - postageCents, _ := parseMoneyCents(row.Postage) - // res 保存响应,供当前处理流程使用 - res := &mtop.PublishItemResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity} - // responseCookieErr 保存响应登录凭证Err,供当前处理流程使用 - var responseCookieErr error - if row.ItemID == "" { - // preferredCategory 保存preferred分类,供当前处理流程使用 - var preferredCategory *mtop.PublishCategory - // rawCategory 保存原始分类,供当前处理流程使用 - rawCategory := strings.TrimSpace(row.CategoryJSON) - if rawCategory != "" && rawCategory != "{}" { - // configured 保存configured,供当前处理流程使用 - var configured mtop.PublishCategory - if // err 保存err,供当前处理流程使用 - err := json.Unmarshal([]byte(rawCategory), &configured); err != nil { - return errors.New("默认类目配置损坏,请重新创建批量任务") - } - if strings.TrimSpace(configured.CatID) != "" || strings.TrimSpace(configured.CatName) != "" || strings.TrimSpace(configured.ChannelCatID) != "" || strings.TrimSpace(configured.TBCatID) != "" { - if strings.TrimSpace(configured.CatID) == "" || strings.TrimSpace(configured.CatName) == "" || strings.TrimSpace(configured.ChannelCatID) == "" { - return errors.New("默认类目信息不完整,请重新创建批量任务") - } - preferredCategory = &configured - } - } - // images、err 保存images、err,供当前处理流程使用 - images, err := loadBatchPublishImages(ctx, batch.UploadDir, row) - if err != nil { - return err - } - // markCtx、markCancel 保存markCtx、mark取消,供当前处理流程使用 - markCtx, markCancel := publishStatusContext(ctx) - // remoteStarted、markErr 保存remoteStarted、markErr,供当前处理流程使用 - remoteStarted, markErr := s.itemPublishRepositoryForServer().MarkClaimedRemoteStarted(markCtx, row.ID, workerToken) - markCancel() - if markErr != nil || !remoteStarted { - return fmt.Errorf("保存远端发布前检查点失败: %w", firstError(markErr, errors.New("批次租约已失效"))) - } - // runtimeCookie 保存runtime登录凭证,供当前处理流程使用 - runtimeCookie := "" - // runtimeCookieChanged 保存runtime登录凭证Changed,供当前处理流程使用 - runtimeCookieChanged := false - res, err = func() (*mtop.PublishItemResult, error) { - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.itemPublishRepositoryForServer().LockCredentials(row.CookieID) - defer credentialUnlock() - // latest、latestErr 保存latest、latestErr,供当前处理流程使用 - latest, latestErr := s.loadCookiePlatformDetail(ctx, row.CookieID) - if latestErr != nil { - return nil, latestErr - } - if latest == nil || latest.UserID != userID { - return nil, db.ErrForbidden - } - if !hasStoredCookieCredential(latest) { - return nil, errors.New("账号 Cookie 为空") - } - cookieValue = latest.Value - // pctx、cancel 保存pctx、cancel,供当前处理流程使用 - pctx, cancel := context.WithTimeout(ctx, 2*time.Minute) - defer cancel() - // mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用 - mtopCtx, cookieSession := withMTopCookieSnapshot(pctx, latest) - // published、publishErr 保存published、publishErr,供当前处理流程使用 - published, publishErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{ - Title: row.Title, - Description: firstNonEmpty(row.Description, row.Title), - PriceCents: priceCents, - OriginalPriceCents: origCents, - Quantity: row.Quantity, - PostageMode: row.PostageMode, - PostageCents: postageCents, - Virtual: true, - Location: selectedLocation, - PreferredCategory: preferredCategory, - Images: images, - }) - // value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用 - value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession) - if persistErr != nil { - // cookieErr 保存登录凭证Err,供当前处理流程使用 - cookieErr := fmt.Errorf("发布商品后保存响应 Cookie Jar: %w", persistErr) - if publishErr != nil { - return published, errors.Join(publishErr, cookieErr) - } - responseCookieErr = cookieErr - } else if handled { - if valueChanged { - runtimeCookie = value - runtimeCookieChanged = true - } - } else if publishErr == nil && published != nil && published.UpdatedCookies != "" && published.UpdatedCookies != cookieValue { - if // saveErr 保存saveErr,供当前处理流程使用 - saveErr := s.itemPublishRepositoryForServer().UpdateCookieValueOwned(ctx, row.CookieID, published.UpdatedCookies, userID); saveErr != nil { - responseCookieErr = fmt.Errorf("发布商品后保存响应 Cookie: %w", saveErr) - } else { - runtimeCookie = published.UpdatedCookies - runtimeCookieChanged = true - } - } - if publishErr != nil { - return published, publishErr - } - if published == nil { - return nil, errors.New("发布商品接口未返回结果") - } - return published, nil - }() - if runtimeCookieChanged { - s.updateRunningCookie(ctx, row.CookieID, runtimeCookie) - } - if err != nil { - s.recoverExpiredMTOPSession(ctx, row.CookieID, err) - if ctx.Err() != nil { - return &uncertainRemotePublishError{err: fmt.Errorf("取消时远端发布结果未知: %w", err)} - } - // perr 保存perr,供当前处理流程使用 - var perr *mtop.PublishError - if errors.As(err, &perr) { - if perr.Code == mtop.PublishErrorStockPermissionMissing { - return errors.New("该账号没有库存发布权限,无法按库存数量发布商品") - } - return err - } - if errors.Is(err, mtop.ErrPublishCategoryUnrecognized) { - return err - } - return &uncertainRemotePublishError{err: fmt.Errorf("远端发布调用失败且结果未知: %w", err)} - } - // rawJSON 保存原始JSON,供当前处理流程使用 - rawJSON, _ := json.Marshal(res.RawData) - // saveCtx、saveCancel 保存saveCtx、save取消,供当前处理流程使用 - saveCtx, saveCancel := publishStatusContext(ctx) - // saved、saveErr 保存saved、saveErr,供当前处理流程使用 - saved, saveErr := s.itemPublishRepositoryForServer().SaveClaimedRemoteResult(saveCtx, row.ID, workerToken, res.ItemID, res.ItemURL, string(rawJSON)) - saveCancel() - if saveErr != nil || !saved { - return &uncertainRemotePublishError{err: fmt.Errorf("保存远端发布结果失败: %w", firstError(saveErr, errors.New("批次租约已失效")))} - } - if responseCookieErr != nil { - return &postPublishError{err: responseCookieErr} - } - } else if strings.TrimSpace(row.RawJSON) != "" { - _ = json.Unmarshal([]byte(row.RawJSON), &res.RawData) - } - if ctx.Err() != nil { - return &postPublishError{err: ctx.Err()} - } - // currentBatch、err 保存currentBatch、err,供当前处理流程使用 - currentBatch, err := s.itemPublishRepositoryForServer().GetBatch(ctx, userID, row.BatchID) - if err != nil || currentBatch.Status == "canceled" || currentBatch.WorkerToken != workerToken { - return &postPublishError{err: context.Canceled} - } - if res.ItemID != "" { - // detail 保存detail,供当前处理流程使用 - detail := map[string]any{ - "item_image": res.ImageURL, - "web_url": res.ItemURL, - "category_name": res.CategoryName, - "quantity": res.Quantity, - "publish_raw": res.RawData, - } - // detailJSON 保存detailJSON,供当前处理流程使用 - detailJSON, _ := json.Marshal(detail) - if // err 保存err,供当前处理流程使用 - err := s.itemPublishRepositoryForServer().UpsertItem(ctx, &db.ItemInfoRow{ - CookieID: row.CookieID, - ItemID: res.ItemID, - ItemTitle: firstNonEmpty(res.Title, row.Title), - ItemDescription: row.Description, - ItemCategory: res.CategoryID, - ItemPrice: res.PriceText, - ItemDetail: string(detailJSON), - MultiQuantityDelivery: row.Quantity > 1, - }); err != nil { - return &postPublishError{err: fmt.Errorf("保存发布商品信息: %w", err)} - } - if // err 保存err,供当前处理流程使用 - err := s.createPublishAutomationRules(ctx, userID, row, res); err != nil { - return &postPublishError{err: fmt.Errorf("创建发布商品自动化规则: %w", err)} - } - } - // rawJSON 保存原始JSON,供当前处理流程使用 - rawJSON, _ := json.Marshal(res.RawData) - // marked、err 保存marked、err,供当前处理流程使用 - marked, err := s.itemPublishRepositoryForServer().MarkClaimedRowSuccess(ctx, row.ID, workerToken, res.ItemID, res.ItemURL, string(rawJSON)) - if err != nil { - return err - } - if !marked { - return errors.New("批量任务租约已失效") - } - return nil -} - -// firstError 负责first错误相关处理。 -func firstError(err, fallback error) error { - if err != nil { - return err - } - return fallback -} - -// createPublishAutomationRules 负责create发布自动化规则列表相关处理。 -func (s *Server) createPublishAutomationRules(ctx context.Context, userID int64, row db.ItemPublishBatchRow, res *mtop.PublishItemResult) error { - // cfg 保存cfg,供当前处理流程使用 - var cfg publishAutomationConfig - if // err 保存err,供当前处理流程使用 - err := json.Unmarshal([]byte(row.AutomationJSON), &cfg); err != nil { - return err - } - // title 保存标题,供当前处理流程使用 - title := firstNonEmpty(res.Title, row.Title) - if cfg.PaidDelivery.Enabled { - // actions 保存动作列表,供当前处理流程使用 - actions := make([]db.AutomationActionInput, 0, len(cfg.PaidDelivery.Actions)+1) - // index、action 表示当前遍历过程中的index、action - for index, action := range cfg.PaidDelivery.Actions { - // actionConfig 保存动作配置,供当前处理流程使用 - actionConfig, _ := json.Marshal(map[string]any{"delay_override": true}) - actions = append(actions, db.AutomationActionInput{ - ActionType: automation.ActionSendCard, CardID: action.CardID, - DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds, - ConfigJSON: string(actionConfig), Enabled: true, SortOrder: index + 1, - }) - } - actions = append(actions, db.AutomationActionInput{ - ActionType: automation.ActionConfirmShipment, Enabled: true, SortOrder: len(actions) + 1, - }) - if // err 保存err,供当前处理流程使用 - err := s.ensurePublishAutomationRule(ctx, db.AutomationRuleInput{ - UserID: userID, CookieID: row.CookieID, ItemID: res.ItemID, - Name: "付款后自动发货 - " + title, TriggerType: automation.TriggerOrderPaid, - Enabled: true, Priority: 100, ConfigJSON: "{}", - Actions: actions, - }); err != nil { - return err - } - } - if cfg.ReviewGift.Enabled { - // actions 保存动作列表,供当前处理流程使用 - actions := make([]db.AutomationActionInput, 0, len(cfg.ReviewGift.Actions)) - // index、action 表示当前遍历过程中的index、action - for index, action := range cfg.ReviewGift.Actions { - // actionConfig 保存动作配置,供当前处理流程使用 - actionConfig, _ := json.Marshal(map[string]any{"delay_override": true}) - actions = append(actions, db.AutomationActionInput{ - ActionType: automation.ActionSendCard, CardID: action.CardID, - DeliveryCount: action.DeliveryCount, DelaySeconds: action.DelaySeconds, - ConfigJSON: string(actionConfig), Enabled: true, SortOrder: index + 1, - }) - } - if // err 保存err,供当前处理流程使用 - err := s.ensurePublishAutomationRule(ctx, db.AutomationRuleInput{ - UserID: userID, CookieID: row.CookieID, ItemID: res.ItemID, - Name: "评价后发送赠品 - " + title, TriggerType: automation.TriggerBuyerReviewed, - Enabled: true, Priority: 100, ConfigJSON: "{}", - Actions: actions, - }); err != nil { - return err - } - } - if cfg.ReviewRequest.Enabled { - // cfgJSON 保存cfgJSON,供当前处理流程使用 - cfgJSON, _ := json.Marshal(map[string]any{"after_shipped_hours": cfg.ReviewRequest.AfterShippedHours, "max_attempts": cfg.ReviewRequest.MaxAttempts}) - if // err 保存err,供当前处理流程使用 - err := s.ensurePublishAutomationRule(ctx, db.AutomationRuleInput{ - UserID: userID, CookieID: row.CookieID, ItemID: res.ItemID, - Name: "超时未评价求评价 - " + title, TriggerType: automation.TriggerReviewMissingTimeout, - Enabled: true, Priority: 100, ConfigJSON: string(cfgJSON), - Actions: []db.AutomationActionInput{ - {ActionType: automation.ActionSendText, MessageTemplate: cfg.ReviewRequest.Message, DelaySeconds: cfg.ReviewRequest.DelaySeconds, Enabled: true, SortOrder: 1}, - }, - }); err != nil { - return err - } - } - return nil -} - -// ensurePublishAutomationRule 负责ensure发布自动化规则相关处理。 -func (s *Server) ensurePublishAutomationRule(ctx context.Context, input db.AutomationRuleInput) error { - // exists、err 保存exists、err,供当前处理流程使用 - exists, err := s.Store.Automation.ExistsPublishRule(ctx, input) - if err != nil { - return err - } - if exists { - return nil - } - _, err = s.Store.Automation.Create(ctx, input) - return err -} - -// parsePublishRows 负责parse发布Rows相关处理。 -func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCookieID, uploadDir string, fallbackCategory mtop.PublishCategory, input []map[string]any) []publishBatchParsedRow { - // out 保存out,供当前处理流程使用 - out := make([]publishBatchParsedRow, 0, len(input)) - // i、m 表示当前遍历过程中的i、m - for i, m := range input { - // row 保存row,供当前处理流程使用 - row := publishBatchParsedRow{ - RowNo: i + 2, - CookieID: firstImportString(m, "cookie_id", "账号ID", "账号id", "账号"), - Title: firstImportString(m, "title", "标题", "商品标题", "商品名称"), - Description: firstImportString(m, "description", "描述", "商品描述", "商品详情"), - Price: firstImportString(m, "price", "价格", "商品价格"), - OriginalPrice: firstImportString(m, "original_price", "原价"), - PostageMode: firstImportString(m, "postage_mode", "邮费模式"), - Postage: firstImportString(m, "postage", "邮费"), - Raw: m, - } - if row.CookieID == "" { - row.CookieID = defaultCookieID - } - if row.Description == "" { - row.Description = row.Title - } - if row.PostageMode == "" { - row.PostageMode = "free" - } - row.PostageMode = strings.ToLower(row.PostageMode) - if row.PostageMode == "包邮" || row.PostageMode == "free_shipping" { - row.PostageMode = "free" - } - if row.PostageMode == "固定邮费" || row.PostageMode == "一口价邮费" { - row.PostageMode = "fixed" - } - row.Quantity = atoiPublishDefault(firstImportString(m, "quantity", "库存", "数量"), 1) - // rowCategory 保存row分类,供当前处理流程使用 - rowCategory := mtop.PublishCategory{ - CatID: firstImportString(m, "category_id", "类目ID", "商品类目ID"), - CatName: firstImportString(m, "category_name", "类目名称", "商品类目名称", "类目"), - ChannelCatID: firstImportString(m, "channel_category_id", "频道类目ID"), - TBCatID: firstImportString(m, "tb_category_id", "淘宝类目ID"), - } - // hasRowCategory 保存hasRow分类,供当前处理流程使用 - hasRowCategory := rowCategory.CatID != "" || rowCategory.CatName != "" || rowCategory.ChannelCatID != "" || rowCategory.TBCatID != "" - if hasRowCategory { - row.Category = rowCategory - if rowCategory.CatID == "" || rowCategory.CatName == "" || rowCategory.ChannelCatID == "" { - row.Errors = append(row.Errors, "指定行类目时必须同时填写类目ID、类目名称和频道类目ID") - } - } else { - row.Category = fallbackCategory - } - row.Automation = parsePublishAutomation(m) - row.Images = splitImageRefs(firstImportString(m, "images", "image", "图片", "商品图片")) - if row.CookieID == "" { - row.Errors = append(row.Errors, "缺少账号ID") - } else if !s.cookieOwnedByUser(ctx, userID, row.CookieID) { - row.Errors = append(row.Errors, "账号不存在或不属于当前用户") - } - if strings.TrimSpace(row.Title) == "" { - row.Errors = append(row.Errors, "缺少标题") - } - if // cents、err 保存cents、err,供当前处理流程使用 - cents, err := parseMoneyCents(row.Price); err != nil || cents <= 0 { - row.Errors = append(row.Errors, "价格必须大于 0") - } - if strings.TrimSpace(row.OriginalPrice) != "" { - if // cents、err 保存cents、err,供当前处理流程使用 - cents, err := parseMoneyCents(row.OriginalPrice); err != nil || cents <= 0 { - row.Errors = append(row.Errors, "原价格式错误") - } - } - if row.Quantity <= 0 { - row.Errors = append(row.Errors, "库存必须大于 0") - } - if row.PostageMode != "free" && row.PostageMode != "fixed" { - row.Errors = append(row.Errors, "邮费模式必须是 free 或 fixed") - } - if row.PostageMode == "fixed" { - if // cents、err 保存cents、err,供当前处理流程使用 - cents, err := parseMoneyCents(row.Postage); err != nil || cents < 0 { - row.Errors = append(row.Errors, "固定邮费格式错误") - } - } - if len(row.Images) == 0 { - row.Errors = append(row.Errors, "缺少图片") - } - if len(row.Images) > 9 { - row.Errors = append(row.Errors, "商品图片最多 9 张") - } - // ref 表示当前遍历过程中的ref - for _, ref := range row.Images { - if // err 保存err,供当前处理流程使用 - err := validateBatchImageRef(uploadDir, ref); err != nil { - row.Errors = append(row.Errors, err.Error()) - } - } - row.Errors = append(row.Errors, s.validatePublishAutomation(ctx, userID, row.Automation)...) - out = append(out, row) - } - return out -} - -// parsePublishAutomation 负责parse发布自动化相关处理。 -func parsePublishAutomation(m map[string]any) publishAutomationConfig { - // cfg 保存cfg,供当前处理流程使用 - cfg := publishAutomationConfig{} - // paidActions、paidParseErr 保存paidActions、paidParseErr,供当前处理流程使用 - paidActions, paidParseErr := parsePublishCardActions(firstImportString(m, "paid_delivery_contents", "付款发货内容")) - cfg.PaidDelivery = publishCardAutomation{ - Enabled: parseLooseBool(firstImportString(m, "paid_delivery_enabled", "付款发货启用")), - Actions: paidActions, - ParseError: paidParseErr, - } - // reviewGiftActions、reviewGiftParseErr 保存reviewGiftActions、reviewGiftParseErr,供当前处理流程使用 - reviewGiftActions, reviewGiftParseErr := parsePublishCardActions(firstImportString(m, "review_gift_contents", "评价赠品内容")) - cfg.ReviewGift = publishCardAutomation{ - Enabled: parseLooseBool(firstImportString(m, "review_gift_enabled", "评价赠品启用")), - Actions: reviewGiftActions, - ParseError: reviewGiftParseErr, - } - cfg.ReviewRequest = publishReviewRequestCfg{ - Enabled: parseLooseBool(firstImportString(m, "review_request_enabled", "求评价启用")), - AfterShippedHours: atoiPublishDefault(firstImportString(m, "review_request_after_hours", "求评价等待小时"), 72), - Message: firstImportString(m, "review_request_message", "求评价文案"), - MaxAttempts: atoiPublishDefault(firstImportString(m, "review_request_max_attempts", "求评价最多次数"), 1), - DelaySeconds: atoiPublishDefault(firstImportString(m, "review_request_delay_seconds", "求评价延迟秒"), 0), - } - return cfg -} - -// parsePublishCardActions 解析“卡密组ID:每件份数:延迟秒”,多条内容用分号或换行分隔。 -func parsePublishCardActions(raw string) ([]publishCardAction, string) { - // entries 保存entries,供当前处理流程使用 - entries := strings.FieldsFunc(strings.TrimSpace(raw), func(r rune) bool { - return r == ';' || r == ';' || r == '\n' || r == '\r' - }) - if len(entries) == 0 { - return nil, "" - } - // actions 保存动作列表,供当前处理流程使用 - actions := make([]publishCardAction, 0, len(entries)) - // index、entry 表示当前遍历过程中的index、entry - for index, entry := range entries { - // parts 保存parts,供当前处理流程使用 - parts := strings.Split(strings.ReplaceAll(strings.TrimSpace(entry), ":", ":"), ":") - if len(parts) < 1 || len(parts) > 3 || strings.TrimSpace(parts[0]) == "" { - return nil, fmt.Sprintf("第%d项格式错误,应为 卡密组ID:每件份数:延迟秒", index+1) - } - // cardID、err 保存卡密ID、err,供当前处理流程使用 - cardID, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64) - if err != nil || cardID <= 0 { - return nil, fmt.Sprintf("第%d项卡密组ID无效", index+1) - } - // count 保存数量,供当前处理流程使用 - count := 1 - if len(parts) >= 2 && strings.TrimSpace(parts[1]) != "" { - count, err = strconv.Atoi(strings.TrimSpace(parts[1])) - if err != nil || count <= 0 { - return nil, fmt.Sprintf("第%d项每件份数必须大于0", index+1) - } - } - // delay 保存延迟,供当前处理流程使用 - delay := 0 - if len(parts) == 3 && strings.TrimSpace(parts[2]) != "" { - delay, err = strconv.Atoi(strings.TrimSpace(parts[2])) - if err != nil || delay < 0 { - return nil, fmt.Sprintf("第%d项延迟秒不能小于0", index+1) - } - } - actions = append(actions, publishCardAction{CardID: cardID, DeliveryCount: count, DelaySeconds: delay}) - } - return actions, "" -} - -// validatePublishAutomation 负责validate发布自动化相关处理。 -func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cfg publishAutomationConfig) []string { - // errs 保存errs,供当前处理流程使用 - var errs []string - // validateCards 保存validate卡密列表,供当前处理流程使用 - validateCards := func(config publishCardAutomation, label string) { - if !config.Enabled { - return - } - if config.ParseError != "" { - errs = append(errs, label+config.ParseError) - return - } - if len(config.Actions) == 0 { - errs = append(errs, label+"需要至少配置一条发货内容") - return - } - // index、action 表示当前遍历过程中的index、action - for index, action := range config.Actions { - // prefix 保存prefix,供当前处理流程使用 - prefix := fmt.Sprintf("%s第%d项", label, index+1) - if !s.cardOwnedByUser(ctx, userID, action.CardID) { - errs = append(errs, prefix+"卡密组不存在或不属于当前用户") - } - if action.DeliveryCount <= 0 { - errs = append(errs, prefix+"每件份数必须大于0") - } - if action.DelaySeconds < 0 || action.DelaySeconds > 3600 { - errs = append(errs, prefix+"延迟秒必须在 0 到 3600 之间") - } - } - } - validateCards(cfg.PaidDelivery, "付款发货") - validateCards(cfg.ReviewGift, "评价赠品") - if cfg.ReviewRequest.Enabled { - if cfg.ReviewRequest.AfterShippedHours <= 0 { - errs = append(errs, "求评价等待小时必须大于 0") - } - if strings.TrimSpace(cfg.ReviewRequest.Message) == "" { - errs = append(errs, "求评价文案不能为空") - } - if cfg.ReviewRequest.MaxAttempts <= 0 { - errs = append(errs, "求评价最多次数必须大于 0") - } - } - return errs -} - -// publishBatchToMap 负责发布批次ToMap相关处理。 -func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) itemPublishBatchResponse { - // locationJSON 保存地址JSON,供当前处理流程使用 - locationJSON := strings.TrimSpace(batch.LocationJSON) - if locationJSON == "" { - locationJSON = "{}" - } - // outRows 保存outRows,供当前处理流程使用 + // outRows 保存转换后的批次明细响应。 outRows := make([]itemPublishBatchRowResponse, 0, len(rows)) - // pending 保存pending,供当前处理流程使用 - pending := 0 - // running 保存running,供当前处理流程使用 - running := 0 - // row 表示当前待转换的批量明细行。 + // pending、running 保存当前批次明细状态计数。 + pending, running := 0, 0 + // row 表示当前待转换的应用批次明细。 for _, row := range rows { if row.Status == "pending" { pending++ @@ -1354,27 +683,26 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow if row.Status == "running" { running++ } - // refs 保存refs,供当前处理流程使用 + // refs 保存当前明细的图片路径列表。 var refs []string _ = json.Unmarshal([]byte(row.ImagesJSON), &refs) - // category 保存分类,供当前处理流程使用 - var category mtop.PublishCategory + // category 保存当前明细的类目配置。 + var category publishCategoryResponse _ = json.Unmarshal([]byte(row.CategoryJSON), &category) - // automationCfg 保存自动化Cfg,供当前处理流程使用 + // automationCfg 保存当前明细的发布后自动化配置。 var automationCfg publishAutomationConfig _ = json.Unmarshal([]byte(row.AutomationJSON), &automationCfg) outRows = append(outRows, itemPublishBatchRowResponse{ ID: row.ID, RowNo: row.RowNo, CookieID: row.CookieID, Title: row.Title, Price: row.Price, Quantity: row.Quantity, Images: refs, - Category: category, - Automation: automationCfg, - Status: row.Status, ItemID: row.ItemID, ItemURL: row.ItemURL, - ErrorMessage: row.ErrorMessage, FailureKind: row.FailureKind, + Category: category, Automation: automationCfg, Status: row.Status, + ItemID: row.ItemID, ItemURL: row.ItemURL, ErrorMessage: row.ErrorMessage, + FailureKind: row.FailureKind, }) } - // retryable 保存retryable,供当前处理流程使用 + // retryable 保存允许用户重新发起的平台失败明细数量。 retryable := 0 - // row 表示当前用于统计可重试数量的批量明细行。 + // row 表示当前用于统计可重试数量的应用批次明细。 for _, row := range rows { if row.Status == "failed" && row.FailureKind != "validation" && row.FailureKind != "uncertain_remote" { retryable++ @@ -1384,62 +712,55 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow ID: batch.ID, Status: batch.Status, Filename: batch.Filename, Total: batch.TotalCount, Success: batch.SuccessCount, Failed: batch.FailedCount, Pending: pending, Running: running, Retryable: retryable, Rows: outRows, - Location: json.RawMessage(locationJSON), - CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt, + Location: json.RawMessage(locationJSON), CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt, } } -// removePublishUploadDir 负责remove发布UploadDir相关处理。 -func (s *Server) removePublishUploadDir(ctx context.Context, batch *db.ItemPublishBatch) { - if batch == nil || strings.TrimSpace(batch.UploadDir) == "" { - return - } - _ = os.RemoveAll(batch.UploadDir) - _ = s.itemPublishRepositoryForServer().ClearUploadDir(ctx, batch.ID) -} - // cleanupExpiredPublishUploads 负责cleanupExpired发布Uploads相关处理。 func (s *Server) cleanupExpiredPublishUploads(ctx context.Context) { - // cutoff 保存cutoff,供当前处理流程使用 - cutoff := time.Now().UTC().Add(-7 * 24 * time.Hour).Format("2006-01-02 15:04:05") - // batches、err 保存batches、err,供当前处理流程使用 - batches, err := s.itemPublishRepositoryForServer().ExpiredUploads(ctx, cutoff, 100) - if err != nil { - return - } - // i 表示当前遍历过程中的i - for i := range batches { - s.removePublishUploadDir(ctx, &batches[i]) + // err 表示过期上传目录清理结果;清理失败不影响当前预检请求。 + if err := s.itemBatchManagementApplication().CleanupExpiredUploads(ctx, time.Now().UTC(), 100); err != nil && s.Logger != nil { + s.Logger.Warn("清理过期批量发布上传目录失败", "err", err) } } // cookieOwnedByUser 判断指定账号是否属于用户,不读取或解密 Cookie 明文。 func (s *Server) cookieOwnedByUser(ctx context.Context, userID int64, cookieID string) bool { - // owned 表示数据库中是否存在匹配用户和账号 ID 的记录。 - owned, err := s.itemPublishRepositoryForServer().ExistsOwned(ctx, userID, cookieID) + // service 提供不读取凭证的账号归属查询能力。 + service := s.accountSummaryApplication() + if service == nil { + return false + } + // owned、err 表示账号摘要服务返回的归属结论及基础设施错误。 + owned, err := service.ExistsOwned(ctx, userID, cookieID) return err == nil && owned } // cookieValueForUser 读取指定用户拥有的单个账号 Cookie 明文。 func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID string) (string, error) { - // value 是按 user_id 与账号 ID 联合过滤后解密的单个 Cookie 明文。 - value, err := s.itemPublishRepositoryForServer().GetCookieValueOwned(ctx, userID, cookieID) + // repository 提供按账号读取的平台窄凭证视图,解密和数据库访问均由 adapter 负责。 + repository := s.accountLoginRepositoryForServer() + if repository == nil { + return "", errors.New("账号凭证 repository 未初始化") + } + // detail 和 err 保存账号归属与 Cookie 明文读取结果;明文只在当前发布边界短暂存在。 + detail, err := repository.LoadPlatformDetail(ctx, cookieID) if err != nil { - if errors.Is(err, db.ErrNotFound) { + if errors.Is(err, accountapp.ErrCredentialNotFound) { return "", errors.New("账号不存在或 Cookie 为空") } return "", err } - if strings.TrimSpace(value) == "" { + if detail == nil || detail.UserID != userID || strings.TrimSpace(detail.Value) == "" { return "", errors.New("账号不存在或 Cookie 为空") } - return value, nil + return detail.Value, nil } // cardOwnedByUser 判断指定卡券组是否属于用户。 func (s *Server) cardOwnedByUser(ctx context.Context, userID int64, cardID int64) bool { - // exists 和 err 表示卡券组所有权查询结果及错误。 - exists, err := s.Store.Cards.ExistsOwned(ctx, cardID, userID) + // exists 和 err 表示卡券应用服务返回的所有权结果及错误。 + exists, err := s.cardsApplication().ExistsOwned(ctx, userID, cardID) return err == nil && exists } @@ -1492,125 +813,62 @@ func firstNonEmpty(values ...string) string { return "" } -// serverBatchRepository 将数据库批次仓储转换为应用层批量发布端口。 -type serverBatchRepository struct { - // server 保存文件清理和数据库适配所需的 Server 引用。 - server *Server - // repository 保存批量状态的窄数据库接口。 - repository itemPublishRepository -} - -// PendingRows 查询数据库明细并移除数据库模型依赖。 -func (r serverBatchRepository) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]itemapp.BatchRow, error) { - // rows、err 保存数据库批量明细及查询错误。 - rows, err := r.repository.PendingRows(ctx, batchID, failedOnly) - if err != nil { - return nil, err - } - // result 保存应用层批量明细。 - result := make([]itemapp.BatchRow, 0, len(rows)) - // row 表示当前转换的数据库批量明细。 - for _, row := range rows { - result = append(result, toApplicationBatchRow(row)) - } - return result, nil -} - -// RenewBatchLease 委托数据库续租并保持应用层只接收基础类型。 -func (r serverBatchRepository) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) { - return r.repository.RenewBatchLease(ctx, batchID, workerToken, leaseExpiresAt) -} - -// GetBatch 查询数据库批次并转换为应用层状态模型。 -func (r serverBatchRepository) GetBatch(ctx context.Context, userID int64, batchID string) (itemapp.BatchInfo, error) { - // batch、err 保存数据库批次及查询错误。 - batch, err := r.repository.GetBatch(ctx, userID, batchID) - if err != nil { - return itemapp.BatchInfo{}, err - } - return itemapp.BatchInfo{ID: batch.ID, UserID: batch.UserID, Status: batch.Status, WorkerToken: batch.WorkerToken, UploadDir: batch.UploadDir}, nil -} - -// ClaimRow 委托数据库抢占明细租约。 -func (r serverBatchRepository) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) { - return r.repository.ClaimRow(ctx, rowID, workerToken) -} - -// BatchStatus 委托数据库读取批次状态用于失败分类。 -func (r serverBatchRepository) BatchStatus(ctx context.Context, batchID string) (string, error) { - return r.repository.BatchStatus(ctx, batchID) -} - -// MarkClaimedRowFailed 委托数据库记录当前 worker 的失败明细。 -func (r serverBatchRepository) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) { - return r.repository.MarkClaimedRowFailed(ctx, rowID, workerToken, message, kind) -} - -// RecountBatch 委托数据库重算批次进度。 -func (r serverBatchRepository) RecountBatch(ctx context.Context, batchID string) error { - return r.repository.RecountBatch(ctx, batchID) -} - -// FinalizeBatch 委托数据库正常收口批次。 -func (r serverBatchRepository) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) { - return r.repository.FinalizeBatch(ctx, batchID, workerToken) -} - -// FinalizeCanceled 委托数据库收口取消中的批次。 -func (r serverBatchRepository) FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) { - return r.repository.FinalizeCanceled(ctx, batchID, workerToken) -} - -// FinalizeInterrupted 委托数据库收口中断批次。 -func (r serverBatchRepository) FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) { - return r.repository.FinalizeInterrupted(ctx, batchID, workerToken, message) -} - -// DeleteUpload 删除已完成批次的上传目录并清除数据库路径。 -func (r serverBatchRepository) DeleteUpload(ctx context.Context, batchID, uploadDir string) error { - if uploadDir == "" { - return nil - } - // removeErr 保存上传目录删除错误;数据库记录仍需尝试清理。 - removeErr := os.RemoveAll(uploadDir) - // clearErr 保存数据库上传目录字段清理错误。 - clearErr := r.repository.ClearUploadDir(ctx, batchID) - if removeErr != nil { - return removeErr - } - return clearErr -} - // serverBatchPublisher 将 Server 的商品发布细节适配为应用层批量发布端口。 type serverBatchPublisher struct { // server 保存平台发布和本地商品结果适配所需的 Server 引用。 server *Server + // remotePort 保存已装配的平台与凭证端口,避免 worker 再进入 Server 远端逻辑。 + remotePort itemapp.BatchPublishPort + // localService 保存已装配的本地商品、自动化规则和成功检查点收口服务。 + localService *itemapp.BatchLocalPublishService } -// PublishRow 调用现有单行发布适配,应用层不再接触数据库或 MTOP 类型。 +// PublishRow 调用批量远端端口并收口本地结果,应用层不接触数据库或 MTOP 类型。 func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) error { - return p.server.publishBatchRow(ctx, userID, p.server.mtopClient(), fromApplicationBatchRow(row), workerToken) -} - -// toApplicationBatchRow 将数据库行映射为纯应用 DTO。 -func toApplicationBatchRow(row db.ItemPublishBatchRow) itemapp.BatchRow { - return itemapp.BatchRow{ID: row.ID, BatchID: row.BatchID, CookieID: row.CookieID, Title: row.Title, Description: row.Description, Price: row.Price, OriginalPrice: row.OriginalPrice, Quantity: row.Quantity, PostageMode: row.PostageMode, Postage: row.Postage, ImagesJSON: row.ImagesJSON, CategoryJSON: row.CategoryJSON, AutomationJSON: row.AutomationJSON, RawJSON: row.RawJSON, ItemID: row.ItemID, ItemURL: row.ItemURL} -} - -// fromApplicationBatchRow 将应用 DTO 还原为 Server 平台适配所需的数据库行模型。 -func fromApplicationBatchRow(row itemapp.BatchRow) db.ItemPublishBatchRow { - return db.ItemPublishBatchRow{ID: row.ID, BatchID: row.BatchID, CookieID: row.CookieID, Title: row.Title, Description: row.Description, Price: row.Price, OriginalPrice: row.OriginalPrice, Quantity: row.Quantity, PostageMode: row.PostageMode, Postage: row.Postage, ImagesJSON: row.ImagesJSON, CategoryJSON: row.CategoryJSON, AutomationJSON: row.AutomationJSON, RawJSON: row.RawJSON, ItemID: row.ItemID, ItemURL: row.ItemURL} + if p.server == nil || p.remotePort == nil { + return errors.New("批量发布端口未装配") + } + if p.localService == nil { + return errors.New("批量发布本地收口端口未装配") + } + // outcome、err 保存远端发布结果及适配器错误。 + outcome, err := p.remotePort.PublishRemoteRow(ctx, userID, row, workerToken) + if err != nil { + // uncertainErr 表示远端调用已经发生但结果无法可靠确认。 + var uncertainErr *itemapp.UncertainRemotePublishError + if errors.As(err, &uncertainErr) { + return &uncertainRemotePublishError{err: err} + } + return err + } + if outcome.Result == nil { + return errors.New("发布商品接口未返回结果") + } + return p.server.completeBatchPublishOutcome(ctx, userID, p.localService, row, workerToken, outcome) } // newItemBatchRunnerApplication 创建批量发布应用层 worker 编排器。 -func newItemBatchRunnerApplication(server *Server) (*itemapp.BatchRunner, error) { +func newItemBatchRunnerApplication(server *Server, remotePort itemapp.BatchPublishPort, localService *itemapp.BatchLocalPublishService) (*itemapp.BatchRunner, error) { + if server == nil || remotePort == nil || localService == nil { + return nil, errors.New("批量发布端口未装配") + } // options 配置批量 worker 的租约、间隔和平台错误语义。 options := itemapp.BatchRunOptions{ - LeaseDuration: publishBatchLease, - IsSessionExpired: func(err error) bool { - return mtop.IsSessionExpiredErr(err) - }, - ClassifyFailure: publishBatchFailure, + LeaseDuration: publishBatchLease, + IsSessionExpired: adapter.IsSessionExpiredError, + ClassifyFailure: publishBatchFailure, } - return itemapp.NewBatchRunner(serverBatchRepository{server: server, repository: newStoreItemPublishRepository(server.Store)}, serverBatchPublisher{server: server}, options) + return itemapp.NewBatchRunner(server.dependencies.NewItemBatchRepository(), serverBatchPublisher{server: server, remotePort: remotePort, localService: localService}, options) +} + +// publishBatchLocation 保存批量发布请求中的发货地字段,不让平台 DTO 进入 HTTP 层。 +type publishBatchLocation struct { + Area string `json:"area"` + City string `json:"city"` + DivisionID string `json:"division_id"` + Longitude float64 `json:"longitude"` + Latitude float64 `json:"latitude"` + POIID string `json:"poi_id"` + POIName string `json:"poi_name"` + Province string `json:"province"` } diff --git a/internal/server/item_publish_images.go b/internal/server/item_publish_images.go index 7f3e835..ad609c0 100644 --- a/internal/server/item_publish_images.go +++ b/internal/server/item_publish_images.go @@ -8,8 +8,6 @@ import ( "context" "crypto/rand" "encoding/hex" - "encoding/json" - "errors" "fmt" "io" "mime" @@ -21,9 +19,7 @@ import ( "strings" "time" - "xianyu-go/internal/db" "xianyu-go/internal/netguard" - "xianyu-go/internal/xianyu/mtop" ) // isPublicIP 保留给同包校验调用;实际策略统一由 netguard 维护。 @@ -112,43 +108,6 @@ func extractPublishImagesZip(raw []byte, dest string) error { return nil } -// loadBatchPublishImages 负责load批次发布Images相关处理。 -func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) { - // refs 保存refs,供当前处理流程使用 - var refs []string - if // err 保存err,供当前处理流程使用 - err := json.Unmarshal([]byte(row.ImagesJSON), &refs); err != nil { - return nil, fmt.Errorf("图片字段格式错误") - } - if len(refs) == 0 { - return nil, errors.New("至少上传 1 张商品图片") - } - // images 保存images,供当前处理流程使用 - images := make([]mtop.PublishImage, 0, len(refs)) - // ref 表示当前遍历过程中的ref - for _, ref := range refs { - // data 保存数据,供当前处理流程使用 - var data []byte - // contentType 保存内容类型,供当前处理流程使用 - var contentType string - // filename 保存filename,供当前处理流程使用 - var filename string - // err 保存err,供当前处理流程使用 - var err error - if isHTTPURL(ref) { - data, contentType, err = downloadImageURL(ctx, ref) - filename = pathBaseFromURL(ref) - } else { - data, contentType, filename, err = readBatchImageFile(uploadDir, ref) - } - if err != nil { - return nil, err - } - images = append(images, mtop.PublishImage{Filename: filename, ContentType: contentType, Data: data}) - } - return images, nil -} - // readBatchImageFile 负责read批次图片文件相关处理。 func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) { // rel、err 保存rel、err,供当前处理流程使用 diff --git a/internal/server/item_publish_images_test.go b/internal/server/item_publish_images_test.go new file mode 100644 index 0000000..6580082 --- /dev/null +++ b/internal/server/item_publish_images_test.go @@ -0,0 +1,14 @@ +package server + +import ( + "context" + + "xianyu-go/internal/adapter" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +// loadBatchPublishImages 保留 Server 测试的历史调用形状,生产路径直接使用 adapter.LoadBatchPublishImages。 +func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) { + return adapter.LoadBatchPublishImages(ctx, uploadDir, row.ImagesJSON, readBatchImageFile, downloadImageURL) +} diff --git a/internal/server/item_publish_repository.go b/internal/server/item_publish_repository.go deleted file mode 100644 index b3e13a9..0000000 --- a/internal/server/item_publish_repository.go +++ /dev/null @@ -1,257 +0,0 @@ -package server - -import ( - "context" - - "xianyu-go/internal/db" -) - -// itemPublishRepository 定义发布应用服务处理商品与批次状态所需的最小持久化能力。 -type itemPublishRepository interface { - // LockCredentials 串行化账号凭证状态变更。 - LockCredentials(cookieID string) func() - // LoadCookiePlatformDetail 读取平台发布所需的最小账号凭证视图。 - LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) - // UpdateCookieValueOwned 更新用户拥有账号的 Cookie。 - UpdateCookieValueOwned(ctx context.Context, cookieID, value string, userID int64) error - // UpsertItem 写入发布成功后的商品基础信息。 - UpsertItem(ctx context.Context, item *db.ItemInfoRow) error - // CreateBatch 创建批次及其明细行。 - CreateBatch(ctx context.Context, batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) error - // RecountBatch 重算批次统计。 - RecountBatch(ctx context.Context, batchID string) error - // GetBatch 查询用户拥有的批次。 - GetBatch(ctx context.Context, userID int64, batchID string) (*db.ItemPublishBatch, error) - // ClaimBatch 抢占批次 worker 租约。 - ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) - // PendingRows 查询批次待处理明细。 - PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]db.ItemPublishBatchRow, error) - // FinalizeBatch 完成批次状态收口。 - FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) - // ListBatchesForUser 查询用户批次列表。 - ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]db.ItemPublishBatch, error) - // ListBatchRows 查询批次明细行。 - ListBatchRows(ctx context.Context, batchID string) ([]db.ItemPublishBatchRow, error) - // RequestCancel 请求取消批次。 - RequestCancel(ctx context.Context, batchID string) (string, bool, error) - // DeleteBatch 删除用户拥有的批次。 - DeleteBatch(ctx context.Context, userID int64, batchID string) error - // ResetFailed 重置批次失败明细。 - ResetFailed(ctx context.Context, batchID string) error - // RecoverableBatches 查询可恢复的批次。 - RecoverableBatches(ctx context.Context, now int64, limit int) ([]db.ItemPublishBatch, error) - // FinalizeExpiredCancellation 收口已过期的取消请求。 - FinalizeExpiredCancellation(ctx context.Context, batchID string, now int64) (bool, error) - // ResetInterrupted 重置进程中断的批次。 - ResetInterrupted(ctx context.Context, batchID string) error - // FailClaimedBatch 标记当前 worker 持有的批次失败。 - FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) - // RenewBatchLease 续租批次 worker。 - RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) - // ClaimRow 抢占批次明细行。 - ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) - // BatchStatus 查询批次状态。 - BatchStatus(ctx context.Context, batchID string) (string, error) - // MarkClaimedRowFailed 标记 worker 持有的明细行失败。 - MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) - // FinalizeCanceled 收口已取消批次。 - FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) - // FinalizeInterrupted 收口被中断批次。 - FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) - // MarkClaimedRemoteStarted 记录远端发布已开始。 - MarkClaimedRemoteStarted(ctx context.Context, rowID int64, workerToken string) (bool, error) - // SaveClaimedRemoteResult 保存远端发布结果。 - SaveClaimedRemoteResult(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) - // MarkClaimedRowSuccess 标记 worker 持有的明细行成功。 - MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) - // ClearUploadDir 清理批次上传目录记录。 - ClearUploadDir(ctx context.Context, batchID string) error - // ExpiredUploads 查询过期上传目录。 - ExpiredUploads(ctx context.Context, cutoff string, limit int) ([]db.ItemPublishBatch, error) - // GetCookieValueOwned 读取用户拥有账号的 Cookie。 - GetCookieValueOwned(ctx context.Context, userID int64, cookieID string) (string, error) - // ExistsOwned 判断账号是否归属于用户。 - ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error) -} - -// storeItemPublishRepository 将完整 Store 适配为发布应用服务窄 repository。 -type storeItemPublishRepository struct { - // store 保存数据库聚合入口,仅在适配器内部使用。 - store *db.Store -} - -// LockCredentials 委托账号凭证锁。 -func (r storeItemPublishRepository) LockCredentials(cookieID string) func() { - return r.store.LockAccountCredentials(cookieID) -} - -// LoadCookiePlatformDetail 委托平台发布凭证查询并转换为 Server 内部模型。 -func (r storeItemPublishRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) { - // data 和 err 保存平台运行视图查询结果。 - data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) - if err != nil { - return nil, err - } - return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser}, nil -} - -// UpdateCookieValueOwned 委托账号 Cookie 更新。 -func (r storeItemPublishRepository) UpdateCookieValueOwned(ctx context.Context, cookieID, value string, userID int64) error { - return r.store.Cookies.UpdateValueOwned(ctx, cookieID, value, userID) -} - -// UpsertItem 委托商品基础信息写入。 -func (r storeItemPublishRepository) UpsertItem(ctx context.Context, item *db.ItemInfoRow) error { - return r.store.Items.Upsert(ctx, item) -} - -// CreateBatch 委托批次创建。 -func (r storeItemPublishRepository) CreateBatch(ctx context.Context, batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) error { - return r.store.PublishBatches.Create(ctx, batch, rows) -} - -// RecountBatch 委托批次统计重算。 -func (r storeItemPublishRepository) RecountBatch(ctx context.Context, batchID string) error { - return r.store.PublishBatches.Recount(ctx, batchID) -} - -// GetBatch 委托用户批次查询。 -func (r storeItemPublishRepository) GetBatch(ctx context.Context, userID int64, batchID string) (*db.ItemPublishBatch, error) { - return r.store.PublishBatches.Get(ctx, userID, batchID) -} - -// ClaimBatch 委托批次租约抢占。 -func (r storeItemPublishRepository) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) { - return r.store.PublishBatches.ClaimBatch(ctx, batchID, workerToken, leaseExpiresAt) -} - -// PendingRows 委托批次待处理明细查询。 -func (r storeItemPublishRepository) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]db.ItemPublishBatchRow, error) { - return r.store.PublishBatches.PendingRows(ctx, batchID, failedOnly) -} - -// FinalizeBatch 委托批次完成状态收口。 -func (r storeItemPublishRepository) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) { - return r.store.PublishBatches.FinalizeBatch(ctx, batchID, workerToken) -} - -// ListBatchesForUser 委托用户批次列表查询。 -func (r storeItemPublishRepository) ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]db.ItemPublishBatch, error) { - return r.store.PublishBatches.ListForUser(ctx, userID, limit) -} - -// ListBatchRows 委托批次明细查询。 -func (r storeItemPublishRepository) ListBatchRows(ctx context.Context, batchID string) ([]db.ItemPublishBatchRow, error) { - return r.store.PublishBatches.Rows(ctx, batchID) -} - -// RequestCancel 委托批次取消请求。 -func (r storeItemPublishRepository) RequestCancel(ctx context.Context, batchID string) (string, bool, error) { - return r.store.PublishBatches.RequestCancel(ctx, batchID) -} - -// DeleteBatch 委托批次删除。 -func (r storeItemPublishRepository) DeleteBatch(ctx context.Context, userID int64, batchID string) error { - return r.store.PublishBatches.Delete(ctx, userID, batchID) -} - -// ResetFailed 委托失败明细重置。 -func (r storeItemPublishRepository) ResetFailed(ctx context.Context, batchID string) error { - return r.store.PublishBatches.ResetFailed(ctx, batchID) -} - -// RecoverableBatches 委托可恢复批次查询。 -func (r storeItemPublishRepository) RecoverableBatches(ctx context.Context, now int64, limit int) ([]db.ItemPublishBatch, error) { - return r.store.PublishBatches.Recoverable(ctx, now, limit) -} - -// FinalizeExpiredCancellation 委托过期取消收口。 -func (r storeItemPublishRepository) FinalizeExpiredCancellation(ctx context.Context, batchID string, now int64) (bool, error) { - return r.store.PublishBatches.FinalizeExpiredCancellation(ctx, batchID, now) -} - -// ResetInterrupted 委托中断批次重置。 -func (r storeItemPublishRepository) ResetInterrupted(ctx context.Context, batchID string) error { - return r.store.PublishBatches.ResetInterrupted(ctx, batchID) -} - -// FailClaimedBatch 委托 worker 持有批次失败标记。 -func (r storeItemPublishRepository) FailClaimedBatch(ctx context.Context, batchID, workerToken string) (bool, error) { - return r.store.PublishBatches.FailClaimedBatch(ctx, batchID, workerToken) -} - -// RenewBatchLease 委托批次租约续期。 -func (r storeItemPublishRepository) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) { - return r.store.PublishBatches.RenewBatchLease(ctx, batchID, workerToken, leaseExpiresAt) -} - -// ClaimRow 委托批次明细行抢占。 -func (r storeItemPublishRepository) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) { - return r.store.PublishBatches.ClaimRow(ctx, rowID, workerToken) -} - -// BatchStatus 委托批次状态查询。 -func (r storeItemPublishRepository) BatchStatus(ctx context.Context, batchID string) (string, error) { - return r.store.PublishBatches.BatchStatus(ctx, batchID) -} - -// MarkClaimedRowFailed 委托 worker 持有明细行失败标记。 -func (r storeItemPublishRepository) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) { - return r.store.PublishBatches.MarkClaimedRowFailed(ctx, rowID, workerToken, message, kind) -} - -// FinalizeCanceled 委托已取消批次收口。 -func (r storeItemPublishRepository) FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) { - return r.store.PublishBatches.FinalizeCanceled(ctx, batchID, workerToken) -} - -// FinalizeInterrupted 委托中断批次收口。 -func (r storeItemPublishRepository) FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) { - return r.store.PublishBatches.FinalizeInterrupted(ctx, batchID, workerToken, message) -} - -// MarkClaimedRemoteStarted 委托远端发布开始标记。 -func (r storeItemPublishRepository) MarkClaimedRemoteStarted(ctx context.Context, rowID int64, workerToken string) (bool, error) { - return r.store.PublishBatches.MarkClaimedRemoteStarted(ctx, rowID, workerToken) -} - -// SaveClaimedRemoteResult 委托远端发布结果保存。 -func (r storeItemPublishRepository) SaveClaimedRemoteResult(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) { - return r.store.PublishBatches.SaveClaimedRemoteResult(ctx, rowID, workerToken, itemID, itemURL, rawJSON) -} - -// MarkClaimedRowSuccess 委托明细行成功标记。 -func (r storeItemPublishRepository) MarkClaimedRowSuccess(ctx context.Context, rowID int64, workerToken, itemID, itemURL, rawJSON string) (bool, error) { - return r.store.PublishBatches.MarkClaimedRowSuccess(ctx, rowID, workerToken, itemID, itemURL, rawJSON) -} - -// ClearUploadDir 委托批次上传目录清理。 -func (r storeItemPublishRepository) ClearUploadDir(ctx context.Context, batchID string) error { - return r.store.PublishBatches.ClearUploadDir(ctx, batchID) -} - -// ExpiredUploads 委托过期上传目录查询。 -func (r storeItemPublishRepository) ExpiredUploads(ctx context.Context, cutoff string, limit int) ([]db.ItemPublishBatch, error) { - return r.store.PublishBatches.ExpiredUploads(ctx, cutoff, limit) -} - -// GetCookieValueOwned 委托用户账号 Cookie 查询。 -func (r storeItemPublishRepository) GetCookieValueOwned(ctx context.Context, userID int64, cookieID string) (string, error) { - return r.store.Cookies.GetValueOwned(ctx, userID, cookieID) -} - -// ExistsOwned 委托账号归属查询。 -func (r storeItemPublishRepository) ExistsOwned(ctx context.Context, userID int64, cookieID string) (bool, error) { - return r.store.Cookies.ExistsOwned(ctx, userID, cookieID) -} - -// newStoreItemPublishRepository 从完整 Store 构造发布应用服务窄 repository。 -func newStoreItemPublishRepository(store *db.Store) itemPublishRepository { - if store == nil || store.Cookies == nil || store.Items == nil || store.PublishBatches == nil { - return nil - } - return storeItemPublishRepository{store: store} -} - -// 确保 Store 适配器始终覆盖发布应用服务所需的全部能力。 -var _ itemPublishRepository = storeItemPublishRepository{} diff --git a/internal/server/item_publish_service.go b/internal/server/item_publish_service.go deleted file mode 100644 index d8a88a4..0000000 --- a/internal/server/item_publish_service.go +++ /dev/null @@ -1,431 +0,0 @@ -package server - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "time" - - itemapp "xianyu-go/internal/application/items" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/mtop" -) - -var ( - // errItemPublishBatchNotFound 表示当前用户无法访问指定批量任务。 - errItemPublishBatchNotFound = errors.New("商品批量任务不存在") - // errItemPublishBatchConflict 表示批量任务的租约或状态发生并发冲突。 - errItemPublishBatchConflict = errors.New("商品批量任务状态冲突") - // errItemPublishBatchInvalidState 表示批量任务当前状态不允许执行请求操作。 - errItemPublishBatchInvalidState = errors.New("商品批量任务状态不允许执行该操作") - // errItemPublishBatchNoRows 表示批量任务没有可继续处理的明细行。 - errItemPublishBatchNoRows = errors.New("商品批量任务没有可处理的明细行") -) - -// itemPublishPreviewInput 是批量发布预检结果持久化所需的业务输入。 -type itemPublishPreviewInput struct { - // UserID 是创建批次的用户标识。 - UserID int64 - // BatchID 是预检批次标识。 - BatchID string - // DefaultCookieID 是未指定账号行使用的默认账号。 - DefaultCookieID string - // Filename 是用户上传的表格文件名。 - Filename string - // UploadDir 是批次图片和表格的受控目录。 - UploadDir string - // Location 是批次统一发货地。 - Location mtop.PublishLocation - // Rows 是解析并校验后的商品行。 - Rows []publishBatchParsedRow -} - -// itemPublishService 是商品发布应用服务,隔离 HTTP 适配与业务状态变更。 -type itemPublishService struct { - // server 提供数据库、MTOP 客户端、运行时 Cookie 和 worker 生命周期依赖。 - server *Server - // repository 提供商品发布用例所需的最小持久化能力。 - repository itemPublishRepository -} - -// itemPublishApplication 返回当前 Server 绑定的商品发布应用服务。 -func (s *Server) itemPublishApplication() *itemPublishService { - return s.applicationServiceSet().itemPublish -} - -// itemSinglePublishApplication 返回只负责单商品发布用例的应用服务。 -func (s *Server) itemSinglePublishApplication() *itemapp.Service { - return s.applicationServiceSet().itemSinglePublish -} - -// itemPublishRepositoryForServer 返回当前 Server 装配的发布持久化边界。 -func (s *Server) itemPublishRepositoryForServer() itemPublishRepository { - return s.itemPublishApplication().repository -} - -// RecommendCategory 调用平台类目推荐并持久化刷新后的账号登录状态。 -func (svc *itemPublishService) RecommendCategory(ctx context.Context, userID int64, cookieID, keyword string) (mtop.PublishCategory, error) { - // s 是当前商品发布应用服务依赖的 Server。 - s := svc.server - // recommender 和 ok 表示 MTOP 客户端是否支持类目推荐。 - recommender, ok := s.mtopClient().(publishCategoryRecommender) - if !ok { - return mtop.PublishCategory{}, errors.New("当前 MTOP 客户端不支持类目推荐") - } - // unlock 释放当前账号的凭证串行化锁。 - unlock := svc.repository.LockCredentials(cookieID) - // runtimeCookie 是需要在释放凭证锁后同步的刷新凭证。 - runtimeCookie := "" - defer func() { - unlock() - if runtimeCookie != "" { - s.updateRunningCookie(context.Background(), cookieID, runtimeCookie) - } - }() - // err 和 latest 保存账号平台详情查询结果。 - latest, err := s.loadCookiePlatformDetail(ctx, cookieID) - if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { - return mtop.PublishCategory{}, errors.New("账号凭证已变化,请重试") - } - // requestCtx 和 cancel 控制类目推荐的最长执行时间。 - requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - // mtopCtx 和 cookieSession 保存带 Cookie 快照的平台上下文。 - mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest) - // category、updatedCookies 和 callErr 是平台推荐结果、刷新凭证及调用错误。 - category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, keyword) - // value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。 - value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession) - if persistErr != nil { - return mtop.PublishCategory{}, fmt.Errorf("保存账号登录状态失败: %w", persistErr) - } - if !handled && updatedCookies != "" && updatedCookies != latest.Value { - // err 表示保存平台返回新 Cookie 的错误。 - if err := svc.repository.UpdateCookieValueOwned(ctx, cookieID, updatedCookies, userID); err != nil { - return mtop.PublishCategory{}, fmt.Errorf("保存账号登录状态失败: %w", err) - } - runtimeCookie = updatedCookies - } else if handled && valueChanged { - runtimeCookie = value - } - if callErr != nil { - return mtop.PublishCategory{}, callErr - } - return category, nil -} - -// PersistPreview 将预检行转换为数据库批次并返回兼容旧接口的预检 DTO。 -func (svc *itemPublishService) PersistPreview(ctx context.Context, input itemPublishPreviewInput) (itemPublishBatchPreviewResponse, error) { - // rows 是待写入数据库的批量明细行。 - rows := make([]db.ItemPublishBatchRow, 0, len(input.Rows)) - // previewRows 是返回给前端的逐行预检视图。 - previewRows := make([]publishBatchPreviewRow, 0, len(input.Rows)) - // valid 和 invalid 记录预检通过与失败的行数。 - valid, invalid := 0, 0 - // parsed 是当前正在转换的预检行。 - for _, parsed := range input.Rows { - // isValid 表示当前行是否没有校验错误。 - isValid := len(parsed.Errors) == 0 - if isValid { - valid++ - } else { - invalid++ - } - // imagesJSON、categoryJSON、automationJSON 和 rawJSON 是行数据的 JSON 表示。 - imagesJSON, _ := json.Marshal(parsed.Images) - // categoryJSON 是商品类目的 JSON 表示。 - categoryJSON, _ := json.Marshal(parsed.Category) - // automationJSON 是发布后自动化配置的 JSON 表示。 - automationJSON, _ := json.Marshal(parsed.Automation) - // rawJSON 是原始导入行的 JSON 表示。 - rawJSON, _ := json.Marshal(parsed.Raw) - // status、errorMessage 和 failureKind 保存数据库状态及失败分类。 - status, errorMessage, failureKind := "pending", "", "" - if !isValid { - status, errorMessage, failureKind = "failed", strings.Join(parsed.Errors, ";"), "validation" - } - rows = append(rows, db.ItemPublishBatchRow{RowNo: parsed.RowNo, CookieID: parsed.CookieID, Title: parsed.Title, Description: parsed.Description, Price: parsed.Price, OriginalPrice: parsed.OriginalPrice, Quantity: parsed.Quantity, PostageMode: parsed.PostageMode, Postage: parsed.Postage, ImagesJSON: string(imagesJSON), CategoryJSON: string(categoryJSON), AutomationJSON: string(automationJSON), Status: status, ErrorMessage: errorMessage, FailureKind: failureKind, RawJSON: string(rawJSON)}) - previewRows = append(previewRows, publishBatchPreviewRow{RowNo: parsed.RowNo, Valid: isValid, Errors: parsed.Errors, CookieID: parsed.CookieID, Title: parsed.Title, Price: parsed.Price, Quantity: parsed.Quantity, Images: parsed.Images, Category: parsed.Category, Automation: parsed.Automation}) - } - if len(rows) == 0 { - return itemPublishBatchPreviewResponse{}, errItemPublishBatchNoRows - } - // locationBytes 是批次发货地配置的 JSON 表示。 - locationBytes, _ := json.Marshal(input.Location) - // err 表示批次及其明细的事务写入错误。 - if err := svc.repository.CreateBatch(ctx, &db.ItemPublishBatch{ID: input.BatchID, UserID: input.UserID, DefaultCookieID: input.DefaultCookieID, Filename: input.Filename, UploadDir: input.UploadDir, LocationJSON: string(locationBytes), Status: "preview"}, rows); err != nil { - return itemPublishBatchPreviewResponse{}, fmt.Errorf("保存预检结果失败: %w", err) - } - _ = svc.repository.RecountBatch(ctx, input.BatchID) - return itemPublishBatchPreviewResponse{Success: true, PreviewID: input.BatchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows}, nil -} - -// StartBatch 校验并声明批量任务租约,然后启动后台发布 worker。 -func (svc *itemPublishService) StartBatch(ctx context.Context, userID int64, batchID string) (string, error) { - // s 是当前商品发布应用服务依赖的 Server。 - s := svc.server - // batch 和 err 保存批次查询结果。 - batch, err := svc.repository.GetBatch(ctx, userID, batchID) - if err != nil { - return "", errItemPublishBatchNotFound - } - if batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix() { - return "", errItemPublishBatchConflict - } - if batch.Status != "preview" && batch.Status != "pending" && batch.Status != "completed" && batch.Status != "running" { - return "", errItemPublishBatchInvalidState - } - // token 是本次 worker 租约的随机凭证。 - token := randomHex(16) - // claimed 和 err 保存批次租约声明结果。 - claimed, err := svc.repository.ClaimBatch(ctx, batch.ID, token, time.Now().UTC().Add(publishBatchLease).Unix()) - if err != nil { - return "", fmt.Errorf("启动任务失败: %w", err) - } - if !claimed { - return "", errItemPublishBatchConflict - } - // pending 和 err 保存待处理明细查询结果。 - pending, err := svc.repository.PendingRows(ctx, batch.ID, false) - if err != nil { - s.failClaimedPublishBatch(batch.ID, token) - return "", fmt.Errorf("读取任务失败: %w", err) - } - if len(pending) == 0 { - _, _, _ = svc.repository.FinalizeBatch(ctx, batch.ID, token) - return "", errItemPublishBatchNoRows - } - s.startPublishBatchWorker(s.lifecycleContext(), userID, batch.ID, token) - return batch.ID, nil -} - -// ListBatches 查询用户的批量任务并映射为 HTTP 无关的响应 DTO。 -func (svc *itemPublishService) ListBatches(ctx context.Context, userID int64, limit int) ([]itemPublishBatchResponse, error) { - // batches 和 err 保存用户批次列表查询结果。 - batches, err := svc.repository.ListBatchesForUser(ctx, userID, limit) - if err != nil { - return nil, err - } - // result 是批次列表响应视图。 - result := make([]itemPublishBatchResponse, 0, len(batches)) - // i 是当前批次在查询结果中的索引。 - for i := range batches { - result = append(result, publishBatchToMap(&batches[i], nil)) - } - return result, nil -} - -// GetBatch 查询用户拥有的批量任务及其明细行。 -func (svc *itemPublishService) GetBatch(ctx context.Context, userID int64, batchID string) (itemPublishBatchResponse, error) { - // batch 和 err 保存批次查询结果。 - batch, err := svc.repository.GetBatch(ctx, userID, batchID) - if err != nil { - return itemPublishBatchResponse{}, errItemPublishBatchNotFound - } - // rows 和 err 保存批次明细查询结果。 - rows, err := svc.repository.ListBatchRows(ctx, batch.ID) - if err != nil { - return itemPublishBatchResponse{}, err - } - return publishBatchToMap(batch, rows), nil -} - -// CancelBatch 请求批量任务取消并通知内存中的 worker。 -func (svc *itemPublishService) CancelBatch(ctx context.Context, userID int64, batchID string) (string, error) { - // s 是当前商品发布应用服务依赖的 Server。 - s := svc.server - // err 表示批次所有权查询错误。 - if _, err := svc.repository.GetBatch(ctx, userID, batchID); err != nil { - return "", errItemPublishBatchNotFound - } - // token、running 和 err 保存取消请求及当前 worker 状态。 - token, running, err := svc.repository.RequestCancel(ctx, batchID) - if err != nil { - if errors.Is(err, db.ErrPublishBatchChanged) { - return "", errItemPublishBatchConflict - } - return "", err - } - if running { - s.cancelPublishBatch(batchID, token) - } - if running { - return "canceling", nil - } - return "canceled", nil -} - -// DeleteBatch 删除非运行中的批量任务并返回其上传目录供适配层清理。 -func (svc *itemPublishService) DeleteBatch(ctx context.Context, userID int64, batchID string) (string, error) { - // batch 和 err 保存批次查询结果。 - batch, err := svc.repository.GetBatch(ctx, userID, batchID) - if err != nil { - return "", errItemPublishBatchNotFound - } - if batch.Status == "running" || batch.Status == "canceling" { - return "", errItemPublishBatchConflict - } - // err 表示批次删除错误。 - if err := svc.repository.DeleteBatch(ctx, userID, batchID); err != nil { - return "", err - } - return batch.UploadDir, nil -} - -// RetryFailedBatch 重置失败明细并启动仅处理失败项的后台 worker。 -func (svc *itemPublishService) RetryFailedBatch(ctx context.Context, userID int64, batchID string) (string, error) { - // s 是当前商品发布应用服务依赖的 Server。 - s := svc.server - // batch 和 err 保存批次查询结果。 - batch, err := svc.repository.GetBatch(ctx, userID, batchID) - if err != nil { - return "", errItemPublishBatchNotFound - } - if batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix() { - return "", errItemPublishBatchConflict - } - // token 是本次重试 worker 的租约凭证。 - token := randomHex(16) - // claimed 和 err 保存重试租约声明结果。 - claimed, err := svc.repository.ClaimBatch(ctx, batchID, token, time.Now().UTC().Add(publishBatchLease).Unix()) - if err != nil { - return "", err - } - if !claimed { - return "", errItemPublishBatchConflict - } - // err 表示重置失败明细的错误。 - if err := svc.repository.ResetFailed(ctx, batchID); err != nil { - s.failClaimedPublishBatch(batchID, token) - return "", err - } - _ = svc.repository.RecountBatch(ctx, batchID) - // pending 和 err 保存可重试明细查询结果。 - pending, err := svc.repository.PendingRows(ctx, batchID, false) - if err != nil { - s.failClaimedPublishBatch(batchID, token) - return "", err - } - if len(pending) == 0 { - _, _, _ = svc.repository.FinalizeBatch(ctx, batchID, token) - return "", errItemPublishBatchNoRows - } - s.startPublishBatchWorker(s.lifecycleContext(), userID, batchID, token) - return batchID, nil -} - -// serverItemPublishPort 将 MTOP、Cookie 会话与运行时同步适配为应用商品发布端口。 -type serverItemPublishPort struct { - // server 保存平台调用和账号凭证适配所需的 Server 依赖。 - server *Server - // repository 提供账号锁、平台凭证查询和 Cookie 写回能力。 - repository itemPublishRepository -} - -// Publish 执行单商品平台发布及响应 Cookie 持久化,不向应用层泄露 MTOP 类型。 -func (p serverItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInput) (itemapp.PublishOutcome, error) { - // unlock 释放当前账号的凭证串行化锁;锁覆盖现有平台会话不变量。 - unlock := p.repository.LockCredentials(input.CookieID) - // latest 保存加锁后读取的平台运行凭证视图。 - latest, err := p.server.loadCookiePlatformDetail(ctx, input.CookieID) - if err != nil || latest == nil || latest.UserID != input.UserID || !hasStoredCookieCredential(latest) { - unlock() - return itemapp.PublishOutcome{}, errors.New("账号凭证已变化,请重试") - } - // requestCtx 和 cancel 控制单商品平台发布的最长执行时间。 - requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) - defer cancel() - // images 保存应用图片 DTO 转换后的平台图片请求。 - images := make([]mtop.PublishImage, 0, len(input.Images)) - // image 表示当前待转换的应用图片。 - for _, image := range input.Images { - images = append(images, mtop.PublishImage{Filename: image.Filename, ContentType: image.ContentType, Data: image.Data}) - } - // location 保存应用发货地 DTO 转换后的平台位置请求。 - var location *mtop.PublishLocation - if input.Location != nil { - location = &mtop.PublishLocation{ - Area: input.Location.Area, City: input.Location.City, DivisionID: input.Location.DivisionID, - Longitude: input.Location.Longitude, Latitude: input.Location.Latitude, POIID: input.Location.POIID, - POIName: input.Location.POIName, Province: input.Location.Province, - } - } - // mtopCtx 和 cookieSession 保存带 Cookie 快照的平台调用上下文。 - mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest) - // result 和 callErr 保存平台发布结果及调用错误。 - result, callErr := p.server.mtopClient().PublishItem(mtopCtx, latest.Value, mtop.PublishItemRequest{ - Title: input.Title, Description: input.Description, PriceCents: input.PriceCents, - OriginalPriceCents: input.OriginalPriceCents, Quantity: input.Quantity, - PostageMode: input.PostageMode, PostageCents: input.PostageCents, Virtual: true, - Location: location, Images: images, - }) - // runtimeCookie 保存需要在释放凭证锁后同步到运行时的刷新 Cookie。 - runtimeCookie := "" - // value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。 - value, valueChanged, handled, persistErr := p.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession) - if persistErr != nil { - if p.server.Logger != nil { - p.server.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", input.CookieID, "err", persistErr) - } - } else if handled && valueChanged { - runtimeCookie = value - } else if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != latest.Value { - // saveErr 表示保存平台返回新 Cookie 的错误。 - if saveErr := p.repository.UpdateCookieValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil { - persistErr = saveErr - } else { - runtimeCookie = result.UpdatedCookies - } - } - unlock() - if runtimeCookie != "" { - p.server.updateRunningCookie(ctx, input.CookieID, runtimeCookie) - } - if callErr != nil { - if persistErr != nil { - callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr)) - } - p.server.recoverExpiredMTOPSession(ctx, input.CookieID, callErr) - return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, callErr - } - if result == nil || strings.TrimSpace(result.ItemID) == "" { - return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, nil - } - return itemapp.PublishOutcome{Result: &itemapp.PublishResult{ - ItemID: result.ItemID, ItemURL: result.ItemURL, Title: result.Title, PriceText: result.PriceText, - CategoryID: result.CategoryID, CategoryName: result.CategoryName, ImageURL: result.ImageURL, - Quantity: result.Quantity, RawData: result.RawData, - }, ResponseCookieErr: persistErr}, nil -} - -// storeItemPublishItemRepository 将商品数据库写入适配为应用层商品仓储端口。 -type storeItemPublishItemRepository struct { - // store 保存数据库聚合入口,仅在 Server 适配器内部使用。 - store *db.Store -} - -// Upsert 保存应用层商品记录,并在边界转换为数据库行模型。 -func (r storeItemPublishItemRepository) Upsert(ctx context.Context, record itemapp.ItemRecord) error { - return r.store.Items.Upsert(ctx, &db.ItemInfoRow{ - CookieID: record.CookieID, ItemID: record.ItemID, ItemTitle: record.ItemTitle, - ItemDescription: record.ItemDescription, ItemCategory: record.ItemCategory, - ItemPrice: record.ItemPrice, ItemDetail: record.ItemDetail, - MultiQuantityDelivery: record.MultiQuantityDelivery, - }) -} - -// newItemPublishApplication 创建单商品发布应用服务并绑定 Server 适配器。 -func newItemPublishApplication(server *Server) *itemapp.Service { - // publisher 是商品发布平台端口适配器。 - publisher := serverItemPublishPort{server: server, repository: newStoreItemPublishRepository(server.Store)} - // repository 是商品本地持久化端口适配器。 - repository := storeItemPublishItemRepository{store: server.Store} - // service 和 err 保存应用服务构造结果。 - service, err := itemapp.NewService(publisher, repository) - if err != nil { - panic(fmt.Sprintf("商品发布应用服务装配失败: %v", err)) - } - return service -} diff --git a/internal/server/item_publish_service_test.go b/internal/server/item_publish_service_test.go index b0f1f4a..c3bf282 100644 --- a/internal/server/item_publish_service_test.go +++ b/internal/server/item_publish_service_test.go @@ -4,26 +4,26 @@ import ( "context" "testing" - "xianyu-go/internal/xianyu/mtop" + itemapp "xianyu-go/internal/application/items" ) -// TestItemPublishServicePersistPreview 验证预检结果由应用服务统一持久化并可再次读取。 -func TestItemPublishServicePersistPreview(t *testing.T) { +// TestBatchManagementReadsPersistedPreview 验证批次管理应用服务可以读取预检持久化结果。 +func TestBatchManagementReadsPersistedPreview(t *testing.T) { // srv、store 和 cleanup 构造并释放测试服务。 srv, _, cleanup := newTestServer(t) defer cleanup() - // service 是待验证的商品发布应用服务。 - service := srv.itemPublishApplication() + // service 是待验证的预检持久化应用服务。 + service := srv.itemBatchPreviewPersistenceApplication() // preview 和 err 保存预检持久化结果。 - preview, err := service.PersistPreview(context.Background(), itemPublishPreviewInput{ - UserID: 1, BatchID: "batch_service_test", DefaultCookieID: "acc1", + preview, err := service.Persist(context.Background(), itemapp.BatchPreviewPersistenceBatch{ + UserID: 1, ID: "batch_service_test", DefaultCookieID: "acc1", Filename: "products.csv", UploadDir: "/tmp/publish-service-test", - Location: mtop.PublishLocation{DivisionID: "3301"}, - Rows: []publishBatchParsedRow{{ - RowNo: 2, CookieID: "acc1", Title: "服务层商品", Price: "12.50", Quantity: 1, - Images: []string{"img/a.png"}, Category: mtop.PublishCategory{CatID: "5001", CatName: "虚拟商品"}, - }}, - }) + Location: itemapp.Location{DivisionID: "3301"}, + }, []itemapp.BatchPreviewRow{{ + RowNo: 2, CookieID: "acc1", Title: "服务层商品", Price: "12.50", Quantity: 1, + Images: []string{"img/a.png"}, Category: itemapp.BatchPreviewCategory{CatID: "5001", CatName: "虚拟商品"}, + }}, + ) if err != nil { t.Fatalf("PersistPreview error: %v", err) } @@ -31,23 +31,23 @@ func TestItemPublishServicePersistPreview(t *testing.T) { t.Fatalf("unexpected preview: %+v", preview) } // got 和 err 保存从数据库读取的批次视图。 - got, err := service.GetBatch(context.Background(), 1, preview.PreviewID) + details, err := srv.itemBatchManagementApplication().GetBatch(context.Background(), 1, preview.PreviewID) if err != nil { t.Fatalf("GetBatch error: %v", err) } - if got.ID != preview.PreviewID || len(got.Rows) != 1 || got.Rows[0].Title != "服务层商品" { - t.Fatalf("unexpected batch: %+v", got) + if details.Batch.ID != preview.PreviewID || len(details.Rows) != 1 || details.Rows[0].Title != "服务层商品" { + t.Fatalf("unexpected batch: %+v", details) } } -// TestItemPublishServiceStartBatchNotFound 验证应用服务对越权或不存在批次返回统一领域错误。 -func TestItemPublishServiceStartBatchNotFound(t *testing.T) { +// TestBatchManagementStartBatchNotFound 验证批次管理服务对越权或不存在批次返回统一领域错误。 +func TestBatchManagementStartBatchNotFound(t *testing.T) { // srv、store 和 cleanup 构造并释放测试服务。 srv, _, cleanup := newTestServer(t) defer cleanup() // err 保存不存在批次的业务错误。 - _, err := srv.itemPublishApplication().StartBatch(context.Background(), 1, "missing-batch") - if err != errItemPublishBatchNotFound { - t.Fatalf("error=%v want %v", err, errItemPublishBatchNotFound) + _, err := srv.itemBatchManagementApplication().StartBatch(context.Background(), 1, "missing-batch", publishBatchLease) + if err != itemapp.ErrBatchNotFound { + t.Fatalf("error=%v want %v", err, itemapp.ErrBatchNotFound) } } diff --git a/internal/server/item_sync_application_test.go b/internal/server/item_sync_application_test.go new file mode 100644 index 0000000..26cf6cc --- /dev/null +++ b/internal/server/item_sync_application_test.go @@ -0,0 +1,59 @@ +package server + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + itemapp "xianyu-go/internal/application/items" +) + +// itemSyncRepositoryStub 是隔离 HTTP 错误映射测试的商品同步 Port 桩。 +type itemSyncRepositoryStub struct { + // owned 表示桩返回的账号归属结果。 + owned bool + // allErr 保存全量同步桩返回的错误。 + allErr error +} + +// OwnsAccount 返回预设的账号归属结果。 +func (s *itemSyncRepositoryStub) OwnsAccount(_ context.Context, _ int64, _ string) (bool, error) { + return s.owned, nil +} + +// SyncAll 返回预设的全量同步错误。 +func (s *itemSyncRepositoryStub) SyncAll(_ context.Context, _ itemapp.SyncQuery) (itemapp.SyncAllResult, error) { + return itemapp.SyncAllResult{}, s.allErr +} + +// SyncPage 返回无错误的空分页结果,满足同步 Port 的完整契约。 +func (s *itemSyncRepositoryStub) SyncPage(_ context.Context, _ itemapp.SyncQuery) (itemapp.SyncPageResult, error) { + return itemapp.SyncPageResult{}, nil +} + +// TestSyncItemsPersistenceFailureMapsToServerError 验证本地持久化失败不会伪装成平台错误。 +func TestSyncItemsPersistenceFailureMapsToServerError(t *testing.T) { + // srv、cleanup 保存本次 HTTP 测试使用的服务和清理函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // persistenceErr 表示应用 Port 报告的本地写入失败。 + persistenceErr := &itemapp.SyncError{Kind: itemapp.SyncErrorPersistence, Err: errors.New("写入失败")} + // srv.applications.itemSync 替换为可控的应用服务,隔离数据库故障映射。 + srv.applications.itemSync = itemapp.NewSyncService(&itemSyncRepositoryStub{owned: true, allErr: persistenceErr}) + // h 保存当前服务路由。 + h := srv.Router() + // cookie 保存认证成功后的会话 Cookie。 + cookie := loginHelper(t, h) + // req 保存发起商品全集同步的请求。 + req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1"}`)) + req.AddCookie(cookie) + // rec 保存 HTTP 响应。 + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } +} diff --git a/internal/server/keyword_handlers.go b/internal/server/keyword_handlers.go index 9ef9c20..13774b4 100644 --- a/internal/server/keyword_handlers.go +++ b/internal/server/keyword_handlers.go @@ -4,15 +4,72 @@ import ( "errors" "net/http" "strconv" - "strings" "github.com/go-chi/chi/v5" + "xianyu-go/internal/application/keywords" "xianyu-go/internal/auth" - "xianyu-go/internal/db" ) -// mountKeywordsReal 关键字端点。 +// keywordRequest 是普通关键词接口使用的文字回复请求 DTO。 +type keywordRequest struct { + // Keyword 是触发匹配文本。 + Keyword string `json:"keyword"` + // Reply 是文字回复正文。 + Reply string `json:"reply"` +} + +// keywordBatchItem 是带商品范围的关键词批量项 DTO。 +type keywordBatchItem struct { + // Keyword 是触发匹配文本。 + Keyword string `json:"keyword"` + // Reply 是文字回复正文。 + Reply string `json:"reply"` + // ItemID 是可选商品标识。 + ItemID string `json:"item_id"` + // Type 是 text 或 image 回复类型。 + Type string `json:"type"` + // ImageURL 是图片回复地址。 + ImageURL string `json:"image_url"` +} + +// keywordBatchRequest 是关键词批量替换或单项创建请求 DTO。 +type keywordBatchRequest struct { + // Keyword 是单项创建的触发匹配文本。 + Keyword string `json:"keyword"` + // Reply 是单项创建的文字回复正文。 + Reply string `json:"reply"` + // ItemID 是单项创建的可选商品标识。 + ItemID string `json:"item_id"` + // Type 是单项创建的回复类型。 + Type string `json:"type"` + // ImageURL 是单项创建的图片回复地址。 + ImageURL string `json:"image_url"` + // Keywords 是批量替换项;为空指针表示请求使用单项模式。 + Keywords *[]keywordBatchItem `json:"keywords"` +} + +// keywordUpdateRequest 是按 ID 更新关键词的请求 DTO。 +type keywordUpdateRequest struct { + // Keyword 是触发匹配文本。 + Keyword string `json:"keyword"` + // Reply 是文字回复正文。 + Reply string `json:"reply"` + // ItemID 是可选商品标识。 + ItemID string `json:"item_id"` + // Type 是 text 或 image 回复类型。 + Type string `json:"type"` + // ImageURL 是图片回复地址。 + ImageURL string `json:"image_url"` +} + +// itemReplyRequest 是指定商品回复写入请求 DTO。 +type itemReplyRequest struct { + // ReplyContent 是商品命中后的回复正文。 + ReplyContent string `json:"reply_content"` +} + +// mountKeywordsReal 注册关键词回复兼容路由。 func (s *Server) mountKeywordsReal(r chi.Router) { r.Get("/keywords/{cid}", s.listKeywords) r.Post("/keywords/{cid}", s.addKeyword) @@ -24,313 +81,260 @@ func (s *Server) mountKeywordsReal(r chi.Router) { r.Delete("/keywords/{cid}/{index}", s.deleteKeyword) } -// listKeywords 负责listKeywords相关处理。 +// keywordApplication 返回关键词回复应用服务;具体依赖由 Server 统一装配。 +func (s *Server) keywordApplication() *keywords.Service { + return s.applicationServiceSet().keywords +} + +// keywordUserID 从认证上下文读取当前用户,不读取任何账号凭证。 +func keywordUserID(w http.ResponseWriter, r *http.Request) (int64, bool) { + // session 是认证中间件注入的当前用户会话。 + session := auth.SessionFromContext(r.Context()) + if session == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") + return 0, false + } + return session.UserID, true +} + +// writeKeywordError 将应用层错误映射为现有关键词接口的 HTTP 语义。 +func writeKeywordError(w http.ResponseWriter, err error, fallback string) { + if err == nil { + return + } + // validationErr 是可安全展示给调用方的参数校验提示。 + var validationErr *keywords.ValidationError + if errors.As(err, &validationErr) { + writeErr(w, http.StatusBadRequest, validationErr.Error()) + return + } + switch { + case errors.Is(err, keywords.ErrForbidden): + writeErr(w, http.StatusForbidden, "无权限操作该账号") + case errors.Is(err, keywords.ErrNotFound): + writeErr(w, http.StatusNotFound, "关键字不存在") + case errors.Is(err, keywords.ErrInvalidInput): + writeErr(w, http.StatusBadRequest, "请求参数无效") + default: + writeErr(w, http.StatusInternalServerError, fallback) + } +} + +// listKeywords 返回兼容的基础关键词响应。 func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.Store.Keywords.AllRows(r.Context(), cid) + // rows 保存应用层查询结果。 + rows, err := s.keywordApplication().List(r.Context(), userID, cookieID) if err != nil { - writeErr(w, http.StatusInternalServerError, "查询失败") + writeKeywordError(w, err, "查询失败") return } - // out 保存out,供当前处理流程使用 - out := make([]keywordBasicResponse, 0, len(rows)) - // k 表示当前遍历过程中的k - for _, k := range rows { - out = append(out, keywordBasicResponse{Keyword: k.Keyword, Reply: k.Reply}) + // result 保存 HTTP 基础响应,隐藏数据库模型和内部字段。 + result := make([]keywordBasicResponse, 0, len(rows)) + // row 是当前待映射的关键词规则。 + for _, row := range rows { + result = append(result, keywordBasicResponse{Keyword: row.Keyword, Reply: row.Reply}) } - writeJSON(w, http.StatusOK, out) + writeJSON(w, http.StatusOK, result) } -// listKeywordsWithItemID 负责listKeywordsWith商品ID相关处理。 +// listKeywordsWithItemID 返回带商品范围的兼容关键词响应。 func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.Store.Keywords.AllRows(r.Context(), cid) + // rows 保存应用层查询结果。 + rows, err := s.keywordApplication().List(r.Context(), userID, cookieID) if err != nil { - writeErr(w, http.StatusInternalServerError, "查询失败") + writeKeywordError(w, err, "查询失败") return } - // out 保存out,供当前处理流程使用 - out := make([]keywordItemResponse, 0, len(rows)) - // k 表示当前遍历过程中的k - for _, k := range rows { - out = append(out, keywordItemResponse{Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID}) + // result 保存带商品字段的 HTTP 响应。 + result := make([]keywordItemResponse, 0, len(rows)) + // row 是当前待映射的关键词规则。 + for _, row := range rows { + result = append(result, keywordItemResponse{Keyword: row.Keyword, Reply: row.Reply, ItemID: row.ItemID}) } - writeJSON(w, http.StatusOK, out) + writeJSON(w, http.StatusOK, result) } -// listKeywordsWithType 负责listKeywordsWith类型相关处理。 +// listKeywordsWithType 返回支持 text/image 类型的兼容响应。 func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.Store.Keywords.AllRows(r.Context(), cid) + // rows 保存应用层查询结果。 + rows, err := s.keywordApplication().List(r.Context(), userID, cookieID) if err != nil { - writeErr(w, http.StatusInternalServerError, "查询失败") + writeKeywordError(w, err, "查询失败") return } - // out 保存out,供当前处理流程使用 - out := make([]keywordTypedResponse, 0, len(rows)) - // k 表示当前遍历过程中的k - for _, k := range rows { - out = append(out, keywordTypedResponse{ - ID: k.ID, Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID, - Type: k.Type, ImageURL: k.ImageURL, - }) + // result 保存带类型字段的 HTTP 响应。 + result := make([]keywordTypedResponse, 0, len(rows)) + // row 是当前待映射的关键词规则。 + for _, row := range rows { + result = append(result, keywordTypedResponse{ID: row.ID, Keyword: row.Keyword, Reply: row.Reply, ItemID: row.ItemID, Type: row.Type, ImageURL: row.ImageURL}) } - writeJSON(w, http.StatusOK, out) + writeJSON(w, http.StatusOK, result) } -// addKeyword 负责add关键词相关处理。 +// addKeyword 创建一条普通文字关键词规则。 func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // req 保存req,供当前处理流程使用 - var req struct { - Keyword string `json:"keyword"` - Reply string `json:"reply"` - } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" { + // request 是普通关键词请求 DTO。 + var request keywordRequest + // err 表示请求 JSON 解码失败。 + if err := decodeJSON(r, &request); err != nil { writeErr(w, http.StatusBadRequest, "keyword 必填") return } - if strings.TrimSpace(req.Reply) == "" { - writeErr(w, http.StatusBadRequest, "文字回复内容不能为空") - return - } - if // err 保存err,供当前处理流程使用 - _, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, "", "text", ""); err != nil { - writeErr(w, http.StatusInternalServerError, "添加失败") + // _, err 表示创建操作的结果;ID 对兼容响应不向客户端暴露。 + if _, err := s.keywordApplication().Add(r.Context(), userID, cookieID, keywords.Draft{Keyword: request.Keyword, Reply: request.Reply, Type: "text"}); err != nil { + writeKeywordError(w, err, "添加失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// addKeywordWithItemID 负责add关键词With商品ID相关处理。 +// addKeywordWithItemID 创建或批量替换带商品范围的关键词规则。 func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // req 保存req,供当前处理流程使用 - var req struct { - Keyword string `json:"keyword"` - Reply string `json:"reply"` - ItemID string `json:"item_id"` - Type string `json:"type"` - ImageURL string `json:"image_url"` - Keywords *[]struct { - Keyword string `json:"keyword"` - Reply string `json:"reply"` - ItemID string `json:"item_id"` - Type string `json:"type"` - ImageURL string `json:"image_url"` - } `json:"keywords"` - } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil { + // request 是单项或批量关键词请求 DTO。 + var request keywordBatchRequest + // err 表示请求 JSON 解码失败。 + if err := decodeJSON(r, &request); err != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - if req.Keywords != nil { - // rows 保存rows,供当前处理流程使用 - rows := make([]db.KeywordRow, 0, len(*req.Keywords)) - // item 表示当前遍历过程中的商品 - for _, item := range *req.Keywords { - if strings.TrimSpace(item.Keyword) == "" { - writeErr(w, http.StatusBadRequest, "keyword 必填") - return - } - item.Type = strings.ToLower(strings.TrimSpace(item.Type)) - if item.Type == "" { - item.Type = "text" - } - switch item.Type { - case "text": - if strings.TrimSpace(item.Reply) == "" { - writeErr(w, http.StatusBadRequest, "文字回复内容不能为空") - return - } - item.ImageURL = "" - case "image": - if strings.TrimSpace(item.ImageURL) == "" { - writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空") - return - } - item.Reply = "" - default: - writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image") - return - } - rows = append(rows, db.KeywordRow{ - CookieID: cid, - Keyword: item.Keyword, - Reply: item.Reply, - ItemID: item.ItemID, - Type: item.Type, - ImageURL: item.ImageURL, - }) + if request.Keywords != nil { + // drafts 保存经过应用服务校验的批量关键词输入。 + drafts := make([]keywords.Draft, 0, len(*request.Keywords)) + // item 是当前待转换的批量请求项。 + for _, item := range *request.Keywords { + drafts = append(drafts, keywords.Draft{Keyword: item.Keyword, Reply: item.Reply, ItemID: item.ItemID, Type: item.Type, ImageURL: item.ImageURL}) } - if // err 保存err,供当前处理流程使用 - err := s.Store.Keywords.ReplaceForCookie(r.Context(), cid, rows); err != nil { - writeErr(w, http.StatusInternalServerError, "保存失败") + // err 表示批量替换规则的应用服务错误。 + if err := s.keywordApplication().Replace(r.Context(), userID, cookieID, drafts); err != nil { + writeKeywordError(w, err, "保存失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) return } - if strings.TrimSpace(req.Keyword) == "" { - writeErr(w, http.StatusBadRequest, "keyword 必填") - return - } - req.Type = strings.ToLower(strings.TrimSpace(req.Type)) - if req.Type == "" { - req.Type = "text" - } - if req.Type == "text" && strings.TrimSpace(req.Reply) == "" { - writeErr(w, http.StatusBadRequest, "文字回复内容不能为空") - return - } - if req.Type == "image" && strings.TrimSpace(req.ImageURL) == "" { - writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空") - return - } - if req.Type != "text" && req.Type != "image" { - writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image") - return - } - if req.Type == "image" { - req.Reply = "" - } else { - req.ImageURL = "" - } - // id、err 保存id、err,供当前处理流程使用 - id, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, req.ItemID, req.Type, req.ImageURL) + // id 是新建规则的持久化标识;兼容响应保留该字段。 + id, err := s.keywordApplication().Add(r.Context(), userID, cookieID, keywords.Draft{Keyword: request.Keyword, Reply: request.Reply, ItemID: request.ItemID, Type: request.Type, ImageURL: request.ImageURL}) if err != nil { - writeErr(w, http.StatusInternalServerError, "添加失败") + writeKeywordError(w, err, "添加失败") return } writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id}) } -// updateKeywordByID 负责update关键词ByID相关处理。 +// updateKeywordByID 按关键词 ID 更新 text/image 规则。 func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // id、err 保存id、err,供当前处理流程使用 - id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) - if err != nil || id <= 0 { + // id 是路由中的关键词持久化标识。 + id, parseErr := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if parseErr != nil || id <= 0 { writeErr(w, http.StatusBadRequest, "无效关键词ID") return } - // req 保存req,供当前处理流程使用 - var req struct { - Keyword string `json:"keyword"` - Reply string `json:"reply"` - ItemID string `json:"item_id"` - Type string `json:"type"` - ImageURL string `json:"image_url"` - } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil || strings.TrimSpace(req.Keyword) == "" { + // request 是关键词更新请求 DTO。 + var request keywordUpdateRequest + // err 表示请求 JSON 解码失败。 + if err := decodeJSON(r, &request); err != nil { writeErr(w, http.StatusBadRequest, "keyword 必填") return } - req.Type = strings.ToLower(strings.TrimSpace(req.Type)) - if req.Type == "" { - req.Type = "text" - } - switch req.Type { - case "text": - if strings.TrimSpace(req.Reply) == "" { - writeErr(w, http.StatusBadRequest, "文字回复内容不能为空") - return - } - req.ImageURL = "" - case "image": - if strings.TrimSpace(req.ImageURL) == "" { - writeErr(w, http.StatusBadRequest, "图片回复 URL 不能为空") - return - } - req.Reply = "" - default: - writeErr(w, http.StatusBadRequest, "回复类型必须是 text 或 image") - return - } - err = s.Store.Keywords.UpdateByID(r.Context(), db.KeywordRow{ - ID: id, CookieID: cid, Keyword: req.Keyword, Reply: req.Reply, - ItemID: req.ItemID, Type: req.Type, ImageURL: req.ImageURL, - }) - if err != nil { - if errors.Is(err, db.ErrNotFound) { - writeErr(w, http.StatusNotFound, "关键字不存在") - return - } - writeErr(w, http.StatusInternalServerError, "保存失败") + // updateErr 表示应用层更新结果。 + updateErr := s.keywordApplication().Update(r.Context(), userID, cookieID, id, keywords.Draft{Keyword: request.Keyword, Reply: request.Reply, ItemID: request.ItemID, Type: request.Type, ImageURL: request.ImageURL}) + if updateErr != nil { + writeKeywordError(w, updateErr, "保存失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// deleteKeywordByID 负责delete关键词ByID相关处理。 +// deleteKeywordByID 按持久化 ID 删除关键词规则。 func (s *Server) deleteKeywordByID(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // id、err 保存id、err,供当前处理流程使用 - id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) - if err != nil || id <= 0 { + // id 是路由中的关键词持久化标识。 + id, parseErr := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if parseErr != nil || id <= 0 { writeErr(w, http.StatusBadRequest, "无效关键词ID") return } - if // err 保存err,供当前处理流程使用 - err := s.Store.Keywords.DeleteByID(r.Context(), cid, id); err != nil { - writeErr(w, http.StatusNotFound, "关键字不存在") + // deleteErr 表示应用层删除结果。 + deleteErr := s.keywordApplication().DeleteByID(r.Context(), userID, cookieID, id) + if deleteErr != nil { + writeKeywordError(w, deleteErr, "关键字不存在") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// deleteKeyword 负责delete关键词相关处理。 +// deleteKeyword 按兼容的零基索引删除关键词规则。 func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cid") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cid") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // index 保存index,供当前处理流程使用 - index := atoiDefault(chi.URLParam(r, "index"), -1) - if // err 保存err,供当前处理流程使用 - err := s.Store.Keywords.DeleteByIndex(r.Context(), cid, index); err != nil { - writeErr(w, http.StatusNotFound, "关键字不存在") + // index 是按关键词 ID 顺序解释的零基索引。 + index, parseErr := strconv.Atoi(chi.URLParam(r, "index")) + if parseErr != nil { + index = -1 + } + // deleteErr 表示应用层删除结果。 + deleteErr := s.keywordApplication().DeleteByIndex(r.Context(), userID, cookieID, index) + if deleteErr != nil { + writeKeywordError(w, deleteErr, "关键字不存在") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// ---- 指定商品回复 ---- +// mountItemRepliesReal 注册指定商品回复兼容路由。 func (s *Server) mountItemRepliesReal(r chi.Router) { r.Get("/itemReplays", s.listItemReplies) r.Get("/item-reply/{cookie_id}/{item_id}", s.getItemReply) @@ -338,84 +342,93 @@ func (s *Server) mountItemRepliesReal(r chi.Router) { r.Delete("/item-reply/{cookie_id}/{item_id}", s.deleteItemReply) } -// listItemReplies 负责list商品回复列表相关处理。 +// listItemReplies 返回当前用户全部账号的指定商品回复。 func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 - sess := auth.SessionFromContext(r.Context()) - cookieIDs, _ := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 是当前用户拥有的账号 ID。 - var result []itemReplyResponse - // cid 表示当前遍历过程中的cid - for _, cid := range cookieIDs { - // rows 保存rows,供当前处理流程使用 - rows, _ := s.Store.ItemReps.AllForUser(r.Context(), cid) - // ir 表示当前遍历过程中的ir - for _, ir := range rows { - result = append(result, itemReplyResponse{ - ItemID: ir.ItemID, CookieID: ir.CookieID, ReplyContent: ir.ReplyContent, - }) - } + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { + return + } + // rows 保存应用层商品回复结果。 + rows, err := s.keywordApplication().ListItemReplies(r.Context(), userID) + if err != nil { + // 兼容历史接口:列表查询失败仍返回空列表和 200。 + writeJSON(w, http.StatusOK, []itemReplyResponse{}) + return + } + // result 保存 HTTP 商品回复响应。 + result := make([]itemReplyResponse, 0, len(rows)) + // row 是当前待映射的商品回复。 + for _, row := range rows { + result = append(result, itemReplyResponse{ItemID: row.ItemID, CookieID: row.CookieID, ReplyContent: row.ReplyContent}) } writeJSON(w, http.StatusOK, result) } -// getItemReply 负责get商品回复相关处理。 +// getItemReply 返回指定商品回复;缺失时保持历史空正文响应。 func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cookie_id") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cookie_id") + // itemID 是路由中的商品标识。 + itemID := chi.URLParam(r, "item_id") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // itemID 保存商品ID,供当前处理流程使用 - itemID := chi.URLParam(r, "item_id") - // ir、err 保存ir、err,供当前处理流程使用 - ir, err := s.Store.ItemReps.Get(r.Context(), cid, itemID) - if err != nil { + // row 保存应用层商品回复结果。 + row, err := s.keywordApplication().GetItemReply(r.Context(), userID, cookieID, itemID) + if errors.Is(err, keywords.ErrNotFound) { writeJSON(w, http.StatusOK, itemReplyResponse{ReplyContent: ""}) return } - writeJSON(w, http.StatusOK, itemReplyResponse{ - ItemID: ir.ItemID, CookieID: ir.CookieID, ReplyContent: ir.ReplyContent, - }) -} - -// setItemReply 负责set商品回复相关处理。 -func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cookie_id") - if !s.requireCookieOwnership(w, r, cid) { + if err != nil { + writeKeywordError(w, err, "查询失败") return } - // itemID 保存商品ID,供当前处理流程使用 + writeJSON(w, http.StatusOK, itemReplyResponse{ItemID: row.ItemID, CookieID: row.CookieID, ReplyContent: row.ReplyContent}) +} + +// setItemReply 覆盖指定商品回复。 +func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cookie_id") + // itemID 是路由中的商品标识。 itemID := chi.URLParam(r, "item_id") - // req 保存req,供当前处理流程使用 - var req struct { - ReplyContent string `json:"reply_content"` + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { + return } - if // err 保存err,供当前处理流程使用 - err := decodeJSON(r, &req); err != nil { + // request 是指定商品回复请求 DTO。 + var request itemReplyRequest + // err 表示请求 JSON 解码失败。 + if err := decodeJSON(r, &request); err != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - if // err 保存err,供当前处理流程使用 - err := s.Store.ItemReps.Set(r.Context(), cid, itemID, req.ReplyContent); err != nil { - writeErr(w, http.StatusInternalServerError, "保存失败") + // err 表示应用层写入结果。 + if err := s.keywordApplication().SetItemReply(r.Context(), userID, cookieID, itemID, request.ReplyContent); err != nil { + writeKeywordError(w, err, "保存失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } -// deleteItemReply 负责delete商品回复相关处理。 +// deleteItemReply 删除指定商品回复。 func (s *Server) deleteItemReply(w http.ResponseWriter, r *http.Request) { - // cid 保存cid,供当前处理流程使用 - cid := chi.URLParam(r, "cookie_id") - if !s.requireCookieOwnership(w, r, cid) { + // cookieID 是路由中的账号标识。 + cookieID := chi.URLParam(r, "cookie_id") + // itemID 是路由中的商品标识。 + itemID := chi.URLParam(r, "item_id") + // userID 是当前认证用户标识。 + userID, ok := keywordUserID(w, r) + if !ok { return } - // itemID 保存商品ID,供当前处理流程使用 - itemID := chi.URLParam(r, "item_id") - if // err 保存err,供当前处理流程使用 - err := s.Store.ItemReps.Delete(r.Context(), cid, itemID); err != nil { - writeErr(w, http.StatusInternalServerError, "删除失败") + // err 表示应用层删除结果。 + if err := s.keywordApplication().DeleteItemReply(r.Context(), userID, cookieID, itemID); err != nil { + writeKeywordError(w, err, "删除失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) diff --git a/internal/server/login_audit.go b/internal/server/login_audit.go index 8418da8..3d4d15f 100644 --- a/internal/server/login_audit.go +++ b/internal/server/login_audit.go @@ -2,102 +2,35 @@ package server import ( "context" - "strings" - "time" - "xianyu-go/internal/db" + accountapp "xianyu-go/internal/application/account" ) -// loginMethodManual 保存登录方法Manual,供当前处理流程使用 const ( - loginMethodManual = "manual" - loginMethodPassword = "password" - loginMethodQRScan = "qr_scan" - loginStatusSuccess = "success" - loginStatusFailed = "failed" + // loginMethodPassword 保留 Server 内部调用方使用的账号密码登录方式别名。 + loginMethodPassword = accountapp.LoginMethodPassword + // loginMethodQRScan 保留 Server 内部调用方使用的扫码登录方式别名。 + loginMethodQRScan = accountapp.LoginMethodQRScan ) -// normalizeLoginMethod 负责normalize登录方法相关处理。 -func normalizeLoginMethod(method string) string { - switch strings.ToLower(strings.TrimSpace(method)) { - case "manual", "cookie", "manual_cookie": - return loginMethodManual - case "password", "password_login": - return loginMethodPassword - case "qr", "qr_login", "qr_scan": - return loginMethodQRScan - default: - return strings.ToLower(strings.TrimSpace(method)) - } -} - -// markSuccessfulLogin 负责markSuccessful登录相关处理。 +// markSuccessfulLogin 将 Server 登录成功事件交给账号应用服务审计,不在 HTTP 层组装数据库模型。 func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userID int64, method, message string) { - // repository 提供登录审计和账号状态持久化能力。 - repository := s.accountLoginRepositoryForServer() - if repository == nil { + if s == nil { return } - method = normalizeLoginMethod(method) - if method == "" { + // auditService 保存应用层登录审计服务;它拥有归一化、启用和日志写入编排。 + auditService := s.loginAuditApplication() + if auditService == nil { return } - // at 保存at,供当前处理流程使用 - at := time.Now().Unix() - if // err 保存err,供当前处理流程使用 - err := repository.MarkLogin(ctx, cookieID, method, at); err != nil { - if s.Logger != nil { - s.Logger.Warn("记录账号登录方式失败", "cookie_id", cookieID, "method", method, "err", err) - } - return - } - if method == loginMethodPassword || method == loginMethodQRScan { - if // err 保存err,供当前处理流程使用 - err := repository.SetStatusWithReason(ctx, cookieID, true, ""); err != nil && s.Logger != nil { - s.Logger.Warn("成功登录后启用账号失败", "cookie_id", cookieID, "method", method, "err", err) - } - } - s.addLoginLog(ctx, cookieID, userID, method, loginStatusSuccess, "", message, at) -} - -// addLoginLog 负责add登录Log相关处理。 -func (s *Server) addLoginLog(ctx context.Context, cookieID string, userID int64, method, status, failureReason, message string, at int64) { - // repository 提供登录日志持久化能力。 - repository := s.accountLoginRepositoryForServer() - if repository == nil { - return - } - if at == 0 { - at = time.Now().Unix() - } - if // err 保存err,供当前处理流程使用 - err := repository.AddLoginLog(ctx, db.AccountLoginLog{ - CookieID: cookieID, - UserID: userID, - OwnerID: userID, - AccountIdentifier: cookieID, - Method: normalizeLoginMethod(method), - Status: status, - Message: truncate(message, 500), - TriggerReason: loginTriggerReason(method), - FailureReason: failureReason, - ErrorMessage: truncate(message, 500), - CreatedAt: at, - }); err != nil && s.Logger != nil { - s.Logger.Warn("记录账号登录日志失败", "cookie_id", cookieID, "method", method, "status", status, "err", err) - } -} - -// loginTriggerReason 负责登录Trigger原因相关处理。 -func loginTriggerReason(method string) string { - switch normalizeLoginMethod(method) { - case loginMethodManual: - return "手动Cookie录入" - case loginMethodPassword: - return "账号密码登录" - case loginMethodQRScan: - return "扫码登录" - default: - return "" + // auditErr 保存审计服务返回的基础设施错误;登录主流程保持旧的成功后续行为并仅记录告警。 + auditErr := auditService.RecordSuccessfulLogin(ctx, accountapp.SuccessfulLoginInput{ + AccountID: cookieID, + UserID: userID, + Method: method, + Message: message, + }) + if auditErr != nil && s.Logger != nil { + s.Logger.Warn("记录账号登录审计失败", "cookie_id", cookieID, "method", method, "err", auditErr) } } diff --git a/internal/server/login_audit_test.go b/internal/server/login_audit_test.go new file mode 100644 index 0000000..051b282 --- /dev/null +++ b/internal/server/login_audit_test.go @@ -0,0 +1,47 @@ +package server + +import ( + "context" + "testing" +) + +// TestMarkSuccessfulLoginUsesApplicationAuditService 验证 Server 仅调用应用审计服务并保持登录成功持久化语义。 +func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) { + // srv、store 和 cleanup 保存带固定管理员账号的 HTTP 测试服务及资源清理函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // admin 保存触发登录审计的非敏感管理员身份。 + admin, adminErr := store.Users.GetByUsername(context.Background(), "admin") + if adminErr != nil { + t.Fatal(adminErr) + } + // srv.markSuccessfulLogin 执行账号密码登录别名的成功审计。 + srv.markSuccessfulLogin(context.Background(), "acc1", admin.ID, "password_login", "账号登录成功") + // summary 保存应用服务写入后的账号非敏感摘要。 + summary, summaryErr := store.Cookies.GetSummaryOwned(context.Background(), admin.ID, "acc1") + if summaryErr != nil || summary.LoginMethod != loginMethodPassword || summary.LastLoginAt == 0 { + t.Fatalf("登录方式未由应用审计服务保存 summary=%+v err=%v", summary, summaryErr) + } + // logs 保存应用审计服务写入的数据库记录。 + logs, logsErr := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10) + if logsErr != nil || len(logs) != 1 || logs[0].Method != loginMethodPassword || logs[0].Status != "success" || logs[0].TriggerReason != "账号密码登录" { + t.Fatalf("登录审计记录异常 logs=%+v err=%v", logs, logsErr) + } +} + +// TestMarkSuccessfulLoginSkipsEmptyMethod 验证 Server 对缺少登录方式的兼容空操作不创建审计记录。 +func TestMarkSuccessfulLoginSkipsEmptyMethod(t *testing.T) { + // srv、store 和 cleanup 保存 HTTP 测试服务及资源清理函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // srv.markSuccessfulLogin 执行缺少方式的兼容调用。 + srv.markSuccessfulLogin(context.Background(), "acc1", 1, "", "不应记录") + // logs 保存兼容调用后的数据库审计记录。 + logs, logsErr := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10) + if logsErr != nil { + t.Fatal(logsErr) + } + if len(logs) != 0 { + t.Fatalf("空登录方式不应写入审计记录: %+v", logs) + } +} diff --git a/internal/server/mtop_cookie_session.go b/internal/server/mtop_cookie_session.go index 3d358ad..1e3d46a 100644 --- a/internal/server/mtop_cookie_session.go +++ b/internal/server/mtop_cookie_session.go @@ -2,42 +2,12 @@ package server import ( "context" - "time" + "errors" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/cookierefresh" - "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/adapter" + accountapp "xianyu-go/internal/application/account" ) -// withMTopCookieSnapshot 为一次业务 MTOP 流程挂载账号 Cookie 会话。有完整 -// Jar 时保持所有作用域;历史账号则使用不冒充完整 Jar 的 flat session,仍能 -// 在成功或失败路径观察并持久化 Set-Cookie。 -// withMTopCookieSnapshot 负责withMTop登录凭证Snapshot相关处理。 -func withMTopCookieSnapshot(ctx context.Context, detail *db.CookieDetail) (context.Context, *mtop.CookieSession) { - if detail == nil { - return ctx, nil - } - // snapshot、ok 保存snapshot、ok,供当前处理流程使用 - snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) - if !ok { - return mtop.WithFlatCookieSession(ctx, detail.Value) - } - return mtop.WithCookieSnapshot(ctx, snapshot) -} - -// hasStoredCookieCredential 负责hasStored登录凭证Credential相关处理。 -func hasStoredCookieCredential(detail *db.CookieDetail) bool { - if detail == nil { - return false - } - if detail.Value != "" { - return true - } - // complete 保存complete,供当前处理流程使用 - _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON) - return complete -} - // persistMTopCookieSessionLocked 原子保存业务 MTOP 响应后的完整 Cookie Jar。 // 调用方必须持有账号凭证锁,并且 detail 必须是加锁后重读的最新记录。 // handled 表示本次请求由完整 Cookie Jar 接管,或 session 已产生可持久化更新; @@ -46,28 +16,13 @@ func hasStoredCookieCredential(detail *db.CookieDetail) bool { // persistMTopCookieSessionLocked 负责persistMTop登录凭证会话Locked相关处理。 func (s *Server) persistMTopCookieSessionLocked( ctx context.Context, - detail *db.CookieDetail, - session *mtop.CookieSession, + detail *accountapp.CredentialDetail, + session *adapter.CookieSession, ) (value string, valueChanged, handled bool, err error) { - if detail == nil || session == nil { - return "", false, false, nil + if s == nil { + return "", false, true, errors.New("cookie 会话持久化服务未初始化") } - // value、snapshot、changed 保存value、snapshot、changed,供当前处理流程使用 - value, snapshot, changed := session.State() - if !changed { - if snapshot != nil { - return detail.Value, false, true, nil - } - return "", false, false, nil - } - // metadata 保存metadata,供当前处理流程使用 - metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) - if snapshot != nil { - metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) - } - if // err 保存err,供当前处理流程使用 - err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()); err != nil { - return value, value != detail.Value, true, err - } - return value, value != detail.Value, true, nil + // repository 负责在凭证适配器内保存 Cookie 与加密 metadata;Server 不直接访问 Store。 + repository := s.accountLoginRepositoryForServer() + return adapter.PersistCookieSessionLocked(ctx, repository, detail, session) } diff --git a/internal/server/mtop_cookie_session_test.go b/internal/server/mtop_cookie_session_test.go index c9039ef..55e617f 100644 --- a/internal/server/mtop_cookie_session_test.go +++ b/internal/server/mtop_cookie_session_test.go @@ -68,8 +68,13 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T) if err != nil { t.Fatal(err) } - // message 保存消息,供当前处理流程使用 - _, _, message := srv.refreshAccountProfile(ctx, detail) + // profile、profileErr 保存资料应用服务返回的非敏感结果和用例错误。 + profile, profileErr := srv.accountProfileApplication().RefreshProfile(ctx, detail.UserID, detail.ID) + // message 保存资料刷新失败时的可展示错误文本。 + message := profile.ErrorMessage + if profileErr != nil { + message = profileErr.Error() + } if message == "" { t.Fatal("无效响应应返回解析错误") } @@ -116,7 +121,7 @@ func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing. if err != nil { t.Fatal(err) } - srv.refreshAccountProfile(context.Background(), detail) + _, _ = srv.accountProfileApplication().RefreshProfile(context.Background(), detail.UserID, detail.ID) // updated、err 保存updated、err,供当前处理流程使用 updated, err := store.Cookies.GetDetails(context.Background(), "acc1") @@ -149,7 +154,7 @@ func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) if err != nil { t.Fatal(err) } - srv.refreshAccountProfile(context.Background(), detail) + _, _ = srv.accountProfileApplication().RefreshProfile(context.Background(), detail.UserID, detail.ID) // updated、err 保存updated、err,供当前处理流程使用 updated, err := store.Cookies.GetDetails(context.Background(), "acc1") diff --git a/internal/server/notification_handlers.go b/internal/server/notification_handlers.go index 0a70d9b..b7caefd 100644 --- a/internal/server/notification_handlers.go +++ b/internal/server/notification_handlers.go @@ -1,7 +1,6 @@ package server import ( - "context" "errors" "net/http" "strconv" @@ -10,7 +9,6 @@ import ( "github.com/go-chi/chi/v5" notificationsapp "xianyu-go/internal/application/notifications" - "xianyu-go/internal/db" ) // notificationChannelCreateRequest 是创建通知渠道的具名 HTTP 请求 DTO;Config 只写入应用端口。 @@ -51,200 +49,11 @@ type notificationBindingRequest struct { Enabled *bool `json:"enabled"` } -// storeNotificationChannelRepository 将通知数据库能力适配为通知应用端口。 -type storeNotificationChannelRepository struct { - // store 保存数据库聚合入口,仅在 Server 基础设施适配器内使用。 - store *db.Store -} - -// ListChannels 查询渠道摘要并丢弃配置,避免敏感配置进入应用展示模型。 -func (r storeNotificationChannelRepository) ListChannels(ctx context.Context, userID int64) ([]notificationsapp.ChannelSummary, error) { - // rows、err 保存数据库渠道非敏感摘要;列表路径不会读取或解密 Config。 - rows, err := r.store.Notifications.ListChannelSummariesForUser(ctx, userID) - if err != nil { - return nil, err - } - // summaries 保存不含渠道配置的应用摘要。 - summaries := make([]notificationsapp.ChannelSummary, 0, len(rows)) - // row 表示当前待转换的数据库渠道行。 - for _, row := range rows { - summaries = append(summaries, notificationsapp.ChannelSummary{ID: row.ID, Name: row.Name, Type: row.Type, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID}) - } - return summaries, nil -} - -// GetChannelForUpdate 查询归属渠道的完整记录,仅供应用层合并部分更新。 -func (r storeNotificationChannelRepository) GetChannelForUpdate(ctx context.Context, channelID, userID int64) (*notificationsapp.ChannelRecord, error) { - // row、err 保存带用户归属的数据库渠道记录。 - row, err := r.store.Notifications.GetChannelRowForUser(ctx, channelID, userID) - if err != nil { - return nil, err - } - if row == nil { - return nil, nil - } - return ¬ificationsapp.ChannelRecord{ID: row.ID, Name: row.Name, Type: row.Type, Config: row.Config, EventTypes: row.EventTypes, Enabled: row.Enabled, UserID: row.UserID}, nil -} - -// CreateChannel 将应用输入转换为数据库行并创建渠道。 -func (r storeNotificationChannelRepository) CreateChannel(ctx context.Context, userID int64, input notificationsapp.ChannelInput) (int64, error) { - // row 保存待加密写入数据库的渠道行;Config 不向 HTTP 返回。 - row := db.NotificationChannelRow{Name: input.Name, Type: input.Type, Config: input.Config, EventTypes: input.EventTypes, Enabled: input.Enabled, UserID: userID} - return r.store.Notifications.CreateChannel(ctx, &row) -} - -// UpdateChannel 将应用层完整渠道记录转换为数据库更新。 -func (r storeNotificationChannelRepository) UpdateChannel(ctx context.Context, userID int64, record notificationsapp.ChannelRecord) error { - // row 保存待加密写入数据库的渠道行;调用方已完成归属和字段校验。 - row := db.NotificationChannelRow{ID: record.ID, Name: record.Name, Type: record.Type, Config: record.Config, EventTypes: record.EventTypes, Enabled: record.Enabled, UserID: userID} - return r.store.Notifications.UpdateChannelForUser(ctx, &row, userID) -} - -// DeleteChannel 删除用户拥有的渠道并统一转换不存在错误。 -func (r storeNotificationChannelRepository) DeleteChannel(ctx context.Context, channelID, userID int64) error { - return normalizeNotificationRepositoryError(r.store.Notifications.DeleteChannelForUser(ctx, channelID, userID)) -} - -// OwnsChannel 查询通知渠道归属,不读取配置内容。 -func (r storeNotificationChannelRepository) OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error) { - return r.store.Notifications.OwnsChannel(ctx, channelID, userID) -} - -// OwnsAccount 查询账号归属,不读取或解密 Cookie。 -func (r storeNotificationChannelRepository) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) { - return r.store.Cookies.ExistsOwned(ctx, userID, cookieID) -} - -// ListBindings 查询绑定摘要并转换为应用模型。 -func (r storeNotificationChannelRepository) ListBindings(ctx context.Context, userID int64) ([]notificationsapp.BindingSummary, error) { - // rows、err 保存数据库绑定摘要及错误。 - rows, err := r.store.Notifications.ListBindingsForUser(ctx, userID) - if err != nil { - return nil, err - } - // bindings 保存不含配置的应用绑定摘要。 - bindings := make([]notificationsapp.BindingSummary, 0, len(rows)) - // row 表示当前待转换的数据库绑定行。 - for _, row := range rows { - bindings = append(bindings, notificationsapp.BindingSummary{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled}) - } - return bindings, nil -} - -// GetBindingIDs 查询账号启用的通知渠道 ID。 -func (r storeNotificationChannelRepository) GetBindingIDs(ctx context.Context, cookieID string) ([]int64, error) { - return r.store.Notifications.AccountBindings(ctx, cookieID) -} - -// SetBindings 覆盖保存账号绑定,并保留数据库事务和跨归属校验。 -func (r storeNotificationChannelRepository) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error { - return normalizeNotificationRepositoryError(r.store.Notifications.SetBindings(ctx, cookieID, channelIDs)) -} - -// SetSingleBinding 更新单个账号绑定状态。 -func (r storeNotificationChannelRepository) SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error { - return r.store.Notifications.SetSingleBinding(ctx, cookieID, channelID, enabled) -} - -// DeleteBinding 删除用户的一条绑定。 -func (r storeNotificationChannelRepository) DeleteBinding(ctx context.Context, userID, bindingID int64) error { - return r.store.Notifications.DeleteBinding(ctx, userID, bindingID) -} - -// DeleteAccountBindings 删除用户账号的全部绑定。 -func (r storeNotificationChannelRepository) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error { - return r.store.Notifications.DeleteAccountBindings(ctx, userID, cookieID) -} - -// normalizeNotificationRepositoryError 将数据库归属错误转换为应用错误,隐藏基础设施类型。 -func normalizeNotificationRepositoryError(err error) error { - if errors.Is(err, db.ErrNotFound) { - return notificationsapp.ErrChannelNotFound - } - if errors.Is(err, db.ErrForbidden) { - return notificationsapp.ErrChannelForbidden - } - return err -} - -// newStoreNotificationChannelRepository 构造通知渠道应用端口适配器。 -func newStoreNotificationChannelRepository(store *db.Store) notificationsapp.ChannelRepository { - if store == nil || store.Notifications == nil || store.Cookies == nil { - return nil - } - return storeNotificationChannelRepository{store: store} -} - // notificationChannelsApplication 返回当前 Server 绑定的通知渠道应用服务。 func (s *Server) notificationChannelsApplication() *notificationsapp.ChannelService { return s.applicationServiceSet().notificationChannels } -// ensureStoreNotificationChannelRepository 保证通知渠道应用端口覆盖全部能力。 -var _ notificationsapp.ChannelRepository = storeNotificationChannelRepository{} - -// storeNotificationUncertainRepository 将数据库通知摘要查询适配为应用层端口。 -type storeNotificationUncertainRepository struct { - // store 保存数据库聚合入口,仅在脱敏摘要适配器内使用。 - store *db.Store -} - -// ListUncertainForUser 查询指定用户的不确定通知摘要,并转换为应用模型。 -func (r storeNotificationUncertainRepository) ListUncertainForUser(ctx context.Context, userID int64, limit int) ([]notificationsapp.UncertainSummary, error) { - // rows、err 保存数据库摘要查询结果及错误。 - rows, err := r.store.Notifications.ListUncertainOutboxForUser(ctx, userID, limit) - if err != nil { - return nil, err - } - return newNotificationUncertainApplicationSummaries(rows), nil -} - -// CountUncertainForUser 统计指定用户的不确定通知数量。 -func (r storeNotificationUncertainRepository) CountUncertainForUser(ctx context.Context, userID int64) (int, error) { - return r.store.Notifications.CountUncertainOutboxForUser(ctx, userID) -} - -// ListUncertainForAdmin 查询全局不确定通知摘要,并转换为应用模型。 -func (r storeNotificationUncertainRepository) ListUncertainForAdmin(ctx context.Context, limit int) ([]notificationsapp.UncertainSummary, error) { - // rows、err 保存数据库全局摘要查询结果及错误。 - rows, err := r.store.Notifications.ListUncertainOutboxForAdmin(ctx, limit) - if err != nil { - return nil, err - } - return newNotificationUncertainApplicationSummaries(rows), nil -} - -// CountUncertainForAdmin 统计全局不确定通知数量。 -func (r storeNotificationUncertainRepository) CountUncertainForAdmin(ctx context.Context) (int, error) { - return r.store.Notifications.CountUncertainOutboxForAdmin(ctx) -} - -// newStoreNotificationUncertainRepository 创建通知不确定状态应用服务使用的数据库适配器。 -func newStoreNotificationUncertainRepository(store *db.Store) notificationsapp.Repository { - if store == nil || store.Notifications == nil { - return nil - } - return storeNotificationUncertainRepository{store: store} -} - -// newNotificationUncertainApplicationSummaries 将数据库摘要转换为不含正文的应用模型。 -func newNotificationUncertainApplicationSummaries(rows []db.NotificationUncertainSummary) []notificationsapp.UncertainSummary { - // summaries 保存脱离数据库模型的非敏感通知摘要。 - summaries := make([]notificationsapp.UncertainSummary, 0, len(rows)) - // row 表示当前待转换的数据库通知摘要。 - for _, row := range rows { - summaries = append(summaries, notificationsapp.UncertainSummary{ - ID: row.ID, ChannelID: row.ChannelID, OwnerUserID: row.OwnerUserID, - EventType: row.EventType, AttemptCount: row.AttemptCount, - UncertainAt: row.UncertainAt, HasError: row.HasError, - }) - } - return summaries -} - -// 确保数据库适配器覆盖通知不确定状态应用端口的全部能力。 -var _ notificationsapp.Repository = storeNotificationUncertainRepository{} - // uncertainNotificationsApplication 返回当前 Server 绑定的通知不确定状态应用服务。 func (s *Server) uncertainNotificationsApplication() *notificationsapp.Service { return s.applicationServiceSet().uncertainNotifications @@ -352,7 +161,7 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "name 和 type 必填") return } - if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) { + if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) { writeErr(w, http.StatusForbidden, "无权操作该通知渠道") return } @@ -374,7 +183,7 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) { sess := authSess(r) // err 保存应用层删除结果。 if err := s.notificationChannelsApplication().DeleteChannel(r.Context(), sess.UserID, id); err != nil { - if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) || errors.Is(err, db.ErrNotFound) { + if errors.Is(err, notificationsapp.ErrChannelForbidden) || errors.Is(err, notificationsapp.ErrChannelNotFound) { writeErr(w, http.StatusForbidden, "无权操作该通知渠道") return } diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go index e0049b2..420b0f1 100644 --- a/internal/server/order_handlers.go +++ b/internal/server/order_handlers.go @@ -1,7 +1,6 @@ package server import ( - "context" "errors" "fmt" "net/http" @@ -11,27 +10,17 @@ import ( orderapp "xianyu-go/internal/application/orders" "xianyu-go/internal/auth" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/mtop" ) // refreshOrderChunkSize 保存refresh订单Chunk数量,供当前处理流程使用 const refreshOrderChunkSize = 100 -// maxSoldOrderPages 保存maxSold订单Pages,供当前处理流程使用 -const maxSoldOrderPages = 100 - // refreshTarget 保存refreshTarget,供当前处理流程使用 type refreshTarget struct { OrderID string CurrentStatus string } -// orderDetailMTop 保存订单DetailMTop,供当前处理流程使用 -type orderDetailMTop interface { - FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error) -} - // mountOrders 订单端点(真实实现)。 func (s *Server) mountOrdersReal(r chi.Router) { r.Get("/api/orders", s.listOrders) @@ -54,7 +43,7 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) { Status: r.URL.Query().Get("status"), Search: r.URL.Query().Get("search"), Page: atoiDefault(r.URL.Query().Get("page"), 1), PageSize: atoiDefault(r.URL.Query().Get("page_size"), 20), }) - if errors.Is(err, db.ErrForbidden) { + if errors.Is(err, orderapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权限操作该账号") return } @@ -81,7 +70,7 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) { // result、err 保存result、err,供当前处理流程使用 result, err := s.orders().GetView(r.Context(), sess.UserID, orderID) if err != nil { - if errors.Is(err, db.ErrForbidden) { + if errors.Is(err, orderapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权操作此订单") } else { writeErr(w, http.StatusNotFound, "订单不存在") @@ -132,11 +121,11 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { // sess := auth.SessionFromContext(r.Context()) // result、err 保存result、err,供当前处理流程使用 result, err := s.orders().RefreshSingle(r.Context(), sess.UserID, orderID) - if errors.Is(err, db.ErrNotFound) { + if errors.Is(err, orderapp.ErrNotFound) { writeErr(w, http.StatusNotFound, "订单不存在") return } - if errors.Is(err, db.ErrForbidden) { + if errors.Is(err, orderapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权操作此订单") return } @@ -167,7 +156,7 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) { sess := auth.SessionFromContext(r.Context()) if // err 保存err,供当前处理流程使用 err := s.orders().Delete(r.Context(), sess.UserID, orderID); err != nil { - if errors.Is(err, db.ErrForbidden) { + if errors.Is(err, orderapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权操作此订单") } else { writeErr(w, http.StatusNotFound, "订单不存在") @@ -232,9 +221,9 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) { if // kind、classified 保存kind、classified,供当前处理流程使用 kind, classified := orderErrorKindOf(err); classified && kind == orderErrorBadRequest { writeErr(w, http.StatusBadRequest, err.Error()) - } else if errors.Is(err, db.ErrForbidden) { + } else if errors.Is(err, orderapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权操作此订单") - } else if errors.Is(err, db.ErrNotFound) { + } else if errors.Is(err, orderapp.ErrNotFound) { writeErr(w, http.StatusNotFound, "订单不存在") } else { writeErr(w, http.StatusInternalServerError, "更新失败") @@ -297,56 +286,6 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { }) } -// consignWithCurrentCookie 负责consignWithCurrent登录凭证相关处理。 -func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) { - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := s.Store.LockAccountCredentials(cookieID) - defer credentialUnlock() - // detail、err 保存detail、err,供当前处理流程使用 - detail, err := s.loadCookiePlatformDetail(ctx, cookieID) - if err != nil { - return false, nil, "", false, err - } - if detail == nil || detail.UserID != userID { - return false, nil, "", false, db.ErrForbidden - } - if !hasStoredCookieCredential(detail) { - return false, nil, "", false, errors.New("账号 Cookie 为空") - } - // mtopCtx、cookieSession 保存mtopCtx、cookie会话,供当前处理流程使用 - mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, detail) - // ok、ret、updatedCookies、callErr 保存ok、ret、updatedCookies、callErr,供当前处理流程使用 - ok, ret, updatedCookies, callErr := s.MTop.ConsignContext(mtopCtx, detail.Value, orderID) - // value、valueChanged、handled、persistErr 保存value、valueChanged、handled、persistErr,供当前处理流程使用 - value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, detail, cookieSession) - if persistErr != nil { - persistErr = fmt.Errorf("保存发货响应 Cookie Jar: %w", persistErr) - if callErr != nil { - return ok, ret, "", false, errors.Join(callErr, persistErr) - } - return ok, ret, "", false, persistErr - } - if handled { - // runtimeCookie 保存runtime登录凭证,供当前处理流程使用 - runtimeCookie := "" - if valueChanged { - runtimeCookie = value - } - return ok, ret, runtimeCookie, valueChanged, callErr - } - if callErr != nil { - return false, ret, "", false, callErr - } - if updatedCookies == "" || updatedCookies == detail.Value { - return ok, ret, "", false, nil - } - if // err 保存err,供当前处理流程使用 - err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil { - return ok, ret, "", false, fmt.Errorf("保存发货响应 Cookie: %w", err) - } - return ok, ret, updatedCookies, true, nil -} - // importOrders 负责import订单列表相关处理。 func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) { // orders、err 保存orders、err,供当前处理流程使用 diff --git a/internal/server/order_handlers_extra_test.go b/internal/server/order_handlers_extra_test.go index 49b7297..ee82236 100644 --- a/internal/server/order_handlers_extra_test.go +++ b/internal/server/order_handlers_extra_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + orderapp "xianyu-go/internal/application/orders" "xianyu-go/internal/db" ) @@ -1101,9 +1102,10 @@ func stringPtrForOrderTest(value string) *string { // TestOrderResponseMappingAndErrorClassification 验证订单响应映射和业务错误分类不依赖 HTTP。 func TestOrderResponseMappingAndErrorClassification(t *testing.T) { // row 保存row,供当前处理流程使用 - row := db.OrderRow{OrderID: "mapped-order", ItemID: "mapped-item", ItemTitle: "测试商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/mapped.png"}}`, OrderStatus: "2"} + // row 保存应用层订单列表模型,模拟适配器已经完成数据库转换。 + row := orderapp.OrderRow{OrderID: "mapped-order", ItemID: "mapped-item", ItemTitle: "测试商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/mapped.png"}}`, OrderStatus: "2"} // view 保存view,供当前处理流程使用 - view := orderDTOFromRow(orderRowsFromDB([]db.OrderRow{row})[0]) + view := orderDTOFromRow(row) if view.OrderStatus != "pending_ship" || view.Status != "pending_ship" || view.ItemImage != "https://img.example/mapped.png" { t.Fatalf("订单响应映射异常: %+v", view) } diff --git a/internal/server/order_model_conversion_test.go b/internal/server/order_model_conversion_test.go index 5076d40..caa6c2e 100644 --- a/internal/server/order_model_conversion_test.go +++ b/internal/server/order_model_conversion_test.go @@ -4,73 +4,11 @@ import ( "reflect" "testing" + "xianyu-go/internal/adapter" orderapp "xianyu-go/internal/application/orders" "xianyu-go/internal/db" ) -// TestOrderModelConversions 保证订单边界转换完整保留业务字段并正确处理空值。 -func TestOrderModelConversions(t *testing.T) { - // databaseOrder 是模拟数据库读取到的完整订单实体。 - databaseOrder := &db.Order{ - OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", SpecName: "颜色", - SpecValue: "蓝", Quantity: "2", Amount: "19.90", OrderStatus: "pending_ship", - CookieID: "cookie-1", IsBargain: 1, ReceiverName: "收货人", ReceiverPhone: "13800000000", - ReceiverAddr: "上海市", ReceiverCity: "上海", Version: 3, ChatID: "chat-1", - SystemShipped: true, PaidAt: "paid", ShippedAt: "shipped", CompletedAt: "completed", - BuyerReviewedAt: "reviewed", LastReviewRequestAt: "requested", ReviewRequestCount: 2, - CreatedAt: "created", UpdatedAt: "updated", - } - // applicationOrder 是订单应用层实体的预期结果。 - applicationOrder := &orderapp.Order{ - OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", SpecName: "颜色", - SpecValue: "蓝", Quantity: "2", Amount: "19.90", OrderStatus: "pending_ship", - CookieID: "cookie-1", IsBargain: 1, ReceiverName: "收货人", ReceiverPhone: "13800000000", - ReceiverAddress: "上海市", ReceiverCity: "上海", Version: 3, ChatID: "chat-1", - SystemShipped: true, PaidAt: "paid", ShippedAt: "shipped", CompletedAt: "completed", - BuyerReviewedAt: "reviewed", LastReviewRequestAt: "requested", ReviewRequestCount: 2, - CreatedAt: "created", UpdatedAt: "updated", - } - // converted 是数据库订单转换后的应用订单。 - converted := orderFromDB(databaseOrder) - if !reflect.DeepEqual(converted, applicationOrder) { - t.Fatalf("订单转换结果不完整: got=%+v want=%+v", converted, applicationOrder) - } - if orderFromDB(nil) != nil { - t.Fatal("空数据库订单应转换为空应用订单") - } - - // databaseItem 是模拟数据库读取到的完整商品实体。 - databaseItem := &db.ItemInfo{ - ID: 7, CookieID: "cookie-1", ItemID: "item-1", ItemTitle: "商品", - ItemDescription: "描述", ItemCategory: "分类", ItemPrice: "9.95", ItemDetail: `{"images":["a"]}`, - IsMultiSpec: true, MultiQuantityDelivery: true, - } - // applicationItem 是商品应用层实体的预期结果。 - applicationItem := &orderapp.ItemInfo{ - ID: 7, CookieID: "cookie-1", ItemID: "item-1", ItemTitle: "商品", - ItemDescription: "描述", ItemCategory: "分类", ItemPrice: "9.95", ItemDetail: `{"images":["a"]}`, - IsMultiSpec: true, MultiQuantityDelivery: true, - } - // convertedItem 是数据库商品转换后的应用商品。 - convertedItem := itemInfoFromDB(databaseItem) - if !reflect.DeepEqual(convertedItem, applicationItem) { - t.Fatalf("商品转换结果不完整: got=%+v want=%+v", convertedItem, applicationItem) - } - if itemInfoFromDB(nil) != nil { - t.Fatal("空数据库商品应转换为空应用商品") - } - - // databaseRuntime 是模拟数据库读取到的平台运行视图。 - databaseRuntime := db.CookiePlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true} - // applicationRuntime 是平台运行视图的预期应用层结果。 - applicationRuntime := &orderapp.PlatformRuntimeData{ID: "cookie-1", UserID: 9, Value: "cookie", MetadataJSON: "{}", ShowBrowser: true} - // convertedRuntime 是数据库平台运行视图转换后的应用模型。 - convertedRuntime := platformRuntimeDataFromDB(databaseRuntime) - if !reflect.DeepEqual(convertedRuntime, applicationRuntime) { - t.Fatalf("平台运行视图转换结果不完整: got=%+v want=%+v", convertedRuntime, applicationRuntime) - } -} - // TestOrderForAutomation 保证未迁移的自动化边界不会丢失订单字段。 func TestOrderForAutomation(t *testing.T) { // applicationOrder 是传入自动化中心适配器的应用订单。 @@ -84,27 +22,11 @@ func TestOrderForAutomation(t *testing.T) { CookieID: "cookie-2", ChatID: "chat-2", OrderStatus: "pending_ship", Version: 4, } // converted 是传给自动化中心的数据库订单。 - converted := orderForAutomation(applicationOrder) + converted := adapter.OrderForAutomation(applicationOrder) if !reflect.DeepEqual(converted, expectedDatabaseOrder) { t.Fatalf("自动化边界订单转换错误: got=%+v want=%+v", converted, expectedDatabaseOrder) } - if orderForAutomation(nil) != nil { + if adapter.OrderForAutomation(nil) != nil { t.Fatal("空应用订单应转换为空数据库订单") } } - -// TestCookieDetailForOrderPlatform 保证订单刷新访问共享会话辅助函数时只映射最小字段。 -func TestCookieDetailForOrderPlatform(t *testing.T) { - // runtimeData 是订单应用层持有的平台运行视图。 - runtimeData := &orderapp.PlatformRuntimeData{ID: "cookie-3", UserID: 11, Value: "value", MetadataJSON: "metadata", ShowBrowser: true} - // expectedDetail 是共享 Server 会话辅助函数使用的兼容详情。 - expectedDetail := &db.CookieDetail{ID: "cookie-3", UserID: 11, Value: "value", MetadataJSON: "metadata", ShowBrowser: true} - // converted 是共享 Server 会话辅助函数使用的平台详情。 - converted := cookieDetailForOrderPlatform(runtimeData) - if !reflect.DeepEqual(converted, expectedDetail) { - t.Fatalf("平台详情边界转换错误: got=%+v want=%+v", converted, expectedDetail) - } - if cookieDetailForOrderPlatform(nil) != nil { - t.Fatal("空平台运行视图应转换为空平台详情") - } -} diff --git a/internal/server/order_refresh_job_handlers.go b/internal/server/order_refresh_job_handlers.go index cc0d1c4..0f28349 100644 --- a/internal/server/order_refresh_job_handlers.go +++ b/internal/server/order_refresh_job_handlers.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "net/http" "time" @@ -61,6 +62,18 @@ type orderRefreshWorker struct { cancel context.CancelFunc } +// orderRefreshJobRefresh 执行订单刷新业务并返回兼容 HTTP 响应模型。 +type orderRefreshJobRefresh func(context.Context, int64, string, string) (orderRefreshResponse, error) + +// orderRefreshJobMarshal 将刷新结果序列化为可持久化的 JSON。 +type orderRefreshJobMarshal func(any) ([]byte, error) + +// orderRefreshJobComplete 以租约令牌写入订单刷新任务终态。 +type orderRefreshJobComplete func(context.Context, string, string, string, string, string) (bool, error) + +// errOrderRefreshJobCompletionNotApplied 表示终态写入未匹配到当前 worker 租约。 +var errOrderRefreshJobCompletionNotApplied = errors.New("订单刷新任务终态未写入") + // mountOrderRefreshJobRoutes 挂载订单刷新后台任务端点。 func (s *Server) mountOrderRefreshJobRoutes(r chi.Router, prefix string) { r.Post(prefix+"/orders/refresh", s.startOrderRefreshJob) @@ -176,15 +189,26 @@ func (s *Server) startOrderRefreshWorker(job *orderapp.RefreshJob, token string) // parent 保存 Server 生命周期上下文,避免 HTTP 请求结束取消后台任务。 parent := s.lifecycleContext() if parent == nil { - parent = context.Background() + if s.Logger != nil { + s.Logger.Error("订单刷新任务缺少 Server 生命周期上下文", "job_id", job.ID) + } + return } // jobCtx、cancel 限制后台任务执行时间并支持用户取消。 jobCtx, cancel := context.WithTimeout(parent, orderRefreshJobTimeout) s.registerOrderRefreshWorker(job.ID, token, cancel) - s.startBackgroundTask("订单刷新任务", func() { + s.startBackgroundTaskResult("订单刷新任务", jobCtx, func() error { defer cancel() defer s.unregisterOrderRefreshWorker(job.ID, token) - s.runOrderRefreshJob(jobCtx, job, token) + // runErr 保存订单刷新业务或终态写入错误,供后台任务日志观测。 + runErr := s.runOrderRefreshJob(jobCtx, job, token) + if runErr != nil && s.Logger != nil { + s.Logger.Warn("订单刷新后台任务结束", "job_id", job.ID, "err", runErr) + } + if jobCtx.Err() != nil { + return nil + } + return runErr }) } @@ -228,26 +252,67 @@ func (s *Server) cancelOrderRefreshWorker(jobID string) bool { } // runOrderRefreshJob 执行订单刷新并以租约令牌写入成功或失败终态。 -func (s *Server) runOrderRefreshJob(ctx context.Context, job *orderapp.RefreshJob, token string) { +func (s *Server) runOrderRefreshJob(ctx context.Context, job *orderapp.RefreshJob, token string) error { + // orders 保存当前 Server 绑定的订单应用适配器。 + orders := s.orders() + if orders == nil || orders.services == nil || orders.services.Refresh == nil || orders.services.RefreshJobs == nil { + return errors.New("订单刷新任务依赖未初始化") + } + return runOrderRefreshJobWith(ctx, job, token, orders.Refresh, json.Marshal, orders.services.RefreshJobs.Complete) +} + +// runOrderRefreshJobWith 执行可注入依赖的订单刷新 worker,便于确定性验证终态边界。 +func runOrderRefreshJobWith(ctx context.Context, job *orderapp.RefreshJob, token string, refresh orderRefreshJobRefresh, marshal orderRefreshJobMarshal, complete orderRefreshJobComplete) error { + if ctx == nil { + return errors.New("订单刷新任务 Context 不能为空") + } + if job == nil { + return errors.New("订单刷新任务不能为空") + } + if refresh == nil || marshal == nil || complete == nil { + return errors.New("订单刷新任务依赖未初始化") + } // result、err 保存订单刷新业务结果及错误。 - result, err := s.orders().Refresh(ctx, job.UserID, job.CookieID, job.FilterStatus) + result, err := refresh(ctx, job.UserID, job.CookieID, job.FilterStatus) if err != nil { - // completeErr 表示失败终态写入错误。 - if _, completeErr := s.orders().services.RefreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", err.Error()); completeErr != nil && s.Logger != nil { - s.Logger.Warn("写入订单刷新失败终态失败", "job_id", job.ID, "err", completeErr) + // completeErr 保存失败终态写入错误。 + completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", err.Error()) + if completeErr != nil { + return errors.Join(err, completeErr) } - return + return err } // resultJSON、marshalErr 保存具名刷新结果 JSON 及序列化错误。 - resultJSON, marshalErr := json.Marshal(result) + resultJSON, marshalErr := marshal(result) if marshalErr != nil { - _, _ = s.orders().services.RefreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", marshalErr.Error()) - return + // completeErr 保存序列化失败终态写入错误。 + completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", marshalErr.Error()) + if completeErr != nil { + return errors.Join(marshalErr, completeErr) + } + return marshalErr } - // completeErr 表示成功终态写入错误。 - if _, completeErr := s.orders().services.RefreshJobs.Complete(context.Background(), job.ID, token, "succeeded", string(resultJSON), ""); completeErr != nil && s.Logger != nil { - s.Logger.Warn("写入订单刷新成功终态失败", "job_id", job.ID, "err", completeErr) + // completeErr 保存成功终态写入错误。 + return completeOrderRefreshJob(ctx, complete, job.ID, token, "succeeded", string(resultJSON), "") +} + +// completeOrderRefreshJob 写入终态并把数据库错误或租约失配转换为可观测错误。 +func completeOrderRefreshJob(ctx context.Context, complete orderRefreshJobComplete, jobID, token, status, resultJSON, errorMessage string) error { + if ctx == nil { + return errors.New("订单刷新任务终态写入 Context 不能为空") } + if complete == nil { + return errors.New("订单刷新任务终态写入依赖未初始化") + } + // applied、err 保存终态写入是否命中当前租约及数据库错误。 + applied, err := complete(ctx, jobID, token, status, resultJSON, errorMessage) + if err != nil { + return fmt.Errorf("订单刷新任务终态写入失败: %w", err) + } + if !applied { + return fmt.Errorf("%w: job_id=%s", errOrderRefreshJobCompletionNotApplied, jobID) + } + return nil } // RunOrderRefreshRecovery 扫描并重新执行租约过期的订单刷新任务。 @@ -287,15 +352,34 @@ func (s *Server) recoverOrderRefreshJobsOnce(ctx context.Context) { for _, job := range jobs { // requeued、requeueErr 保存重新入队结果及错误。 requeued, requeueErr := s.orders().services.RefreshJobs.RequeueExpired(ctx, job.ID, time.Now().Unix()) - if requeueErr != nil || !requeued { + if requeueErr != nil { + if s.Logger != nil { + s.Logger.Warn("重新入队订单刷新任务失败", "job_id", job.ID, "err", requeueErr) + } + continue + } + if !requeued { + if s.Logger != nil { + s.Logger.Warn("重新入队订单刷新任务未生效", "job_id", job.ID) + } continue } // token 保存恢复 worker 的新租约令牌。 token := randomHex(16) // claimed、claimErr 保存恢复任务抢占结果及错误。 claimed, claimErr := s.orders().services.RefreshJobs.Claim(ctx, job.ID, token, time.Now().Add(orderRefreshJobLease).Unix()) - if claimErr == nil && claimed { - s.startOrderRefreshWorker(&job, token) + if claimErr != nil { + if s.Logger != nil { + s.Logger.Warn("抢占恢复订单刷新任务失败", "job_id", job.ID, "err", claimErr) + } + continue } + if !claimed { + if s.Logger != nil { + s.Logger.Warn("抢占恢复订单刷新任务未生效", "job_id", job.ID) + } + continue + } + s.startOrderRefreshWorker(&job, token) } } diff --git a/internal/server/order_refresh_job_lifecycle_test.go b/internal/server/order_refresh_job_lifecycle_test.go new file mode 100644 index 0000000..16ec19f --- /dev/null +++ b/internal/server/order_refresh_job_lifecycle_test.go @@ -0,0 +1,260 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "testing" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" +) + +// orderRefreshLifecycleContextKey 是生命周期测试专用的 Context 键类型,避免与生产或其他测试键冲突。 +type orderRefreshLifecycleContextKey struct{} + +// newOrderRefreshJobLifecycleFixture 创建生命周期测试共用的应用任务模型。 +func newOrderRefreshJobLifecycleFixture() *orderapp.RefreshJob { + return &orderapp.RefreshJob{ID: "refresh-lifecycle-job", UserID: 7, CookieID: "cookie-1", FilterStatus: "pending_ship"} +} + +// TestRunOrderRefreshJobWithSuccess 验证业务成功后会写入成功终态和序列化结果。 +func TestRunOrderRefreshJobWithSuccess(t *testing.T) { + // ctx 是本用例传递给业务和终态写入的生命周期上下文。 + ctx := context.WithValue(context.Background(), orderRefreshLifecycleContextKey{}, "lifecycle") + // job 是待执行的订单刷新任务。 + job := newOrderRefreshJobLifecycleFixture() + // result 是业务刷新返回的确定性结果。 + result := orderRefreshResponse{Message: "刷新完成", Summary: orderRefreshSummary{Total: 1}} + // completed 表示终态写入是否被调用。 + completed := false + // status 保存终态写入的目标状态。 + status := "" + // resultJSON 保存终态写入的序列化结果。 + resultJSON := "" + // refresh 是成功返回固定结果的业务回调。 + refresh := func(gotCtx context.Context, userID int64, cookieID, filterStatus string) (orderRefreshResponse, error) { + if gotCtx != ctx || userID != job.UserID || cookieID != job.CookieID || filterStatus != job.FilterStatus { + t.Fatalf("刷新回调参数不正确: ctx=%p user=%d cookie=%s status=%s", gotCtx, userID, cookieID, filterStatus) + } + return result, nil + } + // marshal 是使用标准 JSON 编码器的确定性序列化回调。 + marshal := func(value any) ([]byte, error) { return json.Marshal(value) } + // complete 是记录终态写入参数的成功回调。 + complete := func(gotCtx context.Context, jobID, token, gotStatus, gotResultJSON, errorMessage string) (bool, error) { + if gotCtx != ctx || jobID != job.ID || token != "token-1" || errorMessage != "" { + t.Fatalf("终态写入参数不正确: ctx=%p job=%s token=%s status=%s error=%s", gotCtx, jobID, token, gotStatus, errorMessage) + } + completed, status, resultJSON = true, gotStatus, gotResultJSON + return true, nil + } + + // err 保存 worker 执行错误。 + err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete) + if err != nil { + t.Fatalf("成功刷新不应返回错误: %v", err) + } + if !completed || status != "succeeded" || resultJSON == "" { + t.Fatalf("成功终态未写入: completed=%v status=%s result=%s", completed, status, resultJSON) + } +} + +// TestRunOrderRefreshJobWithBusinessFailure 验证业务错误会写入失败终态并原样返回。 +func TestRunOrderRefreshJobWithBusinessFailure(t *testing.T) { + // ctx 是本用例传递给业务和终态写入的上下文。 + ctx := context.Background() + // job 是待执行的订单刷新任务。 + job := newOrderRefreshJobLifecycleFixture() + // businessErr 是业务刷新失败的根因。 + businessErr := errors.New("订单平台请求失败") + // failedStatus 保存失败终态写入状态。 + failedStatus := "" + // failedMessage 保存失败终态写入的业务错误文本。 + failedMessage := "" + // refresh 是返回预置业务错误的刷新回调。 + refresh := func(context.Context, int64, string, string) (orderRefreshResponse, error) { + return orderRefreshResponse{}, businessErr + } + // marshal 是不会被业务失败路径调用的序列化回调。 + marshal := func(any) ([]byte, error) { + t.Fatal("业务失败不应尝试序列化成功结果") + return nil, nil + } + // complete 是记录失败终态的回调。 + complete := func(_ context.Context, jobID, token, status, resultJSON, errorMessage string) (bool, error) { + if jobID != job.ID || token != "token-1" || resultJSON != "{}" { + t.Fatalf("失败终态参数不正确: job=%s token=%s result=%s", jobID, token, resultJSON) + } + failedStatus, failedMessage = status, errorMessage + return true, nil + } + + // err 保存 worker 执行错误。 + err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete) + if !errors.Is(err, businessErr) || failedStatus != "failed" || failedMessage != businessErr.Error() { + t.Fatalf("业务失败终态不正确: err=%v status=%s message=%s", err, failedStatus, failedMessage) + } +} + +// TestRunOrderRefreshJobWithSerializationFailure 验证序列化失败会写入失败终态。 +func TestRunOrderRefreshJobWithSerializationFailure(t *testing.T) { + // ctx 是本用例传递给业务和终态写入的上下文。 + ctx := context.Background() + // job 是待执行的订单刷新任务。 + job := newOrderRefreshJobLifecycleFixture() + // marshalErr 是结果序列化失败的根因。 + marshalErr := errors.New("结果序列化失败") + // failedStatus 保存序列化失败后的终态状态。 + failedStatus := "" + // refresh 是返回固定成功结果的刷新回调。 + refresh := func(context.Context, int64, string, string) (orderRefreshResponse, error) { + return orderRefreshResponse{Message: "完成"}, nil + } + // marshal 是返回预置序列化错误的回调。 + marshal := func(any) ([]byte, error) { return nil, marshalErr } + // complete 是记录失败终态的回调。 + complete := func(_ context.Context, jobID, token, status, resultJSON, errorMessage string) (bool, error) { + if jobID != job.ID || token != "token-1" || resultJSON != "{}" || errorMessage != marshalErr.Error() { + t.Fatalf("序列化失败终态参数不正确: job=%s token=%s result=%s error=%s", jobID, token, resultJSON, errorMessage) + } + failedStatus = status + return true, nil + } + + // err 保存 worker 执行错误。 + err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete) + if !errors.Is(err, marshalErr) || failedStatus != "failed" { + t.Fatalf("序列化失败未正确收束: err=%v status=%s", err, failedStatus) + } +} + +// TestRunOrderRefreshJobWithCompletionFailure 验证终态数据库错误和租约失配不会被吞掉。 +func TestRunOrderRefreshJobWithCompletionFailure(t *testing.T) { + // ctx 是本用例传递给业务和终态写入的上下文。 + ctx := context.Background() + // job 是待执行的订单刷新任务。 + job := newOrderRefreshJobLifecycleFixture() + // writeErr 是终态持久化返回的数据库错误。 + writeErr := errors.New("数据库写入失败") + // refresh 是返回固定成功结果的刷新回调。 + refresh := func(context.Context, int64, string, string) (orderRefreshResponse, error) { + return orderRefreshResponse{Message: "完成"}, nil + } + // marshal 是使用标准 JSON 编码器的序列化回调。 + marshal := func(value any) ([]byte, error) { return json.Marshal(value) } + // completeWithError 是返回数据库错误的终态写入回调。 + completeWithError := func(context.Context, string, string, string, string, string) (bool, error) { + return false, writeErr + } + // err 保存数据库错误场景的 worker 执行错误。 + err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, completeWithError) + if !errors.Is(err, writeErr) { + t.Fatalf("终态数据库错误未返回: %v", err) + } + + // completeUnapplied 是返回租约未命中的终态写入回调。 + completeUnapplied := func(context.Context, string, string, string, string, string) (bool, error) { + return false, nil + } + // unappliedErr 保存租约未命中场景的 worker 执行错误。 + unappliedErr := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, completeUnapplied) + if !errors.Is(unappliedErr, errOrderRefreshJobCompletionNotApplied) { + t.Fatalf("终态未生效未转换为可观测错误: %v", unappliedErr) + } +} + +// TestRunOrderRefreshJobWithCancellation 验证取消后的业务和终态写入都继承同一个已取消 Context。 +func TestRunOrderRefreshJobWithCancellation(t *testing.T) { + // ctx、cancel 是 Server 生命周期取消信号及其触发函数。 + ctx, cancel := context.WithCancel(context.Background()) + cancel() + // job 是待执行的订单刷新任务。 + job := newOrderRefreshJobLifecycleFixture() + // completionCtx 保存终态写入收到的上下文。 + var completionCtx context.Context + // refresh 是确认业务收到取消信号的回调。 + refresh := func(gotCtx context.Context, _ int64, _, _ string) (orderRefreshResponse, error) { + if gotCtx != ctx || !errors.Is(gotCtx.Err(), context.Canceled) { + t.Fatalf("业务未继承取消 Context: ctx=%p err=%v", gotCtx, gotCtx.Err()) + } + return orderRefreshResponse{}, context.Canceled + } + // marshal 是不会被取消业务路径调用的序列化回调。 + marshal := func(any) ([]byte, error) { + t.Fatal("取消业务不应尝试序列化成功结果") + return nil, nil + } + // complete 是模拟数据库遵循 Context 取消的终态写入回调。 + complete := func(gotCtx context.Context, _ string, _ string, _ string, _ string, _ string) (bool, error) { + completionCtx = gotCtx + return false, gotCtx.Err() + } + + // err 保存取消场景的 worker 执行错误。 + err := runOrderRefreshJobWith(ctx, job, "token-1", refresh, marshal, complete) + if completionCtx != ctx || !errors.Is(err, context.Canceled) { + t.Fatalf("取消错误或 Context 未保留: ctx=%p completion=%p err=%v", ctx, completionCtx, err) + } +} + +// TestOrderRefreshWorkerUsesCanceledServerLifecycle 验证 Server 关闭后 worker 不会使用脱离生命周期的 Context 写终态。 +func TestOrderRefreshWorkerUsesCanceledServerLifecycle(t *testing.T) { + // srv、store、cleanup 保存测试服务、数据库和清理函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // lifecycleCtx、cancel 是已取消的 Server 生命周期上下文。 + lifecycleCtx, cancel := context.WithCancel(context.Background()) + cancel() + srv.lifecycleMu.Lock() + srv.lifecycleCtx = lifecycleCtx + srv.lifecycleMu.Unlock() + // admin、err 保存任务所属用户及查询错误。 + admin, err := store.Users.GetByUsername(context.Background(), "admin") + if err != nil { + t.Fatalf("读取管理员: %v", err) + } + // dbJob 保存数据库层待执行任务。 + dbJob := &db.OrderRefreshJob{ID: "refresh-canceled-lifecycle", UserID: admin.ID} + // err 保存创建任务错误。 + if err := store.OrderRefreshJobs.Create(context.Background(), dbJob); err != nil { + t.Fatalf("创建刷新任务: %v", err) + } + // token 是当前 worker 的租约令牌。 + token := "refresh-canceled-token" + // claimed、err 保存任务抢占结果及错误。 + claimed, err := store.OrderRefreshJobs.Claim(context.Background(), dbJob.ID, token, 9999999999) + if err != nil || !claimed { + t.Fatalf("抢占刷新任务: claimed=%v err=%v", claimed, err) + } + // job 是传给后台 worker 的应用层任务模型。 + job := &orderapp.RefreshJob{ID: dbJob.ID, UserID: dbJob.UserID} + srv.startOrderRefreshWorker(job, token) + srv.WaitForBackground() + // persisted、err 保存 worker 结束后的任务状态及查询错误。 + persisted, err := store.OrderRefreshJobs.Get(context.Background(), admin.ID, dbJob.ID) + if err != nil { + t.Fatalf("读取取消后的任务: %v", err) + } + if persisted.Status != "running" { + t.Fatalf("取消生命周期后不应使用后台 Context 覆盖租约状态: %+v", persisted) + } +} + +// TestStartBackgroundTaskResultTracksFailure 验证后台任务错误会进入 Server 任务状态。 +func TestStartBackgroundTaskResultTracksFailure(t *testing.T) { + // srv 是只装配任务注册表的最小 Server 生命周期实例。 + srv := &Server{taskRegistry: newTaskRegistry()} + // taskErr 是后台任务返回的确定性错误。 + taskErr := errors.New("后台任务失败") + // taskID 是登记后用于读取任务状态的进程内标识。 + taskID := srv.startBackgroundTaskResult("订单刷新测试任务", context.Background(), func() error { + return taskErr + }) + srv.WaitForBackground() + // snapshots 保存任务注册表返回的状态快照。 + snapshots := srv.taskRegistry.list() + if len(snapshots) != 1 || snapshots[0].ID != taskID || snapshots[0].State != taskStateFailed { + t.Fatalf("后台任务失败状态未记录: %+v", snapshots) + } +} diff --git a/internal/server/order_service.go b/internal/server/order_service.go index 0232128..c33142e 100644 --- a/internal/server/order_service.go +++ b/internal/server/order_service.go @@ -3,81 +3,98 @@ package server import ( "context" "errors" - "strings" - "time" + "log/slog" + "xianyu-go/internal/adapter" orderapp "xianyu-go/internal/application/orders" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/cookierefresh" - "xianyu-go/internal/xianyu/mtop" ) // serverOrderRuntimeAdapter 将 Server 的运行时能力适配为订单应用 Port。 // 适配器只存在于装配边界,订单应用服务本身不再依赖 *Server。 type serverOrderRuntimeAdapter struct { - // server 保存需要被适配的 Server 聚合对象。 - server *Server + // runtime 保存已下沉到 adapter 包的订单运行时端口。 + runtime *adapter.OrderRuntime } // newServerOrderRuntime 创建订单运行时 Port 的 Server 适配器。 -func newServerOrderRuntime(server *Server) serverOrderRuntimeAdapter { - return serverOrderRuntimeAdapter{server: server} +func newServerOrderRuntime(server *Server, reconciliation orderapp.ReconciliationRecorder) serverOrderRuntimeAdapter { + // hooks 保存 Server 运行时回调,避免适配器反向依赖 Server 包。 + hooks := adapter.OrderRuntimeHooks{} + if server != nil { + hooks = adapter.OrderRuntimeHooks{ + Client: server.mtopClient, + ClientAvailable: func() bool { return server.MTop != nil }, + AccountRunning: func(cookieID string) bool { + if server.Manager == nil { + return false + } + // _, running 保存账号运行实例是否存在。 + _, running := server.Manager.GetInstance(cookieID) + return running + }, + AutomationReady: func() bool { return server.Manager != nil && server.automation != nil }, + ManualFullDelivery: func(ctx context.Context, order *orderapp.Order) (int, error) { + if server.automation == nil { + return 0, errors.New("自动化中心未初始化") + } + return server.automation.ManualFullDelivery(ctx, adapter.OrderForAutomation(order)) + }, + UpdateRunningCookie: server.updateRunningCookie, + NotifyDelivery: server.notifyDelivery, + RecoverExpiredSession: server.recoverExpiredMTOPSession, + } + } + // logger 保存 Server 使用的日志器;适配器会在缺失时使用默认日志器。 + var logger = (*slog.Logger)(nil) + if server != nil { + logger = server.Logger + } + // runtime 保存已完成数据库与 Server 回调装配的订单运行时;零值 Server 只用于测试缺失依赖分支。 + var runtime *adapter.OrderRuntime + if server == nil { + runtime = adapter.NewOrderRuntime(nil, hooks, reconciliation, logger) + } else { + runtime = server.dependencies.NewOrderRuntime(hooks, reconciliation, logger) + } + return serverOrderRuntimeAdapter{runtime: runtime} } // AccountRunning 判断指定账号是否在线运行。 func (a serverOrderRuntimeAdapter) AccountRunning(cookieID string) bool { - if a.server == nil || a.server.Manager == nil { - return false - } - // running 表示账号是否已有运行中的实例。 - _, running := a.server.Manager.GetInstance(cookieID) - return running + return a.runtime != nil && a.runtime.AccountRunning(cookieID) } // AutomationReady 判断完整发货自动化依赖是否已装配。 func (a serverOrderRuntimeAdapter) AutomationReady() bool { - return a.server != nil && a.server.Manager != nil && a.server.automation != nil + return a.runtime != nil && a.runtime.AutomationReady() } // ManualFullDelivery 执行完整自动化发货。 func (a serverOrderRuntimeAdapter) ManualFullDelivery(ctx context.Context, order *orderapp.Order) (int, error) { - if a.server == nil || a.server.automation == nil { - return 0, errors.New("自动化中心未初始化") + if a.runtime == nil { + return 0, errors.New("订单运行时未初始化") } - return a.server.automation.ManualFullDelivery(ctx, orderForAutomation(order)) + return a.runtime.ManualFullDelivery(ctx, order) } // MTopAvailable 判断平台客户端是否已注入。 func (a serverOrderRuntimeAdapter) MTopAvailable() bool { - return a.server != nil && a.server.MTop != nil -} - -// mtopClient 返回订单流程使用的平台客户端。 -func (a serverOrderRuntimeAdapter) mtopClient() mtop.Client { - if a.server == nil { - return nil - } - return a.server.mtopClient() -} - -// consignWithCurrentCookie 使用当前账号凭证确认发货。 -func (a serverOrderRuntimeAdapter) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) { - return a.server.consignWithCurrentCookie(ctx, cookieID, orderID, userID) + return a.runtime != nil && a.runtime.MTopAvailable() } // 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, + if a.runtime == nil { + return orderapp.ConsignResult{Err: errors.New("订单运行时未初始化")} } + return a.runtime.ConfirmShipment(ctx, cookieID, orderID, userID) } // updateRunningCookie 同步运行时账号 Cookie。 func (a serverOrderRuntimeAdapter) updateRunningCookie(ctx context.Context, cookieID, value string) { - a.server.updateRunningCookie(ctx, cookieID, value) + if a.runtime != nil { + a.runtime.UpdateRunningCookie(ctx, cookieID, value) + } } // UpdateRunningCookie 将运行时账号 Cookie 能力暴露给手动发货应用 Port。 @@ -87,7 +104,9 @@ func (a serverOrderRuntimeAdapter) UpdateRunningCookie(ctx context.Context, cook // notifyDelivery 发送发货结果通知。 func (a serverOrderRuntimeAdapter) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) { - a.server.notifyDelivery(cookieID, buyerID, itemID, chatID, message) + if a.runtime != nil { + a.runtime.NotifyDelivery(cookieID, buyerID, itemID, chatID, message) + } } // NotifyDelivery 将发货通知能力暴露给手动发货应用 Port。 @@ -97,10 +116,10 @@ func (a serverOrderRuntimeAdapter) NotifyDelivery(cookieID, buyerID, itemID, cha // 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 { - return "", errors.New("订单补偿存储未初始化") + if a.runtime == nil { + return "", errors.New("订单运行时未初始化") } - return a.server.Store.Reconciliations.CreatePending(ctx, orderID, cookieID, kind, message) + return a.runtime.RecordOrderReconciliation(ctx, orderID, cookieID, kind, message) } // RecordReconciliation 将补偿记录能力暴露给手动发货应用 Port。 @@ -110,127 +129,61 @@ func (a serverOrderRuntimeAdapter) RecordReconciliation(ctx context.Context, ord // ReportPersistenceFailure 记录手动发货本地订单状态持久化失败。 func (a serverOrderRuntimeAdapter) ReportPersistenceFailure(orderID string, err error) { - if a.server == nil || a.server.Logger == nil || err == nil { - return + if a.runtime != nil { + a.runtime.ReportPersistenceFailure(orderID, err) } - a.server.Logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err) } // RecoverExpiredSession 处理订单刷新应用服务报告的平台会话过期。 func (a serverOrderRuntimeAdapter) RecoverExpiredSession(ctx context.Context, cookieID string, err error) bool { - return a.server.recoverExpiredMTOPSession(ctx, cookieID, err) + return a.runtime != nil && a.runtime.RecoverExpiredSession(ctx, cookieID, err) } // DetailAvailable 判断订单详情接口是否可用。 func (a serverOrderRuntimeAdapter) DetailAvailable() bool { - // ok 表示当前平台客户端是否实现详情接口。 - _, ok := a.mtopClient().(orderDetailMTop) - return ok + return a.runtime != nil && a.runtime.DetailAvailable() } // SoldAvailable 判断已售订单列表接口是否可用。 func (a serverOrderRuntimeAdapter) SoldAvailable() bool { - // ok 表示当前平台客户端是否实现订单列表接口。 - _, ok := a.mtopClient().(mtop.SoldOrderFetcher) - return ok + return a.runtime != nil && a.runtime.SoldAvailable() } // CredentialAvailable 判断平台请求视图是否包含可用 Cookie。 func (a serverOrderRuntimeAdapter) CredentialAvailable(detail *orderapp.PlatformRuntimeData) bool { - return detail != nil && strings.TrimSpace(detail.Value) != "" + return a.runtime != nil && a.runtime.CredentialAvailable(detail) } // FetchOrderDetail 调用平台详情接口并收集 Cookie 会话变化。 func (a serverOrderRuntimeAdapter) FetchOrderDetail(ctx context.Context, detail *orderapp.PlatformRuntimeData, orderID string) (orderapp.RefreshDetailFetchResult, error) { - // fetcher、ok 保存详情接口适配器及其实现状态。 - fetcher, ok := a.mtopClient().(orderDetailMTop) - if !ok { - return orderapp.RefreshDetailFetchResult{}, orderapp.ErrRefreshDetailUnsupported + if a.runtime == nil { + return orderapp.RefreshDetailFetchResult{}, errors.New("订单运行时未初始化") } - if detail == nil { - return orderapp.RefreshDetailFetchResult{}, errors.New("订单详情请求缺少账号凭证") - } - // requestCtx、session 保存带 Cookie 快照的请求上下文和会话。 - requestCtx, session := withMTopCookieSnapshot(ctx, cookieDetailForOrderPlatform(detail)) - // result、err 保存平台详情响应及错误。 - result, err := fetcher.FetchOrderDetail(requestCtx, detail.Value, orderID) - if err != nil { - return orderapp.RefreshDetailFetchResult{CookieUpdate: a.refreshCookieUpdate(detail, session)}, err - } - if result == nil { - return orderapp.RefreshDetailFetchResult{CookieUpdate: a.refreshCookieUpdate(detail, session)}, errors.New("订单详情接口未返回结果") - } - return orderapp.RefreshDetailFetchResult{Detail: &orderapp.RefreshDetail{Quantity: result.Quantity, SpecName: result.SpecName, SpecValue: result.SpecValue, OrderStatus: result.OrderStatus, Amount: result.Amount, UpdatedCookies: result.UpdatedCookies}, CookieUpdate: a.refreshCookieUpdate(detail, session)}, nil + return a.runtime.FetchOrderDetail(ctx, detail, orderID) } // FetchSoldOrders 调用平台已售订单接口并收集 Cookie 会话变化。 func (a serverOrderRuntimeAdapter) FetchSoldOrders(ctx context.Context, detail *orderapp.PlatformRuntimeData) (orderapp.RefreshSoldFetchResult, error) { - // fetcher、ok 保存订单列表接口适配器及其实现状态。 - fetcher, ok := a.mtopClient().(mtop.SoldOrderFetcher) - if !ok { - return orderapp.RefreshSoldFetchResult{}, errors.New("当前 MTop 客户端不支持订单列表发现") + if a.runtime == nil { + return orderapp.RefreshSoldFetchResult{}, errors.New("订单运行时未初始化") } - if detail == nil { - return orderapp.RefreshSoldFetchResult{}, errors.New("订单列表请求缺少账号凭证") - } - // requestCtx、session 保存带 Cookie 快照的请求上下文和会话。 - requestCtx, session := withMTopCookieSnapshot(ctx, cookieDetailForOrderPlatform(detail)) - // orders 保存跨分页累积的平台订单。 - orders := make([]orderapp.RefreshSoldOrder, 0) - // pageNumber 是当前请求的订单列表页码。 - for pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ { - // page、err 保存当前订单列表页及错误。 - page, err := fetcher.FetchSoldOrdersPage(requestCtx, detail.Value, pageNumber, 30) - if err != nil { - return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: a.refreshCookieUpdate(detail, session)}, err - } - // remote 是当前平台订单列表项。 - for _, remote := range page.Items { - orders = append(orders, orderapp.RefreshSoldOrder{OrderID: remote.OrderID, ItemID: remote.ItemID, BuyerID: remote.BuyerID, OrderStatus: orderapp.NormalizeOrderStatus(remote.OrderStatus), Quantity: remote.Quantity, Amount: remote.Amount, ReceiverName: remote.ReceiverName, ReceiverPhone: remote.ReceiverPhone, ReceiverAddr: remote.ReceiverAddr, ReceiverCity: remote.ReceiverCity, IsBargain: remote.IsBargain}) - } - if !page.NextPage || len(page.Items) == 0 { - break - } - } - return orderapp.RefreshSoldFetchResult{Orders: orders, CookieUpdate: a.refreshCookieUpdate(detail, session)}, nil -} - -// refreshCookieUpdate 将平台 CookieSession 转换为应用层 Cookie 更新模型。 -func (a serverOrderRuntimeAdapter) refreshCookieUpdate(detail *orderapp.PlatformRuntimeData, session *mtop.CookieSession) orderapp.RefreshCookieUpdate { - if detail == nil || session == nil { - return orderapp.RefreshCookieUpdate{} - } - // value、snapshot、changed 保存会话当前 Cookie、快照和变化状态。 - value, snapshot, changed := session.State() - if snapshot == nil { - return orderapp.RefreshCookieUpdate{Value: value, Changed: changed, Handled: false} - } - // metadata 保存包含完整 Cookie 快照的元数据。 - metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot) - return orderapp.RefreshCookieUpdate{Value: value, MetadataJSON: metadata, Changed: changed, Handled: true} + return a.runtime.FetchSoldOrders(ctx, detail) } // PersistCookieSession 在凭证锁内保存应用层 Cookie 更新。 func (a serverOrderRuntimeAdapter) PersistCookieSession(ctx context.Context, detail *orderapp.PlatformRuntimeData, update orderapp.RefreshCookieUpdate) (string, bool, bool, error) { - if detail == nil || !update.Handled { - return "", false, false, nil + if a.runtime == nil { + if detail == nil { + return update.Value, false, update.Handled, errors.New("订单运行时未初始化") + } + return update.Value, update.Value != detail.Value, update.Handled, errors.New("订单运行时未初始化") } - if !update.Changed { - return detail.Value, false, true, nil - } - if a.server == nil || a.server.Store == nil || a.server.Store.Cookies == nil { - return update.Value, update.Value != detail.Value, true, errors.New("账号 Cookie 存储未初始化") - } - // err 保存账号续期 Cookie 写入错误。 - if err := a.server.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, update.Value, update.MetadataJSON, time.Now().Unix()); err != nil { - return update.Value, update.Value != detail.Value, true, err - } - return update.Value, update.Value != detail.Value, true, nil + return a.runtime.PersistCookieSession(ctx, detail, update) } // IsSessionExpired 判断平台错误是否为会话过期。 func (a serverOrderRuntimeAdapter) IsSessionExpired(err error) bool { - return mtop.IsSessionExpiredErr(err) + return a.runtime != nil && a.runtime.IsSessionExpired(err) } // orderHTTPAdapter 将 HTTP 请求模型和兼容响应模型适配到应用层订单服务。 @@ -246,11 +199,12 @@ type orderHTTPAdapter struct { func (a *orderHTTPAdapter) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderSingleRefreshResponse, error) { // result、err 保存应用层单订单刷新结果和错误。 result, err := a.services.Refresh.RefreshSingle(ctx, userID, orderID) + err = adapter.NormalizeOrderError(err) if errors.Is(err, orderapp.ErrNotFound) { - return orderSingleRefreshResponse{}, db.ErrNotFound + return orderSingleRefreshResponse{}, orderapp.ErrNotFound } if errors.Is(err, orderapp.ErrForbidden) { - return orderSingleRefreshResponse{}, db.ErrForbidden + return orderSingleRefreshResponse{}, orderapp.ErrForbidden } if errors.Is(err, orderapp.ErrRefreshDetailUnsupported) { return orderSingleRefreshResponse{}, errOrderDetailUnsupported @@ -268,8 +222,9 @@ func (a *orderHTTPAdapter) RefreshSingle(ctx context.Context, userID int64, orde func (a *orderHTTPAdapter) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderRefreshResponse, error) { // result、err 保存应用层批量刷新结果和错误。 result, err := a.services.Refresh.Refresh(ctx, userID, cookieID, status) + err = adapter.NormalizeOrderError(err) if errors.Is(err, orderapp.ErrForbidden) { - return orderRefreshResponse{}, db.ErrForbidden + return orderRefreshResponse{}, orderapp.ErrForbidden } if err != nil { return orderRefreshResponse{}, err @@ -399,7 +354,7 @@ type orderListResult struct { // orderDTOFromRow 把数据库订单列表行转换为稳定的订单响应视图。 func orderDTOFromRow(row orderapp.OrderRow) orderDTO { // status 保存状态,供当前处理流程使用 - status := db.NormalizeOrderStatus(row.OrderStatus) + status := orderapp.NormalizeOrderStatus(row.OrderStatus) return orderDTO{ OrderID: row.OrderID, ItemID: row.ItemID, ItemTitle: row.ItemTitle, ItemImage: itemImageFromDetail(row.ItemDetail), BuyerID: row.BuyerID, @@ -421,7 +376,7 @@ func orderDTOFromOrder(order *orderapp.Order, item *orderapp.ItemInfo) orderDTO itemImage = itemImageFromDetail(item.ItemDetail) } // status 保存状态,供当前处理流程使用 - status := db.NormalizeOrderStatus(order.OrderStatus) + status := orderapp.NormalizeOrderStatus(order.OrderStatus) return orderDTO{ OrderID: order.OrderID, ItemID: order.ItemID, ItemTitle: itemTitle, ItemImage: itemImage, BuyerID: order.BuyerID, SpecName: order.SpecName, SpecValue: order.SpecValue, @@ -433,36 +388,6 @@ func orderDTOFromOrder(order *orderapp.Order, item *orderapp.ItemInfo) orderDTO } } -// orderForAutomation 将订单应用实体转换为尚未迁移完成的自动化中心数据库实体。 -func orderForAutomation(order *orderapp.Order) *db.Order { - if order == nil { - return nil - } - return &db.Order{ - OrderID: order.OrderID, ItemID: order.ItemID, BuyerID: order.BuyerID, - SpecName: order.SpecName, SpecValue: order.SpecValue, Quantity: order.Quantity, - Amount: order.Amount, OrderStatus: order.OrderStatus, CookieID: order.CookieID, - IsBargain: order.IsBargain, ReceiverName: order.ReceiverName, - ReceiverPhone: order.ReceiverPhone, ReceiverAddr: order.ReceiverAddress, - ReceiverCity: order.ReceiverCity, Version: order.Version, ChatID: order.ChatID, - SystemShipped: order.SystemShipped, PaidAt: order.PaidAt, ShippedAt: order.ShippedAt, - CompletedAt: order.CompletedAt, BuyerReviewedAt: order.BuyerReviewedAt, - LastReviewRequestAt: order.LastReviewRequestAt, ReviewRequestCount: order.ReviewRequestCount, - CreatedAt: order.CreatedAt, UpdatedAt: order.UpdatedAt, - } -} - -// cookieDetailForOrderPlatform 将订单应用层平台运行视图转换为共享 Server 会话辅助函数所需的兼容详情。 -func cookieDetailForOrderPlatform(data *orderapp.PlatformRuntimeData) *db.CookieDetail { - if data == nil { - return nil - } - return &db.CookieDetail{ - ID: data.ID, UserID: data.UserID, Value: data.Value, - MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser, - } -} - // orderDetailResult 返回订单详情的统一响应视图。 type orderDetailResult struct { // Order 是已经完成商品信息补全的订单视图。 @@ -476,8 +401,9 @@ func (a *orderHTTPAdapter) List(ctx context.Context, query orderListQuery) (orde UserID: query.UserID, CookieID: query.CookieID, Status: query.Status, Search: query.Search, Page: query.Page, PageSize: query.PageSize, }) + err = adapter.NormalizeOrderError(err) if errors.Is(err, orderapp.ErrForbidden) { - return orderListResult{}, db.ErrForbidden + return orderListResult{}, orderapp.ErrForbidden } if err != nil { return orderListResult{}, err @@ -498,11 +424,12 @@ func (a *orderHTTPAdapter) List(ctx context.Context, query orderListQuery) (orde func (a *orderHTTPAdapter) Get(ctx context.Context, userID int64, orderID string) (*orderapp.Order, error) { // order、err 保存应用层订单详情结果及错误。 order, err := a.services.Detail.Get(ctx, userID, orderID) + err = adapter.NormalizeOrderError(err) if errors.Is(err, orderapp.ErrNotFound) { - return nil, db.ErrNotFound + return nil, orderapp.ErrNotFound } if errors.Is(err, orderapp.ErrForbidden) { - return nil, db.ErrForbidden + return nil, orderapp.ErrForbidden } return order, err } @@ -511,11 +438,12 @@ func (a *orderHTTPAdapter) Get(ctx context.Context, userID int64, orderID string func (a *orderHTTPAdapter) GetView(ctx context.Context, userID int64, orderID string) (orderDetailResult, error) { // result、err 保存应用层详情结果及错误。 result, err := a.services.Detail.GetView(ctx, userID, orderID) + err = adapter.NormalizeOrderError(err) if errors.Is(err, orderapp.ErrNotFound) { - return orderDetailResult{}, db.ErrNotFound + return orderDetailResult{}, orderapp.ErrNotFound } if errors.Is(err, orderapp.ErrForbidden) { - return orderDetailResult{}, db.ErrForbidden + return orderDetailResult{}, orderapp.ErrForbidden } if err != nil { return orderDetailResult{}, err @@ -527,11 +455,12 @@ func (a *orderHTTPAdapter) GetView(ctx context.Context, userID int64, orderID st func (a *orderHTTPAdapter) Delete(ctx context.Context, userID int64, orderID string) error { // err 保存应用层订单删除错误。 err := a.services.Delete.Delete(ctx, userID, orderID) + err = adapter.NormalizeOrderError(err) if errors.Is(err, orderapp.ErrForbidden) { - return db.ErrForbidden + return orderapp.ErrForbidden } if errors.Is(err, orderapp.ErrNotFound) { - return db.ErrNotFound + return orderapp.ErrNotFound } return err } @@ -586,11 +515,12 @@ func (a *orderHTTPAdapter) Update(ctx context.Context, userID int64, orderID str if errors.As(err, &validationErr) { return newOrderBadRequest(validationErr.Error()) } + err = adapter.NormalizeOrderError(err) if errors.Is(err, orderapp.ErrForbidden) { - return db.ErrForbidden + return orderapp.ErrForbidden } if errors.Is(err, orderapp.ErrNotFound) { - return db.ErrNotFound + return orderapp.ErrNotFound } return err } diff --git a/internal/server/order_service_reconciliation_test.go b/internal/server/order_service_reconciliation_test.go new file mode 100644 index 0000000..3009be2 --- /dev/null +++ b/internal/server/order_service_reconciliation_test.go @@ -0,0 +1,79 @@ +package server + +import ( + "context" + "errors" + "testing" + + orderapp "xianyu-go/internal/application/orders" +) + +// serverOrderReconciliationRecorderFake 是 Server 订单运行时适配器测试使用的补偿 Port。 +type serverOrderReconciliationRecorderFake struct { + // recordID 保存测试补偿写入成功时返回的记录标识。 + recordID string + // recordErr 保存测试补偿写入失败时返回的错误。 + recordErr error + // orderID、cookieID、kind、message 保存最近一次收到的业务字段。 + orderID string + cookieID string + kind string + message string +} + +// RecordReconciliation 记录 Server 适配器传入的补偿写入请求。 +func (f *serverOrderReconciliationRecorderFake) RecordReconciliation(_ context.Context, orderID, cookieID, kind, message string) (string, error) { + f.orderID, f.cookieID, f.kind, f.message = orderID, cookieID, kind, message + return f.recordID, f.recordErr +} + +// TestServerOrderRuntimeAdapterReconciliationPort 验证 Server 只通过订单应用 Port 转发补偿写入。 +func TestServerOrderRuntimeAdapterReconciliationPort(t *testing.T) { + // expectedErr 保存底层补偿写入失败时应原样返回的错误。 + expectedErr := errors.New("补偿数据库写入失败") + // testCases 保存补偿 Port 成功、缺失和持久化失败三种 Server 边界场景。 + testCases := []struct { + // name 是当前边界场景的测试名称。 + name string + // recorder 是当前场景注入的补偿应用 Port。 + recorder *serverOrderReconciliationRecorderFake + // wantID 是当前场景预期返回的补偿记录标识。 + wantID string + // wantErr 是当前场景预期返回的错误。 + wantErr error + // wantErrText 是无法共享错误实例时用于校验的错误文本。 + wantErrText string + }{ + {name: "成功", recorder: &serverOrderReconciliationRecorderFake{recordID: "reconcile-1"}, wantID: "reconcile-1"}, + {name: "缺失依赖", wantErrText: "订单补偿存储未初始化"}, + {name: "持久化错误", recorder: &serverOrderReconciliationRecorderFake{recordErr: expectedErr}, wantErr: expectedErr}, + } + // testCase 表示当前遍历的 Server 补偿边界场景。 + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + // recorder 是避免把空指针伪装成非空接口的补偿应用 Port。 + var recorder orderapp.ReconciliationRecorder + if testCase.recorder != nil { + recorder = testCase.recorder + } + // runtime 保存当前场景构造的 Server 订单运行时适配器。 + runtime := newServerOrderRuntime(nil, recorder) + // recordID、recordErr 保存适配器转发后的补偿写入结果。 + recordID, recordErr := runtime.RecordOrderReconciliation(context.Background(), "order-1", "cookie-1", "manual_status_ship", "本地订单写入失败") + // errMatches 表示当前返回错误是否符合场景预期;缺失依赖场景只校验错误文本。 + errMatches := recordErr == nil || testCase.wantErrText != "" + if testCase.wantErr != nil { + errMatches = errors.Is(recordErr, testCase.wantErr) + } + if testCase.wantErrText != "" { + errMatches = recordErr != nil && recordErr.Error() == testCase.wantErrText + } + if recordID != testCase.wantID || !errMatches { + t.Fatalf("补偿 Port 边界结果异常: id=%q err=%v wantID=%q wantErr=%v", recordID, recordErr, testCase.wantID, testCase.wantErr) + } + if testCase.recorder != nil && (testCase.recorder.orderID != "order-1" || testCase.recorder.cookieID != "cookie-1" || testCase.recorder.kind != "manual_status_ship" || testCase.recorder.message != "本地订单写入失败") { + t.Fatalf("补偿字段未完整转发: %+v", testCase.recorder) + } + }) + } +} diff --git a/internal/server/ownership_helpers.go b/internal/server/ownership_helpers.go index 4e6f1b9..ca50fac 100644 --- a/internal/server/ownership_helpers.go +++ b/internal/server/ownership_helpers.go @@ -1,49 +1,39 @@ package server import ( + "errors" "net/http" + accountapp "xianyu-go/internal/application/account" "xianyu-go/internal/auth" - "xianyu-go/internal/db" ) +// authSess 从请求上下文读取经过认证中间件注入的会话。 +func authSess(r *http.Request) *auth.SessionIdentity { + return auth.IdentityFromContext(r.Context()) +} + // requireCookieOwner 负责require登录凭证所有者相关处理。 -func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cookieID string) (*db.CookieDetail, bool) { +func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cookieID string) (accountapp.AccountSummary, bool) { // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) if sess == nil { writeErr(w, http.StatusUnauthorized, "未授权访问") - return nil, false + return accountapp.AccountSummary{}, false } // d、err 保存d、err,供当前处理流程使用 d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cookieID) if err != nil { writeErr(w, http.StatusNotFound, "账号不存在") - return nil, false + return accountapp.AccountSummary{}, false } if d.UserID != sess.UserID { writeErr(w, http.StatusForbidden, "无权限操作该账号") - return nil, false + return accountapp.AccountSummary{}, false } return d, true } -// requireCookieSecretOwner 校验账号归属后读取登录设置所需的完整详情,仅供需要密码的管理流程使用。 -func (s *Server) requireCookieSecretOwner(w http.ResponseWriter, r *http.Request, cookieID string) (*db.CookieDetail, bool) { - // ownerOK 表示当前会话是否通过账号所有权校验。 - _, ownerOK := s.requireCookieOwner(w, r, cookieID) - if !ownerOK { - return nil, false - } - // detail 是登录设置流程需要的用户名、密码和浏览器显示设置。 - detail, err := s.Store.Cookies.GetDetails(r.Context(), cookieID) - if err != nil || detail == nil { - writeErr(w, http.StatusNotFound, "账号不存在") - return nil, false - } - return detail, true -} - // requireCookieOwnership 校验当前会话是否拥有账号,只读取账号所有权元数据,不解密凭证。 func (s *Server) requireCookieOwnership(w http.ResponseWriter, r *http.Request, cookieID string) bool { // sess 是当前请求经过认证中间件注入的会话。 @@ -52,62 +42,19 @@ func (s *Server) requireCookieOwnership(w http.ResponseWriter, r *http.Request, writeErr(w, http.StatusUnauthorized, "未授权访问") return false } - // owned 表示当前用户是否直接拥有该账号。 - owned, ownedErr := s.Store.Cookies.ExistsOwned(r.Context(), sess.UserID, cookieID) - if ownedErr != nil { + // service 提供按用户过滤的非敏感所有权判断,避免 Server 直接访问账号表。 + service := s.accountSummaryApplication() + if service == nil { writeErr(w, http.StatusNotFound, "账号不存在") return false } - if owned { + // ownershipErr 保存应用服务返回的账号归属结果。 + if ownershipErr := service.RequireOwnership(r.Context(), sess.UserID, cookieID); ownershipErr == nil { return true - } - // ownerID 用于区分账号不存在和账号属于其他用户,保持原有 404/403 响应语义。 - ownerID, ownerErr := s.Store.Cookies.GetOwnerID(r.Context(), cookieID) - if ownerErr != nil { - writeErr(w, http.StatusNotFound, "账号不存在") - return false - } - if ownerID != sess.UserID { + } else if errors.Is(ownershipErr, accountapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权限操作该账号") return false } - return true -} - -// requireCardOwner 校验当前会话是否拥有卡券组。 -func (s *Server) requireCardOwner(w http.ResponseWriter, r *http.Request, cardID int64) (*db.CardFull, bool) { - // sess 是当前请求经过认证中间件注入的会话。 - sess := auth.SessionFromContext(r.Context()) - if sess == nil { - writeErr(w, http.StatusUnauthorized, "未授权访问") - return nil, false - } - // card 和 err 分别表示卡券组记录及其查询错误。 - card, err := s.Store.Cards.Get(r.Context(), cardID) - if err != nil { - writeErr(w, http.StatusNotFound, "卡券不存在") - return nil, false - } - if card.UserID != sess.UserID { - writeErr(w, http.StatusForbidden, "无权操作该卡密组") - return nil, false - } - return card, true -} - -// requireChannelOwner 校验当前会话是否拥有通知渠道。 -func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, channelID int64) bool { - // sess 是当前请求经过认证中间件注入的会话。 - sess := auth.SessionFromContext(r.Context()) - if sess == nil { - writeErr(w, http.StatusUnauthorized, "未授权访问") - return false - } - // exists 和 err 表示通知渠道归属查询结果及错误。 - exists, err := s.Store.Notifications.OwnsChannel(r.Context(), channelID, sess.UserID) - if err != nil || !exists { - writeErr(w, http.StatusForbidden, "无权操作该通知渠道") - return false - } - return true + writeErr(w, http.StatusNotFound, "账号不存在") + return false } diff --git a/internal/server/ownership_secret_scope_test.go b/internal/server/ownership_secret_scope_test.go new file mode 100644 index 0000000..1f4fc63 --- /dev/null +++ b/internal/server/ownership_secret_scope_test.go @@ -0,0 +1,35 @@ +package server + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" +) + +// TestRequireCookieOwnerSkipsLoginSecret 验证账号所有权校验不依赖登录密码密文。 +func TestRequireCookieOwnerSkipsLoginSecret(t *testing.T) { + // srv、store 和 cleanup 分别保存测试服务器、数据库和资源清理函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // ctx 是本测试共用的数据库上下文。 + ctx := context.Background() + // _, updateErr 表示将登录密码替换为损坏密文的数据库操作结果;所有权摘要不应读取该字段。 + if _, updateErr := store.DB.ExecContext(ctx, + `UPDATE cookies SET password=? WHERE id=?`, "not-a-password-ciphertext", "acc1"); updateErr != nil { + t.Fatalf("损坏登录密码密文失败: %v", updateErr) + } + // request 是携带默认测试用户会话的所有权请求。 + request := httptest.NewRequest(http.MethodGet, "/cookies/acc1", nil) + request = request.WithContext(auth.WithSession(request.Context(), &db.Session{UserID: 1})) + // recorder 捕获所有权辅助函数可能写入的 HTTP 错误响应。 + recorder := httptest.NewRecorder() + // detail、owned 表示所有权校验返回的非敏感应用摘要及校验结果。 + detail, owned := srv.requireCookieOwner(recorder, request, "acc1") + if !owned || detail.ID != "acc1" || detail.UserID != 1 { + t.Fatalf("detail=%+v owned=%v status=%d body=%s", detail, owned, recorder.Code, recorder.Body.String()) + } +} diff --git a/internal/server/parser_test.go b/internal/server/parser_test.go index ee814c0..1f771c5 100644 --- a/internal/server/parser_test.go +++ b/internal/server/parser_test.go @@ -316,28 +316,10 @@ func TestPublishBatchHelpers(t *testing.T) { } } -// TestParsePublishCardActions 负责TestParse发布卡密动作列表相关处理。 -func TestParsePublishCardActions(t *testing.T) { - // actions、parseErr 保存actions、parseErr,供当前处理流程使用 - actions, parseErr := parsePublishCardActions("101:1:0; 102:2:3") - if parseErr != "" { - t.Fatalf("parsePublishCardActions: %s", parseErr) - } - if len(actions) != 2 { - t.Fatalf("actions=%+v", actions) - } - if actions[0].CardID != 101 || actions[0].DeliveryCount != 1 || actions[0].DelaySeconds != 0 { - t.Fatalf("actions[0]=%+v", actions[0]) - } - if actions[1].CardID != 102 || actions[1].DeliveryCount != 2 || actions[1].DelaySeconds != 3 { - t.Fatalf("actions[1]=%+v", actions[1]) - } - if // parseErr 保存parseErr,供当前处理流程使用 - _, parseErr := parsePublishCardActions("101:0"); parseErr == "" { - t.Fatal("每件份数为0时应返回格式错误") - } - if // got 保存got,供当前处理流程使用 - got := normalizePublishHeader("付款后发送的卡密"); got != "paid_delivery_contents" { +// TestNormalizePublishCardHeader 验证批量发布卡密字段的历史表头兼容映射。 +func TestNormalizePublishCardHeader(t *testing.T) { + // got 表示历史中文表头归一化后的字段名。 + if got := normalizePublishHeader("付款后发送的卡密"); got != "paid_delivery_contents" { t.Fatalf("normalizePublishHeader=%q", got) } } @@ -361,23 +343,6 @@ func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) { } } -// TestParsePublishAutomationSupportsMultipleCards 负责TestParse发布自动化SupportsMultiple卡密列表相关处理。 -func TestParsePublishAutomationSupportsMultipleCards(t *testing.T) { - // cfg 保存cfg,供当前处理流程使用 - cfg := parsePublishAutomation(map[string]any{ - "paid_delivery_enabled": "是", - "paid_delivery_contents": "101:1:0;102:2:0", - "review_gift_enabled": "true", - "review_gift_contents": "201:1", - }) - if !cfg.PaidDelivery.Enabled || len(cfg.PaidDelivery.Actions) != 2 { - t.Fatalf("paid delivery=%+v", cfg.PaidDelivery) - } - if !cfg.ReviewGift.Enabled || len(cfg.ReviewGift.Actions) != 1 { - t.Fatalf("review gift=%+v", cfg.ReviewGift) - } -} - // TestPublicIPValidation 负责TestPublicIPValidation相关处理。 func TestPublicIPValidation(t *testing.T) { // raw 表示当前遍历过程中的原始 diff --git a/internal/server/platform_runtime.go b/internal/server/platform_runtime.go index 7227e40..10b4275 100644 --- a/internal/server/platform_runtime.go +++ b/internal/server/platform_runtime.go @@ -2,50 +2,43 @@ package server import ( "context" + "errors" - "xianyu-go/internal/db" + accountapp "xianyu-go/internal/application/account" ) // loadCookiePlatformDetail 读取平台请求所需的最小 Cookie 状态,并转换为 Server 内部已有的会话适配模型。 -func (s *Server) loadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) { - // platformData 是 repository 返回的不含登录密码的平台运行视图。 - platformData, err := s.Store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) +func (s *Server) loadCookiePlatformDetail(ctx context.Context, cookieID string) (*accountapp.CredentialDetail, error) { + if s == nil { + return nil, errors.New("平台凭证读取服务未初始化") + } + // repository 提供不读取登录密码的平台凭证窄视图;SQL 和解密逻辑由 adapter 负责。 + repository := s.accountLoginRepositoryForServer() + if repository == nil { + return nil, errors.New("平台凭证 repository 未初始化") + } + // platformData 是应用 Port 返回的不含登录密码的平台运行视图。 + platformData, err := repository.LoadPlatformDetail(ctx, cookieID) if err != nil { return nil, err } - // detail 是仅供 Cookie Session 适配器使用的浅层模型,不包含用户名、密码或账号设置。 - detail := &db.CookieDetail{ - ID: platformData.ID, - UserID: platformData.UserID, - Value: platformData.Value, - MetadataJSON: platformData.MetadataJSON, - } - return detail, nil + return platformData, nil } // loadCookieSummaryDetail 读取账号非敏感摘要并转换为 Server 内部的兼容模型。 -func (s *Server) loadCookieSummaryDetail(ctx context.Context, userID int64, cookieID string) (*db.CookieDetail, error) { - // summary 是按当前用户与账号 ID 联合过滤得到的非敏感摘要。 - summary, err := s.Store.Cookies.GetSummaryOwned(ctx, userID, cookieID) - if err != nil { - return nil, err +func (s *Server) loadCookieSummaryDetail(ctx context.Context, userID int64, cookieID string) (accountapp.AccountSummary, error) { + if s == nil { + return accountapp.AccountSummary{}, errors.New("账号摘要读取服务未初始化") } - // detail 是只包含摘要字段的兼容模型,不携带任何 Cookie、metadata 或登录密码。 - detail := &db.CookieDetail{ - ID: summary.ID, - UserID: summary.UserID, - AutoConfirm: summary.AutoConfirm, - Remark: summary.Remark, - PauseDuration: summary.PauseDuration, - PausedUntil: summary.PausedUntil, - Username: summary.Username, - ShowBrowser: summary.ShowBrowser, - Nickname: summary.Nickname, - AvatarURL: summary.AvatarURL, - LastRefreshAt: summary.LastRefreshAt, - LoginMethod: summary.LoginMethod, - LastLoginAt: summary.LastLoginAt, - CreatedAt: summary.CreatedAt, + // service 提供按用户和账号联合过滤的非敏感摘要;Server 不直接访问账号表。 + service := s.accountSummaryApplication() + if service == nil { + return accountapp.AccountSummary{}, errors.New("账号摘要服务未初始化") } - return detail, nil + // summary、queryErr 保存应用服务返回的非敏感摘要及查询错误。 + summary, queryErr := service.GetOwnedSummary(ctx, userID, cookieID) + if queryErr != nil { + return accountapp.AccountSummary{}, queryErr + } + return summary, nil } diff --git a/internal/server/platform_runtime_boundary_test.go b/internal/server/platform_runtime_boundary_test.go new file mode 100644 index 0000000..70e763d --- /dev/null +++ b/internal/server/platform_runtime_boundary_test.go @@ -0,0 +1,36 @@ +package server + +import ( + "context" + "testing" + + "xianyu-go/internal/adapter" + accountapp "xianyu-go/internal/application/account" +) + +// TestLoadCookiePlatformDetailRequiresCredentialPort 验证平台运行时读取不会在缺少应用 Port 时直接访问 Store。 +func TestLoadCookiePlatformDetailRequiresCredentialPort(t *testing.T) { + // srv 是仅装配空账号登录服务的测试 Server,模拟凭证适配器缺失场景。 + srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}} + // loadErr 保存缺少凭证 Port 时的平台视图读取错误。 + _, loadErr := srv.loadCookiePlatformDetail(context.Background(), "cid") + if loadErr == nil { + t.Fatal("缺少凭证 Port 时不应继续读取平台运行视图") + } +} + +// TestPersistMTopCookieSessionRequiresCredentialPort 验证 MTOP Cookie 会话写回通过凭证 Port 而非直接访问 Store。 +func TestPersistMTopCookieSessionRequiresCredentialPort(t *testing.T) { + // srv 是仅装配空账号登录服务的测试 Server,模拟写回适配器缺失场景。 + srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}} + // detail 是不含登录密码的兼容平台凭证模型。 + detail := &accountapp.CredentialDetail{ID: "cid", Value: "sid=old", MetadataJSON: "{}"} + // ctx、session 保存发生权威 Cookie 变化的 MTOP 会话。 + ctx, session := adapter.WithFlatCookieSession(context.Background(), detail.Value) + session.ReplaceSnapshot([]adapter.BrowserCookie{{Name: "sid", Value: "new", Domain: ".goofish.com", Path: "/"}}) + // value、changed、handled、persistErr 保存会话写回结果及其错误阶段。 + _, changed, handled, persistErr := srv.persistMTopCookieSessionLocked(ctx, detail, session) + if !changed || !handled || persistErr == nil { + t.Fatalf("缺少凭证 Port 时应报告写回错误: changed=%v handled=%v err=%v", changed, handled, persistErr) + } +} diff --git a/internal/server/platform_runtime_scope_test.go b/internal/server/platform_runtime_scope_test.go index e5cb1f2..51d0c05 100644 --- a/internal/server/platform_runtime_scope_test.go +++ b/internal/server/platform_runtime_scope_test.go @@ -29,7 +29,7 @@ func TestServerPlatformRuntimeDetailSkipsLoginSecrets(t *testing.T) { } // summaryDetail 是 ownership 和资料刷新使用的非敏感摘要适配模型。 summaryDetail, summaryErr := srv.loadCookieSummaryDetail(ctx, ownerID, "acc1") - if summaryErr != nil || summaryDetail == nil || summaryDetail.ID != "acc1" || summaryDetail.UserID != ownerID { + if summaryErr != nil || summaryDetail.ID != "acc1" || summaryDetail.UserID != ownerID { t.Fatalf("summary detail=%+v err=%v", summaryDetail, summaryErr) } } diff --git a/internal/server/publish_batch_run_test.go b/internal/server/publish_batch_run_test.go index ce37d26..04ee63e 100644 --- a/internal/server/publish_batch_run_test.go +++ b/internal/server/publish_batch_run_test.go @@ -15,6 +15,8 @@ import ( "testing" "time" + "xianyu-go/internal/adapter" + itemapp "xianyu-go/internal/application/items" "xianyu-go/internal/automation" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/mtop" @@ -28,12 +30,12 @@ func TestFinalPublishBatchStatus(t *testing.T) { // cases 保存cases,供当前处理流程使用 cases := []struct { name string - in db.ItemPublishBatch + in itemapp.BatchInfo want string }{ - {name: "completed", in: db.ItemPublishBatch{SuccessCount: 2}, want: "completed"}, - {name: "failed", in: db.ItemPublishBatch{FailedCount: 2}, want: "failed"}, - {name: "partially failed", in: db.ItemPublishBatch{SuccessCount: 1, FailedCount: 1}, want: "partially_failed"}, + {name: "completed", in: itemapp.BatchInfo{SuccessCount: 2}, want: "completed"}, + {name: "failed", in: itemapp.BatchInfo{FailedCount: 2}, want: "failed"}, + {name: "partially failed", in: itemapp.BatchInfo{SuccessCount: 1, FailedCount: 1}, want: "partially_failed"}, } // tt 表示当前遍历过程中的tt for _, tt := range cases { @@ -180,7 +182,7 @@ func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie } // TestRunItemPublishBatch_FailureMarksRowFailed 启动批次后,mock mtop 对发布请求返回失败, -// 验证 runItemPublishBatch/publishBatchRow 把行标记为 failed。 +// 验证应用层批量 worker 把远端发布失败的行标记为 failed。 // TestRunItemPublishBatch_FailureMarksRowFailed 负责Test运行商品发布批次FailureMarksRow失败相关处理。 func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 @@ -546,8 +548,20 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test remoteCalls++ return nil, context.Canceled })) - if // err 保存err,供当前处理流程使用 - err := srv.publishBatchRow(ctx, admin.ID, client, rows[0], "worker-2"); err != nil { + // port 将测试平台客户端接入批量远端应用端口;已保存远端结果时不会再次发起平台请求。 + port := adapter.NewItemBatchPublishPort(store, func() mtop.Client { return client }, srv.Logger, srv.updateRunningCookie, func(callCtx context.Context, cookieID string, callErr error) { + srv.recoverExpiredMTOPSession(callCtx, cookieID, callErr) + }, readBatchImageFile, downloadImageURL) + // localService 保存本地商品和批次成功检查点收口能力。 + localService, serviceErr := srv.newBatchLocalPublishService() + if serviceErr != nil { + t.Fatal(serviceErr) + } + // applicationRow 保存恢复测试所需的非敏感批次明细模型。 + applicationRow := itemapp.BatchRow{ID: rows[0].ID, BatchID: rows[0].BatchID, RowNo: rows[0].RowNo, CookieID: rows[0].CookieID, Title: rows[0].Title, Description: rows[0].Description, Price: rows[0].Price, OriginalPrice: rows[0].OriginalPrice, Quantity: rows[0].Quantity, PostageMode: rows[0].PostageMode, Postage: rows[0].Postage, ImagesJSON: rows[0].ImagesJSON, CategoryJSON: rows[0].CategoryJSON, AutomationJSON: rows[0].AutomationJSON, RawJSON: rows[0].RawJSON, ItemID: rows[0].ItemID, ItemURL: rows[0].ItemURL, Status: rows[0].Status, ErrorMessage: rows[0].ErrorMessage, FailureKind: rows[0].FailureKind, WorkerToken: rows[0].WorkerToken, CreatedAt: rows[0].CreatedAt, UpdatedAt: rows[0].UpdatedAt} + // err 保存应用层批量发布适配器的恢复结果。 + err = (serverBatchPublisher{server: srv, remotePort: port, localService: localService}).PublishRow(ctx, admin.ID, applicationRow, "worker-2") + if err != nil { t.Fatalf("resume local persistence: %v", err) } if remoteCalls != 0 { @@ -622,9 +636,9 @@ func TestCreatePublishAutomationRules(t *testing.T) { // automationJSON 保存自动化JSON,供当前处理流程使用 automationJSON := `{"paid_delivery":{"enabled":true,"actions":[{"card_id":` + itoa(cardID) + `,"delivery_count":1,"delay_seconds":23}]}}` if // err 保存err,供当前处理流程使用 - err := srv.createPublishAutomationRules(ctx, admin.ID, db.ItemPublishBatchRow{ + err := srv.createPublishAutomationRules(ctx, admin.ID, itemapp.BatchRow{ CookieID: "acc1", Title: "商品A", AutomationJSON: automationJSON, - }, &mtop.PublishItemResult{ItemID: "published-delay-item", Title: "商品A"}); err != nil { + }, &itemapp.BatchPublishResult{ItemID: "published-delay-item", Title: "商品A"}); err != nil { t.Fatal(err) } // rules、err 保存rules、err,供当前处理流程使用 diff --git a/internal/server/publish_batch_test.go b/internal/server/publish_batch_test.go index d92b03a..95032ee 100644 --- a/internal/server/publish_batch_test.go +++ b/internal/server/publish_batch_test.go @@ -654,6 +654,90 @@ func TestDownloadItemPublishBatchResultNotFound(t *testing.T) { } } +// TestDownloadItemPublishBatchResultExportsRows 验证批次结果下载通过应用服务读取并保持 CSV 兼容格式。 +func TestDownloadItemPublishBatchResultExportsRows(t *testing.T) { + // srv、store、cleanup 保存 HTTP 测试服务器、数据库和清理函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // ctx 保存本测试共用的非取消上下文。 + ctx := context.Background() + // admin 保存下载批次的当前用户。 + admin, adminErr := store.Users.GetByUsername(ctx, "admin") + if adminErr != nil { + t.Fatalf("读取测试管理员失败: %v", adminErr) + } + // batchID 保存本次结果下载批次标识。 + batchID := "download-success" + // createErr 保存测试批次及明细写入结果。 + createErr := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ + ID: batchID, UserID: admin.ID, Filename: "items.csv", Status: "completed", + }, []db.ItemPublishBatchRow{{ + RowNo: 2, CookieID: "acc1", Title: "商品A", Price: "12.50", Quantity: 3, + CategoryJSON: `{"cat_id":"5001","cat_name":"虚拟商品"}`, Status: "completed", + ItemID: "item-1", ItemURL: "https://example/item-1", + }}) + if createErr != nil { + t.Fatalf("创建下载测试批次失败: %v", createErr) + } + // h 保存带应用服务装配的 HTTP 路由。 + h := srv.Router() + // cookie 保存管理员登录会话。 + cookie := loginHelper(t, h) + // req 保存结果下载请求。 + req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID+"/result.csv", nil) + req.AddCookie(cookie) + // rec 保存结果下载响应。 + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("下载结果状态=%d body=%s", rec.Code, rec.Body.String()) + } + // body 保存导出的 CSV 内容,包含 UTF-8 BOM、表头和业务明细。 + body := rec.Body.String() + if !strings.HasPrefix(body, "\xEF\xBB\xBF") || !strings.Contains(body, "行号") || !strings.Contains(body, "商品A") || !strings.Contains(body, "item-1") { + t.Fatalf("导出 CSV 内容异常: %q", body) + } +} + +// TestDownloadItemPublishBatchResultHidesOtherUserBatch 验证结果下载不会泄露其他用户的批次存在性。 +func TestDownloadItemPublishBatchResultHidesOtherUserBatch(t *testing.T) { + // srv、store、cleanup 保存 HTTP 测试服务器、数据库和清理函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // ctx 保存本测试共用的非取消上下文。 + ctx := context.Background() + // created 保存其他用户创建结果。 + created, createUserErr := store.Users.Create(ctx, "download-other", "download-other@example.com", "pw") + if createUserErr != nil || !created { + t.Fatalf("创建其他用户失败: created=%v err=%v", created, createUserErr) + } + // other 保存其他用户的数据库身份。 + other, otherErr := store.Users.GetByUsername(ctx, "download-other") + if otherErr != nil { + t.Fatalf("读取其他用户失败: %v", otherErr) + } + // createBatchErr 保存其他用户批次写入结果。 + createBatchErr := store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ + ID: "download-other-batch", UserID: other.ID, Filename: "items.csv", Status: "completed", + }, []db.ItemPublishBatchRow{{RowNo: 2, Title: "不应泄露", Status: "completed"}}) + if createBatchErr != nil { + t.Fatalf("创建其他用户批次失败: %v", createBatchErr) + } + // h 保存结果下载路由。 + h := srv.Router() + // cookie 保存当前管理员的登录会话。 + cookie := loginHelper(t, h) + // req 保存越权结果下载请求。 + req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/download-other-batch/result.csv", nil) + req.AddCookie(cookie) + // rec 保存越权响应。 + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound { + t.Fatalf("越权下载应隐藏批次并返回 404,got %d body=%s", rec.Code, rec.Body.String()) + } +} + // TestSafeCSVCellPreventsSpreadsheetFormulaExecution 负责TestSafeCSVCellPreventsSpreadsheetFormulaExecution相关处理。 func TestSafeCSVCellPreventsSpreadsheetFormulaExecution(t *testing.T) { // input 表示当前遍历过程中的input diff --git a/internal/server/qrlogin_handlers.go b/internal/server/qrlogin_handlers.go index 370c700..0896fdd 100644 --- a/internal/server/qrlogin_handlers.go +++ b/internal/server/qrlogin_handlers.go @@ -10,7 +10,6 @@ import ( "github.com/go-chi/chi/v5" "xianyu-go/internal/auth" - "xianyu-go/internal/xianyu/cookierefresh" ) // qrLoginGenerateTimeout 保存qr登录GenerateTimeout,供当前处理流程使用 @@ -298,23 +297,3 @@ func qrString(result map[string]any, key string) string { value, _ := result[key].(string) return strings.TrimSpace(value) } - -// qrCookieSnapshot 负责qr登录凭证Snapshot相关处理。 -func qrCookieSnapshot(result map[string]any) ([]cookierefresh.BrowserCookie, bool) { - // raw、ok 保存raw、ok,供当前处理流程使用 - raw, ok := result["cookie_snapshot"] - if !ok { - return nil, false - } - // snapshot、ok 保存snapshot、ok,供当前处理流程使用 - snapshot, ok := raw.([]cookierefresh.BrowserCookie) - if !ok || snapshot == nil { - return nil, false - } - // normalized 保存normalized,供当前处理流程使用 - normalized := cookierefresh.NormalizeSnapshot(snapshot) - if normalized == nil { - normalized = []cookierefresh.BrowserCookie{} - } - return normalized, true -} diff --git a/internal/server/qrlogin_keyword_test.go b/internal/server/qrlogin_keyword_test.go index 07e911e..e453d96 100644 --- a/internal/server/qrlogin_keyword_test.go +++ b/internal/server/qrlogin_keyword_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "xianyu-go/internal/adapter" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/cookierefresh" ) @@ -285,7 +286,7 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) { }, }} if // snapshot、ok 保存snapshot、ok,供当前处理流程使用 - snapshot, ok := qrCookieSnapshot(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 { + snapshot, ok := adapter.CookieSnapshotsFromResult(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 { t.Fatalf("测试扫码 Cookie 快照异常: ok=%v snapshot=%+v", ok, snapshot) } ownQRSession(t, srv, store, "s1") diff --git a/internal/server/run_test.go b/internal/server/run_test.go index bc5750f..dc52565 100644 --- a/internal/server/run_test.go +++ b/internal/server/run_test.go @@ -7,6 +7,9 @@ import ( "net/http" "testing" "time" + + "xianyu-go/internal/adapter" + "xianyu-go/internal/auth" ) // freeAddr 获取一个空闲 TCP 端口(立即释放,供测试绑定)。 @@ -122,18 +125,25 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) { // TestNewRejectsMissingRequiredDependencies 确保 HTTP 服务构造阶段拒绝缺失核心依赖。 func TestNewRejectsMissingRequiredDependencies(t *testing.T) { - // err 是缺少 Store 时的构造校验错误。 - if _, err := New(nil, nil, false, "", ":0", nil, nil, nil); err == nil { - t.Fatal("缺少 db.Store 时应返回构造错误") + // err 是缺少基础设施容器时的构造校验错误。 + if _, err := New(nil, nil, nil, "", ":0", nil, nil, nil); err == nil { + t.Fatal("缺少基础设施容器时应返回构造错误") } // srv 是用于提供合法 Store 的测试服务;cleanup 负责释放测试数据库。 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() if srv == nil { t.Fatal("测试服务不应为空") } + // dependencies 保存缺少 Manager 校验时复用的基础设施容器。 + dependencies, dependencyErr := adapter.NewDependencies(store) + if dependencyErr != nil { + t.Fatalf("NewDependencies: %v", dependencyErr) + } + // authentication 保存构造校验需要的会话中间件依赖。 + authentication := &auth.Service{Store: store} // err 是缺少 Manager 时的构造校验错误。 - if _, err := New(srv.Store, nil, false, "", ":0", nil, nil, nil); err == nil { + if _, err := New(dependencies, authentication, nil, "", ":0", nil, nil, nil); err == nil { t.Fatal("缺少 account.Manager 时应返回构造错误") } } diff --git a/internal/server/server.go b/internal/server/server.go index 2c12239..1e84023 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1,5 +1,5 @@ // Package server 实现 HTTP API 服务(chi 路由)。 -// 复用 internal/auth 中间件、internal/db.Store、internal/account.Manager。 +// 复用 internal/auth 中间件、adapter 装配依赖和 internal/account.Manager。 // 端点按分组组织在同一 package 的多个 handler 文件中。 package server @@ -20,26 +20,19 @@ import ( "github.com/go-chi/chi/v5/middleware" "xianyu-go/internal/account" + "xianyu-go/internal/adapter" "xianyu-go/internal/auth" "xianyu-go/internal/automation" "xianyu-go/internal/chat" - "xianyu-go/internal/db" "xianyu-go/internal/logging" "xianyu-go/internal/notify" "xianyu-go/internal/reconciliation" appversion "xianyu-go/internal/version" "xianyu-go/internal/webui" - "xianyu-go/internal/xianyu/mtop" - "xianyu-go/internal/xianyu/qrlogin" - xrenew "xianyu-go/internal/xianyu/renew" ) // qrLoginService 保存qr登录Service,供当前处理流程使用 -type qrLoginService interface { - GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error) - GetSessionStatus(sessionID string) map[string]any - CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) -} +type qrLoginService = adapter.QRLoginService // qrLoginPersistence 保存qr登录Persistence,供当前处理流程使用 type qrLoginPersistence struct { @@ -64,33 +57,37 @@ type publishBatchWorker struct { // ServerOption 是 Server 构造阶段应用可选依赖的配置函数。 type ServerOption func(*Server) +// databaseHealth 定义健康检查需要的最小数据库连通性能力。 +type databaseHealth interface { + // Ping 在调用方 Context 内探测数据库连接是否可用。 + Ping(context.Context) error +} + // Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入, // 不再允许外部直接改字段,避免运行时被替换成 nil。 // Server 保存Server,供当前处理流程使用 type Server struct { - Store *db.Store - Auth *auth.Service - Manager *account.Manager - automation *automation.Center - notifier *notify.Notifier - chat *chat.Service - MTop mtop.Client - CookieRenew xrenew.Service - QRLogin qrLoginService - Logger *slog.Logger - WebDir string // 前端静态资源目录(含 index.html) - Addr string + // dependencies 提供数据库和平台适配器工厂;底层 Store 不进入 Server 业务字段。 + dependencies *adapter.Dependencies + Auth *auth.Service + Manager *account.Manager + automation *automation.Center + notifier *notify.Notifier + chat *chat.Service + MTop adapter.MTOPClient + CookieRenew adapter.LongLoginClient + QRLogin qrLoginService + Logger *slog.Logger + WebDir string // 前端静态资源目录(含 index.html) + Addr string // applications 保存统一装配的应用服务实例。 applications *applicationServices // reconciliation 负责恢复外部发货成功但本地订单状态未完成的记录。 reconciliation *reconciliation.Service // transactionRepository 提供统一事务执行所需的最小持久化能力。 - transactionRepository transactionRepository - // itemSpecCacheMu 保护商品多规格探测缓存。 - itemSpecCacheMu sync.Mutex - // itemSpecCache 保存短期商品多规格探测结果,减少重复远端请求。 - itemSpecCache map[string]itemSpecCacheEntry - + transactionRepository *adapter.TransactionRepository + // databaseHealth 提供健康检查所需的数据库探测能力,避免 handler 直接触碰 SQL 连接。 + databaseHealth databaseHealth publishMu sync.Mutex publishCancels map[string]publishBatchWorker orderRefreshMu sync.Mutex @@ -98,7 +95,10 @@ type Server struct { workerMu sync.Mutex workerCount int workersDone chan struct{} - backgroundWG sync.WaitGroup + // backgroundMu 保护 Server 后台任务计数与完成信号,避免关闭等待创建不可取消的等待 goroutine。 + backgroundMu sync.Mutex + backgroundCount int + backgroundDone chan struct{} // taskRegistryMu 保护后台任务注册表的惰性初始化,避免测试构造的零值 Server 产生数据竞争。 taskRegistryMu sync.Mutex // taskRegistry 保存 Server 自有后台任务的生命周期状态,不持久化业务数据或敏感凭证。 @@ -133,9 +133,12 @@ func WithChatService(service *chat.Service) ServerOption { // New 构造并校验 HTTP 服务所需依赖。autoCenter/notifier 由调用方完成创建后注入 // (创建顺序:adapter → manager → automation → notifier → server)。 // New 负责New相关处理。 -func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) { - if store == nil { - return nil, fmt.Errorf("server 依赖 db.Store 不能为空") +func New(dependencies *adapter.Dependencies, authentication *auth.Service, manager *account.Manager, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) { + if dependencies == nil { + return nil, fmt.Errorf("server 依赖基础设施容器不能为空") + } + if authentication == nil { + return nil, fmt.Errorf("server 依赖认证服务不能为空") } if manager == nil { return nil, fmt.Errorf("server 依赖 account.Manager 不能为空") @@ -143,21 +146,19 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st if logger == nil { logger = logging.NewLogger(os.Stdout, "text") } - // qrMgr 是二维码登录流程使用的默认会话管理器。 - qrMgr := qrlogin.NewManager(logger) // server 是完成依赖装配、等待应用服务初始化后的 HTTP 服务实例。 server := &Server{ - Store: store, - Auth: &auth.Service{Store: store, Logger: logger, Secure: secure}, - Manager: manager, - automation: autoCenter, - notifier: notifier, - MTop: mtop.NewClient(), - CookieRenew: xrenew.Service{}, - QRLogin: qrMgr, - Logger: logger, - WebDir: webDir, - Addr: addr, + dependencies: dependencies, + Auth: authentication, + Manager: manager, + automation: autoCenter, + notifier: notifier, + MTop: adapter.NewMTOPClient(), + CookieRenew: adapter.NewLongLoginClient(), + QRLogin: adapter.NewQRLoginService(logger), + Logger: logger, + WebDir: webDir, + Addr: addr, publishCancels: make(map[string]publishBatchWorker), orderRefreshCancels: make(map[string]orderRefreshWorker), @@ -166,8 +167,8 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st qrPersisted: make(map[string]qrLoginPersistence), qrOwners: make(map[string]qrLoginOwner), loginLimiter: newLoginFailureLimiter(), - itemSpecCache: make(map[string]itemSpecCacheEntry), taskRegistry: newTaskRegistry(), + backgroundDone: closedSignal(), } // option 表示当前遍历过程中的option for _, option := range options { @@ -177,24 +178,25 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st } } server.applications = newApplicationServices(server) - server.transactionRepository = newStoreTransactionRepository(store) - server.reconciliation = reconciliation.New(store, logger) + server.transactionRepository = dependencies.NewTransactionRepository() + server.databaseHealth = dependencies.NewDatabaseHealth() + server.reconciliation = dependencies.NewReconciliationService(logger) return server, nil } // mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。 -func (s *Server) mtopClient() mtop.Client { +func (s *Server) mtopClient() adapter.MTOPClient { if s.MTop != nil { return s.MTop } - return mtop.NewClient() + return adapter.NewMTOPClient() } // recoverExpiredMTOPSession 是 HTTP/API 入口的统一 Session 失效出口。 // 各调用点必须先保存响应 Cookie 并释放账号凭证锁,再进入续期,避免锁反转。 // recoverExpiredMTOPSession 负责recoverExpiredMTOP会话相关处理。 func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string, err error) bool { - if !mtop.IsSessionExpiredErr(err) { + if !adapter.IsSessionExpiredError(err) { return false } if s.Logger != nil { @@ -442,7 +444,7 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) { // ctx、cancel 保存ctx、cancel,供当前处理流程使用 ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() - if s.Store == nil || s.Store.DB == nil || s.Store.DB.PingContext(ctx) != nil { + if s.databaseHealth == nil || s.databaseHealth.Ping(ctx) != nil { writeJSON(w, http.StatusServiceUnavailable, healthResponse{Status: "degraded", Database: "unavailable"}) return } @@ -566,7 +568,7 @@ func (s *Server) Stop(ctx context.Context) error { if httpDone != nil && !waitForSignal(ctx, httpDone) { return ctx.Err() } - if !waitForWaitGroup(ctx, &s.backgroundWG) || !s.waitForWorkersContext(ctx) { + if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) { return ctx.Err() } return nil @@ -594,7 +596,7 @@ func (s *Server) Stop(ctx context.Context) error { if httpDone != nil && !waitForSignal(ctx, httpDone) { return ctx.Err() } - if !waitForWaitGroup(ctx, &s.backgroundWG) || !s.waitForWorkersContext(ctx) { + if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) { return ctx.Err() } return shutdownErr @@ -614,7 +616,7 @@ func (s *Server) WaitForBackground() { if s == nil { return } - s.backgroundWG.Wait() + _ = s.waitForBackgroundContext(context.Background()) s.waitForWorkers(10 * time.Second) } @@ -633,34 +635,88 @@ func (s *Server) lifecycleContext() context.Context { return s.lifecycleCtx } -// startBackgroundTask 登记并启动一个受 Server 生命周期管理的后台任务。 -// 调用方负责在任务函数内部响应上下文取消;WaitForBackground 会等待任务退出。 -// startBackgroundTask 负责开始Background任务相关处理。 -func (s *Server) startBackgroundTask(name string, task func()) string { - return s.startBackgroundTaskContext(name, s.lifecycleContext(), task) -} - // startBackgroundTaskContext 登记并启动带显式 Context 的 Server 后台任务。 // 返回值是可供管理端查询的任务 ID;任务完成、取消或超时后会保留有限历史。 func (s *Server) startBackgroundTaskContext(name string, ctx context.Context, task func()) string { + return s.startBackgroundTaskResult(name, ctx, func() error { + if task != nil { + task() + } + return nil + }) +} + +// startBackgroundTaskResult 登记并启动可返回错误的 Server 后台任务。 +// 任务错误会进入任务注册表;调用方仍需自行处理敏感错误日志和取消语义。 +func (s *Server) startBackgroundTaskResult(name string, ctx context.Context, task func() error) string { // taskID、complete 记录任务状态并提供一次性收束回调。 taskID, complete := s.taskRegistryForServer().start(name, ctx) - s.backgroundWG.Add(1) + s.beginBackgroundTask() // #nosec G118 -- 任务由调用方提供的 Server 生命周期控制。 go func() { - defer s.backgroundWG.Done() - defer complete(nil) + defer s.finishBackgroundTask() + // taskErr 保存后台任务函数返回的可观测错误。 + var taskErr error + defer func() { complete(taskErr) }() if task == nil { if s.Logger != nil { s.Logger.Warn("跳过空后台任务", "task", name) } return } - task() + taskErr = task() }() return taskID } +// beginBackgroundTask 登记一个由 Server 负责等待的后台任务,并刷新零到一任务转换信号。 +func (s *Server) beginBackgroundTask() { + if s == nil { + return + } + s.backgroundMu.Lock() + defer s.backgroundMu.Unlock() + if s.backgroundCount == 0 { + s.backgroundDone = make(chan struct{}) + } + s.backgroundCount++ +} + +// finishBackgroundTask 标记一个后台任务退出,并在计数归零时关闭完成信号。 +func (s *Server) finishBackgroundTask() { + if s == nil { + return + } + s.backgroundMu.Lock() + defer s.backgroundMu.Unlock() + if s.backgroundCount <= 0 { + return + } + s.backgroundCount-- + if s.backgroundCount == 0 && s.backgroundDone != nil { + close(s.backgroundDone) + } +} + +// waitForBackgroundContext 等待已登记后台任务退出;超时只结束当前等待,不创建游离等待 goroutine。 +func (s *Server) waitForBackgroundContext(ctx context.Context) bool { + if s == nil { + return true + } + if ctx == nil { + ctx = context.Background() + } + s.backgroundMu.Lock() + // done 是当前后台任务批次归零时关闭的完成信号。 + done := s.backgroundDone + if done == nil { + done = closedSignal() + s.backgroundDone = done + } + s.backgroundMu.Unlock() + return waitForSignal(ctx, done) +} + // StartOrderReconciliationRecovery 启动受 Server 生命周期管理的订单补偿扫描器。 func (s *Server) StartOrderReconciliationRecovery(ctx context.Context) string { if s == nil || s.reconciliation == nil { @@ -745,14 +801,3 @@ func waitForSignal(ctx context.Context, signal <-chan struct{}) bool { return false } } - -// waitForWaitGroup 在关闭上下文取消或 WaitGroup 清空时返回,避免无界阻塞。 -func waitForWaitGroup(ctx context.Context, group *sync.WaitGroup) bool { - // done 是 WaitGroup 清空后的完成信号。 - done := make(chan struct{}) - go func() { - group.Wait() - close(done) - }() - return waitForSignal(ctx, done) -} diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 0bb4375..d32c3ef 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -11,6 +11,8 @@ import ( "testing" "xianyu-go/internal/account" + "xianyu-go/internal/adapter" + "xianyu-go/internal/auth" "xianyu-go/internal/automation" "xianyu-go/internal/chat" "xianyu-go/internal/db" @@ -36,7 +38,15 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer // mgr 是使用空处理器的测试账号管理器。 mgr := account.NewManager(store, noopHandler{}, nil) // srv 是未启用聊天服务的基础测试 HTTP 服务。 - srv, err := New(store, mgr, false, "", ":0", nil, nil, nil) + // dependencies 保存测试 Server 使用的基础设施工厂,避免 Server 直接持有 Store。 + dependencies, dependencyErr := adapter.NewDependencies(store) + if dependencyErr != nil { + t.Fatalf("NewDependencies: %v", dependencyErr) + } + // authentication 保存测试 HTTP 会话中间件需要的认证服务。 + authentication := &auth.Service{Store: store} + // srv、err 保存测试 HTTP 服务构造结果及失败原因。 + srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil) if err != nil { t.Fatalf("New: %v", err) } @@ -85,7 +95,15 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) { // mgr 是未初始化测试使用的空处理器账号管理器。 mgr := account.NewManager(store, noopHandler{}, nil) // srv 是未初始化测试使用的 HTTP 服务实例。 - srv, err := New(store, mgr, false, "", ":0", nil, nil, nil) + // dependencies 保存未初始化测试 Server 使用的基础设施工厂。 + dependencies, dependencyErr := adapter.NewDependencies(store) + if dependencyErr != nil { + t.Fatalf("NewDependencies: %v", dependencyErr) + } + // authentication 保存未初始化数据库上的会话中间件依赖。 + authentication := &auth.Service{Store: store} + // srv、err 保存未初始化测试服务构造结果及失败原因。 + srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil) if err != nil { t.Fatalf("New: %v", err) } diff --git a/internal/server/settings_extra_test.go b/internal/server/settings_extra_test.go index 843748d..bb69317 100644 --- a/internal/server/settings_extra_test.go +++ b/internal/server/settings_extra_test.go @@ -96,7 +96,7 @@ func TestListAIModelsBadJSON(t *testing.T) { // TestListAIModelsEmptyBaseURL 空地址使用默认并失败(默认阿里云地址不可达或返回非 2xx)。 func TestListAIModelsEmptyBaseURL(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // 注入一个返回错误状态码的本地 server。 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -104,7 +104,7 @@ func TestListAIModelsEmptyBaseURL(t *testing.T) { })) defer ts.Close() // 设置系统设置 ai_api_url 指向该 server。 - srv.Store.Settings.Set(context.Background(), "ai_api_url", ts.URL) + store.Settings.Set(context.Background(), "ai_api_url", ts.URL) // h 保存h,供当前处理流程使用 h := srv.Router() @@ -150,7 +150,7 @@ func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) { defer logging.Level.Set(slog.LevelInfo) // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // h 保存h,供当前处理流程使用 h := srv.Router() @@ -181,7 +181,7 @@ func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) { t.Fatalf("runtime log level=%v want debug", got) } // saved、err 保存saved、err,供当前处理流程使用 - saved, err := srv.Store.Settings.Get(context.Background(), "log_level") + saved, err := store.Settings.Get(context.Background(), "log_level") if err != nil || saved != "debug" { t.Fatalf("saved log_level=%q err=%v", saved, err) } @@ -190,12 +190,12 @@ func TestSetLogLevelValidatesAndAppliesRuntimeLevel(t *testing.T) { // TestSystemSettingsRequireAdmin 负责Test系统设置RequireAdmin相关处理。 func TestSystemSettingsRequireAdmin(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // h 保存h,供当前处理流程使用 h := srv.Router() if // err 保存err,供当前处理流程使用 - _, err := srv.Store.Users.Create(context.Background(), "user-settings", "user-settings@example.com", "pw"); err != nil { + _, err := store.Users.Create(context.Background(), "user-settings", "user-settings@example.com", "pw"); err != nil { t.Fatalf("create user: %v", err) } @@ -237,7 +237,7 @@ func TestSystemSettingsRequireAdmin(t *testing.T) { // TestBulkSystemSettingsAreAtomic 负责TestBulk系统设置AreAtomic相关处理。 func TestBulkSystemSettingsAreAtomic(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // h 保存h,供当前处理流程使用 h := srv.Router() @@ -254,7 +254,7 @@ func TestBulkSystemSettingsAreAtomic(t *testing.T) { t.Fatalf("status=%d body=%s", badRec.Code, badRec.Body.String()) } if // value 保存值,供当前处理流程使用 - value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value == "red" { + value, _ := store.Settings.Get(context.Background(), "theme_color"); value == "red" { t.Fatal("invalid bulk request partially saved theme_color") } @@ -268,11 +268,11 @@ func TestBulkSystemSettingsAreAtomic(t *testing.T) { t.Fatalf("status=%d body=%s", goodRec.Code, goodRec.Body.String()) } if // value 保存值,供当前处理流程使用 - value, _ := srv.Store.Settings.Get(context.Background(), "theme_color"); value != "blue" { + value, _ := store.Settings.Get(context.Background(), "theme_color"); value != "blue" { t.Fatalf("theme_color=%q", value) } if // value 保存值,供当前处理流程使用 - value, _ := srv.Store.Settings.Get(context.Background(), "renewal_log_retention_days"); value != "15" { + value, _ := store.Settings.Get(context.Background(), "renewal_log_retention_days"); value != "15" { t.Fatalf("retention=%q", value) } } diff --git a/internal/server/settings_handlers.go b/internal/server/settings_handlers.go index d8f4c63..3d83e63 100644 --- a/internal/server/settings_handlers.go +++ b/internal/server/settings_handlers.go @@ -1,27 +1,19 @@ package server import ( - "context" "encoding/json" "errors" "fmt" - "io" "net/http" - "sort" "strings" - "time" "github.com/go-chi/chi/v5" + settingsapp "xianyu-go/internal/application/settings" "xianyu-go/internal/auth" - "xianyu-go/internal/db" "xianyu-go/internal/logging" - "xianyu-go/internal/netguard" ) -// maxOpenAIModelsResponseBytes 保存maxOpenAI模型列表响应Bytes,供当前处理流程使用 -const maxOpenAIModelsResponseBytes = 4 << 20 - // systemSettingSecretChangeRequest 是 HTTP 层接收的敏感设置变更命令。 type systemSettingSecretChangeRequest struct { // Action 是 retain、replace 或 clear。 @@ -30,11 +22,6 @@ type systemSettingSecretChangeRequest struct { Value string `json:"value,omitempty"` } -// authSess 从上下文取会话。 -func authSess(r *http.Request) *db.Session { - return auth.SessionFromContext(r.Context()) -} - // mountSettingsReal 系统设置端点(管理员专用)。public 单独挂载在顶层。 func (s *Server) mountSettingsReal(r chi.Router) { r.Group(func(r chi.Router) { @@ -58,7 +45,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) { // values 保存普通设置值。 values := make(map[string]string, len(raw)) // secrets 保存敏感设置的显式变更命令。 - secrets := make(map[string]db.SensitiveSettingChange) + secrets := make(map[string]settingsapp.SecretChange) // valuesRaw 是普通设置对象的原始 JSON;ok 表示请求是否包含该对象。 if valuesRaw, ok := raw["values"]; ok { // explicitValues 是显式请求中的普通设置字段。 @@ -70,13 +57,13 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) { } // key 是显式普通设置中的字段名。 for key := range explicitValues { - if db.IsSensitiveSettingKey(key) { + if s.settingsApplication().IsSensitiveSettingKey(key) { writeErr(w, http.StatusBadRequest, "敏感设置必须放入 secrets 命令") return } } // err 是普通设置字段校验错误。 - if err := collectSystemSettingValues(explicitValues, values); err != nil { + if err := collectSystemSettingValues(explicitValues, values, s.settingsApplication().IsSensitiveSettingKey); err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } @@ -93,11 +80,11 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) { // key 是敏感设置键;change 是对应的三态命令。 for key, change := range explicitSecrets { key = strings.TrimSpace(key) - if !db.IsSensitiveSettingKey(key) || !validSecretSettingAction(change.Action) || change.Action == "replace" && strings.TrimSpace(change.Value) == "" { + if !s.settingsApplication().IsSensitiveSettingKey(key) || !validSecretSettingAction(change.Action) || change.Action == "replace" && strings.TrimSpace(change.Value) == "" { writeErr(w, http.StatusBadRequest, "敏感设置命令无效") return } - secrets[key] = db.SensitiveSettingChange{Action: change.Action, Value: change.Value} + secrets[key] = settingsapp.SecretChange{Action: change.Action, Value: change.Value} } } // legacy 保存旧版顶层普通设置字段,确保兼容接口可以渐进迁移。 @@ -105,7 +92,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) { // key 是兼容顶层字段名;value 是其原始 JSON 值。 for key, value := range raw { if key != "values" && key != "secrets" { - if db.IsSensitiveSettingKey(key) { + if s.settingsApplication().IsSensitiveSettingKey(key) { writeErr(w, http.StatusBadRequest, "敏感设置必须放入 secrets 命令") return } @@ -113,7 +100,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) { } } // err 是兼容顶层字段校验错误。 - if err := collectSystemSettingValues(legacy, values); err != nil { + if err := collectSystemSettingValues(legacy, values, s.settingsApplication().IsSensitiveSettingKey); err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } @@ -126,27 +113,14 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, err.Error()) return } - if len(secrets) > 0 { - // sess 保存当前管理员会话,用于敏感设置写入审计。 - sess := authSess(r) - if sess == nil { - writeErr(w, http.StatusInternalServerError, "审计失败") - return - } - // secretKeys 保存本次敏感设置写入涉及的键名。 - secretKeys := make([]string, 0, len(secrets)) - // key 是本次敏感设置写入涉及的键名。 - for key := range secrets { - secretKeys = append(secretKeys, key) - } - // err 保存敏感设置写入审计错误。 - if err := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.write", "system_settings", secretKeys); err != nil { - writeErr(w, http.StatusInternalServerError, "审计失败") - return - } + // sess 保存当前管理员会话,用于应用服务执行用户范围校验和敏感写入审计。 + sess := authSess(r) + if sess == nil { + writeErr(w, http.StatusInternalServerError, "审计失败") + return } // err 是普通设置与敏感命令原子保存错误。 - if err := s.Store.Settings.ApplyChanges(r.Context(), values, secrets); err != nil { + if err := s.settingsApplication().ApplySystemChanges(r.Context(), sess.UserID, values, secrets); err != nil { writeErr(w, http.StatusInternalServerError, "保存失败") return } @@ -158,14 +132,14 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) { } // collectSystemSettingValues 解析普通设置字段并拒绝敏感明文。 -func collectSystemSettingValues(raw map[string]json.RawMessage, values map[string]string) error { +func collectSystemSettingValues(raw map[string]json.RawMessage, values map[string]string, isSensitive func(string) bool) error { // key 是当前设置键;rawValue 是尚未转换的 JSON 值。 for key, rawValue := range raw { key = strings.TrimSpace(key) if key == "" || len(key) > 100 { return errors.New("设置键无效") } - if db.IsSensitiveSettingKey(key) { + if isSensitive(key) { return fmt.Errorf("敏感设置 %q 必须使用 secrets 命令", key) } // value 是普通设置转换后的任意 JSON 值。 @@ -200,39 +174,10 @@ func validSecretSettingAction(action string) bool { } } -// auditSensitiveSettingsAccess 记录敏感设置访问动作,审计内容只包含键名而不包含秘密值。 -func (s *Server) auditSensitiveSettingsAccess(ctx context.Context, userID int64, action, resource string, keys []string) error { - if len(keys) == 0 { - return nil - } - if s == nil || s.Store == nil || s.Store.SecurityAudit == nil { - return errors.New("敏感访问审计未初始化") - } - // normalizedKeys 保存排序去重后的敏感设置键名。 - normalizedKeys := make([]string, 0, len(keys)) - // seenKeys 保存已经加入审计记录的键名。 - seenKeys := make(map[string]struct{}, len(keys)) - // key 是当前待写入审计记录的敏感设置键名。 - for _, key := range keys { - key = strings.TrimSpace(key) - if key == "" { - continue - } - // exists 表示敏感设置键名是否已经加入审计记录。 - if _, exists := seenKeys[key]; exists { - continue - } - seenKeys[key] = struct{}{} - normalizedKeys = append(normalizedKeys, key) - } - sort.Strings(normalizedKeys) - return s.Store.SecurityAudit.Add(ctx, db.SecurityAuditLog{UserID: userID, Action: action, Resource: resource, Keys: normalizedKeys, Outcome: "accepted"}) -} - // publicSettings 负责public设置相关处理。 func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) { // m、err 保存m、err,供当前处理流程使用 - m, err := s.Store.Settings.Public(r.Context()) + m, err := s.settingsApplication().PublicSystem(r.Context()) if err != nil { writeErrRequest(w, r, http.StatusInternalServerError, "查询失败") return @@ -242,19 +187,14 @@ func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) { // allSettings 负责all设置相关处理。 func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) { - // sess 保存当前管理员会话,用于敏感配置读取审计。 + // sess 保存当前管理员会话,用于应用服务执行敏感配置读取审计。 sess := authSess(r) if sess == nil { writeErr(w, http.StatusInternalServerError, "审计失败") return } - // err 保存敏感配置读取审计错误。 - if err := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.read", "system_settings", db.SensitiveSettingKeys()); err != nil { - writeErr(w, http.StatusInternalServerError, "审计失败") - return - } - // m、err 保存m、err,供当前处理流程使用 - m, err := s.Store.Settings.Redacted(r.Context()) + // m、err 保存脱敏设置及应用服务查询错误。 + m, err := s.settingsApplication().GetSystem(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -278,26 +218,21 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - if db.IsSensitiveSettingKey(key) { + if s.settingsApplication().IsSensitiveSettingKey(key) { // action 是最终采用的敏感设置命令。 action := req.Action if !validSecretSettingAction(action) { writeErr(w, http.StatusBadRequest, "敏感设置命令无效") return } - // sess 保存当前管理员会话,用于单项敏感设置写入审计。 + // sess 保存当前管理员会话,用于应用服务执行单项敏感设置写入审计。 sess := authSess(r) if sess == nil { writeErr(w, http.StatusInternalServerError, "审计失败") return } - // err 保存单项敏感设置写入审计错误。 - if err := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.write", "system_settings", []string{key}); err != nil { - writeErr(w, http.StatusInternalServerError, "审计失败") - return - } - // err 是单项敏感设置原子保存错误。 - if err := s.Store.Settings.ApplyChanges(r.Context(), nil, map[string]db.SensitiveSettingChange{key: {Action: action, Value: req.Value}}); err != nil { + // err 是单项敏感设置原子保存或审计错误。 + if err := s.settingsApplication().SetSystem(r.Context(), sess.UserID, key, req.Value, action); err != nil { writeErr(w, http.StatusInternalServerError, "保存失败") return } @@ -311,8 +246,14 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) { return } } - if // err 保存err,供当前处理流程使用 - err := s.Store.Settings.Set(r.Context(), key, req.Value); err != nil { + // sess 保存当前管理员会话,用于应用服务执行普通设置写入。 + sess := authSess(r) + if sess == nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + // err 表示普通设置保存或应用服务校验失败。 + if err := s.settingsApplication().SetSystem(r.Context(), sess.UserID, key, req.Value, ""); err != nil { writeErr(w, http.StatusInternalServerError, "保存失败") return } @@ -330,10 +271,10 @@ func (s *Server) mountAIReplyReal(r chi.Router) { // listAIReply 负责listAI回复相关处理。 func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 + // sess 保存当前认证会话,用于应用服务执行用户范围查询。 sess := authSess(r) - // rows、err 保存rows、err,供当前处理流程使用 - rows, err := s.Store.AIReply.ListForUser(r.Context(), sess.UserID) + // rows、err 保存应用层 AI 设置摘要及查询错误。 + rows, err := s.settingsApplication().ListAIReply(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -358,23 +299,24 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) { func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) { // cid 保存cid,供当前处理流程使用 cid := chi.URLParam(r, "cookie_id") - if !s.requireCookieOwnership(w, r, cid) { + // sess 保存当前认证会话,用于应用服务执行账号归属校验。 + sess := authSess(r) + if sess == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") return } // cfg、err 保存cfg、err,供当前处理流程使用 - cfg, err := s.Store.AIReply.Get(r.Context(), cid) + cfg, err := s.settingsApplication().GetAIReply(r.Context(), sess.UserID, cid) if err != nil { - if !errors.Is(err, db.ErrNotFound) { - writeErr(w, http.StatusInternalServerError, "查询失败") + if errors.Is(err, settingsapp.ErrConfigNotFound) { + // 未保存配置使用与旧接口一致的默认值。 + writeJSON(w, http.StatusOK, aiReplySettingsResponse{AIEnabled: false, MaxDiscountPercent: 10, MaxDiscountAmount: 100, MaxBargainRounds: 3, CustomPrompts: ""}) return } - // 未保存配置使用与旧接口一致的默认值。 - // 默认响应不携带 cookie_id,避免误认为已持久化账号配置。 - // max_discount_percent 保持默认 10 的业务约束。 - // max_discount_amount 保持默认 100 的业务约束。 - // max_bargain_rounds 保持默认 3 的业务约束。 - // custom_prompts 为空表示未配置自定义提示词。 - writeJSON(w, http.StatusOK, aiReplySettingsResponse{AIEnabled: false, MaxDiscountPercent: 10, MaxDiscountAmount: 100, MaxBargainRounds: 3, CustomPrompts: ""}) + if writeSettingsAccountError(w, err) { + return + } + writeErr(w, http.StatusInternalServerError, "查询失败") return } // 已保存配置返回账号标识,客户端可据此区分账号级设置。 @@ -404,7 +346,18 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - if !s.requireCookieOwnership(w, r, cid) { + // sess 保存当前认证会话,用于在字段校验前复用旧接口的账号归属错误优先级。 + sess := authSess(r) + if sess == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") + return + } + // ownershipErr 保存账号不存在、跨用户或数据库归属查询失败的结果;未配置 AI 设置不是账号错误。 + if _, ownershipErr := s.settingsApplication().GetAIReply(r.Context(), sess.UserID, cid); ownershipErr != nil && !errors.Is(ownershipErr, settingsapp.ErrConfigNotFound) { + if writeSettingsAccountError(w, ownershipErr) { + return + } + writeErr(w, http.StatusInternalServerError, "查询失败") return } if req.MaxDiscountPercent < 0 || req.MaxDiscountPercent > 100 { @@ -420,21 +373,37 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) { return } // err 是 AI 回复配置写入错误。 - err := s.Store.AIReply.UpsertSettings(r.Context(), cid, db.AIReplySettings{ - AIEnabled: req.AIEnabled, MaxDiscountPercent: req.MaxDiscountPercent, + err := s.settingsApplication().UpsertAIReply(r.Context(), sess.UserID, cid, settingsapp.AIReplySettings{ + CookieID: cid, AIEnabled: req.AIEnabled, MaxDiscountPercent: req.MaxDiscountPercent, MaxDiscountAmount: req.MaxDiscountAmount, MaxBargainRounds: req.MaxBargainRounds, CustomPrompts: req.CustomPrompts, }) if err != nil { + if writeSettingsAccountError(w, err) { + return + } writeErr(w, http.StatusInternalServerError, "保存失败") return } writeJSON(w, http.StatusOK, operationResponse{Success: true}) } +// writeSettingsAccountError 将应用层账号归属错误映射为旧接口兼容的 HTTP 状态。 +func writeSettingsAccountError(w http.ResponseWriter, err error) bool { + if errors.Is(err, settingsapp.ErrAccountNotFound) { + writeErr(w, http.StatusNotFound, "账号不存在") + return true + } + if errors.Is(err, settingsapp.ErrForbidden) { + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return true + } + return false +} + // listAIModels 负责listAI模型列表相关处理。 func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) { - // req 保存req,供当前处理流程使用 + // req 保存 HTTP 层接收的模型目录查询参数。 var req struct { BaseURL string `json:"base_url"` APIKey string `json:"api_key"` @@ -444,46 +413,14 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, "请求格式错误") return } - // sess 保存当前管理员会话,用于 AI 密钥使用审计。 + // sess 保存当前管理员会话,用于应用服务执行 AI 密钥审计和读取。 sess := authSess(r) if sess == nil { writeErr(w, http.StatusInternalServerError, "审计失败") return } - // baseURL 保存baseURL,供当前处理流程使用 - baseURL := strings.TrimSpace(req.BaseURL) - if baseURL == "" { - // v、err 保存v、err,供当前处理流程使用 - v, err := s.Store.Settings.Get(r.Context(), "ai_api_url") - if err != nil { - writeErr(w, http.StatusInternalServerError, "读取AI地址失败") - return - } - baseURL = v - } - if baseURL == "" { - baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1" - } - // apiKey 保存apiKey,供当前处理流程使用 - apiKey := strings.TrimSpace(req.APIKey) - if apiKey == "" { - // v、err 保存经访问审计后读取的 AI 密钥及错误。 - v, err := s.Store.ReadSensitiveSetting(r.Context(), sess.UserID, "ai_api_key", "settings.use", "ai_models") - if err != nil { - writeErr(w, http.StatusInternalServerError, "读取AI Key失败") - return - } - apiKey = v - } else if - // auditErr 表示审计外部传入 AI 密钥时返回的错误。 - auditErr := s.auditSensitiveSettingsAccess(r.Context(), sess.UserID, "settings.use", "ai_models", []string{"ai_api_key"}); auditErr != nil { - // 外部传入的 AI 密钥也属于敏感使用,审计不可用时拒绝继续请求。 - writeErr(w, http.StatusInternalServerError, "审计失败") - return - } - - // models、err 保存models、err,供当前处理流程使用 - models, err := fetchOpenAIModels(r.Context(), baseURL, apiKey) + // models、err 保存应用服务读取的模型名称及错误。 + models, err := s.settingsApplication().ListAIModels(r.Context(), sess.UserID, req.BaseURL, req.APIKey) if err != nil { writeErr(w, http.StatusBadGateway, err.Error()) return @@ -491,127 +428,6 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, aiModelsResponse{Models: models}) } -// newSettingsOutboundHTTPClient 保存new设置OutboundHTTPClient,供当前处理流程使用 -var newSettingsOutboundHTTPClient = func(baseURL string) (*http.Client, error) { - return netguard.TrustedEndpointHTTPClient(baseURL, 20*time.Second) -} - -// fetchOpenAIModels 负责fetchOpenAI模型列表相关处理。 -func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, error) { - baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") - if baseURL == "" { - return nil, fmt.Errorf("AI API 地址为空") - } - // req、err 保存req、err,供当前处理流程使用 - req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/models", nil) - if err != nil { - return nil, err - } - req.Header.Set("Accept", "application/json") - if strings.TrimSpace(apiKey) != "" { - req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(apiKey)) - } - // client、err 保存client、err,供当前处理流程使用 - client, err := newSettingsOutboundHTTPClient(baseURL) - if err != nil { - return nil, fmt.Errorf("AI API 地址无效: %w", err) - } - // resp、err 保存resp、err,供当前处理流程使用 - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("读取模型失败: %w", err) - } - defer resp.Body.Close() - // raw、err 保存raw、err,供当前处理流程使用 - raw, err := readOpenAIModelsBody(resp.Body) - if err != nil { - return nil, err - } - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return nil, fmt.Errorf("读取模型失败: HTTP %d %s", resp.StatusCode, truncate(string(raw), 180)) - } - // models、err 保存models、err,供当前处理流程使用 - models, err := parseOpenAIModels(raw) - if err != nil { - return nil, err - } - if len(models) == 0 { - return nil, fmt.Errorf("模型列表为空") - } - return models, nil -} - -// readOpenAIModelsBody 负责readOpenAI模型列表请求体相关处理。 -func readOpenAIModelsBody(r io.Reader) ([]byte, error) { - // raw、err 保存raw、err,供当前处理流程使用 - raw, err := io.ReadAll(io.LimitReader(r, maxOpenAIModelsResponseBytes+1)) - if err != nil { - return nil, err - } - if len(raw) > maxOpenAIModelsResponseBytes { - return nil, fmt.Errorf("模型列表响应超过 %d MiB", maxOpenAIModelsResponseBytes>>20) - } - return raw, nil -} - -// parseOpenAIModels 负责parseOpenAI模型列表相关处理。 -func parseOpenAIModels(raw []byte) ([]string, error) { - // payload 保存请求载荷,供当前处理流程使用 - var payload any - if // err 保存err,供当前处理流程使用 - err := json.Unmarshal(raw, &payload); err != nil { - return nil, fmt.Errorf("解析模型列表失败: %w", err) - } - // seen 保存seen,供当前处理流程使用 - seen := make(map[string]bool) - // out 保存out,供当前处理流程使用 - var out []string - // add 保存add,供当前处理流程使用 - add := func(v string) { - v = strings.TrimSpace(v) - if v == "" || seen[v] { - return - } - seen[v] = true - out = append(out, v) - } - // walk 保存walk,供当前处理流程使用 - var walk func(any) - walk = func(v any) { - switch // x 保存x,供当前处理流程使用 - x := v.(type) { - case []any: - // item 表示当前遍历过程中的商品 - for _, item := range x { - walk(item) - } - case map[string]any: - if // id 保存标识,供当前处理流程使用 - id, _ := x["id"].(string); id != "" { - add(id) - } else if // name 保存名称,供当前处理流程使用 - name, _ := x["name"].(string); name != "" { - add(name) - } - case string: - add(x) - } - } - if // root、ok 保存root、ok,供当前处理流程使用 - root, ok := payload.(map[string]any); ok { - if // data、ok 保存data、ok,供当前处理流程使用 - data, ok := root["data"]; ok { - walk(data) - } else if // models、ok 保存models、ok,供当前处理流程使用 - models, ok := root["models"]; ok { - walk(models) - } - } else { - walk(payload) - } - return out, nil -} - // ---- 用户设置 ---- // mountUserReal 负责mount用户Real相关处理。 @@ -623,10 +439,10 @@ func (s *Server) mountUserReal(r chi.Router) { // listUserSettings 负责list用户设置相关处理。 func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 + // sess 保存当前认证会话,用于应用服务执行用户范围查询。 sess := authSess(r) - // settings、err 保存settings、err,供当前处理流程使用 - settings, err := s.Store.UserSettings.AllForUser(r.Context(), sess.UserID) + // settings、err 保存用户设置及查询错误。 + settings, err := s.settingsApplication().ListUser(r.Context(), sess.UserID) if err != nil { writeErr(w, http.StatusInternalServerError, "查询失败") return @@ -636,12 +452,12 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) { // getUserSetting 负责get用户设置相关处理。 func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) { - // sess 保存sess,供当前处理流程使用 + // sess 保存当前认证会话,用于应用服务执行用户范围查询。 sess := authSess(r) // key 保存key,供当前处理流程使用 key := chi.URLParam(r, "key") - // v、err 保存v、err,供当前处理流程使用 - v, err := s.Store.UserSettings.GetForUser(r.Context(), sess.UserID, key) + // v、err 保存用户设置值及查询错误。 + v, err := s.settingsApplication().GetUser(r.Context(), sess.UserID, key) if err != nil { writeJSON(w, http.StatusOK, userSettingResponse{Value: ""}) return @@ -665,7 +481,7 @@ func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) { return } // err 是用户设置写入错误。 - err := s.Store.UserSettings.SetForUser(r.Context(), sess.UserID, key, req.Value) + err := s.settingsApplication().SetUser(r.Context(), sess.UserID, key, req.Value) if err != nil { writeErr(w, http.StatusInternalServerError, "保存失败") return diff --git a/internal/server/settings_models_compat_test.go b/internal/server/settings_models_compat_test.go new file mode 100644 index 0000000..8f8309e --- /dev/null +++ b/internal/server/settings_models_compat_test.go @@ -0,0 +1,26 @@ +package server + +import ( + "context" + "io" + + "xianyu-go/internal/adapter" +) + +// maxOpenAIModelsResponseBytes 保留旧测试名称,实际限制由适配器统一维护。 +const maxOpenAIModelsResponseBytes = adapter.MaxAIModelsResponseBytes + +// fetchOpenAIModels 保留旧测试辅助入口,生产请求已经由设置应用服务编排。 +func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, error) { + return adapter.NewAIModelClient().Fetch(ctx, baseURL, apiKey) +} + +// readOpenAIModelsBody 保留旧测试辅助入口,实际读取逻辑由适配器维护。 +func readOpenAIModelsBody(reader io.Reader) ([]byte, error) { + return adapter.ReadAIModelsBody(reader) +} + +// parseOpenAIModels 保留旧测试辅助入口,实际解析逻辑由适配器维护。 +func parseOpenAIModels(raw []byte) ([]string, error) { + return adapter.ParseAIModels(raw) +} diff --git a/internal/server/success_contract.go b/internal/server/success_contract.go index 3475808..6468b0c 100644 --- a/internal/server/success_contract.go +++ b/internal/server/success_contract.go @@ -1,11 +1,10 @@ package server import ( + cardsapp "xianyu-go/internal/application/cards" chatapp "xianyu-go/internal/application/chat" + defaultreplyapp "xianyu-go/internal/application/defaultreply" notificationsapp "xianyu-go/internal/application/notifications" - "xianyu-go/internal/automation" - "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/mtop" ) // operationResponse 是密码、会话和设置变更接口共用的操作结果 DTO。 @@ -18,6 +17,14 @@ type operationResponse struct { RequiresRelogin bool `json:"requires_relogin,omitempty"` } +// longLoginResponse 是长登录设置接口的具名响应 DTO,不包含平台 Cookie。 +type longLoginResponse struct { + // CanOpenLongLogin 表示平台是否允许开启长登录。 + CanOpenLongLogin bool `json:"can_open_long_login"` + // Enabled 表示平台当前是否已开启长登录。 + Enabled bool `json:"enabled"` +} + // messageResponse 是只返回提示文本的简单成功响应 DTO。 type messageResponse struct { // Message 是接口操作结果说明。 @@ -78,23 +85,23 @@ type chatSessionDTO struct { UnreadCount int `json:"unread_count"` } -// newChatSessionDTO 将数据库聊天会话转换为 API DTO。 -func newChatSessionDTO(session db.ChatSession) chatSessionDTO { +// newChatSessionDTOFromApplication 将应用层聊天会话转换为 HTTP DTO。 +func newChatSessionDTOFromApplication(session chatapp.Session) chatSessionDTO { return chatSessionDTO{ - AccountID: session.CookieID, ChatID: session.ChatID, BuyerID: session.BuyerID, + AccountID: session.AccountID, ChatID: session.ChatID, BuyerID: session.BuyerID, BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID, ItemTitle: session.ItemTitle, LastMessage: session.LastMessage, LastMessageAt: session.LastMessageAt, UnreadCount: session.UnreadCount, } } -// newChatSessionDTOs 批量转换聊天会话,保持接口响应不直接暴露数据库模型。 -func newChatSessionDTOs(sessions []db.ChatSession) []chatSessionDTO { +// newChatSessionDTOsFromApplication 批量转换应用层聊天会话,保持响应不暴露数据库模型。 +func newChatSessionDTOsFromApplication(sessions []chatapp.Session) []chatSessionDTO { // result 是转换后的聊天会话 DTO 列表。 result := make([]chatSessionDTO, 0, len(sessions)) - // session 是当前待转换的数据库聊天会话。 + // session 表示当前待转换的应用层会话。 for _, session := range sessions { - result = append(result, newChatSessionDTO(session)) + result = append(result, newChatSessionDTOFromApplication(session)) } return result } @@ -125,25 +132,6 @@ type chatMessageDTO struct { SentAt int64 `json:"sent_at"` } -// newChatMessageDTO 将数据库聊天消息转换为 API DTO。 -func newChatMessageDTO(message db.ChatMessage) chatMessageDTO { - return chatMessageDTO{ - ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID, - MessageKey: message.MessageKey, Direction: message.Direction, - SenderID: message.SenderID, SenderName: message.SenderName, - MessageType: message.MessageType, Content: message.Content, - Status: message.Status, SentAt: message.SentAt, - } -} - -// newChatMessageDTOFromPointer 转换可为空的聊天消息指针,避免成功响应因空值 panic。 -func newChatMessageDTOFromPointer(message *db.ChatMessage) chatMessageDTO { - if message == nil { - return chatMessageDTO{} - } - return newChatMessageDTO(*message) -} - // newChatMessageDTOFromApplication 将聊天应用层发送结果转换为 HTTP DTO,避免响应引用数据库模型。 func newChatMessageDTOFromApplication(message *chatapp.Message) chatMessageDTO { if message == nil { @@ -158,17 +146,6 @@ func newChatMessageDTOFromApplication(message *chatapp.Message) chatMessageDTO { } } -// newChatMessageDTOs 批量转换聊天消息,保持接口响应与数据库模型解耦。 -func newChatMessageDTOs(messages []db.ChatMessage) []chatMessageDTO { - // result 是转换后的聊天消息 DTO 列表。 - result := make([]chatMessageDTO, 0, len(messages)) - // message 是当前待转换的数据库聊天消息。 - for _, message := range messages { - result = append(result, newChatMessageDTO(message)) - } - return result -} - // newChatMessageDTOsFromApplication 将聊天应用层消息转换为 HTTP DTO,避免响应暴露数据库模型。 func newChatMessageDTOsFromApplication(messages []chatapp.Message) []chatMessageDTO { // result 是转换后的聊天消息 DTO 列表。 @@ -537,12 +514,52 @@ type automationRulePageResponse struct { TriggerCounts map[string]int `json:"trigger_counts"` } +// automationRunIssueDTO 是自动化异常运行接口对外暴露的具名 DTO。 +type automationRunIssueDTO struct { + // ID 是自动化运行的稳定标识。 + ID int64 `json:"id"` + // CookieID 是关联账号标识。 + CookieID string `json:"cookie_id"` + // OrderID 是关联订单标识。 + OrderID string `json:"order_id"` + // TriggerType 是触发运行的事件类型。 + TriggerType string `json:"trigger_type"` + // ErrorMessage 是运行进入人工处理状态时记录的原因。 + ErrorMessage string `json:"error_message"` + // IssueKind 是应用层归类的异常类型。 + IssueKind string `json:"issue_kind"` + // AllowedResolutions 是当前异常允许的人工处理动作。 + AllowedResolutions []string `json:"allowed_resolutions"` + // ActionCursor 是下一步动作在计划中的位置。 + ActionCursor int `json:"action_cursor"` + // SentCount 是已经确认成功的外部动作数量。 + SentCount int `json:"sent_count"` + // UpdatedAt 是运行状态最近更新的时间文本。 + UpdatedAt string `json:"updated_at"` +} + +// deferredAutomationIssueDTO 是延期任务接口对外暴露的具名 DTO。 +type deferredAutomationIssueDTO struct { + // ID 是延期任务的稳定标识。 + ID int64 `json:"id"` + // CookieID 是关联账号标识。 + CookieID string `json:"cookie_id"` + // TriggerType 是触发延期任务的事件类型。 + TriggerType string `json:"trigger_type"` + // ErrorMessage 是任务进入死信状态时记录的原因。 + ErrorMessage string `json:"error_message"` + // AttemptCount 是任务已经尝试执行的次数。 + AttemptCount int `json:"attempt_count"` + // UpdatedAt 是任务状态最近更新的时间文本。 + UpdatedAt string `json:"updated_at"` +} + // automationIssuesResponse 是自动化异常任务接口的具名响应 DTO。 type automationIssuesResponse struct { // Runs 是需要处理的自动化运行记录。 - Runs []db.AutomationRunIssue `json:"runs"` + Runs []automationRunIssueDTO `json:"runs"` // PendingTasks 是需要处理的延迟任务记录。 - PendingTasks []db.DeferredAutomationIssue `json:"pending_tasks"` + PendingTasks []deferredAutomationIssueDTO `json:"pending_tasks"` } // orderDetailResponse 是订单详情接口的具名响应 DTO,同时保留旧版顶层字段兼容性。 @@ -701,8 +718,8 @@ type cardResponse struct { UserID int64 `json:"user_id,omitempty"` } -// newCardResponse 将数据库卡券模型转换为 HTTP DTO。 -func newCardResponse(card db.CardFull) cardResponse { +// newCardResponse 将应用层卡券模型转换为 HTTP DTO。 +func newCardResponse(card cardsapp.Card) cardResponse { return cardResponse{ ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig, TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL, @@ -711,11 +728,11 @@ func newCardResponse(card db.CardFull) cardResponse { } } -// newCardResponses 批量转换卡券列表,避免直接暴露数据库模型。 -func newCardResponses(cards []db.CardFull) []cardResponse { +// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。 +func newCardResponses(cards []cardsapp.Card) []cardResponse { // result 是转换后的卡券 DTO 列表。 result := make([]cardResponse, 0, len(cards)) - // card 是当前待转换的卡券数据库模型。 + // card 是当前待转换的卡券应用模型。 for _, card := range cards { result = append(result, newCardResponse(card)) } @@ -854,7 +871,63 @@ type categoryRecommendationResponse struct { // Success 表示类目推荐是否成功。 Success bool `json:"success"` // Category 是推荐的商品类目。 - Category mtop.PublishCategory `json:"category"` + Category publishCategoryResponse `json:"category"` +} + +// publishCategoryResponse 是商品类目 HTTP 响应的稳定 DTO,不泄露平台包类型。 +type publishCategoryResponse struct { + // CatID 是平台类目标识。 + CatID string `json:"cat_id"` + // CatName 是平台类目名称。 + CatName string `json:"cat_name"` + // ChannelCatID 是闲鱼频道类目标识。 + ChannelCatID string `json:"channel_cat_id,omitempty"` + // TBCatID 是淘宝类目标识。 + TBCatID string `json:"tb_cat_id,omitempty"` +} + +// publishAutomationConfig 是批量发布预检与详情响应中的自动化配置 DTO。 +type publishAutomationConfig struct { + // PaidDelivery 保存付款后自动发货配置。 + PaidDelivery publishCardAutomation `json:"paid_delivery"` + // ReviewGift 保存评价后赠品配置。 + ReviewGift publishCardAutomation `json:"review_gift"` + // ReviewRequest 保存超时求评价配置。 + ReviewRequest publishReviewRequestCfg `json:"review_request"` +} + +// publishCardAutomation 是批量发布中的卡密自动化 DTO。 +type publishCardAutomation struct { + // Enabled 表示该自动化规则是否启用。 + Enabled bool `json:"enabled"` + // Actions 保存按顺序执行的卡密动作。 + Actions []publishCardAction `json:"actions"` + // ParseError 保存导入动作文本的解析错误。 + ParseError string `json:"-"` +} + +// publishCardAction 是单条批量卡密动作 DTO。 +type publishCardAction struct { + // CardID 是卡密组标识。 + CardID int64 `json:"card_id"` + // DeliveryCount 是每件商品发送的卡密数量。 + DeliveryCount int `json:"delivery_count"` + // DelaySeconds 是发送动作的延迟秒数。 + DelaySeconds int `json:"delay_seconds"` +} + +// publishReviewRequestCfg 是批量发布求评价配置 DTO。 +type publishReviewRequestCfg struct { + // Enabled 表示是否启用求评价。 + Enabled bool `json:"enabled"` + // AfterShippedHours 是发货后的等待小时数。 + AfterShippedHours int `json:"after_shipped_hours"` + // Message 是发送给买家的求评价文案。 + Message string `json:"message"` + // MaxAttempts 是最多提醒次数。 + MaxAttempts int `json:"max_attempts"` + // DelaySeconds 是提醒动作的延迟秒数。 + DelaySeconds int `json:"delay_seconds"` } // itemPublishBatchPreviewResponse 是商品批量发布预检接口的具名响应 DTO。 @@ -906,7 +979,7 @@ type itemPublishBatchRowResponse struct { // Images 是商品图片引用列表。 Images []string `json:"images"` // Category 是商品发布类目。 - Category mtop.PublishCategory `json:"category"` + Category publishCategoryResponse `json:"category"` // Automation 是发布后自动化配置。 Automation publishAutomationConfig `json:"automation"` // Status 是当前明细行状态。 @@ -1015,8 +1088,8 @@ type defaultReplyResponse struct { ReplyOnce bool `json:"reply_once"` } -// newDefaultReplyResponse 将数据库默认回复转换为 HTTP DTO。 -func newDefaultReplyResponse(cookieID string, reply db.DefaultReply) defaultReplyResponse { +// newDefaultReplyResponse 将默认回复应用模型转换为 HTTP DTO。 +func newDefaultReplyResponse(cookieID string, reply defaultreplyapp.Reply) defaultReplyResponse { return defaultReplyResponse{ CookieID: cookieID, Enabled: reply.Enabled, ReplyContent: reply.ReplyContent, ReplyImageURL: reply.ReplyImageURL, ReplyOnce: reply.ReplyOnce, @@ -1043,15 +1116,6 @@ type accountTaskSettingsResponse struct { LastPolishAt int64 `json:"last_polish_at"` } -// newAccountTaskSettingsResponse 将账号任务数据库设置转换为 HTTP DTO。 -func newAccountTaskSettingsResponse(settings db.AccountTaskSettings) accountTaskSettingsResponse { - return accountTaskSettingsResponse{ - AccountID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent, - AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime, - LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt, - } -} - // accountTaskRunResponse 是账号任务执行记录的具名 DTO。 type accountTaskRunResponse struct { // ID 是任务执行记录主键。 @@ -1082,27 +1146,6 @@ type accountTaskRunResponse struct { FinishedAt int64 `json:"finished_at"` } -// newAccountTaskRunResponse 将账号任务执行记录转换为 HTTP DTO。 -func newAccountTaskRunResponse(run db.AccountTaskRun) accountTaskRunResponse { - return accountTaskRunResponse{ - ID: run.ID, RunKey: run.RunKey, AccountID: run.CookieID, TaskType: run.TaskType, - TargetID: run.TargetID, RunDate: run.RunDate, Status: run.Status, SuccessCount: run.SuccessCount, - FailedCount: run.FailedCount, ErrorMessage: run.ErrorMessage, NextRetryAt: run.NextRetryAt, - StartedAt: run.StartedAt, FinishedAt: run.FinishedAt, - } -} - -// newAccountTaskRunResponses 批量转换账号任务执行记录。 -func newAccountTaskRunResponses(runs []db.AccountTaskRun) []accountTaskRunResponse { - // result 是账号任务执行记录 DTO 列表。 - result := make([]accountTaskRunResponse, 0, len(runs)) - // run 是当前待转换的账号任务执行记录。 - for _, run := range runs { - result = append(result, newAccountTaskRunResponse(run)) - } - return result -} - // accountTaskSummaryResponse 是手动执行账号任务的统计 DTO。 type accountTaskSummaryResponse struct { // TaskType 是任务类型。 @@ -1133,14 +1176,6 @@ type accountTaskRunsResponse struct { Runs []accountTaskRunResponse `json:"runs"` } -// newAccountTaskSummaryResponse 将自动化中心统计转换为 HTTP DTO。 -func newAccountTaskSummaryResponse(summary automation.AccountTaskSummary) accountTaskSummaryResponse { - return accountTaskSummaryResponse{ - TaskType: summary.TaskType, Found: summary.Found, Success: summary.Success, - Failed: summary.Failed, Skipped: summary.Skipped, Message: summary.Message, - } -} - // adminUserResponse 是管理员用户列表项的具名响应 DTO。 type adminUserResponse struct { // ID 是用户主键。 diff --git a/internal/server/task_registry_test.go b/internal/server/task_registry_test.go index 7fa7f3b..e29882e 100644 --- a/internal/server/task_registry_test.go +++ b/internal/server/task_registry_test.go @@ -154,3 +154,32 @@ func TestStartBackgroundTaskContextWaitsForTaskExit(t *testing.T) { t.Fatal("后台任务退出后等待未完成") } } + +// TestWaitForBackgroundContextBoundsTimeout 验证后台任务等待超时不会阻塞后续生命周期收束。 +func TestWaitForBackgroundContextBoundsTimeout(t *testing.T) { + // srv 是使用零值字段验证后台完成信号惰性初始化的 Server。 + srv := &Server{} + // taskStarted、releaseTask 分别表示任务已经登记和允许任务退出的信号。 + taskStarted := make(chan struct{}) + // releaseTask 是允许阻塞测试任务退出的信号。 + releaseTask := make(chan struct{}) + srv.startBackgroundTaskContext("超时等待任务", context.Background(), func() { + close(taskStarted) + <-releaseTask + }) + <-taskStarted + // timeoutContext 是限制第一次等待时长的上下文。 + timeoutContext, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if srv.waitForBackgroundContext(timeoutContext) { + t.Fatal("后台任务未退出时不应提前报告完成") + } + // releaseTask 允许后台任务退出,验证后续等待可以直接观察完成信号。 + close(releaseTask) + // completedContext 是用于确认任务退出的有限等待上下文。 + completedContext, completedCancel := context.WithTimeout(context.Background(), time.Second) + defer completedCancel() + if !srv.waitForBackgroundContext(completedContext) { + t.Fatalf("后台任务退出后等待失败: %v", completedContext.Err()) + } +} diff --git a/internal/server/transaction_repository.go b/internal/server/transaction_repository.go deleted file mode 100644 index 9ed257f..0000000 --- a/internal/server/transaction_repository.go +++ /dev/null @@ -1,63 +0,0 @@ -package server - -import ( - "context" - "database/sql" - "errors" - - "xianyu-go/internal/db" -) - -// transactionRepository 定义 Server 统一事务入口所需的最小持久化能力。 -type transactionRepository interface { - // WithTransaction 在一个事务中执行工作并负责提交或回滚。 - WithTransaction(ctx context.Context, work func(*sql.Tx) error) error -} - -// storeTransactionRepository 将完整 Store 适配为事务执行窄 repository。 -type storeTransactionRepository struct { - // store 保存数据库聚合入口,仅在适配器内部使用。 - store *db.Store -} - -// WithTransaction 创建、提交或回滚数据库事务。 -func (r storeTransactionRepository) WithTransaction(ctx context.Context, work func(*sql.Tx) error) error { - if r.store == nil || r.store.DB == nil { - return errors.New("事务 repository 未初始化") - } - // tx 是本次用例使用的数据库事务。 - // err 表示事务创建错误。 - // tx、err 保存tx、err,供当前处理流程使用 - tx, err := r.store.DB.BeginTx(ctx, nil) - if err != nil { - return err - } - // committed 标识事务是否已经成功提交,避免提交失败后重复处理回滚错误。 - committed := false - defer func() { - if !committed { - _ = tx.Rollback() - } - }() - if // err 保存err,供当前处理流程使用 - err := work(tx); err != nil { - return err - } - // err 表示事务提交错误。 - if err := tx.Commit(); err != nil { - return err - } - committed = true - return nil -} - -// newStoreTransactionRepository 从完整 Store 构造事务执行窄 repository。 -func newStoreTransactionRepository(store *db.Store) transactionRepository { - if store == nil || store.DB == nil { - return nil - } - return storeTransactionRepository{store: store} -} - -// 确保 Store 适配器始终覆盖事务执行边界。 -var _ transactionRepository = storeTransactionRepository{} diff --git a/internal/server/unit_of_work_test.go b/internal/server/unit_of_work_test.go index 24dd9e0..4cdc8a4 100644 --- a/internal/server/unit_of_work_test.go +++ b/internal/server/unit_of_work_test.go @@ -10,12 +10,12 @@ import ( // TestWithTransactionCommitAndRollback 验证统一事务入口能够提交成功操作并回滚失败操作。 func TestWithTransactionCommitAndRollback(t *testing.T) { // srv 是使用测试数据库的 Server。 - srv, _, cleanup := newTestServer(t) + srv, store, cleanup := newTestServer(t) defer cleanup() // ctx 是本测试使用的可取消上下文。 ctx := context.Background() // createErr 是创建测试表失败时的错误。 - if _, createErr := srv.Store.DB.ExecContext(ctx, `CREATE TABLE unit_of_work_probe (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`); createErr != nil { + if _, createErr := store.DB.ExecContext(ctx, `CREATE TABLE unit_of_work_probe (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`); createErr != nil { t.Fatalf("创建事务测试表失败: %v", createErr) } // commitErr 是提交事务执行结果。 @@ -43,7 +43,7 @@ func TestWithTransactionCommitAndRollback(t *testing.T) { // count 是事务提交后测试表中的记录数。 var count int if // err 保存err,供当前处理流程使用 - err := srv.Store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil { + err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil { t.Fatalf("查询事务测试结果失败: %v", err) } if count != 1 { diff --git a/internal/webui/static/assets/AccountList-CMeDGrpw.js b/internal/webui/static/assets/AccountList-Bpj-f-W3.js similarity index 99% rename from internal/webui/static/assets/AccountList-CMeDGrpw.js rename to internal/webui/static/assets/AccountList-Bpj-f-W3.js index eb9a1d7..bf7c235 100644 --- a/internal/webui/static/assets/AccountList-CMeDGrpw.js +++ b/internal/webui/static/assets/AccountList-Bpj-f-W3.js @@ -1,3 +1,3 @@ -import{r as l,j as e,b as ne,c as Ee}from"./react-vendor-C_od1ZSF.js";import{f as Ne,u as ve,r as Qe,h as $e,i as Ue,j as Be,k as Me,l as Oe,m as ze,n as Ge,o as We,p as Ve,s as Ke,q as He,t as Xe,v as Je,w as Ye,x as Ze,y as Fe,z as es,A as ss,B as ts,C as as}from"./index-DK02p8DH.js";import{X as oe,n as rs,f as K,o as ls,p as Se,q as Re,r as qe,s as se,t as Ae,K as ns,u as os,v as is,a as ds,w as ie,b as cs,i as Pe,x as xs,k as je,Q as we,R as us,y as ms,z as bs,F as ye,H as hs}from"./icons-vendor-ThcsWkZG.js";const _e=t=>({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),J=(t,s,r)=>t===s&&!r.aborted,fe=(t,s)=>t instanceof Error?t.message:s,pe=t=>t instanceof Error&&t.message==="请求已取消",ke=(t,s)=>!t&&s==="",gs=({account:t,onSaved:s})=>{const[r,a]=l.useState(()=>_e(t)),[u,x]=l.useState(!0),[o,i]=l.useState(!1),[b,m]=l.useState(""),[p,h]=l.useState(""),[d,q]=l.useState(null),[k,g]=l.useState(null),f=l.useRef(0),L=l.useRef(null);l.useEffect(()=>{var v;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;return L.current=w,a(_e(t)),q(null),h(""),i(!1),m(""),g(null),x(!0),Ne(t.id,{signal:w.signal}).then(R=>{J(f.current,S,w.signal)&&a(R)}).catch(R=>{J(f.current,S,w.signal)&&!pe(R)&&h(fe(R,"加载任务设置失败"))}).finally(()=>{J(f.current,S,w.signal)&&x(!1)}),(()=>w.abort())},[t.id]),l.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=l.useCallback(async()=>{var v;if(!ke(o,b))return;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;L.current=w,i(!0),h(""),g(null);try{const R=await ve(t.id,r,{signal:w.signal});if(!J(f.current,S,w.signal))return;a(R),s(R)}catch(R){J(f.current,S,w.signal)&&!pe(R)&&(h(fe(R,"保存失败")),g(()=>U))}finally{J(f.current,S,w.signal)&&i(!1)}},[t.id,r,s,b,o]),B=l.useCallback(async S=>{var R;if(!ke(o,b)||!t.enabled)return;const w=++f.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),q(null),g(null);try{await ve(t.id,r,{signal:v.signal});const y=await Qe(t.id,S,{signal:v.signal}),A=await Ne(t.id,{signal:v.signal});if(!J(f.current,w,v.signal))return;q(y.summary),a(A),s(A)}catch(y){J(f.current,w,v.signal)&&!pe(y)&&(h(fe(y,"任务执行失败")),g(()=>(()=>B(S))))}finally{J(f.current,w,v.signal)&&m("")}},[t.enabled,t.id,r,s,b,o]),T=l.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:u,saving:o,running:b,summary:d,error:p,retryAvailable:k!==null,setForm:a,save:U,run:B,retry:T}},Ce=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),fs=({account:t,onClose:s,onSaved:r})=>{const{form:a,loading:u,saving:x,running:o,error:i,summary:b,retryAvailable:m,setForm:p,save:h,run:d,retry:q}=gs({account:t,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(oe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[u&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(rs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(Ce,{checked:a.auto_rate_enabled,onChange:(()=>p(k=>({...k,auto_rate_enabled:!k.auto_rate_enabled}))),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:a.rate_content,maxLength:500,onChange:(k=>p(g=>({...g,rate_content:k.target.value}))),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:o!==""||!t.enabled,onClick:(()=>void d("auto_rate")),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[o==="auto_rate"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(ls,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(Se,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(Ce,{checked:a.auto_polish_enabled,onChange:(()=>p(k=>({...k,auto_polish_enabled:!k.auto_polish_enabled}))),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:a.polish_time,onChange:(k=>p(g=>({...g,polish_time:k.target.value}))),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:o!==""||!t.enabled,onClick:(()=>void d("auto_polish")),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[o==="auto_polish"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(Re,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),b&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",b.found," 项,成功 ",b.success,",失败 ",b.failed,",跳过 ",b.skipped,"。",b.message||""]}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:i}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void q()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:s,disabled:x||o!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:(()=>void h()),disabled:x||o!==""||a.auto_rate_enabled&&!a.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[x?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(qe,{className:"h-4 w-4"}),"保存"]})]})})]})})},Le=({src:t,alt:s,className:r=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),ps=({account:t,editForm:s,setEditForm:r,saving:a,onClose:u,onSave:x,onRestartPause:o,longLogin:i,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:p,onCancelPasswordLogin:h,notifChannels:d,selectedChannelIds:q,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:f,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:B})=>{const T=(C,W)=>{r(F=>({...F,[C]:W}))},S=()=>void u(),w=()=>void x(),v=C=>T("remark",C.target.value),R=C=>T("cookie",C.target.value),y=()=>T("auto_confirm",!s.auto_confirm),A=C=>T("pause_duration",parseInt(C.target.value,10)||0),E=()=>void o(),X=()=>void b(),H=C=>T("username",C.target.value),G=C=>r(W=>({...W,login_password:C.target.value,clear_password:!1})),V=()=>T("showLoginPassword",!s.showLoginPassword),O=C=>r(W=>({...W,clear_password:C.target.checked,login_password:C.target.checked?"":W.login_password})),I=()=>T("show_browser",!s.show_browser),z=()=>void h(),Q=()=>void p(),$=()=>void L(),Z=C=>{k&&(U(C),B())},te=C=>{const W=q.includes(Number(C.id)),F=()=>Z(Number(C.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:F,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${W?"bg-brand border-brand":"bg-white border-gray-300"}`,children:W&&e.jsx(se,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ne.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(oe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:t.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:s.remark,onChange:v,placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:s.cookie,onChange:R,placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",s.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(se,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:y,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(Ae,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:A,placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),s.pause_duration>0&&!t.paused&&s.pause_duration===(t.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:E,className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(ns,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),i.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:i.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:i.loading||i.saving||!i.canOpen,onClick:X,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${i.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${i.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:s.username,onChange:H,placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:s.showLoginPassword?"text":"password",value:s.login_password,onChange:G,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:V,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(os,{className:"w-5 h-5"}):e.jsx(is,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:s.clear_password,onChange:O,className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:I,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:z,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:Q,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Le,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(d.length>0||g||f)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(ds,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(K,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),f&&!g&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:f}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:$,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:d.map(te)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:w,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(K,{className:"w-4 h-4 animate-spin"}):e.jsx(se,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},js=({account:t,settings:s,saving:r,onChange:a,onClose:u,onSave:x})=>{const o=d=>a({...s,...d}),i=()=>o({ai_enabled:!s.ai_enabled}),b=d=>o({max_discount_percent:parseInt(d.target.value,10)||0}),m=d=>o({max_discount_amount:parseInt(d.target.value,10)||0}),p=d=>o({max_bargain_rounds:parseInt(d.target.value,10)||1}),h=d=>o({custom_prompts:d.target.value});return ne.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ie,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:u,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(oe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ie,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:i,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:s.max_discount_percent,onChange:b,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:s.max_discount_amount,onChange:m,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:s.max_bargain_rounds,onChange:p,className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:s.custom_prompts,onChange:h,placeholder:`输入自定义的AI回复规则或风格指引... +import{r as l,j as e,b as ne,c as Ee}from"./react-vendor-C_od1ZSF.js";import{f as Ne,u as ve,r as Qe,h as $e,i as Ue,j as Be,k as Me,l as Oe,m as ze,n as Ge,o as We,p as Ve,s as Ke,q as He,t as Xe,v as Je,w as Ye,x as Ze,y as Fe,z as es,A as ss,B as ts,C as as}from"./index-CYPNW7Ux.js";import{X as oe,n as rs,f as K,o as ls,p as Se,q as Re,r as qe,s as se,t as Ae,K as ns,u as os,v as is,a as ds,w as ie,b as cs,i as Pe,x as xs,k as je,Q as we,R as us,y as ms,z as bs,F as ye,H as hs}from"./icons-vendor-ThcsWkZG.js";const _e=t=>({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),J=(t,s,r)=>t===s&&!r.aborted,fe=(t,s)=>t instanceof Error?t.message:s,pe=t=>t instanceof Error&&t.message==="请求已取消",ke=(t,s)=>!t&&s==="",gs=({account:t,onSaved:s})=>{const[r,a]=l.useState(()=>_e(t)),[u,x]=l.useState(!0),[o,i]=l.useState(!1),[b,m]=l.useState(""),[p,h]=l.useState(""),[d,q]=l.useState(null),[k,g]=l.useState(null),f=l.useRef(0),L=l.useRef(null);l.useEffect(()=>{var v;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;return L.current=w,a(_e(t)),q(null),h(""),i(!1),m(""),g(null),x(!0),Ne(t.id,{signal:w.signal}).then(R=>{J(f.current,S,w.signal)&&a(R)}).catch(R=>{J(f.current,S,w.signal)&&!pe(R)&&h(fe(R,"加载任务设置失败"))}).finally(()=>{J(f.current,S,w.signal)&&x(!1)}),(()=>w.abort())},[t.id]),l.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=l.useCallback(async()=>{var v;if(!ke(o,b))return;const S=++f.current;(v=L.current)==null||v.abort();const w=new AbortController;L.current=w,i(!0),h(""),g(null);try{const R=await ve(t.id,r,{signal:w.signal});if(!J(f.current,S,w.signal))return;a(R),s(R)}catch(R){J(f.current,S,w.signal)&&!pe(R)&&(h(fe(R,"保存失败")),g(()=>U))}finally{J(f.current,S,w.signal)&&i(!1)}},[t.id,r,s,b,o]),B=l.useCallback(async S=>{var R;if(!ke(o,b)||!t.enabled)return;const w=++f.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),q(null),g(null);try{await ve(t.id,r,{signal:v.signal});const y=await Qe(t.id,S,{signal:v.signal}),A=await Ne(t.id,{signal:v.signal});if(!J(f.current,w,v.signal))return;q(y.summary),a(A),s(A)}catch(y){J(f.current,w,v.signal)&&!pe(y)&&(h(fe(y,"任务执行失败")),g(()=>(()=>B(S))))}finally{J(f.current,w,v.signal)&&m("")}},[t.enabled,t.id,r,s,b,o]),T=l.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:u,saving:o,running:b,summary:d,error:p,retryAvailable:k!==null,setForm:a,save:U,run:B,retry:T}},Ce=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${t?"translate-x-6":""}`})}),fs=({account:t,onClose:s,onSaved:r})=>{const{form:a,loading:u,saving:x,running:o,error:i,summary:b,retryAvailable:m,setForm:p,save:h,run:d,retry:q}=gs({account:t,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(oe,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[u&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600",children:e.jsx(rs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"自动评价"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"持续扫描待评价订单,按订单执行;不是每日任务。"})]}),e.jsx(Ce,{checked:a.auto_rate_enabled,onChange:(()=>p(k=>({...k,auto_rate_enabled:!k.auto_rate_enabled}))),label:"自动评价"})]}),e.jsx("label",{className:"mt-4 block text-xs font-extrabold text-slate-600",children:"统一好评文案"}),e.jsx("textarea",{"aria-label":"统一好评文案",value:a.rate_content,maxLength:500,onChange:(k=>p(g=>({...g,rate_content:k.target.value}))),className:"mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100"}),e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-slate-400",children:["最近扫描:",a.last_rate_scan_at?new Date(a.last_rate_scan_at*1e3).toLocaleString("zh-CN"):"尚未执行"]}),e.jsxs("button",{type:"button",disabled:o!==""||!t.enabled,onClick:(()=>void d("auto_rate")),className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50",children:[o==="auto_rate"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(ls,{className:"h-4 w-4"}),"立即评价"]})]})]})]})}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600",children:e.jsx(Se,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-black text-slate-900",children:"每日自动擦亮"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-slate-500",children:"每个账号每天最多执行一次,按北京时间判断。"})]}),e.jsx(Ce,{checked:a.auto_polish_enabled,onChange:(()=>p(k=>({...k,auto_polish_enabled:!k.auto_polish_enabled}))),label:"每日自动擦亮"})]}),e.jsxs("div",{className:"mt-4 flex items-end justify-between gap-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs font-extrabold text-slate-600",children:"每日执行时间"}),e.jsx("input",{type:"time",value:a.polish_time,onChange:(k=>p(g=>({...g,polish_time:k.target.value}))),className:"mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400"})]}),e.jsxs("button",{type:"button",disabled:o!==""||!t.enabled,onClick:(()=>void d("auto_polish")),className:"flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50",children:[o==="auto_polish"?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(Re,{className:"h-4 w-4"}),"立即擦亮"]})]}),e.jsxs("div",{className:"mt-3 text-xs text-slate-400",children:["上次完成:",a.last_polish_at?new Date(a.last_polish_at*1e3).toLocaleString("zh-CN"):"尚未执行"]})]})]})}),b&&e.jsxs("div",{className:"rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900",children:["本次发现 ",b.found," 项,成功 ",b.success,",失败 ",b.failed,",跳过 ",b.skipped,"。",b.message||""]}),i&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700",children:[e.jsx("span",{children:i}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void q()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:s,disabled:x||o!=="",className:"flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50",children:"关闭"}),e.jsxs("button",{type:"button",onClick:(()=>void h()),disabled:x||o!==""||a.auto_rate_enabled&&!a.rate_content.trim(),className:"ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50",children:[x?e.jsx(K,{className:"h-4 w-4 animate-spin"}):e.jsx(qe,{className:"h-4 w-4"}),"保存"]})]})})]})})},Le=({src:t,alt:s,className:r=""})=>e.jsx("img",{src:t,alt:s,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),ps=({account:t,editForm:s,setEditForm:r,saving:a,onClose:u,onSave:x,onRestartPause:o,longLogin:i,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:p,onCancelPasswordLogin:h,notifChannels:d,selectedChannelIds:q,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:f,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:B})=>{const T=(C,W)=>{r(F=>({...F,[C]:W}))},S=()=>void u(),w=()=>void x(),v=C=>T("remark",C.target.value),R=C=>T("cookie",C.target.value),y=()=>T("auto_confirm",!s.auto_confirm),A=C=>T("pause_duration",parseInt(C.target.value,10)||0),E=()=>void o(),X=()=>void b(),H=C=>T("username",C.target.value),G=C=>r(W=>({...W,login_password:C.target.value,clear_password:!1})),V=()=>T("showLoginPassword",!s.showLoginPassword),O=C=>r(W=>({...W,clear_password:C.target.checked,login_password:C.target.checked?"":W.login_password})),I=()=>T("show_browser",!s.show_browser),z=()=>void h(),Q=()=>void p(),$=()=>void L(),Z=C=>{k&&(U(C),B())},te=C=>{const W=q.includes(Number(C.id)),F=()=>Z(Number(C.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:F,disabled:!k,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${W?"bg-brand border-brand":"bg-white border-gray-300"}`,children:W&&e.jsx(se,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:C.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[C.type,C.enabled?"":" · 已停用"]})]})]},C.id)};return ne.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(oe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:t.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:s.remark,onChange:v,placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:s.cookie,onChange:R,placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",s.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(se,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:y,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.auto_confirm?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(Ae,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:s.pause_duration,onChange:A,placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),s.pause_duration>0&&!t.paused&&s.pause_duration===(t.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:E,className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(ns,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),i.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:i.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:i.loading||i.saving||!i.canOpen,onClick:X,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${i.enabled?"bg-brand":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${i.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:s.username,onChange:H,placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:s.showLoginPassword?"text":"password",value:s.login_password,onChange:G,placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:V,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:s.showLoginPassword?e.jsx(os,{className:"w-5 h-5"}):e.jsx(is,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:s.clear_password,onChange:O,className:"w-4 h-4 accent-brand"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:I,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.show_browser?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),m.status==="processing"||m.status==="verification_required"?e.jsx("button",{type:"button",onClick:z,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:Q,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),m.message&&e.jsx("div",{className:`text-sm font-medium ${m.status==="failed"?"text-red-700":m.status==="success"?"text-green-700":"text-blue-800"}`,children:m.message}),m.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),m.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(Le,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(d.length>0||g||f)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(ds,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),g&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(K,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),f&&!g&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:f}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:$,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:d.map(te)})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:S,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:a,children:"取消"}),e.jsxs("button",{onClick:w,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:a,children:[a?e.jsx(K,{className:"w-4 h-4 animate-spin"}):e.jsx(se,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},js=({account:t,settings:s,saving:r,onChange:a,onClose:u,onSave:x})=>{const o=d=>a({...s,...d}),i=()=>o({ai_enabled:!s.ai_enabled}),b=d=>o({max_discount_percent:parseInt(d.target.value,10)||0}),m=d=>o({max_discount_amount:parseInt(d.target.value,10)||0}),p=d=>o({max_bargain_rounds:parseInt(d.target.value,10)||1}),h=d=>o({custom_prompts:d.target.value});return ne.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ie,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t.nickname||t.remark||t.id})]}),e.jsx("button",{onClick:u,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(oe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ie,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:i,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${s.ai_enabled?"bg-brand":"bg-gray-300"}`,"aria-label":"切换 AI 自动回复",children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${s.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:s.max_discount_percent,onChange:b,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:s.max_discount_amount,onChange:m,className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:s.max_bargain_rounds,onChange:p,className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:s.custom_prompts,onChange:h,placeholder:`输入自定义的AI回复规则或风格指引... 例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:u,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void x()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(K,{className:"w-4 h-4 animate-spin"}):e.jsx(qe,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},ws=(t,s)=>{if(!t||!s)return!1;const r=Date.parse(t),a=Date.parse(s);return Number.isFinite(r)&&Number.isFinite(a)&&at.map(r=>{const a=s[r.id];return!a||ws(r.runtime_updated_at,a.updated_at)?r:{...r,runtime_state:a.state,runtime_message:a.message||"",runtime_connected:a.connected,runtime_updated_at:a.updated_at}}),Ns=t=>{if(!t.enabled||t.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(t.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},vs=Ee.memo(function({account:s,refreshing:r,deleting:a,onRefreshProfile:u,onReauthorize:x,onEdit:o,onAI:i,onTasks:b,onToggle:m,onDelete:p}){const h=Ns(s),d=s.runtime_state==="auth_expired"||s.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[s.avatar_url?e.jsx("img",{src:s.avatar_url,alt:s.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(Pe,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${h.dot}`,children:s.runtime_state==="online"&&e.jsx(se,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:s.nickname||s.remark||`账号 ${s.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${h.badge}`,children:h.label}),s.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(ie,{className:"w-3 h-3"})," AI"]}),s.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(xs,{className:"h-3 w-3"})," 自动评价"]}),s.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(Se,{className:"h-3 w-3"})," 每日擦亮"]}),s.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(se,{className:"h-3 w-3"})," 自动确认发货"]}),s.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:s.profile_error,children:[e.jsx(je,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"text-sm font-medium text-gray-500",children:[e.jsx("p",{children:s.remark||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",s.id]})]}),s.runtime_message&&s.runtime_state!=="online"&&s.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${d?"text-red-700":"text-amber-700"}`,children:[e.jsx(je,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:s.runtime_message}),d&&e.jsxs("button",{type:"button",onClick:(()=>x(s)),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(we,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),s.paused&&e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700",children:[e.jsx(Ae,{className:"h-3 w-3"})," 暂停处理中"]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:(()=>u(s)),disabled:r,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(us,{className:`w-5 h-5 ${r?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>x(s)),className:`p-3 rounded-xl transition-colors ${d?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(we,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>o(s)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(ms,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>i(s)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(ie,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>b(s)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Re,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>m(s.id,s.enabled)),className:`p-3 rounded-xl transition-colors ${s.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:s.enabled?"停用账号":"启用账号",children:e.jsx(bs,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>p(s)),disabled:a,className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40",title:a?"删除中…":`删除账号 ${s.nickname||s.remark||s.id}`,children:a?e.jsx(K,{className:"w-5 h-5 animate-spin"}):e.jsx(ye,{className:"w-5 h-5"})})]})]})]})]})})}),_s=({account:t,deleting:s,error:r,onClose:a,onConfirm:u})=>ne.createPortal(e.jsx("div",{className:"modal-overlay-centered",role:"presentation",children:e.jsxs("div",{className:"h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal",role:"dialog","aria-modal":"true","aria-labelledby":"delete-account-title","aria-describedby":"delete-account-description",children:[e.jsxs("div",{className:"relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5",children:[e.jsx("div",{className:"absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl"}),e.jsxs("div",{className:"relative flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200",children:e.jsx(ye,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{id:"delete-account-title",className:"text-lg font-extrabold tracking-tight text-gray-950",children:"删除这个账号?"}),e.jsx("p",{id:"delete-account-description",className:"mt-1 text-xs leading-5 text-gray-600",children:"删除后,该账号的关联配置也会一并清理,此操作无法撤销。"})]}),e.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"关闭删除确认",children:e.jsx(oe,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3",children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:t.nickname||t.remark||"未命名账号"}),t.remark&&t.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",t.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",t.id]})]}),s&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3",role:"progressbar","aria-label":"正在删除账号",children:[e.jsx(K,{className:"h-5 w-5 flex-shrink-0 animate-spin text-brand"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-blue-950",children:"正在删除账号"}),e.jsx("div",{className:"mt-0.5 text-xs text-blue-700",children:"正在清理关联数据,请保持页面打开…"})]})]}),r&&e.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3",role:"alert",children:[e.jsx(je,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-red-800",children:"删除失败"}),e.jsx("div",{className:"mt-1 text-xs leading-5 text-red-700",children:r})]})]})]}),e.jsxs("div",{className:"flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4",children:[e.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50",children:"取消"}),e.jsx("button",{type:"button",onClick:(()=>void u()),disabled:s,className:"flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400",children:s?e.jsxs(e.Fragment,{children:[e.jsx(K,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(ye,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),ks=({faceQrUrl:t,verificationScreenshot:s})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(hs,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:t?e.jsx("img",{src:t,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):s?e.jsx("img",{src:s,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(K,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Cs=({target:t,status:s,codeUrl:r,errorMessage:a,faceQrUrl:u,verificationScreenshot:x,onClose:o})=>ne.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:o,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors","aria-label":"关闭二维码登录",children:e.jsx(oe,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:t?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:t?`请用闲鱼APP扫码,为「${t.nickname||t.remark||t.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${s==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[s==="loading"&&e.jsx(K,{className:"w-10 h-10 text-brand animate-spin"}),s==="waiting"&&e.jsx(Le,{src:r,alt:"闲鱼登录二维码",className:"p-2"}),s==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(se,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),s==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:a||"请关闭窗口后重新发起扫码登录。"})]}),s==="verification"&&e.jsx(ks,{faceQrUrl:u,verificationScreenshot:x})]}),s!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),Ss=(t,s)=>t.map(r=>{var a,u,x,o,i;return{...r,ai_enabled:((a=s[r.id])==null?void 0:a.ai_enabled)??!1,max_discount_percent:((u=s[r.id])==null?void 0:u.max_discount_percent)??10,max_discount_amount:((x=s[r.id])==null?void 0:x.max_discount_amount)??100,max_bargain_rounds:((o=s[r.id])==null?void 0:o.max_bargain_rounds)??3,custom_prompts:((i=s[r.id])==null?void 0:i.custom_prompts)??""}}),Rs=()=>{const[t,s]=l.useState([]),[r,a]=l.useState(!0),u=l.useRef(0),x=l.useRef(null),o=l.useCallback(async()=>{var m;const i=++u.current;(m=x.current)==null||m.abort();const b=new AbortController;x.current=b,a(!0);try{const p={signal:b.signal},[h,d]=await Promise.allSettled([$e(p),Ue(p)]);if(i!==u.current)return;if(h.status==="rejected")throw h.reason;const q=d.status==="fulfilled"?d.value:{};d.status==="rejected"&&console.error("加载 AI 设置失败:",d.reason),s(Ss(h.value,q))}catch(p){i===u.current&&!b.signal.aborted&&console.error("加载账号失败:",p)}finally{i===u.current&&a(!1)}},[]);return l.useEffect(()=>{let i=!1,b=null;const m=new AbortController,p=async()=>{try{const d=await Be({signal:m.signal,timeoutMs:1e4});i||s(q=>ys(q,d))}catch(d){i||console.error("加载账号运行状态失败:",d)}finally{i||(b=window.setTimeout(()=>void p(),2e3))}};return o().finally(()=>{i||p()}),()=>{var d;i=!0,m.abort(),u.current+=1,(d=x.current)==null||d.abort(),b!==null&&window.clearTimeout(b)}},[o]),{accounts:t,setAccounts:s,loading:r,loadAccounts:o}},qs=new Set(["expired","cancelled","error","not_found"]),As=()=>{let t=0;return{next:()=>(t+=1,t),cancel:()=>{t+=1},isCurrent:(s=>s===t)}},Ps=(t={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let s=null,r=null,a=-1,u=0;const x=()=>{u+=1,r==null||r.abort(),r=null,s!==null&&(t.clearInterval(s),s=null)};return{start:(i,b,m,p=2e3)=>{x();const h=u;r=new AbortController;const d=r.signal;s=t.setInterval(()=>{a===h||h!==u||(a=h,(async()=>{var q,k;try{const g=await b(i,d);if(g.status==="success"){x(),await m.onSuccess(g);return}if(g.status==="scanned"){(q=m.onScanned)==null||q.call(m,g);return}if(g.status==="verification_required"){(k=m.onVerificationRequired)==null||k.call(m,g);return}g.status&&qs.has(g.status)&&(x(),m.onTerminalError(g))}catch(g){if(d.aborted||h!==u)return;x(),m.onPollError(g)}finally{a===h&&(a=-1)}})())},p)},stop:x,isActive:(()=>s!==null)}},Ls=({onLoginSuccess:t})=>{const[s,r]=l.useState(!1),[a,u]=l.useState(""),[x,o]=l.useState("pending"),[i,b]=l.useState(""),[m,p]=l.useState(""),[h,d]=l.useState(""),[q,k]=l.useState(null),g=l.useRef(null),f=l.useRef(null),L=l.useRef(null),U=l.useRef(null);g.current===null&&(g.current=Ps()),f.current===null&&(f.current=As());const B=()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},T=()=>{var y;(y=g.current)==null||y.stop()},S=()=>{var y,A;(y=L.current)==null||y.abort(),(A=f.current)==null||A.cancel(),T(),B(),r(!1)},w=()=>{B(),U.current=window.setTimeout(()=>{U.current=null,r(!1),t()},1e3)};l.useEffect(()=>()=>{var A,E;T(),(A=f.current)==null||A.cancel(),(E=L.current)==null||E.abort(),B()},[]);const v=async(y,A)=>{const E=await ze(y,A==null?void 0:A.id);if(!E.success||!E.account_id)throw new Error(E.message||"保存扫码授权失败");return E.account_id};return{showQRModal:s,qrCodeUrl:a,qrStatus:x,qrErrorMessage:i,verificationScreenshot:m,faceQrUrl:h,qrReauthTarget:q,startQRLogin:async y=>{var H,G,V,O;T(),(H=L.current)==null||H.abort();const A=new AbortController;L.current=A;const E=f.current.next();B();const X=y||null;k(X),r(!0),o("loading"),b(""),u(""),p(""),d("");try{const I=await Me({signal:A.signal});if(!((G=f.current)!=null&&G.isCurrent(E)))return;if(!I.success||!I.qr_code_url||!I.session_id)throw new Error(I.message||"闲鱼未返回可用的登录二维码");const z=I.session_id;u(I.qr_code_url),o("waiting"),(V=g.current)==null||V.start(z,Oe,{onSuccess:(async()=>{try{await v(z,X)}catch(Q){console.error("保存扫码授权失败",Q),o("error");return}o("success"),w()}),onScanned:(()=>{o("waiting")}),onTerminalError:(()=>{o("error")}),onPollError:(Q=>{console.error("轮询扫码状态失败",Q),o("error")}),onVerificationRequired:(Q=>{o("verification"),Q.face_qr_url&&d(Q.face_qr_url),Q.verification_screenshot&&p(Q.verification_screenshot)})})}catch(I){if(!((O=f.current)!=null&&O.isCurrent(E))||A.signal.aborted)return;b(I instanceof Error?I.message:"二维码获取失败,请稍后重试"),o("error")}finally{L.current===A&&(L.current=null)}},closeQRModal:S}},Is=(t,s)=>t!==(s.pause_duration||0),Ts=(t,s)=>{const r=s.username!==(t.username||""),a=s.show_browser!==(t.show_browser||!1),u=s.login_password!=="",x=s.clear_password===!0;if(!r&&!a&&!u&&!x)return null;const o={username:s.username,show_browser:s.show_browser};return x?o.clear_password=!0:u&&(o.login_password=s.login_password),o},Y=(t,s,r,a)=>t===s&&r===a,Ds=t=>t.status==="success"?{sessionId:"",status:"success",message:t.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}:t.status==="processing"||t.status==="verification_required"?{sessionId:"",status:t.status,message:t.message||(t.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:t.qr_code_url||""}:{sessionId:"",status:"failed",message:t.error||t.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""},Es=(t,s)=>t&&s,Qs=({editingAccount:t,setEditingAccount:s,setActiveModal:r,editForm:a,setEditForm:u,loadAccounts:x})=>{const[o,i]=l.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[b,m]=l.useState([]),[p,h]=l.useState([]),[d,q]=l.useState(!1),[k,g]=l.useState(!1),[f,L]=l.useState(!1),[U,B]=l.useState(""),[T,S]=l.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[w,v]=l.useState(!1),[R,y]=l.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),A=l.useRef(0),E=l.useRef(null),X=l.useRef(0),H=l.useRef(null),G=l.useRef(0),V=l.useRef(null),O=l.useRef(0),I=l.useRef(""),z=l.useRef(null),Q=l.useRef(null),$=l.useCallback(()=>{Q.current!==null&&(window.clearTimeout(Q.current),Q.current=null)},[]),Z=l.useCallback(async n=>{var M;const c=++A.current;(M=E.current)==null||M.abort();const _=new AbortController;E.current=_,g(!0),q(!1),L(!1),B("");const[D,N]=await Promise.allSettled([Ge({signal:_.signal}),We(n,{signal:_.signal})]);Y(c,A.current,n,n)&&(D.status==="fulfilled"?m(D.value.data||[]):(m([]),B("通知渠道列表加载失败,请重试")),N.status==="fulfilled"?(h(N.value||[]),q(!0)):(h([]),B("通知绑定加载失败;本次保存不会修改现有绑定")),g(!1))},[]),te=l.useCallback(n=>{h(c=>c.includes(n)?c.filter(_=>_!==n):[...c,n]),L(!0)},[]),C=l.useCallback(async n=>{var N,M;const c=++X.current;(N=H.current)==null||N.abort();const _=new AbortController;H.current=_,O.current+=1,I.current=n.id,(M=z.current)==null||M.abort(),$(),y({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),s(n),u({remark:n.remark||"",cookie:n.value||"",auto_confirm:n.auto_confirm||!1,pause_duration:n.pause_duration||0,username:n.username||"",login_password:n.login_password||"",show_browser:n.show_browser||!1,showLoginPassword:!1,clear_password:!1}),r("edit"),i({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,D]=await Promise.allSettled([Z(n.id),Ve(n.id,{signal:_.signal})]);c===X.current&&(D.status==="fulfilled"?i({loading:!1,saving:!1,canOpen:D.value.can_open_long_login,enabled:D.value.enabled,error:""}):i({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[$,Z,r,u,s]),W=l.useCallback(async()=>{if(!t||o.loading||o.saving||!o.canOpen)return;const n=!o.enabled;i(c=>({...c,saving:!0,error:""}));try{const c=await Ke(t.id,n);i({loading:!1,saving:!1,canOpen:c.can_open_long_login,enabled:c.enabled,error:""})}catch(c){i(_=>({..._,saving:!1,error:c instanceof Error?c.message:"保存登录信息设置失败"}))}},[t,o]),F=l.useCallback(async n=>{var D;const c=++G.current;(D=V.current)==null||D.abort();const _=new AbortController;V.current=_,s(n),r("ai-settings"),v(!0);try{const N=await He(n.id,{signal:_.signal});if(!Y(c,G.current,n.id,n.id))return;S({ai_enabled:N.ai_enabled??!1,max_discount_percent:N.max_discount_percent??10,max_discount_amount:N.max_discount_amount??100,max_bargain_rounds:N.max_bargain_rounds??3,custom_prompts:N.custom_prompts??""})}catch(N){Y(c,G.current,n.id,n.id)&&console.error("加载 AI 设置失败:",N)}finally{Y(c,G.current,n.id,n.id)&&v(!1)}},[r,s]),de=l.useCallback(async()=>{if(!(!t||w)){v(!0);try{await Xe(t.id,T),r(null),await x()}catch(n){console.error("更新 AI 设置失败:",n)}finally{v(!1)}}},[T,t,x,w,r]),ce=l.useCallback(async()=>{if(!(!t||w)){v(!0);try{const n={};a.remark!==(t.remark||"")&&(n.remark=a.remark),a.cookie&&a.cookie!==(t.value||"")&&(n.cookie=a.cookie),a.auto_confirm!==t.auto_confirm&&(n.auto_confirm=a.auto_confirm),Is(a.pause_duration,t)&&(n.pause_duration=a.pause_duration);const c=Ts(t,a);c&&Object.assign(n,c),Es(d,f)&&(n.channel_ids=p),Object.keys(n).length>0&&await Je(t.id,n),r(null),await x()}catch(n){console.error("更新账号失败:",n)}finally{v(!1)}}},[f,d,a,t,x,p,w,r]),xe=l.useCallback(async()=>{if(!(!t||a.pause_duration<=0||w)){v(!0);try{const n=await Ye(t.id,a.pause_duration);s(c=>c&&{...c,pause_duration:a.pause_duration,paused:(n==null?void 0:n.paused)===!0,paused_until:Number((n==null?void 0:n.paused_until)||0)}),await x()}catch(n){console.error("重新暂停失败:",n)}finally{v(!1)}}},[a.pause_duration,t,x,w,s]),ae=l.useCallback(async(n,c,_)=>{var N;(N=z.current)==null||N.abort();const D=new AbortController;z.current=D;try{const M=await Ze(n,D.signal);if(!Y(c,O.current,_,I.current))return;const le={...Ds(M),sessionId:n};if(M.status==="success"){$(),y(le),u(he=>({...he,login_password:"",showLoginPassword:!1})),await x();return}if(M.status==="processing"||M.status==="verification_required"){y(le),$(),Q.current=window.setTimeout(()=>void ae(n,c,_),1500);return}$(),y(le)}catch(M){if(!Y(c,O.current,_,I.current))return;$(),y({sessionId:n,status:"failed",message:M instanceof Error?M.message:"查询密码登录状态失败",qrCodeUrl:""})}},[$,x,u]),ue=l.useCallback(async()=>{var D;if(!t)return;const n=a.username.trim();if(!n||!a.login_password)return;$(),(D=z.current)==null||D.abort();const c=++O.current;I.current=t.id;const _=new AbortController;z.current=_,y({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const N=await Fe({account_id:t.id,account:n,password:a.login_password,show_browser:a.show_browser},{signal:_.signal});if(!Y(c,O.current,t.id,I.current))return;if(!N.success||!N.session_id)throw new Error(N.message||"无法启动密码登录");y({sessionId:N.session_id,status:"processing",message:N.message||"登录处理中",qrCodeUrl:""}),await ae(N.session_id,c,t.id)}catch(N){if(!Y(c,O.current,t.id,I.current))return;y({sessionId:"",status:"failed",message:N instanceof Error?N.message:"启动密码登录失败",qrCodeUrl:""})}},[$,a.login_password,a.show_browser,a.username,t,ae]),re=l.useCallback(async()=>{var c;const n=R.sessionId;O.current+=1,I.current="",(c=z.current)==null||c.abort(),$(),n&&await es(n).catch(()=>{}),y({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[$,R.sessionId]),me=l.useCallback(async()=>{var n,c,_;(n=E.current)==null||n.abort(),X.current+=1,(c=H.current)==null||c.abort(),(_=V.current)==null||_.abort(),(R.status==="processing"||R.status==="verification_required")&&await re(),r(null)},[re,R.status,r]),be=l.useCallback(()=>{var n;G.current+=1,(n=V.current)==null||n.abort(),r(null)},[r]);return l.useEffect(()=>(()=>{var n,c,_,D;(n=E.current)==null||n.abort(),(c=H.current)==null||c.abort(),(_=V.current)==null||_.abort(),(D=z.current)==null||D.abort(),$()}),[$]),{longLogin:o,notifChannels:b,selectedChannelIds:p,bindingsLoaded:d,bindingsLoading:k,bindingsDirty:f,bindingsLoadError:U,aiSettings:T,saving:w,passwordLoginView:R,setAiSettings:S,setBindingsDirty:L,setEditForm:u,openEditModal:C,closeEditModal:me,openAIModal:F,closeAIModal:be,loadNotificationBindings:Z,toggleNotificationChannel:te,handleLongLoginToggle:W,handleSaveAISettings:de,handleSaveEdit:ce,handleRestartPause:xe,handlePasswordLogin:ue,handleCancelPasswordLogin:re}},Ms=()=>{const{accounts:t,setAccounts:s,loading:r,loadAccounts:a}=Rs(),[u,x]=l.useState(""),[o,i]=l.useState(""),[b,m]=l.useState(""),[p,h]=l.useState(null),[d,q]=l.useState(""),[k,g]=l.useState(null),[f,L]=l.useState(null),[U,B]=l.useState(null),[T,S]=l.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),w=Qs({editingAccount:f,setEditingAccount:L,setActiveModal:g,editForm:T,setEditForm:S,loadAccounts:a}),{longLogin:v,notifChannels:R,selectedChannelIds:y,bindingsLoaded:A,bindingsLoading:E,bindingsLoadError:X,aiSettings:H,saving:G,passwordLoginView:V,setAiSettings:O,setBindingsDirty:I,openEditModal:z,closeEditModal:Q,openAIModal:$,closeAIModal:Z,loadNotificationBindings:te,toggleNotificationChannel:C,handleLongLoginToggle:W,handleSaveAISettings:F,handleSaveEdit:de,handleRestartPause:ce,handlePasswordLogin:xe,handleCancelPasswordLogin:ae}=w,ue=Ls({onLoginSuccess:a}),{showQRModal:re,qrCodeUrl:me,qrStatus:be,qrErrorMessage:n,verificationScreenshot:c,faceQrUrl:_,qrReauthTarget:D,startQRLogin:N,closeQRModal:M}=ue,le=async(j,P)=>{await ss(j,!P),a()},he=j=>{b||(q(""),h(j))},Ie=()=>{b||(q(""),h(null))},Te=async()=>{const j=p;if(!(!j||b)){m(j.id),q("");try{await as(j.id),s(P=>P.filter(ee=>ee.id!==j.id)),h(null)}catch(P){console.error("删除账号失败:",P),q((P==null?void 0:P.message)||"删除账号失败,请稍后重试")}finally{m("")}}},De=async j=>{i(j.id);try{const P=await ts(j.id);P!=null&&P.profile_error&&alert("资料刷新失败:"+P.profile_error),await a()}catch(P){console.error("刷新账号资料失败:",P),alert((P==null?void 0:P.message)||"刷新账号资料失败,请先重新授权该账号")}finally{i("")}};if(r)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(K,{className:"w-8 h-8 text-brand animate-spin"})});const ge=t.filter(j=>{const P=u.trim().toLowerCase();return P?[j.id,j.nickname,j.remark,j.username,j.runtime_message].some(ee=>(ee||"").toLowerCase().includes(P)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:u,onChange:(j=>x(j.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>N()),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(we,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",ge.length," / ",t.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[ge.map(j=>e.jsx(vs,{account:j,refreshing:o===j.id,deleting:b===j.id,onRefreshProfile:De,onReauthorize:N,onEdit:z,onAI:$,onTasks:B,onToggle:le,onDelete:he},j.id)),t.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Pe,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),t.length>0&&ge.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),U&&ne.createPortal(e.jsx(fs,{account:U,onClose:(()=>B(null)),onSaved:(j=>{s(P=>P.map(ee=>ee.id===U.id?{...ee,auto_rate_enabled:j.auto_rate_enabled,rate_content:j.rate_content,auto_polish_enabled:j.auto_polish_enabled,polish_time:j.polish_time,last_rate_scan_at:j.last_rate_scan_at,last_polish_date:j.last_polish_date,last_polish_at:j.last_polish_at}:ee))})}),document.body),p&&e.jsx(_s,{account:p,deleting:b===p.id,error:d,onClose:Ie,onConfirm:Te}),re&&e.jsx(Cs,{target:D,status:be,codeUrl:me,errorMessage:n,faceQrUrl:_,verificationScreenshot:c,onClose:M}),k==="edit"&&f&&e.jsx(ps,{account:f,editForm:T,setEditForm:S,saving:G,onClose:Q,onSave:de,onRestartPause:ce,longLogin:v,onToggleLongLogin:W,passwordLoginView:V,onPasswordLogin:xe,onCancelPasswordLogin:ae,notifChannels:R,selectedChannelIds:y,bindingsLoaded:A,bindingsLoading:E,bindingsLoadError:X,onRetryBindings:(()=>te(f.id)),onToggleChannel:C,onSettingsDirty:(()=>I(!0))}),k==="ai-settings"&&f&&e.jsx(js,{account:f,settings:H,saving:G,onChange:O,onClose:Z,onSave:F})]})};export{Ms as default}; diff --git a/internal/webui/static/assets/CardList-CV-IXa79.js b/internal/webui/static/assets/CardList-D5uSws-z.js similarity index 99% rename from internal/webui/static/assets/CardList-CV-IXa79.js rename to internal/webui/static/assets/CardList-D5uSws-z.js index 10d43b3..5cc8e42 100644 --- a/internal/webui/static/assets/CardList-CV-IXa79.js +++ b/internal/webui/static/assets/CardList-D5uSws-z.js @@ -1,4 +1,4 @@ -import{b as z,j as e,r}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Y,J as $,Y as Q,f as U,N as V,C as H,_ as Z,$ as W,a0 as K,a1 as ee,I as te,a2 as ae,V as se,F as le,P as ne,r as re}from"./icons-vendor-ThcsWkZG.js";import{K as oe,L as ie,M as de,N as J,O as ce,P as xe}from"./index-DK02p8DH.js";const pe=({dataCards:c,downloadCardTemplate:d,...s})=>{var x;const u=a=>{var m;s.setBatchFile(((m=a.target.files)==null?void 0:m[0])||null)},p=a=>{s.setAppendContent(a.target.value)},_=a=>{s.setAppendTargetId(a.target.value)},j=()=>s.closeBatchModal(),f=()=>s.setBatchTab("create"),i=()=>s.setBatchTab("append"),A=()=>void s.handleRetryBatchCreate(),o=()=>void s.handleRetryBatchAppend(),y=s.batchResult&&"rows"in s.batchResult?s.batchResult:null,N=a=>e.jsxs("option",{value:String(a.id),children:[a.name,"(ID: ",a.id,")"]},a.id),b=()=>void s.handleBatchCreate(),l=()=>void s.handleBatchAppend();return s.showBatchModal?z.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:j,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:f,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Y,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:i,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx($,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),s.batchTab==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),"。 类型填 text/data/image;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:d,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(Q,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx($,{className:"w-4 h-4"}),s.batchFile?s.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=s.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!s.batchFile||s.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(a=>!a.success).map(a=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",a.row_no," 行「",a.name,"」:",a.error]},a.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:c.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:s.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:c.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:s.appendContent,onChange:p,placeholder:`VIP-001 +import{b as z,j as e,r}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Y,J as $,Y as Q,f as U,N as V,C as H,_ as Z,$ as W,a0 as K,a1 as ee,I as te,a2 as ae,V as se,F as le,P as ne,r as re}from"./icons-vendor-ThcsWkZG.js";import{K as oe,L as ie,M as de,N as J,O as ce,P as xe}from"./index-CYPNW7Ux.js";const pe=({dataCards:c,downloadCardTemplate:d,...s})=>{var x;const u=a=>{var m;s.setBatchFile(((m=a.target.files)==null?void 0:m[0])||null)},p=a=>{s.setAppendContent(a.target.value)},_=a=>{s.setAppendTargetId(a.target.value)},j=()=>s.closeBatchModal(),f=()=>s.setBatchTab("create"),i=()=>s.setBatchTab("append"),A=()=>void s.handleRetryBatchCreate(),o=()=>void s.handleRetryBatchAppend(),y=s.batchResult&&"rows"in s.batchResult?s.batchResult:null,N=a=>e.jsxs("option",{value:String(a.id),children:[a.name,"(ID: ",a.id,")"]},a.id),b=()=>void s.handleBatchCreate(),l=()=>void s.handleBatchAppend();return s.showBatchModal?z.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:j,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:f,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Y,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:i,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${s.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx($,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),s.batchTab==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),"。 类型填 text/data/image;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:d,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(Q,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx($,{className:"w-4 h-4"}),s.batchFile?s.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=s.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!s.batchFile||s.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(a=>!a.success).map(a=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",a.row_no," 行「",a.name,"」:",a.error]},a.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:c.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:s.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:c.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:s.appendContent,onChange:p,placeholder:`VIP-001 VIP-002 VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",s.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),s.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.appendError}),e.jsx("button",{type:"button",onClick:o,disabled:s.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",s.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:j,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),s.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!s.batchFile||s.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[s.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx($,{className:"w-4 h-4"}),s.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:l,disabled:!s.appendTargetId||s.appendPreview.length===0||s.batchBusy||c.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[s.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(V,{className:"w-4 h-4"}),s.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},me=({type:c})=>{switch(c){case"text":return e.jsx(K,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(W,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(Z,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(H,{className:"w-5 h-5 text-gray-500"})}},he=(c,d,s)=>{const u=s.trim().toLocaleLowerCase();return c.filter(p=>(!d||p.type===d)&&(!u||p.name.toLocaleLowerCase().includes(u)))},X=c=>c.split(` `).map(d=>d.trim()).filter(Boolean),ue=(c,d,s)=>!!(c&&X(d).length>0&&!s),F=(c,d,s,u)=>c===d&&s===u,be=()=>{const[c,d]=r.useState([]),[s,u]=r.useState(!0),p=r.useRef(0),_=r.useRef(null),j=r.useCallback(async()=>{var A;const f=++p.current;(A=_.current)==null||A.abort();const i=new AbortController;_.current=i,u(!0);try{const o=await oe({signal:i.signal});if(f!==p.current)return;d(o)}catch(o){f===p.current&&!i.signal.aborted&&console.error("加载卡密库存失败:",o)}finally{f===p.current&&u(!1)}},[]);return r.useEffect(()=>(j(),()=>{var i;p.current+=1,(i=_.current)==null||i.abort()}),[j]),{cards:c,setCards:d,loading:s,loadCards:j}},ge=c=>{const d=c.dataCards,s=c.loadCards,[u,p]=r.useState(!1),[_,j]=r.useState("create"),[f,i]=r.useState(null),[A,o]=r.useState(null),[y,N]=r.useState(!1),[b,l]=r.useState(""),[x,a]=r.useState(""),[m,E]=r.useState(null),[M,R]=r.useState(""),w=r.useRef(0),T=r.useRef(null),P=r.useRef(""),L=r.useMemo(()=>X(x),[x]),n=r.useCallback(()=>{var h;j("create"),i(null),o(null),l((h=d[0])!=null&&h.id?String(d[0].id):""),a(""),E(null),R(""),p(!0)},[d]),t=r.useCallback(()=>{var h;w.current+=1,(h=T.current)==null||h.abort(),N(!1),p(!1)},[]),g=r.useCallback(async()=>{var v;if(!f||y)return;const h=++w.current;(v=T.current)==null||v.abort();const B=new AbortController;T.current=B,N(!0),o(null);try{const I=await ie(f,{signal:B.signal});if(!F(h,w.current,"",""))return;o(I),I.created>0&&await s()}catch(I){if(!F(h,w.current,"",""))return;o({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(h,w.current,"","")&&N(!1)}},[y,f,s]),k=r.useCallback(async()=>{var I;if(!ue(b,x,y))return;const h=b,B=++w.current;P.current=h,(I=T.current)==null||I.abort();const v=new AbortController;T.current=v,N(!0),E(null),R("");try{const O=await de(h,x,{signal:v.signal});if(!F(B,w.current,h,b))return;E({added:O.added}),a(""),await s()}catch(O){if(!F(B,w.current,h,b))return;R((O==null?void 0:O.message)||"追加失败")}finally{F(B,w.current,h,b)&&N(!1)}},[x,b,y,s]),S=r.useCallback(async()=>{await g()},[g]),C=r.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:p,batchTab:_,setBatchTab:j,batchFile:f,setBatchFile:i,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:l,appendContent:x,setAppendContent:a,appendResult:m,appendError:M,appendPreview:L,openBatchModal:n,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),D=(c,d)=>c instanceof Error?c.message:d,ye=({cards:c,loadCards:d})=>{const[s,u]=r.useState(!1),[p,_]=r.useState(!1),[j,f]=r.useState(null),[i,A]=r.useState({}),[o,y]=r.useState(q),[N,b]=r.useState(""),[l,x]=r.useState(""),a=r.useMemo(()=>c.filter(n=>n.type==="data"),[c]),m=r.useMemo(()=>he(c,N,l),[c,l,N]),E=r.useCallback(n=>{var t,g,k,S,C;f(n),A({id:n.id,name:n.name||"",type:n.type||"text",api_url:((t=n.api_config)==null?void 0:t.url)||"",api_method:((g=n.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=n.api_config)==null?void 0:k.timeout)||10,api_headers:((S=n.api_config)==null?void 0:S.headers)||"",api_params:((C=n.api_config)==null?void 0:C.params)||"",text_content:n.text_content||"",data_content:n.data_content||"",image_url:n.image_url||"",delay_seconds:n.delay_seconds||0,description:n.description||"",enabled:n.enabled}),u(!0)},[]),M=r.useCallback(async()=>{var n,t,g,k,S,C,h,B;if(j){if(!((n=i.name)!=null&&n.trim())){alert("请输入卡密名称");return}if(!i.type){alert("请选择卡密类型");return}try{const v={name:i.name.trim(),type:i.type,description:(t=i.description)==null?void 0:t.trim(),delay_seconds:i.delay_seconds||0,enabled:i.enabled??!0};i.type==="api"?v.api_config={url:((g=i.api_url)==null?void 0:g.trim())||"",method:i.api_method||"GET",timeout:i.api_timeout||10,headers:((k=i.api_headers)==null?void 0:k.trim())||void 0,params:((S=i.api_params)==null?void 0:S.trim())||void 0}:i.type==="text"?v.text_content=((C=i.text_content)==null?void 0:C.trim())||"":i.type==="data"?v.data_content=((h=i.data_content)==null?void 0:h.trim())||"":i.type==="image"&&(v.image_url=((B=i.image_url)==null?void 0:B.trim())||""),await J(j.id,v),u(!1),await d()}catch(v){console.error("更新卡密失败:",v),alert(D(v,"更新失败,请重试"))}}},[i,d,j]),R=r.useCallback(async n=>{if(confirm("确认删除该卡密吗?"))try{await ce(n),await d()}catch(t){console.error("删除卡密失败:",t),alert(D(t,"删除失败,请重试"))}},[d]),w=r.useCallback(async()=>{if(!o.name.trim()){alert("请输入卡密名称");return}if(!o.content.trim()){alert(o.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const n={name:o.name.trim(),type:o.type,description:o.description.trim(),enabled:o.enabled,delay_seconds:o.delay_seconds};o.type==="text"&&(n.text_content=o.content.trim()),o.type==="data"&&(n.data_content=o.content.trim()),o.type==="image"&&(n.image_url=o.content.trim()),o.type==="api"&&(n.api_config={url:o.content.trim(),method:o.api_method,timeout:o.api_timeout,headers:o.api_headers.trim()||void 0,params:o.api_params.trim()||void 0}),await xe(n),_(!1),y(q()),await d()}catch(n){console.error("添加卡密失败:",n),alert(D(n,"添加失败,请重试"))}},[o,d]),T=r.useCallback(async n=>{try{await J(n.id,{...n,enabled:!n.enabled}),await d()}catch(t){console.error("切换状态失败:",t)}},[d]),P=r.useCallback(async n=>{try{await navigator.clipboard.writeText(String(n)),alert(`已复制卡密组ID:${n}`)}catch{prompt("复制卡密组ID",String(n))}},[]),L=r.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 diff --git a/internal/webui/static/assets/Chat-ChmGl-XK.js b/internal/webui/static/assets/Chat-BLyP9Pyt.js similarity index 99% rename from internal/webui/static/assets/Chat-ChmGl-XK.js rename to internal/webui/static/assets/Chat-BLyP9Pyt.js index c35fbee..059b0b9 100644 --- a/internal/webui/static/assets/Chat-ChmGl-XK.js +++ b/internal/webui/static/assets/Chat-BLyP9Pyt.js @@ -1 +1 @@ -import{j as e,c as W0,r as a}from"./react-vendor-C_od1ZSF.js";import{ap as R0,aq as M0,ar as q0,as as G0,at as X0,h as Y0,j as T0}from"./index-DK02p8DH.js";import{f as i0,ak as K0,al as $0,M as L0,I as ee,R as te,ad as E0,k as se,am as ie,s as ae,an as ne,ao as re,ah as le}from"./icons-vendor-ThcsWkZG.js";const U0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],ce=m=>m,oe=new Map(U0.map(([m,g])=>[m,g])),pe=m=>m.split(/(\[[^\]]+\])/g).map((g,i)=>{const r=g.startsWith("[")?oe.get(g.slice(1,-1)):void 0;return r?e.jsx("img",{src:r,alt:g,title:g,className:"mx-0.5 inline-block h-7 w-7 align-middle"},i):e.jsx(W0.Fragment,{children:g},i)}),me=(m,g,i)=>{const r=g.trim().toLowerCase();return m.filter(x=>i&&x.unread_count<=0?!1:r?[x.buyer_name,x.buyer_id,x.item_title,x.last_message].some(N=>(N||"").toLowerCase().includes(r)):!0)},ge=(m,g)=>{const i=new Set(m.map(r=>r.message_key));return[...g.filter(r=>!i.has(r.message_key)),...m]},D0=(m,g)=>{const i=m.findIndex(r=>r.message_key===g.message_key);return i<0?[...m,g]:m.map((r,x)=>x===i?g:r)},j=(m,g,i)=>m===g&&!i.aborted,Q=m=>m instanceof Error&&m.message==="请求已取消",de=m=>{if(!m)return"";const g=new Date(m<1e10?m*1e3:m),i=new Date;return g.toDateString()===i.toDateString()?g.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):g.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},xe=m=>new Date(m<1e10?m*1e3:m).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),_e=()=>{const[m,g]=a.useState([]),[i,r]=a.useState(""),[x,N]=a.useState({}),[b,P]=a.useState(""),[E,v]=a.useState([]),[Z,h0]=a.useState(""),[M,u0]=a.useState(!1),[q,a0]=a.useState(""),[b0,T]=a.useState(!0),[L,D]=a.useState(!1),[z,V]=a.useState(!1),[W,n0]=a.useState(!1),[r0,l0]=a.useState(),[G,U]=a.useState({}),[X,Y]=a.useState({}),[K,c0]=a.useState(!1),[o0,f0]=a.useState(!1),[C,A]=a.useState(!1),[j0,w]=a.useState(""),[w0,H]=a.useState("connecting"),[F,$]=a.useState(null),[s,u]=a.useState(null),O=a.useRef(""),e0=a.useRef(""),p0=a.useRef(null),N0=a.useRef({accountID:"",chatID:""}),C0=a.useRef(!0),m0=a.useRef(!1),y0=a.useRef(null),I0=a.useRef(new Set),O0=a.useRef(0),v0=a.useRef(null),J=a.useRef(0),k0=a.useRef(null),t0=a.useRef(0),g0=a.useRef(null),k=a.useRef(0),B=a.useRef(null);a.useEffect(()=>{O.current=i},[i]),a.useEffect(()=>{e0.current=b},[b]);const s0=a.useCallback(async t=>{var n;const l=++O0.current;(n=v0.current)==null||n.abort();const c=new AbortController;v0.current=c;try{const p=await R0(t,void 0,{signal:c.signal},!0);return j(O0.current,l,c.signal)?(N(o=>({...o,[t]:p.sessions})),U(o=>({...o,[t]:p.next_cursor})),Y(o=>({...o,[t]:p.has_more})),p.sessions):[]}catch(p){return j(O0.current,l,c.signal)&&!Q(p)&&w(p instanceof Error?p.message:"同步会话失败"),[]}},[]);a.useEffect(()=>{const t=new AbortController;return(async()=>{var c;T(!0);try{const[n,p]=await Promise.all([Y0({signal:t.signal}),T0({signal:t.signal})]),d=n.map(_=>{var y,S0;return{..._,runtime_state:((y=p[_.id])==null?void 0:y.state)||(_.enabled?"connecting":"disabled"),runtime_connected:((S0=p[_.id])==null?void 0:S0.connected)===!0}}).filter(_=>_.enabled),S=await Promise.all(d.map(async _=>[_.id,await R0(_.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;g(d),N(Object.fromEntries(S.map(([_,y])=>[_,y.sessions]))),U(Object.fromEntries(S.map(([_,y])=>[_,y.next_cursor]))),Y(Object.fromEntries(S.map(([_,y])=>[_,y.has_more])));const f=window.localStorage.getItem("ydisks.chat.account.v1")||"",I=d.some(_=>_.id===f)?f:((c=d[0])==null?void 0:c.id)||"";r(I)}catch(n){t.signal.aborted||w(n instanceof Error?n.message:"加载聊天数据失败")}finally{t.signal.aborted||T(!1)}})(),(()=>t.abort())},[]),a.useEffect(()=>{let t=!1,l=0,c=null;const n=async()=>{c=new AbortController;try{const p=await T0({signal:c.signal,timeoutMs:1e4});t||g(o=>o.map(d=>{var S,f;return{...d,runtime_state:((S=p[d.id])==null?void 0:S.state)||d.runtime_state,runtime_connected:((f=p[d.id])==null?void 0:f.connected)??d.runtime_connected}}))}catch{}finally{t||(l=window.setTimeout(n,3e3))}};return l=window.setTimeout(n,3e3),(()=>{t=!0,window.clearTimeout(l),c==null||c.abort()})},[]),a.useEffect(()=>{if(!i)return;window.localStorage.setItem("ydisks.chat.account.v1",i);const t=x[i]||[];P(l=>{var c;return t.some(n=>n.chat_id===l)?l:((c=t[0])==null?void 0:c.chat_id)||""})},[i,x]),a.useEffect(()=>{!i||I0.current.has(i)||(I0.current.add(i),s0(i))},[i,s0]),a.useEffect(()=>{var c;if(!i||!b){v([]);return}const t=++J.current;(c=k0.current)==null||c.abort();const l=new AbortController;return k0.current=l,D(!0),Promise.all([M0(i,b,void 0,void 0,{signal:l.signal}),q0(i,b,{signal:l.signal})]).then(([n])=>{j(J.current,t,l.signal)&&(v(n.messages),n0(n.has_more),l0(n.next_cursor),n.session&&N(p=>({...p,[i]:(p[i]||[]).map(o=>{var d;return o.chat_id===((d=n.session)==null?void 0:d.chat_id)?n.session:o})})),N(p=>({...p,[i]:(p[i]||[]).map(o=>o.chat_id===b?{...o,unread_count:0}:o)})))}).catch(n=>{j(J.current,t,l.signal)&&!Q(n)&&w(n instanceof Error?n.message:"加载消息失败")}).finally(()=>{j(J.current,t,l.signal)&&D(!1)}),(()=>l.abort())},[i,b]),a.useEffect(()=>{var t;(t=g0.current)==null||t.abort(),t0.current+=1},[i]),a.useEffect(()=>{var t;(t=B.current)==null||t.abort(),k.current+=1},[i,b]),a.useEffect(()=>(()=>{var t,l,c,n;(t=v0.current)==null||t.abort(),(l=k0.current)==null||l.abort(),(c=g0.current)==null||c.abort(),(n=B.current)==null||n.abort()}),[]);const A0=a.useCallback(async()=>{var p;if(!i||!b||z||!W)return;const t=p0.current,l=(t==null?void 0:t.scrollHeight)||0,c=J.current,n=new AbortController;m0.current=!0,V(!0),w("");try{const o=(p=E[0])==null?void 0:p.id,d=await M0(i,b,r0,o,{signal:n.signal});if(!j(J.current,c,n.signal))return;v(S=>ge(S,d.messages)),n0(d.has_more),l0(d.next_cursor),requestAnimationFrame(()=>{t&&(t.scrollTop+=t.scrollHeight-l)})}catch(o){m0.current=!1,Q(o)||w(o instanceof Error?o.message:"加载历史消息失败")}finally{V(!1)}},[i,b,W,r0,E,z]);a.useEffect(()=>{let t=!1,l=0,c=0,n=null;const p=()=>{if(t)return;H("connecting");const o=window.location.protocol==="https:"?"wss:":"ws:";n=new WebSocket(`${o}//${window.location.host}/api/v1/chat/ws`),n.onopen=()=>{c=0,H("online")},n.onmessage=d=>{try{const f=JSON.parse(d.data).message;if(!f)return;const I=f.account_id;N(_=>{const y=_[I]||[];return y.some(R=>R.chat_id===f.chat_id)?{..._,[I]:y.map(R=>R.chat_id===f.chat_id?{...R,last_message:f.content,last_message_at:f.sent_at,unread_count:f.direction==="incoming"&&(O.current!==I||e0.current!==f.chat_id)?R.unread_count+1:R.unread_count}:R).sort((R,V0)=>V0.last_message_at-R.last_message_at)}:(s0(I),_)}),O.current===I&&e0.current===f.chat_id&&(v(_=>D0(_,f)),f.direction==="incoming"&&q0(I,f.chat_id))}catch{}},n.onclose=()=>{if(t)return;H("offline");const d=Math.min(15e3,1e3*2**Math.min(c++,4));l=window.setTimeout(p,d)},n.onerror=()=>n==null?void 0:n.close()};return p(),(()=>{t=!0,window.clearTimeout(l),n==null||n.close()})},[s0]);const H0=a.useCallback(()=>{const t=p0.current;if(!t)return;const l=t.scrollHeight-t.scrollTop-t.clientHeight;C0.current=l<=48},[]);a.useLayoutEffect(()=>{const t=N0.current.accountID!==i||N0.current.chatID!==b;N0.current={accountID:i,chatID:b},t&&(C0.current=!0);const l=p0.current;if(l){if(m0.current){m0.current=!1;return}(L||C0.current)&&(l.scrollTop=l.scrollHeight)}},[i,b,E,L]);const F0=m.find(t=>t.id===i),d0=x[i]||[],h=d0.find(t=>t.chat_id===b),J0=a.useMemo(()=>me(d0,Z,M),[d0,Z,M]),B0=a.useCallback(t=>(x[t]||[]).reduce((l,c)=>l+c.unread_count,0),[x]),Q0=a.useCallback(async()=>{var n;if(!i||K||!X[i])return;const t=++t0.current;(n=g0.current)==null||n.abort();const l=new AbortController;g0.current=l;const c=i;c0(!0),w("");try{const p=await R0(c,G[c],{signal:l.signal},!0);if(!j(t0.current,t,l.signal))return;N(o=>({...o,[c]:p.sessions})),U(o=>({...o,[c]:p.next_cursor})),Y(o=>({...o,[c]:p.has_more}))}catch(p){j(t0.current,t,l.signal)&&!Q(p)&&w(p instanceof Error?p.message:"加载历史联系人失败")}finally{j(t0.current,t,l.signal)&&c0(!1)}},[i,G,K,X]),x0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await G0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,item_id:h.item_id,item_title:h.item_title,text:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;a0(""),$(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&$(t),Q(o)||w(o instanceof Error?o.message:"消息发送失败"))}finally{j(k.current,c,n.signal)&&A(!1)}},[i,h,C]),_0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await X0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,buyer_avatar_url:h.buyer_avatar_url,item_id:h.item_id,item_title:h.item_title,image:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;u(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&u(t),Q(o)||w(o instanceof Error?o.message:"图片发送失败"))}finally{j(k.current,c,n.signal)&&(A(!1),y0.current&&(y0.current.value=""))}},[i,h,C]),P0=a.useCallback(async()=>{const t=q.trim();!t||!h||!i||C||await x0(t,!0)},[i,q,h,x0,C]),Z0=a.useCallback(async t=>{!t||!h||!i||C||await _0(t,!0)},[i,h,_0,C]),z0=a.useCallback(async()=>{F?await x0(F,!1):s&&await _0(s,!1)},[s,F,_0,x0]);return{accounts:m,activeAccountID:i,activeSessions:d0,selectedSession:h,activeAccount:F0,messages:E,search:Z,unreadOnly:M,draft:q,loading:b0,messagesLoading:L,olderLoading:z,hasOlder:W,contactsLoading:K,hasMoreContacts:X[i]===!0,emojiOpen:o0,sending:C,error:j0,liveState:w0,activeChatID:b,filteredSessions:J0,scrollRef:p0,imageInputRef:y0,setActiveAccountID:r,setActiveChatID:P,setSearch:h0,setUnreadOnly:u0,setDraft:a0,setEmojiOpen:f0,reloadSessions:s0,loadMoreContacts:Q0,loadOlderMessages:A0,handleMessageScroll:H0,handleSend:P0,handleImage:Z0,retrySend:z0,retryAvailable:!!(F||s),unreadForAccount:B0,emojiURL:ce,xianyuEmojis:U0,renderXianyuText:pe,formatClock:de,messageTime:xe}},fe=()=>{const{accounts:m,activeAccountID:g,activeChatID:i,activeAccount:r,selectedSession:x,filteredSessions:N,messages:b,search:P,unreadOnly:E,draft:v,loading:Z,messagesLoading:h0,olderLoading:M,hasOlder:u0,contactsLoading:q,hasMoreContacts:a0,emojiOpen:b0,sending:T,error:L,liveState:D,scrollRef:z,imageInputRef:V,setActiveAccountID:W,setActiveChatID:n0,setSearch:r0,setUnreadOnly:l0,setDraft:G,setEmojiOpen:U,reloadSessions:X,loadMoreContacts:Y,loadOlderMessages:K,handleMessageScroll:c0,handleSend:o0,handleImage:f0,retrySend:C,retryAvailable:A,unreadForAccount:j0,emojiURL:w,xianyuEmojis:w0,renderXianyuText:H,formatClock:F,messageTime:$}=_e();return Z?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(i0,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${D==="online"?"bg-emerald-50 text-emerald-700":D==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[D==="online"?e.jsx(K0,{className:"h-3.5 w-3.5"}):e.jsx($0,{className:"h-3.5 w-3.5"}),D==="online"?"实时同步中":D==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:m.map(s=>{const u=s.id===g,O=j0(s.id),e0=s.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":u,onClick:(()=>W(s.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${u?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${e0?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:s.nickname||s.remark||s.id}),O>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:O>99?"99+":O})]},s.id)})})]}),m.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ee,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:P,onChange:(s=>r0(s.target.value)),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:(()=>l0(s=>!s)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${E?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:E?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void X(g)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(te,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[N.map(s=>e.jsxs("button",{type:"button",onClick:(()=>n0(s.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${s.chat_id===i?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:s.buyer_avatar_url?e.jsx("img",{src:s.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:s.buyer_name||`用户 ${s.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:F(s.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:s.last_message||"暂无消息"}),s.unread_count>0&&e.jsx("span",{className:"ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white",children:s.unread_count})]}),s.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",s.item_title]})]})]},s.chat_id)),N.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),a0&&!P&&!E&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void Y()),disabled:q,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[q&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),q?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:x?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:x.buyer_name||x.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",x.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(r==null?void 0:r.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(r==null?void 0:r.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:z,onScroll:c0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:h0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(i0,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[u0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void K()),disabled:M,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[M&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),M?"正在加载":"加载更早消息"]})}),b.map(s=>{const u=s.direction==="outgoing";return s.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[H(s.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:$(s.sent_at)})]})},s.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${u?"justify-end":"justify-start"}`,children:[!u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:x.buyer_avatar_url?e.jsx("img",{src:x.buyer_avatar_url,alt:x.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${u?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:u?(r==null?void 0:r.nickname)||(r==null?void 0:r.remark)||"我":x.buyer_name||s.sender_name||x.buyer_id}),s.message_type==="image"?e.jsx("a",{href:s.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${u?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:s.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):s.message_type==="video"?e.jsx("video",{src:s.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${u?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:H(s.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[$(s.sent_at),u&&(s.status==="failed"?e.jsx(se,{className:"h-3 w-3 text-red-500"}):s.status==="sent"?e.jsx(ie,{className:"h-3 w-3 text-sky-500"}):e.jsx(ae,{className:"h-3 w-3"}))]})]}),u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:r!=null&&r.avatar_url?e.jsx("img",{src:r.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-sky-600"})})]},s.message_key)})]})}),L&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:L}),A&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void C()),children:"重试发送"})]}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:(()=>U(s=>!s)),disabled:T||(r==null?void 0:r.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(ne,{className:"h-5 w-5"})}),b0&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:w0.map(([s,u])=>e.jsx("button",{type:"button",title:`[${s}]`,onClick:(()=>{G(O=>O+`[${s}]`),U(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:w(u),alt:`[${s}]`,className:"h-8 w-8 object-contain"})},s))})]})]}),e.jsx("input",{ref:V,type:"file",accept:"image/*",className:"hidden",onChange:(s=>{var u;return void f0((u=s.target.files)==null?void 0:u[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var s;return(s=V.current)==null?void 0:s.click()}),disabled:T||(r==null?void 0:r.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(re,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:v,onChange:(s=>G(s.target.value)),rows:2,maxLength:2e3,onKeyDown:(s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),o0())}),disabled:(r==null?void 0:r.runtime_state)!=="online",placeholder:(r==null?void 0:r.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:(()=>void o0()),disabled:!v.trim()||T||(r==null?void 0:r.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:T?e.jsx(i0,{className:"h-4 w-4 animate-spin"}):e.jsx(le,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})};export{fe as default}; +import{j as e,c as W0,r as a}from"./react-vendor-C_od1ZSF.js";import{ap as R0,aq as M0,ar as q0,as as G0,at as X0,h as Y0,j as T0}from"./index-CYPNW7Ux.js";import{f as i0,ak as K0,al as $0,M as L0,I as ee,R as te,ad as E0,k as se,am as ie,s as ae,an as ne,ao as re,ah as le}from"./icons-vendor-ThcsWkZG.js";const U0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"],["流汗","https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"],["憨笑","https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"],["耶","https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"],["奋斗","https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"],["咒骂","https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"],["疑问","https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"],["嘘","https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"],["晕","https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"],["开心到模糊","https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"],["衰","https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"],["委屈","https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"],["再见","https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"],["鼓掌","https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"],["吐","https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"],["坏笑","https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"],["抠鼻","https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"],["叹气","https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"],["无聊","https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"],["思考","https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"],["呆","https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["哇哦","https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"],["飞吻","https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"],["好喜欢","https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"],["拜托","https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"],["真棒","https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"],["流鼻血","https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"],["费解","https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"],["秃头","https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"],["嘿哈","https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"],["吃土","https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"],["机智","https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"],["举杯","https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"],["握手","https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"],["挥手","https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"],["yeah","https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"],["666","https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"],["棒","https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"],["爱你","https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"],["比心","https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"],["感谢","https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"],["拍手","https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"],["拉钩","https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"],["没钱","https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"],["小刀","https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"],["不刀","https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"],["同出","https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"],["递钱","https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"],["数钱","https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"],["打call","https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"],["号外","https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"],["包邮","https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"],["求赞","https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"],["非主流","https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"],["吃瓜","https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"],["种草","https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"],["佛系","https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"],["超便宜","https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"],["拥抱","https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"],["摊手","https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"],["举手","https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"],["蹲","https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"],["跪了","https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"],["拜","https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"],["排","https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"],["旺财","https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"],["招财猫","https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"],["酸了","https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"],["鸭鸭","https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"],["方了","https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"],["白菜","https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"],["桃子","https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"],["打包","https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"],["沙发","https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"],["南","https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"],["盯","https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"],["hot","https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"],["new","https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"],["cool","https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"],["1","https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"],["可","https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"],["搬砖","https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"],["菜狗","https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"],["开心面具","https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"],["快递","https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["裂开","https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"],["啤酒","https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"],["瑞思拜","https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"],["小丑","https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"],["爱心","https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"]],ce=m=>m,oe=new Map(U0.map(([m,g])=>[m,g])),pe=m=>m.split(/(\[[^\]]+\])/g).map((g,i)=>{const r=g.startsWith("[")?oe.get(g.slice(1,-1)):void 0;return r?e.jsx("img",{src:r,alt:g,title:g,className:"mx-0.5 inline-block h-7 w-7 align-middle"},i):e.jsx(W0.Fragment,{children:g},i)}),me=(m,g,i)=>{const r=g.trim().toLowerCase();return m.filter(x=>i&&x.unread_count<=0?!1:r?[x.buyer_name,x.buyer_id,x.item_title,x.last_message].some(N=>(N||"").toLowerCase().includes(r)):!0)},ge=(m,g)=>{const i=new Set(m.map(r=>r.message_key));return[...g.filter(r=>!i.has(r.message_key)),...m]},D0=(m,g)=>{const i=m.findIndex(r=>r.message_key===g.message_key);return i<0?[...m,g]:m.map((r,x)=>x===i?g:r)},j=(m,g,i)=>m===g&&!i.aborted,Q=m=>m instanceof Error&&m.message==="请求已取消",de=m=>{if(!m)return"";const g=new Date(m<1e10?m*1e3:m),i=new Date;return g.toDateString()===i.toDateString()?g.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):g.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},xe=m=>new Date(m<1e10?m*1e3:m).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),_e=()=>{const[m,g]=a.useState([]),[i,r]=a.useState(""),[x,N]=a.useState({}),[b,P]=a.useState(""),[E,v]=a.useState([]),[Z,h0]=a.useState(""),[M,u0]=a.useState(!1),[q,a0]=a.useState(""),[b0,T]=a.useState(!0),[L,D]=a.useState(!1),[z,V]=a.useState(!1),[W,n0]=a.useState(!1),[r0,l0]=a.useState(),[G,U]=a.useState({}),[X,Y]=a.useState({}),[K,c0]=a.useState(!1),[o0,f0]=a.useState(!1),[C,A]=a.useState(!1),[j0,w]=a.useState(""),[w0,H]=a.useState("connecting"),[F,$]=a.useState(null),[s,u]=a.useState(null),O=a.useRef(""),e0=a.useRef(""),p0=a.useRef(null),N0=a.useRef({accountID:"",chatID:""}),C0=a.useRef(!0),m0=a.useRef(!1),y0=a.useRef(null),I0=a.useRef(new Set),O0=a.useRef(0),v0=a.useRef(null),J=a.useRef(0),k0=a.useRef(null),t0=a.useRef(0),g0=a.useRef(null),k=a.useRef(0),B=a.useRef(null);a.useEffect(()=>{O.current=i},[i]),a.useEffect(()=>{e0.current=b},[b]);const s0=a.useCallback(async t=>{var n;const l=++O0.current;(n=v0.current)==null||n.abort();const c=new AbortController;v0.current=c;try{const p=await R0(t,void 0,{signal:c.signal},!0);return j(O0.current,l,c.signal)?(N(o=>({...o,[t]:p.sessions})),U(o=>({...o,[t]:p.next_cursor})),Y(o=>({...o,[t]:p.has_more})),p.sessions):[]}catch(p){return j(O0.current,l,c.signal)&&!Q(p)&&w(p instanceof Error?p.message:"同步会话失败"),[]}},[]);a.useEffect(()=>{const t=new AbortController;return(async()=>{var c;T(!0);try{const[n,p]=await Promise.all([Y0({signal:t.signal}),T0({signal:t.signal})]),d=n.map(_=>{var y,S0;return{..._,runtime_state:((y=p[_.id])==null?void 0:y.state)||(_.enabled?"connecting":"disabled"),runtime_connected:((S0=p[_.id])==null?void 0:S0.connected)===!0}}).filter(_=>_.enabled),S=await Promise.all(d.map(async _=>[_.id,await R0(_.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;g(d),N(Object.fromEntries(S.map(([_,y])=>[_,y.sessions]))),U(Object.fromEntries(S.map(([_,y])=>[_,y.next_cursor]))),Y(Object.fromEntries(S.map(([_,y])=>[_,y.has_more])));const f=window.localStorage.getItem("ydisks.chat.account.v1")||"",I=d.some(_=>_.id===f)?f:((c=d[0])==null?void 0:c.id)||"";r(I)}catch(n){t.signal.aborted||w(n instanceof Error?n.message:"加载聊天数据失败")}finally{t.signal.aborted||T(!1)}})(),(()=>t.abort())},[]),a.useEffect(()=>{let t=!1,l=0,c=null;const n=async()=>{c=new AbortController;try{const p=await T0({signal:c.signal,timeoutMs:1e4});t||g(o=>o.map(d=>{var S,f;return{...d,runtime_state:((S=p[d.id])==null?void 0:S.state)||d.runtime_state,runtime_connected:((f=p[d.id])==null?void 0:f.connected)??d.runtime_connected}}))}catch{}finally{t||(l=window.setTimeout(n,3e3))}};return l=window.setTimeout(n,3e3),(()=>{t=!0,window.clearTimeout(l),c==null||c.abort()})},[]),a.useEffect(()=>{if(!i)return;window.localStorage.setItem("ydisks.chat.account.v1",i);const t=x[i]||[];P(l=>{var c;return t.some(n=>n.chat_id===l)?l:((c=t[0])==null?void 0:c.chat_id)||""})},[i,x]),a.useEffect(()=>{!i||I0.current.has(i)||(I0.current.add(i),s0(i))},[i,s0]),a.useEffect(()=>{var c;if(!i||!b){v([]);return}const t=++J.current;(c=k0.current)==null||c.abort();const l=new AbortController;return k0.current=l,D(!0),Promise.all([M0(i,b,void 0,void 0,{signal:l.signal}),q0(i,b,{signal:l.signal})]).then(([n])=>{j(J.current,t,l.signal)&&(v(n.messages),n0(n.has_more),l0(n.next_cursor),n.session&&N(p=>({...p,[i]:(p[i]||[]).map(o=>{var d;return o.chat_id===((d=n.session)==null?void 0:d.chat_id)?n.session:o})})),N(p=>({...p,[i]:(p[i]||[]).map(o=>o.chat_id===b?{...o,unread_count:0}:o)})))}).catch(n=>{j(J.current,t,l.signal)&&!Q(n)&&w(n instanceof Error?n.message:"加载消息失败")}).finally(()=>{j(J.current,t,l.signal)&&D(!1)}),(()=>l.abort())},[i,b]),a.useEffect(()=>{var t;(t=g0.current)==null||t.abort(),t0.current+=1},[i]),a.useEffect(()=>{var t;(t=B.current)==null||t.abort(),k.current+=1},[i,b]),a.useEffect(()=>(()=>{var t,l,c,n;(t=v0.current)==null||t.abort(),(l=k0.current)==null||l.abort(),(c=g0.current)==null||c.abort(),(n=B.current)==null||n.abort()}),[]);const A0=a.useCallback(async()=>{var p;if(!i||!b||z||!W)return;const t=p0.current,l=(t==null?void 0:t.scrollHeight)||0,c=J.current,n=new AbortController;m0.current=!0,V(!0),w("");try{const o=(p=E[0])==null?void 0:p.id,d=await M0(i,b,r0,o,{signal:n.signal});if(!j(J.current,c,n.signal))return;v(S=>ge(S,d.messages)),n0(d.has_more),l0(d.next_cursor),requestAnimationFrame(()=>{t&&(t.scrollTop+=t.scrollHeight-l)})}catch(o){m0.current=!1,Q(o)||w(o instanceof Error?o.message:"加载历史消息失败")}finally{V(!1)}},[i,b,W,r0,E,z]);a.useEffect(()=>{let t=!1,l=0,c=0,n=null;const p=()=>{if(t)return;H("connecting");const o=window.location.protocol==="https:"?"wss:":"ws:";n=new WebSocket(`${o}//${window.location.host}/api/v1/chat/ws`),n.onopen=()=>{c=0,H("online")},n.onmessage=d=>{try{const f=JSON.parse(d.data).message;if(!f)return;const I=f.account_id;N(_=>{const y=_[I]||[];return y.some(R=>R.chat_id===f.chat_id)?{..._,[I]:y.map(R=>R.chat_id===f.chat_id?{...R,last_message:f.content,last_message_at:f.sent_at,unread_count:f.direction==="incoming"&&(O.current!==I||e0.current!==f.chat_id)?R.unread_count+1:R.unread_count}:R).sort((R,V0)=>V0.last_message_at-R.last_message_at)}:(s0(I),_)}),O.current===I&&e0.current===f.chat_id&&(v(_=>D0(_,f)),f.direction==="incoming"&&q0(I,f.chat_id))}catch{}},n.onclose=()=>{if(t)return;H("offline");const d=Math.min(15e3,1e3*2**Math.min(c++,4));l=window.setTimeout(p,d)},n.onerror=()=>n==null?void 0:n.close()};return p(),(()=>{t=!0,window.clearTimeout(l),n==null||n.close()})},[s0]);const H0=a.useCallback(()=>{const t=p0.current;if(!t)return;const l=t.scrollHeight-t.scrollTop-t.clientHeight;C0.current=l<=48},[]);a.useLayoutEffect(()=>{const t=N0.current.accountID!==i||N0.current.chatID!==b;N0.current={accountID:i,chatID:b},t&&(C0.current=!0);const l=p0.current;if(l){if(m0.current){m0.current=!1;return}(L||C0.current)&&(l.scrollTop=l.scrollHeight)}},[i,b,E,L]);const F0=m.find(t=>t.id===i),d0=x[i]||[],h=d0.find(t=>t.chat_id===b),J0=a.useMemo(()=>me(d0,Z,M),[d0,Z,M]),B0=a.useCallback(t=>(x[t]||[]).reduce((l,c)=>l+c.unread_count,0),[x]),Q0=a.useCallback(async()=>{var n;if(!i||K||!X[i])return;const t=++t0.current;(n=g0.current)==null||n.abort();const l=new AbortController;g0.current=l;const c=i;c0(!0),w("");try{const p=await R0(c,G[c],{signal:l.signal},!0);if(!j(t0.current,t,l.signal))return;N(o=>({...o,[c]:p.sessions})),U(o=>({...o,[c]:p.next_cursor})),Y(o=>({...o,[c]:p.has_more}))}catch(p){j(t0.current,t,l.signal)&&!Q(p)&&w(p instanceof Error?p.message:"加载历史联系人失败")}finally{j(t0.current,t,l.signal)&&c0(!1)}},[i,G,K,X]),x0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await G0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,item_id:h.item_id,item_title:h.item_title,text:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;a0(""),$(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&$(t),Q(o)||w(o instanceof Error?o.message:"消息发送失败"))}finally{j(k.current,c,n.signal)&&A(!1)}},[i,h,C]),_0=a.useCallback(async(t,l)=>{var p;if(!h||!i||C)return;const c=++k.current;(p=B.current)==null||p.abort();const n=new AbortController;B.current=n,A(!0),w("");try{const o=await X0({account_id:i,chat_id:h.chat_id,buyer_id:h.buyer_id,buyer_name:h.buyer_name,buyer_avatar_url:h.buyer_avatar_url,item_id:h.item_id,item_title:h.item_title,image:t},{signal:n.signal});if(!j(k.current,c,n.signal))return;u(null),v(d=>D0(d,o.message))}catch(o){j(k.current,c,n.signal)&&(l&&u(t),Q(o)||w(o instanceof Error?o.message:"图片发送失败"))}finally{j(k.current,c,n.signal)&&(A(!1),y0.current&&(y0.current.value=""))}},[i,h,C]),P0=a.useCallback(async()=>{const t=q.trim();!t||!h||!i||C||await x0(t,!0)},[i,q,h,x0,C]),Z0=a.useCallback(async t=>{!t||!h||!i||C||await _0(t,!0)},[i,h,_0,C]),z0=a.useCallback(async()=>{F?await x0(F,!1):s&&await _0(s,!1)},[s,F,_0,x0]);return{accounts:m,activeAccountID:i,activeSessions:d0,selectedSession:h,activeAccount:F0,messages:E,search:Z,unreadOnly:M,draft:q,loading:b0,messagesLoading:L,olderLoading:z,hasOlder:W,contactsLoading:K,hasMoreContacts:X[i]===!0,emojiOpen:o0,sending:C,error:j0,liveState:w0,activeChatID:b,filteredSessions:J0,scrollRef:p0,imageInputRef:y0,setActiveAccountID:r,setActiveChatID:P,setSearch:h0,setUnreadOnly:u0,setDraft:a0,setEmojiOpen:f0,reloadSessions:s0,loadMoreContacts:Q0,loadOlderMessages:A0,handleMessageScroll:H0,handleSend:P0,handleImage:Z0,retrySend:z0,retryAvailable:!!(F||s),unreadForAccount:B0,emojiURL:ce,xianyuEmojis:U0,renderXianyuText:pe,formatClock:de,messageTime:xe}},fe=()=>{const{accounts:m,activeAccountID:g,activeChatID:i,activeAccount:r,selectedSession:x,filteredSessions:N,messages:b,search:P,unreadOnly:E,draft:v,loading:Z,messagesLoading:h0,olderLoading:M,hasOlder:u0,contactsLoading:q,hasMoreContacts:a0,emojiOpen:b0,sending:T,error:L,liveState:D,scrollRef:z,imageInputRef:V,setActiveAccountID:W,setActiveChatID:n0,setSearch:r0,setUnreadOnly:l0,setDraft:G,setEmojiOpen:U,reloadSessions:X,loadMoreContacts:Y,loadOlderMessages:K,handleMessageScroll:c0,handleSend:o0,handleImage:f0,retrySend:C,retryAvailable:A,unreadForAccount:j0,emojiURL:w,xianyuEmojis:w0,renderXianyuText:H,formatClock:F,messageTime:$}=_e();return Z?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(i0,{className:"h-8 w-8 animate-spin text-sky-500"})}):e.jsxs("section",{className:"flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat",children:[e.jsxs("header",{className:"border-b border-slate-200 bg-slate-50/70 px-5 pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-black tracking-tight text-slate-950",children:"在线聊天"}),e.jsx("p",{className:"mt-0.5 text-xs font-medium text-slate-500",children:"复用账号实时连接,消息按账号完全隔离"})]}),e.jsxs("div",{className:`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${D==="online"?"bg-emerald-50 text-emerald-700":D==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[D==="online"?e.jsx(K0,{className:"h-3.5 w-3.5"}):e.jsx($0,{className:"h-3.5 w-3.5"}),D==="online"?"实时同步中":D==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:m.map(s=>{const u=s.id===g,O=j0(s.id),e0=s.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":u,onClick:(()=>W(s.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${u?"border-sky-500 text-sky-700":"border-transparent text-slate-500 hover:text-slate-900"}`,children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${e0?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:s.nickname||s.remark||s.id}),O>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:O>99?"99+":O})]},s.id)})})]}),m.length===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-800",children:"暂无启用账号"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"先在账号管理中启用账号,聊天会话会自动出现。"})]}):e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]",children:[e.jsxs("aside",{className:"flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40",children:[e.jsxs("div",{className:"space-y-3 border-b border-slate-200 p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ee,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:P,onChange:(s=>r0(s.target.value)),placeholder:"搜索用户、商品或消息",className:"h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{type:"button",onClick:(()=>l0(s=>!s)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${E?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:E?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void X(g)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(te,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[N.map(s=>e.jsxs("button",{type:"button",onClick:(()=>n0(s.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${s.chat_id===i?"bg-white shadow-chat-active":"hover:bg-white/80"}`,children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500",children:s.buyer_avatar_url?e.jsx("img",{src:s.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-extrabold text-slate-900",children:s.buyer_name||`用户 ${s.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:F(s.last_message_at)})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs text-slate-500",children:s.last_message||"暂无消息"}),s.unread_count>0&&e.jsx("span",{className:"ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white",children:s.unread_count})]}),s.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",s.item_title]})]})]},s.chat_id)),N.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),a0&&!P&&!E&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void Y()),disabled:q,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[q&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),q?"正在加载":"加载更多历史联系人"]})})]})]}),e.jsx("main",{className:"flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle",children:x?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-black text-slate-950",children:x.buyer_name||x.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",x.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(r==null?void 0:r.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(r==null?void 0:r.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:z,onScroll:c0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:h0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(i0,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[u0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void K()),disabled:M,className:"flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50",children:[M&&e.jsx(i0,{className:"h-3.5 w-3.5 animate-spin"}),M?"正在加载":"加载更早消息"]})}),b.map(s=>{const u=s.direction==="outgoing";return s.message_type==="system"?e.jsx("div",{className:"flex justify-center py-1",children:e.jsxs("div",{className:"max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500",children:[H(s.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:$(s.sent_at)})]})},s.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${u?"justify-end":"justify-start"}`,children:[!u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:x.buyer_avatar_url?e.jsx("img",{src:x.buyer_avatar_url,alt:x.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${u?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:u?(r==null?void 0:r.nickname)||(r==null?void 0:r.remark)||"我":x.buyer_name||s.sender_name||x.buyer_id}),s.message_type==="image"?e.jsx("a",{href:s.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${u?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:s.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):s.message_type==="video"?e.jsx("video",{src:s.content,controls:!0,preload:"metadata",className:"max-h-80 max-w-full rounded-2xl bg-black"}):e.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${u?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:H(s.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[$(s.sent_at),u&&(s.status==="failed"?e.jsx(se,{className:"h-3 w-3 text-red-500"}):s.status==="sent"?e.jsx(ie,{className:"h-3 w-3 text-sky-500"}):e.jsx(ae,{className:"h-3 w-3"}))]})]}),u&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:r!=null&&r.avatar_url?e.jsx("img",{src:r.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(E0,{className:"m-2 h-5 w-5 text-sky-600"})})]},s.message_key)})]})}),L&&e.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700",children:[e.jsx("span",{children:L}),A&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void C()),children:"重试发送"})]}),e.jsxs("div",{className:"relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1",children:[e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:(()=>U(s=>!s)),disabled:T||(r==null?void 0:r.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"闲鱼表情",children:e.jsx(ne,{className:"h-5 w-5"})}),b0&&e.jsxs("div",{className:"absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl",children:[e.jsx("div",{className:"mb-2 text-xs font-bold text-slate-500",children:"全部表情"}),e.jsx("div",{className:"grid max-h-72 grid-cols-8 gap-1 overflow-y-auto",children:w0.map(([s,u])=>e.jsx("button",{type:"button",title:`[${s}]`,onClick:(()=>{G(O=>O+`[${s}]`),U(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:w(u),alt:`[${s}]`,className:"h-8 w-8 object-contain"})},s))})]})]}),e.jsx("input",{ref:V,type:"file",accept:"image/*",className:"hidden",onChange:(s=>{var u;return void f0((u=s.target.files)==null?void 0:u[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var s;return(s=V.current)==null?void 0:s.click()}),disabled:T||(r==null?void 0:r.runtime_state)!=="online",className:"rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40",title:"发送图片(最大 10MB)",children:e.jsx(re,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100",children:[e.jsx("textarea",{value:v,onChange:(s=>G(s.target.value)),rows:2,maxLength:2e3,onKeyDown:(s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),o0())}),disabled:(r==null?void 0:r.runtime_state)!=="online",placeholder:(r==null?void 0:r.runtime_state)==="online"?"输入消息,Enter 发送,Shift + Enter 换行":"账号离线,暂时无法发送",className:"max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed"}),e.jsx("button",{type:"button",onClick:(()=>void o0()),disabled:!v.trim()||T||(r==null?void 0:r.runtime_state)!=="online",className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none","aria-label":"发送消息",children:T?e.jsx(i0,{className:"h-4 w-4 animate-spin"}):e.jsx(le,{className:"h-4 w-4"})})]})]})]}):e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:[e.jsx(L0,{className:"h-12 w-12 text-slate-300"}),e.jsx("h3",{className:"mt-4 font-black text-slate-700",children:"选择一个用户开始聊天"}),e.jsx("p",{className:"mt-1 text-sm text-slate-400",children:"该账号的新消息会实时出现在左侧列表。"})]})})]})]})};export{fe as default}; diff --git a/internal/webui/static/assets/Dashboard-BjrV0BPa.js b/internal/webui/static/assets/Dashboard-sUNU2Eg5.js similarity index 99% rename from internal/webui/static/assets/Dashboard-BjrV0BPa.js rename to internal/webui/static/assets/Dashboard-sUNU2Eg5.js index 12b203c..904640d 100644 --- a/internal/webui/static/assets/Dashboard-BjrV0BPa.js +++ b/internal/webui/static/assets/Dashboard-sUNU2Eg5.js @@ -1 +1 @@ -import{r as d,j as e}from"./react-vendor-C_od1ZSF.js";import{g as oe,a as ie,b as le,c as ce,d as H,e as de}from"./index-DK02p8DH.js";import{f as xe}from"./dateTime-DDi7rqpW.js";import{j as ne,k as me,l as J,D as ue,U as he,P as ge,m as Q,E as be,T as pe}from"./icons-vendor-ThcsWkZG.js";import{R as E,B as fe,X as Z,Y as ee,T as z,a as ye,C as V,A as je,b as ve,c as Ne,P as te,d as se,L as we}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const _e=s=>{const r={};return s.forEach(a=>{r[a.item_id]=a.item_title||a.item_id}),r},ke=s=>{var r;return((r=s.daily_stats)==null?void 0:r.map(a=>({name:a.date.slice(5),amount:a.amount,orders:a.order_count,avgAmount:a.order_count>0?(a.amount/a.order_count).toFixed(2):0})))||[]},Ce=(s,r)=>(s.item_stats||[]).map(a=>{const n=r[a.item_id]||a.item_id;return{name:n.length>12?`${n.substring(0,12)}...`:n,sales:a.order_count}}).sort((a,n)=>n.sales-a.sales).slice(0,10),Se=(s,r,a)=>{const n=s.revenue_stats.total_orders||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:l.order_count,percent:n>0?l.order_count/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,6).map((l,o)=>({...l,color:a[o%a.length]}))},De=(s,r,a)=>{const n=s.revenue_stats.total_amount||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:l.total_amount,orderCount:l.order_count,percentage:n>0?l.total_amount/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,5).map((l,o)=>({...l,color:a[o%a.length],percentage:l.percentage.toFixed(1)}))},$e=(s,r)=>{if(!s||!r)return null;const a=s.revenue_stats.total_amount,n=r.revenue_stats.total_amount;if(n===0)return a>0?"+100%":"0%";const l=(a-n)/n*100;return`${l>=0?"+":""}${l.toFixed(1)}%`},Re=s=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[s.range]||"所选范围",Le=s=>Math.max(...s.map(r=>r.sales),1),ae=(s,r,a)=>s===r&&!a.aborted,re=s=>s instanceof Error&&s.message==="请求已取消",q=(s,r)=>s instanceof Error?s.message:r,Ae=s=>{const{range:r,customStartDate:a,customEndDate:n,customRangeVersion:l}=s,[o,S]=d.useState(null),[w,M]=d.useState(null),[F,v]=d.useState({overview:"idle",range:"idle",error:""}),[c,O]=d.useState(0),D=d.useRef(0),P=d.useMemo(()=>({range:r,customStartDate:a,customEndDate:n}),[n,a,r]),$=d.useCallback(()=>O(x=>x+1),[]);d.useEffect(()=>{const x=new AbortController;return v(g=>({...g,overview:"loading",error:""})),Promise.all([oe({signal:x.signal}),ie(void 0,{signal:x.signal})]).then(([g,h])=>{x.signal.aborted||(S({stats:g,items:h,itemNames:_e(h)}),v(u=>({...u,overview:"success"})))}).catch(g=>{x.signal.aborted||re(g)||v(h=>({...h,overview:"error",error:q(g,"概览加载失败")}))}),(()=>x.abort())},[c]),d.useEffect(()=>{let x;try{x=le(r,new Date,a,n)}catch(b){v(k=>({...k,range:"error",error:q(b,"日期范围无效")}));return}const g=ce(x),h=++D.current,u=new AbortController;return v(b=>({...b,range:"loading",error:""})),Promise.all([H({start_date:x.startDate,end_date:x.endDate},{signal:u.signal}),H({start_date:g.startDate,end_date:g.endDate},{signal:u.signal}),de({start_date:x.startDate,end_date:x.endDate},{signal:u.signal})]).then(([b,k,L])=>{ae(D.current,h,u.signal)&&(M({analytics:b,previousAnalytics:k,validOrders:L,dateRange:x}),v(B=>({...B,range:"success"})))}).catch(b=>{!ae(D.current,h,u.signal)||re(b)||v(k=>({...k,range:"error",error:q(b,"经营数据加载失败")}))}),(()=>u.abort())},[l,r,c]);const f=d.useMemo(()=>o&&w?{...o,...w}:null,[o,w]),_=(o==null?void 0:o.itemNames)||{},m=(w==null?void 0:w.analytics)||null,K=d.useMemo(()=>m?ke(m):[],[m]),C=d.useMemo(()=>m?Ce(m,_):[],[m,_]),y=d.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),N=d.useMemo(()=>m?Se(m,_,y):[],[m,y,_]),R=d.useMemo(()=>m?De(m,_,y):[],[m,y,_]),I=d.useMemo(()=>Le(C),[C]);return{data:f,status:F,chartData:K,productSalesData:C,sourceData:N,categoryData:R,maxProductSales:I,trendPercent:$e(m,(f==null?void 0:f.previousAnalytics)||null),selectedRangeLabel:Re(P),refresh:$}},i=(s,r)=>r===void 0?`rgb(var(--color-${s}))`:`rgb(var(--color-${s}) / ${r})`,Oe=({chartData:s,selectedRangeLabel:r,totalAmount:a})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[r,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:s.length===0||a===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(ne,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):s.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(fe,{data:s,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(n=>`¥${n}`)}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(n=>[`¥${Number(n).toFixed(2)}`,"营收"])}),e.jsx(ye,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:s.map((n,l)=>e.jsx(V,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${l}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:s,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(ve,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Ne,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),j=(s,r)=>`rgb(var(--color-${s}))`,Pe=({status:s})=>{const r={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},a={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${r[s]||r.cancelled}`,children:a[s]||s})},W=({title:s,value:r,icon:a,colorClass:n,trend:l})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${n} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${n} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(a,{className:`w-6 h-6 ${n.replace("bg-","text-")}`})}),l&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(pe,{className:"w-3 h-3"})," ",l]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:r}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Ke=()=>{const[s,r]=d.useState("7days"),[a,n]=d.useState(""),[l,o]=d.useState(""),[S,w]=d.useState(""),[M,F]=d.useState(0),v=Ae({range:s,customStartDate:a,customEndDate:l,customRangeVersion:M}),{data:c,status:O,chartData:D,productSalesData:P,sourceData:$,categoryData:f,maxProductSales:_,trendPercent:m,selectedRangeLabel:K,refresh:C}=v,y=(c==null?void 0:c.stats)||null,N=(c==null?void 0:c.analytics)||null;c!=null&&c.previousAnalytics;const R=(c==null?void 0:c.validOrders.orders)||[],I=(c==null?void 0:c.validOrders.total)||0,x=(c==null?void 0:c.validOrders.truncated)||!1,g=O.range==="loading",h=O.error,u=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],b=t=>`¥${Number(t||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!y||!N))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(me,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:C,children:"重新加载"})]});if(!y||!N)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(J,{className:"w-8 h-8 animate-spin text-brand"})});const k=N.revenue_stats.total_orders||0,L=N.revenue_stats.total_amount||0,B=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let T;try{T=le(s,new Date,a,l)}catch{T={startDate:a,endDate:l}}const A=S.trim().toLowerCase(),G=R.filter(t=>{var p,U,Y,X;return((p=t.order_id)==null?void 0:p.toLowerCase().includes(A))||((U=t.item_id)==null?void 0:U.toLowerCase().includes(A))||((Y=t.item_title)==null?void 0:Y.toLowerCase().includes(A))||((X=t.buyer_id)==null?void 0:X.toLowerCase().includes(A))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:C,children:"重试"})]}),e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[B.map(t=>e.jsx("button",{onClick:(()=>r(t.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${s===t.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:t.label},t.key)),s==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:a,onChange:(t=>n(t.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:l,onChange:(t=>o(t.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:(()=>F(t=>t+1)),className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(W,{title:"累计营收 (CNY)",value:`¥${N.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:ue,colorClass:"bg-blue-400",trend:m||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${y.active_cookies} / ${y.total_cookies}`,icon:he,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:N.revenue_stats.total_orders.toLocaleString(),icon:ne,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:y.available_card_stock,icon:ge,colorClass:"bg-purple-500"})]}),e.jsx(Oe,{chartData:D,selectedRangeLabel:K,totalAmount:L}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:P.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:P.map((t,p)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${p<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:p+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:t.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[t.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,t.sales/_*100)}%`}})})]},`${t.name}-${p}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${k} 单`,children:$.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:$,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:$.map((t,p)=>e.jsx(V,{fill:t.color},`cell-${p}`))}),e.jsx(z,{formatter:(t=>`${Number(t||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(we,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(t=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:t}))})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:k}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),x&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",R.length," / ",I," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:S,onChange:(t=>w(t.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:g?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(J,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):G.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(Q,{className:"w-7 h-7 text-gray-300"})}),A?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",R.length," 单参与统计,但没有订单号、商品、买家匹配“",S,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",T.startDate," 至 ",T.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",N.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:G.map(t=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(Q,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:t.item_title||t.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:t.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:t.buyer_id}),t.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:xe(t.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",t.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(Pe,{status:t.status||t.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${t.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(be,{className:"w-4 h-4"})})})]},t.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),f.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${b(L)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:f,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:f.map((t,p)=>e.jsx(V,{fill:t.color||u[p%u.length]},`cell-${p}`))}),e.jsx(z,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(t=>`¥${Number(t||0).toLocaleString()}`)})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:b(L)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:f.map(t=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:t.color||u[f.indexOf(t)%u.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:t.name,children:t.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",t.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[t.percentage,"%"]})]})]},t.name))})]})]})]})]})};export{Pe as StatusBadge,Ke as default}; +import{r as d,j as e}from"./react-vendor-C_od1ZSF.js";import{g as oe,a as ie,b as le,c as ce,d as H,e as de}from"./index-CYPNW7Ux.js";import{f as xe}from"./dateTime-DDi7rqpW.js";import{j as ne,k as me,l as J,D as ue,U as he,P as ge,m as Q,E as be,T as pe}from"./icons-vendor-ThcsWkZG.js";import{R as E,B as fe,X as Z,Y as ee,T as z,a as ye,C as V,A as je,b as ve,c as Ne,P as te,d as se,L as we}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const _e=s=>{const r={};return s.forEach(a=>{r[a.item_id]=a.item_title||a.item_id}),r},ke=s=>{var r;return((r=s.daily_stats)==null?void 0:r.map(a=>({name:a.date.slice(5),amount:a.amount,orders:a.order_count,avgAmount:a.order_count>0?(a.amount/a.order_count).toFixed(2):0})))||[]},Ce=(s,r)=>(s.item_stats||[]).map(a=>{const n=r[a.item_id]||a.item_id;return{name:n.length>12?`${n.substring(0,12)}...`:n,sales:a.order_count}}).sort((a,n)=>n.sales-a.sales).slice(0,10),Se=(s,r,a)=>{const n=s.revenue_stats.total_orders||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:l.order_count,percent:n>0?l.order_count/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,6).map((l,o)=>({...l,color:a[o%a.length]}))},De=(s,r,a)=>{const n=s.revenue_stats.total_amount||0;return(s.item_stats||[]).map(l=>{const o=r[l.item_id]||l.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:l.total_amount,orderCount:l.order_count,percentage:n>0?l.total_amount/n*100:0}}).sort((l,o)=>o.value-l.value).slice(0,5).map((l,o)=>({...l,color:a[o%a.length],percentage:l.percentage.toFixed(1)}))},$e=(s,r)=>{if(!s||!r)return null;const a=s.revenue_stats.total_amount,n=r.revenue_stats.total_amount;if(n===0)return a>0?"+100%":"0%";const l=(a-n)/n*100;return`${l>=0?"+":""}${l.toFixed(1)}%`},Re=s=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[s.range]||"所选范围",Le=s=>Math.max(...s.map(r=>r.sales),1),ae=(s,r,a)=>s===r&&!a.aborted,re=s=>s instanceof Error&&s.message==="请求已取消",q=(s,r)=>s instanceof Error?s.message:r,Ae=s=>{const{range:r,customStartDate:a,customEndDate:n,customRangeVersion:l}=s,[o,S]=d.useState(null),[w,M]=d.useState(null),[F,v]=d.useState({overview:"idle",range:"idle",error:""}),[c,O]=d.useState(0),D=d.useRef(0),P=d.useMemo(()=>({range:r,customStartDate:a,customEndDate:n}),[n,a,r]),$=d.useCallback(()=>O(x=>x+1),[]);d.useEffect(()=>{const x=new AbortController;return v(g=>({...g,overview:"loading",error:""})),Promise.all([oe({signal:x.signal}),ie(void 0,{signal:x.signal})]).then(([g,h])=>{x.signal.aborted||(S({stats:g,items:h,itemNames:_e(h)}),v(u=>({...u,overview:"success"})))}).catch(g=>{x.signal.aborted||re(g)||v(h=>({...h,overview:"error",error:q(g,"概览加载失败")}))}),(()=>x.abort())},[c]),d.useEffect(()=>{let x;try{x=le(r,new Date,a,n)}catch(b){v(k=>({...k,range:"error",error:q(b,"日期范围无效")}));return}const g=ce(x),h=++D.current,u=new AbortController;return v(b=>({...b,range:"loading",error:""})),Promise.all([H({start_date:x.startDate,end_date:x.endDate},{signal:u.signal}),H({start_date:g.startDate,end_date:g.endDate},{signal:u.signal}),de({start_date:x.startDate,end_date:x.endDate},{signal:u.signal})]).then(([b,k,L])=>{ae(D.current,h,u.signal)&&(M({analytics:b,previousAnalytics:k,validOrders:L,dateRange:x}),v(B=>({...B,range:"success"})))}).catch(b=>{!ae(D.current,h,u.signal)||re(b)||v(k=>({...k,range:"error",error:q(b,"经营数据加载失败")}))}),(()=>u.abort())},[l,r,c]);const f=d.useMemo(()=>o&&w?{...o,...w}:null,[o,w]),_=(o==null?void 0:o.itemNames)||{},m=(w==null?void 0:w.analytics)||null,K=d.useMemo(()=>m?ke(m):[],[m]),C=d.useMemo(()=>m?Ce(m,_):[],[m,_]),y=d.useMemo(()=>["rgb(var(--color-brand))","rgb(var(--color-brand-highlight))","rgb(var(--color-success-500))","rgb(var(--color-warning-500))","rgb(var(--color-accent-500))"],[]),N=d.useMemo(()=>m?Se(m,_,y):[],[m,y,_]),R=d.useMemo(()=>m?De(m,_,y):[],[m,y,_]),I=d.useMemo(()=>Le(C),[C]);return{data:f,status:F,chartData:K,productSalesData:C,sourceData:N,categoryData:R,maxProductSales:I,trendPercent:$e(m,(f==null?void 0:f.previousAnalytics)||null),selectedRangeLabel:Re(P),refresh:$}},i=(s,r)=>r===void 0?`rgb(var(--color-${s}))`:`rgb(var(--color-${s}) / ${r})`,Oe=({chartData:s,selectedRangeLabel:r,totalAmount:a})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[r,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:s.length===0||a===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(ne,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):s.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(fe,{data:s,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(n=>`¥${n}`)}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(n=>[`¥${Number(n).toFixed(2)}`,"营收"])}),e.jsx(ye,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:s.map((n,l)=>e.jsx(V,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${l}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:s,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(Z,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ee,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(ve,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(z,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Ne,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),j=(s,r)=>`rgb(var(--color-${s}))`,Pe=({status:s})=>{const r={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},a={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${r[s]||r.cancelled}`,children:a[s]||s})},W=({title:s,value:r,icon:a,colorClass:n,trend:l})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${n} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${n} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(a,{className:`w-6 h-6 ${n.replace("bg-","text-")}`})}),l&&e.jsxs("span",{className:"text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(pe,{className:"w-3 h-3"})," ",l]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:r}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Ke=()=>{const[s,r]=d.useState("7days"),[a,n]=d.useState(""),[l,o]=d.useState(""),[S,w]=d.useState(""),[M,F]=d.useState(0),v=Ae({range:s,customStartDate:a,customEndDate:l,customRangeVersion:M}),{data:c,status:O,chartData:D,productSalesData:P,sourceData:$,categoryData:f,maxProductSales:_,trendPercent:m,selectedRangeLabel:K,refresh:C}=v,y=(c==null?void 0:c.stats)||null,N=(c==null?void 0:c.analytics)||null;c!=null&&c.previousAnalytics;const R=(c==null?void 0:c.validOrders.orders)||[],I=(c==null?void 0:c.validOrders.total)||0,x=(c==null?void 0:c.validOrders.truncated)||!1,g=O.range==="loading",h=O.error,u=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],b=t=>`¥${Number(t||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!y||!N))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(me,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:C,children:"重新加载"})]});if(!y||!N)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(J,{className:"w-8 h-8 animate-spin text-brand"})});const k=N.revenue_stats.total_orders||0,L=N.revenue_stats.total_amount||0,B=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let T;try{T=le(s,new Date,a,l)}catch{T={startDate:a,endDate:l}}const A=S.trim().toLowerCase(),G=R.filter(t=>{var p,U,Y,X;return((p=t.order_id)==null?void 0:p.toLowerCase().includes(A))||((U=t.item_id)==null?void 0:U.toLowerCase().includes(A))||((Y=t.item_title)==null?void 0:Y.toLowerCase().includes(A))||((X=t.buyer_id)==null?void 0:X.toLowerCase().includes(A))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[h&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:C,children:"重试"})]}),e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[B.map(t=>e.jsx("button",{onClick:(()=>r(t.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${s===t.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:t.label},t.key)),s==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:a,onChange:(t=>n(t.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:l,onChange:(t=>o(t.target.value)),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"}),e.jsx("button",{onClick:(()=>F(t=>t+1)),className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(W,{title:"累计营收 (CNY)",value:`¥${N.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:ue,colorClass:"bg-blue-400",trend:m||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${y.active_cookies} / ${y.total_cookies}`,icon:he,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:N.revenue_stats.total_orders.toLocaleString(),icon:ne,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:y.available_card_stock,icon:ge,colorClass:"bg-purple-500"})]}),e.jsx(Oe,{chartData:D,selectedRangeLabel:K,totalAmount:L}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:P.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:P.map((t,p)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${p<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:p+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:t.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[t.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${Math.max(8,t.sales/_*100)}%`}})})]},`${t.name}-${p}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品下单占比,共 ${k} 单`,children:$.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:$,cx:"50%",cy:"45%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:96,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:$.map((t,p)=>e.jsx(V,{fill:t.color},`cell-${p}`))}),e.jsx(z,{formatter:(t=>`${Number(t||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(we,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(t=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:t}))})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9",children:[e.jsx("span",{className:"text-2xl font-extrabold text-gray-900 tabular-nums",children:k}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总订单"})]})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),x&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",R.length," / ",I," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:S,onChange:(t=>w(t.target.value)),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:g?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(J,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):G.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(Q,{className:"w-7 h-7 text-gray-300"})}),A?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",R.length," 单参与统计,但没有订单号、商品、买家匹配“",S,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",T.startDate," 至 ",T.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",N.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full min-w-[760px] text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4 whitespace-nowrap",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:G.map(t=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(Q,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:t.item_title||t.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:t.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:t.buyer_id}),t.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:xe(t.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",t.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(Pe,{status:t.status||t.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${t.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(be,{className:"w-4 h-4"})})})]},t.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),f.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dashboard-pie-chart h-[280px] relative",role:"img","aria-label":`商品金额分析,总金额 ${b(L)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(te,{accessibilityLayer:!1,children:[e.jsx(se,{data:f,cx:"50%",cy:"50%",innerRadius:60,outerRadius:92,paddingAngle:2,dataKey:"value",activeShape:{outerRadius:98,stroke:"none",strokeWidth:0},rootTabIndex:-1,label:!1,labelLine:!1,children:f.map((t,p)=>e.jsx(V,{fill:t.color||u[p%u.length]},`cell-${p}`))}),e.jsx(z,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(t=>`¥${Number(t||0).toLocaleString()}`)})]})}),e.jsxs("div",{className:"pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"text-lg font-extrabold text-gray-900 tabular-nums",children:b(L)}),e.jsx("span",{className:"text-xs font-medium text-gray-400 mt-0.5",children:"总金额"})]})]}),e.jsx("div",{className:"space-y-3 mt-4",children:f.map(t=>e.jsxs("div",{className:"flex justify-between items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:t.color||u[f.indexOf(t)%u.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:t.name,children:t.name})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0 whitespace-nowrap",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",t.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[t.percentage,"%"]})]})]},t.name))})]})]})]})]})};export{Pe as StatusBadge,Ke as default}; diff --git a/internal/webui/static/assets/ItemList-DX-qMjnd.js b/internal/webui/static/assets/ItemList-kyCurZV6.js similarity index 99% rename from internal/webui/static/assets/ItemList-DX-qMjnd.js rename to internal/webui/static/assets/ItemList-kyCurZV6.js index 3d6e857..b094ce2 100644 --- a/internal/webui/static/assets/ItemList-DX-qMjnd.js +++ b/internal/webui/static/assets/ItemList-kyCurZV6.js @@ -1,2 +1,2 @@ -import{r as a,j as e,b as ue}from"./react-vendor-C_od1ZSF.js";import{Q as Oe,R as ee,S as lt,T as it,U as rt,V as nt,W as ct,X as dt,Y as ot,Z as xt,_ as mt,$ as ht,a0 as ut,a as Ae,a1 as Fe,h as pt}from"./index-DK02p8DH.js";import{a3 as gt,i as Me,R as Ne,N as Re,a4 as ve,a5 as pe,V as bt,F as yt,B as ft,a6 as Ee,a7 as jt,a8 as Nt,A as vt,S as wt,X as re,r as _t,a9 as $e,I as De}from"./icons-vendor-ThcsWkZG.js";const Ue="ydisks-amap-js-api",kt="c9b68d4ce9a2a97f22a4a439404488ca";let ne=null;const Ct=()=>kt,It=()=>window.AMap?Promise.resolve(window.AMap):ne||(ne=new Promise((s,c)=>{const x=document.getElementById(Ue),d=x||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(P)},g=()=>{window.AMap?(m(),s(window.AMap)):(m(),c(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},P=window.setTimeout(()=>{m(),c(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,d.id=Ue,d.async=!0,d.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Ct())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,d.onerror=()=>{m(),c(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},x||document.head.appendChild(d)}).catch(s=>{throw ne=null,s}),ne),ge=s=>Number.isFinite(s)&&s!==0,St=s=>{var m,g;const c=Number((m=s.location)==null?void 0:m.lng),x=Number((g=s.location)==null?void 0:g.lat),d={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:c,latitude:x,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!d.division_id||!d.province||!d.city||!d.poi_id||!d.poi_name||!ge(c)||!ge(x)||c<-180||c>180||x<-90||x>90?null:d},Pt=async(s,c)=>{if(!ge(s)||!ge(c)||s<-180||s>180||c<-90||c>90)throw new Error("经纬度无效");const x=await It();return new Promise((d,m)=>{new x.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,c],1e3,(P,f)=>{var w;if(P!=="complete"){if(P==="no_data"){d([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const A=(((w=f==null?void 0:f.poiList)==null?void 0:w.pois)||[]).map(St).filter(K=>K!==null);d(A)})})},Bt=s=>s.find(c=>c.status==="running"||c.status==="canceling"),_e=s=>s==="running"||s==="canceling",Lt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),At=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!_e(s.status)),Ft=(s,c)=>s===c,qe=s=>{switch(s){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return s||"-"}},Te=s=>{switch(s){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Mt=s=>{const[c,x]=a.useState(!1),[d,m]=a.useState("upload"),[g,P]=a.useState(null),[f,A]=a.useState(null),[w,K]=a.useState(""),[O,Z]=a.useState(!1),[E,J]=a.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[y,N]=a.useState(null),[n,_]=a.useState(null),[I,$]=a.useState(null),[V,D]=a.useState([]),[U,B]=a.useState(null),[q,p]=a.useState(!1),k=a.useRef(!1),o=a.useRef(0),F=a.useCallback(async()=>{m("upload"),N(null),_(null),P(null),A(null),K(""),J({catId:"",catName:"",channelCatId:"",tbCatId:""}),D([]),B(null),x(!0),p(!0);try{const r=await Oe(20),h=Bt(r);if(h!=null&&h.id){const S=await ee(h.id);$(S),_(S),m(["running","canceling"].includes(S.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{p(!1)}},[]),u=a.useCallback(async()=>{const r=w.trim();if(!s.selectedAccount){alert("请先选择默认发布账号");return}if(!r){alert("请输入类目关键词");return}Z(!0);try{const S=(await lt(s.selectedAccount,r)).category;J({catId:S.cat_id,catName:S.cat_name,channelCatId:S.channel_cat_id,tbCatId:S.tb_cat_id||""})}catch(h){console.error("获取推荐类目失败:",h),alert((h==null?void 0:h.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{Z(!1)}},[w,s.selectedAccount]),M=a.useCallback(async()=>{if(I!=null&&I.id){p(!0),x(!0);try{const r=await ee(I.id);_(r),m(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{p(!1)}}},[I==null?void 0:I.id]),te=a.useCallback(async()=>{if(!g){alert("请先上传商品表格");return}if(!s.selectedAccount){alert("请先选择默认发布账号");return}p(!0);try{const r=await it({file:g,imagesZip:f,defaultCookieId:s.selectedAccount,fallbackCategory:E,location:U||void 0});N(r),_(null),m("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{p(!1)}},[E,g,f,U,s.selectedAccount]),W=a.useCallback(async()=>{if(y!=null&&y.preview_id){if(!Lt(y)){alert("没有可发布的商品行");return}p(!0);try{const r=await rt(y.preview_id),h=await ee(r.batch_id||y.preview_id);_(h),$(h),m(h.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{p(!1)}}},[y]),Y=a.useCallback(async()=>{if(n!=null&&n.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){p(!0);try{const r=await nt(n.id),h=await ee(n.id);_(h),m((r==null?void 0:r.status)==="canceling"||h.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{p(!1)}}},[n==null?void 0:n.id]),X=a.useCallback(async()=>{const r=y==null?void 0:y.preview_id;if(r&&d==="preview")try{await ct(r)}catch(h){console.error("清理批量铺货预检失败:",h)}N(null),m("upload")},[d,y==null?void 0:y.preview_id]),Q=a.useCallback(async()=>{await X(),x(!1)},[X]),se=a.useCallback(async()=>{if(!(!(n!=null&&n.id)||!At(n))){p(!0);try{await dt(n.id),_(await ee(n.id)),m("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{p(!1)}}},[n]);return a.useEffect(()=>{if(!c||!(n!=null&&n.id)||!_e(n.status))return;const r=++o.current,h=async()=>{if(!k.current){k.current=!0;try{const T=await ee(n.id);if(!Ft(r,o.current))return;_(T),$(T),_e(T.status)||(m("done"),await Promise.all([s.loadItems(),s.loadShippingRules()]))}catch(T){console.error("刷新批量铺货进度失败:",T)}finally{k.current=!1}}},S=window.setInterval(()=>void h(),3e3);return(()=>{window.clearInterval(S),o.current+=1})},[n==null?void 0:n.id,n==null?void 0:n.status,s.loadItems,s.loadShippingRules,c]),{showBatchModal:c,setShowBatchModal:x,batchLoading:q,batchPhase:d,setBatchPhase:m,batchFile:g,setBatchFile:P,batchImagesZip:f,setBatchImagesZip:A,batchCategoryKeyword:w,setBatchCategoryKeyword:K,batchCategoryLoading:O,batchFallbackCategory:E,setBatchFallbackCategory:J,batchPreview:y,setBatchPreview:N,batchDetail:n,setBatchDetail:_,recentBatch:I,setRecentBatch:$,batchLocations:V,batchLocation:U,setBatchLocations:D,setBatchLocation:B,openBatchModal:F,handleRecommendBatchCategory:u,openRecentBatchResult:M,handlePreviewBatch:te,handleStartBatch:W,handleCancelBatch:Y,abandonBatchPreview:X,closeBatchModal:Q,handleRetryBatchFailed:se}},ze=()=>({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),Ke=(s="")=>({cookie_id:s,title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),we=(s,c)=>{if(s instanceof Error)return s.message;const x=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof x=="string"?x:c},Rt=({selectedAccount:s,setSelectedAccount:c,setItems:x,loadItems:d,loadShippingRules:m,onConfigureDelivery:g,setBatchLocations:P,setBatchLocation:f})=>{const[A,w]=a.useState(!1),[K,O]=a.useState(!1),[Z,E]=a.useState(!1),[J,y]=a.useState(!1),[N,n]=a.useState(!1),[_,I]=a.useState(!1),[$,V]=a.useState([]),[D,U]=a.useState(null),[B,q]=a.useState(null),[p,k]=a.useState({}),[o,F]=a.useState(ze),[u,M]=a.useState(Ke),[te,W]=a.useState([]);a.useEffect(()=>{if(!N||u.images.length===0){W([]);return}const l=u.images.map((j,C)=>({key:j.name+C,url:URL.createObjectURL(j)}));return W(l),(()=>l.forEach(j=>URL.revokeObjectURL(j.url)))},[u.images,N]);const Y=a.useCallback(async()=>{if(!s)return alert("请先选择账号");w(!0);try{const l=await ot(s);await d(),alert((l==null?void 0:l.message)||"商品同步完成")}catch(l){console.error("同步商品失败:",l),alert(we(l,"同步失败,请重试"))}finally{w(!1)}},[d,s]),X=a.useCallback(l=>{q(l),k({...l}),E(!0)},[]),Q=a.useCallback(async()=>{if(B)try{await xt(B.cookie_id,B.item_id,{item_title:p.item_title||"",item_description:p.item_description||"",item_category:p.item_category||"",item_price:p.item_price||"",item_detail:p.item_detail||B.item_detail||""}),await d(),await m(),E(!1),q(null)}catch(l){console.error("更新商品失败:",l),alert("更新失败,请重试")}},[p,d,m,B]),se=a.useCallback(async l=>{if(confirm(`确认删除商品"${l.item_title}"吗?`))try{await mt(l.cookie_id,l.item_id),x(j=>j.filter(C=>!(C.cookie_id===l.cookie_id&&C.item_id===l.item_id)))}catch(j){console.error("删除商品失败:",j),alert("删除失败,请重试")}},[x]),ce=a.useCallback(async()=>{try{if(!o.cookie_id||!o.item_id){alert("请选择账号并填写商品ID");return}await ht(o.cookie_id,{item_id:o.item_id,item_title:o.item_title,item_price:o.item_price,item_detail:o.item_image?JSON.stringify({item_image:o.item_image}):""}),await d(),y(!1),F(ze())}catch(l){console.error("添加商品失败:",l),alert("添加失败,请重试")}},[o,d]),r=a.useCallback(async()=>{if(!u.cookie_id)return alert("请选择发布账号");if(!u.title.trim())return alert("请填写商品标题");if(!u.price.trim())return alert("请填写商品价格");if(!u.quantity||Number(u.quantity)<=0)return alert("库存数量必须大于 0");if(u.images.length===0)return alert("至少上传 1 张商品图片");if(u.postage_mode==="fixed"&&!u.postage.trim())return alert("请填写一口价邮费");O(!0);try{const l=await ut({...u,location:D||void 0});if(await d(),n(!1),M(Ke(s||"")),V([]),U(null),l!=null&&l.item_id){const j={id:l.item_id,cookie_id:u.cookie_id,item_id:l.item_id,item_title:l.item_title||u.title,item_price:l.item_price||u.price,item_image:l.item_image};g(j),alert("商品发布成功,ID: "+l.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(l){console.error("发布商品失败:",l);const j=l==null?void 0:l.payload;if((j==null?void 0:j.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert(we(l,"发布失败,请重试"))}finally{O(!1)}},[d,g,u,D,s]),h=a.useCallback(()=>{const C=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目ID","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","","","","","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","","","","","否","","否","","否","","",""]]].map(ye=>ye.map(fe=>`"${String(fe).replace(/"/g,'""')}"`).join(",")).join(` +import{r as a,j as e,b as ue}from"./react-vendor-C_od1ZSF.js";import{Q as Oe,R as ee,S as lt,T as it,U as rt,V as nt,W as ct,X as dt,Y as ot,Z as xt,_ as mt,$ as ht,a0 as ut,a as Ae,a1 as Fe,h as pt}from"./index-CYPNW7Ux.js";import{a3 as gt,i as Me,R as Ne,N as Re,a4 as ve,a5 as pe,V as bt,F as yt,B as ft,a6 as Ee,a7 as jt,a8 as Nt,A as vt,S as wt,X as re,r as _t,a9 as $e,I as De}from"./icons-vendor-ThcsWkZG.js";const Ue="ydisks-amap-js-api",kt="c9b68d4ce9a2a97f22a4a439404488ca";let ne=null;const Ct=()=>kt,It=()=>window.AMap?Promise.resolve(window.AMap):ne||(ne=new Promise((s,c)=>{const x=document.getElementById(Ue),d=x||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(P)},g=()=>{window.AMap?(m(),s(window.AMap)):(m(),c(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},P=window.setTimeout(()=>{m(),c(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,d.id=Ue,d.async=!0,d.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Ct())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,d.onerror=()=>{m(),c(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},x||document.head.appendChild(d)}).catch(s=>{throw ne=null,s}),ne),ge=s=>Number.isFinite(s)&&s!==0,St=s=>{var m,g;const c=Number((m=s.location)==null?void 0:m.lng),x=Number((g=s.location)==null?void 0:g.lat),d={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:c,latitude:x,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!d.division_id||!d.province||!d.city||!d.poi_id||!d.poi_name||!ge(c)||!ge(x)||c<-180||c>180||x<-90||x>90?null:d},Pt=async(s,c)=>{if(!ge(s)||!ge(c)||s<-180||s>180||c<-90||c>90)throw new Error("经纬度无效");const x=await It();return new Promise((d,m)=>{new x.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,c],1e3,(P,f)=>{var w;if(P!=="complete"){if(P==="no_data"){d([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const A=(((w=f==null?void 0:f.poiList)==null?void 0:w.pois)||[]).map(St).filter(K=>K!==null);d(A)})})},Bt=s=>s.find(c=>c.status==="running"||c.status==="canceling"),_e=s=>s==="running"||s==="canceling",Lt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),At=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!_e(s.status)),Ft=(s,c)=>s===c,qe=s=>{switch(s){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return s||"-"}},Te=s=>{switch(s){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Mt=s=>{const[c,x]=a.useState(!1),[d,m]=a.useState("upload"),[g,P]=a.useState(null),[f,A]=a.useState(null),[w,K]=a.useState(""),[O,Z]=a.useState(!1),[E,J]=a.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[y,N]=a.useState(null),[n,_]=a.useState(null),[I,$]=a.useState(null),[V,D]=a.useState([]),[U,B]=a.useState(null),[q,p]=a.useState(!1),k=a.useRef(!1),o=a.useRef(0),F=a.useCallback(async()=>{m("upload"),N(null),_(null),P(null),A(null),K(""),J({catId:"",catName:"",channelCatId:"",tbCatId:""}),D([]),B(null),x(!0),p(!0);try{const r=await Oe(20),h=Bt(r);if(h!=null&&h.id){const S=await ee(h.id);$(S),_(S),m(["running","canceling"].includes(S.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{p(!1)}},[]),u=a.useCallback(async()=>{const r=w.trim();if(!s.selectedAccount){alert("请先选择默认发布账号");return}if(!r){alert("请输入类目关键词");return}Z(!0);try{const S=(await lt(s.selectedAccount,r)).category;J({catId:S.cat_id,catName:S.cat_name,channelCatId:S.channel_cat_id,tbCatId:S.tb_cat_id||""})}catch(h){console.error("获取推荐类目失败:",h),alert((h==null?void 0:h.message)||"没有匹配到类目,请换一个更具体的关键词")}finally{Z(!1)}},[w,s.selectedAccount]),M=a.useCallback(async()=>{if(I!=null&&I.id){p(!0),x(!0);try{const r=await ee(I.id);_(r),m(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{p(!1)}}},[I==null?void 0:I.id]),te=a.useCallback(async()=>{if(!g){alert("请先上传商品表格");return}if(!s.selectedAccount){alert("请先选择默认发布账号");return}p(!0);try{const r=await it({file:g,imagesZip:f,defaultCookieId:s.selectedAccount,fallbackCategory:E,location:U||void 0});N(r),_(null),m("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{p(!1)}},[E,g,f,U,s.selectedAccount]),W=a.useCallback(async()=>{if(y!=null&&y.preview_id){if(!Lt(y)){alert("没有可发布的商品行");return}p(!0);try{const r=await rt(y.preview_id),h=await ee(r.batch_id||y.preview_id);_(h),$(h),m(h.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{p(!1)}}},[y]),Y=a.useCallback(async()=>{if(n!=null&&n.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){p(!0);try{const r=await nt(n.id),h=await ee(n.id);_(h),m((r==null?void 0:r.status)==="canceling"||h.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{p(!1)}}},[n==null?void 0:n.id]),X=a.useCallback(async()=>{const r=y==null?void 0:y.preview_id;if(r&&d==="preview")try{await ct(r)}catch(h){console.error("清理批量铺货预检失败:",h)}N(null),m("upload")},[d,y==null?void 0:y.preview_id]),Q=a.useCallback(async()=>{await X(),x(!1)},[X]),se=a.useCallback(async()=>{if(!(!(n!=null&&n.id)||!At(n))){p(!0);try{await dt(n.id),_(await ee(n.id)),m("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{p(!1)}}},[n]);return a.useEffect(()=>{if(!c||!(n!=null&&n.id)||!_e(n.status))return;const r=++o.current,h=async()=>{if(!k.current){k.current=!0;try{const T=await ee(n.id);if(!Ft(r,o.current))return;_(T),$(T),_e(T.status)||(m("done"),await Promise.all([s.loadItems(),s.loadShippingRules()]))}catch(T){console.error("刷新批量铺货进度失败:",T)}finally{k.current=!1}}},S=window.setInterval(()=>void h(),3e3);return(()=>{window.clearInterval(S),o.current+=1})},[n==null?void 0:n.id,n==null?void 0:n.status,s.loadItems,s.loadShippingRules,c]),{showBatchModal:c,setShowBatchModal:x,batchLoading:q,batchPhase:d,setBatchPhase:m,batchFile:g,setBatchFile:P,batchImagesZip:f,setBatchImagesZip:A,batchCategoryKeyword:w,setBatchCategoryKeyword:K,batchCategoryLoading:O,batchFallbackCategory:E,setBatchFallbackCategory:J,batchPreview:y,setBatchPreview:N,batchDetail:n,setBatchDetail:_,recentBatch:I,setRecentBatch:$,batchLocations:V,batchLocation:U,setBatchLocations:D,setBatchLocation:B,openBatchModal:F,handleRecommendBatchCategory:u,openRecentBatchResult:M,handlePreviewBatch:te,handleStartBatch:W,handleCancelBatch:Y,abandonBatchPreview:X,closeBatchModal:Q,handleRetryBatchFailed:se}},ze=()=>({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),Ke=(s="")=>({cookie_id:s,title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),we=(s,c)=>{if(s instanceof Error)return s.message;const x=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof x=="string"?x:c},Rt=({selectedAccount:s,setSelectedAccount:c,setItems:x,loadItems:d,loadShippingRules:m,onConfigureDelivery:g,setBatchLocations:P,setBatchLocation:f})=>{const[A,w]=a.useState(!1),[K,O]=a.useState(!1),[Z,E]=a.useState(!1),[J,y]=a.useState(!1),[N,n]=a.useState(!1),[_,I]=a.useState(!1),[$,V]=a.useState([]),[D,U]=a.useState(null),[B,q]=a.useState(null),[p,k]=a.useState({}),[o,F]=a.useState(ze),[u,M]=a.useState(Ke),[te,W]=a.useState([]);a.useEffect(()=>{if(!N||u.images.length===0){W([]);return}const l=u.images.map((j,C)=>({key:j.name+C,url:URL.createObjectURL(j)}));return W(l),(()=>l.forEach(j=>URL.revokeObjectURL(j.url)))},[u.images,N]);const Y=a.useCallback(async()=>{if(!s)return alert("请先选择账号");w(!0);try{const l=await ot(s);await d(),alert((l==null?void 0:l.message)||"商品同步完成")}catch(l){console.error("同步商品失败:",l),alert(we(l,"同步失败,请重试"))}finally{w(!1)}},[d,s]),X=a.useCallback(l=>{q(l),k({...l}),E(!0)},[]),Q=a.useCallback(async()=>{if(B)try{await xt(B.cookie_id,B.item_id,{item_title:p.item_title||"",item_description:p.item_description||"",item_category:p.item_category||"",item_price:p.item_price||"",item_detail:p.item_detail||B.item_detail||""}),await d(),await m(),E(!1),q(null)}catch(l){console.error("更新商品失败:",l),alert("更新失败,请重试")}},[p,d,m,B]),se=a.useCallback(async l=>{if(confirm(`确认删除商品"${l.item_title}"吗?`))try{await mt(l.cookie_id,l.item_id),x(j=>j.filter(C=>!(C.cookie_id===l.cookie_id&&C.item_id===l.item_id)))}catch(j){console.error("删除商品失败:",j),alert("删除失败,请重试")}},[x]),ce=a.useCallback(async()=>{try{if(!o.cookie_id||!o.item_id){alert("请选择账号并填写商品ID");return}await ht(o.cookie_id,{item_id:o.item_id,item_title:o.item_title,item_price:o.item_price,item_detail:o.item_image?JSON.stringify({item_image:o.item_image}):""}),await d(),y(!1),F(ze())}catch(l){console.error("添加商品失败:",l),alert("添加失败,请重试")}},[o,d]),r=a.useCallback(async()=>{if(!u.cookie_id)return alert("请选择发布账号");if(!u.title.trim())return alert("请填写商品标题");if(!u.price.trim())return alert("请填写商品价格");if(!u.quantity||Number(u.quantity)<=0)return alert("库存数量必须大于 0");if(u.images.length===0)return alert("至少上传 1 张商品图片");if(u.postage_mode==="fixed"&&!u.postage.trim())return alert("请填写一口价邮费");O(!0);try{const l=await ut({...u,location:D||void 0});if(await d(),n(!1),M(Ke(s||"")),V([]),U(null),l!=null&&l.item_id){const j={id:l.item_id,cookie_id:u.cookie_id,item_id:l.item_id,item_title:l.item_title||u.title,item_price:l.item_price||u.price,item_image:l.item_image};g(j),alert("商品发布成功,ID: "+l.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(l){console.error("发布商品失败:",l);const j=l==null?void 0:l.payload;if((j==null?void 0:j.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert(we(l,"发布失败,请重试"))}finally{O(!1)}},[d,g,u,D,s]),h=a.useCallback(()=>{const C=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","类目ID","类目名称","频道类目ID","淘宝类目ID","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","","","","","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","","","","","否","","否","","否","","",""]]].map(ye=>ye.map(fe=>`"${String(fe).replace(/"/g,'""')}"`).join(",")).join(` `),L=new Blob(["\uFEFF"+C],{type:"text/csv;charset=utf-8"}),de=URL.createObjectURL(L),H=document.createElement("a");H.href=de,H.download="批量铺货模板.csv",document.body.appendChild(H),H.click(),H.remove(),URL.revokeObjectURL(de)},[]),S=a.useCallback(()=>{F(l=>({...l,cookie_id:s||l.cookie_id})),y(!0)},[s]),T=a.useCallback(()=>{M(l=>({...l,cookie_id:s||l.cookie_id})),n(!0)},[s]),be=a.useCallback(async l=>{if(!(l?s:u.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");I(!0),navigator.geolocation.getCurrentPosition(async C=>{try{const L=await Pt(C.coords.longitude,C.coords.latitude);if(!L.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");l?(P(L),f(L[0])):(V(L),U(L[0]))}catch(L){alert(we(L,"获取发货地失败"))}finally{I(!1)}},C=>{I(!1),alert(C.code===C.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[u.cookie_id,s,f,P]);return{selectedAccount:s,setSelectedAccount:c,loading:A,publishing:K,showEditModal:Z,setShowEditModal:E,showAddModal:J,setShowAddModal:y,showPublishModal:N,setShowPublishModal:n,locationLoading:_,publishLocations:$,setPublishLocations:V,publishLocation:D,setPublishLocation:U,selectedItem:B,editForm:p,setEditForm:k,addForm:o,setAddForm:F,publishForm:u,setPublishForm:M,publishImagePreviews:te,handleSync:Y,handleEdit:X,handleSaveEdit:Q,handleDelete:se,handleAddItem:ce,handlePublishItem:r,downloadPublishTemplate:h,openAddModal:S,openPublishModal:T,locateForPublish:be}},Et=({phase:s})=>{const c=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:c.map(([x,d])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===x?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:d},x))})},$t=s=>{const c=String(s||"").trim();return c?/^[¥¥]/.test(c)?c:`¥${c}`:"-"},Tt=({onConfigureDelivery:s})=>{const[c,x]=a.useState([]),[d,m]=a.useState([]),[g,P]=a.useState([]),[f,A]=a.useState(""),[w,K]=a.useState(""),O=a.useCallback(async()=>{const t=await Ae();x(t)},[]),Z=a.useCallback(async()=>{m(await Fe())},[]),E=Mt({selectedAccount:f,loadItems:O,loadShippingRules:Z}),{showBatchModal:J,setShowBatchModal:y,batchLoading:N,batchPhase:n,batchFile:_,setBatchFile:I,batchImagesZip:$,setBatchImagesZip:V,batchCategoryKeyword:D,setBatchCategoryKeyword:U,batchCategoryLoading:B,batchFallbackCategory:q,setBatchFallbackCategory:p,batchPreview:k,batchDetail:o,recentBatch:F,setRecentBatch:u,batchLocations:M,batchLocation:te,setBatchLocations:W,setBatchLocation:Y,openBatchModal:X,handleRecommendBatchCategory:Q,openRecentBatchResult:se,handlePreviewBatch:ce,handleStartBatch:r,handleCancelBatch:h,abandonBatchPreview:S,closeBatchModal:T,handleRetryBatchFailed:be}=E,l=Rt({selectedAccount:f,setSelectedAccount:A,setItems:x,loadItems:O,loadShippingRules:Z,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Y}),{loading:j,publishing:C,showEditModal:L,setShowEditModal:de,showAddModal:H,setShowAddModal:ye,showPublishModal:fe,setShowPublishModal:Ze,locationLoading:oe,publishLocations:xe,setPublishLocations:Ge,publishLocation:Je,setPublishLocation:ke,selectedItem:Ce,editForm:G,setEditForm:me,addForm:R,setAddForm:ae,publishForm:b,setPublishForm:z,publishImagePreviews:Ie,handleSync:Ve,handleEdit:We,handleSaveEdit:Ye,handleDelete:Xe,handleAddItem:He,handlePublishItem:Qe,downloadPublishTemplate:et,openAddModal:tt,openPublishModal:st,locateForPublish:Se}=l;a.useEffect(()=>{Promise.all([pt(),Ae(),Fe(),Oe(20)]).then(([t,i,v,ie])=>{P(t),x(i),m(v);const he=ie.find(je=>["running","canceling"].includes(je.status))||ie.find(je=>je.status!=="preview");u(he||null)}).catch(t=>console.error("加载商品配置失败:",t))},[]);const at=t=>d.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id).length>0?d.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id):d.filter(i=>i.cookie_id===t.cookie_id&&!i.item_id),Pe=a.useMemo(()=>new Map(g.map(t=>[t.id,t])),[g]),Be=a.useMemo(()=>w?c.filter(t=>t.cookie_id===w):c,[w,c]),le=t=>{const i=Pe.get(t),v=(i==null?void 0:i.remark)||(i==null?void 0:i.nickname);return v?`${v} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Le=t=>{const i=Pe.get(t);return(i==null?void 0:i.remark)||(i==null?void 0:i.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(gt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:w,onChange:(t=>K(t.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(t=>e.jsx("option",{value:t.id,children:le(t.id)},t.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(Me,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:f,onChange:(t=>A(t.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:le(t.id)},t.id))]})]})]}),e.jsxs("button",{onClick:Ve,disabled:j||!f,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Ne,{className:`w-4 h-4 ${j?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:tt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Re,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:st,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(ve,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void X()),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(pe,{className:"w-4 h-4"}),F&&["running","canceling"].includes(F.status)?"继续批量任务":"批量铺货"]}),F&&!["running","canceling"].includes(F.status)&&e.jsx("button",{onClick:(()=>void se()),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Be.map(t=>{const i=at(t),v=i.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:(()=>We(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors",title:"编辑",children:e.jsx(bt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>Xe(t)),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(yt,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[t.item_image?e.jsx("img",{src:t.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(ft,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:$t(t.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:t.item_title}),e.jsxs("div",{className:"mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:Le(t.cookie_id),children:[e.jsx(Me,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:Le(t.cookie_id)})]}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",t.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${v?"text-emerald-600":"text-amber-600"}`,children:[v?e.jsx(Ee,{className:"w-3 h-3"}):e.jsx(jt,{className:"w-3 h-3"}),v?`${i.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:(()=>s(t)),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${v?"bg-gray-900 text-white hover:bg-black":"bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nt,{className:"w-3.5 h-3.5"}),v?"查看发货规则":"关联发货规则"]}),e.jsx(vt,{className:"w-3.5 h-3.5"})]})})]},`${t.cookie_id}-${t.item_id}`)}),Be.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(wt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),w?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),L&&Ce&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",Ce.item_id]})]}),e.jsx("button",{onClick:(()=>de(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:G.item_title||"",onChange:(t=>me({...G,item_title:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:G.item_price||"",onChange:(t=>me({...G,item_price:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:G.item_category||"",onChange:(t=>me({...G,item_category:t.target.value}))}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:G.item_description||"",onChange:(t=>me({...G,item_description:t.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:Ye,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(_t,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),H&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:(()=>ye(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:R.cookie_id,onChange:(t=>ae({...R,cookie_id:t.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:le(t.id)},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:R.item_id,onChange:(t=>ae({...R,item_id:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:R.item_price,onChange:(t=>ae({...R,item_price:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:R.item_title,onChange:(t=>ae({...R,item_title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:R.item_image,onChange:(t=>ae({...R,item_image:t.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:He,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Re,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),fe&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:(()=>Ze(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",children:"发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:b.cookie_id,onChange:(t=>{z({...b,cookie_id:t.target.value}),Ge([]),ke(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:le(t.id)},t.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:b.title,onChange:(t=>z({...b,title:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:b.quantity,onChange:(t=>z({...b,quantity:t.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:b.description,onChange:(t=>z({...b,description:t.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"售价"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:b.price,onChange:(t=>z({...b,price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:b.original_price,onChange:(t=>z({...b,original_price:t.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:b.postage_mode,onChange:(t=>z({...b,postage_mode:t.target.value})),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),b.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:b.postage,onChange:(t=>z({...b,postage:t.target.value}))})]}),e.jsxs("div",{className:"rounded-2xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品无需发货地;发布失败时可再定位并作为补充信息提交。"})]}),e.jsxs("button",{type:"button",disabled:oe||!b.cookie_id,onClick:(()=>void Se(!1)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx($e,{className:"h-4 w-4"}),oe?"定位中...":"获取当前位置"]})]}),xe.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,xe.indexOf(Je))),onChange:(t=>ke(xe[Number(t.target.value)]||null)),children:xe.map((t,i)=>e.jsx("option",{value:String(i),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${i}`))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(pe,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:b.images.length?"已选择 "+b.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:(t=>z({...b,images:Array.from(t.target.files||[]).slice(0,9)}))})]}),Ie.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:Ie.map(t=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:t.url,alt:"",className:"w-full h-full object-cover"})},t.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:C,onClick:Qe,className:"w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ve,{className:"w-4 h-4"}),C?"正在发布...":"发布到闲鱼"]})})]})}),document.body),J&&ue.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:(()=>void T()),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(re,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx(Et,{phase:n}),n==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:et,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:f,onChange:(t=>{A(t.target.value),W([]),Y(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:le(t.id)},t.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-extrabold text-gray-900",children:["默认类目 ",e.jsx("span",{className:"font-medium text-gray-500",children:"(可为空)"})]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-amber-800",children:"填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。"})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs("label",{className:"relative flex-1",children:[e.jsx("span",{className:"sr-only",children:"类目关键词"}),e.jsx(De,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3",placeholder:"输入关键词,例如:课程资料、设计素材",value:D,onChange:(t=>U(t.target.value)),onKeyDown:(t=>{t.key==="Enter"&&(t.preventDefault(),Q())})})]}),e.jsxs("button",{type:"button",disabled:!f||!D.trim()||B,onClick:(()=>void Q()),className:"ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50",children:[e.jsx(De,{className:"h-4 w-4"}),B?"匹配中...":"获取类目"]})]}),q.catId?e.jsxs("div",{className:"flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold text-gray-900",children:[e.jsx(Ee,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:q.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",q.catId," · 频道 ",q.channelCatId]})]}),e.jsx("button",{type:"button",title:"清除默认类目",onClick:(()=>p({catId:"",catName:"",channelCatId:"",tbCatId:""})),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900",children:e.jsx(re,{className:"h-4 w-4"})})]}):null]}),e.jsxs("div",{className:"rounded-xl border border-sky-200 bg-sky-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"批次发货地(可选)"}),e.jsx("p",{className:"mt-1 text-xs text-sky-800",children:"虚拟商品可留空;填写后整个批次使用同一个发货地,并随任务保存用于恢复和重试。"})]}),e.jsxs("button",{type:"button",disabled:oe||!f,onClick:(()=>void Se(!0)),className:"ios-btn-primary flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold disabled:opacity-50",children:[e.jsx($e,{className:"h-4 w-4"}),oe?"定位中...":"获取当前位置"]})]}),M.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,M.indexOf(te))),onChange:(t=>Y(M[Number(t.target.value)]||null)),children:M.map((t,i)=>e.jsx("option",{value:String(i),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${i}`))})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors",children:[e.jsx(pe,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:_?_.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:(t=>{var i;return I(((i=t.target.files)==null?void 0:i[0])||null)})})]}),e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(pe,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:$?$.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:(t=>{var i;return V(((i=t.target.files)==null?void 0:i[0])||null)})})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","需要覆盖默认账号时填写","上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["类目ID","需要指定当前行默认类目时填写","必须和“类目名称、频道类目ID”同时填写;优先于自动识别"],["类目名称","填写了“类目ID”时必填","填写该 ID 对应的准确类目名称"],["频道类目ID","覆盖类目时必填","必须填写闲鱼返回的准确频道类目 ID"],["淘宝类目ID","按闲鱼返回填写","“电子资料”无淘宝类目 ID,保持为空"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([t,i,v])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:t}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${i==="每个商品都要填"?"text-red-600":i==="可以留空"?"text-gray-500":"text-amber-700"}`,children:i}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:v})]},t))})]})})]})]}),n==="preview"&&k&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:k.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:k.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:k.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:k.rows.map(t=>{var i,v,ie,he;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${t.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:t.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:t.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",t.price||"-"," / ",t.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((i=t.category)==null?void 0:i.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((v=t.category)==null?void 0:v.cat_id)||"失败后使用电子资料"})]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((ie=t.images)==null?void 0:ie.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((he=t.errors)==null?void 0:he.join(";"))||"-"})]},t.row_no)})})]})})]}),(n==="running"||n==="done")&&o&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${Te(o.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:qe(o.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:o.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:o.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:o.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:o.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"类目策略"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:o.rows.map(t=>{var i,v;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:t.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${Te(t.status)}`,children:qe(t.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:t.title}),e.jsxs("td",{className:"px-4 py-3 text-xs text-gray-600 min-w-[150px]",children:[e.jsx("div",{className:"font-bold text-gray-800",children:((i=t.category)==null?void 0:i.cat_name)||"自动识别"}),e.jsx("div",{className:"font-mono text-gray-400",children:((v=t.category)==null?void 0:v.cat_id)||"失败后使用电子资料"})]}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:t.item_url?e.jsx("a",{href:t.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:t.item_id}):t.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:t.error_message||"-"})]},t.id)})})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[n==="upload"&&e.jsxs("button",{disabled:N||!_||!f,onClick:ce,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Ne,{className:`w-4 h-4 ${N?"animate-spin":""}`}),N?"正在预检...":"开始预检"]}),n==="preview"&&k&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:N,onClick:(()=>void S()),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:N||k.valid<=0,onClick:r,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(ve,{className:"w-4 h-4"}),N?"启动中...":`确认发布 ${k.valid} 个商品`]})]}),(n==="running"||n==="done")&&o&&e.jsxs("div",{className:"flex gap-3 w-full",children:[o.status==="running"?e.jsx("button",{disabled:N,onClick:h,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):o.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:(()=>window.open(`/api/v1/items/publish-batches/${o.id}/result.csv`,"_blank")),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),o.retryable>0&&!["running","canceling"].includes(o.status)&&e.jsxs("button",{disabled:N,onClick:be,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ne,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(o.status)&&e.jsx("button",{onClick:(()=>{y(!1),O(),Z()}),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})};export{Tt as default}; diff --git a/internal/webui/static/assets/Notifications-D65tIfCl.js b/internal/webui/static/assets/Notifications-CyWpiVXa.js similarity index 99% rename from internal/webui/static/assets/Notifications-D65tIfCl.js rename to internal/webui/static/assets/Notifications-CyWpiVXa.js index 840ade9..059f7e7 100644 --- a/internal/webui/static/assets/Notifications-D65tIfCl.js +++ b/internal/webui/static/assets/Notifications-CyWpiVXa.js @@ -1 +1 @@ -import{j as e,b as be,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as fe,x as G,a as W,f as I,y as ye,F as je,s as J,X as te,u as ae,v as le,r as Ne,R as _e,N as ve}from"./icons-vendor-ThcsWkZG.js";import{n as we,a3 as ke,al as Y,am as Ce,an as Se,ao as Te,a5 as Pe}from"./index-DK02p8DH.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],Q=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},re=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?Q(s.use_custom_smtp,!1):a}},ne=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=Q(a.smtp_use_tls,!0),a.smtp_use_ssl=Q(a.smtp_use_ssl,!1),a},oe=s=>{const t=re(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},$={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:G,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:G,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:G,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:fe,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:ee,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},ce=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],Z=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Ee=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=ce.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Me=(s,t)=>{const a=s.type==="email"?re({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ne(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},qe=s=>{const a=$[s.type].fields.find(n=>n.required&&!String(s.config[n.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const n=oe(s.config);if(n.use_custom_smtp){const w=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([g])=>!String(n[g]||"").trim());if(w)return`请填写 ${w[1]}`}}return""},Re=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?oe(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),h=(s,t)=>s===t,A=(s,t)=>s instanceof Error&&s.message?s.message:t,Le=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:w})=>{const g=r=>s.find(o=>o.id===r.currentTarget.dataset.channelId)||null,N=r=>{const o=g(r);o&&b(o)},C=r=>{const o=g(r);o&&w(o)},E=r=>{const o=g(r);o&&a(o)},j=r=>{const o=g(r);o&&n(o)},M=r=>{const o=$[r.type]||$.webhook,P=o.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(P,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:r.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!r.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:o.fields.map(x=>{var k;return(k=r.config)==null?void 0:k[x.key]}).filter(Boolean).map((x,k)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},k))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Ee(r.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":r.id,onClick:N,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${r.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:r.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":r.id,onClick:C,disabled:t===r.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[t===r.id?e.jsx(I,{className:"w-3 h-3 animate-spin"}):e.jsx(se,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":r.id,onClick:E,className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(ye,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":r.id,onClick:j,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(je,{className:"w-4 h-4"})})]})]},r.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(W,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:s.map(M)})},Be=({selectedEvents:s,onToggleEvent:t})=>{const a=n=>{const b=n.currentTarget.dataset.event;b&&t(b)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:ce.map(n=>{const b=s.includes(n.value);return e.jsxs("button",{type:"button","data-event":n.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${b?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${b?"bg-brand border-brand":"border-gray-300"}`,children:b&&e.jsx(J,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:n.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:n.description})]},n.value)})})]})},$e=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:w,setShowChannelSmtpPassword:g,saving:N,onClose:C,onSave:E})=>{const j=$[a.type],M=l=>n(m=>({...m,name:l.target.value})),r=l=>{const m=l.currentTarget.dataset.type;m&&n(_=>({..._,type:m,config:{}}))},o=l=>{const m=l.currentTarget.dataset.field;m&&n(_=>({..._,config:{..._.config,[m]:l.target.value}}))},P=()=>n(l=>({...l,config:l.config.use_custom_smtp===!0?{...l.config,use_custom_smtp:!1}:ne(l.config,b)})),x=l=>n(m=>({...m,config:{...m.config,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:m.config.smtp_use_ssl}})),k=l=>n(m=>({...m,config:{...m.config,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:m.config.smtp_use_tls}})),U=l=>n(m=>({...m,event_types:m.event_types.includes(l)?m.event_types.filter(_=>_!==l):[...m.event_types,l]})),D=()=>n(l=>({...l,enabled:!l.enabled})),X=()=>g(l=>!l),z=(l,m)=>e.jsx("li",{children:l},m);return s?be.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:C,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(te,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:a.name,onChange:M,placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys($).map(l=>{const m=$[l],_=m.icon,q=a.type===l;return e.jsxs("button",{"data-type":l,type:"button",onClick:r,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${q?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(_,{className:`w-5 h-5 ${q?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${q?"text-brand":"text-gray-600"}`,children:m.label})]},l)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",j.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:j.guide.steps.map(z)}),j.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:j.guide.urlFormat})]}),j.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",j.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:j.fields.map(l=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[l.label,l.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":l.key,type:l.type==="password"?"password":l.type==="number"?"number":"text",value:String(a.config[l.key]||""),onChange:o,placeholder:l.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),l.help&&e.jsx("p",{className:"text-xs text-gray-500",children:l.help})]},l.key))}),a.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.config.use_custom_smtp===!0?"bg-brand":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{"data-field":"smtp_password",type:w?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:X,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:w?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_tls!==!1,onChange:x}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_ssl===!0,onChange:k}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Be,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:D,className:`relative w-11 h-6 rounded-full transition-colors ${a.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${a.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:C,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:E,disabled:N,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[N?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(J,{className:"w-4 h-4"}),N?"保存中...":"保存"]})]})]})}),document.body):null},Fe=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:w})=>{const g=r=>{const o=r.currentTarget.dataset.field;o&&t(P=>({...P,[o]:r.target.value}))},N=r=>{t(o=>({...o,smtp_port:parseInt(r.target.value,10)||587}))},C=r=>{t(o=>({...o,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:o.smtp_use_ssl}))},E=r=>{t(o=>({...o,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:o.smtp_use_tls}))},j=r=>{t(o=>({...o,smtp_password:r.target.value}))},M=()=>b(r=>!r);return e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(ee,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:s.smtp_server||"",onChange:g,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:s.smtp_port||587,onChange:N,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:s.smtp_user||"",onChange:g,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:n?"text":"password",value:s.smtp_password||"",onChange:j,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:n?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:s.smtp_from_name||"",onChange:g,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:s.smtp_from_address||s.smtp_user||"",onChange:g,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:C}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:w,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Ne,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},Ae=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[w,g]=d.useState(!1),[N,C]=d.useState(null),[E,j]=d.useState(!1),[M,r]=d.useState(""),[o,P]=d.useState(null),[x,k]=d.useState({}),[U,D]=d.useState(!1),[X,z]=d.useState(!1),[l,m]=d.useState(!1),[_,q]=d.useState(Z),F=d.useRef(0),K=d.useRef(null),S=d.useRef(0),L=d.useRef(null),f=d.useRef(0),T=d.useRef(null),B=d.useRef(null),y=d.useCallback((c,i)=>{P({type:c,text:i}),B.current!==null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{B.current=null,P(null)},3e3)},[]),R=d.useCallback(async()=>{var p;const c=++F.current;(p=K.current)==null||p.abort();const i=new AbortController;K.current=i,b(!0);try{const u=await we({signal:i.signal});if(!h(c,F.current))return;a(u.data||[])}catch(u){h(c,F.current)&&!i.signal.aborted&&console.error("加载通知渠道失败",u)}finally{h(c,F.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i;try{const u=await ke({signal:i.signal});h(c,S.current)&&k(u||{})}catch(u){h(c,S.current)&&!i.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var c;return R(),s?V():(S.current+=1,(c=L.current)==null||c.abort(),k({})),(()=>{var i,p;F.current+=1,(i=K.current)==null||i.abort(),S.current+=1,(p=L.current)==null||p.abort()})},[s,R,V]),d.useEffect(()=>(()=>{B.current!==null&&window.clearTimeout(B.current)}),[]);const ie=d.useCallback(()=>{C(null),q(Z()),m(!1),g(!0)},[]),de=d.useCallback(c=>{C(c),q(Me(c,x)),m(!1),g(!0)},[x]),me=d.useCallback(()=>{var c;f.current+=1,(c=T.current)==null||c.abort(),j(!1),g(!1)},[]),pe=d.useCallback(async()=>{var u;const c=qe(_);if(c){y("error",c);return}const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p,j(!0);try{const v=Re(_);if(N?await Y(N.id,v,{signal:p.signal}):await Ce(v,{signal:p.signal}),!h(i,f.current)||(g(!1),await R(),!h(i,f.current)))return;y("success",N?"已更新":"已创建")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"保存失败"))}finally{h(i,f.current)&&j(!1)}},[N,_,R,y]),ue=d.useCallback(async c=>{var u;if(!confirm(`确认删除渠道「${c.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Se(c.id,{signal:p.signal}),!h(i,f.current)||(await R(),!h(i,f.current)))return;y("success","已删除")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"删除失败"))}},[R,y]),xe=d.useCallback(async c=>{var u;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Y(c.id,{enabled:!c.enabled},{signal:p.signal}),!h(i,f.current))return;a(v=>v.map(O=>O.id===c.id?{...O,enabled:!O.enabled}:O))}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"切换失败"))}},[y]),he=d.useCallback(async c=>{var u;r(c.id);const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{await Te(c.id,{signal:p.signal}),h(i,f.current)&&y("success","测试通知已发送,请检查对应渠道")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"发送失败"))}finally{h(i,f.current)&&r("")}},[y]),ge=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i,D(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Pe(u,{signal:i.signal}),h(c,S.current)&&y("success","SMTP 配置已保存")}catch(u){h(c,S.current)&&!i.signal.aborted&&y("error",A(u,"保存失败"))}finally{h(c,S.current)&&D(!1)}},[y,x]);return{channels:t,loading:n,showModal:w,editing:N,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:X,showChannelSmtpPassword:l,form:_,setForm:q,setSmtp:k,setShowSmtpPassword:z,setShowChannelSmtpPassword:m,loadChannels:R,openCreate:ie,openEdit:de,closeModal:me,showToast:y,handleSave:pe,handleDelete:ue,handleToggleEnabled:xe,handleTest:he,handleSaveSmtp:ge}},Ie=({isAdmin:s=!1})=>{const t=Ae(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(_e,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(ve,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(W,{className:"w-5 h-5 text-brand mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(I,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Le,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Fe,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx($e,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&e.jsxs("div",{className:`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(J,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{Ie as default}; +import{j as e,b as be,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as fe,x as G,a as W,f as I,y as ye,F as je,s as J,X as te,u as ae,v as le,r as Ne,R as _e,N as ve}from"./icons-vendor-ThcsWkZG.js";import{n as we,a3 as ke,al as Y,am as Ce,an as Se,ao as Te,a5 as Pe}from"./index-CYPNW7Ux.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],Q=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},re=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?Q(s.use_custom_smtp,!1):a}},ne=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=Q(a.smtp_use_tls,!0),a.smtp_use_ssl=Q(a.smtp_use_ssl,!1),a},oe=s=>{const t=re(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},$={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:G,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:G,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:G,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:fe,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:ee,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},ce=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],Z=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Ee=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=ce.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Me=(s,t)=>{const a=s.type==="email"?re({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ne(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},qe=s=>{const a=$[s.type].fields.find(n=>n.required&&!String(s.config[n.key]||"").trim());if(a)return`请填写 ${a.label}`;if(!s.name.trim())return"请填写渠道名称";if(s.type==="email"){const n=oe(s.config);if(n.use_custom_smtp){const w=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([g])=>!String(n[g]||"").trim());if(w)return`请填写 ${w[1]}`}}return""},Re=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?oe(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),h=(s,t)=>s===t,A=(s,t)=>s instanceof Error&&s.message?s.message:t,Le=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:w})=>{const g=r=>s.find(o=>o.id===r.currentTarget.dataset.channelId)||null,N=r=>{const o=g(r);o&&b(o)},C=r=>{const o=g(r);o&&w(o)},E=r=>{const o=g(r);o&&a(o)},j=r=>{const o=g(r);o&&n(o)},M=r=>{const o=$[r.type]||$.webhook,P=o.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(P,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:r.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:o.label}),!r.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:o.fields.map(x=>{var k;return(k=r.config)==null?void 0:k[x.key]}).filter(Boolean).map((x,k)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},k))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Ee(r.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":r.id,onClick:N,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${r.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:r.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":r.id,onClick:C,disabled:t===r.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[t===r.id?e.jsx(I,{className:"w-3 h-3 animate-spin"}):e.jsx(se,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{"data-channel-id":r.id,onClick:E,className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(ye,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":r.id,onClick:j,className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(je,{className:"w-4 h-4"})})]})]},r.id)};return s.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(W,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:s.map(M)})},Be=({selectedEvents:s,onToggleEvent:t})=>{const a=n=>{const b=n.currentTarget.dataset.event;b&&t(b)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:ce.map(n=>{const b=s.includes(n.value);return e.jsxs("button",{type:"button","data-event":n.value,onClick:a,className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${b?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${b?"bg-brand border-brand":"border-gray-300"}`,children:b&&e.jsx(J,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${b?"text-brand":"text-gray-800"}`,children:n.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:n.description})]},n.value)})})]})},$e=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:w,setShowChannelSmtpPassword:g,saving:N,onClose:C,onSave:E})=>{const j=$[a.type],M=l=>n(m=>({...m,name:l.target.value})),r=l=>{const m=l.currentTarget.dataset.type;m&&n(_=>({..._,type:m,config:{}}))},o=l=>{const m=l.currentTarget.dataset.field;m&&n(_=>({..._,config:{..._.config,[m]:l.target.value}}))},P=()=>n(l=>({...l,config:l.config.use_custom_smtp===!0?{...l.config,use_custom_smtp:!1}:ne(l.config,b)})),x=l=>n(m=>({...m,config:{...m.config,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:m.config.smtp_use_ssl}})),k=l=>n(m=>({...m,config:{...m.config,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:m.config.smtp_use_tls}})),U=l=>n(m=>({...m,event_types:m.event_types.includes(l)?m.event_types.filter(_=>_!==l):[...m.event_types,l]})),D=()=>n(l=>({...l,enabled:!l.enabled})),X=()=>g(l=>!l),z=(l,m)=>e.jsx("li",{children:l},m);return s?be.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:t?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:C,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(te,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:a.name,onChange:M,placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys($).map(l=>{const m=$[l],_=m.icon,q=a.type===l;return e.jsxs("button",{"data-type":l,type:"button",onClick:r,className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${q?"border-brand bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(_,{className:`w-5 h-5 ${q?"text-brand":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${q?"text-brand":"text-gray-600"}`,children:m.label})]},l)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",j.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:j.guide.steps.map(z)}),j.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:j.guide.urlFormat})]}),j.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",j.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:j.fields.map(l=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[l.label,l.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":l.key,type:l.type==="password"?"password":l.type==="number"?"number":"text",value:String(a.config[l.key]||""),onChange:o,placeholder:l.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),l.help&&e.jsx("p",{className:"text-xs text-gray-500",children:l.help})]},l.key))}),a.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:a.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:P,className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${a.config.use_custom_smtp===!0?"bg-brand":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${a.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),a.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:String(a.config.smtp_server||""),onChange:o,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_port",type:"number",value:String(a.config.smtp_port||587),onChange:o,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:String(a.config.smtp_user||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{"data-field":"smtp_password",type:w?"text":"password",value:String(a.config.smtp_password||""),onChange:o,placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:X,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:w?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:String(a.config.smtp_from_name||""),onChange:o,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:String(a.config.smtp_from_address||""),onChange:o,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_tls!==!1,onChange:x}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:a.config.smtp_use_ssl===!0,onChange:k}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Be,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:D,className:`relative w-11 h-6 rounded-full transition-colors ${a.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${a.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:C,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:E,disabled:N,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[N?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(J,{className:"w-4 h-4"}),N?"保存中...":"保存"]})]})]})}),document.body):null},Fe=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:w})=>{const g=r=>{const o=r.currentTarget.dataset.field;o&&t(P=>({...P,[o]:r.target.value}))},N=r=>{t(o=>({...o,smtp_port:parseInt(r.target.value,10)||587}))},C=r=>{t(o=>({...o,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:o.smtp_use_ssl}))},E=r=>{t(o=>({...o,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:o.smtp_use_tls}))},j=r=>{t(o=>({...o,smtp_password:r.target.value}))},M=()=>b(r=>!r);return e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(ee,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{"data-field":"smtp_server",type:"text",value:s.smtp_server||"",onChange:g,placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:s.smtp_port||587,onChange:N,placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{"data-field":"smtp_user",type:"email",value:s.smtp_user||"",onChange:g,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:n?"text":"password",value:s.smtp_password||"",onChange:j,placeholder:s.smtp_password_configured?"已配置,如需替换请输入新密码":"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:M,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:n?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(le,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{"data-field":"smtp_from_name",type:"text",value:s.smtp_from_name||"",onChange:g,placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{"data-field":"smtp_from_address",type:"email",value:s.smtp_from_address||s.smtp_user||"",onChange:g,placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_tls!==!1,onChange:C}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:s.smtp_use_ssl===!0,onChange:E}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:w,disabled:a,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Ne,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},Ae=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[w,g]=d.useState(!1),[N,C]=d.useState(null),[E,j]=d.useState(!1),[M,r]=d.useState(""),[o,P]=d.useState(null),[x,k]=d.useState({}),[U,D]=d.useState(!1),[X,z]=d.useState(!1),[l,m]=d.useState(!1),[_,q]=d.useState(Z),F=d.useRef(0),K=d.useRef(null),S=d.useRef(0),L=d.useRef(null),f=d.useRef(0),T=d.useRef(null),B=d.useRef(null),y=d.useCallback((c,i)=>{P({type:c,text:i}),B.current!==null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{B.current=null,P(null)},3e3)},[]),R=d.useCallback(async()=>{var p;const c=++F.current;(p=K.current)==null||p.abort();const i=new AbortController;K.current=i,b(!0);try{const u=await we({signal:i.signal});if(!h(c,F.current))return;a(u.data||[])}catch(u){h(c,F.current)&&!i.signal.aborted&&console.error("加载通知渠道失败",u)}finally{h(c,F.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i;try{const u=await ke({signal:i.signal});h(c,S.current)&&k(u||{})}catch(u){h(c,S.current)&&!i.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var c;return R(),s?V():(S.current+=1,(c=L.current)==null||c.abort(),k({})),(()=>{var i,p;F.current+=1,(i=K.current)==null||i.abort(),S.current+=1,(p=L.current)==null||p.abort()})},[s,R,V]),d.useEffect(()=>(()=>{B.current!==null&&window.clearTimeout(B.current)}),[]);const ie=d.useCallback(()=>{C(null),q(Z()),m(!1),g(!0)},[]),de=d.useCallback(c=>{C(c),q(Me(c,x)),m(!1),g(!0)},[x]),me=d.useCallback(()=>{var c;f.current+=1,(c=T.current)==null||c.abort(),j(!1),g(!1)},[]),pe=d.useCallback(async()=>{var u;const c=qe(_);if(c){y("error",c);return}const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p,j(!0);try{const v=Re(_);if(N?await Y(N.id,v,{signal:p.signal}):await Ce(v,{signal:p.signal}),!h(i,f.current)||(g(!1),await R(),!h(i,f.current)))return;y("success",N?"已更新":"已创建")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"保存失败"))}finally{h(i,f.current)&&j(!1)}},[N,_,R,y]),ue=d.useCallback(async c=>{var u;if(!confirm(`确认删除渠道「${c.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Se(c.id,{signal:p.signal}),!h(i,f.current)||(await R(),!h(i,f.current)))return;y("success","已删除")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"删除失败"))}},[R,y]),xe=d.useCallback(async c=>{var u;const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{if(await Y(c.id,{enabled:!c.enabled},{signal:p.signal}),!h(i,f.current))return;a(v=>v.map(O=>O.id===c.id?{...O,enabled:!O.enabled}:O))}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"切换失败"))}},[y]),he=d.useCallback(async c=>{var u;r(c.id);const i=++f.current;(u=T.current)==null||u.abort();const p=new AbortController;T.current=p;try{await Te(c.id,{signal:p.signal}),h(i,f.current)&&y("success","测试通知已发送,请检查对应渠道")}catch(v){h(i,f.current)&&!p.signal.aborted&&y("error",A(v,"发送失败"))}finally{h(i,f.current)&&r("")}},[y]),ge=d.useCallback(async()=>{var p;const c=++S.current;(p=L.current)==null||p.abort();const i=new AbortController;L.current=i,D(!0);try{const u={smtp_server:x.smtp_server||"",smtp_port:x.smtp_port||587,smtp_user:x.smtp_user||"",smtp_from_name:x.smtp_from_name||"",smtp_from_address:x.smtp_from_address||x.smtp_user||"",smtp_use_tls:x.smtp_use_tls!==!1,smtp_use_ssl:x.smtp_use_ssl===!0};Object.prototype.hasOwnProperty.call(x,"smtp_password")&&(u.smtp_password=x.smtp_password),await Pe(u,{signal:i.signal}),h(c,S.current)&&y("success","SMTP 配置已保存")}catch(u){h(c,S.current)&&!i.signal.aborted&&y("error",A(u,"保存失败"))}finally{h(c,S.current)&&D(!1)}},[y,x]);return{channels:t,loading:n,showModal:w,editing:N,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:X,showChannelSmtpPassword:l,form:_,setForm:q,setSmtp:k,setShowSmtpPassword:z,setShowChannelSmtpPassword:m,loadChannels:R,openCreate:ie,openEdit:de,closeModal:me,showToast:y,handleSave:pe,handleDelete:ue,handleToggleEnabled:xe,handleTest:he,handleSaveSmtp:ge}},Ie=({isAdmin:s=!1})=>{const t=Ae(s);return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:t.loadChannels,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(_e,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:t.openCreate,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(ve,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(W,{className:"w-5 h-5 text-brand mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),t.loading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(I,{className:"w-8 h-8 text-brand animate-spin"})}):e.jsx(Le,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Fe,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx($e,{showModal:t.showModal,editing:t.editing,form:t.form,setForm:t.setForm,smtp:t.smtp,showChannelSmtpPassword:t.showChannelSmtpPassword,setShowChannelSmtpPassword:t.setShowChannelSmtpPassword,saving:t.saving,onClose:t.closeModal,onSave:t.handleSave}),t.toast&&e.jsxs("div",{className:`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${t.toast.type==="success"?"bg-success-500":"bg-danger-500"}`,children:[t.toast.type==="success"?e.jsx(J,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{Ie as default}; diff --git a/internal/webui/static/assets/OrderList-DCxOUz7n.js b/internal/webui/static/assets/OrderList-Bb5NffV_.js similarity index 99% rename from internal/webui/static/assets/OrderList-DCxOUz7n.js rename to internal/webui/static/assets/OrderList-Bb5NffV_.js index b441896..07560f2 100644 --- a/internal/webui/static/assets/OrderList-DCxOUz7n.js +++ b/internal/webui/static/assets/OrderList-Bb5NffV_.js @@ -1 +1 @@ -import{j as e,b as U,r as a}from"./react-vendor-C_od1ZSF.js";import{i as ee,I as te,X as H,J as ae,R as W,N as le,O as X,m as K,E as re,v as ne,V as ie,F as ce,d as de,c as oe,r as xe}from"./icons-vendor-ThcsWkZG.js";import{D as me,h as ue,a as he,E as ge,F as pe,G as be,H as ye,I as je,J as fe}from"./index-DK02p8DH.js";import{f as Y}from"./dateTime-DDi7rqpW.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Ne=s=>{const r=typeof s=="object"&&s!==null?s:{},m=Array.isArray(r.results)?r.results:[];return{total:Number(r.total||0),success_count:Number(r.success_count||0),failed_count:Number(r.failed_count||0),results:m.map(we)}},we=s=>{const r=typeof s=="object"&&s!==null?s:{};return{order_id:String(r.order_id||"unknown"),success:r.success===!0,message:String(r.message||"")}},_e=s=>(s==null?void 0:s.results.filter(ke))||[],ke=s=>!s.success,Ce=(s,r)=>s!==null&&!r,Se=s=>{if(!s)return"请选择订单文件";const r=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(r)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},q=(s,r)=>s===r,Ie=(s,r)=>s instanceof Error&&s.message?s.message:r,Ee=({filter:s,onFilterChange:r,accountFilter:m,onAccountFilterChange:p,accounts:j,accountName:x,searchText:b,onSearchChange:N})=>{const E=n=>r(n.currentTarget.dataset.status||"all"),S=n=>p(n.target.value),f=n=>N(n.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:ve.map(n=>e.jsx("button",{"data-status":n.key,onClick:E,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===n.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:n.label},n.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ee,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:m,onChange:S,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),j.map(n=>e.jsx("option",{value:n.id,children:x(n.id)},n.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:b,onChange:f,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const r=x=>{var b;s.setImportFile(((b=x.target.files)==null?void 0:b[0])||null)},m=()=>s.closeImportModal(),p=()=>void s.handleImportOrders(),j=()=>void s.handleRetryImport();return s.showImportModal?U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:m,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:r,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:j,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:_e(s.importResult).map((x,b)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${b}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:m,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:p,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Me=(s={pageSize:20})=>{const[r,m]=a.useState([]),[p,j]=a.useState([]),[x,b]=a.useState([]),[N,E]=a.useState("all"),[S,f]=a.useState(""),[n,d]=a.useState(""),[F,$]=a.useState(""),[I,w]=a.useState(1),[_,A]=a.useState(1),[O,i]=a.useState(!1),y=a.useRef(0),u=a.useRef(null),M=a.useRef(null),R=a.useCallback(async()=>{var h;const c=++y.current;(h=u.current)==null||h.abort();const o=new AbortController;u.current=o,i(!0);try{const k=await me(S||void 0,N,I,s.pageSize,F,{signal:o.signal});if(!q(c,y.current))return;m(k.data),A(k.total_pages)}catch(k){q(c,y.current)&&!o.signal.aborted&&console.error("加载订单失败:",k)}finally{q(c,y.current)&&i(!1)}},[S,F,N,s.pageSize,I]);a.useEffect(()=>{const c=window.setTimeout(()=>{w(1),$(n.trim())},300);return(()=>window.clearTimeout(c))},[n]),a.useEffect(()=>(R(),(()=>{var c;y.current+=1,(c=u.current)==null||c.abort()})),[R]),a.useEffect(()=>{var o;const c=new AbortController;return(o=M.current)==null||o.abort(),M.current=c,Promise.all([ue({signal:c.signal}),he(void 0,{signal:c.signal})]).then(([h,k])=>{c.signal.aborted||(b(h),j(k))}).catch(h=>{c.signal.aborted||console.error("加载订单辅助数据失败:",h)}),(()=>c.abort())},[]);const v=a.useMemo(()=>new Map(x.map(c=>[c.id,c])),[x]),P=a.useMemo(()=>{const c={};return p.forEach(o=>{o.item_id&&(c[`${o.cookie_id}:${o.item_id}`]=o.item_title||o.item_id)}),c},[p]),G=a.useCallback(c=>{const o=v.get(c),h=(o==null?void 0:o.remark)||(o==null?void 0:o.nickname);return h?`${h} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},[v]),V=a.useCallback(c=>{const o=v.get(c);return(o==null?void 0:o.remark)||(o==null?void 0:o.nickname)||"未命名账号"},[v]),z=a.useCallback((c,o,h)=>{if(h!=null&&h.trim())return h;const k=P[`${c}:${o}`];if(k)return k;const C=p.find(T=>{if(!h||!T.item_title)return!1;const B=h.toLowerCase(),L=T.item_title.toLowerCase();return L.includes(B)||B.includes(L)});return(C==null?void 0:C.item_title)||"未知商品"},[P,p]);return{orders:r,items:p,accounts:x,filter:N,setFilter:E,accountFilter:S,setAccountFilter:f,searchText:n,setSearchText:d,page:I,setPage:w,totalPages:_,loading:O,loadOrders:R,accountName:G,accountNickname:V,getItemNameById:z}},Fe=s=>{const[r,m]=a.useState(!1),[p,j]=a.useState(null),[x,b]=a.useState(null),[N,E]=a.useState(!1),[S,f]=a.useState(""),n=a.useRef(0),d=a.useRef(null),F=a.useCallback(()=>{j(null),b(null),f(""),m(!0)},[]),$=a.useCallback(()=>{var _;n.current+=1,(_=d.current)==null||_.abort(),E(!1),m(!1),j(null),b(null),f("")},[]),I=a.useCallback(async()=>{var y;if(!Ce(p,N))return;const _=p;if(!_)return;const A=Se(_);if(A){f(A);return}const O=++n.current;(y=d.current)==null||y.abort();const i=new AbortController;d.current=i,E(!0),b(null),f("");try{const u=new FormData;u.append("file",_);const M=Ne(await ge(u,{signal:i.signal}));if(!q(O,n.current))return;b(M),j(null),await s(),M.failed_count===0&&q(O,n.current)&&(alert(`订单导入成功,共 ${M.success_count} 条`),m(!1),b(null))}catch(u){q(O,n.current)&&!i.signal.aborted&&f(Ie(u,"导入失败,请检查文件格式"))}finally{q(O,n.current)&&E(!1)}},[p,N,s]),w=a.useCallback(async()=>{await I()},[I]);return{showImportModal:r,importFile:p,setImportFile:j,importResult:x,importing:N,importError:S,openImportModal:F,closeImportModal:$,handleImportOrders:I,handleRetryImport:w}},Q=(s,r)=>s instanceof Error?s.message:r,Re=({orders:s,page:r,accountFilter:m,filter:p,setPage:j,loadOrders:x})=>{const[b,N]=a.useState(!1),[E,S]=a.useState(null),[f,n]=a.useState(!1),[d,F]=a.useState(null),[$,I]=a.useState(!1),[w,_]=a.useState(""),[A,O]=a.useState(!1),[i,y]=a.useState(null),[u,M]=a.useState(null),[R,v]=a.useState(null),P=a.useCallback(async()=>{try{const l=await pe(m||void 0,p);await x(),l.message&&alert(l.message)}catch(l){console.error("同步订单失败:",l),alert(Q(l,"同步失败,请重试"))}},[m,p,x]),G=a.useCallback(l=>{_(l),y(null),I(!0)},[]),V=a.useCallback(async l=>{var g;O(!0),y(null);try{const D=(g=(await be([w],l)).results)==null?void 0:g[0];D!=null&&D.success?(y({success:!0,message:D.message}),x()):y({success:!1,message:(D==null?void 0:D.message)||"发货失败"})}catch(J){y({success:!1,message:Q(J,"请求失败")})}finally{O(!1)}},[x,w]),z=a.useCallback(l=>{S(l),N(!0)},[]),c=a.useCallback(l=>{F({...l}),n(!0)},[]),o=a.useCallback(l=>{F(g=>g&&{...g,...l})},[]),h=a.useCallback(async()=>{if(d!=null&&d.order_id)try{const l={};d.status!==void 0&&(l.order_status=d.status),d.buyer_id!==void 0&&(l.buyer_id=d.buyer_id),d.amount!==void 0&&(l.amount=d.amount),d.receiver_name!==void 0&&(l.receiver_name=d.receiver_name),d.receiver_phone!==void 0&&(l.receiver_phone=d.receiver_phone),d.receiver_address!==void 0&&(l.receiver_address=d.receiver_address),d.item_id!==void 0&&(l.item_id=d.item_id),d.quantity!==void 0&&(l.quantity=d.quantity),d.item_title!==void 0&&(l.item_title=d.item_title),await ye(d.order_id,l),n(!1),F(null),await x()}catch(l){console.error("更新订单失败:",l),alert("更新失败,请重试")}},[d,x]),k=a.useCallback(async l=>{M(l);try{const g=await je(l);g.success?await x():alert(g.message||"同步失败")}catch(g){console.error("同步订单失败:",g),alert(Q(g,"同步失败,请重试"))}finally{M(null)}},[x]),C=a.useCallback(async l=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){v(l);try{await fe(l),s.length===1&&r>1?j(g=>g-1):await x()}catch(g){console.error("删除订单失败:",g),alert(Q(g,"删除失败,请重试")),await x()}finally{v(null)}}},[x,s.length,r,j]),T=a.useCallback(()=>N(!1),[]),B=a.useCallback(()=>n(!1),[]),L=a.useCallback(()=>{I(!1),y(null)},[]);return{showDetailModal:b,selectedOrder:E,showEditModal:f,editingOrder:d,showShipModal:$,shipOrderId:w,shipLoading:A,shipResult:i,syncingOrderId:u,deletingOrderId:R,handleSync:P,handleShip:G,executeShip:V,handleViewDetail:z,handleEdit:c,handleSaveEdit:h,updateEditingOrder:o,handleSyncSingle:k,handleDelete:C,closeDetailModal:T,closeEditModal:B,closeShipModal:L}},Z=({status:s})=>{const r={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},m={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${r[s]||r.cancelled}`,children:m[s]||s})},Pe=()=>{const s=Me(),r=Fe(s.loadOrders),{orders:m,accounts:p,filter:j,setFilter:x,accountFilter:b,setAccountFilter:N,searchText:E,setSearchText:S,page:f,setPage:n,totalPages:d,loading:F,loadOrders:$,accountName:I,accountNickname:w,getItemNameById:_}=s,A=Re({orders:m,page:f,accountFilter:b,filter:j,setPage:n,loadOrders:$}),{showDetailModal:O,selectedOrder:i,showEditModal:y,editingOrder:u,showShipModal:M,shipLoading:R,shipResult:v,syncingOrderId:P,deletingOrderId:G,handleSync:V,handleShip:z,executeShip:c,handleViewDetail:o,handleEdit:h,handleSaveEdit:k,updateEditingOrder:C,handleSyncSingle:T,handleDelete:B,closeDetailModal:L,closeEditModal:l,closeShipModal:g}=A,J=t=>{x(t),n(1),S("")},D=t=>{N(t),n(1)},se=t=>{S(t),n(1)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:$,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(W,{className:`w-5 h-5 ${F?"animate-spin":""}`})}),e.jsxs("button",{onClick:r.openImportModal,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(le,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:V,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(X,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Ee,{filter:j,onFilterChange:J,accountFilter:b,onAccountFilterChange:D,accounts:p,accountName:I,searchText:E,onSearchChange:se}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:m.map(t=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:t.item_image?e.jsx("img",{src:t.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(K,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_(t.cookie_id,t.item_id,t.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:w(t.cookie_id),children:[e.jsx(ee,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:w(t.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",t.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity," • ",Y(t.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:t.buyer_id}),t.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:t.receiver_name})]}),t.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:t.receiver_phone})]}),t.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:t.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:t.amount?`¥${t.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(Z,{status:t.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[t.status==="pending_ship"&&e.jsx("button",{onClick:(()=>z(t.order_id)),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${t.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(re,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>o(t)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(ne,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>h(t)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(ie,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>T(t.order_id)),disabled:P===t.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(W,{className:`w-4 h-4 ${P===t.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(t.order_id)),disabled:G===t.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(ce,{className:"w-4 h-4"})})]})]},t.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",f," 页 / 共 ",d," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:f<=1,onClick:(()=>n(t=>t-1)),"aria-label":"上一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(de,{className:"w-5 h-5"})}),e.jsx("button",{disabled:f>=d,onClick:(()=>n(t=>t+1)),"aria-label":"下一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(oe,{className:"w-5 h-5"})})]})]})]}),O&&i&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:L,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:i.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:w(i.cookie_id),children:w(i.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(Z,{status:i.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:i.amount?`¥${i.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:i.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:Y(i.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[i.item_image&&e.jsx("img",{src:i.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:_(i.cookie_id,i.item_id,i.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",i.item_id]}),i.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",i.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:i.buyer_id})]}),i.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:i.receiver_name})]}),i.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:i.receiver_phone})]}),i.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:i.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:L,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),i.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{L(),z(i.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Oe,{...r}),M&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:g,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:(()=>c("status_only")),disabled:R,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(X,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:(()=>c("full_delivery")),disabled:R,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(K,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),R&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(W,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),v&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${v.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[v.success?"✓ ":"✗ ",v.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:g,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:v!=null&&v.success?"完成":"取消"})})]})}),document.body),y&&u&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:l,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:u.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:u.status,onChange:(t=>C({status:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:u.buyer_id,onChange:(t=>C({buyer_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:u.amount,onChange:(t=>C({amount:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:u.receiver_name||"",onChange:(t=>C({receiver_name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:u.receiver_phone||"",onChange:(t=>C({receiver_phone:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:u.receiver_address||"",onChange:(t=>C({receiver_address:t.target.value})),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:u.item_title||"",onChange:(t=>C({item_title:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Pe as default}; +import{j as e,b as U,r as a}from"./react-vendor-C_od1ZSF.js";import{i as ee,I as te,X as H,J as ae,R as W,N as le,O as X,m as K,E as re,v as ne,V as ie,F as ce,d as de,c as oe,r as xe}from"./icons-vendor-ThcsWkZG.js";import{D as me,h as ue,a as he,E as ge,F as pe,G as be,H as ye,I as je,J as fe}from"./index-CYPNW7Ux.js";import{f as Y}from"./dateTime-DDi7rqpW.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Ne=s=>{const r=typeof s=="object"&&s!==null?s:{},m=Array.isArray(r.results)?r.results:[];return{total:Number(r.total||0),success_count:Number(r.success_count||0),failed_count:Number(r.failed_count||0),results:m.map(we)}},we=s=>{const r=typeof s=="object"&&s!==null?s:{};return{order_id:String(r.order_id||"unknown"),success:r.success===!0,message:String(r.message||"")}},_e=s=>(s==null?void 0:s.results.filter(ke))||[],ke=s=>!s.success,Ce=(s,r)=>s!==null&&!r,Se=s=>{if(!s)return"请选择订单文件";const r=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(r)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},q=(s,r)=>s===r,Ie=(s,r)=>s instanceof Error&&s.message?s.message:r,Ee=({filter:s,onFilterChange:r,accountFilter:m,onAccountFilterChange:p,accounts:j,accountName:x,searchText:b,onSearchChange:N})=>{const E=n=>r(n.currentTarget.dataset.status||"all"),S=n=>p(n.target.value),f=n=>N(n.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:ve.map(n=>e.jsx("button",{"data-status":n.key,onClick:E,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===n.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:n.label},n.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ee,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:m,onChange:S,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),j.map(n=>e.jsx("option",{value:n.id,children:x(n.id)},n.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:b,onChange:f,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const r=x=>{var b;s.setImportFile(((b=x.target.files)==null?void 0:b[0])||null)},m=()=>s.closeImportModal(),p=()=>void s.handleImportOrders(),j=()=>void s.handleRetryImport();return s.showImportModal?U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:m,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:r,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:j,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.importResult.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:_e(s.importResult).map((x,b)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${b}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:m,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:p,disabled:!s.importFile||s.importing,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:s.importing?"正在导入…":"导入订单"})]})})]})}),document.body):null},Me=(s={pageSize:20})=>{const[r,m]=a.useState([]),[p,j]=a.useState([]),[x,b]=a.useState([]),[N,E]=a.useState("all"),[S,f]=a.useState(""),[n,d]=a.useState(""),[F,$]=a.useState(""),[I,w]=a.useState(1),[_,A]=a.useState(1),[O,i]=a.useState(!1),y=a.useRef(0),u=a.useRef(null),M=a.useRef(null),R=a.useCallback(async()=>{var h;const c=++y.current;(h=u.current)==null||h.abort();const o=new AbortController;u.current=o,i(!0);try{const k=await me(S||void 0,N,I,s.pageSize,F,{signal:o.signal});if(!q(c,y.current))return;m(k.data),A(k.total_pages)}catch(k){q(c,y.current)&&!o.signal.aborted&&console.error("加载订单失败:",k)}finally{q(c,y.current)&&i(!1)}},[S,F,N,s.pageSize,I]);a.useEffect(()=>{const c=window.setTimeout(()=>{w(1),$(n.trim())},300);return(()=>window.clearTimeout(c))},[n]),a.useEffect(()=>(R(),(()=>{var c;y.current+=1,(c=u.current)==null||c.abort()})),[R]),a.useEffect(()=>{var o;const c=new AbortController;return(o=M.current)==null||o.abort(),M.current=c,Promise.all([ue({signal:c.signal}),he(void 0,{signal:c.signal})]).then(([h,k])=>{c.signal.aborted||(b(h),j(k))}).catch(h=>{c.signal.aborted||console.error("加载订单辅助数据失败:",h)}),(()=>c.abort())},[]);const v=a.useMemo(()=>new Map(x.map(c=>[c.id,c])),[x]),P=a.useMemo(()=>{const c={};return p.forEach(o=>{o.item_id&&(c[`${o.cookie_id}:${o.item_id}`]=o.item_title||o.item_id)}),c},[p]),G=a.useCallback(c=>{const o=v.get(c),h=(o==null?void 0:o.remark)||(o==null?void 0:o.nickname);return h?`${h} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},[v]),V=a.useCallback(c=>{const o=v.get(c);return(o==null?void 0:o.remark)||(o==null?void 0:o.nickname)||"未命名账号"},[v]),z=a.useCallback((c,o,h)=>{if(h!=null&&h.trim())return h;const k=P[`${c}:${o}`];if(k)return k;const C=p.find(T=>{if(!h||!T.item_title)return!1;const B=h.toLowerCase(),L=T.item_title.toLowerCase();return L.includes(B)||B.includes(L)});return(C==null?void 0:C.item_title)||"未知商品"},[P,p]);return{orders:r,items:p,accounts:x,filter:N,setFilter:E,accountFilter:S,setAccountFilter:f,searchText:n,setSearchText:d,page:I,setPage:w,totalPages:_,loading:O,loadOrders:R,accountName:G,accountNickname:V,getItemNameById:z}},Fe=s=>{const[r,m]=a.useState(!1),[p,j]=a.useState(null),[x,b]=a.useState(null),[N,E]=a.useState(!1),[S,f]=a.useState(""),n=a.useRef(0),d=a.useRef(null),F=a.useCallback(()=>{j(null),b(null),f(""),m(!0)},[]),$=a.useCallback(()=>{var _;n.current+=1,(_=d.current)==null||_.abort(),E(!1),m(!1),j(null),b(null),f("")},[]),I=a.useCallback(async()=>{var y;if(!Ce(p,N))return;const _=p;if(!_)return;const A=Se(_);if(A){f(A);return}const O=++n.current;(y=d.current)==null||y.abort();const i=new AbortController;d.current=i,E(!0),b(null),f("");try{const u=new FormData;u.append("file",_);const M=Ne(await ge(u,{signal:i.signal}));if(!q(O,n.current))return;b(M),j(null),await s(),M.failed_count===0&&q(O,n.current)&&(alert(`订单导入成功,共 ${M.success_count} 条`),m(!1),b(null))}catch(u){q(O,n.current)&&!i.signal.aborted&&f(Ie(u,"导入失败,请检查文件格式"))}finally{q(O,n.current)&&E(!1)}},[p,N,s]),w=a.useCallback(async()=>{await I()},[I]);return{showImportModal:r,importFile:p,setImportFile:j,importResult:x,importing:N,importError:S,openImportModal:F,closeImportModal:$,handleImportOrders:I,handleRetryImport:w}},Q=(s,r)=>s instanceof Error?s.message:r,Re=({orders:s,page:r,accountFilter:m,filter:p,setPage:j,loadOrders:x})=>{const[b,N]=a.useState(!1),[E,S]=a.useState(null),[f,n]=a.useState(!1),[d,F]=a.useState(null),[$,I]=a.useState(!1),[w,_]=a.useState(""),[A,O]=a.useState(!1),[i,y]=a.useState(null),[u,M]=a.useState(null),[R,v]=a.useState(null),P=a.useCallback(async()=>{try{const l=await pe(m||void 0,p);await x(),l.message&&alert(l.message)}catch(l){console.error("同步订单失败:",l),alert(Q(l,"同步失败,请重试"))}},[m,p,x]),G=a.useCallback(l=>{_(l),y(null),I(!0)},[]),V=a.useCallback(async l=>{var g;O(!0),y(null);try{const D=(g=(await be([w],l)).results)==null?void 0:g[0];D!=null&&D.success?(y({success:!0,message:D.message}),x()):y({success:!1,message:(D==null?void 0:D.message)||"发货失败"})}catch(J){y({success:!1,message:Q(J,"请求失败")})}finally{O(!1)}},[x,w]),z=a.useCallback(l=>{S(l),N(!0)},[]),c=a.useCallback(l=>{F({...l}),n(!0)},[]),o=a.useCallback(l=>{F(g=>g&&{...g,...l})},[]),h=a.useCallback(async()=>{if(d!=null&&d.order_id)try{const l={};d.status!==void 0&&(l.order_status=d.status),d.buyer_id!==void 0&&(l.buyer_id=d.buyer_id),d.amount!==void 0&&(l.amount=d.amount),d.receiver_name!==void 0&&(l.receiver_name=d.receiver_name),d.receiver_phone!==void 0&&(l.receiver_phone=d.receiver_phone),d.receiver_address!==void 0&&(l.receiver_address=d.receiver_address),d.item_id!==void 0&&(l.item_id=d.item_id),d.quantity!==void 0&&(l.quantity=d.quantity),d.item_title!==void 0&&(l.item_title=d.item_title),await ye(d.order_id,l),n(!1),F(null),await x()}catch(l){console.error("更新订单失败:",l),alert("更新失败,请重试")}},[d,x]),k=a.useCallback(async l=>{M(l);try{const g=await je(l);g.success?await x():alert(g.message||"同步失败")}catch(g){console.error("同步订单失败:",g),alert(Q(g,"同步失败,请重试"))}finally{M(null)}},[x]),C=a.useCallback(async l=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){v(l);try{await fe(l),s.length===1&&r>1?j(g=>g-1):await x()}catch(g){console.error("删除订单失败:",g),alert(Q(g,"删除失败,请重试")),await x()}finally{v(null)}}},[x,s.length,r,j]),T=a.useCallback(()=>N(!1),[]),B=a.useCallback(()=>n(!1),[]),L=a.useCallback(()=>{I(!1),y(null)},[]);return{showDetailModal:b,selectedOrder:E,showEditModal:f,editingOrder:d,showShipModal:$,shipOrderId:w,shipLoading:A,shipResult:i,syncingOrderId:u,deletingOrderId:R,handleSync:P,handleShip:G,executeShip:V,handleViewDetail:z,handleEdit:c,handleSaveEdit:h,updateEditingOrder:o,handleSyncSingle:k,handleDelete:C,closeDetailModal:T,closeEditModal:B,closeShipModal:L}},Z=({status:s})=>{const r={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},m={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${r[s]||r.cancelled}`,children:m[s]||s})},Pe=()=>{const s=Me(),r=Fe(s.loadOrders),{orders:m,accounts:p,filter:j,setFilter:x,accountFilter:b,setAccountFilter:N,searchText:E,setSearchText:S,page:f,setPage:n,totalPages:d,loading:F,loadOrders:$,accountName:I,accountNickname:w,getItemNameById:_}=s,A=Re({orders:m,page:f,accountFilter:b,filter:j,setPage:n,loadOrders:$}),{showDetailModal:O,selectedOrder:i,showEditModal:y,editingOrder:u,showShipModal:M,shipLoading:R,shipResult:v,syncingOrderId:P,deletingOrderId:G,handleSync:V,handleShip:z,executeShip:c,handleViewDetail:o,handleEdit:h,handleSaveEdit:k,updateEditingOrder:C,handleSyncSingle:T,handleDelete:B,closeDetailModal:L,closeEditModal:l,closeShipModal:g}=A,J=t=>{x(t),n(1),S("")},D=t=>{N(t),n(1)},se=t=>{S(t),n(1)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:$,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(W,{className:`w-5 h-5 ${F?"animate-spin":""}`})}),e.jsxs("button",{onClick:r.openImportModal,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(le,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:V,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(X,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Ee,{filter:j,onFilterChange:J,accountFilter:b,onAccountFilterChange:D,accounts:p,accountName:I,searchText:E,onSearchChange:se}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:m.map(t=>e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:t.item_image?e.jsx("img",{src:t.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(K,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_(t.cookie_id,t.item_id,t.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:w(t.cookie_id),children:[e.jsx(ee,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:w(t.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",t.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",t.quantity," • ",Y(t.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:t.buyer_id}),t.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:t.receiver_name})]}),t.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:t.receiver_phone})]}),t.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:t.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:t.amount?`¥${t.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(Z,{status:t.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[t.status==="pending_ship"&&e.jsx("button",{onClick:(()=>z(t.order_id)),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${t.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(re,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>o(t)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(ne,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>h(t)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(ie,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>T(t.order_id)),disabled:P===t.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(W,{className:`w-4 h-4 ${P===t.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(t.order_id)),disabled:G===t.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(ce,{className:"w-4 h-4"})})]})]},t.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",f," 页 / 共 ",d," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:f<=1,onClick:(()=>n(t=>t-1)),"aria-label":"上一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(de,{className:"w-5 h-5"})}),e.jsx("button",{disabled:f>=d,onClick:(()=>n(t=>t+1)),"aria-label":"下一页",className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(oe,{className:"w-5 h-5"})})]})]})]}),O&&i&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:L,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:i.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:w(i.cookie_id),children:w(i.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(Z,{status:i.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:i.amount?`¥${i.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:i.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:Y(i.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[i.item_image&&e.jsx("img",{src:i.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:_(i.cookie_id,i.item_id,i.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",i.item_id]}),i.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",i.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:i.buyer_id})]}),i.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:i.receiver_name})]}),i.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:i.receiver_phone})]}),i.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:i.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:L,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),i.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{L(),z(i.order_id)}),className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),e.jsx(Oe,{...r}),M&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:g,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:(()=>c("status_only")),disabled:R,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(X,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:(()=>c("full_delivery")),disabled:R,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(K,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),R&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(W,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),v&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${v.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[v.success?"✓ ":"✗ ",v.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:g,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:v!=null&&v.success?"完成":"取消"})})]})}),document.body),y&&u&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:l,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:u.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:u.status,onChange:(t=>C({status:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:u.buyer_id,onChange:(t=>C({buyer_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:u.amount,onChange:(t=>C({amount:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:u.receiver_name||"",onChange:(t=>C({receiver_name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:u.receiver_phone||"",onChange:(t=>C({receiver_phone:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:u.receiver_address||"",onChange:(t=>C({receiver_address:t.target.value})),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:u.item_title||"",onChange:(t=>C({item_title:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:k,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Pe as default}; diff --git a/internal/webui/static/assets/Rules-D884-CgU.js b/internal/webui/static/assets/Rules-MPWRzM5C.js similarity index 99% rename from internal/webui/static/assets/Rules-D884-CgU.js rename to internal/webui/static/assets/Rules-MPWRzM5C.js index 8e8c271..0377a12 100644 --- a/internal/webui/static/assets/Rules-D884-CgU.js +++ b/internal/webui/static/assets/Rules-MPWRzM5C.js @@ -1 +1 @@ -import{j as e,r,b as Ie}from"./react-vendor-C_od1ZSF.js";import{k as Ve,ae as tt,af as pt,m as bt,R as Le,N as Ue,Z as Ke,x as gt,w as We,I as yt,a1 as ft,X as Ne,V as De,F as we,d as jt,c as _t,a6 as vt,ag as Nt,r as Ze,ah as wt}from"./icons-vendor-ThcsWkZG.js";import{h as kt,K as st,a as at,a7 as Xe,a8 as Ct,a9 as St,aa as Rt,ab as Qe,ac as At,ad as Mt,ae as Pt,af as $t,ag as It,ah as Lt,ai as Dt,aj as Ft,ak as Tt,a1 as zt}from"./index-DK02p8DH.js";const Fe=(s,c)=>s.allowed_resolutions.includes(c),Et=(s,c)=>({runs:s.runs.filter(d=>!c||d.cookie_id===c),pending_tasks:s.pending_tasks.filter(d=>!c||d.cookie_id===c)}),qt=s=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[s]||"自动化异常",Vt=({runs:s,pendingTasks:c,onResolveRun:d,onResolveDeferredTask:y})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[s.map(o=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",o.cookie_id," · 订单 ",o.order_id||"-"," · 已记录发送 ",o.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:qt(o.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:o.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Fe(o,"continue")&&e.jsx("button",{onClick:(()=>d(o.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Fe(o,"retry")&&e.jsx("button",{onClick:(()=>d(o.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Fe(o,"cancel")&&e.jsx("button",{onClick:(()=>d(o.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${o.id}`)),c.map(o=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",o.cookie_id," · 延迟任务重试已达 ",o.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:o.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>y(o.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>y(o.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${o.id}`))]})]}),Te=()=>({submitting:!1,result:"idle"}),ze=s=>s.submitting?s:{submitting:!0,result:"idle"},Ee=(s,c)=>({submitting:!1,result:c?"success":"failure"}),Ye=s=>s+1,qe=(s,c,d,y)=>s===c&&d===y,Ot=s=>{const[c,d]=r.useState([]),[y,o]=r.useState({runs:[],pending_tasks:[]}),[U,F]=r.useState([]),[K,C]=r.useState({}),[se,T]=r.useState([]),[V,v]=r.useState([]),[O,P]=r.useState([]),[j,W]=r.useState(!1),z=r.useRef(0),ae=r.useRef(0),[Z,B]=r.useState(0),[le,X]=r.useState(0),[E,Q]=r.useState({}),G=r.useCallback(async()=>{const A=Promise.all([kt(),st(),at(),Xe()]),[b,f,$,Y]=await A;T(b),v(f),P($),C(Y),s.setSelectedAccountId(re=>{var L;return re||((L=b[0])==null?void 0:L.id)||""})},[s.setSelectedAccountId]),l=r.useCallback(async()=>{var Y;const A=Ye(z.current);z.current=A;const b=Ct().catch(re=>(console.warn("加载自动化异常列表失败,不阻断规则展示",re),null)),f=await St({cookieId:s.selectedAccountId||void 0,triggerType:s.automationTriggerFilter,enabled:s.automationStatusFilter==="all"?void 0:s.automationStatusFilter==="enabled",search:s.debouncedAutomationSearch,page:s.automationPage,pageSize:s.automationPageSize});if(!qe(A,z.current,s.selectedAccountId,s.selectedAccountId))return;d(f.data),B(f.total),X(f.total_pages),Q(f.trigger_counts||{}),f.page!==s.automationPage&&((Y=s.onAutomationPageChange)==null||Y.call(s,f.page));const $=await b;qe(A,z.current,s.selectedAccountId,s.selectedAccountId)&&$&&o($)},[s.automationPage,s.automationPageSize,s.automationStatusFilter,s.automationTriggerFilter,s.debouncedAutomationSearch,s.onAutomationPageChange,s.selectedAccountId]),S=r.useCallback(async()=>{const A=Ye(ae.current);ae.current=A;const b=s.selectedAccountId;if(F([]),!b)return;const f=await Rt(b);qe(A,ae.current,b,s.selectedAccountId)&&F(f)},[s.selectedAccountId]),k=r.useCallback(async()=>{C(await Xe())},[]),I=r.useCallback(async()=>{W(!0);try{s.activeTab==="automation"?await l():s.activeTab==="reply"?await S():await k()}finally{W(!1)}},[l,k,S,s.activeTab]);return{automationRules:c,automationIssues:y,replyRules:U,defaultReplies:K,accounts:se,cards:V,items:O,automationTotal:Z,automationTotalPages:le,automationTriggerCounts:E,loading:j,setLoading:W,setAutomationRules:d,setCards:v,setItems:P,loadReferenceData:G,loadAutomationRules:l,loadReplyRules:S,loadDefaultReplies:k,refresh:I}},te={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:bt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:pt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:tt}},ke=["order_paid","buyer_reviewed","review_missing_timeout"],Bt="亲,商品使用满意的话,麻烦给个评价,谢谢~",be=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),lt=s=>{if(!s)return{};try{const c=JSON.parse(s);return c&&typeof c=="object"&&!Array.isArray(c)?c:{}}catch{return{}}},de=(s,c={})=>{const d=lt(s);return JSON.stringify({after_shipped_hours:Number(d.after_shipped_hours||72),repeat_interval_hours:Number(d.repeat_interval_hours||24),max_attempts:Number(d.max_attempts||1),...c})},ge=(s,c)=>{var y;const d=((y=te[s])==null?void 0:y.label)||"自动化规则";return c?`${d} - ${c}`:d},He=s=>{const c=(s||"").trim();return c?Object.values(te).some(d=>c===d.label||c.startsWith(`${d.label} -`)):!0},ye=(s,c=0)=>{if(s==="review_missing_timeout")return[{action_type:"send_text",message_template:Bt,enabled:!0,sort_order:1}];const d={action_type:"send_card",card_id:c,delivery_count:1,enabled:!0,sort_order:1};return s==="order_paid"?[d,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[d]},Gt=s=>{var d,y;if(s.trigger_type==="review_missing_timeout")return((y=(d=s.actions)==null?void 0:d.find(o=>o.action_type==="send_text"))==null?void 0:y.message_template)||"发送求评价文案";const c=(s.actions||[]).filter(o=>o.action_type==="send_card");return c.length?c.map(o=>o.card_name||`卡密 ${o.card_id}`).join(" / "):"未配置卡密库存"},et=(s,c=!1)=>{const d={blue:c?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:c?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:c?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return d[s]||d.blue},Jt=s=>s?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Ce=s=>(s==null?void 0:s.nickname)||(s==null?void 0:s.remark)||(s==null?void 0:s.id)||"未知账号",Ut=s=>s===!0||s===1||s==="1",Kt=({selectedAccountId:s,setSelectedAccountId:c,setActiveTab:d,items:y,setAutomationRules:o,setCards:U,setItems:F,setLoading:K,loadAutomationRules:C,loadReferenceData:se,loadReplyRules:T,loadDefaultReplies:V,initialDeliveryTarget:v,onDeliveryTargetHandled:O})=>{var me;const[P,j]=r.useState(!1),[W,z]=r.useState(!1),[ae,Z]=r.useState(!1),[B,le]=r.useState(Te),[X,E]=r.useState(Te),[Q,G]=r.useState(Te),[l,S]=r.useState(null),[k,I]=r.useState(null),[R,A]=r.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),b=r.useMemo(()=>l!=null&&l.cookie_id&&l.item_id?y.find(a=>a.cookie_id===l.cookie_id&&a.item_id===l.item_id):void 0,[l==null?void 0:l.cookie_id,l==null?void 0:l.item_id,y]),f=Ut(b==null?void 0:b.is_multi_spec),$=(l==null?void 0:l.trigger_type)||"order_paid",Y=te[$],re=lt(l==null?void 0:l.config_json),L=(me=l==null?void 0:l.variants)!=null&&me.length?l.variants:[be()],J=r.useCallback((a="order_paid",n=s,h="")=>{const x=y.find(_=>_.cookie_id===n&&_.item_id===h),p=(x==null?void 0:x.item_title)||h;return{name:ge(a,p),trigger_type:a,cookie_id:n,item_id:h,item_title:(x==null?void 0:x.item_title)||"",item_keyword:p,card_group_id:0,priority:100,enabled:!0,config_json:a==="review_missing_timeout"?de():"{}",actions:ye(a),variants:a==="review_missing_timeout"?[]:[be()]}},[y,s]),xe=r.useCallback(a=>{var h,x;const n=a.trigger_type||"order_paid";S({...a,trigger_type:n,config_json:n==="review_missing_timeout"?de(a.config_json):a.config_json||"{}",actions:(h=a.actions)!=null&&h.length?a.actions.map(p=>({...p})):ye(n,a.card_group_id),variants:(x=a.variants)!=null&&x.length?a.variants.map(p=>({...p})):n==="review_missing_timeout"?[]:[be()]}),j(!0)},[]);r.useEffect(()=>{if(!v)return;let a=!1;return(async()=>{d("automation"),c(v.cookieId),K(!0);try{const[h,x,p]=await Promise.all([zt(),at(),st().catch(g=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",g),[]))]);if(a)return;o(h),F(x),U(p);const _=h.find(g=>g.cookie_id===v.cookieId&&g.item_id===v.itemId&&g.trigger_type==="order_paid");if(_)xe(_);else{const g=x.find(q=>q.cookie_id===v.cookieId&&q.item_id===v.itemId);S({...J("order_paid",v.cookieId,v.itemId),item_title:(g==null?void 0:g.item_title)||"",item_keyword:(g==null?void 0:g.item_title)||v.itemId,name:ge("order_paid",(g==null?void 0:g.item_title)||v.itemId)}),j(!0)}}catch(h){console.error("打开商品自动化规则失败",h),alert("无法加载该商品的自动化规则")}finally{a||(K(!1),O==null||O())}})(),(()=>{a=!0})},[J,v,O,xe,d,o,U,F,K,c]);const Se=r.useCallback((a="order_paid")=>{if(!s){alert("请先选择账号");return}S(J(a)),j(!0)},[J,s]),fe=r.useCallback(a=>{var x,p,_,g,q;if(!l)return;const n=((p=(x=l.variants)==null?void 0:x.find(ee=>ee.card_id))==null?void 0:p.card_id)||((g=(_=l.actions)==null?void 0:_.find(ee=>ee.action_type==="send_card"))==null?void 0:g.card_id)||l.card_group_id||0,h=(b==null?void 0:b.item_title)||l.item_title||l.item_id||"";S({...l,trigger_type:a,name:He(l.name)?ge(a,h):l.name,card_group_id:n,config_json:a==="review_missing_timeout"?de(l.config_json):"{}",actions:ye(a,n),variants:a==="review_missing_timeout"?[]:(q=l.variants)!=null&&q.length?l.variants:[{...be(),card_id:n}]})},[l,b]),Re=r.useCallback(a=>{if(!l)return;const n=y.find(x=>x.cookie_id===(l.cookie_id||s)&&x.item_id===a),h=(n==null?void 0:n.item_title)||a;S({...l,item_id:a,item_title:(n==null?void 0:n.item_title)||"",item_keyword:h,name:He(l.name)?ge($,h):l.name})},[$,l,y,s]),ue=r.useCallback((a,n)=>{var x;if(!l)return;const h=L.map((p,_)=>_===a?{...p,...n}:p);S({...l,variants:h,card_group_id:((x=h[0])==null?void 0:x.card_id)||0})},[L,l]),Ae=r.useCallback(()=>{if(!l)return;const a=L[L.length-1];S({...l,variants:[...L,{...be(),spec_name:f&&(a==null?void 0:a.spec_name)||"",spec_value:f&&(a==null?void 0:a.spec_value)||""}]})},[L,l,f]),je=r.useCallback(async()=>{var p,_,g,q,ee;if(!l||B.submitting)return;const a=l.trigger_type||"order_paid";if(!l.cookie_id)return alert("请选择账号");const n=(p=l.variants)!=null&&p.length?l.variants:[];if(a!=="review_missing_timeout"){if(!n.length||n.some(N=>!N.card_id))return alert(a==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(f&&n.some(N=>!N.spec_name.trim()||!N.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(a==="review_missing_timeout"&&!(((g=(_=l.actions)==null?void 0:_.find(Me=>Me.action_type==="send_text"))==null?void 0:g.message_template)||"").trim())return alert("请填写求评价文案");const h=a==="review_missing_timeout"?[]:n.map(N=>({...N,spec_name:f?N.spec_name.trim():"",spec_value:f?N.spec_value.trim():"",delivery_count:Math.max(1,Number(N.delivery_count)||1),enabled:N.enabled!==!1}));le(ze(B));let x=!1;try{await Qe({...l,trigger_type:a,name:(l.name||"").trim()||ge(a,(b==null?void 0:b.item_title)||l.item_id||""),config_json:a==="review_missing_timeout"?de(l.config_json):l.config_json||"{}",actions:(q=l.actions)!=null&&q.length?l.actions:ye(a,((ee=h[0])==null?void 0:ee.card_id)||l.card_group_id||0),variants:h}),j(!1),await Promise.all([C(),se()]),alert("保存成功"),x=!0}catch(N){console.error("保存自动化规则失败:",N),alert("保存失败:"+N.message)}finally{le(N=>Ee(N,x))}},[B,l,f,C,se,b]),u=r.useCallback(async a=>{if(confirm("确定删除该自动化规则吗?"))try{await At(a),await C(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[C]),D=r.useCallback(async a=>{try{await Qe({...a,enabled:!a.enabled}),await C()}catch(n){alert("操作失败:"+n.message)}},[C]),w=r.useCallback(async(a,n)=>{if(confirm(n==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":n==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Mt(a,n),await C()}catch(x){alert("处理失败:"+x.message)}},[C]),H=r.useCallback(async(a,n)=>{if(confirm(n==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Pt(a,n),await C()}catch(h){alert("处理失败:"+h.message)}},[C]),M=r.useCallback(()=>{if(!s)return alert("请先选择账号");I({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),z(!0)},[s]),ne=r.useCallback(async()=>{var h,x,p;if(!k||!s||X.submitting)return;const a=k.type==="image"?!!((h=k.image_url)!=null&&h.trim()):!!((x=k.reply_content)!=null&&x.trim());if(!((p=k.keyword)!=null&&p.trim())||!a)return alert("请填写关键词和回复内容");E(ze(X));let n=!1;try{await $t({...k,match_type:"fuzzy",enabled:!0},s),z(!1),await T(),alert("保存成功"),n=!0}catch(_){alert("保存失败:"+_.message)}finally{E(_=>Ee(_,n))}},[k,T,X,s]),he=r.useCallback(async a=>{if(!(!s||!confirm("确定删除该回复规则吗?")))try{await It(a,s),await T(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[T,s]),ie=r.useCallback(async(a=s)=>{if(!a)return alert("请先选择账号");try{const n=await Lt(a);A({cookie_id:a,enabled:n.enabled,reply_content:n.reply_content,reply_once:n.reply_once,reply_image_url:n.reply_image_url||""})}catch{A({cookie_id:a,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Z(!0)},[s]),ce=r.useCallback(async()=>{if(Q.submitting)return;if(!R.cookie_id)return alert("请先选择账号");if(R.enabled&&!R.reply_content.trim()&&!R.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");G(ze(Q));let a=!1;try{await Dt(R.cookie_id,{enabled:R.enabled,reply_content:R.reply_content,reply_once:R.reply_once,reply_image_url:R.reply_image_url}),Z(!1),await V(),alert("保存成功"),a=!0}catch(n){alert("保存失败:"+n.message)}finally{G(n=>Ee(n,a))}},[R,Q,V]),_e=r.useCallback(async a=>{if(confirm("确定删除该账号默认回复吗?"))try{await Ft(a),await V(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[V]),pe=r.useCallback(async a=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Tt(a),alert("清空成功")}catch(n){alert("清空失败:"+n.message)}},[]);return{showAutomationModal:P,setShowAutomationModal:j,showReplyModal:W,setShowReplyModal:z,showDefaultModal:ae,setShowDefaultModal:Z,automationSubmitState:B,replySubmitState:X,defaultReplySubmitState:Q,editingAutomationRule:l,setEditingAutomationRule:S,editingReplyRule:k,setEditingReplyRule:I,defaultForm:R,setDefaultForm:A,selectedRuleItem:b,isMultiSpecRule:f,currentTrigger:$,currentMeta:Y,reviewConfig:re,displayVariants:L,buildAutomationDraft:J,openAutomationRule:xe,openNewAutomationRule:Se,handleTriggerChange:fe,handleAutomationItemChange:Re,updateVariant:ue,appendDeliveryContent:Ae,handleSaveAutomationRule:je,handleDeleteAutomation:u,handleToggleAutomation:D,handleResolveRunIssue:w,handleResolveDeferredIssue:H,handleAddReplyRule:M,handleSaveReplyRule:ne,handleDeleteReply:he,openDefaultReplyModal:ie,handleSaveDefaultReply:ce,handleDeleteDefaultReply:_e,handleClearDefaultReplyRecords:pe}},Qt=({initialDeliveryTarget:s,onDeliveryTargetHandled:c})=>{var Ge,Je;const[d,y]=r.useState("automation"),[o,U]=r.useState(""),[F,K]=r.useState(""),[C,se]=r.useState(""),[T,V]=r.useState(""),[v,O]=r.useState("all"),[P,j]=r.useState(1),[W,z]=r.useState(10),ae=Ot({activeTab:d,selectedAccountId:o,automationTriggerFilter:T,automationStatusFilter:v,debouncedAutomationSearch:C,automationPage:P,automationPageSize:W,setSelectedAccountId:U,onAutomationPageChange:j}),{automationRules:Z,automationIssues:B,replyRules:le,defaultReplies:X,accounts:E,cards:Q,items:G,loading:l,setLoading:S,automationTotal:k,automationTotalPages:I,automationTriggerCounts:R,setAutomationRules:A,setCards:b,setItems:f,loadReferenceData:$,loadAutomationRules:Y,loadReplyRules:re,loadDefaultReplies:L,refresh:J}=ae,xe=Kt({selectedAccountId:o,setSelectedAccountId:U,setActiveTab:y,items:G,setAutomationRules:A,setCards:b,setItems:f,setLoading:S,loadAutomationRules:Y,loadReferenceData:$,loadReplyRules:re,loadDefaultReplies:L,initialDeliveryTarget:s,onDeliveryTargetHandled:c}),{showAutomationModal:Se,setShowAutomationModal:fe,showReplyModal:Re,setShowReplyModal:ue,showDefaultModal:Ae,setShowDefaultModal:je,editingAutomationRule:u,setEditingAutomationRule:D,editingReplyRule:w,setEditingReplyRule:H,defaultForm:M,setDefaultForm:ne,selectedRuleItem:he,isMultiSpecRule:ie,currentTrigger:ce,currentMeta:_e,reviewConfig:pe,displayVariants:me,openAutomationRule:a,openNewAutomationRule:n,handleTriggerChange:h,handleAutomationItemChange:x,updateVariant:p,appendDeliveryContent:_,handleSaveAutomationRule:g,handleDeleteAutomation:q,handleToggleAutomation:ee,handleResolveRunIssue:N,handleResolveDeferredIssue:Me,handleAddReplyRule:rt,handleSaveReplyRule:nt,handleDeleteReply:it,openDefaultReplyModal:Oe,handleSaveDefaultReply:ot,handleDeleteDefaultReply:dt,handleClearDefaultReplyRecords:ct}=xe;r.useEffect(()=>{const t=window.setTimeout(()=>{j(1),se(F.trim())},300);return(()=>window.clearTimeout(t))},[F]),r.useEffect(()=>{$().catch(t=>console.error("加载规则参考数据失败",t))},[$]),r.useEffect(()=>{J().catch(t=>console.error("刷新规则页面失败",t))},[J]);const Pe=r.useMemo(()=>Z.filter(t=>!o||t.cookie_id===o),[Z,o]),ve=r.useMemo(()=>Et(B,o),[B,o]),Be=r.useMemo(()=>E.filter(t=>!o||t.id===o),[E,o]),mt=r.useMemo(()=>{if(I<=1)return[];const t=Math.max(1,Math.min(P-2,I-4)),i=Math.min(I,t+4);return Array.from({length:i-t+1},(m,oe)=>t+oe)},[P,I]),$e=!!(F.trim()||T||v!=="all"),xt=()=>{K(""),se(""),V(""),O("all"),j(1)},ut=r.useMemo(()=>{const t=(u==null?void 0:u.cookie_id)||o;return G.filter(i=>i.cookie_id===t)},[u==null?void 0:u.cookie_id,G,o]),ht=d==="automation"?"新建自动化":d==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:o,onChange:(t=>{U(t.target.value),j(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]}),e.jsxs("button",{onClick:J,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors",children:[e.jsx(Le,{className:`w-4 h-4 ${l?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:d==="automation"?(()=>n("order_paid")):d==="reply"?rt:(()=>void Oe()),disabled:!o,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(Ue,{className:"w-4 h-4"}),ht]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Ke},{id:"reply",label:"关键词回复",icon:gt},{id:"default",label:"账号默认回复",icon:We}].map(t=>{const i=t.icon;return e.jsxs("button",{onClick:(()=>y(t.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${d===t.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(i,{className:"w-4 h-4"}),t.label]},t.id)})}),d==="automation"&&(ve.runs.length>0||ve.pending_tasks.length>0)&&e.jsx(Vt,{runs:ve.runs,pendingTasks:ve.pending_tasks,onResolveRun:((t,i)=>void N(t,i)),onResolveDeferredTask:((t,i)=>void Me(t,i))}),d==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.icon;return e.jsx("button",{type:"button",onClick:(()=>n(t)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${et(i.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(m,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:i.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:i.description})]})]})},t)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",k," 条"]})]}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(m,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:i.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:R[t]||0})]},t)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(yt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"搜索自动化规则",placeholder:"搜索规则名、商品名或商品 ID...",value:F,onChange:(t=>{K(t.target.value),j(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]}),e.jsxs("div",{className:"relative xl:w-52",children:[e.jsx(ft,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按自动化类型筛选",value:T,onChange:(t=>{V(t.target.value),j(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部自动化类型"}),ke.map(t=>e.jsx("option",{value:t,children:te[t].shortLabel},t))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:v,onChange:(t=>{O(t.target.value),j(1)}),className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),$e&&e.jsx("button",{type:"button",onClick:xt,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(Ne,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",k," 条规则"]}),l&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Le,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),l&&Pe.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(Le,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Pe.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Ke,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:$e?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:$e?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Pe.map(t=>{const i=te[t.trigger_type],m=i.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${et(i.accent,!0)}`,children:e.jsx(m,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:t.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Jt(t.enabled)}`,children:t.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:i.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:t.item_title||t.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Gt(t)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>a(t)),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>ee(t)),className:`px-4 py-2 rounded-xl text-sm font-bold ${t.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:t.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>q(t.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(we,{className:"w-4 h-4"})})]})]})},t.id)}),k>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",P," / ",Math.max(I,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:W,onChange:(t=>{z(Number(t.target.value)),j(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(t=>e.jsxs("option",{value:t,children:[t," 条/页"]},t))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:P<=1||l,onClick:(()=>j(t=>Math.max(1,t-1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(jt,{className:"h-4 w-4"})}),mt.map(t=>e.jsx("button",{type:"button",disabled:l,onClick:(()=>j(t)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${t===P?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${t} 页`,"aria-current":t===P?"page":void 0,children:t},t)),e.jsx("button",{type:"button",disabled:P>=I||l,onClick:(()=>j(t=>Math.min(I,t+1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(_t,{className:"h-4 w-4"})})]})]})]})]}),d==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Ve,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[le.map(t=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",t.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:t.type==="image"&&t.image_url?t.image_url:t.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>{H({...t}),ue(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(De,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>it(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(we,{className:"w-5 h-5"})})]})]},t.id)),le.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),d==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Ve,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Be.map(t=>{const i=X[t.id],m=!!(i!=null&&i.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${m?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${m?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(We,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Ce(t)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${m?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:m?"已启用":"未启用"}),(i==null?void 0:i.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:m?i.reply_content||i.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>void Oe(t.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(De,{className:"w-4 h-4"})}),m&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void ct(t.id)),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:(()=>void dt(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(we,{className:"w-5 h-5"})})]})]})]},t.id)}),Be.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),Se&&u&&Ie.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:u.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:_e.description})]}),e.jsx("button",{onClick:(()=>fe(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.icon,oe=ce===t;return e.jsx("button",{type:"button",onClick:(()=>h(t)),className:`w-full rounded-2xl p-4 text-left border transition-all ${oe?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(m,{className:`w-5 h-5 mt-0.5 ${oe?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:i.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${oe?"text-gray-500":"text-gray-400"}`,children:i.description})]})]})},t)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:_e.flow.map((t,i)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:i+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:t})]},t))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(vt,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:u.name||"",onChange:(t=>D({...u,name:t.target.value})),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:u.cookie_id||"",onChange:(t=>D({...u,cookie_id:t.target.value,item_id:"",item_title:"",item_keyword:""})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:u.item_id||"",onChange:(t=>x(t.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ut.map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.item_id}`))]})]})]}),he&&ce!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:he.item_title||he.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${ie?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:ie?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),ce!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:ce==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:ie?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:_,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Ue,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:me.map((t,i)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${ie?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[ie&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:t.spec_name,onChange:(m=>p(i,{spec_name:m.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:t.spec_value,onChange:(m=>p(i,{spec_value:m.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:t.card_id||"",onChange:(m=>p(i,{card_id:Number(m.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),Q.filter(m=>m.enabled&&m.type!=="api").map(m=>e.jsx("option",{value:m.id,children:m.name},m.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:t.delivery_count,onChange:(m=>p(i,{delivery_count:Math.max(1,Number(m.target.value)||1)})),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:t.delay_override===!0,onChange:(m=>p(i,{delay_override:m.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),t.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:t.delay_seconds||0,onChange:(m=>p(i,{delay_seconds:Math.max(0,Number(m.target.value)||0)})),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:t.delay_override?`本动作延时 ${t.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:me.length===1,onClick:(()=>D({...u,variants:me.filter((m,oe)=>oe!==i)})),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(we,{className:"w-4 h-4"})})]},t.id||i))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(tt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(pe.after_shipped_hours||72),onChange:(t=>D({...u,config_json:de(u.config_json,{after_shipped_hours:Math.max(1,Number(t.target.value)||72)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(pe.repeat_interval_hours||24),onChange:(t=>D({...u,config_json:de(u.config_json,{repeat_interval_hours:Math.max(1,Number(t.target.value)||24)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(pe.max_attempts||1),onChange:(t=>D({...u,config_json:de(u.config_json,{max_attempts:Math.max(1,Number(t.target.value)||1)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((Je=(Ge=u.actions)==null?void 0:Ge.find(t=>t.action_type==="send_text"))==null?void 0:Je.message_template)||"",onChange:(t=>{var i;return D({...u,actions:((i=u.actions)!=null&&i.length?u.actions:ye("review_missing_timeout")).map(m=>m.action_type==="send_text"?{...m,message_template:t.target.value}:m)})}),className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:u.priority||100,onChange:(t=>D({...u,priority:Number(t.target.value)||100})),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:u.enabled!==!1,onChange:(t=>D({...u,enabled:t.target.checked})),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:(()=>fe(!1)),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:g,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Re&&w&&Ie.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:w.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>ue(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:w.item_id||"",onChange:(t=>H({...w,item_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),G.filter(t=>!o||t.cookie_id===o).map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:w.type||"text",onChange:(t=>{const i=t.target.value;H({...w,type:i,reply_content:i==="text"?w.reply_content:"",image_url:i==="image"?w.image_url:""})}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:w.keyword||"",onChange:(t=>H({...w,keyword:t.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),w.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:w.image_url||"",onChange:(t=>H({...w,image_url:t.target.value})),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:w.reply_content||"",onChange:(t=>H({...w,reply_content:t.target.value})),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ue(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:nt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(wt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Ae&&Ie.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:M.cookie_id,onChange:(t=>ne({...M,cookie_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:(()=>ne({...M,enabled:!M.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${M.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${M.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:M.reply_content,onChange:(t=>ne({...M,reply_content:t.target.value})),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:M.reply_image_url,onChange:(t=>ne({...M,reply_image_url:t.target.value})),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:M.reply_once,onChange:(t=>ne({...M,reply_once:t.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>je(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ot,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{Qt as default}; +import{j as e,r,b as Ie}from"./react-vendor-C_od1ZSF.js";import{k as Ve,ae as tt,af as pt,m as bt,R as Le,N as Ue,Z as Ke,x as gt,w as We,I as yt,a1 as ft,X as Ne,V as De,F as we,d as jt,c as _t,a6 as vt,ag as Nt,r as Ze,ah as wt}from"./icons-vendor-ThcsWkZG.js";import{h as kt,K as st,a as at,a7 as Xe,a8 as Ct,a9 as St,aa as Rt,ab as Qe,ac as At,ad as Mt,ae as Pt,af as $t,ag as It,ah as Lt,ai as Dt,aj as Ft,ak as Tt,a1 as zt}from"./index-CYPNW7Ux.js";const Fe=(s,c)=>s.allowed_resolutions.includes(c),Et=(s,c)=>({runs:s.runs.filter(d=>!c||d.cookie_id===c),pending_tasks:s.pending_tasks.filter(d=>!c||d.cookie_id===c)}),qt=s=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[s]||"自动化异常",Vt=({runs:s,pendingTasks:c,onResolveRun:d,onResolveDeferredTask:y})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ve,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[s.map(o=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",o.cookie_id," · 订单 ",o.order_id||"-"," · 已记录发送 ",o.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:qt(o.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:o.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Fe(o,"continue")&&e.jsx("button",{onClick:(()=>d(o.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Fe(o,"retry")&&e.jsx("button",{onClick:(()=>d(o.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Fe(o,"cancel")&&e.jsx("button",{onClick:(()=>d(o.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${o.id}`)),c.map(o=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",o.cookie_id," · 延迟任务重试已达 ",o.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:o.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>y(o.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>y(o.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${o.id}`))]})]}),Te=()=>({submitting:!1,result:"idle"}),ze=s=>s.submitting?s:{submitting:!0,result:"idle"},Ee=(s,c)=>({submitting:!1,result:c?"success":"failure"}),Ye=s=>s+1,qe=(s,c,d,y)=>s===c&&d===y,Ot=s=>{const[c,d]=r.useState([]),[y,o]=r.useState({runs:[],pending_tasks:[]}),[U,F]=r.useState([]),[K,C]=r.useState({}),[se,T]=r.useState([]),[V,v]=r.useState([]),[O,P]=r.useState([]),[j,W]=r.useState(!1),z=r.useRef(0),ae=r.useRef(0),[Z,B]=r.useState(0),[le,X]=r.useState(0),[E,Q]=r.useState({}),G=r.useCallback(async()=>{const A=Promise.all([kt(),st(),at(),Xe()]),[b,f,$,Y]=await A;T(b),v(f),P($),C(Y),s.setSelectedAccountId(re=>{var L;return re||((L=b[0])==null?void 0:L.id)||""})},[s.setSelectedAccountId]),l=r.useCallback(async()=>{var Y;const A=Ye(z.current);z.current=A;const b=Ct().catch(re=>(console.warn("加载自动化异常列表失败,不阻断规则展示",re),null)),f=await St({cookieId:s.selectedAccountId||void 0,triggerType:s.automationTriggerFilter,enabled:s.automationStatusFilter==="all"?void 0:s.automationStatusFilter==="enabled",search:s.debouncedAutomationSearch,page:s.automationPage,pageSize:s.automationPageSize});if(!qe(A,z.current,s.selectedAccountId,s.selectedAccountId))return;d(f.data),B(f.total),X(f.total_pages),Q(f.trigger_counts||{}),f.page!==s.automationPage&&((Y=s.onAutomationPageChange)==null||Y.call(s,f.page));const $=await b;qe(A,z.current,s.selectedAccountId,s.selectedAccountId)&&$&&o($)},[s.automationPage,s.automationPageSize,s.automationStatusFilter,s.automationTriggerFilter,s.debouncedAutomationSearch,s.onAutomationPageChange,s.selectedAccountId]),S=r.useCallback(async()=>{const A=Ye(ae.current);ae.current=A;const b=s.selectedAccountId;if(F([]),!b)return;const f=await Rt(b);qe(A,ae.current,b,s.selectedAccountId)&&F(f)},[s.selectedAccountId]),k=r.useCallback(async()=>{C(await Xe())},[]),I=r.useCallback(async()=>{W(!0);try{s.activeTab==="automation"?await l():s.activeTab==="reply"?await S():await k()}finally{W(!1)}},[l,k,S,s.activeTab]);return{automationRules:c,automationIssues:y,replyRules:U,defaultReplies:K,accounts:se,cards:V,items:O,automationTotal:Z,automationTotalPages:le,automationTriggerCounts:E,loading:j,setLoading:W,setAutomationRules:d,setCards:v,setItems:P,loadReferenceData:G,loadAutomationRules:l,loadReplyRules:S,loadDefaultReplies:k,refresh:I}},te={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:bt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:pt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:tt}},ke=["order_paid","buyer_reviewed","review_missing_timeout"],Bt="亲,商品使用满意的话,麻烦给个评价,谢谢~",be=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),lt=s=>{if(!s)return{};try{const c=JSON.parse(s);return c&&typeof c=="object"&&!Array.isArray(c)?c:{}}catch{return{}}},de=(s,c={})=>{const d=lt(s);return JSON.stringify({after_shipped_hours:Number(d.after_shipped_hours||72),repeat_interval_hours:Number(d.repeat_interval_hours||24),max_attempts:Number(d.max_attempts||1),...c})},ge=(s,c)=>{var y;const d=((y=te[s])==null?void 0:y.label)||"自动化规则";return c?`${d} - ${c}`:d},He=s=>{const c=(s||"").trim();return c?Object.values(te).some(d=>c===d.label||c.startsWith(`${d.label} -`)):!0},ye=(s,c=0)=>{if(s==="review_missing_timeout")return[{action_type:"send_text",message_template:Bt,enabled:!0,sort_order:1}];const d={action_type:"send_card",card_id:c,delivery_count:1,enabled:!0,sort_order:1};return s==="order_paid"?[d,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[d]},Gt=s=>{var d,y;if(s.trigger_type==="review_missing_timeout")return((y=(d=s.actions)==null?void 0:d.find(o=>o.action_type==="send_text"))==null?void 0:y.message_template)||"发送求评价文案";const c=(s.actions||[]).filter(o=>o.action_type==="send_card");return c.length?c.map(o=>o.card_name||`卡密 ${o.card_id}`).join(" / "):"未配置卡密库存"},et=(s,c=!1)=>{const d={blue:c?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:c?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:c?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return d[s]||d.blue},Jt=s=>s?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Ce=s=>(s==null?void 0:s.nickname)||(s==null?void 0:s.remark)||(s==null?void 0:s.id)||"未知账号",Ut=s=>s===!0||s===1||s==="1",Kt=({selectedAccountId:s,setSelectedAccountId:c,setActiveTab:d,items:y,setAutomationRules:o,setCards:U,setItems:F,setLoading:K,loadAutomationRules:C,loadReferenceData:se,loadReplyRules:T,loadDefaultReplies:V,initialDeliveryTarget:v,onDeliveryTargetHandled:O})=>{var me;const[P,j]=r.useState(!1),[W,z]=r.useState(!1),[ae,Z]=r.useState(!1),[B,le]=r.useState(Te),[X,E]=r.useState(Te),[Q,G]=r.useState(Te),[l,S]=r.useState(null),[k,I]=r.useState(null),[R,A]=r.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),b=r.useMemo(()=>l!=null&&l.cookie_id&&l.item_id?y.find(a=>a.cookie_id===l.cookie_id&&a.item_id===l.item_id):void 0,[l==null?void 0:l.cookie_id,l==null?void 0:l.item_id,y]),f=Ut(b==null?void 0:b.is_multi_spec),$=(l==null?void 0:l.trigger_type)||"order_paid",Y=te[$],re=lt(l==null?void 0:l.config_json),L=(me=l==null?void 0:l.variants)!=null&&me.length?l.variants:[be()],J=r.useCallback((a="order_paid",n=s,h="")=>{const x=y.find(_=>_.cookie_id===n&&_.item_id===h),p=(x==null?void 0:x.item_title)||h;return{name:ge(a,p),trigger_type:a,cookie_id:n,item_id:h,item_title:(x==null?void 0:x.item_title)||"",item_keyword:p,card_group_id:0,priority:100,enabled:!0,config_json:a==="review_missing_timeout"?de():"{}",actions:ye(a),variants:a==="review_missing_timeout"?[]:[be()]}},[y,s]),xe=r.useCallback(a=>{var h,x;const n=a.trigger_type||"order_paid";S({...a,trigger_type:n,config_json:n==="review_missing_timeout"?de(a.config_json):a.config_json||"{}",actions:(h=a.actions)!=null&&h.length?a.actions.map(p=>({...p})):ye(n,a.card_group_id),variants:(x=a.variants)!=null&&x.length?a.variants.map(p=>({...p})):n==="review_missing_timeout"?[]:[be()]}),j(!0)},[]);r.useEffect(()=>{if(!v)return;let a=!1;return(async()=>{d("automation"),c(v.cookieId),K(!0);try{const[h,x,p]=await Promise.all([zt(),at(),st().catch(g=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",g),[]))]);if(a)return;o(h),F(x),U(p);const _=h.find(g=>g.cookie_id===v.cookieId&&g.item_id===v.itemId&&g.trigger_type==="order_paid");if(_)xe(_);else{const g=x.find(q=>q.cookie_id===v.cookieId&&q.item_id===v.itemId);S({...J("order_paid",v.cookieId,v.itemId),item_title:(g==null?void 0:g.item_title)||"",item_keyword:(g==null?void 0:g.item_title)||v.itemId,name:ge("order_paid",(g==null?void 0:g.item_title)||v.itemId)}),j(!0)}}catch(h){console.error("打开商品自动化规则失败",h),alert("无法加载该商品的自动化规则")}finally{a||(K(!1),O==null||O())}})(),(()=>{a=!0})},[J,v,O,xe,d,o,U,F,K,c]);const Se=r.useCallback((a="order_paid")=>{if(!s){alert("请先选择账号");return}S(J(a)),j(!0)},[J,s]),fe=r.useCallback(a=>{var x,p,_,g,q;if(!l)return;const n=((p=(x=l.variants)==null?void 0:x.find(ee=>ee.card_id))==null?void 0:p.card_id)||((g=(_=l.actions)==null?void 0:_.find(ee=>ee.action_type==="send_card"))==null?void 0:g.card_id)||l.card_group_id||0,h=(b==null?void 0:b.item_title)||l.item_title||l.item_id||"";S({...l,trigger_type:a,name:He(l.name)?ge(a,h):l.name,card_group_id:n,config_json:a==="review_missing_timeout"?de(l.config_json):"{}",actions:ye(a,n),variants:a==="review_missing_timeout"?[]:(q=l.variants)!=null&&q.length?l.variants:[{...be(),card_id:n}]})},[l,b]),Re=r.useCallback(a=>{if(!l)return;const n=y.find(x=>x.cookie_id===(l.cookie_id||s)&&x.item_id===a),h=(n==null?void 0:n.item_title)||a;S({...l,item_id:a,item_title:(n==null?void 0:n.item_title)||"",item_keyword:h,name:He(l.name)?ge($,h):l.name})},[$,l,y,s]),ue=r.useCallback((a,n)=>{var x;if(!l)return;const h=L.map((p,_)=>_===a?{...p,...n}:p);S({...l,variants:h,card_group_id:((x=h[0])==null?void 0:x.card_id)||0})},[L,l]),Ae=r.useCallback(()=>{if(!l)return;const a=L[L.length-1];S({...l,variants:[...L,{...be(),spec_name:f&&(a==null?void 0:a.spec_name)||"",spec_value:f&&(a==null?void 0:a.spec_value)||""}]})},[L,l,f]),je=r.useCallback(async()=>{var p,_,g,q,ee;if(!l||B.submitting)return;const a=l.trigger_type||"order_paid";if(!l.cookie_id)return alert("请选择账号");const n=(p=l.variants)!=null&&p.length?l.variants:[];if(a!=="review_missing_timeout"){if(!n.length||n.some(N=>!N.card_id))return alert(a==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(f&&n.some(N=>!N.spec_name.trim()||!N.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(a==="review_missing_timeout"&&!(((g=(_=l.actions)==null?void 0:_.find(Me=>Me.action_type==="send_text"))==null?void 0:g.message_template)||"").trim())return alert("请填写求评价文案");const h=a==="review_missing_timeout"?[]:n.map(N=>({...N,spec_name:f?N.spec_name.trim():"",spec_value:f?N.spec_value.trim():"",delivery_count:Math.max(1,Number(N.delivery_count)||1),enabled:N.enabled!==!1}));le(ze(B));let x=!1;try{await Qe({...l,trigger_type:a,name:(l.name||"").trim()||ge(a,(b==null?void 0:b.item_title)||l.item_id||""),config_json:a==="review_missing_timeout"?de(l.config_json):l.config_json||"{}",actions:(q=l.actions)!=null&&q.length?l.actions:ye(a,((ee=h[0])==null?void 0:ee.card_id)||l.card_group_id||0),variants:h}),j(!1),await Promise.all([C(),se()]),alert("保存成功"),x=!0}catch(N){console.error("保存自动化规则失败:",N),alert("保存失败:"+N.message)}finally{le(N=>Ee(N,x))}},[B,l,f,C,se,b]),u=r.useCallback(async a=>{if(confirm("确定删除该自动化规则吗?"))try{await At(a),await C(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[C]),D=r.useCallback(async a=>{try{await Qe({...a,enabled:!a.enabled}),await C()}catch(n){alert("操作失败:"+n.message)}},[C]),w=r.useCallback(async(a,n)=>{if(confirm(n==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":n==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Mt(a,n),await C()}catch(x){alert("处理失败:"+x.message)}},[C]),H=r.useCallback(async(a,n)=>{if(confirm(n==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Pt(a,n),await C()}catch(h){alert("处理失败:"+h.message)}},[C]),M=r.useCallback(()=>{if(!s)return alert("请先选择账号");I({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),z(!0)},[s]),ne=r.useCallback(async()=>{var h,x,p;if(!k||!s||X.submitting)return;const a=k.type==="image"?!!((h=k.image_url)!=null&&h.trim()):!!((x=k.reply_content)!=null&&x.trim());if(!((p=k.keyword)!=null&&p.trim())||!a)return alert("请填写关键词和回复内容");E(ze(X));let n=!1;try{await $t({...k,match_type:"fuzzy",enabled:!0},s),z(!1),await T(),alert("保存成功"),n=!0}catch(_){alert("保存失败:"+_.message)}finally{E(_=>Ee(_,n))}},[k,T,X,s]),he=r.useCallback(async a=>{if(!(!s||!confirm("确定删除该回复规则吗?")))try{await It(a,s),await T(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[T,s]),ie=r.useCallback(async(a=s)=>{if(!a)return alert("请先选择账号");try{const n=await Lt(a);A({cookie_id:a,enabled:n.enabled,reply_content:n.reply_content,reply_once:n.reply_once,reply_image_url:n.reply_image_url||""})}catch{A({cookie_id:a,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Z(!0)},[s]),ce=r.useCallback(async()=>{if(Q.submitting)return;if(!R.cookie_id)return alert("请先选择账号");if(R.enabled&&!R.reply_content.trim()&&!R.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");G(ze(Q));let a=!1;try{await Dt(R.cookie_id,{enabled:R.enabled,reply_content:R.reply_content,reply_once:R.reply_once,reply_image_url:R.reply_image_url}),Z(!1),await V(),alert("保存成功"),a=!0}catch(n){alert("保存失败:"+n.message)}finally{G(n=>Ee(n,a))}},[R,Q,V]),_e=r.useCallback(async a=>{if(confirm("确定删除该账号默认回复吗?"))try{await Ft(a),await V(),alert("删除成功")}catch(n){alert("删除失败:"+n.message)}},[V]),pe=r.useCallback(async a=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Tt(a),alert("清空成功")}catch(n){alert("清空失败:"+n.message)}},[]);return{showAutomationModal:P,setShowAutomationModal:j,showReplyModal:W,setShowReplyModal:z,showDefaultModal:ae,setShowDefaultModal:Z,automationSubmitState:B,replySubmitState:X,defaultReplySubmitState:Q,editingAutomationRule:l,setEditingAutomationRule:S,editingReplyRule:k,setEditingReplyRule:I,defaultForm:R,setDefaultForm:A,selectedRuleItem:b,isMultiSpecRule:f,currentTrigger:$,currentMeta:Y,reviewConfig:re,displayVariants:L,buildAutomationDraft:J,openAutomationRule:xe,openNewAutomationRule:Se,handleTriggerChange:fe,handleAutomationItemChange:Re,updateVariant:ue,appendDeliveryContent:Ae,handleSaveAutomationRule:je,handleDeleteAutomation:u,handleToggleAutomation:D,handleResolveRunIssue:w,handleResolveDeferredIssue:H,handleAddReplyRule:M,handleSaveReplyRule:ne,handleDeleteReply:he,openDefaultReplyModal:ie,handleSaveDefaultReply:ce,handleDeleteDefaultReply:_e,handleClearDefaultReplyRecords:pe}},Qt=({initialDeliveryTarget:s,onDeliveryTargetHandled:c})=>{var Ge,Je;const[d,y]=r.useState("automation"),[o,U]=r.useState(""),[F,K]=r.useState(""),[C,se]=r.useState(""),[T,V]=r.useState(""),[v,O]=r.useState("all"),[P,j]=r.useState(1),[W,z]=r.useState(10),ae=Ot({activeTab:d,selectedAccountId:o,automationTriggerFilter:T,automationStatusFilter:v,debouncedAutomationSearch:C,automationPage:P,automationPageSize:W,setSelectedAccountId:U,onAutomationPageChange:j}),{automationRules:Z,automationIssues:B,replyRules:le,defaultReplies:X,accounts:E,cards:Q,items:G,loading:l,setLoading:S,automationTotal:k,automationTotalPages:I,automationTriggerCounts:R,setAutomationRules:A,setCards:b,setItems:f,loadReferenceData:$,loadAutomationRules:Y,loadReplyRules:re,loadDefaultReplies:L,refresh:J}=ae,xe=Kt({selectedAccountId:o,setSelectedAccountId:U,setActiveTab:y,items:G,setAutomationRules:A,setCards:b,setItems:f,setLoading:S,loadAutomationRules:Y,loadReferenceData:$,loadReplyRules:re,loadDefaultReplies:L,initialDeliveryTarget:s,onDeliveryTargetHandled:c}),{showAutomationModal:Se,setShowAutomationModal:fe,showReplyModal:Re,setShowReplyModal:ue,showDefaultModal:Ae,setShowDefaultModal:je,editingAutomationRule:u,setEditingAutomationRule:D,editingReplyRule:w,setEditingReplyRule:H,defaultForm:M,setDefaultForm:ne,selectedRuleItem:he,isMultiSpecRule:ie,currentTrigger:ce,currentMeta:_e,reviewConfig:pe,displayVariants:me,openAutomationRule:a,openNewAutomationRule:n,handleTriggerChange:h,handleAutomationItemChange:x,updateVariant:p,appendDeliveryContent:_,handleSaveAutomationRule:g,handleDeleteAutomation:q,handleToggleAutomation:ee,handleResolveRunIssue:N,handleResolveDeferredIssue:Me,handleAddReplyRule:rt,handleSaveReplyRule:nt,handleDeleteReply:it,openDefaultReplyModal:Oe,handleSaveDefaultReply:ot,handleDeleteDefaultReply:dt,handleClearDefaultReplyRecords:ct}=xe;r.useEffect(()=>{const t=window.setTimeout(()=>{j(1),se(F.trim())},300);return(()=>window.clearTimeout(t))},[F]),r.useEffect(()=>{$().catch(t=>console.error("加载规则参考数据失败",t))},[$]),r.useEffect(()=>{J().catch(t=>console.error("刷新规则页面失败",t))},[J]);const Pe=r.useMemo(()=>Z.filter(t=>!o||t.cookie_id===o),[Z,o]),ve=r.useMemo(()=>Et(B,o),[B,o]),Be=r.useMemo(()=>E.filter(t=>!o||t.id===o),[E,o]),mt=r.useMemo(()=>{if(I<=1)return[];const t=Math.max(1,Math.min(P-2,I-4)),i=Math.min(I,t+4);return Array.from({length:i-t+1},(m,oe)=>t+oe)},[P,I]),$e=!!(F.trim()||T||v!=="all"),xt=()=>{K(""),se(""),V(""),O("all"),j(1)},ut=r.useMemo(()=>{const t=(u==null?void 0:u.cookie_id)||o;return G.filter(i=>i.cookie_id===t)},[u==null?void 0:u.cookie_id,G,o]),ht=d==="automation"?"新建自动化":d==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"min-w-0 space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:flex-wrap gap-3",children:[e.jsxs("select",{value:o,onChange:(t=>{U(t.target.value),j(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]}),e.jsxs("button",{onClick:J,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors",children:[e.jsx(Le,{className:`w-4 h-4 ${l?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:d==="automation"?(()=>n("order_paid")):d==="reply"?rt:(()=>void Oe()),disabled:!o,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50",children:[e.jsx(Ue,{className:"w-4 h-4"}),ht]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Ke},{id:"reply",label:"关键词回复",icon:gt},{id:"default",label:"账号默认回复",icon:We}].map(t=>{const i=t.icon;return e.jsxs("button",{onClick:(()=>y(t.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${d===t.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(i,{className:"w-4 h-4"}),t.label]},t.id)})}),d==="automation"&&(ve.runs.length>0||ve.pending_tasks.length>0)&&e.jsx(Vt,{runs:ve.runs,pendingTasks:ve.pending_tasks,onResolveRun:((t,i)=>void N(t,i)),onResolveDeferredTask:((t,i)=>void Me(t,i))}),d==="automation"&&e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]",children:[e.jsxs("aside",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.icon;return e.jsx("button",{type:"button",onClick:(()=>n(t)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${et(i.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(m,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:i.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:i.description})]})]})},t)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"font-black text-gray-900",children:"筛选结果构成"}),e.jsxs("span",{className:"text-xs font-bold text-gray-400",children:["共 ",k," 条"]})]}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(m,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:i.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:R[t]||0})]},t)})})]})]}),e.jsxs("section",{className:"min-w-0 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-gray-100 bg-surface-muted p-4 shadow-sm",children:[e.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(yt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"搜索自动化规则",placeholder:"搜索规则名、商品名或商品 ID...",value:F,onChange:(t=>{K(t.target.value),j(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]}),e.jsxs("div",{className:"relative xl:w-52",children:[e.jsx(ft,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按自动化类型筛选",value:T,onChange:(t=>{V(t.target.value),j(1)}),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部自动化类型"}),ke.map(t=>e.jsx("option",{value:t,children:te[t].shortLabel},t))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:v,onChange:(t=>{O(t.target.value),j(1)}),className:"ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36",children:[e.jsx("option",{value:"all",children:"全部状态"}),e.jsx("option",{value:"enabled",children:"已启用"}),e.jsx("option",{value:"disabled",children:"已禁用"})]}),$e&&e.jsx("button",{type:"button",onClick:xt,className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900",title:"清除筛选","aria-label":"清除筛选",children:e.jsx(Ne,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs font-bold text-gray-400",children:[e.jsxs("span",{children:["找到 ",k," 条规则"]}),l&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Le,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),l&&Pe.length===0?e.jsxs("div",{className:"flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400",children:[e.jsx(Le,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Pe.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Ke,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:$e?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:$e?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Pe.map(t=>{const i=te[t.trigger_type],m=i.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${et(i.accent,!0)}`,children:e.jsx(m,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:t.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Jt(t.enabled)}`,children:t.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:i.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:t.item_title||t.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Gt(t)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>a(t)),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>ee(t)),className:`px-4 py-2 rounded-xl text-sm font-bold ${t.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:t.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>q(t.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(we,{className:"w-4 h-4"})})]})]})},t.id)}),k>0&&e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm font-medium text-gray-500",children:[e.jsxs("span",{children:["第 ",P," / ",Math.max(I,1)," 页"]}),e.jsx("span",{className:"h-4 w-px bg-gray-200"}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"sr-only",children:"每页显示数量"}),e.jsx("select",{value:W,onChange:(t=>{z(Number(t.target.value)),j(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(t=>e.jsxs("option",{value:t,children:[t," 条/页"]},t))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:P<=1||l,onClick:(()=>j(t=>Math.max(1,t-1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"上一页",title:"上一页",children:e.jsx(jt,{className:"h-4 w-4"})}),mt.map(t=>e.jsx("button",{type:"button",disabled:l,onClick:(()=>j(t)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${t===P?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${t} 页`,"aria-current":t===P?"page":void 0,children:t},t)),e.jsx("button",{type:"button",disabled:P>=I||l,onClick:(()=>j(t=>Math.min(I,t+1))),className:"flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40","aria-label":"下一页",title:"下一页",children:e.jsx(_t,{className:"h-4 w-4"})})]})]})]})]}),d==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Ve,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[le.map(t=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",t.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:t.type==="image"&&t.image_url?t.image_url:t.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>{H({...t}),ue(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(De,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>it(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(we,{className:"w-5 h-5"})})]})]},t.id)),le.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),d==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(Ve,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Be.map(t=>{const i=X[t.id],m=!!(i!=null&&i.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${m?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${m?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(We,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Ce(t)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${m?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:m?"已启用":"未启用"}),(i==null?void 0:i.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:m?i.reply_content||i.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:(()=>void Oe(t.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(De,{className:"w-4 h-4"})}),m&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void ct(t.id)),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:(()=>void dt(t.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(we,{className:"w-5 h-5"})})]})]})]},t.id)}),Be.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),Se&&u&&Ie.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:u.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:_e.description})]}),e.jsx("button",{onClick:(()=>fe(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:ke.map(t=>{const i=te[t],m=i.icon,oe=ce===t;return e.jsx("button",{type:"button",onClick:(()=>h(t)),className:`w-full rounded-2xl p-4 text-left border transition-all ${oe?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(m,{className:`w-5 h-5 mt-0.5 ${oe?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:i.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${oe?"text-gray-500":"text-gray-400"}`,children:i.description})]})]})},t)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:_e.flow.map((t,i)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:i+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:t})]},t))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-surface-subtle",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(vt,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:u.name||"",onChange:(t=>D({...u,name:t.target.value})),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:u.cookie_id||"",onChange:(t=>D({...u,cookie_id:t.target.value,item_id:"",item_title:"",item_keyword:""})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:u.item_id||"",onChange:(t=>x(t.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ut.map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.item_id}`))]})]})]}),he&&ce!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:he.item_title||he.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${ie?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:ie?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),ce!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nt,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:ce==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:ie?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:_,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Ue,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:me.map((t,i)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${ie?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[ie&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:t.spec_name,onChange:(m=>p(i,{spec_name:m.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:t.spec_value,onChange:(m=>p(i,{spec_value:m.target.value})),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:t.card_id||"",onChange:(m=>p(i,{card_id:Number(m.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),Q.filter(m=>m.enabled&&m.type!=="api").map(m=>e.jsx("option",{value:m.id,children:m.name},m.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:t.delivery_count,onChange:(m=>p(i,{delivery_count:Math.max(1,Number(m.target.value)||1)})),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:t.delay_override===!0,onChange:(m=>p(i,{delay_override:m.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),t.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:t.delay_seconds||0,onChange:(m=>p(i,{delay_seconds:Math.max(0,Number(m.target.value)||0)})),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:t.delay_override?`本动作延时 ${t.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:me.length===1,onClick:(()=>D({...u,variants:me.filter((m,oe)=>oe!==i)})),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(we,{className:"w-4 h-4"})})]},t.id||i))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(tt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(pe.after_shipped_hours||72),onChange:(t=>D({...u,config_json:de(u.config_json,{after_shipped_hours:Math.max(1,Number(t.target.value)||72)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(pe.repeat_interval_hours||24),onChange:(t=>D({...u,config_json:de(u.config_json,{repeat_interval_hours:Math.max(1,Number(t.target.value)||24)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(pe.max_attempts||1),onChange:(t=>D({...u,config_json:de(u.config_json,{max_attempts:Math.max(1,Number(t.target.value)||1)})})),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((Je=(Ge=u.actions)==null?void 0:Ge.find(t=>t.action_type==="send_text"))==null?void 0:Je.message_template)||"",onChange:(t=>{var i;return D({...u,actions:((i=u.actions)!=null&&i.length?u.actions:ye("review_missing_timeout")).map(m=>m.action_type==="send_text"?{...m,message_template:t.target.value}:m)})}),className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:u.priority||100,onChange:(t=>D({...u,priority:Number(t.target.value)||100})),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:u.enabled!==!1,onChange:(t=>D({...u,enabled:t.target.checked})),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:(()=>fe(!1)),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:g,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Re&&w&&Ie.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:w.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>ue(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:w.item_id||"",onChange:(t=>H({...w,item_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),G.filter(t=>!o||t.cookie_id===o).map(t=>e.jsx("option",{value:t.item_id,children:t.item_title||t.item_id},`${t.cookie_id}-${t.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:w.type||"text",onChange:(t=>{const i=t.target.value;H({...w,type:i,reply_content:i==="text"?w.reply_content:"",image_url:i==="image"?w.image_url:""})}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:w.keyword||"",onChange:(t=>H({...w,keyword:t.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),w.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:w.image_url||"",onChange:(t=>H({...w,image_url:t.target.value})),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:w.reply_content||"",onChange:(t=>H({...w,reply_content:t.target.value})),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ue(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:nt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(wt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Ae&&Ie.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:M.cookie_id,onChange:(t=>ne({...M,cookie_id:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),E.map(t=>e.jsx("option",{value:t.id,children:Ce(t)},t.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:(()=>ne({...M,enabled:!M.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${M.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${M.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:M.reply_content,onChange:(t=>ne({...M,reply_content:t.target.value})),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:M.reply_image_url,onChange:(t=>ne({...M,reply_image_url:t.target.value})),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:M.reply_once,onChange:(t=>ne({...M,reply_once:t.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>je(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ot,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{Qt as default}; diff --git a/internal/webui/static/assets/Settings-j3SwRFCx.js b/internal/webui/static/assets/Settings-5xhSVKHU.js similarity index 99% rename from internal/webui/static/assets/Settings-j3SwRFCx.js rename to internal/webui/static/assets/Settings-5xhSVKHU.js index 3012579..39e19ec 100644 --- a/internal/webui/static/assets/Settings-j3SwRFCx.js +++ b/internal/webui/static/assets/Settings-5xhSVKHU.js @@ -1 +1 @@ -import{r as a,j as e}from"./react-vendor-C_od1ZSF.js";import{a2 as ce,a3 as ie,a4 as de,a5 as xe,a6 as ue}from"./index-DK02p8DH.js";import{b as pe,R as se,aa as me,p as he,u as q,v as D,ab as ge,s as ye,h as te,ac as ae,ad as be,r as fe}from"./icons-vendor-ThcsWkZG.js";const le="https://dashscope.aliyuncs.com/compatible-mode/v1",we=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],je=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),ve=s=>Object.fromEntries(Object.entries(s).filter(([c,m])=>!je.has(c)&&m!==void 0&&m!==null)),Ne=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",g=(s,c,m)=>s===c&&!m.aborted,O=s=>s instanceof Error&&s.message==="请求已取消",K=(s,c)=>s instanceof Error?s.message:c,_e=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,c)=>({type:s,text:c}),Se=()=>{const[s,c]=a.useState(null),[m,k]=a.useState(!1),[I,x]=a.useState(""),[N,E]=a.useState(!1),[P,_]=a.useState(""),[S,b]=a.useState([]),[f,A]=a.useState(!1),[M,i]=a.useState(""),[$,w]=a.useState(!1),[U,L]=a.useState(!1),[z,d]=a.useState(!1),[y,F]=a.useState(!1),[G,J]=a.useState(!1),[V,j]=a.useState(!1),[R,h]=a.useState(null),[t,X]=a.useState(()=>_e()),[re,W]=a.useState("idle"),Z=a.useRef(null),ee=a.useRef(null),u=a.useRef(0),Y=a.useRef(null);ee.current=s;const C=a.useCallback(()=>{var n;(n=Y.current)==null||n.abort();const r=new AbortController;return Y.current=r,u.current+=1,{controller:r,sequence:u.current}},[]),B=a.useCallback(async(r,n=!1,l)=>{const o=r||ee.current,p=(o==null?void 0:o.ai_api_url)||(o==null?void 0:o.ai_base_url)||le;A(!0),i("");try{const v=await ce(p,(o==null?void 0:o.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;b(v),w(n&&v.length>0),!(o!=null&&o.ai_model)&&v.length>0&&c(Q=>Q&&{...Q,ai_model:v[0]})}catch(v){if(l!=null&&l.aborted||O(v))return;b([]),w(!1),i(K(v,"读取模型失败"))}finally{l!=null&&l.aborted||A(!1)}},[]),H=a.useCallback(()=>{const{controller:r,sequence:n}=C();k(!0),W("loading"),x(""),Promise.all([ie({signal:r.signal}),de({signal:r.signal})]).then(([l,o])=>{g(u.current,n,r.signal)&&(c(l),o.username&&X(p=>({...p,new_username:o.username||""})),B(l,!1,r.signal),W("success"))}).catch(l=>{!g(u.current,n,r.signal)||O(l)||(c(null),x(K(l,"加载配置失败")),W("error"))}).finally(()=>{g(u.current,n,r.signal)&&k(!1)})},[C,B]);a.useEffect(()=>(H(),(()=>{var r;return(r=Y.current)==null?void 0:r.abort()})),[H]),a.useEffect(()=>{const r=n=>{var l;(l=Z.current)!=null&&l.contains(n.target)||w(!1)};return document.addEventListener("mousedown",r),(()=>document.removeEventListener("mousedown",r))},[]);const ne=a.useCallback(async()=>{if(!s||N)return;const{controller:r,sequence:n}=C();E(!0),_("");try{if(await xe(ve(s),{signal:r.signal}),!g(u.current,n,r.signal))return;window.alert("系统配置已保存")}catch(l){if(!g(u.current,n,r.signal)||O(l))return;_(K(l,"保存配置失败"))}finally{g(u.current,n,r.signal)&&E(!1)}},[C,N,s]),oe=a.useCallback(async r=>{r.preventDefault(),h(null);const n=Ne(t);if(n){h(T("error",n));return}const{controller:l,sequence:o}=C();j(!0);try{const p=await ue({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!g(u.current,o,l.signal))return;if(!p.success){h(T("error",p.message||"登录凭据更新失败"));return}h(T("success",p.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(p){if(!g(u.current,o,l.signal)||O(p))return;h(T("error",K(p,"登录凭据更新失败")))}finally{g(u.current,o,l.signal)&&j(!1)}},[C,t]);return{settings:s,loading:m,loadError:I,saving:N,saveError:P,aiModels:S,modelsLoading:f,modelError:M,modelDropdownOpen:$,showApiKey:U,showCaptchaSecret:z,showCurrentPassword:y,showNewPassword:G,credentialsSaving:V,credentialsMessage:R,credentials:t,requestStatus:re,modelPickerRef:Z,loadSettings:H,loadAIModels:((r,n)=>void B(r,n)),handleSave:ne,handleCredentialsSave:oe,setSettings:c,setModelDropdownOpen:w,setShowApiKey:L,setShowCaptchaSecret:d,setShowCurrentPassword:F,setShowNewPassword:J,setCredentials:X,setCredentialsMessage:h}},Ae=()=>{const{settings:s,loading:c,loadError:m,saving:k,saveError:I,aiModels:x,modelsLoading:N,modelError:E,modelDropdownOpen:P,showApiKey:_,showCaptchaSecret:S,showCurrentPassword:b,showNewPassword:f,credentialsSaving:A,credentialsMessage:M,credentials:i,modelPickerRef:$,loadSettings:w,loadAIModels:U,handleSave:L,handleCredentialsSave:z,setSettings:d,setModelDropdownOpen:y,setShowApiKey:F,setShowCaptchaSecret:G,setShowCurrentPassword:J,setShowNewPassword:V,setCredentials:j}=Se();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[m||(c?"加载配置中...":"暂无配置"),!c&&m&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:w,children:"重新加载"})})]});const R=s.ai_model||"",h=x;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(pe,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:w,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(se,{className:"w-4 h-4"}),"刷新"]})]}),I&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:I}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(me,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>d({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:we.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>d({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>d({...s,renewal_log_retention_days:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(he,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||le,onChange:(t=>d({...s,ai_api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:_?"text":"password",value:s.ai_api_key||"",onChange:(t=>d({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>F(!_)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:_?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:$,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:R,onFocus:(()=>x.length>0&&y(!0)),onChange:(t=>{d({...s,ai_model:t.target.value}),x.length>0&&y(!0)}),onKeyDown:(t=>{t.key==="Escape"&&y(!1),t.key==="ArrowDown"&&x.length>0&&y(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>x.length>0&&y(t=>!t)),disabled:x.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(ge,{className:`w-4 h-4 transition-transform ${P?"rotate-180":""}`})}),P&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:h.length>0?h.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{d({...s,ai_model:t}),y(!1)}),className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t}),t===R&&e.jsx(ye,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>U(void 0,!0)),disabled:N,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(se,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"读取模型"]})]}),E?e.jsx("p",{className:"text-xs text-red-500",children:E}):e.jsx("p",{className:"text-xs text-gray-500",children:x.length>0?`已从当前 API 地址读取到 ${x.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(te,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>d({...s,"captcha.remote_service_url":t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:S?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>d({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>G(!S)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:S?"隐藏秘钥":"显示秘钥",children:S?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>d({...s,"captcha.remote_pass_cookies":t.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(ae,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:z,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:i.new_username,onChange:(t=>j({...i,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:b?"text":"password",value:i.current_password,onChange:(t=>j({...i,current_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>J(!b)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:b?"隐藏密码":"显示密码",children:b?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:f?"text":"password",value:i.new_password,onChange:(t=>j({...i,new_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>V(!f)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:f?"隐藏密码":"显示密码",children:f?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:f?"text":"password",value:i.confirm_password,onChange:(t=>j({...i,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),M&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${M.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(te,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:M.text})]}),e.jsxs("button",{type:"submit",disabled:A||!i.new_username||!i.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(ae,{className:"w-4 h-4"}),A?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:L,disabled:k,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(fe,{className:"w-6 h-6"}),k?"保存中...":"保存所有配置"]})})]})};export{Ae as default}; +import{r as a,j as e}from"./react-vendor-C_od1ZSF.js";import{a2 as ce,a3 as ie,a4 as de,a5 as xe,a6 as ue}from"./index-CYPNW7Ux.js";import{b as pe,R as se,aa as me,p as he,u as q,v as D,ab as ge,s as ye,h as te,ac as ae,ad as be,r as fe}from"./icons-vendor-ThcsWkZG.js";const le="https://dashscope.aliyuncs.com/compatible-mode/v1",we=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],je=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),ve=s=>Object.fromEntries(Object.entries(s).filter(([c,m])=>!je.has(c)&&m!==void 0&&m!==null)),Ne=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",g=(s,c,m)=>s===c&&!m.aborted,O=s=>s instanceof Error&&s.message==="请求已取消",K=(s,c)=>s instanceof Error?s.message:c,_e=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,c)=>({type:s,text:c}),Se=()=>{const[s,c]=a.useState(null),[m,k]=a.useState(!1),[I,x]=a.useState(""),[N,E]=a.useState(!1),[P,_]=a.useState(""),[S,b]=a.useState([]),[f,A]=a.useState(!1),[M,i]=a.useState(""),[$,w]=a.useState(!1),[U,L]=a.useState(!1),[z,d]=a.useState(!1),[y,F]=a.useState(!1),[G,J]=a.useState(!1),[V,j]=a.useState(!1),[R,h]=a.useState(null),[t,X]=a.useState(()=>_e()),[re,W]=a.useState("idle"),Z=a.useRef(null),ee=a.useRef(null),u=a.useRef(0),Y=a.useRef(null);ee.current=s;const C=a.useCallback(()=>{var n;(n=Y.current)==null||n.abort();const r=new AbortController;return Y.current=r,u.current+=1,{controller:r,sequence:u.current}},[]),B=a.useCallback(async(r,n=!1,l)=>{const o=r||ee.current,p=(o==null?void 0:o.ai_api_url)||(o==null?void 0:o.ai_base_url)||le;A(!0),i("");try{const v=await ce(p,(o==null?void 0:o.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;b(v),w(n&&v.length>0),!(o!=null&&o.ai_model)&&v.length>0&&c(Q=>Q&&{...Q,ai_model:v[0]})}catch(v){if(l!=null&&l.aborted||O(v))return;b([]),w(!1),i(K(v,"读取模型失败"))}finally{l!=null&&l.aborted||A(!1)}},[]),H=a.useCallback(()=>{const{controller:r,sequence:n}=C();k(!0),W("loading"),x(""),Promise.all([ie({signal:r.signal}),de({signal:r.signal})]).then(([l,o])=>{g(u.current,n,r.signal)&&(c(l),o.username&&X(p=>({...p,new_username:o.username||""})),B(l,!1,r.signal),W("success"))}).catch(l=>{!g(u.current,n,r.signal)||O(l)||(c(null),x(K(l,"加载配置失败")),W("error"))}).finally(()=>{g(u.current,n,r.signal)&&k(!1)})},[C,B]);a.useEffect(()=>(H(),(()=>{var r;return(r=Y.current)==null?void 0:r.abort()})),[H]),a.useEffect(()=>{const r=n=>{var l;(l=Z.current)!=null&&l.contains(n.target)||w(!1)};return document.addEventListener("mousedown",r),(()=>document.removeEventListener("mousedown",r))},[]);const ne=a.useCallback(async()=>{if(!s||N)return;const{controller:r,sequence:n}=C();E(!0),_("");try{if(await xe(ve(s),{signal:r.signal}),!g(u.current,n,r.signal))return;window.alert("系统配置已保存")}catch(l){if(!g(u.current,n,r.signal)||O(l))return;_(K(l,"保存配置失败"))}finally{g(u.current,n,r.signal)&&E(!1)}},[C,N,s]),oe=a.useCallback(async r=>{r.preventDefault(),h(null);const n=Ne(t);if(n){h(T("error",n));return}const{controller:l,sequence:o}=C();j(!0);try{const p=await ue({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!g(u.current,o,l.signal))return;if(!p.success){h(T("error",p.message||"登录凭据更新失败"));return}h(T("success",p.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(p){if(!g(u.current,o,l.signal)||O(p))return;h(T("error",K(p,"登录凭据更新失败")))}finally{g(u.current,o,l.signal)&&j(!1)}},[C,t]);return{settings:s,loading:m,loadError:I,saving:N,saveError:P,aiModels:S,modelsLoading:f,modelError:M,modelDropdownOpen:$,showApiKey:U,showCaptchaSecret:z,showCurrentPassword:y,showNewPassword:G,credentialsSaving:V,credentialsMessage:R,credentials:t,requestStatus:re,modelPickerRef:Z,loadSettings:H,loadAIModels:((r,n)=>void B(r,n)),handleSave:ne,handleCredentialsSave:oe,setSettings:c,setModelDropdownOpen:w,setShowApiKey:L,setShowCaptchaSecret:d,setShowCurrentPassword:F,setShowNewPassword:J,setCredentials:X,setCredentialsMessage:h}},Ae=()=>{const{settings:s,loading:c,loadError:m,saving:k,saveError:I,aiModels:x,modelsLoading:N,modelError:E,modelDropdownOpen:P,showApiKey:_,showCaptchaSecret:S,showCurrentPassword:b,showNewPassword:f,credentialsSaving:A,credentialsMessage:M,credentials:i,modelPickerRef:$,loadSettings:w,loadAIModels:U,handleSave:L,handleCredentialsSave:z,setSettings:d,setModelDropdownOpen:y,setShowApiKey:F,setShowCaptchaSecret:G,setShowCurrentPassword:J,setShowNewPassword:V,setCredentials:j}=Se();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[m||(c?"加载配置中...":"暂无配置"),!c&&m&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:w,children:"重新加载"})})]});const R=s.ai_model||"",h=x;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(pe,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:w,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(se,{className:"w-4 h-4"}),"刷新"]})]}),I&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700",children:[e.jsx("span",{children:I}),e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>{}),children:"重试保存"})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(me,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:(t=>d({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:we.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:(t=>d({...s,log_format:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:(t=>d({...s,renewal_log_retention_days:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-brand text-white",children:e.jsx(he,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||le,onChange:(t=>d({...s,ai_api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:_?"text":"password",value:s.ai_api_key||"",onChange:(t=>d({...s,ai_api_key:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:s.ai_api_key_configured?"已配置,如需替换请输入新密钥":"sk-..."}),e.jsx("button",{type:"button",onClick:(()=>F(!_)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:_?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:$,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:R,onFocus:(()=>x.length>0&&y(!0)),onChange:(t=>{d({...s,ai_model:t.target.value}),x.length>0&&y(!0)}),onKeyDown:(t=>{t.key==="Escape"&&y(!1),t.key==="ArrowDown"&&x.length>0&&y(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>x.length>0&&y(t=>!t)),disabled:x.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(ge,{className:`w-4 h-4 transition-transform ${P?"rotate-180":""}`})}),P&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:h.length>0?h.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{d({...s,ai_model:t}),y(!1)}),className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:t}),t===R&&e.jsx(ye,{className:"w-4 h-4 shrink-0 text-brand"})]},t)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:(()=>U(void 0,!0)),disabled:N,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(se,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"读取模型"]})]}),E?e.jsx("p",{className:"text-xs text-red-500",children:E}):e.jsx("p",{className:"text-xs text-gray-500",children:x.length>0?`已从当前 API 地址读取到 ${x.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(te,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:(t=>d({...s,"captcha.remote_service_url":t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:S?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>d({...s,"captcha.remote_secret_key":t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off",placeholder:s["captcha.remote_secret_key_configured"]?"已配置,如需替换请输入新密钥":"请输入服务秘钥"}),e.jsx("button",{type:"button",onClick:(()=>G(!S)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:S?"隐藏秘钥":"显示秘钥",children:S?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:(t=>d({...s,"captcha.remote_pass_cookies":t.target.checked})),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(ae,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:z,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:i.new_username,onChange:(t=>j({...i,new_username:t.target.value})),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:b?"text":"password",value:i.current_password,onChange:(t=>j({...i,current_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:(()=>J(!b)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:b?"隐藏密码":"显示密码",children:b?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:f?"text":"password",value:i.new_password,onChange:(t=>j({...i,new_password:t.target.value})),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:(()=>V(!f)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:f?"隐藏密码":"显示密码",children:f?e.jsx(q,{className:"w-4 h-4"}):e.jsx(D,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:f?"text":"password",value:i.confirm_password,onChange:(t=>j({...i,confirm_password:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),M&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${M.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(te,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:M.text})]}),e.jsxs("button",{type:"submit",disabled:A||!i.new_username||!i.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(ae,{className:"w-4 h-4"}),A?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:L,disabled:k,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(fe,{className:"w-6 h-6"}),k?"保存中...":"保存所有配置"]})})]})};export{Ae as default}; diff --git a/internal/webui/static/assets/index-CYPNW7Ux.js b/internal/webui/static/assets/index-CYPNW7Ux.js new file mode 100644 index 0000000..2063c4c --- /dev/null +++ b/internal/webui/static/assets/index-CYPNW7Ux.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-sUNU2Eg5.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-ThcsWkZG.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-Bpj-f-W3.js","assets/OrderList-Bb5NffV_.js","assets/CardList-D5uSws-z.js","assets/ItemList-kyCurZV6.js","assets/Settings-5xhSVKHU.js","assets/Rules-MPWRzM5C.js","assets/Notifications-CyWpiVXa.js","assets/Chat-BLyP9Pyt.js"])))=>i.map(i=>d[i]); +import{j as n,r as p,c as ee,d as xe}from"./react-vendor-C_od1ZSF.js";import{L as we,U as je,M as Le,C as Ne,B as Se,S as ke,Z as Ce,a as Ae,b as Ee,G as Z,c as $e,d as De,e as Ie,f as D,g as H,h as I,A as G,i as Oe}from"./icons-vendor-ThcsWkZG.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();const te="ydisks.sidebar.v1",Te=()=>{try{return window.localStorage.getItem(te)==="collapsed"}catch{return!1}},Pe=e=>{try{window.localStorage.setItem(te,e?"collapsed":"expanded")}catch{}},Re=({className:e="w-full h-full text-white"})=>n.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:n.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:n.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),R=({sizeClass:e="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>n.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[n.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),n.jsxs("div",{className:`relative ${e} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[n.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[n.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),n.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),n.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),n.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:n.jsx(Re,{className:t})})]})]}),ze="modulepreload",qe=function(e){return"/static/"+e},Q={},L=function(t,s,r){let a=Promise.resolve();if(s&&s.length>0){let o=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=o(s.map(d=>{if(d=qe(d),d in Q)return;Q[d]=!0;const u=d.endsWith(".css"),m=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":ze,u||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((x,v)=>{h.addEventListener("load",x),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return a.then(o=>{for(const c of o||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})},Me=3e4,Be=10*6e4;let O=!1;const se=()=>{O||typeof window>"u"||(O=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{O=!1}))},Fe=e=>{if(!e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))a!=null&&t.set(r,String(a));const s=t.toString();return s?`?${s}`:""},$=async(e,t,s={})=>{var d;const r=Fe(s.params),a=`${t}${r}`,i=ae(s.signal,s.timeoutMs??Me);let o;try{o=await fetch(a,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(u){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):u}finally{i.cleanup()}const l=(o.headers.get("content-type")||"").includes("application/json");if(!o.ok){o.status===401&&!s.skipAuthLogout&&se();const u=l?await o.json().catch(()=>{}):await o.text().catch(()=>{}),m=ne(u,o.status);throw new Error(m)}return l?await o.json():await o.text()},g=async(e,t,s)=>$("GET",e,{params:t,...s}),y=async(e,t,s)=>$("POST",e,{body:t,...s}),b=async(e,t,s)=>$("PUT",e,{body:t,...s}),j=async(e,t,s)=>$("DELETE",e,{params:t,...s}),S=async(e,t,s={})=>{var l;const r=ae(s.signal,s.timeoutMs??Be);let a;try{a=await fetch(e,{method:"POST",credentials:"include",signal:r.signal,body:t})}catch(d){throw r.signal.aborted?new Error((l=s.signal)!=null&&l.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{r.cleanup()}const c=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>{}):await a.text().catch(()=>{});if(!a.ok){a.status===401&&se();const d=ne(c,a.status),u=new Error(d);throw u.payload=c,u}return c},ae=(e,t)=>{const s=new AbortController,r=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?r():e==null||e.addEventListener("abort",r,{once:!0});const a=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(a),e==null||e.removeEventListener("abort",r)}}},Ve=e=>{if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.code=="string"&&typeof t.message=="string"},ne=(e,t)=>typeof e=="string"?e:Ve(e)?e.message:`请求失败: ${t}`,E=e=>{const t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${s}-${r}`},q=(e,t)=>{const s=new Date(e);return s.setHours(12,0,0,0),s.setDate(s.getDate()+t),s},z=(e,t)=>({startDate:E(q(e,-(t-1))),endDate:E(e)}),jt=(e,t=new Date,s="",r="")=>{if(e==="custom"&&s&&r){if(s>r)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:r}}return e==="yesterday"?z(q(t,-1),1):z(t,e==="3days"?3:e==="30days"?30:e==="today"?1:7)},Lt=e=>{const t=new Date(`${e.startDate}T12:00:00`),s=new Date(`${e.endDate}T12:00:00`),r=Math.round((s.getTime()-t.getTime())/864e5)+1,a=q(t,-1);return z(a,r)},Je=e=>{const t={...e},s=["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"];for(const r of s){const a=`${r}_configured`;a in t&&(t[a]=t[a]===!0||t[a]==="true")}if("renewal_log_retention_days"in t){const r=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(r)?r:10}return t},Ue=async e=>y("/api/v1/session/login",e,{skipAuthLogout:!0}),Ke=async e=>y("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ye=async e=>g("/api/v1/session",void 0,e),Ze=async e=>g("/health",void 0,e),He=async()=>y("/api/v1/session/logout",{}),Nt=async(e,t)=>b("/api/v1/session/credentials",e,t),Ge=(e,t)=>{const s=e.avatar_url||"";if(!s)return"";try{const r=new URL(s,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",t),r.toString()}catch{return s}},St=async e=>{const t=await g("/api/v1/accounts/details",void 0,e),s=Date.now().toString();return t.map(r=>({id:r.id,value:"",enabled:r.enabled,auto_confirm:r.auto_confirm,remark:r.remark,pause_duration:r.pause_duration,paused_until:Number(r.paused_until||0),paused:r.paused===!0,username:r.username||"",login_password:"",show_browser:r.show_browser===!0||r.show_browser===1||r.show_browser==="1"||r.show_browser==="true",nickname:r.nickname||r.remark||`账号 ${r.id.substring(0,6)}`,avatar_url:Ge(r,s),profile_error:r.profile_error||"",ai_enabled:!1,auto_rate_enabled:r.auto_rate_enabled,rate_content:r.rate_content||"不错的买家,交易愉快",auto_polish_enabled:r.auto_polish_enabled,polish_time:r.polish_time||"03:00",last_rate_scan_at:Number(r.last_rate_scan_at||0),last_polish_date:r.last_polish_date||"",last_polish_at:Number(r.last_polish_at||0)}))},kt=async(e,t)=>g(`/api/v1/account-tasks/${e}`,void 0,t),Ct=async(e,t,s)=>b(`/api/v1/account-tasks/${e}`,t,s),At=async(e,t,s)=>y(`/api/v1/account-tasks/${e}/run`,{task_type:t},{timeoutMs:12e4,...s}),Et=async(e,t,s,r=!1)=>{const a=await g("/api/v1/chat/sessions",{account_id:e,cursor:t,refresh:r?1:void 0},r?{timeoutMs:6e4,...s}:s);return{sessions:a.sessions||[],has_more:a.has_more===!0,next_cursor:a.next_cursor}},$t=async(e,t,s,r,a)=>{const i=await g("/api/v1/chat/messages",{account_id:e,chat_id:t,cursor:s,before_id:r},a);return{messages:i.messages||[],has_more:i.has_more===!0,next_cursor:i.next_cursor,session:i.session}},Dt=async(e,t)=>y("/api/v1/chat/messages",e,t),It=async(e,t)=>{const s=new FormData;return Object.entries(e).forEach(([r,a])=>s.append(r,a)),S("/api/v1/chat/images",s,{timeoutMs:12e4,...t})},Ot=async(e,t,s)=>y("/api/v1/chat/read",{account_id:e,chat_id:t},s),Tt=async e=>g("/api/v1/accounts/runtime-status",void 0,e),Pt=async e=>y("/api/v1/qr-login/generate",void 0,{...e,timeoutMs:(e==null?void 0:e.timeoutMs)??13e4}),Rt=async(e,t)=>g(`/api/v1/qr-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),zt=async(e,t)=>y(`/api/v1/qr-login/complete-verification/${e}`,{target_account_id:t||""}),qt=async(e,t)=>b(`/api/v1/accounts/${e}/status`,{enabled:t}),Mt=async e=>j(`/api/v1/accounts/${e}`),Bt=async(e,t,s)=>b(`/api/v1/accounts/${e}/pause-duration`,{pause_duration:t},s),Ft=async(e,t,s)=>b(`/api/v1/accounts/${e}/settings`,t,s),Vt=async(e,t)=>g(`/api/v1/accounts/${e}/long-login`,void 0,t),Jt=async(e,t,s)=>b(`/api/v1/accounts/${e}/long-login`,{enabled:t},s),Ut=async(e,t)=>y("/api/v1/password-login",e,t),Kt=async(e,t)=>g(`/api/v1/password-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),Yt=async(e,t)=>j(`/api/v1/password-login/cancel/${e}`,void 0,t),Zt=async e=>y(`/api/v1/accounts/${e}/refresh-profile`,{}),Ht=async e=>g("/api/v1/settings/ai-reply",void 0,e),re=e=>{const t=String(e||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Gt=async(e,t,s=1,r=20,a,i)=>{const o={page:s,page_size:r};e&&(o.cookie_id=e),t&&t!=="all"&&(o.status=t),a!=null&&a.trim()&&(o.search=a.trim());const c=await g("/api/v1/orders",o,i),d=(c.orders||c.data||[]).map(u=>({...u,id:u.id||u.order_id,status:re(u.status||u.order_status),quantity:Number(u.quantity||1)}));return{success:!0,data:d,total:c.total||d.length,page:c.page||s,page_size:c.page_size||r,total_pages:c.total_pages||1}},Qt=async(e,t)=>b(`/api/v1/orders/${e}`,t),Wt=async e=>j(`/api/v1/orders/${e}`),Xt=async(e,t,s)=>{const r=new FormData;e&&r.append("cookie_id",e),t&&r.append("status",t);const a=await S("/api/v1/orders/refresh",r,s),i=180;let o=0;try{for(;o{const m=()=>{globalThis.clearTimeout(h),u(new Error("请求已取消"))},h=globalThis.setTimeout(()=>{var x;(x=s==null?void 0:s.signal)==null||x.removeEventListener("abort",m),d()},l);s!=null&&s.signal&&(s.signal.aborted?m():s.signal.addEventListener("abort",m,{once:!0}))}),o+=1}}finally{}throw new Error("订单刷新任务等待超时")},es=async e=>y(`/api/v1/orders/${e}/refresh`),ts=async(e,t)=>y("/api/v1/orders/manual-ship",{order_ids:e,ship_mode:t}),ss=async(e,t)=>e instanceof FormData?S("/api/v1/orders/import",e,t):y("/api/v1/orders/import",e,t),as=async e=>g("/api/v1/analytics/dashboard",void 0,e),ns=async(e=7,t)=>{let s;if(typeof e=="number"){const r=new Date,a=new Date;a.setDate(a.getDate()-e),s={start_date:E(a),end_date:E(r)}}else s=e;return g("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},t)},rs=async(e,t)=>{const s=await g("/api/v1/analytics/orders/valid",{start_date:e.start_date,end_date:e.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()},t),a=(Array.isArray(s)?s:s.orders||[]).map(i=>({...i,id:i.id||i.order_id,status:re(i.status||i.order_status),quantity:Number(i.quantity||1)}));return{orders:a,total:Array.isArray(s)?a.length:Number(s.total??a.length),truncated:Array.isArray(s)?!1:s.truncated===!0}},Qe=e=>{let t=e.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...e,api_config:t||void 0}},ie=e=>({...e,api_config:e.api_config?JSON.stringify(e.api_config):""}),is=async e=>{const t=await g("/api/v1/cards",void 0,e);return(Array.isArray(t)?t:(t==null?void 0:t.cards)||[]).map(Qe)},os=async e=>y("/api/v1/cards",ie(e)),cs=async(e,t)=>b(`/api/v1/cards/${e}`,ie(t)),ls=async e=>j(`/api/v1/cards/${e}`),ds=async(e,t)=>{const s=new FormData;return s.append("file",e),S("/api/v1/cards/batch",s,t)},us=async(e,t,s)=>y(`/api/v1/cards/${e}/append-data`,{content:t},s),T=e=>e===!0||e===1||e==="1",ps=async(e,t)=>{const s=await g("/api/v1/items",void 0,t);return(Array.isArray(s)?s:s.items||[]).map(a=>({...a,id:a.id||`${a.cookie_id}-${a.item_id}`,is_multi_spec:T(a.is_multi_spec),is_multi_qty_ship:T(a.is_multi_qty_ship??a.multi_quantity_delivery),multi_quantity_delivery:T(a.multi_quantity_delivery??a.is_multi_qty_ship)}))},gs=async e=>y("/api/v1/items/get-all-from-account",{cookie_id:e}),ys=async(e,t)=>j(`/api/v1/items/${e}/${t}`),ms=async(e,t)=>y(`/api/v1/items/${e}`,t),fs=async e=>{const t=new FormData;t.set("cookie_id",e.cookie_id),t.set("title",e.title),t.set("description",e.description),t.set("price",e.price),t.set("original_price",e.original_price||""),t.set("quantity",String(e.quantity)),t.set("postage_mode",e.postage_mode),t.set("postage",e.postage||""),e.location&&t.set("location",JSON.stringify(e.location));for(const s of e.images)t.append("images",s);return S("/api/v1/items/publish",t)},hs=async(e,t)=>y("/api/v1/items/publish-categories/recommend",{cookie_id:e,keyword:t}),_s=async e=>{const t=new FormData;return t.set("file",e.file),e.imagesZip&&t.set("images_zip",e.imagesZip),e.defaultCookieId&&t.set("default_cookie_id",e.defaultCookieId),t.set("fallback_category_id",e.fallbackCategory.catId),t.set("fallback_category_name",e.fallbackCategory.catName),t.set("fallback_channel_category_id",e.fallbackCategory.channelCatId||""),t.set("fallback_tb_category_id",e.fallbackCategory.tbCatId||""),e.location&&t.set("location",JSON.stringify(e.location)),S("/api/v1/items/publish-batches/preview",t)},vs=async e=>y("/api/v1/items/publish-batches",{preview_id:e}),bs=async e=>g(`/api/v1/items/publish-batches/${e}`),xs=async(e=20)=>{const t=await g("/api/v1/items/publish-batches",{limit:e});return Array.isArray(t)?t:t.batches||[]},ws=async e=>j(`/api/v1/items/publish-batches/${e}`),js=async e=>y(`/api/v1/items/publish-batches/${e}/cancel`,{}),Ls=async e=>y(`/api/v1/items/publish-batches/${e}/retry-failed`,{}),Ns=async(e,t,s)=>b(`/api/v1/items/${e}/${t}`,s),oe=e=>e.map(t=>{var s,r;return{id:String(t.id),name:t.name||"",trigger_type:t.trigger_type||"order_paid",item_keyword:t.item_title||t.item_id||"",cookie_id:t.cookie_id||"",item_id:t.item_id||"",item_title:t.item_title||"",card_group_id:Number(((s=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:s.card_id)||0),card_group_name:((r=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:r.card_name)||"",priority:t.priority||100,enabled:t.enabled||!1,config_json:t.config_json||"{}",actions:(t.actions||[]).map(a=>({id:a.id?String(a.id):void 0,action_type:a.action_type,card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),message_template:a.message_template||"",delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}",enabled:a.enabled!==!1,sort_order:Number(a.sort_order||0)})),variants:(t.actions||[]).filter(a=>a.action_type==="send_card").map(a=>{let i={};try{i=JSON.parse(a.config_json||"{}")}catch{}return{id:a.id?String(a.id):void 0,spec_name:i.spec_name||"",spec_value:i.spec_value||"",card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),enabled:a.enabled!==!1,delay_override:i.delay_override===!0,delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}"}})}}),Ss=async()=>{const e=await g("/api/v1/automation-rules"),t=Array.isArray(e)?e:e.data||[];return oe(t)},ks=async({cookieId:e,triggerType:t,enabled:s,search:r,page:a=1,pageSize:i=10}={})=>{const o=await g("/api/v1/automation-rules",{page:a,page_size:i,cookie_id:e||void 0,trigger_type:t||void 0,enabled:s,search:(r==null?void 0:r.trim())||void 0}),c=oe(Array.isArray(o)?o:o.data||[]);return{success:!0,data:c,total:Number(Array.isArray(o)?c.length:o.total??c.length),page:Number(Array.isArray(o)?a:o.page??a),page_size:Number(Array.isArray(o)?i:o.page_size??i),total_pages:Number(Array.isArray(o)?c.length?1:0:o.total_pages??(c.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(o)?{}:o.trigger_counts||{}).map(([l,d])=>[l,Number(d)]))}},We=(e,t)=>{if(e!=="order_paid")return t.map((a,i)=>({...a,sort_order:a.sort_order||i+1}));const s=t.filter(a=>a.action_type==="send_card").map((a,i)=>({...a,sort_order:i+1})),r=t.filter(a=>a.action_type!=="send_card"&&a.action_type!=="confirm_shipment");return[...s,...r.map((a,i)=>({...a,sort_order:s.length+i+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:s.length+r.length+1}]},Cs=async e=>{const t=e.trigger_type||"order_paid",r=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",e.item_title||e.item_id||e.cookie_id||""].filter(Boolean).join(" - "),a=(e.actions||[]).filter(l=>l.action_type!=="send_card"&&l.action_type!=="confirm_shipment"),i=e.variants&&e.variants.length>0?[...e.variants.map((l,d)=>({action_type:"send_card",card_id:l.card_id,delivery_count:l.delivery_count||1,enabled:l.enabled!==!1,sort_order:d+1,delay_seconds:l.delay_seconds||0,config_json:JSON.stringify({spec_name:l.spec_name||"",spec_value:l.spec_value||"",delay_override:l.delay_override===!0})})),...a]:e.actions&&e.actions.length>0?e.actions:[{action_type:"send_card",card_id:e.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],o=We(t,i),c={cookie_id:e.cookie_id||"",item_id:e.item_id||"",name:(e.name||"").trim()||r||"自动化规则",trigger_type:t,enabled:e.enabled??!0,priority:e.priority||100,config_json:e.config_json||"{}",actions:o.map((l,d)=>({action_type:l.action_type,card_id:l.card_id||0,delivery_count:l.delivery_count||1,message_template:l.message_template||"",delay_seconds:l.delay_seconds||0,config_json:l.config_json||"{}",enabled:l.enabled!==!1,sort_order:l.sort_order||d+1}))};return e.id?b(`/api/v1/automation-rules/${e.id}`,c):y("/api/v1/automation-rules",c)},As=async e=>j(`/api/v1/automation-rules/${e}`),Es=async()=>{const e=await g("/api/v1/automation-issues");return{runs:Array.isArray(e==null?void 0:e.runs)?e.runs:[],pending_tasks:Array.isArray(e==null?void 0:e.pending_tasks)?e.pending_tasks:[]}},$s=async(e,t)=>y(`/api/v1/automation-runs/${e}/resolve`,{resolution:t}),Ds=async(e,t)=>y(`/api/v1/automation-pending-tasks/${e}/resolve`,{resolution:t}),Xe=e=>({id:String((e==null?void 0:e.id)||""),keyword:(e==null?void 0:e.keyword)||"",reply:(e==null?void 0:e.reply)||"",item_id:(e==null?void 0:e.item_id)||"",type:(e==null?void 0:e.type)==="image"?"image":"text",image_url:(e==null?void 0:e.image_url)||""}),et=async e=>{const t=await g(`/api/v1/reply-rules/${e}/typed`);return Array.isArray(t)?t.map(Xe):[]},Is=async e=>e?(await et(e)).map(s=>({id:s.id,keyword:s.keyword||"",reply_content:s.reply||"",match_type:"fuzzy",enabled:!0,item_id:s.item_id||"",type:s.type==="image"?"image":"text",image_url:s.image_url||""})):[],Os=async(e,t)=>{const s=e.type||"text",r={keyword:e.keyword||"",reply:s==="text"&&e.reply_content||"",item_id:e.item_id||"",type:s,image_url:s==="image"&&e.image_url||""};return e.id?b(`/api/v1/reply-rules/${t}/typed/${e.id}`,r):y(`/api/v1/reply-rules/${t}/items`,r)},Ts=async(e,t)=>j(`/api/v1/reply-rules/${t}/typed/${e}`),tt=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),st=e=>{if("values"in e||"secrets"in e)return e;const t={},s={};for(const r of Object.entries(e)){const[a,i]=r;i!=null&&(tt.has(a)?s[a]=i===""?{action:"clear"}:{action:"replace",value:String(i)}:t[a]=i)}return Object.keys(s).length>0?{values:t,secrets:s}:t},Ps=async e=>{const t=await g("/api/v1/settings/system",void 0,e);return Je(t.data||t)},Rs=async(e,t)=>{const s=st(e);return b("/api/v1/settings/system",s,t)},zs=async(e,t)=>g(`/api/v1/settings/ai-reply/${e}`,void 0,t),qs=async(e,t,s)=>{const r={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return b(`/api/v1/settings/ai-reply/${e}`,r,s)},Ms=async(e,t="",s)=>(await y("/api/v1/settings/ai-models",{base_url:e,api_key:t},s)).models||[],at=e=>{if(Array.isArray(e))return e.filter(Boolean);if(typeof e!="string"||!e.trim())return[];try{const t=JSON.parse(e);if(Array.isArray(t))return t.filter(Boolean)}catch{}return e.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ce=e=>{const t=Array.from(new Set((e||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Bs=async e=>({success:!0,data:(await g("/api/v1/notifications/channels",void 0,e)||[]).map(r=>{let a;try{a=typeof r.config=="string"?JSON.parse(r.config):r.config}catch{a={}}return{id:String(r.id),name:r.name,type:r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type,config:a,event_types:at(r.event_types),enabled:r.enabled,created_at:r.created_at,updated_at:r.updated_at}})}),Fs=async(e,t)=>y("/api/v1/notifications/channels",{...e,config:JSON.stringify(e.config),event_types:ce(e.event_types)},t),Vs=async(e,t,s)=>{const r={...t};return"config"in t&&(r.config=JSON.stringify(t.config)),"event_types"in t&&(r.event_types=ce(t.event_types)),b(`/api/v1/notifications/channels/${e}`,r,s)},Js=async(e,t)=>j(`/api/v1/notifications/channels/${e}`,void 0,t),Us=async(e,t)=>{const s=await g(`/api/v1/notifications/accounts/${e}/bindings`,void 0,t);return(s==null?void 0:s.channel_ids)||[]},Ks=async(e,t)=>y(`/api/v1/notifications/channels/${e}/test`,{},t),Ys=async()=>g("/api/v1/default-replies"),Zs=async e=>{const t=await g(`/api/v1/default-replies/${e}`);return{cookie_id:e,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Hs=async(e,t)=>b(`/api/v1/default-replies/${e}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Gs=async e=>j(`/api/v1/default-replies/${e}`),Qs=async e=>y(`/api/v1/default-replies/${e}/clear-records`,{}),nt=({activeTab:e,isAdmin:t=!1,collapsed:s,onToggleCollapsed:r,onNavigate:a,onLogout:i})=>{const[o,c]=p.useState({version:"dev",commit:"unknown"});p.useEffect(()=>{const u=new AbortController;return Ze({signal:u.signal}).then(m=>c({version:String(m.version||"dev"),commit:String(m.commit||"unknown")})).catch(m=>{m instanceof DOMException&&m.name}),(()=>u.abort())},[]);const l=[{id:"dashboard",icon:we,label:"仪表盘"},{id:"accounts",icon:je,label:"账号管理"},{id:"chat",icon:Le,label:"在线聊天"},{id:"cards",icon:Ne,label:"卡密库存"},{id:"items",icon:Se,label:"商品列表"},{id:"orders",icon:ke,label:"订单管理"},{id:"rules",icon:Ce,label:"自动化规则"},{id:"notifications",icon:Ae,label:"通知设置"},...t?[{id:"settings",icon:Ee,label:"系统与AI"}]:[]],d=/^\d+\.\d+\.\d+$/.test(o.version)?`v${o.version}`:o.version;return n.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${s?"w-16":"w-64"}`,children:[n.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[n.jsx(R,{sizeClass:"h-10 w-10"}),!s&&n.jsxs("div",{className:"min-w-0 leading-tight",children:[n.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),n.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),n.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:l.map(u=>{const m=u.icon,h=e===u.id;return n.jsx(ee.Fragment,{children:n.jsxs("button",{type:"button",title:s?u.label:void 0,"aria-label":u.label,"aria-current":h?"page":void 0,onClick:(()=>a(u.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${h?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[n.jsx(m,{className:`h-[19px] w-[19px] shrink-0 ${h?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!s&&n.jsx("span",{className:"truncate text-sm font-bold",children:u.label}),h&&!s&&n.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},u.id)})}),n.jsxs("div",{children:[n.jsx("div",{title:s?`版本 ${o.version} · ${o.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${s?"flex justify-center px-1":"px-6"}`,children:s?n.jsx(Z,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${o.version}`}):n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[n.jsx(Z,{className:"h-3.5 w-3.5"}),"运行版本"]}),n.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[n.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:d}),n.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:o.commit})]})]})}),n.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[n.jsxs("button",{type:"button",onClick:r,title:s?"展开侧边栏":"收起侧边栏","aria-label":s?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${s?"justify-center":"gap-3 px-3"}`,children:[s?n.jsx($e,{className:"h-5 w-5"}):n.jsx(De,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),n.jsxs("button",{type:"button",onClick:i,title:s?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${s?"justify-center":"gap-3 px-3"}`,children:[n.jsx(Ie,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},P=p.lazy(()=>L(()=>import("./Dashboard-sUNU2Eg5.js"),__vite__mapDeps([0,1,2,3,4,5]))),rt=p.lazy(()=>L(()=>import("./AccountList-Bpj-f-W3.js"),__vite__mapDeps([6,1,3]))),it=p.lazy(()=>L(()=>import("./OrderList-Bb5NffV_.js"),__vite__mapDeps([7,1,3,2]))),ot=p.lazy(()=>L(()=>import("./CardList-D5uSws-z.js"),__vite__mapDeps([8,1,3]))),ct=p.lazy(()=>L(()=>import("./ItemList-kyCurZV6.js"),__vite__mapDeps([9,1,3]))),lt=p.lazy(()=>L(()=>import("./Settings-5xhSVKHU.js"),__vite__mapDeps([10,1,3]))),dt=p.lazy(()=>L(()=>import("./Rules-MPWRzM5C.js"),__vite__mapDeps([11,1,3]))),ut=p.lazy(()=>L(()=>import("./Notifications-CyWpiVXa.js"),__vite__mapDeps([12,1,3]))),pt=p.lazy(()=>L(()=>import("./Chat-BLyP9Pyt.js"),__vite__mapDeps([13,1,3]))),gt=()=>n.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:n.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),yt=({activeTab:e,isAdmin:t,deliveryRuleTarget:s,onConfigureDelivery:r,onDeliveryTargetHandled:a})=>{const i=c=>{r({cookieId:c.cookie_id,itemId:c.item_id,requestId:Date.now()})},o=()=>{switch(e){case"dashboard":return n.jsx(P,{});case"accounts":return n.jsx(rt,{});case"chat":return n.jsx(pt,{});case"orders":return n.jsx(it,{});case"cards":return n.jsx(ot,{});case"items":return n.jsx(ct,{onConfigureDelivery:i});case"rules":return n.jsx(dt,{initialDeliveryTarget:s,onDeliveryTargetHandled:a});case"notifications":return n.jsx(ut,{isAdmin:t});case"settings":return t?n.jsx(lt,{}):n.jsx(P,{});default:return n.jsx(P,{})}};return n.jsx(p.Suspense,{fallback:n.jsx(gt,{}),children:o()})},mt=({activeTab:e,isAdmin:t,collapsed:s,deliveryRuleTarget:r,onToggleCollapsed:a,onNavigate:i,onLogout:o,onConfigureDelivery:c,onDeliveryTargetHandled:l})=>n.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[n.jsx(nt,{activeTab:e,isAdmin:t,collapsed:s,onToggleCollapsed:a,onNavigate:i,onLogout:o}),n.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${s?"ml-16":"ml-64"} ${e==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[n.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),n.jsx("div",{className:`${e==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:n.jsx(yt,{activeTab:e,isAdmin:t,deliveryRuleTarget:r,onConfigureDelivery:c,onDeliveryTargetHandled:l})})]})]}),le=p.createContext(void 0),ft=({children:e})=>{const[t,s]=p.useState(!1),[r,a]=p.useState(!1),[i,o]=p.useState(!0),[c,l]=p.useState(!1),d=()=>{s(!1),a(!1)};p.useEffect(()=>{const x=new AbortController;let v=!0;Ye({signal:x.signal}).then(w=>{if(v){if((w==null?void 0:w.initialized)===!1){l(!0),d();return}l(!1),w!=null&&w.authenticated?(s(!0),a(w.is_admin===!0)):d()}}).catch(w=>{!v||w instanceof DOMException&&w.name==="AbortError"||(l(!1),d())}).finally(()=>{v&&o(!1)});const k=()=>d();return window.addEventListener("auth:logout",k),(()=>{v=!1,x.abort(),window.removeEventListener("auth:logout",k)})},[]);const u=async x=>{const v=await Ue(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},m=async x=>{const v=await Ke(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},h=async()=>{try{await He()}finally{d()}};return n.jsx(le.Provider,{value:{checkingAuth:i,isLoggedIn:t,isAdmin:r,needsInit:c,signIn:u,initialize:m,signOut:h},children:e})},ht=()=>{const e=p.useContext(le);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},de={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},W=Object.fromEntries(Object.entries(de).map(([e,t])=>[t,e])),X=()=>de[window.location.pathname]||"dashboard",_t=()=>{const{checkingAuth:e,isLoggedIn:t,isAdmin:s,needsInit:r,signIn:a,initialize:i,signOut:o}=ht(),[c,l]=p.useState(X),[d,u]=p.useState(""),[m,h]=p.useState(""),[x,v]=p.useState(!1),[k,w]=p.useState(""),[A,M]=p.useState(""),[B,F]=p.useState(""),[V,J]=p.useState(!1),[U,C]=p.useState(""),[pe,K]=p.useState(),[ge,ye]=p.useState(Te),Y=f=>{const _=f==="settings"&&!s?"dashboard":f,N=W[_];N&&N!==window.location.pathname&&window.history.pushState({},"",N),l(_)};p.useEffect(()=>{const f=()=>l(X());return window.addEventListener("popstate",f),()=>window.removeEventListener("popstate",f)},[]),p.useEffect(()=>{!e&&t&&!s&&c==="settings"&&(window.history.replaceState({},"",W.dashboard),l("dashboard"))},[e,t,s,c]);const me=async f=>{f.preventDefault(),v(!0),w("");try{const _=await a({username:d,password:m});_.success||w(_.message||"登录失败")}catch(_){const N=_ instanceof Error?_.message:String(_);w(N||"登录失败")}finally{v(!1)}},fe=async f=>{if(f.preventDefault(),C(""),A.length<8){C("密码至少需要 8 个字符");return}if(A!==B){C("两次输入的密码不一致");return}J(!0);try{const _=await i(A);if(!_.success){C(_.message||"初始化失败,请重试");return}M(""),F("")}catch(_){const N=_ instanceof Error?_.message:String(_);C(N||"初始化失败,请重试")}finally{J(!1)}},he=async()=>{try{await o()}catch(f){console.error("退出登录失败",f)}};if(e)return n.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:n.jsx(D,{className:"w-8 h-8 text-brand animate-spin"})});if(r)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),n.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"首次设置管理员密码"}),n.jsx("p",{className:"text-gray-600 font-medium",children:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),n.jsxs("form",{onSubmit:fe,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(H,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"password",placeholder:"设置管理员密码(至少 8 个字符)",value:A,onChange:f=>M(f.target.value),autoFocus:!0,className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(I,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"password",placeholder:"再次输入密码",value:B,onChange:f=>F(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),U&&n.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[n.jsx(I,{className:"w-4 h-4"})," ",U]}),n.jsx("button",{type:"submit",disabled:V,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:V?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["设置密码并进入系统 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!t)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),n.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[n.jsxs("div",{className:"text-center mb-10",children:[n.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),n.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),n.jsxs("form",{onSubmit:me,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(Oe,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"text",placeholder:"管理员账号",value:d,onChange:f=>u(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(H,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"password",placeholder:"密码",value:m,onChange:f=>h(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),k&&n.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[n.jsx(I,{className:"w-4 h-4"})," ",k]}),n.jsx("button",{type:"submit",disabled:x,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:x?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["立即登录 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:n.jsx("div",{className:"mt-6 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const _e=f=>{K(f),Y("rules")},ve=()=>K(void 0),be=()=>ye(f=>{const _=!f;return Pe(_),_});return n.jsx(mt,{activeTab:c,isAdmin:s,collapsed:ge,deliveryRuleTarget:pe,onToggleCollapsed:be,onNavigate:Y,onLogout:he,onConfigureDelivery:_e,onDeliveryTargetHandled:ve})},vt=()=>n.jsx(ft,{children:n.jsx(_t,{})}),ue=document.getElementById("root");if(!ue)throw new Error("Could not find root element to mount to");const bt=xe.createRoot(ue);bt.render(n.jsx(ee.StrictMode,{children:n.jsx(vt,{})}));export{ms as $,qt as A,Zt as B,Mt as C,Gt as D,ss as E,Xt as F,ts as G,Qt as H,es as I,Wt as J,is as K,ds as L,us as M,cs as N,ls as O,os as P,xs as Q,bs as R,hs as S,_s as T,vs as U,js as V,ws as W,Ls as X,gs as Y,Ns as Z,ys as _,ps as a,fs as a0,Ss as a1,Ms as a2,Ps as a3,Ye as a4,Rs as a5,Nt as a6,Ys as a7,Es as a8,ks as a9,Is as aa,Cs as ab,As as ac,$s as ad,Ds as ae,Os as af,Ts as ag,Zs as ah,Hs as ai,Gs as aj,Qs as ak,Vs as al,Fs as am,Js as an,Ks as ao,Et as ap,$t as aq,Ot as ar,Dt as as,It as at,jt as b,Lt as c,ns as d,rs as e,kt as f,as as g,St as h,Ht as i,Tt as j,Pt as k,Rt as l,zt as m,Bs as n,Us as o,Vt as p,zs as q,At as r,Jt as s,qs as t,Ct as u,Ft as v,Bt as w,Kt as x,Ut as y,Yt as z}; diff --git a/internal/webui/static/assets/index-DK02p8DH.js b/internal/webui/static/assets/index-DK02p8DH.js deleted file mode 100644 index c45af36..0000000 --- a/internal/webui/static/assets/index-DK02p8DH.js +++ /dev/null @@ -1,2 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-BjrV0BPa.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-ThcsWkZG.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-CMeDGrpw.js","assets/OrderList-DCxOUz7n.js","assets/CardList-CV-IXa79.js","assets/ItemList-DX-qMjnd.js","assets/Settings-j3SwRFCx.js","assets/Rules-D884-CgU.js","assets/Notifications-D65tIfCl.js","assets/Chat-ChmGl-XK.js"])))=>i.map(i=>d[i]); -import{j as n,r as p,c as ee,d as xe}from"./react-vendor-C_od1ZSF.js";import{L as we,U as je,M as Le,C as Ne,B as Se,S as ke,Z as Ce,a as Ae,b as Ee,G as Z,c as $e,d as De,e as Ie,f as D,g as H,h as I,A as G,i as Oe}from"./icons-vendor-ThcsWkZG.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();const te="ydisks.sidebar.v1",Te=()=>{try{return window.localStorage.getItem(te)==="collapsed"}catch{return!1}},Pe=e=>{try{window.localStorage.setItem(te,e?"collapsed":"expanded")}catch{}},Re=({className:e="w-full h-full text-white"})=>n.jsx("svg",{className:e,viewBox:"0 0 256 256","aria-hidden":"true",children:n.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:n.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),R=({sizeClass:e="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>n.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[n.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),n.jsxs("div",{className:`relative ${e} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[n.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[n.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),n.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),n.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),n.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:n.jsx(Re,{className:t})})]})]}),ze="modulepreload",qe=function(e){return"/static/"+e},Q={},L=function(t,s,r){let a=Promise.resolve();if(s&&s.length>0){let o=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=o(s.map(d=>{if(d=qe(d),d in Q)return;Q[d]=!0;const u=d.endsWith(".css"),m=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const h=document.createElement("link");if(h.rel=u?"stylesheet":ze,u||(h.as="script"),h.crossOrigin="",h.href=d,l&&h.setAttribute("nonce",l),document.head.appendChild(h),u)return new Promise((x,v)=>{h.addEventListener("load",x),h.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return a.then(o=>{for(const c of o||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})},Me=3e4,Be=10*6e4;let O=!1;const se=()=>{O||typeof window>"u"||(O=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{O=!1}))},Fe=e=>{if(!e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))a!=null&&t.set(r,String(a));const s=t.toString();return s?`?${s}`:""},$=async(e,t,s={})=>{var d;const r=Fe(s.params),a=`${t}${r}`,i=ae(s.signal,s.timeoutMs??Me);let o;try{o=await fetch(a,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(u){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):u}finally{i.cleanup()}const l=(o.headers.get("content-type")||"").includes("application/json");if(!o.ok){o.status===401&&!s.skipAuthLogout&&se();const u=l?await o.json().catch(()=>{}):await o.text().catch(()=>{}),m=ne(u,o.status);throw new Error(m)}return l?await o.json():await o.text()},g=async(e,t,s)=>$("GET",e,{params:t,...s}),y=async(e,t,s)=>$("POST",e,{body:t,...s}),b=async(e,t,s)=>$("PUT",e,{body:t,...s}),j=async(e,t,s)=>$("DELETE",e,{params:t,...s}),S=async(e,t,s={})=>{var l;const r=ae(s.signal,s.timeoutMs??Be);let a;try{a=await fetch(e,{method:"POST",credentials:"include",signal:r.signal,body:t})}catch(d){throw r.signal.aborted?new Error((l=s.signal)!=null&&l.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{r.cleanup()}const c=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>{}):await a.text().catch(()=>{});if(!a.ok){a.status===401&&se();const d=ne(c,a.status),u=new Error(d);throw u.payload=c,u}return c},ae=(e,t)=>{const s=new AbortController,r=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?r():e==null||e.addEventListener("abort",r,{once:!0});const a=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(a),e==null||e.removeEventListener("abort",r)}}},Ve=e=>{if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.code=="string"&&typeof t.message=="string"},ne=(e,t)=>typeof e=="string"?e:Ve(e)?e.message:`请求失败: ${t}`,E=e=>{const t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${s}-${r}`},q=(e,t)=>{const s=new Date(e);return s.setHours(12,0,0,0),s.setDate(s.getDate()+t),s},z=(e,t)=>({startDate:E(q(e,-(t-1))),endDate:E(e)}),jt=(e,t=new Date,s="",r="")=>{if(e==="custom"&&s&&r){if(s>r)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:r}}return e==="yesterday"?z(q(t,-1),1):z(t,e==="3days"?3:e==="30days"?30:e==="today"?1:7)},Lt=e=>{const t=new Date(`${e.startDate}T12:00:00`),s=new Date(`${e.endDate}T12:00:00`),r=Math.round((s.getTime()-t.getTime())/864e5)+1,a=q(t,-1);return z(a,r)},Je=e=>{const t={...e},s=["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"];for(const r of s){const a=`${r}_configured`;a in t&&(t[a]=t[a]===!0||t[a]==="true")}if("renewal_log_retention_days"in t){const r=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(r)?r:10}return t},Ue=async e=>y("/api/v1/session/login",e,{skipAuthLogout:!0}),Ke=async e=>y("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ye=async e=>g("/api/v1/session",void 0,e),Ze=async e=>g("/health",void 0,e),He=async()=>y("/api/v1/session/logout",{}),Nt=async(e,t)=>b("/api/v1/session/credentials",e,t),Ge=(e,t)=>{const s=e.avatar_url||"";if(!s)return"";try{const r=new URL(s,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",t),r.toString()}catch{return s}},St=async e=>{const t=await g("/api/v1/accounts/details",void 0,e),s=Date.now().toString();return t.map(r=>({id:r.id,value:"",enabled:r.enabled,auto_confirm:r.auto_confirm,remark:r.remark,pause_duration:r.pause_duration,paused_until:Number(r.paused_until||0),paused:r.paused===!0,username:r.username||"",login_password:"",show_browser:r.show_browser===!0||r.show_browser===1||r.show_browser==="1"||r.show_browser==="true",nickname:r.nickname||r.remark||`账号 ${r.id.substring(0,6)}`,avatar_url:Ge(r,s),profile_error:r.profile_error||"",ai_enabled:!1,auto_rate_enabled:r.auto_rate_enabled,rate_content:r.rate_content||"不错的买家,交易愉快",auto_polish_enabled:r.auto_polish_enabled,polish_time:r.polish_time||"03:00",last_rate_scan_at:Number(r.last_rate_scan_at||0),last_polish_date:r.last_polish_date||"",last_polish_at:Number(r.last_polish_at||0)}))},kt=async(e,t)=>g(`/api/v1/account-tasks/${e}`,void 0,t),Ct=async(e,t,s)=>b(`/api/v1/account-tasks/${e}`,t,s),At=async(e,t,s)=>y(`/api/v1/account-tasks/${e}/run`,{task_type:t},{timeoutMs:12e4,...s}),Et=async(e,t,s,r=!1)=>{const a=await g("/api/v1/chat/sessions",{account_id:e,cursor:t,refresh:r?1:void 0},r?{timeoutMs:6e4,...s}:s);return{sessions:a.sessions||[],has_more:a.has_more===!0,next_cursor:a.next_cursor}},$t=async(e,t,s,r,a)=>{const i=await g("/api/v1/chat/messages",{account_id:e,chat_id:t,cursor:s,before_id:r},a);return{messages:i.messages||[],has_more:i.has_more===!0,next_cursor:i.next_cursor,session:i.session}},Dt=async(e,t)=>y("/api/v1/chat/messages",e,t),It=async(e,t)=>{const s=new FormData;return Object.entries(e).forEach(([r,a])=>s.append(r,a)),S("/api/v1/chat/images",s,{timeoutMs:12e4,...t})},Ot=async(e,t,s)=>y("/api/v1/chat/read",{account_id:e,chat_id:t},s),Tt=async e=>g("/api/v1/accounts/runtime-status",void 0,e),Pt=async e=>y("/api/v1/qr-login/generate",void 0,{...e,timeoutMs:(e==null?void 0:e.timeoutMs)??13e4}),Rt=async(e,t)=>g(`/api/v1/qr-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),zt=async(e,t)=>y(`/api/v1/qr-login/complete-verification/${e}`,{target_account_id:t||""}),qt=async(e,t)=>b(`/api/v1/accounts/${e}/status`,{enabled:t}),Mt=async e=>j(`/api/v1/accounts/${e}`),Bt=async(e,t,s)=>b(`/api/v1/accounts/${e}/pause-duration`,{pause_duration:t},s),Ft=async(e,t,s)=>b(`/api/v1/accounts/${e}/settings`,t,s),Vt=async(e,t)=>g(`/api/v1/accounts/${e}/long-login`,void 0,t),Jt=async(e,t,s)=>b(`/api/v1/accounts/${e}/long-login`,{enabled:t},s),Ut=async(e,t)=>y("/api/v1/password-login",e,t),Kt=async(e,t)=>g(`/api/v1/password-login/check/${e}`,void 0,{signal:t,timeoutMs:1e4}),Yt=async(e,t)=>j(`/api/v1/password-login/cancel/${e}`,void 0,t),Zt=async e=>y(`/api/v1/accounts/${e}/refresh-profile`,{}),Ht=async e=>g("/api/v1/settings/ai-reply",void 0,e),re=e=>{const t=String(e||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Gt=async(e,t,s=1,r=20,a,i)=>{const o={page:s,page_size:r};e&&(o.cookie_id=e),t&&t!=="all"&&(o.status=t),a!=null&&a.trim()&&(o.search=a.trim());const c=await g("/api/v1/orders",o,i),d=(c.orders||c.data||[]).map(u=>({...u,id:u.id||u.order_id,status:re(u.status||u.order_status),quantity:Number(u.quantity||1)}));return{success:!0,data:d,total:c.total||d.length,page:c.page||s,page_size:c.page_size||r,total_pages:c.total_pages||1}},Qt=async(e,t)=>b(`/api/v1/orders/${e}`,t),Wt=async e=>j(`/api/v1/orders/${e}`),Xt=async(e,t,s)=>{const r=new FormData;e&&r.append("cookie_id",e),t&&r.append("status",t);const a=await S("/api/v1/orders/refresh",r,s),i=180;let o=0;try{for(;o{const m=()=>{globalThis.clearTimeout(h),u(new Error("请求已取消"))},h=globalThis.setTimeout(()=>{var x;(x=s==null?void 0:s.signal)==null||x.removeEventListener("abort",m),d()},l);s!=null&&s.signal&&(s.signal.aborted?m():s.signal.addEventListener("abort",m,{once:!0}))}),o+=1}}finally{}throw new Error("订单刷新任务等待超时")},es=async e=>y(`/api/v1/orders/${e}/refresh`),ts=async(e,t)=>y("/api/v1/orders/manual-ship",{order_ids:e,ship_mode:t}),ss=async(e,t)=>e instanceof FormData?S("/api/v1/orders/import",e,t):y("/api/v1/orders/import",e,t),as=async e=>g("/api/v1/analytics/dashboard",void 0,e),ns=async(e=7,t)=>{let s;if(typeof e=="number"){const r=new Date,a=new Date;a.setDate(a.getDate()-e),s={start_date:E(a),end_date:E(r)}}else s=e;return g("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},t)},rs=async(e,t)=>{const s=await g("/api/v1/analytics/orders/valid",{start_date:e.start_date,end_date:e.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()},t),a=(Array.isArray(s)?s:s.orders||[]).map(i=>({...i,id:i.id||i.order_id,status:re(i.status||i.order_status),quantity:Number(i.quantity||1)}));return{orders:a,total:Array.isArray(s)?a.length:Number(s.total??a.length),truncated:Array.isArray(s)?!1:s.truncated===!0}},Qe=e=>{let t=e.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...e,api_config:t||void 0}},ie=e=>({...e,api_config:e.api_config?JSON.stringify(e.api_config):""}),is=async e=>{const t=await g("/api/v1/cards",void 0,e);return(Array.isArray(t)?t:t.cards||[]).map(Qe)},os=async e=>y("/api/v1/cards",ie(e)),cs=async(e,t)=>b(`/api/v1/cards/${e}`,ie(t)),ls=async e=>j(`/api/v1/cards/${e}`),ds=async(e,t)=>{const s=new FormData;return s.append("file",e),S("/api/v1/cards/batch",s,t)},us=async(e,t,s)=>y(`/api/v1/cards/${e}/append-data`,{content:t},s),T=e=>e===!0||e===1||e==="1",ps=async(e,t)=>{const s=await g("/api/v1/items",void 0,t);return(Array.isArray(s)?s:s.items||[]).map(a=>({...a,id:a.id||`${a.cookie_id}-${a.item_id}`,is_multi_spec:T(a.is_multi_spec),is_multi_qty_ship:T(a.is_multi_qty_ship??a.multi_quantity_delivery),multi_quantity_delivery:T(a.multi_quantity_delivery??a.is_multi_qty_ship)}))},gs=async e=>y("/api/v1/items/get-all-from-account",{cookie_id:e}),ys=async(e,t)=>j(`/api/v1/items/${e}/${t}`),ms=async(e,t)=>y(`/api/v1/items/${e}`,t),fs=async e=>{const t=new FormData;t.set("cookie_id",e.cookie_id),t.set("title",e.title),t.set("description",e.description),t.set("price",e.price),t.set("original_price",e.original_price||""),t.set("quantity",String(e.quantity)),t.set("postage_mode",e.postage_mode),t.set("postage",e.postage||""),e.location&&t.set("location",JSON.stringify(e.location));for(const s of e.images)t.append("images",s);return S("/api/v1/items/publish",t)},hs=async(e,t)=>y("/api/v1/items/publish-categories/recommend",{cookie_id:e,keyword:t}),_s=async e=>{const t=new FormData;return t.set("file",e.file),e.imagesZip&&t.set("images_zip",e.imagesZip),e.defaultCookieId&&t.set("default_cookie_id",e.defaultCookieId),t.set("fallback_category_id",e.fallbackCategory.catId),t.set("fallback_category_name",e.fallbackCategory.catName),t.set("fallback_channel_category_id",e.fallbackCategory.channelCatId||""),t.set("fallback_tb_category_id",e.fallbackCategory.tbCatId||""),e.location&&t.set("location",JSON.stringify(e.location)),S("/api/v1/items/publish-batches/preview",t)},vs=async e=>y("/api/v1/items/publish-batches",{preview_id:e}),bs=async e=>g(`/api/v1/items/publish-batches/${e}`),xs=async(e=20)=>{const t=await g("/api/v1/items/publish-batches",{limit:e});return Array.isArray(t)?t:t.batches||[]},ws=async e=>j(`/api/v1/items/publish-batches/${e}`),js=async e=>y(`/api/v1/items/publish-batches/${e}/cancel`,{}),Ls=async e=>y(`/api/v1/items/publish-batches/${e}/retry-failed`,{}),Ns=async(e,t,s)=>b(`/api/v1/items/${e}/${t}`,s),oe=e=>e.map(t=>{var s,r;return{id:String(t.id),name:t.name||"",trigger_type:t.trigger_type||"order_paid",item_keyword:t.item_title||t.item_id||"",cookie_id:t.cookie_id||"",item_id:t.item_id||"",item_title:t.item_title||"",card_group_id:Number(((s=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:s.card_id)||0),card_group_name:((r=(t.actions||[]).find(a=>a.action_type==="send_card"))==null?void 0:r.card_name)||"",priority:t.priority||100,enabled:t.enabled||!1,config_json:t.config_json||"{}",actions:(t.actions||[]).map(a=>({id:a.id?String(a.id):void 0,action_type:a.action_type,card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),message_template:a.message_template||"",delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}",enabled:a.enabled!==!1,sort_order:Number(a.sort_order||0)})),variants:(t.actions||[]).filter(a=>a.action_type==="send_card").map(a=>{let i={};try{i=JSON.parse(a.config_json||"{}")}catch{}return{id:a.id?String(a.id):void 0,spec_name:i.spec_name||"",spec_value:i.spec_value||"",card_id:Number(a.card_id||0),card_name:a.card_name||"",delivery_count:Number(a.delivery_count||1),enabled:a.enabled!==!1,delay_override:i.delay_override===!0,delay_seconds:Number(a.delay_seconds||0),config_json:a.config_json||"{}"}})}}),Ss=async()=>{const e=await g("/api/v1/automation-rules"),t=Array.isArray(e)?e:e.data||[];return oe(t)},ks=async({cookieId:e,triggerType:t,enabled:s,search:r,page:a=1,pageSize:i=10}={})=>{const o=await g("/api/v1/automation-rules",{page:a,page_size:i,cookie_id:e||void 0,trigger_type:t||void 0,enabled:s,search:(r==null?void 0:r.trim())||void 0}),c=oe(Array.isArray(o)?o:o.data||[]);return{success:!0,data:c,total:Number(Array.isArray(o)?c.length:o.total??c.length),page:Number(Array.isArray(o)?a:o.page??a),page_size:Number(Array.isArray(o)?i:o.page_size??i),total_pages:Number(Array.isArray(o)?c.length?1:0:o.total_pages??(c.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(Array.isArray(o)?{}:o.trigger_counts||{}).map(([l,d])=>[l,Number(d)]))}},We=(e,t)=>{if(e!=="order_paid")return t.map((a,i)=>({...a,sort_order:a.sort_order||i+1}));const s=t.filter(a=>a.action_type==="send_card").map((a,i)=>({...a,sort_order:i+1})),r=t.filter(a=>a.action_type!=="send_card"&&a.action_type!=="confirm_shipment");return[...s,...r.map((a,i)=>({...a,sort_order:s.length+i+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:s.length+r.length+1}]},Cs=async e=>{const t=e.trigger_type||"order_paid",r=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",e.item_title||e.item_id||e.cookie_id||""].filter(Boolean).join(" - "),a=(e.actions||[]).filter(l=>l.action_type!=="send_card"&&l.action_type!=="confirm_shipment"),i=e.variants&&e.variants.length>0?[...e.variants.map((l,d)=>({action_type:"send_card",card_id:l.card_id,delivery_count:l.delivery_count||1,enabled:l.enabled!==!1,sort_order:d+1,delay_seconds:l.delay_seconds||0,config_json:JSON.stringify({spec_name:l.spec_name||"",spec_value:l.spec_value||"",delay_override:l.delay_override===!0})})),...a]:e.actions&&e.actions.length>0?e.actions:[{action_type:"send_card",card_id:e.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],o=We(t,i),c={cookie_id:e.cookie_id||"",item_id:e.item_id||"",name:(e.name||"").trim()||r||"自动化规则",trigger_type:t,enabled:e.enabled??!0,priority:e.priority||100,config_json:e.config_json||"{}",actions:o.map((l,d)=>({action_type:l.action_type,card_id:l.card_id||0,delivery_count:l.delivery_count||1,message_template:l.message_template||"",delay_seconds:l.delay_seconds||0,config_json:l.config_json||"{}",enabled:l.enabled!==!1,sort_order:l.sort_order||d+1}))};return e.id?b(`/api/v1/automation-rules/${e.id}`,c):y("/api/v1/automation-rules",c)},As=async e=>j(`/api/v1/automation-rules/${e}`),Es=async()=>{const e=await g("/api/v1/automation-issues");return{runs:Array.isArray(e==null?void 0:e.runs)?e.runs:[],pending_tasks:Array.isArray(e==null?void 0:e.pending_tasks)?e.pending_tasks:[]}},$s=async(e,t)=>y(`/api/v1/automation-runs/${e}/resolve`,{resolution:t}),Ds=async(e,t)=>y(`/api/v1/automation-pending-tasks/${e}/resolve`,{resolution:t}),Xe=e=>({id:String((e==null?void 0:e.id)||""),keyword:(e==null?void 0:e.keyword)||"",reply:(e==null?void 0:e.reply)||"",item_id:(e==null?void 0:e.item_id)||"",type:(e==null?void 0:e.type)==="image"?"image":"text",image_url:(e==null?void 0:e.image_url)||""}),et=async e=>{const t=await g(`/api/v1/reply-rules/${e}/typed`);return Array.isArray(t)?t.map(Xe):[]},Is=async e=>e?(await et(e)).map(s=>({id:s.id,keyword:s.keyword||"",reply_content:s.reply||"",match_type:"fuzzy",enabled:!0,item_id:s.item_id||"",type:s.type==="image"?"image":"text",image_url:s.image_url||""})):[],Os=async(e,t)=>{const s=e.type||"text",r={keyword:e.keyword||"",reply:s==="text"&&e.reply_content||"",item_id:e.item_id||"",type:s,image_url:s==="image"&&e.image_url||""};return e.id?b(`/api/v1/reply-rules/${t}/typed/${e.id}`,r):y(`/api/v1/reply-rules/${t}/items`,r)},Ts=async(e,t)=>j(`/api/v1/reply-rules/${t}/typed/${e}`),tt=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),st=e=>{if("values"in e||"secrets"in e)return e;const t={},s={};for(const r of Object.entries(e)){const[a,i]=r;i!=null&&(tt.has(a)?s[a]=i===""?{action:"clear"}:{action:"replace",value:String(i)}:t[a]=i)}return Object.keys(s).length>0?{values:t,secrets:s}:t},Ps=async e=>{const t=await g("/api/v1/settings/system",void 0,e);return Je(t.data||t)},Rs=async(e,t)=>{const s=st(e);return b("/api/v1/settings/system",s,t)},zs=async(e,t)=>g(`/api/v1/settings/ai-reply/${e}`,void 0,t),qs=async(e,t,s)=>{const r={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return b(`/api/v1/settings/ai-reply/${e}`,r,s)},Ms=async(e,t="",s)=>(await y("/api/v1/settings/ai-models",{base_url:e,api_key:t},s)).models||[],at=e=>{if(Array.isArray(e))return e.filter(Boolean);if(typeof e!="string"||!e.trim())return[];try{const t=JSON.parse(e);if(Array.isArray(t))return t.filter(Boolean)}catch{}return e.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ce=e=>{const t=Array.from(new Set((e||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Bs=async e=>({success:!0,data:(await g("/api/v1/notifications/channels",void 0,e)||[]).map(r=>{let a;try{a=typeof r.config=="string"?JSON.parse(r.config):r.config}catch{a={}}return{id:String(r.id),name:r.name,type:r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type,config:a,event_types:at(r.event_types),enabled:r.enabled,created_at:r.created_at,updated_at:r.updated_at}})}),Fs=async(e,t)=>y("/api/v1/notifications/channels",{...e,config:JSON.stringify(e.config),event_types:ce(e.event_types)},t),Vs=async(e,t,s)=>{const r={...t};return"config"in t&&(r.config=JSON.stringify(t.config)),"event_types"in t&&(r.event_types=ce(t.event_types)),b(`/api/v1/notifications/channels/${e}`,r,s)},Js=async(e,t)=>j(`/api/v1/notifications/channels/${e}`,void 0,t),Us=async(e,t)=>{const s=await g(`/api/v1/notifications/accounts/${e}/bindings`,void 0,t);return(s==null?void 0:s.channel_ids)||[]},Ks=async(e,t)=>y(`/api/v1/notifications/channels/${e}/test`,{},t),Ys=async()=>g("/api/v1/default-replies"),Zs=async e=>{const t=await g(`/api/v1/default-replies/${e}`);return{cookie_id:e,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Hs=async(e,t)=>b(`/api/v1/default-replies/${e}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Gs=async e=>j(`/api/v1/default-replies/${e}`),Qs=async e=>y(`/api/v1/default-replies/${e}/clear-records`,{}),nt=({activeTab:e,isAdmin:t=!1,collapsed:s,onToggleCollapsed:r,onNavigate:a,onLogout:i})=>{const[o,c]=p.useState({version:"dev",commit:"unknown"});p.useEffect(()=>{const u=new AbortController;return Ze({signal:u.signal}).then(m=>c({version:String(m.version||"dev"),commit:String(m.commit||"unknown")})).catch(m=>{m instanceof DOMException&&m.name}),(()=>u.abort())},[]);const l=[{id:"dashboard",icon:we,label:"仪表盘"},{id:"accounts",icon:je,label:"账号管理"},{id:"chat",icon:Le,label:"在线聊天"},{id:"cards",icon:Ne,label:"卡密库存"},{id:"items",icon:Se,label:"商品列表"},{id:"orders",icon:ke,label:"订单管理"},{id:"rules",icon:Ce,label:"自动化规则"},{id:"notifications",icon:Ae,label:"通知设置"},...t?[{id:"settings",icon:Ee,label:"系统与AI"}]:[]],d=/^\d+\.\d+\.\d+$/.test(o.version)?`v${o.version}`:o.version;return n.jsxs("aside",{className:`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${s?"w-16":"w-64"}`,children:[n.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[n.jsx(R,{sizeClass:"h-10 w-10"}),!s&&n.jsxs("div",{className:"min-w-0 leading-tight",children:[n.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),n.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),n.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:l.map(u=>{const m=u.icon,h=e===u.id;return n.jsx(ee.Fragment,{children:n.jsxs("button",{type:"button",title:s?u.label:void 0,"aria-label":u.label,"aria-current":h?"page":void 0,onClick:(()=>a(u.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${h?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[n.jsx(m,{className:`h-[19px] w-[19px] shrink-0 ${h?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!s&&n.jsx("span",{className:"truncate text-sm font-bold",children:u.label}),h&&!s&&n.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},u.id)})}),n.jsxs("div",{children:[n.jsx("div",{title:s?`版本 ${o.version} · ${o.commit}`:void 0,className:`border-y border-slate-100 bg-slate-50/70 py-2.5 ${s?"flex justify-center px-1":"px-6"}`,children:s?n.jsx(Z,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${o.version}`}):n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[n.jsx(Z,{className:"h-3.5 w-3.5"}),"运行版本"]}),n.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[n.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:d}),n.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:o.commit})]})]})}),n.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[n.jsxs("button",{type:"button",onClick:r,title:s?"展开侧边栏":"收起侧边栏","aria-label":s?"展开侧边栏":"收起侧边栏",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${s?"justify-center":"gap-3 px-3"}`,children:[s?n.jsx($e,{className:"h-5 w-5"}):n.jsx(De,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),n.jsxs("button",{type:"button",onClick:i,title:s?"退出登录":void 0,"aria-label":"退出登录",className:`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${s?"justify-center":"gap-3 px-3"}`,children:[n.jsx(Ie,{className:"h-5 w-5"}),!s&&n.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},P=p.lazy(()=>L(()=>import("./Dashboard-BjrV0BPa.js"),__vite__mapDeps([0,1,2,3,4,5]))),rt=p.lazy(()=>L(()=>import("./AccountList-CMeDGrpw.js"),__vite__mapDeps([6,1,3]))),it=p.lazy(()=>L(()=>import("./OrderList-DCxOUz7n.js"),__vite__mapDeps([7,1,3,2]))),ot=p.lazy(()=>L(()=>import("./CardList-CV-IXa79.js"),__vite__mapDeps([8,1,3]))),ct=p.lazy(()=>L(()=>import("./ItemList-DX-qMjnd.js"),__vite__mapDeps([9,1,3]))),lt=p.lazy(()=>L(()=>import("./Settings-j3SwRFCx.js"),__vite__mapDeps([10,1,3]))),dt=p.lazy(()=>L(()=>import("./Rules-D884-CgU.js"),__vite__mapDeps([11,1,3]))),ut=p.lazy(()=>L(()=>import("./Notifications-D65tIfCl.js"),__vite__mapDeps([12,1,3]))),pt=p.lazy(()=>L(()=>import("./Chat-ChmGl-XK.js"),__vite__mapDeps([13,1,3]))),gt=()=>n.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:n.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),yt=({activeTab:e,isAdmin:t,deliveryRuleTarget:s,onConfigureDelivery:r,onDeliveryTargetHandled:a})=>{const i=c=>{r({cookieId:c.cookie_id,itemId:c.item_id,requestId:Date.now()})},o=()=>{switch(e){case"dashboard":return n.jsx(P,{});case"accounts":return n.jsx(rt,{});case"chat":return n.jsx(pt,{});case"orders":return n.jsx(it,{});case"cards":return n.jsx(ot,{});case"items":return n.jsx(ct,{onConfigureDelivery:i});case"rules":return n.jsx(dt,{initialDeliveryTarget:s,onDeliveryTargetHandled:a});case"notifications":return n.jsx(ut,{isAdmin:t});case"settings":return t?n.jsx(lt,{}):n.jsx(P,{});default:return n.jsx(P,{})}};return n.jsx(p.Suspense,{fallback:n.jsx(gt,{}),children:o()})},mt=({activeTab:e,isAdmin:t,collapsed:s,deliveryRuleTarget:r,onToggleCollapsed:a,onNavigate:i,onLogout:o,onConfigureDelivery:c,onDeliveryTargetHandled:l})=>n.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[n.jsx(nt,{activeTab:e,isAdmin:t,collapsed:s,onToggleCollapsed:a,onNavigate:i,onLogout:o}),n.jsxs("main",{className:`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${s?"ml-16":"ml-64"} ${e==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[n.jsx("div",{className:"fixed top-0 right-0 -z-10 h-[800px] w-[800px] pointer-events-none rounded-full bg-gradient-to-bl from-blue-50 to-transparent opacity-60 blur-[120px]"}),n.jsx("div",{className:`${e==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:n.jsx(yt,{activeTab:e,isAdmin:t,deliveryRuleTarget:r,onConfigureDelivery:c,onDeliveryTargetHandled:l})})]})]}),le=p.createContext(void 0),ft=({children:e})=>{const[t,s]=p.useState(!1),[r,a]=p.useState(!1),[i,o]=p.useState(!0),[c,l]=p.useState(!1),d=()=>{s(!1),a(!1)};p.useEffect(()=>{const x=new AbortController;let v=!0;Ye({signal:x.signal}).then(w=>{if(v){if((w==null?void 0:w.initialized)===!1){l(!0),d();return}l(!1),w!=null&&w.authenticated?(s(!0),a(w.is_admin===!0)):d()}}).catch(w=>{!v||w instanceof DOMException&&w.name==="AbortError"||(l(!1),d())}).finally(()=>{v&&o(!1)});const k=()=>d();return window.addEventListener("auth:logout",k),(()=>{v=!1,x.abort(),window.removeEventListener("auth:logout",k)})},[]);const u=async x=>{const v=await Ue(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},m=async x=>{const v=await Ke(x);return v.success&&(l(!1),s(!0),a(v.is_admin===!0)),v},h=async()=>{try{await He()}finally{d()}};return n.jsx(le.Provider,{value:{checkingAuth:i,isLoggedIn:t,isAdmin:r,needsInit:c,signIn:u,initialize:m,signOut:h},children:e})},ht=()=>{const e=p.useContext(le);if(!e)throw new Error("useSession 必须在 SessionProvider 内使用");return e},de={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/chat":"chat","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},W=Object.fromEntries(Object.entries(de).map(([e,t])=>[t,e])),X=()=>de[window.location.pathname]||"dashboard",_t=()=>{const{checkingAuth:e,isLoggedIn:t,isAdmin:s,needsInit:r,signIn:a,initialize:i,signOut:o}=ht(),[c,l]=p.useState(X),[d,u]=p.useState(""),[m,h]=p.useState(""),[x,v]=p.useState(!1),[k,w]=p.useState(""),[A,M]=p.useState(""),[B,F]=p.useState(""),[V,J]=p.useState(!1),[U,C]=p.useState(""),[pe,K]=p.useState(),[ge,ye]=p.useState(Te),Y=f=>{const _=f==="settings"&&!s?"dashboard":f,N=W[_];N&&N!==window.location.pathname&&window.history.pushState({},"",N),l(_)};p.useEffect(()=>{const f=()=>l(X());return window.addEventListener("popstate",f),()=>window.removeEventListener("popstate",f)},[]),p.useEffect(()=>{!e&&t&&!s&&c==="settings"&&(window.history.replaceState({},"",W.dashboard),l("dashboard"))},[e,t,s,c]);const me=async f=>{f.preventDefault(),v(!0),w("");try{const _=await a({username:d,password:m});_.success||w(_.message||"登录失败")}catch(_){const N=_ instanceof Error?_.message:String(_);w(N||"登录失败")}finally{v(!1)}},fe=async f=>{if(f.preventDefault(),C(""),A.length<8){C("密码至少需要 8 个字符");return}if(A!==B){C("两次输入的密码不一致");return}J(!0);try{const _=await i(A);if(!_.success){C(_.message||"初始化失败,请重试");return}M(""),F("")}catch(_){const N=_ instanceof Error?_.message:String(_);C(N||"初始化失败,请重试")}finally{J(!1)}},he=async()=>{try{await o()}catch(f){console.error("退出登录失败",f)}};if(e)return n.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface",children:n.jsx(D,{className:"w-8 h-8 text-brand animate-spin"})});if(r)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),n.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[n.jsxs("div",{className:"text-center mb-8",children:[n.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"首次设置管理员密码"}),n.jsx("p",{className:"text-gray-600 font-medium",children:"设置完成后会自动进入系统,管理员账号为 admin。"})]}),n.jsxs("form",{onSubmit:fe,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(H,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"password",placeholder:"设置管理员密码(至少 8 个字符)",value:A,onChange:f=>M(f.target.value),autoFocus:!0,className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(I,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"password",placeholder:"再次输入密码",value:B,onChange:f=>F(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),U&&n.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[n.jsx(I,{className:"w-4 h-4"})," ",U]}),n.jsx("button",{type:"submit",disabled:V,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:V?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["设置密码并进入系统 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!t)return n.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans",children:[n.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),n.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),n.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[n.jsxs("div",{className:"text-center mb-10",children:[n.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:n.jsx(R,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),n.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),n.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),n.jsxs("form",{onSubmit:me,className:"space-y-5",children:[n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"relative group",children:[n.jsx(Oe,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"text",placeholder:"管理员账号",value:d,onChange:f=>u(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),n.jsxs("div",{className:"relative group",children:[n.jsx(H,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),n.jsx("input",{type:"password",placeholder:"密码",value:m,onChange:f=>h(f.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),k&&n.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[n.jsx(I,{className:"w-4 h-4"})," ",k]}),n.jsx("button",{type:"submit",disabled:x,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:x?n.jsx(D,{className:"w-5 h-5 animate-spin"}):n.jsxs(n.Fragment,{children:["立即登录 ",n.jsx(G,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),n.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:n.jsx("div",{className:"mt-6 text-center",children:n.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const _e=f=>{K(f),Y("rules")},ve=()=>K(void 0),be=()=>ye(f=>{const _=!f;return Pe(_),_});return n.jsx(mt,{activeTab:c,isAdmin:s,collapsed:ge,deliveryRuleTarget:pe,onToggleCollapsed:be,onNavigate:Y,onLogout:he,onConfigureDelivery:_e,onDeliveryTargetHandled:ve})},vt=()=>n.jsx(ft,{children:n.jsx(_t,{})}),ue=document.getElementById("root");if(!ue)throw new Error("Could not find root element to mount to");const bt=xe.createRoot(ue);bt.render(n.jsx(ee.StrictMode,{children:n.jsx(vt,{})}));export{ms as $,qt as A,Zt as B,Mt as C,Gt as D,ss as E,Xt as F,ts as G,Qt as H,es as I,Wt as J,is as K,ds as L,us as M,cs as N,ls as O,os as P,xs as Q,bs as R,hs as S,_s as T,vs as U,js as V,ws as W,Ls as X,gs as Y,Ns as Z,ys as _,ps as a,fs as a0,Ss as a1,Ms as a2,Ps as a3,Ye as a4,Rs as a5,Nt as a6,Ys as a7,Es as a8,ks as a9,Is as aa,Cs as ab,As as ac,$s as ad,Ds as ae,Os as af,Ts as ag,Zs as ah,Hs as ai,Gs as aj,Qs as ak,Vs as al,Fs as am,Js as an,Ks as ao,Et as ap,$t as aq,Ot as ar,Dt as as,It as at,jt as b,Lt as c,ns as d,rs as e,kt as f,as as g,St as h,Ht as i,Tt as j,Pt as k,Rt as l,zt as m,Bs as n,Us as o,Vt as p,zs as q,At as r,Jt as s,qs as t,Ct as u,Ft as v,Bt as w,Kt as x,Ut as y,Yt as z}; diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index 2ce56f2..ec3f1fd 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,7 +6,7 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - + diff --git a/tools/architecturecheck/main.go b/tools/architecturecheck/main.go index 68a42e1..1b4b64f 100644 --- a/tools/architecturecheck/main.go +++ b/tools/architecturecheck/main.go @@ -215,47 +215,7 @@ func isForbiddenServerLowLevelImport(filePath, importedPath string) bool { importedPath != "internal/browser" && !strings.HasPrefix(importedPath, "internal/browser/") { return false } - return !temporaryServerLowLevelAllowlist[filePath] -} - -// temporaryServerLowLevelAllowlist 是审计重开前已存在的 Server 低层依赖临时白名单。 -// 每迁移一个业务域,必须删除对应文件条目;新文件不得加入白名单代替迁移。 -var temporaryServerLowLevelAllowlist = map[string]bool{ - "internal/server/account_login_repository.go": true, - "internal/server/account_login_service.go": true, - "internal/server/account_task_handlers.go": true, - "internal/server/analytics_handlers.go": true, - "internal/server/analytics_repository.go": true, - "internal/server/analytics_service.go": true, - "internal/server/api_contract.go": true, - "internal/server/auth_handlers.go": true, - "internal/server/automation_handlers.go": true, - "internal/server/card_batch_handlers.go": true, - "internal/server/card_handlers.go": true, - "internal/server/chat_handlers.go": true, - "internal/server/communication_repository.go": true, - "internal/server/communication_service.go": true, - "internal/server/cookie_handlers.go": true, - "internal/server/default_reply_handlers.go": true, - "internal/server/item_handlers.go": true, - "internal/server/item_publish_batch_handlers.go": true, - "internal/server/item_publish_images.go": true, - "internal/server/item_publish_repository.go": true, - "internal/server/item_publish_service.go": true, - "internal/server/keyword_handlers.go": true, - "internal/server/login_audit.go": true, - "internal/server/mtop_cookie_session.go": true, - "internal/server/notification_handlers.go": true, - "internal/server/order_handlers.go": true, - "internal/server/order_repository.go": true, - "internal/server/order_service.go": true, - "internal/server/ownership_helpers.go": true, - "internal/server/platform_runtime.go": true, - "internal/server/server.go": true, - "internal/server/settings_handlers.go": true, - "internal/server/success_contract.go": true, - "internal/server/transaction_repository.go": true, - "internal/server/qrlogin_handlers.go": true, + return true } // isForbiddenLowLevelImport 判断低层包是否依赖了上层应用包。 diff --git a/tools/architecturecheck/main_test.go b/tools/architecturecheck/main_test.go index 43bd247..e8273f8 100644 --- a/tools/architecturecheck/main_test.go +++ b/tools/architecturecheck/main_test.go @@ -32,10 +32,10 @@ func TestApplicationImportBoundary(t *testing.T) { } } -// TestServerLowLevelTemporaryAllowlist 验证旧 Server 低层依赖必须显式登记。 -func TestServerLowLevelTemporaryAllowlist(t *testing.T) { - if isForbiddenServerLowLevelImport("internal/server/order_service.go", "internal/db") { - t.Fatal("现有白名单文件不应被当前门禁阻断") +// TestServerLowLevelBoundary 验证 Server 低层依赖不得通过临时白名单保留。 +func TestServerLowLevelBoundary(t *testing.T) { + if !isForbiddenServerLowLevelImport("internal/server/cookie_handlers.go", "internal/db") { + t.Fatal("Server 低层依赖应被门禁拒绝") } if !isForbiddenServerLowLevelImport("internal/server/new_service.go", "internal/db") { t.Fatal("新增 Server 低层依赖必须被门禁拒绝")