diff --git a/cmd/server/main.go b/cmd/server/main.go index 20fd3c9..2d4451a 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -21,6 +21,7 @@ import ( "xianyu-go/internal/account" "xianyu-go/internal/adapter" + lifecycleapp "xianyu-go/internal/application/lifecycle" "xianyu-go/internal/auth" "xianyu-go/internal/automation" "xianyu-go/internal/browser" @@ -295,10 +296,6 @@ func runServer(parent context.Context, opts serverOptions) error { var bm *browser.Manager if !opts.noBrowser { bm = browser.NewManager(logger) - if // err 保存err,供当前处理流程使用 - err := bm.Initialize(); err != nil { - return fmt.Errorf("初始化 Playwright Chromium 指纹失败: %w", err) - } } // ap 保存ap,供当前处理流程使用 @@ -308,44 +305,130 @@ func runServer(parent context.Context, opts serverOptions) error { ap.SetChatService(chatService) // mgr 保存mgr,供当前处理流程使用 mgr := account.NewManager(store, ap, logger) - // autoCenter 保存autoCenter,供当前处理流程使用 - autoCenter := automation.New(store, mgr, logger) - autoCenter.SetOrderDetailFetcher(ap) // notifier 保存notifier,供当前处理流程使用 notifier := notify.New("", store, logger) - notifier.Start(ctx) - autoCenter.SetNotifier(notifier) + // autoCenter 保存依赖在启动前固定完成的自动化中心。 + autoCenter := automation.NewWithDependencies(store, mgr, logger, automation.CenterDependencies{ + OrderDetailFetcher: ap, + Notifier: notifier, + }) ap.SetAutomation(autoCenter) ap.SetNotifier(notifier) - if // err 保存err,供当前处理流程使用 - err := mgr.StartAll(ctx); err != nil { - logger.Error("启动账号引擎失败", "err", err) - } // automationScheduler 保存自动化Scheduler,供当前处理流程使用 automationScheduler := automation.NewScheduler(autoCenter) - go automationScheduler.Run(ctx) // renewalScheduler 保存renewalScheduler,供当前处理流程使用 renewalScheduler := renewal.NewScheduler(store, mgr, ap, logger, notifier) - go renewalScheduler.Run(ctx) + + // lifecycleCoordinator 统一拥有应用组件的启动顺序、取消 Context 和逆序关闭。 + lifecycleCoordinator := lifecycleapp.NewCoordinator() + if bm != nil { + // err 表示浏览器基础设施组件登记失败。 + if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "browser", Component: lifecycleapp.FuncComponent{ + StartFunc: func(context.Context) error { return bm.Initialize() }, + CloseFunc: bm.CloseContext, + }}); err != nil { + return fmt.Errorf("登记浏览器生命周期组件失败: %w", err) + } + } + // err 表示通知 worker 生命周期组件登记失败。 + if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "notifier", Component: lifecycleapp.FuncComponent{ + StartFunc: func(componentCtx context.Context) error { notifier.Start(componentCtx); return nil }, + CloseFunc: notifier.WaitContext, + }}); err != nil { + return fmt.Errorf("登记通知生命周期组件失败: %w", err) + } + // err 表示账号运行时生命周期组件登记失败。 + if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "account-manager", Component: lifecycleapp.FuncComponent{ + StartFunc: mgr.StartAll, + CloseFunc: mgr.StopAllContext, + }}); err != nil { + return fmt.Errorf("登记账号生命周期组件失败: %w", err) + } + // err 表示自动化调度器生命周期组件登记失败。 + if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "automation-scheduler", Component: lifecycleapp.FuncComponent{ + StartFunc: func(componentCtx context.Context) error { go automationScheduler.Run(componentCtx); return nil }, + CloseFunc: automationScheduler.WaitContext, + }}); err != nil { + return fmt.Errorf("登记自动化调度生命周期组件失败: %w", err) + } + // err 表示续期调度器生命周期组件登记失败。 + if err := lifecycleCoordinator.Add(lifecycleapp.NamedComponent{Name: "renewal-scheduler", Component: lifecycleapp.FuncComponent{ + StartFunc: func(componentCtx context.Context) error { go renewalScheduler.Run(componentCtx); return nil }, + CloseFunc: renewalScheduler.StopContext, + }}); err != nil { + return fmt.Errorf("登记续期调度生命周期组件失败: %w", err) + } // srv 是完成依赖校验并注入聊天服务后的 HTTP 应用实例。 - // serverDependencies 封装 HTTP 服务需要的持久化适配器,避免 Server 直接持有 Store。 - serverDependencies, dependencyErr := adapter.NewDependencies(store) - if dependencyErr != nil { - return fmt.Errorf("构造 HTTP 基础设施依赖失败: %w", dependencyErr) + // orderDependencies 保存订单应用服务专用的显式装配能力,避免订单路径读取通用设施容器。 + orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store) + if orderDependencyErr != nil { + return fmt.Errorf("构造订单基础设施依赖失败: %w", orderDependencyErr) + } + // accountDependencies 保存账号应用服务专用的显式装配能力,避免账号路径读取通用设施容器。 + accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store) + if accountDependencyErr != nil { + return fmt.Errorf("构造账号基础设施依赖失败: %w", accountDependencyErr) + } + // itemDependencies 保存商品应用服务专用的显式装配能力,避免商品路径读取通用设施容器。 + itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store) + if itemDependencyErr != nil { + return fmt.Errorf("构造商品基础设施依赖失败: %w", itemDependencyErr) + } + // automationDependencies 保存自动化、默认回复和关键词应用服务的显式装配能力。 + automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store) + if automationDependencyErr != nil { + return fmt.Errorf("构造自动化基础设施依赖失败: %w", automationDependencyErr) + } + // miscDependencies 保存通知、分析和卡券应用服务的显式装配能力。 + miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store) + if miscDependencyErr != nil { + return fmt.Errorf("构造通知分析卡券基础设施依赖失败: %w", miscDependencyErr) + } + // adminSettingsDependencies 保存管理员与系统设置应用服务的显式装配能力。 + adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store) + if adminSettingsDependencies == nil { + return fmt.Errorf("构造管理员设置基础设施依赖失败") + } + // chatDependencies 保存聊天应用服务使用的显式运行时与平台适配器。 + chatDependencies := adapter.NewChatDependencies(store) + if chatDependencies == nil { + return fmt.Errorf("构造聊天基础设施依赖失败") + } + // systemDependencies 保存健康检查和订单补偿扫描使用的显式数据库适配器。 + systemDependencies := adapter.NewSystemDependencies(store) + if systemDependencies == nil { + return fmt.Errorf("构造系统基础设施依赖失败") + } + // platformDependencies 保存服务端显式注入的 MTOP、长登录和二维码平台能力。 + platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(logger) + if platformDependencyErr != nil { + return fmt.Errorf("构造平台基础设施依赖失败: %w", platformDependencyErr) } // 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)) + srv, err := server.New(authentication, mgr, opts.webDir, opts.addr, logger, autoCenter, notifier, server.WithChatService(chatService), server.WithChatDependencies(chatDependencies), server.WithSystemDependencies(systemDependencies), server.WithOrderDependencies(orderDependencies), server.WithAccountDependencies(accountDependencies), server.WithItemDependencies(itemDependencies), server.WithAutomationDependencies(automationDependencies), server.WithMiscDependencies(miscDependencies), server.WithAdminSettingsDependencies(adminSettingsDependencies), server.WithPlatformDependencies(platformDependencies), server.WithApplicationLifecycle(lifecycleCoordinator)) if err != nil { return fmt.Errorf("构造 HTTP 服务失败: %w", err) } - srv.StartPublishBatchRecovery(ctx) - srv.StartOrderReconciliationRecovery(ctx) - srv.StartOrderRefreshRecovery(ctx) + // component 表示 Server 暴露给进程装配层的一个应用 worker 生命周期组件。 + for _, component := range srv.ApplicationLifecycleComponents() { + // err 表示应用 worker 生命周期组件登记失败。 + if err := lifecycleCoordinator.Add(component); err != nil { + return fmt.Errorf("登记应用 worker 生命周期组件 %q 失败: %w", component.Name, err) + } + } + // err 表示应用组件按依赖顺序启动失败的原因。 + if err := lifecycleCoordinator.Start(ctx); err != nil { + return fmt.Errorf("启动应用生命周期失败: %w", err) + } // err 是 HTTP 服务显式启动失败的原因。 if err := srv.Start(ctx); err != nil { + // rollbackCtx、rollbackCancel 限制 HTTP 启动失败后的组件回滚时间并释放定时器。 + rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer rollbackCancel() + _ = lifecycleCoordinator.Close(rollbackCtx) return fmt.Errorf("启动 HTTP 服务失败: %w", err) } // runErr 是 HTTP 监听退出时返回的错误。 @@ -353,30 +436,17 @@ func runServer(parent context.Context, opts serverOptions) error { if runErr != nil { logger.Error("HTTP 服务退出", "err", runErr) } - cancel() - // stopCtx 是关闭 HTTP 服务及其后台 worker 的有限等待上下文。 + // stopCtx 是关闭 HTTP 服务及全部应用组件的有限等待上下文。 // stopCancel 释放 stopCtx 的定时器资源。 // stopCtx、stopCancel 保存stopCtx、stop取消,供当前处理流程使用 stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second) - _ = srv.Stop(stopCtx) - // err 表示自动化调度器在关闭上下文内未完成退出的错误。 - if err := automationScheduler.WaitContext(stopCtx); err != nil { - logger.Warn("自动化调度器关闭未完成", "err", err) + // err 表示 HTTP 优雅关闭的错误;即使失败也继续关闭应用组件。 + if err := srv.Stop(stopCtx); err != nil { + logger.Warn("HTTP 服务关闭未完成", "err", err) } - // err 表示续期调度器在关闭上下文内未完成退出的错误。 - if err := renewalScheduler.WaitContext(stopCtx); err != nil { - logger.Warn("续期调度器关闭未完成", "err", err) - } - // err 表示账号运行时未能在关闭上下文内完整停止的错误。 - if err := mgr.StopAllContext(stopCtx); err != nil { - logger.Warn("账号运行时关闭未完成", "err", err) - } - if bm != nil { - _ = bm.Close() - } - // err 表示通知 worker 在关闭上下文内未完成退出的错误。 - if err := notifier.WaitContext(stopCtx); err != nil { - logger.Warn("通知 worker 关闭未完成", "err", err) + // err 表示应用组件逆序关闭时的聚合错误;协调器已保证每个组件都会尝试关闭。 + if err := lifecycleCoordinator.Close(stopCtx); err != nil { + logger.Warn("应用组件关闭未完成", "err", err) } stopCancel() return runErr diff --git a/docs/architecture/api-compatibility-matrix.md b/docs/architecture/api-compatibility-matrix.md index 21eefd9..f3ee110 100644 --- a/docs/architecture/api-compatibility-matrix.md +++ b/docs/architecture/api-compatibility-matrix.md @@ -9,6 +9,28 @@ - 新增接口必须先进入 `/api/v1/...`,旧路径只有在确认外部调用方为零后才允许删除。 - 删除旧路径前必须在本文件记录调用方审计证据、迁移版本和回滚方式,并同步删除对应契约测试。 +## 阶段 3 调用方审计 + +旧入口的仓库内调用方由 `tools/architecturecheck` 中的 +`TestFrontendProductionRequestsUseVersionedAPI` 静态清点,并在每次改动前端请求适配层时运行: + +| 调用方范围 | 当前证据 | 结论与删除条件 | +| --- | --- | --- | +| React 生产源码(`frontend/**/*.ts`、`frontend/**/*.tsx`,排除测试和构建产物) | 静态扫描未发现未版本化业务请求 | 已迁移到 `/api/v1`;新增调用必须继续通过该门禁 | +| React 测试、文档和兼容适配器 | 不作为生产调用方计数 | 可以保留历史样例,但不得被打包到生产请求路径 | +| 服务端旧路由 | 各领域版本化契约测试同时请求新旧入口 | 旧路径继续由同一 handler 提供;删除前必须确认外部调用方为零并同步删除契约测试 | +| 桌面包、脚本和第三方客户端 | 仓库内无法观测 | 暂不删除;发布侧需要增加请求遥测,连续两个发布周期无调用后才设置 Sunset 版本,并保留回滚版本 | + +该清点只证明仓库内 React 生产请求已经迁移,不能推断外部调用方为零。删除旧路径前,发布说明必须 +记录调用方审计、Deprecation/Sunset 版本、观测窗口和回滚方式;在证据缺失时保持兼容入口。 + +## 受控动态键响应 + +`notificationBindingListResponse`(按账号 ID 分组的绑定列表)和 +`automationRulePageResponse.trigger_counts`(按触发类型统计)是已有客户端依赖的动态键 JSON +形状,本阶段不改变字段形状。它们的值类型仍是具名 DTO 或明确标量;架构门禁只允许这类已登记的 +兼容结构,禁止新增 `map[string]any`、`[]map[string]any` 或未登记的动态响应类型。 + ## 仍保留的旧入口 服务端目前保留 `/api/...`、`/...` 和 `/admin/...` 等历史入口。仓库内生产 React 调用已经全部迁移到 `/api/v1/...`,服务端契约测试仍覆盖新旧路径的等价响应和权限边界。 diff --git a/docs/architecture/lifecycle-inventory.md b/docs/architecture/lifecycle-inventory.md index d05d8a6..5b5c0fc 100644 --- a/docs/architecture/lifecycle-inventory.md +++ b/docs/architecture/lifecycle-inventory.md @@ -1,27 +1,37 @@ # 生命周期与后台任务清单 -本文是重构计划阶段 5 的持续审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界, -用于逐项关闭“生命周期与删除 fencing”父切片;清单本身不代表对应组件已经满足完成条件。 +本文是重构计划阶段 5 收口后的静态审计清单。它记录后台组件的所有者、Context 来源、停止和等待边界, +用于防止后续迭代重新引入游离 goroutine;阶段状态和验收证据只记录在重构进度文档中。 ## 组件清单 | 组件/入口 | 所有者 | 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 证据仍待完善 | +| `server.Server` HTTP 与请求后台任务 | `cmd/server`(HTTP)/`server.Server`(请求任务观测) | `Server.Start` 接收的进程 Context;请求任务使用调用方显式 Context | `Server.Stop(ctx)` 只关闭 HTTP 与请求任务等待;应用 worker 不由 Server 关闭 | `Wait`、`WaitForBackground`、任务注册表状态查询 | Server 生命周期、超时等待和任务注册表测试 | 业务 worker 已移出 Server;任务业务语义继续由应用服务维护 | +| 订单刷新 worker/recovery | `lifecycle.Coordinator` → `orders.RefreshJobService` | 协调器共享应用生命周期 Context;请求只负责创建任务 | 协调器逆序 `Close(ctx)`,runner 通过租约 token 和 Context 收束 | 应用任务状态、租约终态和 runner `Wait/Close` | 订单刷新生命周期、租约、取消和晚到写入测试 | 统一运维查询属于后续观测迭代,不改变生命周期所有权 | +| 商品批量发布 worker/recovery | `lifecycle.Coordinator` → `items.BatchWorkerCoordinator` | 协调器共享应用生命周期 Context;取消后的本地收口使用受控补偿 Context | 协调器逆序 `Close(ctx)`,worker cancel、租约 token 和终态补偿由应用协调器负责 | 批次状态、协调器 `Wait/Close` 与错误回调 | 批量取消 race、应用 BatchRunner 和协调器测试 | 恢复指标属于后续观测迭代,不改变生命周期所有权 | +| 订单 reconciliation worker | `lifecycle.Coordinator` → `orders.ReconciliationRecoveryCoordinator` | 协调器共享应用生命周期 Context | 协调器逆序 `Close(ctx)` 取消当前扫描并等待退出 | 补偿记录状态与协调器 `Wait/Close` | reconciliation 成功/失败重试、取消和协调器测试 | 指数退避属于后续补偿策略迭代 | +| `account.Manager` 账号运行时集合 | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopAllContext`,保留全局 stopping fence | 等待单账号或全部账号结束 | Manager fencing、删除 fencing、生命周期和 race 测试 | 运行时内部任务的细分归入阶段 6,不改变进程级 owner | +| `engine.Account` 单账号运行时 | `account.Manager`;连接、出站、凭证和迟到续期分别由 `connectionCoordinator`、`outgoingMessageCoordinator`、`credentialCoordinator`、`pendingRenewalCoordinator` 负责 | `Account.Run(parent)` | `StopContext` 取消运行 Context;连接协调器以受限预算等待自有 worker | `StopContext` 返回错误;共享完成信号支持超时后的再次 Join;运行状态可查询 | Engine lifecycle、连接协调器、出站发送、credential coordinator、刷新取消与迟到续期测试 | recorder 子任务继续沿用账号运行 Context,不允许脱离 facade 生命周期 | +| 浏览器 `Manager` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 每次调用的独立 Context;初始化和关闭受协调器 Context/Close Context 约束 | 协调器逆序调用 `CloseContext`,关闭 fencing 并等待活动调用归零 | `CloseContext` 返回超时并可重试 | Browser lifecycle 与 race 测试 | 底层同步 Playwright Close 无法被 Context 中断,这是实现约束 | +| 续期 `renewal.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `StopContext`,幂等并阻止 Stop 后 Run | `WaitContext` | 先 Stop、重复 Stop、零值和 race 测试 | 迟到 Cookie 合并语义由续期组件自身 generation/锁测试保护 | +| 自动化 `automation.Scheduler` | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序取消 Context 并调用 `WaitContext` | `WaitContext` | scheduler 与结果收口测试 | 自动化外部动作语义归入阶段 6,不改变调度器 owner | +| 通知 outbox worker | `lifecycle.Coordinator`(由 `cmd/server` 装配) | 协调器共享应用生命周期 Context | 协调器逆序调用 `WaitContext`,由共享 Context 停止拉取与发送 | `WaitContext`、uncertain 状态查询 | notify worker、uncertain 状态和三库测试 | 运维重试与人工核对流程属于通知业务迭代 | +| WebSocket/聊天后台发送任务 | `chat.Service` 与请求级连接 owner | 请求 Context 和连接关闭信号;不继承 Server 业务 worker Context | 请求取消或连接关闭时先取消发送/读取任务,再由连接 owner 等待 Join | WebSocket handler 显式等待读取 goroutine,发送结果和连接状态保留可观测字段 | WebSocket 事件流测试、Server race;`chatWebSocket` 已显式 Wait/Join 读取任务 | 更细的消息分发状态拆分属于阶段 6,不新增 Server 生命周期入口 | + +## 阶段 6 并发与锁边界 + +| 锁/协调状态 | 所有者与保护范围 | 明确禁止 | 锁顺序/验证 | +| --- | --- | --- | --- | +| `Store` 账号凭证锁 | 保护 Cookie、metadata、Token 绑定指纹的快照读取和条件写回 | 不得跨 MTOP、WebSocket、浏览器、通知或用户等待 I/O | `refreshGate → credential lock`;锁外 I/O、旧响应冲突和锁外 Handler 通知测试 | +| Engine `refreshGate` | 用单令牌通道串行化同一账号 Token/续期状态机及迟到响应收口,不持有互斥锁等待外部 I/O | 不得反向取得其他 worker 锁;等待必须响应调用 Context 取消 | `refreshGate → credential lock`;Token、API 续期、迟到 Cookie、取消和 race 测试 | +| Engine `outgoingMessageCoordinator` | 先短暂读取 `runtimeMu` 中的连接,再短暂读取凭证锁中的 `unb` 身份;发送与历史查询在两把锁外执行 | 不得同时持有 `runtimeMu` 与凭证锁,不得持锁执行 WebSocket I/O | `runtime snapshot → credential snapshot`,两段锁不重叠;出站发送与连接 race 测试 | +| Automation `cardLocks` | 保护同一卡密组库存消费与确定未发送时恢复 | 不得覆盖 WebSocket 消息发送、图片发送或人工等待 | 每次库存操作独立加锁;并发卡密发送阻塞测试 | +| Automation 运行租约/动作检查点 | 由数据库租约拥有跨进程 worker 的唯一执行权;结果通知以 `runID + status` 写入持久化 outbox | 不得在本地互斥锁内持有外部动作;不确定结果不得自动重放或重新入队 | `StartRunAction` 后执行外部动作;通知 outbox 的成功/失败/不确定隔离与重复恢复测试 | ## 使用规则 1. 新增 goroutine 必须在本表增加一行,注明启动者、Context 来源、取消责任和等待方式。 -2. 每个组件完成生命周期迁移后,必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动完成。 +2. 新组件必须同时提供取消、超时、重复停止和晚到写入测试;测试通过不等于其他组件自动继承其业务语义。 3. 删除账号前必须先建立账号级 stopping fence,再在受限 Context 内停止运行时,最后重新校验归属并删除持久化记录。 -4. 本表中标记为“剩余风险”的项目未满足父切片关闭条件前,阶段 5 必须保持“进行中”。 +4. 本表只记录 owner 与边界;阶段 6 以后业务策略、运维观测和实时连接细分风险不得重新转化为 Server 生命周期入口。 diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index bca5520..c830c98 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -58,16 +58,20 @@ React app shell 空列表编码为 `[]`,前端同时接受数组、包裹对象和 `null`;对应回归测试是强制契约。 - 远端 `main` 的文档链接变更不影响运行功能。生成前端资产的文本冲突必须通过当前源码重新构建 解决,禁止手工合并压缩产物。 -- Server 生产代码已大幅迁移到应用 Port,架构检查当前可通过;但仍存在 Server 暴露 - `*sql.Tx` 的遗留事务边界、Server 持有业务 worker/会话状态,以及集中式依赖工厂隐藏底层 - `Store` 的风险,因此阶段 4 和阶段 5 尚未验收。 +- Server 生产代码已迁移到应用 Port,架构检查当前可通过;阶段 4 已移除 Server 暴露 + `*sql.Tx` 的遗留事务边界,并将订单刷新任务、订单补偿扫描、批量发布 worker、扫码会话、账号登录、 + 商品、聊天、通知、分析、卡券、自动化和管理员设置装配下沉到应用服务与显式类型化依赖。Session 恢复、 + 订单运行时 typed port 和账号凭证恢复协调也已完成,已知调用方不再依赖集中式 `adapter.Dependencies`; + 阶段 4 与阶段 5 已完成。 - 账号敏感摘要与秘密访问已经分离,并已有审计和多数据库覆盖;阶段 2 可视为完成,但后续迭代 不得重新扩大读取、解密、序列化或日志范围。 -- HTTP 已有 `/api/v1` 路径和兼容契约测试,但 transport 仍使用动态 map、部分兼容响应别名和 - 未生成的集中类型,因此阶段 3 尚未验收。 -- Engine `Account`、Automation `Center`、集中前端 API/类型文件和若干大型 Hook 仍承担过多职责; - 目录已经拆分不等于对应阶段完成。 -- 生命周期清单仍列有 Engine 子任务、实时连接、恢复任务和运维观测缺口;阶段 5 尚未验收。 +- HTTP `/api/v1` 版本化、具名 DTO、统一错误、前端兼容归一和调用方审计已完成阶段 3 验收; + 受控的设置键、账号绑定键和触发统计键仍按兼容清单保留,删除条件记录在 + `docs/architecture/api-compatibility-matrix.md`。 +- Engine `Account` 与 Automation `Center` 已收束为稳定 facade;连接、出站消息、凭证、运行检查点、 + 动作执行、库存、通知和迟到续期分别由明确组件拥有。集中前端 API/类型文件和若干大型 Hook + 仍属于阶段 7 的后续范围。 +- 阶段 5 已完成进程级应用装配与生命周期收口;生命周期清单保留 Engine/Automation 内部状态拆分和运维观测等后续阶段风险,但不再允许回流为 Server 或 cmd 的隐式后台入口。 - 三方言迁移编号当前对齐,订单已有游标和批量写入能力;跨 repository 事务、查询计划、补偿和 大数据量行为仍需阶段 8 统一验收。 - 注释历史基线文件当前为空,但源码仍存在“保存 X 供当前流程使用”等模板化注释。机械基线清零 @@ -85,12 +89,12 @@ React app shell | 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 和三方言验收 | +| 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. 注释与复杂度收口 | 待执行 | 清除模板注释和复杂度债务,形成最终质量门禁 | diff --git a/docs/architecture/refactoring-progress.md b/docs/architecture/refactoring-progress.md new file mode 100644 index 0000000..30289e2 --- /dev/null +++ b/docs/architecture/refactoring-progress.md @@ -0,0 +1,145 @@ +# 重构阶段验收记录 + +本文件只记录阶段整体的验收证据、更新日志和阶段边界。每个阶段对应一个 PR;阶段内并行实现不形成独立任务、独立验收或额外 PR。 + +## 阶段 3:HTTP API 契约 + +状态:已完成。 + +主要证据:业务入口使用 `/api/v1` 版本化路径、具名 DTO、统一错误 envelope 和前端兼容归一;空集合兼容、契约测试、前端构建和嵌入资源均已验证。 + +## 阶段 4:Server 应用服务 + +状态:已完成;对应一个阶段 4 PR 边界。 + +完成证据: + +- Server 生产代码不再导入 `database/sql`、`internal/db`、`internal/xianyu` 或 `internal/browser`,不创建事务,也不持有通用 `adapter.Dependencies`。 +- 订单刷新、订单补偿扫描、批量发布、二维码会话、账号登录、Cookie 写入、资料刷新、聊天刷新/订阅、商品发布和管理员删除均通过应用服务与消费者定义的最小 Port 编排。 +- Session 失效恢复统一由 `adapter.SessionRecoveryHandler` 分类和记录脱敏诊断,再调用账号运行时应用端口;生产适配器不再把 `Server.recoverExpiredMTOPSession` 作为回调传入。 +- 订单运行时使用 `adapter.OrderAutomation`、`adapter.OrderNotifier` 等 typed port;Server 不再编排 Manager、Automation 和 Notifier 闭包。订单补偿扫描由 `orders.ReconciliationRecoveryCoordinator` 拥有启动、取消、等待和关闭生命周期。 +- 账号凭证恢复使用 `account.CredentialRefreshCoordinator` 按账号并发登记;慢速协议续期不在协调锁内执行,自动化唤醒经过 `CredentialWakePort`/`CredentialWakeService`。 +- 所有必需领域依赖由显式类型化依赖组构造并在 `Server.New` 阶段校验;缺失依赖、越权、失败、取消、重复启动/关闭、租约 fencing、补偿和晚到结果均有聚焦测试。 +- `MTop`、`CookieRenew`、`QRLogin` 以及少量 Adapter setter 仅作为测试/兼容入口保留。删除条件为已知生产与测试调用清零、契约测试证明新构造路径覆盖全部调用,并完成外部调用方审计;这些兼容入口不作为新增业务依赖。 +- 冻结滑块 CAPTCHA 实现及其测试未修改。 + +统一验证证据: + +```text +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 +go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json +git diff --check +``` + +以上命令均通过;race 运行实际覆盖应用层、适配器和 Server 生命周期/凭证并发路径。 + +## 更新日志 + +- 2026-08-17:完成阶段 4 整体 Server 应用服务改造,统一完成应用 Port、显式装配、凭证边界、Session 恢复、订单补偿生命周期和并发协调,并通过阶段 4 全部门禁。 + +## 阶段 5:应用装配与生命周期 + +状态:已完成;对应一个阶段 5 PR 边界。阶段内并行实现不形成独立任务、独立验收或额外 PR。 + +完成证据: + +- 新增 `internal/application/lifecycle.Coordinator`,统一拥有共享 Context、登记顺序、启动失败逆序回滚、关闭逆序、并发 Close 等待、超时和错误聚合;组件回调始终在锁外执行。 +- `cmd/server` 统一登记浏览器、Notifier、账号 Manager、Automation Scheduler、Renewal Scheduler 以及订单刷新、批量发布、订单 reconciliation 三类应用 worker;HTTP Server 只负责 HTTP 启停,退出时先停 HTTP,再由协调器逆序关闭应用组件。 +- Server 删除业务 worker 的启动/关闭入口和应用 worker 等待逻辑;Server 仅通过只读生命周期 Context 为请求创建的应用 worker 提供父 Context,生命周期 owner 保持在协调器与应用服务。 +- 启动失败回滚、重复 Start/Close、并发 Close、启动与关闭竞争、批次/订单 worker 取消、租约 fencing、账号 stopping fence、浏览器关闭超时重试和实时连接 Join 均有聚焦测试;冻结 CAPTCHA 文件未修改。 +- `docs/architecture/lifecycle-inventory.md` 已转为静态 owner/Context/Stop/Wait 清单,后续 Engine/Automation 内部状态拆分和运维观测风险归入阶段 6 及后续迭代,不得重新引入 Server 生命周期入口。 + +统一验证证据: + +```text +make check +go test -race ./internal/server ./internal/account ./internal/engine ./internal/automation ./internal/renewal -count=1 +go test ./... -count=1 +go run ./tools/architecturecheck +go run ./tools/commentlint -mode check -root . -baseline .commentlint/go-baseline.json +git diff --check +``` + +以上命令均通过;race 子集实际覆盖 Server、账号、Engine、Automation、续期和生命周期竞争路径。 + +下一安全入口:阶段 6「Engine 与 Automation」,只处理其内部状态所有权和动作语义拆分,不回退或扩大阶段 5 的进程生命周期边界。 + +## 更新日志 + +- 2026-08-17:完成阶段 5 应用装配与生命周期整体改造,统一 cmd 生命周期协调、Server HTTP 边界、应用 worker owner、启动回滚与关闭等待,并通过阶段 5 全部门禁。 + +## 阶段 6:Engine 与 Automation + +状态:已完成;对应一个阶段 6 PR 边界。阶段内并行实现不形成独立任务、独立验收或额外 PR。 + +完成证据: + +- `automationActionExecutor.sendDataCard` 的卡券锁仅覆盖库存预留与确定未发送时的恢复,外部 WebSocket 发送已移到锁外,并有并发阻塞测试证明第二个库存操作不会等待第一个外部发送。 +- `confirmShipmentAttempt` 在凭证锁内只读取最小运行时快照,MTOP 调用在锁外执行;响应写回重新获取凭证锁并进行指纹条件校验,冲突时跳过旧响应并记录人工核对所需错误。 +- 新增凭证锁锁外外部 I/O、并发新凭证不被旧响应覆盖的确定性测试;冻结 CAPTCHA 实现及测试未修改。 +- `automation.NewWithDependencies` 固定 MTOP、账号任务、订单详情、通知和 Cookie 读取依赖;所有 `Center` setter、运行时依赖覆盖和其锁已删除,延迟恢复通过同一构造依赖重建 Center。 +- `engine.Account` 已将连接、出站消息、凭证、消息分发、运行状态、生命周期和迟到续期收束到独立组件;凭证实现已物理迁入 `credentialCoordinator`,facade 仅保留稳定入口和必要兼容委托。 +- `refreshGate` 支持 Context 取消;凭证锁只覆盖快照和条件提交,MTOP、WebSocket、浏览器、通知及 Handler 回调均在锁外执行。`pendingRenewalCoordinator` 与连接协调器以共享完成信号和有限预算 Join,不创建超时后无法回收的等待 goroutine。 +- 自动化外部动作在运行检查点后执行,保留成功、失败和 `needs_review` 三态。结果通知以 `runID + status` 作为持久化 outbox 幂等键,重复恢复不会重复入队;外部投递成功但本地确认失败的 `uncertain` 记录不会自动重放。SQLite、MySQL、PostgreSQL 的 `00034` 通知幂等迁移已对齐。 +- 冻结 CAPTCHA 受保护文件未改动;浏览器集成和全部冻结行为测试通过。 + +下一安全入口:阶段 7「React Feature 化」。仅处理 `app -> features -> shared`、feature API adapter、状态归属与路由加载,不回退阶段 6 的 Engine、Automation、凭证、通知或并发边界。 + +当前统一验证证据: + +```text +make check # 通过 +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 # 通过 +git diff --check # 通过 +make cover # Go statements 66.5% +make cover-browser # Browser statements 60.9%(RUN_BROWSER_INTEGRATION=1) +make cover-frontend # Frontend statements 93.01% +``` + +覆盖率例外:未跳过本地确定性 Engine、Automation 或浏览器行为;仅保留项目既有的真实账号/外部平台不可用场景分类。 + +更新日志: + +- 2026-08-17:完成阶段 6 整体 Engine 与 Automation 改造,统一收束 facade、凭证和 worker 生命周期、锁外外部 I/O、运行检查点及通知幂等/不确定态,并通过阶段 6 全部门禁。 + +## 阶段 7:React Feature 化 + +状态:已完成;对应一个阶段 7 PR 边界。阶段内并行实现不形成独立任务、独立验收或额外 PR。 + +完成证据: + +- 根 `App` 仅装配错误边界、会话 Provider 和路由;认证表单归属 session feature,认证后导航、权限回退、侧边栏偏好和一次性跨页面载荷由 app 路由壳管理。 +- 九个业务页面与其直属组件、Hook、状态、API adapter 和测试均归入各自 feature;账号自动任务归入 accounts,删除跨 feature 的 accountAutomation 目录。 +- 已删除集中式 `frontend/services/api.ts`、`frontend/types.ts`、`frontend/request.ts` 和 `frontend/services/contract.ts`;feature API adapter 直接依赖 `shared/http`,只读传输契约位于 `shared/api-contract`,DTO 归一保留在所属 feature 边界。 +- `shared` 只保留 HTTP transport、兼容 JSON contract、通用异步 gate、浏览器偏好和纯展示 UI;架构测试禁止 feature 相互导入、shared 反向依赖 feature、组件直连网络和根 components 回流。 +- 所有业务页面由 `React.lazy` 按路由加载;构建验证九个独立页面分片、首屏不预加载 charts 分片且每页原始大小满足既有预算。仪表盘乱序、卡密/订单卸载取消、聊天切换与旧分页响应均有确定性行为测试。 +- 冻结 CAPTCHA 实现、测试及调用语义均未修改。 + +当前统一验证证据: + +```text +npm test --prefix frontend # 63 files, 383 tests 通过 +npm run typecheck --prefix frontend # 通过 +npm run comments:check --prefix frontend # 通过 +npm run build --prefix frontend # 通过,已更新 internal/webui/static +make cover-frontend # Frontend statements 79.84%,RUN_BROWSER_INTEGRATION 未使用 +git diff --check # 通过 +go run ./tools/architecturecheck # 通过 +make comments # 通过 +make check # 通过 +``` + +覆盖率例外:纯 React 页面、展示组件与错误边界在本阶段的 V8 报告中存在未覆盖行;所有新改动的业务 API、Hook、状态、取消、切换和乱序行为均由确定性 Vitest 覆盖。无真实账号或外部平台调用。 + +下一安全入口:阶段 8「DB 与事务治理」,仅处理窄 repository、应用层 Unit of Work、批量与三方言事务验收;不得回退阶段 7 的 feature 边界、共享 HTTP 或路由加载约束。 + +更新日志: + +- 2026-08-17:完成阶段 7 React Feature 化整体改造,统一落地 app -> features -> shared、feature API adapter、路由懒加载、异步请求生命周期与前端架构门禁,并通过阶段全部验证。 diff --git a/frontend/App.tsx b/frontend/App.tsx index 69e9607..b50f0c5 100644 --- a/frontend/App.tsx +++ b/frontend/App.tsx @@ -1,304 +1,15 @@ -import React, { useState, useEffect } from 'react'; -import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState'; -import { YdisksBrandIcon } from './components/YdisksLogo'; -import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react'; -import AuthenticatedShell, { type DeliveryRuleTarget } from './app/shell/AuthenticatedShell'; -import { SessionProvider, useSession } from './app/providers/SessionProvider'; +import React from 'react'; +import { AppErrorBoundary } from './app/errors/AppErrorBoundary'; +import { SessionProvider } from './app/providers/SessionProvider'; +import { AppRouter } from './app/router/AppRouter'; -// 路由:URL path ↔ tab id。所有 SPA 路由统一挂 /app/ 前缀,避免和后端 API -// 路径(/orders、/cards、/items 等)冲突——后者在 chi 里先注册,刷新会直接 -// 返回 JSON 而不是 SPA 页面。 -const ROUTES: Record = { - '/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', -}; -const TAB_TO_PATH: Record = Object.fromEntries( - Object.entries(ROUTES).map(([path, tab]) => [tab, path] /* 回调函数负责当前业务流程。 */) -); /* TAB_TO_PATH 表示TABTO当前路径。 */ -const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard'; /* tabFromPath 表示tabFrom当前路径。 */ - -// AppView 渲染认证表单、路由状态和认证成功后的应用壳。 -const AppView: React.FC = () => { - // session 从 Provider 读取认证状态和会话操作,避免页面直接管理全局会话副作用。 - const { checkingAuth, isLoggedIn, isAdmin, needsInit, signIn, initialize, signOut } = useSession(); - const [activeTab, setActiveTab] = useState(tabFromPath); /* [activeTab, setActiveTab] 表示activeTabsetActiveTab。 */ - const [username, setUsername] = useState(''); /* [username, setUsername] 表示usernamesetUsername。 */ - const [password, setPassword] = useState(''); /* [password, setPassword] 表示passwordsetPassword。 */ - const [loginLoading, setLoginLoading] = useState(false); /* [loginLoading, setLoginLoading] 表示login加载状态setLogin加载状态。 */ - const [loginError, setLoginError] = useState(''); /* [loginError, setLoginError] 表示login当前操作返回的错误setLogin当前操作返回的错误。 */ - const [initialPassword, setInitialPassword] = useState(''); /* [initialPassword, setInitialPassword] 表示initialPasswordsetInitialPassword。 */ - const [initialPasswordConfirm, setInitialPasswordConfirm] = useState(''); /* [initialPasswordConfirm, setInitialPasswordConfirm] 表示initialPasswordConfirmsetInitialPasswordConfirm。 */ - const [initializing, setInitializing] = useState(false); /* [initializing, setInitializing] 表示initializingsetInitializing。 */ - const [initializationError, setInitializationError] = useState(''); /* [initializationError, setInitializationError] 表示initialization当前操作返回的错误setInitialization当前操作返回的错误。 */ - const [deliveryRuleTarget, setDeliveryRuleTarget] = useState(); /* [deliveryRuleTarget, setDeliveryRuleTarget] 表示delivery当前规则TargetsetDelivery当前规则Target。 */ - const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed); /* [sidebarCollapsed, setSidebarCollapsed] 表示sidebarCollapsedsetSidebarCollapsed。 */ - - // 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。 - const navigate = (tab: string) => { - const nextTab = tab === 'settings' && !isAdmin ? 'dashboard' : tab; /* nextTab 表示nextTab。 */ - const path = TAB_TO_PATH[nextTab]; /* path 表示当前路径。 */ - if (path && path !== window.location.pathname) { - window.history.pushState({}, '', path); - } - setActiveTab(nextTab); - }; - - // 浏览器后退/前进同步 tab。 - useEffect(() => { - const onPopState = () => setActiveTab(tabFromPath()); /* onPopState 表示onPopState。 */ - window.addEventListener('popstate', onPopState); - return () => window.removeEventListener('popstate', onPopState) /* 回调函数负责当前业务流程。 */; - } /* 回调函数负责当前业务流程。 */, []); - - useEffect(() => { - if (!checkingAuth && isLoggedIn && !isAdmin && activeTab === 'settings') { - window.history.replaceState({}, '', TAB_TO_PATH.dashboard); - setActiveTab('dashboard'); - } - } /* 回调函数负责当前业务流程。 */, [checkingAuth, isLoggedIn, isAdmin, activeTab]); - - const handleLogin = async (e: React.FormEvent) => { - e.preventDefault(); - setLoginLoading(true); - setLoginError(''); - - try { - const res = await signIn({ username, password }); /* res 表示接口响应结果。 */ - if (!res.success) { - setLoginError(res.message || '登录失败'); - } - } catch (err /* err 表示当前操作返回的错误。 */) { - const msg = err instanceof Error ? err.message : String(err); /* msg 表示msg。 */ - setLoginError(msg || '登录失败'); - } finally { - setLoginLoading(false); - } - }; /* handleLogin 表示handleLogin。 */ - - const handleInitialize = async (e: React.FormEvent) => { - e.preventDefault(); - setInitializationError(''); - if (initialPassword.length < 8) { - setInitializationError('密码至少需要 8 个字符'); - return; - } - if (initialPassword !== initialPasswordConfirm) { - setInitializationError('两次输入的密码不一致'); - return; - } - - setInitializing(true); - try { - const res = await initialize(initialPassword); /* res 表示接口响应结果。 */ - if (!res.success) { - setInitializationError(res.message || '初始化失败,请重试'); - return; - } - setInitialPassword(''); - setInitialPasswordConfirm(''); - } catch (err /* err 表示当前操作返回的错误。 */) { - const msg = err instanceof Error ? err.message : String(err); /* msg 表示msg。 */ - setInitializationError(msg || '初始化失败,请重试'); - } finally { - setInitializing(false); - } - }; /* handleInitialize 表示handleInitialize。 */ - - const handleLogout = async () => { - try { - await signOut(); - } catch (err /* err 表示当前操作返回的错误。 */) { - console.error('退出登录失败', err); - } - }; /* handleLogout 表示handleLogout。 */ - - - if (checkingAuth) { - return ( -
- -
- ); - } - - // Init Screen (system not initialized) - if (needsInit) { - return ( -
-
-
- -
-
-
- -
-

首次设置管理员密码

-

设置完成后会自动进入系统,管理员账号为 admin。

-
- -
-
-
- - setInitialPassword(e.target.value) /* 回调函数负责当前业务流程。 */} - autoFocus - className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14" - /> -
-
- - setInitialPasswordConfirm(e.target.value) /* 回调函数负责当前业务流程。 */} - className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14" - /> -
-
- - {initializationError && ( -
- {initializationError} -
- )} - - -
- -
- Secure Bootstrap -
-
-
- ); - } - - // Login Screen Component - if (!isLoggedIn) { - return ( -
- {/* Animated Background Blobs */} -
-
- -
- - {/* Header with Logo */} -
-
- -
-

欢迎回来

-

Ydisks闲鱼助手 · 自动发货与管家系统

-
- -
-
-
- - setUsername(e.target.value) /* 回调函数负责当前业务流程。 */} - className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14" - /> -
-
- - setPassword(e.target.value) /* 回调函数负责当前业务流程。 */} - className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14" - /> -
-
- - {loginError && ( -
- {loginError} -
- )} - - -
- -
-
- - Ydisks闲鱼助手 v1.0 - -
-
-
-
- ); - } - - // handleConfigureDelivery 保存商品页传来的规则目标并切换到规则页面。 - const handleConfigureDelivery = (target /* target 表示商品页传来的规则配置目标。 */: DeliveryRuleTarget) => { - setDeliveryRuleTarget(target); - navigate('rules'); - }; - - // handleDeliveryTargetHandled 清理已经被规则页面消费的联动目标。 - const handleDeliveryTargetHandled = () => setDeliveryRuleTarget(undefined); - - // handleToggleSidebar 切换侧边栏状态并持久化用户偏好。 - const handleToggleSidebar = () => setSidebarCollapsed(/* current 表示更新前的侧边栏折叠状态。 */ current => { - // next 表示切换后的侧边栏折叠状态。 - const next = !current; - writeSidebarCollapsed(next); - return next; - }); - - return ( - - ); -}; /* AppView 表示认证页面和应用壳视图。 */ - -// App 在根部装配 SessionProvider,确保所有认证状态共享同一生命周期。 +/** App 只装配全局 Provider、错误边界和路由,不保留任何领域页面或请求状态。 */ const App: React.FC = () => ( - - - + + + + + ); export default App; diff --git a/frontend/app/errors/AppErrorBoundary.tsx b/frontend/app/errors/AppErrorBoundary.tsx new file mode 100644 index 0000000..08b623d --- /dev/null +++ b/frontend/app/errors/AppErrorBoundary.tsx @@ -0,0 +1,49 @@ +import React from 'react'; + +/** ErrorBoundaryProps 描述顶层错误边界可恢复的页面子树。 */ +interface ErrorBoundaryProps { + /** children 是由错误边界保护的整个应用路由树。 */ + children: React.ReactNode; +} + +/** ErrorBoundaryState 只记录渲染期故障,避免把错误对象或敏感响应写入浏览器状态。 */ +interface ErrorBoundaryState { + /** hasError 表示应用子树是否因渲染错误而被隔离。 */ + hasError: boolean; +} + +/** AppErrorBoundary 隔离未捕获的页面渲染错误,并提供不依赖网络请求的恢复入口。 */ +export class AppErrorBoundary extends React.Component { + /** state 保存当前子树的错误隔离状态。 */ + public state: ErrorBoundaryState = { hasError: false }; + + /** getDerivedStateFromError 在 React 捕获到子树异常时切换到静态恢复视图。 */ + public static getDerivedStateFromError(): ErrorBoundaryState { + return { hasError: true }; + } + + /** handleReload 由用户点击触发,使用完整刷新重新建立会话和路由运行环境。 */ + private handleReload = (): void => { + window.location.reload(); + }; + + /** render 在正常路径渲染应用子树;捕获异常后只暴露安全的恢复界面。 */ + public render(): React.ReactNode { + // hasError 表示当前是否需要显示错误隔离界面。 + const { hasError } = this.state; + // children 是未发生渲染错误时应继续展示的应用路由树。 + const { children } = this.props; + if (!hasError) return children; + + return ( +
+
+

页面暂时无法显示

+ +
+
+ ); + } +} diff --git a/frontend/app/features/accountAutomation/api.ts b/frontend/app/features/accountAutomation/api.ts deleted file mode 100644 index 34199e2..0000000 --- a/frontend/app/features/accountAutomation/api.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** AccountAutomation feature 使用的账号任务 API。 */ -export { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from '../../../services/api'; diff --git a/frontend/app/features/accounts/accountAutomationApi.ts b/frontend/app/features/accounts/accountAutomationApi.ts new file mode 100644 index 0000000..986c959 --- /dev/null +++ b/frontend/app/features/accounts/accountAutomationApi.ts @@ -0,0 +1,11 @@ +import { get, post, put, type RequestControlOptions } from '../../../shared/http/client'; +import type { AccountTaskSettings, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope } from '../../../shared/api-contract'; + +/** 获取指定账号的自动评价与自动擦亮设置。 */ +export const getAccountTaskSettings = async (accountID: string, options?: RequestControlOptions): Promise => get(`/api/v1/account-tasks/${accountID}`, undefined, options); + +/** 保存指定账号的自动评价与自动擦亮设置。 */ +export const updateAccountTaskSettings = async (accountID: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise => put(`/api/v1/account-tasks/${accountID}`, settings, options); + +/** 立即发起账号级计划任务,并使用较长超时覆盖平台执行窗口。 */ +export const runAccountTask = async (accountID: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise => post(`/api/v1/account-tasks/${accountID}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options }); diff --git a/frontend/app/features/accountAutomation/hooks.test.tsx b/frontend/app/features/accounts/accountAutomationHooks.test.tsx similarity index 96% rename from frontend/app/features/accountAutomation/hooks.test.tsx rename to frontend/app/features/accounts/accountAutomationHooks.test.tsx index 6d85d16..e0e3dfd 100644 --- a/frontend/app/features/accountAutomation/hooks.test.tsx +++ b/frontend/app/features/accounts/accountAutomationHooks.test.tsx @@ -1,11 +1,11 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail, AccountTaskSettingsResponse } from '../../../types'; -import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api'; -import { useAccountAutomation } from './hooks'; +import type { AccountDetail, AccountTaskSettingsResponse } from '../../../shared/api-contract'; +import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi'; +import { useAccountAutomation } from './accountAutomationHooks'; -vi.mock('./api', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({ +vi.mock('./accountAutomationApi', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({ getAccountTaskSettings: vi.fn(), runAccountTask: vi.fn(), updateAccountTaskSettings: vi.fn(), diff --git a/frontend/app/features/accountAutomation/hooks.ts b/frontend/app/features/accounts/accountAutomationHooks.ts similarity index 97% rename from frontend/app/features/accountAutomation/hooks.ts rename to frontend/app/features/accounts/accountAutomationHooks.ts index 688438f..a890897 100644 --- a/frontend/app/features/accountAutomation/hooks.ts +++ b/frontend/app/features/accounts/accountAutomationHooks.ts @@ -1,8 +1,8 @@ import { useCallback, useEffect, useRef, useState } from 'react'; -import type { AccountTaskSettings, AccountTaskSummary } from '../../../types'; -import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api'; -import { accountTaskErrorMessage, buildAccountTaskDefaults, canStartAccountTask, isAccountTaskAbortError, isCurrentAccountTaskRequest } from './state'; -import type { AccountAutomationOptions, AccountAutomationState, AccountTaskType } from './types'; +import type { AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract'; +import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './accountAutomationApi'; +import { accountTaskErrorMessage, buildAccountTaskDefaults, canStartAccountTask, isAccountTaskAbortError, isCurrentAccountTaskRequest } from './accountAutomationState'; +import type { AccountAutomationOptions, AccountAutomationState, AccountTaskType } from './accountAutomationTypes'; /** AccountAutomation Hook 的完整返回值。 */ export type UseAccountAutomationResult = AccountAutomationState & { diff --git a/frontend/app/features/accountAutomation/state.test.ts b/frontend/app/features/accounts/accountAutomationState.test.ts similarity index 92% rename from frontend/app/features/accountAutomation/state.test.ts rename to frontend/app/features/accounts/accountAutomationState.test.ts index aa95bbe..943bdba 100644 --- a/frontend/app/features/accountAutomation/state.test.ts +++ b/frontend/app/features/accounts/accountAutomationState.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'vitest'; -import type { AccountDetail } from '../../../types'; -import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './state'; +import type { AccountDetail } from '../../../shared/api-contract'; +import { buildAccountTaskDefaults, canStartAccountTask, isCurrentAccountTaskRequest } from './accountAutomationState'; // accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。 const accountFixture: AccountDetail = { diff --git a/frontend/app/features/accountAutomation/state.ts b/frontend/app/features/accounts/accountAutomationState.ts similarity index 94% rename from frontend/app/features/accountAutomation/state.ts rename to frontend/app/features/accounts/accountAutomationState.ts index 158db82..d9e5352 100644 --- a/frontend/app/features/accountAutomation/state.ts +++ b/frontend/app/features/accounts/accountAutomationState.ts @@ -1,5 +1,5 @@ -import type { AccountDetail, AccountTaskSettings } from '../../../types'; -import type { AccountTaskType } from './types'; +import type { AccountDetail, AccountTaskSettings } from '../../../shared/api-contract'; +import type { AccountTaskType } from './accountAutomationTypes'; /** 根据账号详情创建任务设置初始草稿。 */ export const buildAccountTaskDefaults = (account: AccountDetail): AccountTaskSettings => ({ diff --git a/frontend/app/features/accountAutomation/types.ts b/frontend/app/features/accounts/accountAutomationTypes.ts similarity index 95% rename from frontend/app/features/accountAutomation/types.ts rename to frontend/app/features/accounts/accountAutomationTypes.ts index 05c9a0c..05afa7f 100644 --- a/frontend/app/features/accountAutomation/types.ts +++ b/frontend/app/features/accounts/accountAutomationTypes.ts @@ -1,4 +1,4 @@ -import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../types'; +import type { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../../../shared/api-contract'; /** 账号任务类型。 */ export type AccountTaskType = 'auto_rate' | 'auto_polish'; diff --git a/frontend/components/accountBindings.test.ts b/frontend/app/features/accounts/accountBindings.test.ts similarity index 100% rename from frontend/components/accountBindings.test.ts rename to frontend/app/features/accounts/accountBindings.test.ts diff --git a/frontend/components/accountBindings.ts b/frontend/app/features/accounts/accountBindings.ts similarity index 100% rename from frontend/components/accountBindings.ts rename to frontend/app/features/accounts/accountBindings.ts diff --git a/frontend/app/features/accounts/api.ts b/frontend/app/features/accounts/api.ts index 0fda71f..1f28519 100644 --- a/frontend/app/features/accounts/api.ts +++ b/frontend/app/features/accounts/api.ts @@ -1,31 +1,325 @@ -// 账号 feature 只通过本适配层访问账号相关网络接口,页面不再直接依赖共享 API 文件。 -export { - cancelPasswordLogin, - checkPasswordLoginStatus, - checkQRLoginStatus, - completeQRVerification, - deleteAccount, - generateQRLogin, - getAccountAISettings, - getAccountBindings, - getAccountDetails, - getAccountRuntimeStatuses, - getAllAISettings, - getLongLoginSettings, - getNotificationChannels, - passwordLogin, - refreshAccountProfile, - setLongLoginSettings, - updateAccountAISettings, - updateAccountPauseDuration, - updateAccountSettings, - updateAccountStatus, -} from '../../../services/api'; +import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client'; +import { + SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse, + AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, + Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, + NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, + CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse +} from '../../../shared/api-contract'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; +// Accounts +// addAccount 新增账号。 +export const addAccount = async (id: string, value: string, loginMethod?: string): Promise => { + return post('/api/v1/accounts', { id, value, login_method: loginMethod }); +}; -// 账号 feature 重新导出接口返回类型,保持页面与网络契约的依赖方向稳定。 -export type { - AccountRuntimeStatus, - LongLoginSettings, - PasswordLoginStartResponse, - PasswordLoginStatusResponse, -} from '../../../services/api'; +// accountAvatarURL 生成账号头像地址。 +const accountAvatarURL = (item: AccountSummaryResponse, version: string): string => { + // raw 原始值,用于当前 API 处理流程。 + const raw = item.avatar_url || ''; + if (!raw) return ''; + + try { + // url 解析后的地址,用于当前 API 处理流程。 + const url = new URL(raw, window.location.origin); + if (url.hostname.endsWith('alicdn.com')) { + url.searchParams.set('_v', version); + } + return url.toString(); + } catch { + return raw; + } +}; + +// getAccountDetails 读取账号详情。 +export const getAccountDetails = async (options?: RequestControlOptions): Promise => { + // data 数据,用于当前 API 处理流程。 + const response = await get('/api/v1/accounts/details', undefined, options); + // data 是兼容数组、null 和历史 data 包裹后的账号摘要列表。 + const data = collectionFrom(response, ['data', 'accounts', 'details']); + // avatarVersion 头像缓存版本,用于当前 API 处理流程。 + const avatarVersion = Date.now().toString(); + return data.map(/* 当前回调用于处理集合元素或接口响应。 */ item => ({ + id: item.id, + cookie_configured: item.has_cookie === true, + enabled: item.enabled, + auto_confirm: item.auto_confirm, + remark: item.remark, + pause_duration: item.pause_duration, + paused_until: Number(item.paused_until || 0), + paused: item.paused === true, + username: item.username || '', + login_password_configured: undefined, + show_browser: item.show_browser === true || item.show_browser === 1 || item.show_browser === '1' || item.show_browser === 'true', + nickname: item.nickname || item.remark || `账号 ${item.id.substring(0,6)}`, + avatar_url: accountAvatarURL(item, avatarVersion), + profile_error: item.profile_error || '', + ai_enabled: false, + auto_rate_enabled: item.auto_rate_enabled, + rate_content: item.rate_content || '不错的买家,交易愉快', + auto_polish_enabled: item.auto_polish_enabled, + polish_time: item.polish_time || '03:00', + last_rate_scan_at: Number(item.last_rate_scan_at || 0), + last_polish_date: item.last_polish_date || '', + last_polish_at: Number(item.last_polish_at || 0), + })); +}; + +// getAccountTaskSettings 读取账号计划任务设置。 +export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise => + get(`/api/v1/account-tasks/${id}`, undefined, options); + +// updateAccountTaskSettings 更新账号计划任务设置。 +export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise => + put(`/api/v1/account-tasks/${id}`, settings, options); + +// runAccountTask 立即执行账号计划任务。 +export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise => + post(`/api/v1/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options }); + + +export interface AccountRuntimeStatus { + /** state 表示状态。 */ state: NonNullable; + /** message 表示消息数据。 */ message?: string; + /** connected 表示连接状态。 */ connected: boolean; + /** failures 表示失败次数。 */ failures: number; + /** updated_at 表示最后更新时间。 */ updated_at: string; +} + +// getAccountRuntimeStatuses 读取账号运行状态。 +export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise> => { + const response = await get('/api/v1/accounts/runtime-status', undefined, options); + // statuses 是兼容直接映射、statuses 包裹和 null 的运行状态索引。 + const statuses = objectFrom>(response, ['statuses', 'data', 'result']); + return statuses || {}; +}; + +// generateQRLogin 生成二维码登录会话。 +export const generateQRLogin = async (options?: RequestControlOptions): Promise => { + // 风控后匿名 token 接口可能超过通用的 30 秒请求窗口;后端总生成窗口为 2 分钟。 + return post('/api/v1/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 }); +}; + +// checkQRLoginStatus 查询二维码登录状态。 +export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise => { + return get(`/api/v1/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 }); +}; + +// completeQRVerification 完成二维码登录验证。 +export const completeQRVerification = async ( + sessionId: string, + targetAccountId?: string, +): Promise => { + return post(`/api/v1/qr-login/complete-verification/${sessionId}`, { + target_account_id: targetAccountId || '', + }); +}; + + + + + + +// updateAccountStatus 更新账号状态。 +export const updateAccountStatus = async (id: string, enabled: boolean): Promise => { + return put(`/api/v1/accounts/${id}/status`, { enabled }); +}; + +// deleteAccount 删除账号。 +export const deleteAccount = async (id: string): Promise => { + return del(`/api/v1/accounts/${id}`); +}; + +// updateAccountRemark 更新账号备注。 +export const updateAccountRemark = async (id: string, remark: string): Promise => { + return put(`/api/v1/accounts/${id}/remark`, { remark }); +}; + +// updateAccountAutoConfirm 更新账号自动确认设置。 +export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise => { + return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm }); +}; + +// updateAccountPauseDuration 更新账号暂停时长。 +export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise => { + return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options); +}; + +// updateAccountCookie 更新账号登录凭证。 +export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise => { + return put(`/api/v1/accounts/${id}`, { id, value, login_method: loginMethod }); +}; + +export interface AccountSettingsUpdate { + /** cookie 表示登录凭证。 */ cookie?: string; + /** remark 表示备注。 */ remark?: string; + /** auto_confirm 表示自动确认状态。 */ auto_confirm?: boolean; + /** pause_duration 表示暂停时长。 */ pause_duration?: number; + /** username 表示用户名。 */ username?: string; + /** login_password 表示登录密码。 */ login_password?: string; + /** clear_password 表示是否清理登录密码。 */ clear_password?: boolean; + /** show_browser 表示是否显示浏览器。 */ show_browser?: boolean; + /** channel_ids 表示通知渠道标识列表。 */ channel_ids?: number[]; +} + +// updateAccountSettings 更新账号设置。 +export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise => { + return put(`/api/v1/accounts/${id}/settings`, data, options); +}; + +export interface LongLoginSettings { + /** can_open_long_login 表示是否允许开启长期登录。 */ can_open_long_login: boolean; + /** enabled 表示启用状态。 */ enabled: boolean; +} + +// getLongLoginSettings 读取长期登录设置。 +export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise => { + return get(`/api/v1/accounts/${id}/long-login`, undefined, options); +}; + +// setLongLoginSettings 设置长期登录开关。 +export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise => { + return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options); +}; + +export interface PasswordLoginStartResponse { + /** success 表示是否成功。 */ success: boolean; + /** session_id 表示会话标识。 */ session_id?: string; + /** status 表示状态值。 */ status?: 'processing' | 'failed'; + /** message 表示消息数据。 */ message?: string; +} + +export interface PasswordLoginStatusResponse { + /** status 表示状态值。 */ status: 'processing' | 'success' | 'failed' | 'verification_required' | 'not_found' | 'error'; + /** message 表示消息数据。 */ message?: string; + /** account_id 表示账号标识。 */ account_id?: string; + /** is_new_account 表示是否为新账号。 */ is_new_account?: boolean; + /** cookie_count 表示登录凭证数量。 */ cookie_count?: number; + /** verification_url 表示验证地址。 */ verification_url?: string; + /** screenshot_path 表示验证截图路径。 */ screenshot_path?: string; + /** qr_code_url 表示二维码地址。 */ qr_code_url?: string; + /** error 表示错误信息。 */ error?: string; + /** reason 表示失败原因。 */ reason?: string; +} + +// passwordLogin 执行密码登录。 +export const passwordLogin = async (data: { + /** account_id 表示账号标识。 */ account_id: string; + /** account 表示账号。 */ account: string; + /** password 表示密码。 */ password: string; + /** show_browser 表示是否显示浏览器。 */ show_browser?: boolean; +}, options?: RequestControlOptions): Promise => { + return post('/api/v1/password-login', data, options); +}; + +// checkPasswordLoginStatus 查询密码登录状态。 +export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise => { + return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 }); +}; + +// cancelPasswordLogin 取消密码登录。 +export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise => { + return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options); +}; + +// refreshAccountProfile 刷新账号资料。 +export const refreshAccountProfile = async (id: string): Promise => { + return post(`/api/v1/accounts/${id}/refresh-profile`, {}); +}; + +// updateAccountLoginInfo 更新账号登录信息。 +export const updateAccountLoginInfo = async (id: string, data: { + /** username 表示用户名。 */ username?: string; + /** login_password 表示登录密码。 */ login_password?: string; + /** clear_password 表示是否清理登录密码。 */ clear_password?: boolean; + /** show_browser 表示是否显示浏览器。 */ show_browser?: boolean; +}): Promise => { + return put(`/api/v1/accounts/${id}/login-info`, data); +}; + +// getAllAISettings 读取全部人工智能设置。 +export const getAllAISettings = async (options?: RequestControlOptions): Promise> => { + const response = await get('/api/v1/settings/ai-reply', undefined, options); + // settings 是兼容直接映射、data 包裹和 null 的账号 AI 设置索引。 + return objectFrom>(response, ['settings', 'data', 'result']) || {}; +}; + + +// getAccountAISettings 读取账号人工智能设置。 +export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise => { + return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options); +} + +// updateAccountAISettings 更新账号人工智能设置。 +export const updateAccountAISettings = async (cookieId: string, settings: Partial, options?: RequestControlOptions): Promise => { + // payload 请求载荷,用于当前 API 处理流程。 + const payload = { + ai_enabled: settings.ai_enabled ?? false, + max_discount_percent: settings.max_discount_percent ?? 10, + max_discount_amount: settings.max_discount_amount ?? 100, + max_bargain_rounds: settings.max_bargain_rounds ?? 3, + custom_prompts: settings.custom_prompts ?? '' + }; + return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options); +} + + +// parseNotificationEventTypes 解析通知事件类型。 +const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => { + if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[]; + if (typeof raw !== 'string' || !raw.trim()) return []; + try { + // parsed 转换后的数值,用于当前 API 处理流程。 + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[]; + } catch { + // fall back to legacy comma/semicolon separated values + } + return raw.split(/[,\s;]+/).map(/* 当前回调用于处理集合元素或接口响应。 */ v => v.trim()).filter(Boolean) as NotificationEventType[]; +}; + +// stringifyNotificationEventTypes 序列化通知事件类型。 +const stringifyNotificationEventTypes = (events?: NotificationEventType[]): string => { + // clean 清理后的事件类型列表,用于当前 API 处理流程。 + const clean = Array.from(new Set((events || []).filter(Boolean))); + return clean.length > 0 ? JSON.stringify(clean) : ''; +}; + +// getNotificationChannels 读取通知渠道。 +export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationChannel[] }> => { + // result 接口响应结果,用于当前 API 处理流程。 + const result = await get('/api/v1/notifications/channels', undefined, options); + // channels 通知渠道列表,用于当前 API 处理流程。 + const channels = collectionFrom(result, ['data', 'channels', 'items']).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: NotificationChannelResponse) => { + // parsedConfig 解析后的通知配置,用于当前 API 处理流程。 + let parsedConfig; + try { + parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config; + } catch { + parsedConfig = {}; + } + // normalizedType 是兼容旧渠道别名后的前端渠道类型。 + const normalizedType = (item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type)) as NotificationChannel['type']; + return { + id: String(item.id), + name: item.name, + type: normalizedType, + config: parsedConfig, + event_types: parseNotificationEventTypes(item.event_types), + enabled: item.enabled, + created_at: item.created_at, + updated_at: item.updated_at, + }; + }); + return { success: true, data: channels }; +} + + +// 账号 ↔ 渠道 绑定(覆盖式) +export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise => { + // response 是兼容直接绑定对象、data 包裹和 null 的通知绑定响应。 + const response = await get(`/api/v1/notifications/accounts/${cookieId}/bindings`, undefined, options); + // result 是去除历史包裹后的账号通知绑定对象。 + const result = objectFrom>(response, ['data', 'result']) || {}; + return Array.isArray(result.channel_ids) ? result.channel_ids : []; +} diff --git a/frontend/app/features/accounts/components/AccountAISettingsModal.tsx b/frontend/app/features/accounts/components/AccountAISettingsModal.tsx index 18b06c8..cb2c746 100644 --- a/frontend/app/features/accounts/components/AccountAISettingsModal.tsx +++ b/frontend/app/features/accounts/components/AccountAISettingsModal.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { createPortal } from 'react-dom'; import { Bot, Loader2, Save, Settings, X } from 'lucide-react'; -import type { AccountDetail, AIReplySettings } from '../../../../types'; +import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract'; // AccountAISettingsModalProps 描述账号 AI 设置弹窗需要的状态和回调。 export interface AccountAISettingsModalProps { diff --git a/frontend/components/AccountAutomationModal.tsx b/frontend/app/features/accounts/components/AccountAutomationModal.tsx similarity index 98% rename from frontend/components/AccountAutomationModal.tsx rename to frontend/app/features/accounts/components/AccountAutomationModal.tsx index 4af41c3..090c9b7 100644 --- a/frontend/components/AccountAutomationModal.tsx +++ b/frontend/app/features/accounts/components/AccountAutomationModal.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react'; -import { AccountDetail, AccountTaskSettings } from '../types'; -import { useAccountAutomation } from '../app/features/accountAutomation/hooks'; +import { AccountDetail, AccountTaskSettings } from '../../../../shared/api-contract'; +import { useAccountAutomation } from '../accountAutomationHooks'; interface Props { /** account 表示账号。 */ account: AccountDetail; diff --git a/frontend/app/features/accounts/components/AccountCard.tsx b/frontend/app/features/accounts/components/AccountCard.tsx index 950ff87..4da234d 100644 --- a/frontend/app/features/accounts/components/AccountCard.tsx +++ b/frontend/app/features/accounts/components/AccountCard.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { AlertCircle, Bot, CalendarClock, Check, Clock, Loader2, MessageCircle, Power, QrCode, RefreshCw, Sparkles, Trash2, User, Edit2 } from 'lucide-react'; -import type { AccountDetail } from '../../../../types'; +import type { AccountDetail } from '../../../../shared/api-contract'; import { accountRuntimePresentation } from '../runtime'; // AccountCardProps 描述账号卡片展示所需的数据和动作。 diff --git a/frontend/app/features/accounts/components/AccountDeleteDialog.tsx b/frontend/app/features/accounts/components/AccountDeleteDialog.tsx index cc1f16f..e7a9d49 100644 --- a/frontend/app/features/accounts/components/AccountDeleteDialog.tsx +++ b/frontend/app/features/accounts/components/AccountDeleteDialog.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { createPortal } from 'react-dom'; import { AlertCircle, Loader2, Trash2, X } from 'lucide-react'; -import type { AccountDetail } from '../../../../types'; +import type { AccountDetail } from '../../../../shared/api-contract'; // AccountDeleteDialogProps 描述账号删除确认框需要的状态和回调。 export interface AccountDeleteDialogProps { diff --git a/frontend/app/features/accounts/components/AccountEditModal.tsx b/frontend/app/features/accounts/components/AccountEditModal.tsx index 57f8c9c..9d2c772 100644 --- a/frontend/app/features/accounts/components/AccountEditModal.tsx +++ b/frontend/app/features/accounts/components/AccountEditModal.tsx @@ -1,8 +1,8 @@ import React from 'react'; import { createPortal } from 'react-dom'; import { Bell, Check, Clock, Eye, EyeOff, Key, Loader2, X } from 'lucide-react'; -import { SquareQRCode } from '../../../../components/SquareQRCode'; -import type { NotificationChannel } from '../../../../types'; +import { SquareQRCode } from './SquareQRCode'; +import type { NotificationChannel } from '../../../../shared/api-contract'; import type { AccountEditForm, AccountEditModalProps } from '../types'; // AccountEditModal 负责账号备注、暂停、登录信息和通知绑定的编辑界面。 diff --git a/frontend/app/features/accounts/components/AccountQRCodeModal.tsx b/frontend/app/features/accounts/components/AccountQRCodeModal.tsx index 8538a5b..832dd02 100644 --- a/frontend/app/features/accounts/components/AccountQRCodeModal.tsx +++ b/frontend/app/features/accounts/components/AccountQRCodeModal.tsx @@ -1,9 +1,9 @@ import React from 'react'; import { createPortal } from 'react-dom'; import { Check, Loader2, X } from 'lucide-react'; -import type { AccountDetail } from '../../../../types'; -import { RiskVerificationPanel } from '../../../../components/RiskVerificationPanel'; -import { SquareQRCode } from '../../../../components/SquareQRCode'; +import type { AccountDetail } from '../../../../shared/api-contract'; +import { RiskVerificationPanel } from './RiskVerificationPanel'; +import { SquareQRCode } from './SquareQRCode'; // AccountQRCodeModalProps 描述二维码登录弹窗的展示状态和关闭回调。 export interface AccountQRCodeModalProps { diff --git a/frontend/components/RiskVerificationPanel.test.tsx b/frontend/app/features/accounts/components/RiskVerificationPanel.test.tsx similarity index 100% rename from frontend/components/RiskVerificationPanel.test.tsx rename to frontend/app/features/accounts/components/RiskVerificationPanel.test.tsx diff --git a/frontend/components/RiskVerificationPanel.tsx b/frontend/app/features/accounts/components/RiskVerificationPanel.tsx similarity index 100% rename from frontend/components/RiskVerificationPanel.tsx rename to frontend/app/features/accounts/components/RiskVerificationPanel.tsx diff --git a/frontend/components/SquareQRCode.test.tsx b/frontend/app/features/accounts/components/SquareQRCode.test.tsx similarity index 100% rename from frontend/components/SquareQRCode.test.tsx rename to frontend/app/features/accounts/components/SquareQRCode.test.tsx diff --git a/frontend/components/SquareQRCode.tsx b/frontend/app/features/accounts/components/SquareQRCode.tsx similarity index 100% rename from frontend/components/SquareQRCode.tsx rename to frontend/app/features/accounts/components/SquareQRCode.tsx diff --git a/frontend/app/features/accounts/components/accountComponents.test.tsx b/frontend/app/features/accounts/components/accountComponents.test.tsx index a465ba2..ae74b6f 100644 --- a/frontend/app/features/accounts/components/accountComponents.test.tsx +++ b/frontend/app/features/accounts/components/accountComponents.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { fireEvent, render, screen, cleanup } from '@testing-library/react'; import { afterEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail, AIReplySettings } from '../../../../types'; +import type { AccountDetail, AIReplySettings } from '../../../../shared/api-contract'; import { AccountAISettingsModal } from './AccountAISettingsModal'; import { AccountCard } from './AccountCard'; import { AccountDeleteDialog } from './AccountDeleteDialog'; diff --git a/frontend/app/features/accounts/hooks.test.tsx b/frontend/app/features/accounts/hooks.test.tsx index 4860294..04ec298 100644 --- a/frontend/app/features/accounts/hooks.test.tsx +++ b/frontend/app/features/accounts/hooks.test.tsx @@ -2,7 +2,7 @@ import { renderHook, waitFor } from '@testing-library/react'; import { act } from 'react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api'; import { useAccountsData } from './hooks'; diff --git a/frontend/app/features/accounts/hooks.ts b/frontend/app/features/accounts/hooks.ts index 8cb711a..c819877 100644 --- a/frontend/app/features/accounts/hooks.ts +++ b/frontend/app/features/accounts/hooks.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react'; import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api'; -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; import { mergeAccountRuntimeStatuses } from './runtime'; import type { AccountAISettingsState } from './types'; diff --git a/frontend/components/AccountList.test.tsx b/frontend/app/features/accounts/pages/AccountList.test.tsx similarity index 89% rename from frontend/components/AccountList.test.tsx rename to frontend/app/features/accounts/pages/AccountList.test.tsx index fc0c66a..858b027 100644 --- a/frontend/components/AccountList.test.tsx +++ b/frontend/app/features/accounts/pages/AccountList.test.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail } from '../types'; +import type { AccountDetail } from '../../../../shared/api-contract'; // accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。 const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({ @@ -26,7 +26,7 @@ const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试 pollCallbacks: null as Record void> | null, })); -vi.mock('../app/features/accounts/hooks', /* accountsHookMockFactory 提供账号列表数据 Hook 替身。 */ () => ({ +vi.mock('../hooks', /* accountsHookMockFactory 提供账号列表数据 Hook 替身。 */ () => ({ useAccountsData: /* useAccountsDataMock 返回固定账号列表和刷新操作。 */ () => ({ accounts: accountListMocks.accounts, setAccounts: accountListMocks.setAccounts, @@ -35,7 +35,7 @@ vi.mock('../app/features/accounts/hooks', /* accountsHookMockFactory 提供账 }), })); -vi.mock('../app/features/accounts/submoduleHooks', /* submoduleHookMockFactory 提供账号弹窗状态 Hook 替身。 */ () => ({ +vi.mock('../submoduleHooks', /* submoduleHookMockFactory 提供账号弹窗状态 Hook 替身。 */ () => ({ useAccountSubmodules: /* useAccountSubmodulesMock 返回不阻断页面渲染的子模块状态。 */ () => ({ longLogin: false, notifChannels: [], @@ -63,7 +63,7 @@ vi.mock('../app/features/accounts/submoduleHooks', /* submoduleHookMockFactory }), })); -vi.mock('../app/features/accounts/api', /* accountApiMockFactory 提供账号页面 API 替身。 */ () => ({ +vi.mock('../api', /* accountApiMockFactory 提供账号页面 API 替身。 */ () => ({ updateAccountStatus: accountListMocks.updateAccountStatus, deleteAccount: accountListMocks.deleteAccount, generateQRLogin: accountListMocks.generateQRLogin, @@ -72,7 +72,7 @@ vi.mock('../app/features/accounts/api', /* accountApiMockFactory 提供账号页 refreshAccountProfile: accountListMocks.refreshAccountProfile, })); -vi.mock('../app/features/accounts/qrPolling', /* qrPollingMockFactory 提供二维码轮询器替身。 */ () => ({ +vi.mock('../qrPolling', /* qrPollingMockFactory 提供二维码轮询器替身。 */ () => ({ createLatestRequestGate: /* requestGateFactory 创建二维码请求代次门禁。 */ () => ({ next: accountListMocks.requestNext, isCurrent: accountListMocks.requestIsCurrent, @@ -84,7 +84,7 @@ vi.mock('../app/features/accounts/qrPolling', /* qrPollingMockFactory 提供二 }), })); -vi.mock('../app/features/accounts/components/AccountCard', /* accountCardMockFactory 提供账号卡片交互替身。 */ () => { +vi.mock('../components/AccountCard', /* accountCardMockFactory 提供账号卡片交互替身。 */ () => { // AccountCardMock 渲染页面测试需要的账号操作入口。 const AccountCardMock: React.FC = (props /* props 表示账号卡片及其事件回调。 */) => (
@@ -98,7 +98,7 @@ vi.mock('../app/features/accounts/components/AccountCard', /* accountCardMockFac return { AccountCard: AccountCardMock }; }); -vi.mock('../app/features/accounts/components/AccountDeleteDialog', /* deleteDialogMockFactory 提供删除确认弹窗替身。 */ () => { +vi.mock('../components/AccountDeleteDialog', /* deleteDialogMockFactory 提供删除确认弹窗替身。 */ () => { // AccountDeleteDialogMock 展示删除错误并暴露确认/关闭操作。 const AccountDeleteDialogMock: React.FC = (props /* props 表示删除弹窗及其操作回调。 */) => (
@@ -110,7 +110,7 @@ vi.mock('../app/features/accounts/components/AccountDeleteDialog', /* deleteDial return { AccountDeleteDialog: AccountDeleteDialogMock }; }); -vi.mock('../app/features/accounts/components/AccountQRCodeModal', /* qrModalMockFactory 提供二维码弹窗替身。 */ () => { +vi.mock('../components/AccountQRCodeModal', /* qrModalMockFactory 提供二维码弹窗替身。 */ () => { // AccountQRCodeModalMock 展示二维码状态并暴露关闭操作。 const AccountQRCodeModalMock: React.FC = (props /* props 表示二维码弹窗及其操作回调。 */) => (
@@ -121,11 +121,11 @@ vi.mock('../app/features/accounts/components/AccountQRCodeModal', /* qrModalMock return { AccountQRCodeModal: AccountQRCodeModalMock }; }); -vi.mock('../app/features/accounts/components/AccountEditModal', /* editModalMockFactory 提供账号编辑弹窗替身。 */ () => ({ +vi.mock('../components/AccountEditModal', /* editModalMockFactory 提供账号编辑弹窗替身。 */ () => ({ AccountEditModal: /* AccountEditModalMock 表示账号编辑弹窗替身。 */ () => null, })); -vi.mock('../app/features/accounts/components/AccountAISettingsModal', /* aiModalMockFactory 提供 AI 设置弹窗替身。 */ () => ({ +vi.mock('../components/AccountAISettingsModal', /* aiModalMockFactory 提供 AI 设置弹窗替身。 */ () => ({ AccountAISettingsModal: /* AccountAISettingsModalMock 表示 AI 设置弹窗替身。 */ () => null, })); diff --git a/frontend/components/AccountList.tsx b/frontend/app/features/accounts/pages/AccountList.tsx similarity index 93% rename from frontend/components/AccountList.tsx rename to frontend/app/features/accounts/pages/AccountList.tsx index 394e3de..2215cbd 100644 --- a/frontend/components/AccountList.tsx +++ b/frontend/app/features/accounts/pages/AccountList.tsx @@ -1,22 +1,22 @@ import React, { useState } from 'react'; import { createPortal } from 'react-dom'; -import { AccountDetail } from '../types'; +import { AccountDetail } from '../../../../shared/api-contract'; import { updateAccountStatus, deleteAccount, refreshAccountProfile, -} from '../app/features/accounts/api'; +} from '../api'; import { Loader2, QrCode, User } from 'lucide-react'; -import AccountAutomationModal from './AccountAutomationModal'; -import { AccountEditModal } from '../app/features/accounts/components/AccountEditModal'; -import { AccountAISettingsModal } from '../app/features/accounts/components/AccountAISettingsModal'; -import { AccountCard } from '../app/features/accounts/components/AccountCard'; -import { AccountDeleteDialog } from '../app/features/accounts/components/AccountDeleteDialog'; -import { AccountQRCodeModal } from '../app/features/accounts/components/AccountQRCodeModal'; -import { useAccountsData } from '../app/features/accounts/hooks'; -import { useAccountQRCodeLogin } from '../app/features/accounts/qrLogin'; -import { useAccountSubmodules, type AccountModalType } from '../app/features/accounts/submoduleHooks'; -import type { AccountEditForm } from '../app/features/accounts/types'; +import AccountAutomationModal from '../components/AccountAutomationModal'; +import { AccountEditModal } from '../components/AccountEditModal'; +import { AccountAISettingsModal } from '../components/AccountAISettingsModal'; +import { AccountCard } from '../components/AccountCard'; +import { AccountDeleteDialog } from '../components/AccountDeleteDialog'; +import { AccountQRCodeModal } from '../components/AccountQRCodeModal'; +import { useAccountsData } from '../hooks'; +import { useAccountQRCodeLogin } from '../qrLogin'; +import { useAccountSubmodules, type AccountModalType } from '../submoduleHooks'; +import type { AccountEditForm } from '../types'; // AccountList 渲染账号列表组件。 const AccountList: React.FC = () => { diff --git a/frontend/app/features/accounts/qrLogin.test.tsx b/frontend/app/features/accounts/qrLogin.test.tsx index 0923da6..a489236 100644 --- a/frontend/app/features/accounts/qrLogin.test.tsx +++ b/frontend/app/features/accounts/qrLogin.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; // qrLoginMocks 保存二维码登录协调器测试使用的接口替身。 const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({ diff --git a/frontend/app/features/accounts/qrLogin.ts b/frontend/app/features/accounts/qrLogin.ts index 70d0a4e..c82a8b6 100644 --- a/frontend/app/features/accounts/qrLogin.ts +++ b/frontend/app/features/accounts/qrLogin.ts @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react'; -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; import { checkQRLoginStatus, completeQRVerification, generateQRLogin } from './api'; import { createLatestRequestGate, createQRLoginPoller } from './qrPolling'; diff --git a/frontend/components/qrPolling.test.ts b/frontend/app/features/accounts/qrPolling.test.ts similarity index 100% rename from frontend/components/qrPolling.test.ts rename to frontend/app/features/accounts/qrPolling.test.ts diff --git a/frontend/app/features/accounts/runtime.test.ts b/frontend/app/features/accounts/runtime.test.ts index 557a220..33d934f 100644 --- a/frontend/app/features/accounts/runtime.test.ts +++ b/frontend/app/features/accounts/runtime.test.ts @@ -1,11 +1,10 @@ import { describe, expect, test } from 'vitest'; -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; import { accountRuntimePresentation, isOlderStatus, mergeAccountRuntimeStatuses } from './runtime'; // account 创建运行状态测试使用的最小账号对象。 const account = (overrides: Partial = {}): AccountDetail => ({ id: 'account-1', - value: 'cookie', enabled: true, auto_confirm: false, ...overrides, diff --git a/frontend/app/features/accounts/runtime.ts b/frontend/app/features/accounts/runtime.ts index 464d26a..491dfb7 100644 --- a/frontend/app/features/accounts/runtime.ts +++ b/frontend/app/features/accounts/runtime.ts @@ -1,5 +1,5 @@ import type { AccountRuntimeStatus } from './api'; -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; import type { AccountRuntimePresentation } from './types'; // isOlderStatus 判断传入的运行时快照是否早于账号当前已展示的快照。 diff --git a/frontend/app/features/accounts/state.test.ts b/frontend/app/features/accounts/state.test.ts index 73dfa6e..7ca819f 100644 --- a/frontend/app/features/accounts/state.test.ts +++ b/frontend/app/features/accounts/state.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, diff --git a/frontend/app/features/accounts/state.ts b/frontend/app/features/accounts/state.ts index ce9359d..bb415cd 100644 --- a/frontend/app/features/accounts/state.ts +++ b/frontend/app/features/accounts/state.ts @@ -1,4 +1,4 @@ -import type { AccountDetail } from '../../../types'; +import type { AccountDetail } from '../../../shared/api-contract'; import type { PasswordLoginStatusResponse } from './api'; import type { AccountEditForm, PasswordLoginView } from './types'; diff --git a/frontend/app/features/accounts/submoduleHooks.test.tsx b/frontend/app/features/accounts/submoduleHooks.test.tsx index 2a5ca63..6bc724a 100644 --- a/frontend/app/features/accounts/submoduleHooks.test.tsx +++ b/frontend/app/features/accounts/submoduleHooks.test.tsx @@ -2,7 +2,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; import type { Dispatch, SetStateAction } from 'react'; -import type { AccountDetail, AIReplySettings } from '../../../types'; +import type { AccountDetail, AIReplySettings } from '../../../shared/api-contract'; import { cancelPasswordLogin, checkPasswordLoginStatus, @@ -101,6 +101,7 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知 expect(hook.result.current.longLogin.canOpen).toBe(true); expect(hook.result.current.notifChannels).toHaveLength(1); expect(hook.result.current.selectedChannelIds).toEqual([1]); + expect(setEditForm).toHaveBeenCalledWith(expect.objectContaining({ cookie: '', login_password: '' })); await act( // toggleAction 切换通知渠道绑定。 () => hook.result.current.toggleNotificationChannel(2), diff --git a/frontend/app/features/accounts/submoduleHooks.ts b/frontend/app/features/accounts/submoduleHooks.ts index 53acf5e..f9d3350 100644 --- a/frontend/app/features/accounts/submoduleHooks.ts +++ b/frontend/app/features/accounts/submoduleHooks.ts @@ -1,9 +1,9 @@ import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react'; -import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types'; +import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract'; import { cancelPasswordLogin, checkPasswordLoginStatus, getAccountAISettings, getAccountBindings, getLongLoginSettings, getNotificationChannels, passwordLogin, setLongLoginSettings, updateAccountAISettings, updateAccountPauseDuration, updateAccountSettings } from './api'; import { buildAccountLoginInfoUpdate, isCurrentAccountRequest, passwordLoginViewFromStatus, shouldUpdateAccountPause } from './state'; import type { AccountEditForm, LongLoginState, PasswordLoginView } from './types'; -import { shouldSaveNotificationBindings } from '../../../components/accountBindings'; +import { shouldSaveNotificationBindings } from './accountBindings'; /** AccountList 当前编辑弹窗类型。 */ export type AccountModalType = 'edit' | 'ai-settings' | null; @@ -124,7 +124,8 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct clearPasswordTimer(); setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' }); setEditingAccount(account); - setEditForm({ remark: account.remark || '', cookie: account.value || '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: account.login_password || '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false }); + // 摘要接口不会返回 Cookie 或密码明文;编辑表单只接收本次用户主动输入的秘密。 + setEditForm({ remark: account.remark || '', cookie: '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: '', show_browser: account.show_browser || false, showLoginPassword: false, clear_password: false }); setActiveModal('edit'); setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' }); // longLoginResult 保存长登录设置读取结果。 @@ -200,7 +201,8 @@ export const useAccountSubmodules = ({ editingAccount, setEditingAccount, setAct // payload 保存需要提交的账号编辑补丁。 const payload: Parameters[1] = {}; if (editForm.remark !== (editingAccount.remark || '')) payload.remark = editForm.remark; - if (editForm.cookie && editForm.cookie !== (editingAccount.value || '')) payload.cookie = editForm.cookie; + // 编辑表单中的 Cookie 只有用户本次输入时才会提交,避免从账号摘要读取或回填明文。 + if (editForm.cookie) payload.cookie = editForm.cookie; if (editForm.auto_confirm !== editingAccount.auto_confirm) payload.auto_confirm = editForm.auto_confirm; if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) payload.pause_duration = editForm.pause_duration; // loginInfo 保存登录字段变更补丁。 diff --git a/frontend/app/features/accounts/types.ts b/frontend/app/features/accounts/types.ts index eb75498..6bb34ef 100644 --- a/frontend/app/features/accounts/types.ts +++ b/frontend/app/features/accounts/types.ts @@ -1,5 +1,5 @@ import type { Dispatch, SetStateAction } from 'react'; -import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../types'; +import type { AccountDetail, AIReplySettings, NotificationChannel } from '../../../shared/api-contract'; // AccountEditForm 描述账号编辑弹窗中的可编辑字段。 export interface AccountEditForm { diff --git a/frontend/services/api.test.ts b/frontend/app/features/apiAdapters.test.ts similarity index 95% rename from frontend/services/api.test.ts rename to frontend/app/features/apiAdapters.test.ts index 8f1ecfd..f935bf0 100644 --- a/frontend/services/api.test.ts +++ b/frontend/app/features/apiAdapters.test.ts @@ -2,45 +2,27 @@ import { afterEach, expect, test, vi } from 'vitest'; import { addAccount, cancelPasswordLogin, - deleteItemPublishBatch, deleteItem, cancelItemPublishBatch, retryFailedItemPublishBatch, checkPasswordLoginStatus, checkQRLoginStatus, completeQRVerification, generateQRLogin, - createNotificationChannel, getAllAISettings, getAccountAISettings, updateAccountAISettings, fetchAIModels, - getAccountDetails, getAccountRuntimeStatuses, updateAccountStatus, - getAutomationIssues, changePassword, createItem, deleteAccount, deleteOrder, deleteShippingRule, updateLoginCredentials, - getItems, getItemDetail, syncItemsFromAccount, - getItemPublishBatches, getItemPublishBatch, startItemPublishBatch, - getNotificationChannels, getMessageNotifications, getAccountBindings, - getOrders, getOrderDetail, updateOrder, - getAdminStats, getDashboardStats, getOrderAnalytics, - getReplyRules, getDefaultReplies, getDefaultReply, updateDefaultReply, deleteDefaultReply, clearDefaultReplyRecords, - getShippingRules, - getShippingRulesPage, - getSystemSettings, getHealth, getCards, createCard, updateCard, deleteCard, getCardDetails, batchCreateCards, appendCardData, - getValidOrders, - publishItem, recommendPublishCategory, previewItemPublishBatch, - logout, - importOrders, + getAllAISettings, getAccountAISettings, updateAccountAISettings, + getAccountDetails, getAccountRuntimeStatuses, updateAccountStatus, deleteAccount, passwordLogin, - resolveAutomationRun, - resolveDeferredAutomationTask, - syncOrders, cancelOrderRefreshJob, syncSingleOrder, manualShipOrder, - updateReplyRule, - deleteReplyRule, updateAccountCookie, updateAccountLoginInfo, updateAccountSettings, updateAccountRemark, updateAccountAutoConfirm, updateAccountPauseDuration, getLongLoginSettings, setLongLoginSettings, refreshAccountProfile, - updateItem, - updateNotificationChannel, deleteNotificationChannel, setMessageNotification, deleteMessageNotification, deleteAccountNotifications, setAccountBindings, testNotificationChannel, - updateSystemSettings, - updateShippingRule, - getChatSessions, getChatSessionPage, - getChatMessages, getChatMessagePage, - sendChatMessage, sendChatImage, - markChatRead, getAccountTaskSettings, updateAccountTaskSettings, - runAccountTask, login, initializeAdmin, verifySession, -} from './api'; + runAccountTask, +} from './accounts/api'; +import { appendCardData, batchCreateCards, createCard, deleteCard, getCardDetails, getCards, updateCard } from './cards/api'; +import { getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions, markChatRead, sendChatImage, sendChatMessage } from './chat/api'; +import { getDashboardStats, getOrderAnalytics, getValidOrders } from './dashboard/api'; +import { createItem, deleteItem, deleteItemPublishBatch, cancelItemPublishBatch, getItemDetail, getItemPublishBatch, getItemPublishBatches, getItems, previewItemPublishBatch, publishItem, recommendPublishCategory, retryFailedItemPublishBatch, startItemPublishBatch, syncItemsFromAccount, updateItem } from './items/api'; +import { createNotificationChannel, deleteAccountNotifications, deleteMessageNotification, deleteNotificationChannel, getAccountBindings, getMessageNotifications, getNotificationChannels, setAccountBindings, setMessageNotification, testNotificationChannel, updateNotificationChannel } from './notifications/api'; +import { cancelOrderRefreshJob, deleteOrder, getAdminStats, getOrderDetail, getOrders, importOrders, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './orders/api'; +import { clearDefaultReplyRecords, deleteDefaultReply, deleteReplyRule, deleteShippingRule, getAutomationIssues, getDefaultReplies, getDefaultReply, getReplyRules, getShippingRules, getShippingRulesPage, resolveAutomationRun, resolveDeferredAutomationTask, updateDefaultReply, updateReplyRule, updateShippingRule } from './rules/api'; +import { initializeAdmin, login, logout, verifySession } from './session/api'; +import { changePassword, fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings } from './settings/api'; +import { getHealth } from './system/api'; afterEach(() => { vi.unstubAllGlobals(); @@ -579,12 +561,43 @@ test('getAccountDetails normalizes show_browser and never exposes password', asy id: 'acc1', username: 'login-user', show_browser: true, - login_password: '', paused_until: 1780000000, paused: true, }); + expect(accounts[0]).not.toHaveProperty('login_password'); + expect(accounts[0]).not.toHaveProperty('value'); } /* 回调函数负责当前业务流程。 */); +test('列表 API 将 null 和历史 data 包裹统一为空数组', async () => { + // fetchMock 依次模拟账号、商品、订单和规则接口的历史空响应。 + const fetchMock = vi.fn() + .mockResolvedValueOnce(jsonResponse(null)) + .mockResolvedValueOnce(jsonResponse({ data: null })) + .mockResolvedValueOnce(jsonResponse(null)) + .mockResolvedValueOnce(jsonResponse({ data: null })); + vi.stubGlobal('fetch', fetchMock); + + await expect(getAccountDetails()).resolves.toEqual([]); + await expect(getItems()).resolves.toEqual([]); + await expect(getOrders()).resolves.toMatchObject({ data: [], total: 0 }); + await expect(getShippingRules()).resolves.toEqual([]); +} /* 回调函数验证列表接口的空集合契约。 */); + +test('列表 API 接受历史命名包裹对象并保持具名 UI 结果', async () => { + // fetchMock 模拟订单、商品、卡密和批次接口各自的历史字段名称。 + const fetchMock = vi.fn() + .mockResolvedValueOnce(jsonResponse({ orders: [{ order_id: 'o-wrap', order_status: 'paid' }] })) + .mockResolvedValueOnce(jsonResponse({ items: [{ cookie_id: 'a1', item_id: 'i1', item_title: '商品' }] })) + .mockResolvedValueOnce(jsonResponse({ cards: [{ id: 1, name: '库存', type: 'data', enabled: true }] })) + .mockResolvedValueOnce(jsonResponse({ batches: [{ id: 'b1', status: 'running' }] })); + vi.stubGlobal('fetch', fetchMock); + + await expect(getOrders()).resolves.toMatchObject({ data: [{ id: 'o-wrap', status: 'pending_ship' }] }); + await expect(getItems()).resolves.toMatchObject([{ id: 'a1-i1' }]); + await expect(getCards()).resolves.toMatchObject([{ id: 1, name: '库存' }]); + await expect(getItemPublishBatches()).resolves.toEqual([{ id: 'b1', status: 'running' }]); +} /* 回调函数验证历史包裹字段的兼容归一。 */); + test('getAccountDetails 归一化头像地址并保留非法地址', /* 当前回调验证头像缓存参数和 URL 兼容边界。 */ async () => { // windowStub 是头像 URL 解析使用的浏览器位置替身。 vi.stubGlobal('window', { location: { origin: 'http://localhost' } }); diff --git a/frontend/app/features/cards/api.ts b/frontend/app/features/cards/api.ts index fe1008f..288a208 100644 --- a/frontend/app/features/cards/api.ts +++ b/frontend/app/features/cards/api.ts @@ -1,12 +1,78 @@ -// 卡密 feature 只通过本适配层访问库存和批量接口,页面不直接依赖共享 API 文件。 -export { - appendCardData, - batchCreateCards, - createCard, - deleteCard, - getCards, - updateCard, -} from '../../../services/api'; +import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client'; +import { + SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse, + AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, + Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, + NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, + CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse +} from '../../../shared/api-contract'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; +// Cards +// normalizeCard 归一化卡密数据。 +const normalizeCard = (item: any): Card => { + // apiConfig 卡密接口配置,用于当前 API 处理流程。 + let apiConfig = item.api_config; + if (typeof apiConfig === 'string' && apiConfig.trim()) { + try { + apiConfig = JSON.parse(apiConfig); + } catch { + apiConfig = undefined; + } + } + return {...item, api_config: apiConfig || undefined} as Card; +}; -// 卡密 feature 重新导出接口响应类型,保持批量结果契约稳定。 -export type { CardAppendResponse, CardBatchResponse } from '../../../types'; +// cardPayload 卡密请求载荷,用于当前 API 处理流程。 +const cardPayload = (data: Partial): Record => ({ + ...data, + api_config: data.api_config ? JSON.stringify(data.api_config) : '', +}); + +// getCards 读取卡密列表。 +export const getCards = async (options?: RequestControlOptions): Promise => { + // res 接口响应结果,用于当前 API 处理流程。 + const res = await get('/api/v1/cards', undefined, options); + // cards 卡密列表,用于当前 API 处理流程。 + const cards = collectionFrom(res, ['cards', 'data', 'items']); + return cards.map(normalizeCard); +}; + +// createCard 创建卡密组。 +export const createCard = async (data: Partial): Promise => { + return post('/api/v1/cards', cardPayload(data)); +}; + +// updateCard 更新卡密组。 +export const updateCard = async (cardId: string | number, data: Partial): Promise => { + return put(`/api/v1/cards/${cardId}`, cardPayload(data)); +}; + +// deleteCard 删除卡密组。 +export const deleteCard = async (cardId: string | number): Promise => { + return del(`/api/v1/cards/${cardId}`); +}; + +// getCardDetails 读取卡密组详情。 +export const getCardDetails = async (cardId: string | number): Promise => { + // card 卡密详情,用于当前 API 处理流程。 + const card = await get(`/api/v1/cards/${cardId}/details`); + return normalizeCard(card); +}; + +// 批量创建卡密组(上传表格) +export const batchCreateCards = async (file: File, options?: RequestControlOptions): Promise => { + // 批量创建接口返回总行数、成功数、失败数和逐行结果。 + // CardBatchResponse 保留旧字段名称,调用方无需转换统计字段。 + // rows 中的 id 只在创建成功时返回。 + // rows 中的 error 只在对应行失败时返回。 + // 表单上传方式和接口路径保持不变。 + // 此处只收紧 TypeScript 响应契约。 + const body = new FormData(); + body.append('file', file); + return postForm('/api/v1/cards/batch', body, options); +}; + +// 往 data 类型卡密组批量追加卡密号 +export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise => { + return post(`/api/v1/cards/${cardId}/append-data`, { content }, options); +}; diff --git a/frontend/app/features/cards/batchState.test.ts b/frontend/app/features/cards/batchState.test.ts index 33172ae..6b99d9e 100644 --- a/frontend/app/features/cards/batchState.test.ts +++ b/frontend/app/features/cards/batchState.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import type { Card } from '../../../types'; +import type { Card } from '../../../shared/api-contract'; import { canSubmitAppend, filterCards, isCurrentCardRequest, previewAppendContent } from './batchState'; // cards 是卡密筛选测试使用的最小卡密组列表。 diff --git a/frontend/app/features/cards/batchState.ts b/frontend/app/features/cards/batchState.ts index c5b25f5..ab9f254 100644 --- a/frontend/app/features/cards/batchState.ts +++ b/frontend/app/features/cards/batchState.ts @@ -1,4 +1,4 @@ -import type { Card } from '../../../types'; +import type { Card } from '../../../shared/api-contract'; // filterCards 按类型和名称筛选卡密组,两个条件同时满足才保留。 export const filterCards = ( diff --git a/frontend/app/features/cards/cardActions.test.tsx b/frontend/app/features/cards/cardActions.test.tsx index 3d85dae..a91ac9f 100644 --- a/frontend/app/features/cards/cardActions.test.tsx +++ b/frontend/app/features/cards/cardActions.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import type { Card } from '../../../types'; +import type { Card } from '../../../shared/api-contract'; import { createCard, deleteCard, updateCard } from './api'; import { useCardActions } from './cardActions'; diff --git a/frontend/app/features/cards/cardActions.ts b/frontend/app/features/cards/cardActions.ts index 0fcf467..7dde2fc 100644 --- a/frontend/app/features/cards/cardActions.ts +++ b/frontend/app/features/cards/cardActions.ts @@ -1,5 +1,5 @@ import { useCallback, useMemo, useState, type Dispatch, type SetStateAction } from 'react'; -import type { Card } from '../../../types'; +import type { Card } from '../../../shared/api-contract'; import { createCard, deleteCard, updateCard } from './api'; import { filterCards } from './batchState'; import type { AddCardForm, EditCardForm } from './types'; diff --git a/frontend/app/features/cards/components/BatchCardImportModal.tsx b/frontend/app/features/cards/components/BatchCardImportModal.tsx index 1633636..2a901c2 100644 --- a/frontend/app/features/cards/components/BatchCardImportModal.tsx +++ b/frontend/app/features/cards/components/BatchCardImportModal.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { createPortal } from 'react-dom'; import { FileDown, ListPlus, Loader2, Plus, Upload, X } from 'lucide-react'; -import type { Card } from '../../../../types'; +import type { Card } from '../../../../shared/api-contract'; import type { CardBatchModalProps } from '../types'; // BatchCardImportModal 负责卡密批量创建和单组库存追加的交互界面。 diff --git a/frontend/app/features/cards/components/CardIcon.tsx b/frontend/app/features/cards/components/CardIcon.tsx index ee3ed68..abd90bd 100644 --- a/frontend/app/features/cards/components/CardIcon.tsx +++ b/frontend/app/features/cards/components/CardIcon.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { Code, CreditCard, FileText, Image as ImageIcon } from 'lucide-react'; -import type { Card } from '../../../../types'; +import type { Card } from '../../../../shared/api-contract'; // CardIconProps 描述库存图标所需的卡密类型参数。 interface CardIconProps { diff --git a/frontend/app/features/cards/hooks.test.tsx b/frontend/app/features/cards/hooks.test.tsx index 63c7bf4..c1d47e0 100644 --- a/frontend/app/features/cards/hooks.test.tsx +++ b/frontend/app/features/cards/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { Card } from '../../../types'; +import type { Card } from '../../../shared/api-contract'; import { appendCardData, batchCreateCards, getCards } from './api'; import { useCardBatchActions, useCardsData } from './hooks'; @@ -212,4 +212,35 @@ describe('useCardsData 与 useCardBatchActions', /* 当前回调处理卡密库 expect(hook.result.current.cards).toEqual([]); hook.unmount(); }); + + test('批量创建在卸载时取消未完成请求', /* 当前回调验证批量表单卸载后不再允许晚到上传响应更新状态。 */ async () => { + // uploadSignal 保存批量创建接口收到的取消信号。 + let uploadSignal: AbortSignal | undefined; + batchCreateMock.mockImplementation( + // pendingCreate 保持上传请求未完成,以便验证 Hook 卸载时主动取消。 + (_file, requestOptions) => { + uploadSignal = requestOptions?.signal; + return new Promise(/* pendingCreateExecutor 故意不完成上传 Promise,直到 Hook 卸载取消请求。 */ () => undefined); + }, + ); + // hook 是带有上传文件的批量创建 Hook。 + const hook = renderHook( + // batchHookFactory 创建批量操作 Hook。 + () => useCardBatchActions({ dataCards: [cardFixture], loadCards: loadCardsFixture }), + ); + await act( + // fileAction 写入将要上传的卡密文件。 + () => hook.result.current.setBatchFile(new File(['name'], 'cards.csv')), + ); + await act( + // createAction 发起尚未完成的上传但不等待其结束。 + () => { void hook.result.current.handleBatchCreate(); }, + ); + await waitFor( + // uploadStartedAssertion 等待上传请求拿到取消信号。 + () => expect(uploadSignal).toBeDefined(), + ); + hook.unmount(); + expect(uploadSignal?.aborted).toBe(true); + }); }); diff --git a/frontend/app/features/cards/hooks.ts b/frontend/app/features/cards/hooks.ts index 6666acd..d761aa7 100644 --- a/frontend/app/features/cards/hooks.ts +++ b/frontend/app/features/cards/hooks.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react'; import { appendCardData, batchCreateCards, getCards } from './api'; -import type { Card } from '../../../types'; +import type { Card } from '../../../shared/api-contract'; import { canSubmitAppend, isCurrentCardRequest, previewAppendContent } from './batchState'; import type { CardBatchState } from './types'; @@ -110,6 +110,18 @@ export const useCardBatchActions = (options: CardBatchOptions): CardBatchState = // lastAppendTarget 保存最近一次提交追加的目标 ID,供失败重试使用。 const lastAppendTarget = useRef(''); + useEffect( + // 批量操作生命周期副作用在弹窗页面卸载时使未完成请求失效,防止晚到响应写入已销毁的表单状态。 + () => ( + // batchRequestCleanup 取消创建或追加请求,并推进代次屏蔽不响应 AbortSignal 的旧响应。 + () => { + requestGeneration.current += 1; + requestAbort.current?.abort(); + } + ), + [], + ); + // appendPreview 按行派生追加预览,不重复存储派生状态。 const appendPreview = useMemo( // 追加预览回调根据当前文本派生有效卡密行。 diff --git a/frontend/components/CardList.test.tsx b/frontend/app/features/cards/pages/CardList.test.tsx similarity index 93% rename from frontend/components/CardList.test.tsx rename to frontend/app/features/cards/pages/CardList.test.tsx index 265a186..cf8a1b7 100644 --- a/frontend/components/CardList.test.tsx +++ b/frontend/app/features/cards/pages/CardList.test.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import type { Card } from '../types'; +import type { Card } from '../../../../shared/api-contract'; // cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。 const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({ @@ -14,7 +14,7 @@ const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享 updateCard: vi.fn(), })); -vi.mock('../app/features/cards/hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({ +vi.mock('../hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({ useCardsData: /* useCardsDataMock 返回固定卡密库存。 */ () => ({ cards: cardListMocks.cards, setCards: vi.fn(), @@ -46,13 +46,13 @@ vi.mock('../app/features/cards/hooks', /* cardsHooksMockFactory 提供卡密库 }), })); -vi.mock('../app/features/cards/api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。 */ () => ({ +vi.mock('../api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。 */ () => ({ createCard: cardListMocks.createCard, deleteCard: cardListMocks.deleteCard, updateCard: cardListMocks.updateCard, })); -vi.mock('../app/features/cards/components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({ +vi.mock('../components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({ BatchCardImportModal: /* BatchCardImportModalMock 表示批量导入弹窗替身。 */ () => null, })); diff --git a/frontend/components/CardList.tsx b/frontend/app/features/cards/pages/CardList.tsx similarity index 99% rename from frontend/components/CardList.tsx rename to frontend/app/features/cards/pages/CardList.tsx index 861f8bb..fc1a835 100644 --- a/frontend/components/CardList.tsx +++ b/frontend/app/features/cards/pages/CardList.tsx @@ -1,11 +1,11 @@ import React from 'react'; import { createPortal } from 'react-dom'; -import { Card } from '../types'; +import { Card } from '../../../../shared/api-contract'; import { Plus, CreditCard, FileText, Image as ImageIcon, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, Search, SlidersHorizontal } from 'lucide-react'; -import { BatchCardImportModal } from '../app/features/cards/components/BatchCardImportModal'; -import { CardIcon } from '../app/features/cards/components/CardIcon'; -import { useCardBatchActions, useCardsData } from '../app/features/cards/hooks'; -import { useCardActions } from '../app/features/cards/cardActions'; +import { BatchCardImportModal } from '../components/BatchCardImportModal'; +import { CardIcon } from '../components/CardIcon'; +import { useCardBatchActions, useCardsData } from '../hooks'; +import { useCardActions } from '../cardActions'; // CardList 渲染卡密列表组件。 const CardList: React.FC = () => { diff --git a/frontend/app/features/cards/types.ts b/frontend/app/features/cards/types.ts index 3d0d9f9..9a0c2b5 100644 --- a/frontend/app/features/cards/types.ts +++ b/frontend/app/features/cards/types.ts @@ -1,5 +1,5 @@ import type { Dispatch, SetStateAction } from 'react'; -import type { Card, CardAppendResponse, CardBatchResponse } from '../../../types'; +import type { Card, CardAppendResponse, CardBatchResponse } from '../../../shared/api-contract'; // AddCardForm 描述新增卡密组弹窗中的可编辑字段。 export interface AddCardForm { diff --git a/frontend/app/features/chat/api.ts b/frontend/app/features/chat/api.ts index e6ddefd..9175f11 100644 --- a/frontend/app/features/chat/api.ts +++ b/frontend/app/features/chat/api.ts @@ -1,12 +1,73 @@ -/** Chat feature 使用的会话、消息和账号运行状态 API。 */ -export { - getAccountDetails, - getAccountRuntimeStatuses, - getChatMessagePage, - getChatMessages, - getChatSessionPage, - getChatSessions, - markChatRead, - sendChatImage, - sendChatMessage, -} from '../../../services/api'; +import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client'; +import { + SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse, + AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, + Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, + NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, + CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse +} from '../../../shared/api-contract'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; + +/** 聊天账号选择器读取非敏感账号摘要。 */ +export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); + +/** 聊天运行提示读取账号连接状态索引。 */ +export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise; /** 状态说明。 */ message?: string; /** 是否已连接。 */ connected: boolean; /** 连续失败次数。 */ failures: number; /** 最近更新时间。 */ updated_at: string }>> => get('/api/v1/accounts/runtime-status', undefined, options); +export interface ChatSessionPage { /** sessions 表示聊天会话列表。 */ sessions: ChatSession[]; /** has_more 表示是否存在更多数据。 */ has_more: boolean; /** next_cursor 表示下一页游标。 */ next_cursor?: number } + +// getChatSessionPage 分页读取聊天会话。 +export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise => { + // result 接口响应结果,用于当前 API 处理流程。 + const response = await get('/api/v1/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined }, + refresh ? { timeoutMs: 60_000, ...options } : options); + // result 是兼容直接分页对象和 data 包裹后的聊天会话分页。 + const result = objectFrom>(response, ['data', 'result']) || {}; + return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor }; +}; + +// getChatSessions 读取聊天会话列表。 +export const getChatSessions = async (accountId: string, options?: RequestControlOptions): Promise => + (await getChatSessionPage(accountId, undefined, options)).sessions; + +export interface ChatMessagePage { + /** messages 表示聊天消息列表。 */ messages: ChatMessage[]; + /** has_more 表示是否存在更多数据。 */ has_more: boolean; + /** next_cursor 表示下一页游标。 */ next_cursor?: number; + /** session 表示会话。 */ session?: ChatSession; +} + +// getChatMessagePage 分页读取聊天消息。 +export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise => { + // result 接口响应结果,用于当前 API 处理流程。 + const response = await get('/api/v1/chat/messages', { + account_id: accountId, chat_id: chatId, cursor, before_id: beforeId, + }, options); + // result 是兼容直接分页对象和 data 包裹后的聊天消息分页。 + const result = objectFrom>(response, ['data', 'result']) || {}; + return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session }; +}; + +// getChatMessages 读取聊天消息列表。 +export const getChatMessages = async (accountId: string, chatId: string, beforeId?: number, options?: RequestControlOptions): Promise => + (await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages; + +// sendChatMessage 发送聊天文本消息。 +export const sendChatMessage = async (input: { + /** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string; + /** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** text 表示文本。 */ text: string; +}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => post('/api/v1/chat/messages', input, options); + +// sendChatImage 发送聊天图片消息。 +export const sendChatImage = async (input: { + /** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string; + /** buyer_avatar_url 表示买家头像地址。 */ buyer_avatar_url?: string; /** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** image 表示图片数据。 */ image: File; +}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => { + // form 消息表单,用于当前 API 处理流程。 + const form = new FormData(); + Object.entries(input).forEach(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => form.append(key, value)); + return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options }); +}; + +// markChatRead 标记聊天消息已读。 +export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise => + post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options); diff --git a/frontend/app/features/chat/hooks.test.tsx b/frontend/app/features/chat/hooks.test.tsx index 19c49f7..870b54e 100644 --- a/frontend/app/features/chat/hooks.test.tsx +++ b/frontend/app/features/chat/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail, ChatMessage, ChatSession } from '../../../types'; +import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract'; import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api'; import { useChat } from './hooks'; @@ -429,4 +429,43 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时 expect(latestSocket?.close).toHaveBeenCalled(); hook.unmount(); }); + + test('切换或清空会话时取消未完成的历史消息分页', /* 当前回调验证历史分页不会在会话上下文失效后写入新会话状态。 */ async () => { + // historySignal 保存历史分页接口收到的取消信号。 + let historySignal: AbortSignal | undefined; + // hook 是已加载默认账号和会话的聊天 Hook。 + const hook = renderHook( + // chatHookFactory 创建聊天 Hook。 + () => useChat(), + ); + await waitFor( + // activeChatAssertion 等待默认会话成为当前选择。 + () => expect(hook.result.current.activeChatID).toBe('chat-1'), + ); + await waitFor( + // messagesLoadedAssertion 等待首次消息分页完成并允许继续加载历史消息。 + () => expect(hook.result.current.messagesLoading).toBe(false), + ); + getMessagePageMock.mockImplementationOnce( + // pendingHistory 保持历史分页未完成,以便验证会话切换时主动取消。 + (_accountID, _chatID, _cursor, _oldestID, requestOptions) => { + historySignal = requestOptions?.signal; + return new Promise(/* pendingHistoryExecutor 故意不完成历史分页 Promise,直到会话切换取消请求。 */ () => undefined); + }, + ); + await act( + // olderMessagesAction 触发需要保持未完成的历史消息分页。 + () => { void hook.result.current.loadOlderMessages(); }, + ); + await waitFor( + // historyStartedAssertion 等待历史分页请求建立取消信号。 + () => expect(historySignal).toBeDefined(), + ); + await act( + // clearChatAction 清空当前会话,使历史分页上下文立即失效。 + () => hook.result.current.setActiveChatID(''), + ); + expect(historySignal?.aborted).toBe(true); + hook.unmount(); + }); }); diff --git a/frontend/app/features/chat/hooks.ts b/frontend/app/features/chat/hooks.ts index 08ae0d5..1bd4968 100644 --- a/frontend/app/features/chat/hooks.ts +++ b/frontend/app/features/chat/hooks.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import type React from 'react'; -import type { AccountDetail, ChatMessage, ChatSession } from '../../../types'; +import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract'; import { emojiURL, renderXianyuText, xianyuEmojis } from '../../../chatEmojis'; import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatSessionPage, markChatRead, sendChatImage, sendChatMessage } from './api'; import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; @@ -128,6 +128,10 @@ export const useChat = (): UseChatResult => { const messageSequence = useRef(0); // messageController 保存当前消息请求控制器。 const messageController = useRef(null); + // olderSequence 隔离同一会话中被关闭、切换或替换的历史消息分页请求。 + const olderSequence = useRef(0); + // olderController 保存当前历史消息分页请求,切换会话或卸载时必须由本 Hook 取消。 + const olderController = useRef(null); // contactSequence 隔离联系人分页产生的旧响应。 const contactSequence = useRef(0); // contactController 保存当前联系人分页控制器。 @@ -252,6 +256,11 @@ export const useChat = (): UseChatResult => { useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { if (!activeAccountID || !activeChatID) { + // 无有效会话时也推进消息与历史分页代次,避免晚到响应恢复已清空的消息列表。 + messageSequence.current += 1; + olderSequence.current += 1; + olderController.current?.abort(); + skipNextMessageScrollRef.current = false; setMessages([]); return; } @@ -290,9 +299,18 @@ export const useChat = (): UseChatResult => { sendSequence.current += 1; }, [activeAccountID, activeChatID]); + useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { + // 会话切换时取消历史分页;新的消息加载拥有独立控制器,不能复用这个低优先级请求。 + olderSequence.current += 1; + olderController.current?.abort(); + skipNextMessageScrollRef.current = false; + }, [activeAccountID, activeChatID]); + useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => /* 当前回调同步 React 副作用和资源生命周期。 */ () => { sessionController.current?.abort(); messageController.current?.abort(); + olderSequence.current += 1; + olderController.current?.abort(); contactController.current?.abort(); sendController.current?.abort(); }, []); @@ -306,8 +324,12 @@ export const useChat = (): UseChatResult => { const previousHeight = container?.scrollHeight || 0; // sequence 请求序号。 const sequence = messageSequence.current; - // controller 请求取消控制器。 + // olderRequestSequence 标识本次历史分页,连续翻页、切换会话或卸载后旧分页不能写入状态。 + const olderRequestSequence = ++olderSequence.current; + olderController.current?.abort(); + // controller 取消当前历史消息请求。 const controller = new AbortController(); + olderController.current = controller; skipNextMessageScrollRef.current = true; setOlderLoading(true); setError(''); @@ -316,18 +338,20 @@ export const useChat = (): UseChatResult => { const oldestID = messages[0]?.id; // page 页码。 const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID, { signal: controller.signal }); - if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal)) return; + if (!isCurrentChatRequest(messageSequence.current, sequence, controller.signal) || olderRequestSequence !== olderSequence.current) return; setMessages(/* 当前回调处理用户交互或异步状态变化。 */ current => mergeOlderMessages(current, page.messages)); setHasOlder(page.has_more); setHistoryCursor(page.next_cursor); requestAnimationFrame(/* 当前回调处理用户交互或异步状态变化。 */ () => { - if (container) container.scrollTop += container.scrollHeight - previousHeight; + if (olderRequestSequence === olderSequence.current && !controller.signal.aborted && container) { + container.scrollTop += container.scrollHeight - previousHeight; + } }); } catch (/* loadError 表示加载错误。 */ loadError) { skipNextMessageScrollRef.current = false; if (!isChatAbortError(loadError)) setError(loadError instanceof Error ? loadError.message : '加载历史消息失败'); } finally { - setOlderLoading(false); + if (olderRequestSequence === olderSequence.current) setOlderLoading(false); } }, [activeAccountID, activeChatID, hasOlder, historyCursor, messages, olderLoading]); diff --git a/frontend/components/Chat.tsx b/frontend/app/features/chat/pages/Chat.tsx similarity index 99% rename from frontend/components/Chat.tsx rename to frontend/app/features/chat/pages/Chat.tsx index f6650bb..89b5524 100644 --- a/frontend/components/Chat.tsx +++ b/frontend/app/features/chat/pages/Chat.tsx @@ -3,7 +3,7 @@ import { AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw, Search, Send, Smile, UserRound, Wifi, WifiOff, } from 'lucide-react'; -import { useChat } from '../app/features/chat/hooks'; +import { useChat } from '../hooks'; // Chat 展示实时会话、消息分页和消息发送界面。 const Chat: React.FC = () => { diff --git a/frontend/app/features/chat/state.test.ts b/frontend/app/features/chat/state.test.ts index cdb1397..20d0be5 100644 --- a/frontend/app/features/chat/state.test.ts +++ b/frontend/app/features/chat/state.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import type { ChatMessage, ChatSession } from '../../../types'; +import type { ChatMessage, ChatSession } from '../../../shared/api-contract'; import { filterChatSessions, formatClock, isChatAbortError, isCurrentChatRequest, mergeLiveMessage, mergeOlderMessages, messageTime } from './state'; // sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。 diff --git a/frontend/app/features/chat/state.ts b/frontend/app/features/chat/state.ts index c1cc64b..004d533 100644 --- a/frontend/app/features/chat/state.ts +++ b/frontend/app/features/chat/state.ts @@ -1,4 +1,4 @@ -import type { ChatMessage, ChatSession } from '../../../types'; +import type { ChatMessage, ChatSession } from '../../../shared/api-contract'; /** 按搜索条件筛选会话列表。 */ export const filterChatSessions = (sessions: ChatSession[], search: string, unreadOnly: boolean): ChatSession[] => { diff --git a/frontend/app/features/chat/types.ts b/frontend/app/features/chat/types.ts index 2969bbb..783a49a 100644 --- a/frontend/app/features/chat/types.ts +++ b/frontend/app/features/chat/types.ts @@ -1,4 +1,4 @@ -import type { AccountDetail, ChatMessage, ChatSession } from '../../../types'; +import type { AccountDetail, ChatMessage, ChatSession } from '../../../shared/api-contract'; /** 按账号保存会话列表。 */ export type SessionsByAccount = Record; diff --git a/frontend/app/features/dashboard/api.ts b/frontend/app/features/dashboard/api.ts index 6b6f044..2210015 100644 --- a/frontend/app/features/dashboard/api.ts +++ b/frontend/app/features/dashboard/api.ts @@ -1,2 +1,64 @@ -/** Dashboard 数据接口集中导出,避免页面组件直接依赖通用 API 模块。 */ -export { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from '../../../services/api'; +import { get, type RequestControlOptions } from '../../../shared/http/client'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; +import type { DashboardStatsResponse, Item, ItemListEnvelope, Order, OrderAnalyticsResponse, OrderStatus, ValidOrderResponse, ValidOrdersResponse } from '../../../shared/api-contract'; +import { formatLocalDate } from '../../../dateRange'; + +/** 仪表盘订单明细接口转换后的分页结果。 */ +export interface ValidOrdersResult { + /** 当前时间范围的订单明细。 */ + orders: Order[]; + /** 服务端匹配到的订单总数。 */ + total: number; + /** 是否存在未返回的后续订单。 */ + truncated: boolean; +} + +/** 将服务端订单状态映射为仪表盘可稳定展示的状态集合。 */ +const normalizeOrderStatus = (value: unknown): OrderStatus => { + // status 是服务端返回的原始或历史订单状态。 + const status = String(value || ''); + if (status === 'paid') return 'pending_ship'; + return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status) ? status as OrderStatus : 'unknown'; +}; + +/** 读取仪表盘概览统计。 */ +export const getDashboardStats = async (options?: RequestControlOptions): Promise => get('/api/v1/analytics/dashboard', undefined, options); + +/** 读取仪表盘商品索引,兼容历史 items 包装。 */ +export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise => { + // response 是商品列表的原始 transport 响应。 + const response = await get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options); + // items 是从直接数组或历史包装中取出的商品集合。 + const items = collectionFrom(response, ['items', 'data', 'results']); + return items.map(/* item 是当前需要兼容布尔标记的商品传输记录。 */ item => ({ ...item, id: item.id || `${item.cookie_id}-${item.item_id}`, is_multi_spec: item.is_multi_spec === true || item.is_multi_spec === 1, multi_quantity_delivery: item.multi_quantity_delivery === true || item.multi_quantity_delivery === 1 })); +}; + +/** 读取指定自然日范围的订单统计,并显式传递浏览器时区偏移。 */ +export const getOrderAnalytics = async (range: number | { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string } = 7, options?: RequestControlOptions): Promise => { + // dateRange 是标准化后的统计日期范围。 + let dateRange: { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string }; + if (typeof range === 'number') { + // endDate 是计算默认区间使用的当前本地日期。 + const endDate = new Date(); + // startDate 是向前回溯指定天数后的本地日期。 + const startDate = new Date(); + startDate.setDate(startDate.getDate() - range); + dateRange = { start_date: formatLocalDate(startDate), end_date: formatLocalDate(endDate) }; + } else { + dateRange = range; + } + return get('/api/v1/analytics/orders', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options); +}; + +/** 读取可参与仪表盘统计的订单并适配历史响应形状。 */ +export const getValidOrders = async (dateRange: { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string }, options?: RequestControlOptions): Promise => { + // response 是有效订单接口的未知兼容响应。 + const response = await get('/api/v1/analytics/orders/valid', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options); + // page 是移除历史 transport 包装后的分页元数据。 + const page = objectFrom>(response, ['data', 'result']) || {}; + // rows 是直接数组或历史 orders 包装中的原始订单。 + const rows = collectionFrom(response, ['orders', 'data', 'items']); + // orders 是转换状态、数量和稳定标识后的仪表盘订单模型。 + const orders = rows.map(/* row 是当前需要归一化状态与数量的有效订单 DTO。 */ row => ({ ...row, id: row.order_id, status: normalizeOrderStatus(row.status || row.order_status), order_status: normalizeOrderStatus(row.order_status), quantity: Number(row.quantity || 1) })); + return { orders, total: Number(page.total ?? orders.length), truncated: page.truncated === true }; +}; diff --git a/frontend/app/features/dashboard/hooks.test.tsx b/frontend/app/features/dashboard/hooks.test.tsx index 678676c..b249ce3 100644 --- a/frontend/app/features/dashboard/hooks.test.tsx +++ b/frontend/app/features/dashboard/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../types'; +import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../shared/api-contract'; import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api'; import { useDashboard } from './hooks'; import type { UseDashboardOptions } from './hooks'; @@ -142,4 +142,33 @@ describe('useDashboard', /* 当前回调处理仪表盘并行请求和派生数 expect(hook.result.current.status.range).toBe('success'); hook.unmount(); }); + + test('刷新期间丢弃忽略取消信号的旧概览响应', /* 当前回调验证概览请求即使底层实现没有响应取消,也不能覆盖刷新后的统计数据。 */ async () => { + // resolveFirstStats 是首次概览统计请求的完成控制器。 + let resolveFirstStats: (value: DashboardStats) => void = () => undefined; + // firstStatsRequest 是故意忽略 AbortSignal 的旧统计请求。 + const firstStatsRequest = new Promise(/* firstStatsExecutor 保存旧统计请求的完成函数。 */ resolve => { resolveFirstStats = resolve; }); + // refreshedStats 是刷新后应保留在页面中的权威概览数据。 + const refreshedStats = { ...statsFixture, total_orders: 99 }; + getStatsMock.mockReset(); + getStatsMock.mockReturnValueOnce(firstStatsRequest); + getStatsMock.mockResolvedValueOnce(refreshedStats); + // hook 是概览刷新竞态场景的 Hook 渲染结果。 + const hook = renderHook(renderDashboardHook); + await act( + // refreshAction 发起第二次概览加载并使首个请求过期。 + () => hook.result.current.refresh(), + ); + await waitFor( + // refreshedOverviewAssertion 等待新概览统计写入页面状态。 + () => expect(hook.result.current.data?.stats).toEqual(refreshedStats), + ); + resolveFirstStats(statsFixture); + await act( + // staleOverviewResolveAction 完成被取消但仍返回的旧统计请求。 + async () => { await firstStatsRequest; }, + ); + expect(hook.result.current.data?.stats).toEqual(refreshedStats); + hook.unmount(); + }); }); diff --git a/frontend/app/features/dashboard/hooks.ts b/frontend/app/features/dashboard/hooks.ts index 3bc0e1b..916acb1 100644 --- a/frontend/app/features/dashboard/hooks.ts +++ b/frontend/app/features/dashboard/hooks.ts @@ -42,6 +42,8 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult = const [refreshKey, setRefreshKey] = useState(0); // requestSequence 请求请求序号,负责当前功能中的对应处理。 const requestSequence = useRef(0); + // overviewSequence 隔离刷新后仍然完成的旧概览响应,避免忽略取消信号的底层实现覆盖新数据。 + const overviewSequence = useRef(0); // rangeSelection 范围选择,负责当前功能中的对应处理。 const rangeSelection = useMemo( // selection 是当前时间范围的不可变快照。 @@ -57,6 +59,8 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult = ); useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { + // sequence 标识本轮概览请求,刷新或卸载后旧请求不得写入状态。 + const sequence = ++overviewSequence.current; // controller 请求取消控制器。 const controller = new AbortController(); setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'loading', error: '' })); @@ -64,11 +68,11 @@ export const useDashboard = (options: UseDashboardOptions): UseDashboardResult = getDashboardStats({ signal: controller.signal }), getItems(undefined, { signal: controller.signal }), ]).then(/* 当前回调处理用户交互或异步状态变化。 */ ([stats, items]) => { - if (controller.signal.aborted) return; + if (!isCurrentDashboardRequest(overviewSequence.current, sequence, controller.signal)) return; setOverview({ stats, items, itemNames: buildItemNameMap(items) }); setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'success' })); }).catch(/* 当前回调处理用户交互或异步状态变化。 */ error => { - if (controller.signal.aborted || isAbortError(error)) return; + if (!isCurrentDashboardRequest(overviewSequence.current, sequence, controller.signal) || isAbortError(error)) return; setStatus(/* 当前回调处理用户交互或异步状态变化。 */ current => ({ ...current, overview: 'error', error: errorMessage(error, '概览加载失败') })); }); return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort(); diff --git a/frontend/components/Dashboard.test.tsx b/frontend/app/features/dashboard/pages/Dashboard.test.tsx similarity index 93% rename from frontend/components/Dashboard.test.tsx rename to frontend/app/features/dashboard/pages/Dashboard.test.tsx index ee11d23..f31b7d2 100644 --- a/frontend/components/Dashboard.test.tsx +++ b/frontend/app/features/dashboard/pages/Dashboard.test.tsx @@ -8,9 +8,9 @@ import { StatusBadge } from './Dashboard'; // dashboardSource 仪表盘测试数据源。 const dashboardSource = readFileSync(resolve(__dirname, 'Dashboard.tsx'), 'utf8'); // trendChartSource 趋势图测试数据源。 -const trendChartSource = readFileSync(resolve(__dirname, '../app/features/dashboard/DashboardTrendChart.tsx'), 'utf8'); +const trendChartSource = readFileSync(resolve(__dirname, '../DashboardTrendChart.tsx'), 'utf8'); // globalStyles 测试用全局样式。 -const globalStyles = readFileSync(resolve(__dirname, '../index.css'), 'utf8'); +const globalStyles = readFileSync(resolve(__dirname, '../../../../index.css'), 'utf8'); describe('Dashboard presentation safeguards', /* 当前回调处理用户交互或异步状态变化。 */ () => { test('keeps order status badges on one line', /* 当前回调处理用户交互或异步状态变化。 */ () => { diff --git a/frontend/components/Dashboard.tsx b/frontend/app/features/dashboard/pages/Dashboard.tsx similarity index 98% rename from frontend/components/Dashboard.tsx rename to frontend/app/features/dashboard/pages/Dashboard.tsx index 7a9ec93..49c36ef 100644 --- a/frontend/components/Dashboard.tsx +++ b/frontend/app/features/dashboard/pages/Dashboard.tsx @@ -1,11 +1,11 @@ import React, { useState } from 'react'; -import { OrderStatus } from '../types'; -import { getDateRange, TimeRange } from '../dateRange'; -import { formatLocalDateTime } from '../dateTime'; +import { OrderStatus } from '../../../../shared/api-contract'; +import { getDateRange, TimeRange } from '../../../../dateRange'; +import { formatLocalDateTime } from '../../../../dateTime'; import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react'; import { Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts'; -import { useDashboard } from '../app/features/dashboard/hooks'; -import { DashboardTrendChart } from '../app/features/dashboard/DashboardTrendChart'; +import { useDashboard } from '../hooks'; +import { DashboardTrendChart } from '../DashboardTrendChart'; // cssColor 状态颜色样式。 const cssColor = (token: string, alpha?: number) => ( diff --git a/frontend/app/features/dashboard/state.test.ts b/frontend/app/features/dashboard/state.test.ts index fa90439..21e130c 100644 --- a/frontend/app/features/dashboard/state.test.ts +++ b/frontend/app/features/dashboard/state.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import type { OrderAnalytics } from '../../../types'; +import type { OrderAnalytics } from '../../../shared/api-contract'; import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state'; // analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。 diff --git a/frontend/app/features/dashboard/state.ts b/frontend/app/features/dashboard/state.ts index 4718527..19cdff0 100644 --- a/frontend/app/features/dashboard/state.ts +++ b/frontend/app/features/dashboard/state.ts @@ -1,4 +1,4 @@ -import type { Item, OrderAnalytics } from '../../../types'; +import type { Item, OrderAnalytics } from '../../../shared/api-contract'; import type { DateRange, TimeRange } from '../../../dateRange'; import type { DashboardRangeSelection } from './types'; diff --git a/frontend/app/features/dashboard/types.ts b/frontend/app/features/dashboard/types.ts index f40d885..2a8c600 100644 --- a/frontend/app/features/dashboard/types.ts +++ b/frontend/app/features/dashboard/types.ts @@ -1,4 +1,4 @@ -import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../types'; +import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../shared/api-contract'; import type { DateRange, TimeRange } from '../../../dateRange'; /** Dashboard 请求状态。 */ diff --git a/frontend/app/features/items/api.ts b/frontend/app/features/items/api.ts index 74af4e7..4bb9a68 100644 --- a/frontend/app/features/items/api.ts +++ b/frontend/app/features/items/api.ts @@ -1,21 +1,164 @@ -// ItemList feature 通过本适配层访问商品、批量任务和发货地 API。 -export { - getItems, - getAccountDetails, - syncItemsFromAccount, - createItem, - publishItem, - recommendPublishCategory, - previewItemPublishBatch, - startItemPublishBatch, - getItemPublishBatch, - getItemPublishBatches, - deleteItemPublishBatch, - cancelItemPublishBatch, - retryFailedItemPublishBatch, - updateItem, - deleteItem, - getShippingRules, -} from '../../../services/api'; -export type { PublishLocation } from '../../../services/api'; -export { getPublishLocations } from '../../../services/amapLocation'; +import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client'; +import { + SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse, + AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, + Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, + NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, + CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse +} from '../../../shared/api-contract'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; +import { getPublishLocations } from '../../../services/amapLocation'; +import type { PublishLocation } from '../../../shared/api-contract'; + +/** 商品账号筛选器读取非敏感账号摘要。 */ +export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); + +/** 商品页面读取自动化发货规则的兼容列表。 */ +export const getShippingRules = async (): Promise => get('/api/v1/automation-rules'); + +export { getPublishLocations }; +export type { PublishLocation } from '../../../shared/api-contract'; +// Items +// normalizeBooleanFlag 归一化布尔标记。 +const normalizeBooleanFlag = (value: unknown): boolean => + value === true || value === 1 || value === '1'; + +// getItems 读取商品列表。 +export const getItems = async (cookieId?: string, options?: RequestControlOptions): Promise => { + // res 接口响应结果,用于当前 API 处理流程。 + const res = await get('/api/v1/items', cookieId ? { cookie_id: cookieId } : undefined, options); + // items 商品列表,用于当前 API 处理流程。 + const items = collectionFrom(res, ['items', 'data', 'results']); + return items.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ + ...item, + id: item.id || `${item.cookie_id}-${item.item_id}`, + is_multi_spec: normalizeBooleanFlag(item.is_multi_spec), + is_multi_qty_ship: normalizeBooleanFlag(item.is_multi_qty_ship ?? item.multi_quantity_delivery), + multi_quantity_delivery: normalizeBooleanFlag(item.multi_quantity_delivery ?? item.is_multi_qty_ship), + })); +} + +// syncItemsFromAccount 从账号同步商品。 +export const syncItemsFromAccount = async (cookieId: string): Promise => { + return post('/api/v1/items/get-all-from-account', { cookie_id: cookieId }); +} + +// deleteItem 删除商品。 +export const deleteItem = async (cookieId: string, itemId: string): Promise => { + return del(`/api/v1/items/${cookieId}/${itemId}`); +} + +// createItem 创建商品。 +export const createItem = async (cookieId: string, data: Partial): Promise => { + return post(`/api/v1/items/${cookieId}`, data); +} + +// publishItem 发布商品。 +export const publishItem = async (form: { + /** cookie_id 表示登录凭证标识。 */ cookie_id: string; + /** title 表示标题。 */ title: string; + /** description 表示描述。 */ description: string; + /** price 表示售价。 */ price: string; + /** original_price 表示原始售价。 */ original_price?: string; + /** quantity 表示数量。 */ quantity: string | number; + /** postage_mode 表示运费模式。 */ postage_mode: string; + /** postage 表示运费。 */ postage?: string; + /** images 表示图片列表。 */ images: File[]; + /** location 表示地址。 */ location?: PublishLocation; +}): Promise => { + // body 请求体,用于当前 API 处理流程。 + const body = new FormData(); + body.set('cookie_id', form.cookie_id); + body.set('title', form.title); + body.set('description', form.description); + body.set('price', form.price); + body.set('original_price', form.original_price || ''); + body.set('quantity', String(form.quantity)); + body.set('postage_mode', form.postage_mode); + body.set('postage', form.postage || ''); + if (form.location) body.set('location', JSON.stringify(form.location)); + for (const // file 上传文件,用于当前 API 处理流程。 +file of form.images) { + body.append('images', file); + } + return postForm('/api/v1/items/publish', body); +} + +// recommendPublishCategory 推荐商品发布分类。 +export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise => { + // 类目推荐成功响应使用共享 CategoryRecommendationResponse。 + // category 字段保留平台类目 ID、名称和频道类目 ID。 + // tb_cat_id 继续保持可选,兼容电子资料类目。 + // 请求仍携带账号 ID 和关键词。 + // 失败响应由共享 HTTP 错误结构处理。 + // 该类型收口不改变凭证刷新和错误处理。 + // 前端批量发布流程可直接复用 category。 + // 旧路径继续由现有 Vite 代理转发。 + return post('/api/v1/items/publish-categories/recommend', { cookie_id: cookieId, keyword }); +}; + +// previewItemPublishBatch 预览商品批量发布。 +export const previewItemPublishBatch = async (form: { + /** file 表示上传文件。 */ file: File; + /** imagesZip 表示图片压缩包。 */ imagesZip?: File | null; + /** defaultCookieId 表示默认账号凭证标识。 */ defaultCookieId?: string; + /** fallbackCategory 表示备用分类。 */ fallbackCategory: { + /** catId 表示分类标识。 */ catId: string; + /** catName 表示分类名称。 */ catName: string; + /** channelCatId 表示渠道分类标识。 */ channelCatId?: string; + /** tbCatId 表示淘宝分类标识。 */ tbCatId?: string; + }; + /** location 表示地址。 */ location?: PublishLocation; +}): Promise => { + // body 请求体,用于当前 API 处理流程。 + const body = new FormData(); + body.set('file', form.file); + if (form.imagesZip) body.set('images_zip', form.imagesZip); + if (form.defaultCookieId) body.set('default_cookie_id', form.defaultCookieId); + body.set('fallback_category_id', form.fallbackCategory.catId); + body.set('fallback_category_name', form.fallbackCategory.catName); + body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || ''); + body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || ''); + if (form.location) body.set('location', JSON.stringify(form.location)); + return postForm('/api/v1/items/publish-batches/preview', body); +} + +// startItemPublishBatch 启动商品批量发布。 +export const startItemPublishBatch = async (previewId: string): Promise => { + return post('/api/v1/items/publish-batches', { preview_id: previewId }); +} + +// getItemPublishBatch 读取商品发布批次。 +export const getItemPublishBatch = async (batchId: string): Promise => { + return get(`/api/v1/items/publish-batches/${batchId}`); +} + +// getItemPublishBatches 读取商品发布批次列表。 +export const getItemPublishBatches = async (limit = 20): Promise => { + // res 接口响应结果,用于当前 API 处理流程。 + const res = await get('/api/v1/items/publish-batches', { limit }); + return collectionFrom(res, ['batches', 'data', 'items']); +} + +// deleteItemPublishBatch 删除商品发布批次。 +export const deleteItemPublishBatch = async (batchId: string): Promise => { + return del(`/api/v1/items/publish-batches/${batchId}`); +} + +// cancelItemPublishBatch 取消商品发布批次。 +export const cancelItemPublishBatch = async (batchId: string): Promise => { + return post(`/api/v1/items/publish-batches/${batchId}/cancel`, {}); +} + +// retryFailedItemPublishBatch 重试失败的商品发布任务。 +export const retryFailedItemPublishBatch = async (batchId: string): Promise => { + return post(`/api/v1/items/publish-batches/${batchId}/retry-failed`, {}); +} + +// updateItem 更新商品。 +export const updateItem = async (cookieId: string, itemId: string, data: Partial): Promise => { + return put(`/api/v1/items/${cookieId}/${itemId}`, data); +} + +/** 读取指定账号与商品的详情,用于编辑器恢复表单。 */ +export const getItemDetail = async (accountID: string, itemID: string): Promise => get(`/api/v1/items/${accountID}/${itemID}`); diff --git a/frontend/app/features/items/hooks.test.tsx b/frontend/app/features/items/hooks.test.tsx index c7ec50c..cd8eece 100644 --- a/frontend/app/features/items/hooks.test.tsx +++ b/frontend/app/features/items/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../types'; +import type { BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchResponse } from '../../../shared/api-contract'; import { cancelItemPublishBatch, deleteItemPublishBatch, diff --git a/frontend/app/features/items/itemActions.test.tsx b/frontend/app/features/items/itemActions.test.tsx index bfb24df..c463161 100644 --- a/frontend/app/features/items/itemActions.test.tsx +++ b/frontend/app/features/items/itemActions.test.tsx @@ -2,7 +2,7 @@ import { act, renderHook } from '@testing-library/react'; import { useState } from 'react'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import type { Item } from '../../../types'; +import type { Item } from '../../../shared/api-contract'; import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api'; import { useItemActions, type ItemActionsOptions } from './itemActions'; diff --git a/frontend/app/features/items/itemActions.ts b/frontend/app/features/items/itemActions.ts index 0c57573..38794ee 100644 --- a/frontend/app/features/items/itemActions.ts +++ b/frontend/app/features/items/itemActions.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from 'react'; -import type { Item } from '../../../types'; +import type { Item } from '../../../shared/api-contract'; import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api'; import type { PublishLocation } from './api'; diff --git a/frontend/components/ItemList.tsx b/frontend/app/features/items/pages/ItemList.tsx similarity index 99% rename from frontend/components/ItemList.tsx rename to frontend/app/features/items/pages/ItemList.tsx index e90a54b..ec3758e 100644 --- a/frontend/components/ItemList.tsx +++ b/frontend/app/features/items/pages/ItemList.tsx @@ -1,18 +1,18 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { createPortal } from 'react-dom'; -import type { Item } from '../types'; +import type { Item } from '../../../../shared/api-contract'; import { getItems, getAccountDetails, getShippingRules, getItemPublishBatches, -} from '../app/features/items/api'; -import type { AccountDetail, ShippingRule } from '../types'; -import type { ItemListProps } from '../app/features/items/types'; -import { useItemPublishBatch } from '../app/features/items/hooks'; -import { useItemActions } from '../app/features/items/itemActions'; -import { batchStatusClass, batchStatusText } from '../app/features/items/batchState'; -import { BatchPhaseIndicator } from '../app/features/items/components/BatchPhaseIndicator'; +} from '../api'; +import type { AccountDetail, ShippingRule } from '../../../../shared/api-contract'; +import type { ItemListProps } from '../types'; +import { useItemPublishBatch } from '../hooks'; +import { useItemActions } from '../itemActions'; +import { batchStatusClass, batchStatusText } from '../batchState'; +import { BatchPhaseIndicator } from '../components/BatchPhaseIndicator'; import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react'; // formatItemPrice 将商品价格转换为本地化展示文本。 diff --git a/frontend/app/features/items/types.ts b/frontend/app/features/items/types.ts index 27c2bb2..6abb733 100644 --- a/frontend/app/features/items/types.ts +++ b/frontend/app/features/items/types.ts @@ -1,5 +1,5 @@ import type { Dispatch, SetStateAction } from 'react'; -import type { Item, AccountDetail, ShippingRule } from '../../../types'; +import type { Item, AccountDetail, ShippingRule } from '../../../shared/api-contract'; import type { PublishLocation } from './api'; // ItemListProps 描述商品页面从父级接收的规则配置回调。 diff --git a/frontend/app/features/notifications/api.ts b/frontend/app/features/notifications/api.ts index 4eecbe4..41b0c6b 100644 --- a/frontend/app/features/notifications/api.ts +++ b/frontend/app/features/notifications/api.ts @@ -1,11 +1,134 @@ -export { - createNotificationChannel, - deleteNotificationChannel, - getNotificationChannels, - getSystemSettings, - testNotificationChannel, - updateNotificationChannel, - updateSystemSettings, -} from '../../../services/api'; +import { del, get, post, put, type RequestControlOptions } from '../../../shared/http/client'; +import type { MutationIDResponse, NotificationBinding, NotificationChannel, NotificationChannelResponse, NotificationEventType, OperationResponse, SystemSettings } from '../../../shared/api-contract'; -// notifications feature 通过本适配层声明渠道和 SMTP API 的来源。 +/** 通知渠道写入时使用的具名请求 DTO。 */ +export interface NotificationChannelRequest { + /** 管理界面展示的渠道名称。 */ + name?: string; + /** 后端支持的渠道类型。 */ + type?: string; + /** 由各渠道表单构造的非敏感配置。 */ + config?: Record; + /** 需要订阅的系统事件。 */ + event_types?: NotificationEventType[]; + /** 渠道是否参与通知投递。 */ + enabled?: boolean; +} + +/** 将后端字符串或历史分隔文本转换为稳定事件类型列表。 */ +const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => { + if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[]; + if (typeof raw !== 'string' || !raw.trim()) return []; + try { + // parsed 是解析后的历史 JSON 事件列表。 + const parsed: unknown = JSON.parse(raw); + if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[]; + } catch { + // 非 JSON 历史值继续按分隔符兼容解析。 + } + return raw.split(/[,\s;]+/).map(value => value.trim()).filter(Boolean) as NotificationEventType[]; +}; + +/** 将事件类型列表序列化为后端稳定保存的 JSON 文本。 */ +const stringifyNotificationEventTypes = (eventTypes?: NotificationEventType[]): string => { + // uniqueTypes 是去重且去除空值后的事件列表。 + const uniqueTypes = Array.from(new Set((eventTypes || []).filter(Boolean))); + return uniqueTypes.length > 0 ? JSON.stringify(uniqueTypes) : ''; +}; + +/** 把后端渠道 DTO 转换为通知编辑器使用的 UI 模型。 */ +const toNotificationChannel = (channel: NotificationChannelResponse): NotificationChannel => { + // config 是解析失败时降级为空对象的渠道配置。 + let config: Record = {}; + try { + // parsed 是配置文本解析后的未知 JSON 值。 + const parsed: unknown = typeof channel.config === 'string' ? JSON.parse(channel.config) : channel.config; + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed as Record; + } catch { + // 历史损坏配置不阻止用户继续编辑渠道。 + } + // type 是处理 ding_talk/lark 历史别名后的渠道类型。 + const type = (channel.type === 'ding_talk' ? 'dingtalk' : channel.type === 'lark' ? 'feishu' : channel.type) as NotificationChannel['type']; + return { id: String(channel.id), name: channel.name, type, config, event_types: parseNotificationEventTypes(channel.event_types), enabled: channel.enabled, created_at: channel.created_at, updated_at: channel.updated_at }; +}; + +/** 获取全部通知渠道并转换为编辑器模型。 */ +export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** 操作是否完成。 */ success: boolean; /** 渠道列表。 */ data: NotificationChannel[] }> => { + // response 是渠道列表的原始传输响应。 + const response = await get('/api/v1/notifications/channels', undefined, options); + // channels 是兼容直接数组与包装数组后的原始渠道列表。 + const channels = Array.isArray(response) ? response : response.data || response.channels || []; + return { success: true, data: channels.map(toNotificationChannel) }; +}; + +/** 创建通知渠道,并在传输边界序列化配置与事件。 */ +export const createNotificationChannel = async (data: Required> & NotificationChannelRequest, options?: RequestControlOptions): Promise => post('/api/v1/notifications/channels', { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) }, options); + +/** 更新通知渠道的可编辑字段。 */ +export const updateNotificationChannel = async (channelID: string, data: NotificationChannelRequest, options?: RequestControlOptions): Promise => { + // payload 是已完成配置和事件序列化的更新请求。 + const payload: Record = { ...data }; + if ('config' in data) payload.config = JSON.stringify(data.config); + if ('event_types' in data) payload.event_types = stringifyNotificationEventTypes(data.event_types); + return put(`/api/v1/notifications/channels/${channelID}`, payload, options); +}; + +/** 删除指定通知渠道。 */ +export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => del(`/api/v1/notifications/channels/${channelID}`, undefined, options); + +/** 获取并展平按账号分组存储的消息通知绑定。 */ +export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => { + // response 是按账号 ID 分组的通知绑定响应。 + const response = await get>('/api/v1/notifications/messages'); + // bindings 是供页面直接渲染的扁平绑定集合。 + const bindings: NotificationBinding[] = []; + for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) { + if (!Array.isArray(channelBindings)) continue; + for (const /* binding 是当前待展平的单个账号渠道绑定。 */ binding of channelBindings) bindings.push({ ...binding, cookie_id: accountID }); + } + return { success: true, data: bindings }; +}; + +/** 设置单个账号与渠道之间的启用状态。 */ +export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_id: channelID, enabled }); + +/** 删除单个消息通知绑定。 */ +export const deleteMessageNotification = async (notificationID: string): Promise => del(`/api/v1/notifications/messages/${notificationID}`); + +/** 删除指定账号的全部消息通知绑定。 */ +export const deleteAccountNotifications = async (accountID: string): Promise => del(`/api/v1/notifications/messages/account/${accountID}`); + +/** 读取指定账号已绑定的通知渠道主键。 */ +export const getAccountBindings = async (accountID: string, options?: RequestControlOptions): Promise => { + // response 是账号渠道绑定的具名响应。 + const response = await get<{ /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } }>(`/api/v1/notifications/accounts/${accountID}/bindings`, undefined, options); + return Array.isArray(response.channel_ids) ? response.channel_ids : Array.isArray(response.data?.channel_ids) ? response.data.channel_ids : []; +}; + +/** 覆盖保存指定账号的通知渠道绑定。 */ +export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_ids: channelIDs }); + +/** 向单一通知渠道发送测试投递。 */ +export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => post(`/api/v1/notifications/channels/${channelID}/test`, {}, options); + +/** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */ +const normalizeSystemSettings = (settings: Record): SystemSettings => { + // result 是不改变原始响应对象的设置副本。 + const result: Record = { ...settings }; + if ('renewal_log_retention_days' in result) { + // days 是已校验的日志保留天数。 + const days = Number(result.renewal_log_retention_days); + result.renewal_log_retention_days = Number.isFinite(days) ? days : 10; + } + return result as SystemSettings; +}; + +/** 获取通知 SMTP 编辑器需要的系统设置。 */ +export const getSystemSettings = async (options?: RequestControlOptions): Promise => { + // response 是服务端可能以 data 包装的系统设置响应。 + const response = await get<{ /** data 是当前服务端系统设置。 */ data?: Record; /** settings 是兼容字段。 */ settings?: Record } & Record>('/api/v1/settings/system', undefined, options); + return normalizeSystemSettings(response.data || response.settings || response); +}; + +/** 保存通知 SMTP 编辑器提交的系统设置。 */ +export const updateSystemSettings = async (settings: Partial, options?: RequestControlOptions): Promise => put('/api/v1/settings/system', settings, options); diff --git a/frontend/app/features/notifications/components/NotificationChannelList.tsx b/frontend/app/features/notifications/components/NotificationChannelList.tsx index 1afab85..fe63151 100644 --- a/frontend/app/features/notifications/components/NotificationChannelList.tsx +++ b/frontend/app/features/notifications/components/NotificationChannelList.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { Bell, Edit2, Loader2, Send, Trash2 } from 'lucide-react'; -import type { NotificationChannel } from '../../../../types'; +import type { NotificationChannel } from '../../../../shared/api-contract'; import { notificationChannelTypes, notificationEventSummary } from '../state'; // NotificationChannelListProps 描述通知渠道列表的操作边界。 diff --git a/frontend/app/features/notifications/components/NotificationChannelModal.tsx b/frontend/app/features/notifications/components/NotificationChannelModal.tsx index 7d15873..d0b720a 100644 --- a/frontend/app/features/notifications/components/NotificationChannelModal.tsx +++ b/frontend/app/features/notifications/components/NotificationChannelModal.tsx @@ -4,7 +4,7 @@ import { Bell, Check, Eye, EyeOff, Loader2, X } from 'lucide-react'; import { enableCustomSMTP } from '../../../../notificationEmailConfig'; import { notificationChannelTypes } from '../state'; import { NotificationEventSelector } from './NotificationEventSelector'; -import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../types'; +import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../../shared/api-contract'; import type { NotificationForm } from '../types'; // NotificationChannelModalProps 描述渠道编辑弹窗所需的状态和回调。 diff --git a/frontend/app/features/notifications/components/NotificationEventSelector.tsx b/frontend/app/features/notifications/components/NotificationEventSelector.tsx index 1ab41d1..edea5ec 100644 --- a/frontend/app/features/notifications/components/NotificationEventSelector.tsx +++ b/frontend/app/features/notifications/components/NotificationEventSelector.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Check } from 'lucide-react'; import { notificationEvents } from '../state'; -import type { NotificationEventType } from '../../../../types'; +import type { NotificationEventType } from '../../../../shared/api-contract'; // NotificationEventSelectorProps 描述通知事件绑定组件的输入状态。 export interface NotificationEventSelectorProps { diff --git a/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx b/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx index ea41a2c..7bfbdda 100644 --- a/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx +++ b/frontend/app/features/notifications/components/NotificationSmtpSettings.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { Eye, EyeOff, Loader2, Mail, Save } from 'lucide-react'; -import type { SystemSettings } from '../../../../types'; +import type { SystemSettings } from '../../../../shared/api-contract'; // NotificationSmtpSettingsProps 描述系统 SMTP 配置面板所需的状态和事件。 export interface NotificationSmtpSettingsProps { diff --git a/frontend/app/features/notifications/hooks.test.tsx b/frontend/app/features/notifications/hooks.test.tsx index 6d5c658..ababd04 100644 --- a/frontend/app/features/notifications/hooks.test.tsx +++ b/frontend/app/features/notifications/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { NotificationChannel, SystemSettings } from '../../../types'; +import type { NotificationChannel, SystemSettings } from '../../../shared/api-contract'; import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api'; import { useNotifications } from './hooks'; diff --git a/frontend/app/features/notifications/hooks.ts b/frontend/app/features/notifications/hooks.ts index 83f53f5..8b901ac 100644 --- a/frontend/app/features/notifications/hooks.ts +++ b/frontend/app/features/notifications/hooks.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react'; -import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../types'; +import type { NotificationChannel, NotificationChannelType, SystemSettings } from '../../../shared/api-contract'; import { createNotificationChannel, deleteNotificationChannel, getNotificationChannels, getSystemSettings, testNotificationChannel, updateNotificationChannel, updateSystemSettings } from './api'; import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, notificationErrorMessage, normalizeNotificationForm, validateNotificationForm } from './state'; import type { NotificationForm, NotificationState } from './types'; diff --git a/frontend/components/Notifications.tsx b/frontend/app/features/notifications/pages/Notifications.tsx similarity index 90% rename from frontend/components/Notifications.tsx rename to frontend/app/features/notifications/pages/Notifications.tsx index e46c2a6..f860167 100644 --- a/frontend/components/Notifications.tsx +++ b/frontend/app/features/notifications/pages/Notifications.tsx @@ -1,9 +1,9 @@ import React from 'react'; import { Bell, Check, Loader2, Plus, RefreshCw, X } from 'lucide-react'; -import { NotificationChannelList } from '../app/features/notifications/components/NotificationChannelList'; -import { NotificationChannelModal } from '../app/features/notifications/components/NotificationChannelModal'; -import { NotificationSmtpSettings } from '../app/features/notifications/components/NotificationSmtpSettings'; -import { useNotifications } from '../app/features/notifications/hooks'; +import { NotificationChannelList } from '../components/NotificationChannelList'; +import { NotificationChannelModal } from '../components/NotificationChannelModal'; +import { NotificationSmtpSettings } from '../components/NotificationSmtpSettings'; +import { useNotifications } from '../hooks'; // NotificationsProps 描述通知页面接收的权限上下文。 interface NotificationsProps { diff --git a/frontend/app/features/notifications/state.test.ts b/frontend/app/features/notifications/state.test.ts index 5fef219..46fa742 100644 --- a/frontend/app/features/notifications/state.test.ts +++ b/frontend/app/features/notifications/state.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import type { NotificationChannel } from '../../../types'; +import type { NotificationChannel } from '../../../shared/api-contract'; import type { NotificationForm } from './types'; import { buildNotificationPayload, emptyNotificationForm, isCurrentNotificationRequest, normalizeNotificationForm, notificationErrorMessage, notificationEventSummary, validateNotificationForm } from './state'; diff --git a/frontend/app/features/notifications/state.ts b/frontend/app/features/notifications/state.ts index a4736e3..911c7a3 100644 --- a/frontend/app/features/notifications/state.ts +++ b/frontend/app/features/notifications/state.ts @@ -1,5 +1,5 @@ import { Bell, Mail, MessageCircle, Send as Telegram, Webhook } from 'lucide-react'; -import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types'; +import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract'; import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../../../notificationEmailConfig'; import type { NotificationChannelMeta, NotificationEventMeta, NotificationForm, NotificationPayload } from './types'; diff --git a/frontend/app/features/notifications/types.ts b/frontend/app/features/notifications/types.ts index 47bff39..fb23cc8 100644 --- a/frontend/app/features/notifications/types.ts +++ b/frontend/app/features/notifications/types.ts @@ -1,5 +1,5 @@ import type { Dispatch, ElementType, SetStateAction } from 'react'; -import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../types'; +import type { NotificationChannel, NotificationChannelType, NotificationEventType, SystemSettings } from '../../../shared/api-contract'; // NotificationField 描述通知渠道表单中的一个配置字段。 export interface NotificationField { diff --git a/frontend/app/features/orders/api.ts b/frontend/app/features/orders/api.ts index 36bc3d3..f25c93c 100644 --- a/frontend/app/features/orders/api.ts +++ b/frontend/app/features/orders/api.ts @@ -1,13 +1,166 @@ -export { - deleteOrder, - getAccountDetails, - getItems, - getOrders, - importOrders, - manualShipOrder, - syncOrders, - syncSingleOrder, - updateOrder, -} from '../../../services/api'; +import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client'; +import { + SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse, + AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, + Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, + NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, + CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse +} from '../../../shared/api-contract'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; -// 订单 feature 通过本文件声明服务 API 来源,页面不再直接依赖通用 API 模块。 +/** 订单筛选器读取非敏感账号摘要。 */ +export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); + +/** 订单关联商品展示读取当前商品索引。 */ +export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options); + +/** 管理员统计仍由订单域兼容 API 提供给历史管理页面。 */ +export const getAdminStats = async (): Promise => get('/api/v1/admin/stats'); +// Orders +// normalizeOrderStatus 归一化订单状态。 +const normalizeOrderStatus = (value: unknown): Order['status'] => { + // status 状态值,用于当前 API 处理流程。 + const status = String(value || ''); + if (status === 'paid') return 'pending_ship'; + return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status) + ? status as Order['status'] + : 'unknown'; +}; + +// getOrders 读取订单列表。 +export const getOrders = async ( + cookieId?: string, + status?: string, + page: number = 1, + pageSize: number = 20, + search?: string, + options?: RequestControlOptions, +): Promise> => { + // params 请求参数,用于当前 API 处理流程。 + const params: any = { page, page_size: pageSize }; + if (cookieId) params.cookie_id = cookieId; + if (status && status !== 'all') params.status = status; + if (search?.trim()) params.search = search.trim(); + + // res 接口响应结果,用于当前 API 处理流程。 + const response = await get('/api/v1/orders', params, options); + // res 是兼容直接分页对象、orders 别名和 data 包裹后的订单响应。 + const res = objectFrom> & { /** orders 是历史订单列表字段别名。 */ orders?: Order[] }>(response, ['data', 'result']) || {}; + + // Handle backend response variations + // rawOrders 原始订单列表,用于当前 API 处理流程。 + const rawOrders = Array.isArray(res.orders) ? res.orders : collectionFrom(res.data, ['data', 'orders', 'items']); + // orders 订单列表,用于当前 API 处理流程。 + const orders = rawOrders.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ + ...item, + id: item.id || item.order_id, + status: normalizeOrderStatus(item.status || item.order_status), + quantity: Number(item.quantity || 1), + })); + return { + success: true, + data: orders, + total: res.total || orders.length, + page: res.page || page, + page_size: res.page_size || pageSize, + total_pages: res.total_pages || 1 + }; +}; + +// getOrderDetail 读取订单详情。 +export const getOrderDetail = async (orderId: string): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: OrderDTOResponse }> => { + // result 接口响应结果,用于当前 API 处理流程。 + const result = await get(`/api/v1/orders/${orderId}`); + return { + success: true, + data: result.data + }; +}; + +// updateOrder 更新订单。 +export const updateOrder = async (orderId: string, data: Partial): Promise => { + return put(`/api/v1/orders/${orderId}`, data); +}; + +// deleteOrder 删除订单。 +export const deleteOrder = async (orderId: string): Promise => { + return del(`/api/v1/orders/${orderId}`); +}; + +// syncOrders 同步订单。 +export const syncOrders = async (cookieId?: string, status?: string, options?: RequestControlOptions): Promise => { + // formData 表单数据,用于当前 API 处理流程。 + const formData = new FormData(); + if (cookieId) formData.append('cookie_id', cookieId); + if (status) formData.append('status', status); + + // start 表示后台订单刷新任务创建响应。 + const start = await postForm('/api/v1/orders/refresh', formData, options); + // cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务。 + const cancelOnAbort = () => { + void cancelOrderRefreshJob(start.job_id).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined); + }; + options?.signal?.addEventListener('abort', cancelOnAbort, { once: true }); + // pollLimit 限制前端等待后台任务的轮询次数。 + const pollLimit = 180; + // pollIndex 表示当前订单刷新任务状态轮询次数。 + let pollIndex = 0; + try { + while (pollIndex < pollLimit) { + // job 表示当前轮询得到的后台任务状态。 + const job = await get(`/api/v1/orders/refresh/${start.job_id}`, undefined, options); + if (job.status === 'succeeded' && job.result) { + return job.result; + } + if (job.status === 'failed' || job.status === 'cancelled') { + throw new Error(job.error_message || '订单刷新任务失败'); + } + // waitMs 是下一次任务状态轮询前的等待时间。 + const waitMs = 500; + await new Promise(/* 轮询等待器负责等待下一次任务状态查询。 */ (resolve, reject) => { + // abort 负责响应调用方取消轮询。 + const abort = () => { + globalThis.clearTimeout(timer); + reject(new Error('请求已取消')); + }; + // timer 表示当前轮询等待定时器。 + const timer = globalThis.setTimeout(/* 轮询完成回调清理取消监听并结束等待。 */ () => { + options?.signal?.removeEventListener('abort', abort); + resolve(); + }, waitMs); + if (!options?.signal) return; + if (options.signal.aborted) abort(); + else options.signal.addEventListener('abort', abort, { once: true }); + }); + pollIndex += 1; + } + } finally { + options?.signal?.removeEventListener('abort', cancelOnAbort); + } + throw new Error('订单刷新任务等待超时'); +}; + +// cancelOrderRefreshJob 请求取消当前用户的订单刷新后台任务。 +export const cancelOrderRefreshJob = async (jobId: string): Promise => { + return del(`/api/v1/orders/refresh/${jobId}`); +}; + +// syncSingleOrder 同步单个订单。 +export const syncSingleOrder = async (orderId: string): Promise => { + return post(`/api/v1/orders/${orderId}/refresh`); +}; + +// manualShipOrder 手动发货订单。 +export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise => { + return post('/api/v1/orders/manual-ship', { + order_ids: orderIds, + ship_mode: shipMode, + }); +} + +// importOrders 导入订单。 +export const importOrders = async (data: Partial[] | FormData, options?: RequestControlOptions): Promise => { + // isFormData 是否为表单请求,用于当前 API 处理流程。 + const isFormData = data instanceof FormData; + return isFormData ? postForm('/api/v1/orders/import', data, options) : post('/api/v1/orders/import', data, options); +} diff --git a/frontend/app/features/orders/components/OrderFilterBar.tsx b/frontend/app/features/orders/components/OrderFilterBar.tsx index 8bddb5d..b486862 100644 --- a/frontend/app/features/orders/components/OrderFilterBar.tsx +++ b/frontend/app/features/orders/components/OrderFilterBar.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { Search, User as UserIcon } from 'lucide-react'; -import type { AccountDetail } from '../../../../types'; +import type { AccountDetail } from '../../../../shared/api-contract'; import { orderStatusOptions } from '../state'; // OrderFilterBarProps 描述订单状态、账号和文本筛选所需的页面状态。 diff --git a/frontend/app/features/orders/hooks.test.tsx b/frontend/app/features/orders/hooks.test.tsx index b1b7d79..b1b8132 100644 --- a/frontend/app/features/orders/hooks.test.tsx +++ b/frontend/app/features/orders/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail, Item } from '../../../types'; +import type { AccountDetail, Item } from '../../../shared/api-contract'; import { getAccountDetails, getItems, getOrders, importOrders } from './api'; import { useOrderImport, useOrderQuery } from './hooks'; @@ -287,4 +287,37 @@ describe('useOrderQuery 与 useOrderImport', /* 当前回调处理订单查询 expect(hook.result.current.orders).toEqual([orderFixture]); hook.unmount(); }); + + test('订单导入在卸载时取消未完成上传', /* 当前回调验证导入弹窗离开页面后不会接受忽略取消信号的旧响应。 */ async () => { + // importSignal 保存导入接口收到的取消信号。 + let importSignal: AbortSignal | undefined; + importOrdersMock.mockImplementation( + // pendingImport 保持文件上传未完成,以便观察 Hook 卸载时的取消行为。 + (_formData, requestOptions) => { + importSignal = requestOptions?.signal; + return new Promise(/* pendingImportExecutor 故意不完成导入 Promise,直到 Hook 卸载取消请求。 */ () => undefined); + }, + ); + // refreshOrders 是导入成功后刷新订单列表的替身。 + const refreshOrders = vi.fn().mockResolvedValue(undefined); + // hook 是订单导入 Hook 渲染结果。 + const hook = renderHook( + // importHookFactory 使用稳定的列表刷新回调创建导入 Hook。 + () => useOrderImport(refreshOrders), + ); + await act( + // fileAction 写入符合格式要求的订单导入文件。 + () => hook.result.current.setImportFile(new File(['order'], 'orders.csv')), + ); + await act( + // importAction 启动上传但不等待未完成网络请求。 + () => { void hook.result.current.handleImportOrders(); }, + ); + await waitFor( + // importStartedAssertion 等待导入请求建立取消信号。 + () => expect(importSignal).toBeDefined(), + ); + hook.unmount(); + expect(importSignal?.aborted).toBe(true); + }); }); diff --git a/frontend/app/features/orders/hooks.ts b/frontend/app/features/orders/hooks.ts index 54c370b..427cd42 100644 --- a/frontend/app/features/orders/hooks.ts +++ b/frontend/app/features/orders/hooks.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react'; -import type { AccountDetail, Item, Order } from '../../../types'; +import type { AccountDetail, Item, Order } from '../../../shared/api-contract'; import { getAccountDetails, getItems, getOrders, importOrders } from './api'; import { canSubmitOrderImport, isCurrentOrderRequest, normalizeOrderImportResult, orderErrorMessage, validateOrderImportFile } from './state'; import type { OrderImportState, OrderQueryState } from './types'; @@ -249,6 +249,18 @@ export const useOrderImport = (loadOrders: () => Promise): OrderImportStat // importAbort 保存当前导入请求的取消控制器。 const importAbort = useRef(null); + useEffect( + // 导入生命周期副作用负责在弹窗组件卸载时取消上传并禁止旧结果继续更新 React 状态。 + () => ( + // importRequestCleanup 推进导入代次并中止尚未结束的 multipart 请求。 + () => { + importGeneration.current += 1; + importAbort.current?.abort(); + } + ), + [], + ); + // openImportModal 打开订单导入弹窗并重置上一次结果。 const openImportModal = useCallback( // 打开弹窗回调清理上一次导入状态。 diff --git a/frontend/app/features/orders/orderActions.test.tsx b/frontend/app/features/orders/orderActions.test.tsx index c33b32e..ec68e24 100644 --- a/frontend/app/features/orders/orderActions.test.tsx +++ b/frontend/app/features/orders/orderActions.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import type { Order } from '../../../types'; +import type { Order } from '../../../shared/api-contract'; import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api'; import { useOrderActions } from './orderActions'; diff --git a/frontend/app/features/orders/orderActions.ts b/frontend/app/features/orders/orderActions.ts index 093fb21..0002f26 100644 --- a/frontend/app/features/orders/orderActions.ts +++ b/frontend/app/features/orders/orderActions.ts @@ -1,5 +1,5 @@ import { useCallback, useState, type Dispatch, type SetStateAction } from 'react'; -import type { Order, OrderStatus } from '../../../types'; +import type { Order, OrderStatus } from '../../../shared/api-contract'; import { deleteOrder, manualShipOrder, syncOrders, syncSingleOrder, updateOrder } from './api'; // OrderShipMode 表示订单发货操作的两种业务模式。 diff --git a/frontend/components/OrderList.test.tsx b/frontend/app/features/orders/pages/OrderList.test.tsx similarity index 94% rename from frontend/components/OrderList.test.tsx rename to frontend/app/features/orders/pages/OrderList.test.tsx index cd6350f..7c9f47f 100644 --- a/frontend/components/OrderList.test.tsx +++ b/frontend/app/features/orders/pages/OrderList.test.tsx @@ -2,7 +2,7 @@ import React from 'react'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; -import type { Order } from '../types'; +import type { Order } from '../../../../shared/api-contract'; // orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。 const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({ @@ -24,7 +24,7 @@ const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共 deleteOrder: vi.fn(), })); -vi.mock('../app/features/orders/hooks', /* ordersHooksMockFactory 提供订单查询与导入 Hook 替身。 */ () => ({ +vi.mock('../hooks', /* ordersHooksMockFactory 提供订单查询与导入 Hook 替身。 */ () => ({ useOrderQuery: /* useOrderQueryMock 返回订单页面固定查询状态。 */ () => ({ orders: orderListMocks.orders, accounts: [{ id: 'account-1', enabled: true, auto_confirm: false, nickname: 'Alpha', remark: '主账号' }], @@ -57,7 +57,7 @@ vi.mock('../app/features/orders/hooks', /* ordersHooksMockFactory 提供订单 }), })); -vi.mock('../app/features/orders/api', /* ordersApiMockFactory 提供订单页面动作 API 替身。 */ () => ({ +vi.mock('../api', /* ordersApiMockFactory 提供订单页面动作 API 替身。 */ () => ({ syncOrders: orderListMocks.syncOrders, syncSingleOrder: orderListMocks.syncSingleOrder, manualShipOrder: orderListMocks.manualShipOrder, @@ -65,7 +65,7 @@ vi.mock('../app/features/orders/api', /* ordersApiMockFactory 提供订单页面 deleteOrder: orderListMocks.deleteOrder, })); -vi.mock('../app/features/orders/components/OrderFilterBar', /* filterBarMockFactory 提供订单筛选栏替身。 */ () => { +vi.mock('../components/OrderFilterBar', /* filterBarMockFactory 提供订单筛选栏替身。 */ () => { // OrderFilterBarMock 暴露筛选栏的状态切换和输入事件。 const OrderFilterBarMock: React.FC = (props /* props 表示筛选栏状态和事件回调。 */) => (
@@ -80,7 +80,7 @@ vi.mock('../app/features/orders/components/OrderFilterBar', /* filterBarMockFact return { OrderFilterBar: OrderFilterBarMock }; }); -vi.mock('../app/features/orders/components/OrderImportModal', /* importModalMockFactory 提供订单导入弹窗替身。 */ () => ({ +vi.mock('../components/OrderImportModal', /* importModalMockFactory 提供订单导入弹窗替身。 */ () => ({ OrderImportModal: /* OrderImportModalMock 表示订单导入弹窗替身。 */ (props: any) => props.showImportModal ?
订单导入弹窗
: null, })); diff --git a/frontend/components/OrderList.tsx b/frontend/app/features/orders/pages/OrderList.tsx similarity index 98% rename from frontend/components/OrderList.tsx rename to frontend/app/features/orders/pages/OrderList.tsx index bfc61a4..90b6b61 100644 --- a/frontend/components/OrderList.tsx +++ b/frontend/app/features/orders/pages/OrderList.tsx @@ -1,12 +1,12 @@ import React from 'react'; import { createPortal } from 'react-dom'; -import type { OrderStatus } from '../types'; -import { OrderFilterBar } from '../app/features/orders/components/OrderFilterBar'; -import { OrderImportModal } from '../app/features/orders/components/OrderImportModal'; -import { useOrderImport, useOrderQuery } from '../app/features/orders/hooks'; -import { useOrderActions } from '../app/features/orders/orderActions'; +import type { OrderStatus } from '../../../../shared/api-contract'; +import { OrderFilterBar } from '../components/OrderFilterBar'; +import { OrderImportModal } from '../components/OrderImportModal'; +import { useOrderImport, useOrderQuery } from '../hooks'; +import { useOrderActions } from '../orderActions'; import { Truck, RefreshCw, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, ExternalLink, Trash2 } from 'lucide-react'; -import { formatLocalDateTime } from '../dateTime'; +import { formatLocalDateTime } from '../../../../dateTime'; // StatusBadge 渲染订单状态徽标。 const StatusBadge: React.FC<{ /** status 表示状态。 */ status: OrderStatus }> = ({ status }) => { diff --git a/frontend/app/features/orders/types.ts b/frontend/app/features/orders/types.ts index 6e846f3..083a104 100644 --- a/frontend/app/features/orders/types.ts +++ b/frontend/app/features/orders/types.ts @@ -1,5 +1,5 @@ import type { Dispatch, SetStateAction } from 'react'; -import type { AccountDetail, Item, Order, OrderStatus } from '../../../types'; +import type { AccountDetail, Item, Order, OrderStatus } from '../../../shared/api-contract'; // OrderImportRowResult 描述订单导入接口返回的单行处理结果。 export interface OrderImportRowResult { diff --git a/frontend/app/features/presentational-components.test.tsx b/frontend/app/features/presentational-components.test.tsx index bfcd051..6a94b41 100644 --- a/frontend/app/features/presentational-components.test.tsx +++ b/frontend/app/features/presentational-components.test.tsx @@ -1,7 +1,7 @@ import ReactDOMServer from 'react-dom/server'; import { describe, expect, test } from 'vitest'; -import type { NotificationChannel } from '../../types'; -import type { SystemSettings } from '../../types'; +import type { NotificationChannel } from '../../shared/api-contract'; +import type { SystemSettings } from '../../shared/api-contract'; import { CardIcon } from './cards/components/CardIcon'; import { BatchPhaseIndicator } from './items/components/BatchPhaseIndicator'; import { NotificationChannelList } from './notifications/components/NotificationChannelList'; diff --git a/frontend/app/features/rules/api.ts b/frontend/app/features/rules/api.ts index c177169..ac58920 100644 --- a/frontend/app/features/rules/api.ts +++ b/frontend/app/features/rules/api.ts @@ -1,24 +1,355 @@ -// 规则 feature 只通过本适配层访问共享 API,组件不直接依赖网络客户端。 -export { - clearDefaultReplyRecords, - deleteDefaultReply, - deleteReplyRule, - deleteShippingRule, - getAccountDetails, - getCards, - getDefaultReplies, - getDefaultReply, - getItems, - getAutomationIssues, - getReplyRules, - getShippingRules, - getShippingRulesPage, - updateDefaultReply, - updateReplyRule, - updateShippingRule, - resolveAutomationRun, - resolveDeferredAutomationTask, -} from '../../../services/api'; +import { get, post, put, del, postForm, type RequestControlOptions } from '../../../shared/http/client'; +import { + SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse, + AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, + Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, + NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, + CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse +} from '../../../shared/api-contract'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; -// 规则异常类型由共享 API 层定义,feature 通过类型重导出保持边界稳定。 -export type { AutomationRunIssue, DeferredAutomationIssue } from '../../../services/api'; +/** 自动化规则筛选器读取非敏感账号摘要。 */ +export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); + +/** 自动化动作编辑器读取可选卡券组。 */ +export const getCards = async (options?: RequestControlOptions): Promise => get('/api/v1/cards', undefined, options); + +/** 自动化规则商品选择器读取商品索引。 */ +export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options); +// Rules - 自动化规则 +const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ + id: String(item.id), + name: item.name || '', + trigger_type: item.trigger_type || 'order_paid', + item_keyword: item.item_title || item.item_id || '', + cookie_id: item.cookie_id || '', + item_id: item.item_id || '', + item_title: item.item_title || '', + card_group_id: Number((item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_id || 0), + card_group_name: (item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_name || '', + priority: item.priority || 100, + enabled: item.enabled || false, + config_json: item.config_json || '{}', + actions: (item.actions || []).map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => ({ + id: action.id ? String(action.id) : undefined, + action_type: action.action_type, + card_id: Number(action.card_id || 0), + card_name: action.card_name || '', + delivery_count: Number(action.delivery_count || 1), + message_template: action.message_template || '', + delay_seconds: Number(action.delay_seconds || 0), + config_json: action.config_json || '{}', + enabled: action.enabled !== false, + sort_order: Number(action.sort_order || 0), + })), + variants: (item.actions || []) + .filter(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => action.action_type === 'send_card') + .map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => { + // cfg 动作配置,用于当前 API 处理流程。 + let cfg: any = {}; + try { cfg = JSON.parse(action.config_json || '{}'); } catch {} + return { + id: action.id ? String(action.id) : undefined, + spec_name: cfg.spec_name || '', + spec_value: cfg.spec_value || '', + card_id: Number(action.card_id || 0), + card_name: action.card_name || '', + delivery_count: Number(action.delivery_count || 1), + enabled: action.enabled !== false, + delay_override: cfg.delay_override === true, + delay_seconds: Number(action.delay_seconds || 0), + config_json: action.config_json || '{}', + }; + }), + })); + +// getShippingRules 读取发货规则列表。 +export const getShippingRules = async (): Promise => { + // res 接口响应结果,用于当前 API 处理流程。 + const res = await get('/api/v1/automation-rules'); + // rules 规则列表,用于当前 API 处理流程。 + const rules = collectionFrom(res, ['data', 'rules', 'items']); + return normalizeShippingRules(rules); +} + +export interface ShippingRuleListParams { + /** cookieId 表示登录凭证标识。 */ cookieId?: string; + /** triggerType 表示触发类型。 */ triggerType?: AutomationTriggerType | ''; + /** enabled 表示启用状态。 */ enabled?: boolean; + /** search 表示搜索条件。 */ search?: string; + /** page 表示页码。 */ page?: number; + /** pageSize 表示每页数量。 */ pageSize?: number; +} + +// getShippingRulesPage 分页读取发货规则。 +export const getShippingRulesPage = async ({ + cookieId, + triggerType, + enabled, + search, + page: requestedPage = 1, + pageSize = 10, +}: ShippingRuleListParams = {}): Promise> => { + // res 接口响应结果,用于当前 API 处理流程。 + const response = await get('/api/v1/automation-rules', { + page: requestedPage, + page_size: pageSize, + cookie_id: cookieId || undefined, + trigger_type: triggerType || undefined, + enabled, + search: search?.trim() || undefined, + }); + // rules 规则列表,用于当前 API 处理流程。 + // page 是兼容直接分页对象和 data 包裹后的分页元数据。 + const pageMeta = objectFrom>(response, ['data', 'result']) || {}; + // rules 是归一化后的自动化规则列表。 + const rules = normalizeShippingRules(collectionFrom(response, ['data', 'rules', 'items'])); + return { + success: true, + data: rules, + total: Number(pageMeta.total ?? rules.length), + page: Number(pageMeta.page ?? requestedPage), + page_size: Number(pageMeta.page_size ?? pageSize), + total_pages: Number(pageMeta.total_pages ?? (rules.length ? 1 : 0)), + trigger_counts: Object.fromEntries( + Object.entries(pageMeta.trigger_counts || {}).map(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => [key, Number(value)]), + ), + }; +} + +// orderAutomationActions 构建订单自动化动作。 +const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => { + if (triggerType !== 'order_paid') { + return actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: action.sort_order || index + 1 })); + } + // sendCards 发送Cards。 + const sendCards = actions + .filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type === 'send_card') + .map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: index + 1 })); + // others 其他动作列表,用于当前 API 处理流程。 + const others = actions.filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment'); + return [ + ...sendCards, + ...others.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: sendCards.length + index + 1 })), + { action_type: 'confirm_shipment' as const, enabled: true, sort_order: sendCards.length + others.length + 1 }, + ]; +}; + +// updateShippingRule 更新发货规则。 +export const updateShippingRule = async (rule: Partial): Promise => { + // triggerType 触发类型,用于当前 API 处理流程。 + const triggerType = rule.trigger_type || 'order_paid'; + // triggerName 触发名称,用于当前 API 处理流程。 + const triggerName: Record = { + order_paid: '付款后自动发货', + buyer_reviewed: '评价后发送赠品', + review_missing_timeout: '超时未评价求评价', + }; + // generatedName 生成d名称。 + const generatedName = [ + triggerName[triggerType] || '自动化规则', + rule.item_title || rule.item_id || rule.cookie_id || '', + ].filter(Boolean).join(' - '); + // preservedNonCardActions 保留的非卡密动作,用于当前 API 处理流程。 + const preservedNonCardActions = (rule.actions || []).filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment'); + // baseActions 基础动作列表,用于当前 API 处理流程。 + const baseActions: AutomationAction[] = rule.variants && rule.variants.length > 0 + ? [...rule.variants.map(/* 当前回调用于处理集合元素或接口响应。 */ (variant, index) => ({ + action_type: 'send_card' as const, + card_id: variant.card_id, + delivery_count: variant.delivery_count || 1, + enabled: variant.enabled !== false, + sort_order: index + 1, + delay_seconds: variant.delay_seconds || 0, + config_json: JSON.stringify({ + spec_name: variant.spec_name || '', + spec_value: variant.spec_value || '', + delay_override: variant.delay_override === true, + }), + })), ...preservedNonCardActions] + : (rule.actions && rule.actions.length > 0 ? rule.actions : [{ + action_type: 'send_card' as const, + card_id: rule.card_group_id || 0, + delivery_count: 1, + enabled: true, + sort_order: 1, + }]); + // actions 动作列表,用于当前 API 处理流程。 + const actions = orderAutomationActions(triggerType, baseActions); + // payload 请求载荷,用于当前 API 处理流程。 + const payload = { + cookie_id: rule.cookie_id || '', + item_id: rule.item_id || '', + name: (rule.name || '').trim() || generatedName || '自动化规则', + trigger_type: triggerType, + enabled: rule.enabled ?? true, + priority: rule.priority || 100, + config_json: rule.config_json || '{}', + actions: actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ + action_type: action.action_type, + card_id: action.card_id || 0, + delivery_count: action.delivery_count || 1, + message_template: action.message_template || '', + delay_seconds: action.delay_seconds || 0, + config_json: action.config_json || '{}', + enabled: action.enabled !== false, + sort_order: action.sort_order || index + 1, + })), + }; + return rule.id ? put(`/api/v1/automation-rules/${rule.id}`, payload) : post('/api/v1/automation-rules', payload); +} + +// deleteShippingRule 删除发货规则。 +export const deleteShippingRule = async (id: string): Promise => del(`/api/v1/automation-rules/${id}`); + +export interface AutomationRunIssue { + /** id 表示标识。 */ id: number; + /** cookie_id 表示登录凭证标识。 */ cookie_id: string; + /** order_id 表示订单标识。 */ order_id: string; + /** trigger_type 表示触发条件类型。 */ trigger_type: string; + /** error_message 表示错误消息。 */ error_message: string; + /** issue_kind 表示问题类型。 */ issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed'; + /** allowed_resolutions 表示允许的解决方式。 */ allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>; + /** action_cursor 表示动作游标。 */ action_cursor: number; + /** sent_count 表示已发送数量。 */ sent_count: number; + /** updated_at 表示最后更新时间。 */ updated_at: string; +} + +export interface DeferredAutomationIssue { + /** id 表示标识。 */ id: number; + /** cookie_id 表示登录凭证标识。 */ cookie_id: string; + /** trigger_type 表示触发条件类型。 */ trigger_type: string; + /** error_message 表示错误消息。 */ error_message: string; + /** attempt_count 表示尝试次数。 */ attempt_count: number; + /** updated_at 表示最后更新时间。 */ updated_at: string; +} + +// getAutomationIssues 读取自动化问题列表。 +export const getAutomationIssues = async (): Promise<{ /** runs 表示运行记录。 */ runs: AutomationRunIssue[]; /** pending_tasks 表示待处理任务列表。 */ pending_tasks: DeferredAutomationIssue[] }> => { + // response 是兼容直接问题对象、data 包裹和 null 的自动化问题响应。 + const response = await get('/api/v1/automation-issues'); + // result 是去除历史包裹后的自动化问题对象。 + const result = objectFrom>(response, ['data', 'result']) || {}; + return { + runs: Array.isArray(result?.runs) ? result.runs : [], + pending_tasks: Array.isArray(result?.pending_tasks) ? result.pending_tasks : [], + }; +}; + +// resolveAutomationRun 处理自动化运行记录。 +export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise => + post(`/api/v1/automation-runs/${id}/resolve`, { resolution }); + +// resolveDeferredAutomationTask 处理延迟自动化任务。 +export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise => + post(`/api/v1/automation-pending-tasks/${id}/resolve`, { resolution }); + +// Rules - 关键词回复规则 (使用关键词API) +type KeywordRowPayload = { + /** id 表示标识。 */ id: string; + /** keyword 表示关键词。 */ keyword: string; + /** reply 表示回复内容。 */ reply: string; + /** item_id 表示商品标识。 */ item_id: string; + /** type 表示规则类型。 */ type: 'text' | 'image'; + /** image_url 表示图片地址。 */ image_url: string; +}; + +// normalizeKeywordRow 归一化关键词规则。 +const normalizeKeywordRow = (item: any): KeywordRowPayload => ({ + id: String(item?.id || ''), + keyword: item?.keyword || '', + reply: item?.reply || '', + item_id: item?.item_id || '', + type: item?.type === 'image' ? 'image' : 'text', + image_url: item?.image_url || '', +}); + +// getKeywordRowsWithType 读取带类型的关键词规则。 +const getKeywordRowsWithType = async (cookieId: string): Promise => { + // existing 已有规则,用于当前 API 处理流程。 + const existing = await get(`/api/v1/reply-rules/${cookieId}/typed`); + return collectionFrom(existing, ['data', 'items', 'rules']).map(normalizeKeywordRow); +}; + +// getReplyRules 读取回复规则。 +export const getReplyRules = async (cookieId?: string): Promise => { + if (!cookieId) return []; + // keywords keywords,用于当前 API 处理流程。 + const keywords = await getKeywordRowsWithType(cookieId); + return keywords.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ + id: item.id, + keyword: item.keyword || '', + reply_content: item.reply || '', + match_type: 'fuzzy' as const, + enabled: true, + item_id: item.item_id || '', + type: item.type === 'image' ? 'image' : 'text', + image_url: item.image_url || '' + })); +} + +// updateReplyRule 更新回复规则。 +export const updateReplyRule = async (rule: Partial, cookieId: string): Promise => { + // type 规则类型,用于当前 API 处理流程。 + const type = rule.type || 'text'; + // payload 请求载荷,用于当前 API 处理流程。 + const payload = { + keyword: rule.keyword || '', + reply: type === 'text' ? (rule.reply_content || '') : '', + item_id: rule.item_id || '', + type, + image_url: type === 'image' ? (rule.image_url || '') : '', + }; + return rule.id + ? put(`/api/v1/reply-rules/${cookieId}/typed/${rule.id}`, payload) + : post(`/api/v1/reply-rules/${cookieId}/items`, payload); +} + +// deleteReplyRule 删除回复规则。 +export const deleteReplyRule = async (id: string, cookieId: string): Promise => { + return del(`/api/v1/reply-rules/${cookieId}/typed/${id}`); +} + + +// Default Reply +// getDefaultReplies 读取默认回复列表。 +export const getDefaultReplies = async (): Promise> => { + const response = await get('/api/v1/default-replies'); + // replies 是兼容直接映射、data 包裹和 null 的默认回复索引。 + return objectFrom>(response, ['data', 'replies', 'items']) || {}; +}; + +// getDefaultReply 读取默认回复。 +export const getDefaultReply = async (cookieId: string): Promise => { + // result 接口响应结果,用于当前 API 处理流程。 + const response = await get(`/api/v1/default-replies/${cookieId}`); + // result 是兼容直接默认回复和 data 包裹后的对象。 + const result = objectFrom>(response, ['data', 'result']) || {}; + return { + cookie_id: cookieId, + enabled: result.enabled || false, + reply_content: result.reply_content || '', + reply_once: result.reply_once || false, + reply_image_url: result.reply_image_url || '' + }; +}; + +// updateDefaultReply 更新默认回复。 +export const updateDefaultReply = async (cookieId: string, data: Partial): Promise => { + return put(`/api/v1/default-replies/${cookieId}`, { + enabled: data.enabled ?? false, + reply_content: data.reply_content || '', + reply_once: data.reply_once ?? false, + reply_image_url: data.reply_image_url || '' + }); +}; + +// deleteDefaultReply 删除默认回复。 +export const deleteDefaultReply = async (cookieId: string): Promise => { + return del(`/api/v1/default-replies/${cookieId}`); +}; + +// clearDefaultReplyRecords 清理默认回复记录。 +export const clearDefaultReplyRecords = async (cookieId: string): Promise => { + return post(`/api/v1/default-replies/${cookieId}/clear-records`, {}); +}; diff --git a/frontend/app/features/rules/hooks.test.tsx b/frontend/app/features/rules/hooks.test.tsx index 00fc417..a722a3a 100644 --- a/frontend/app/features/rules/hooks.test.tsx +++ b/frontend/app/features/rules/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { AccountDetail, Card, DefaultReply, Item, ReplyRule, ShippingRule } from '../../../types'; +import type { AccountDetail, Card, DefaultReply, Item, ReplyRule, ShippingRule } from '../../../shared/api-contract'; import { getAccountDetails, getAutomationIssues, diff --git a/frontend/app/features/rules/hooks.ts b/frontend/app/features/rules/hooks.ts index 0d2020f..38b98b1 100644 --- a/frontend/app/features/rules/hooks.ts +++ b/frontend/app/features/rules/hooks.ts @@ -16,7 +16,7 @@ import type { Item, ReplyRule, ShippingRule, -} from '../../../types'; +} from '../../../shared/api-contract'; import type { AutomationIssueState, RulesDataOptions, RulesDataResult, RulesTab } from './types'; import { isCurrentRequest, nextRequestGeneration } from './interactionState'; diff --git a/frontend/components/Rules.tsx b/frontend/app/features/rules/pages/Rules.tsx similarity index 99% rename from frontend/components/Rules.tsx rename to frontend/app/features/rules/pages/Rules.tsx index 8ee39bc..311dcfc 100644 --- a/frontend/components/Rules.tsx +++ b/frontend/app/features/rules/pages/Rules.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useMemo, useState } from 'react'; import { createPortal } from 'react-dom'; -import type { AutomationTriggerType } from '../app/features/rules/types'; +import type { AutomationTriggerType } from '../types'; import { AlertCircle, Bot, @@ -21,12 +21,12 @@ import { X, Zap, } from 'lucide-react'; -import { AutomationIssuePanel } from '../app/features/rules/components/AutomationIssuePanel'; -import { useRulesData } from '../app/features/rules/hooks'; -import { filterAutomationIssues } from '../app/features/rules/issueState'; -import { triggerMeta, triggerOrder, actionSummary, accentClasses, statusPill, accountLabel, buildReviewConfig, cardActionsForTrigger } from '../app/features/rules/utils'; -import type { RulesProps, RulesTab } from '../app/features/rules/types'; -import { useRuleActions } from '../app/features/rules/ruleActions'; +import { AutomationIssuePanel } from '../components/AutomationIssuePanel'; +import { useRulesData } from '../hooks'; +import { filterAutomationIssues } from '../issueState'; +import { triggerMeta, triggerOrder, actionSummary, accentClasses, statusPill, accountLabel, buildReviewConfig, cardActionsForTrigger } from '../utils'; +import type { RulesProps, RulesTab } from '../types'; +import { useRuleActions } from '../ruleActions'; // Rules 是规则 feature 在旧页面目录下保留的兼容入口组件。 const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHandled }) => { diff --git a/frontend/app/features/rules/types.ts b/frontend/app/features/rules/types.ts index ad27c49..94c9a5a 100644 --- a/frontend/app/features/rules/types.ts +++ b/frontend/app/features/rules/types.ts @@ -9,7 +9,7 @@ import type { ReplyRule, ShippingRule, ShippingVariant, -} from '../../../types'; +} from '../../../shared/api-contract'; import type { AutomationRunIssue, DeferredAutomationIssue } from './api'; // Rules feature 通过此类型入口重导出共享领域模型,避免页面直接依赖全局类型文件。 @@ -23,7 +23,7 @@ export type { ReplyRule, ShippingRule, ShippingVariant, -} from '../../../types'; +} from '../../../shared/api-contract'; // RulesTab 表示规则页面的三个业务页签。 export type RulesTab = 'automation' | 'reply' | 'default'; diff --git a/frontend/app/features/rules/utils.test.ts b/frontend/app/features/rules/utils.test.ts index 55656bc..73239f0 100644 --- a/frontend/app/features/rules/utils.test.ts +++ b/frontend/app/features/rules/utils.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'vitest'; -import type { AccountDetail, ShippingRule } from '../../../types'; +import type { AccountDetail, ShippingRule } from '../../../shared/api-contract'; import { accentClasses, accountLabel, diff --git a/frontend/app/features/rules/utils.ts b/frontend/app/features/rules/utils.ts index d05130b..f1b504e 100644 --- a/frontend/app/features/rules/utils.ts +++ b/frontend/app/features/rules/utils.ts @@ -5,7 +5,7 @@ import type { AutomationTriggerType, ShippingRule, ShippingVariant, -} from '../../../types'; +} from '../../../shared/api-contract'; import type { TriggerMeta } from './types'; // triggerMeta 是自动化触发类型的统一展示元数据,供列表和编辑器复用。 diff --git a/frontend/app/features/session/api.ts b/frontend/app/features/session/api.ts index 91b4ec4..d90e68c 100644 --- a/frontend/app/features/session/api.ts +++ b/frontend/app/features/session/api.ts @@ -1,2 +1,40 @@ -// Session feature 只通过本适配层访问会话相关网络接口。 -export { initializeAdmin, login, logout, verifySession } from '../../../services/api'; +import { get, post, type RequestControlOptions } from '../../../shared/http/client'; +import type { OperationResponse, SessionResponse } from '../../../shared/api-contract'; + +/** 会话状态接口返回的只读传输契约。 */ +export interface SessionStatusResponse { + /** 当前浏览器会话是否已认证。 */ + authenticated: boolean; + /** 服务是否已经完成首次管理员初始化。 */ + initialized?: boolean; + /** 当前登录用户的数据库标识。 */ + user_id?: number; + /** 当前登录用户的名称。 */ + username?: string; + /** 当前登录用户是否具备管理员权限。 */ + is_admin?: boolean; +} + +/** 登录请求的具名传输 DTO。 */ +export interface LoginRequest { + /** 用户名登录方式使用的账号名称。 */ + username?: string; + /** 用户名登录方式使用的密码,仅在本次请求体中存在。 */ + password?: string; + /** 邮箱验证码登录方式使用的邮箱地址。 */ + email?: string; + /** 邮箱验证码登录方式使用的一次性验证码。 */ + verification_code?: string; +} + +/** 以用户名密码或邮箱验证码建立管理会话。 */ +export const login = async (data: LoginRequest): Promise => post('/api/v1/session/login', data, { skipAuthLogout: true }); + +/** 用首次设置的管理员密码完成系统初始化并建立会话。 */ +export const initializeAdmin = async (password: string): Promise => post('/api/v1/session/initialize', { password }, { skipAuthLogout: true }); + +/** 读取当前浏览器的认证与初始化状态,调用者可取消页面卸载前的请求。 */ +export const verifySession = async (options?: RequestControlOptions): Promise => get('/api/v1/session', undefined, options); + +/** 结束当前浏览器会话。 */ +export const logout = async (): Promise => post('/api/v1/session/logout', {}); diff --git a/frontend/app/features/session/pages/SessionGate.tsx b/frontend/app/features/session/pages/SessionGate.tsx new file mode 100644 index 0000000..78f06ca --- /dev/null +++ b/frontend/app/features/session/pages/SessionGate.tsx @@ -0,0 +1,158 @@ +import React, { useState } from 'react'; +import { ArrowRight, Loader2, Lock, ShieldCheck, User } from 'lucide-react'; +import { YdisksBrandIcon } from '../../../../shared/ui/YdisksLogo'; +import { useSession } from '../../../providers/SessionProvider'; + +/** SessionGate 在会话校验完成前显示加载状态,并承载首次初始化和管理员登录表单。 */ +export const SessionGate: React.FC = () => { + // checkingAuth 与 needsInit 是 Provider 维护的会话服务端状态,页面不自行请求认证接口。 + const { checkingAuth, needsInit, signIn, initialize } = useSession(); + // username 与 password 是登录表单短暂状态,永不写入持久化存储。 + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + // initialPassword 与 initialPasswordConfirm 是首次初始化时一次性提交的秘密输入。 + const [initialPassword, setInitialPassword] = useState(''); + const [initialPasswordConfirm, setInitialPasswordConfirm] = useState(''); + // isSubmitting 区分当前正在提交的表单,防止重复发起认证或初始化请求。 + const [isSubmitting, setIsSubmitting] = useState(false); + // formError 是仅用于当前界面显示的通用失败信息,不保存接口响应载荷。 + const [formError, setFormError] = useState(''); + + /** handleLogin 在管理员明确提交后调用 Provider 登录,并在失败时展示安全错误文本。 */ + const handleLogin = async (event: React.FormEvent): Promise => { + event.preventDefault(); + setIsSubmitting(true); + setFormError(''); + try { + // response 是服务端登录契约,只使用其公开的成功和消息字段。 + const response = await signIn({ username, password }); + if (!response.success) setFormError(response.message || '登录失败'); + } catch (error /* error 是认证请求失败原因,不能包含或重显密码。 */) { + setFormError(error instanceof Error ? error.message || '登录失败' : '登录失败'); + } finally { + setIsSubmitting(false); + } + }; + + /** handleInitialize 校验两次管理员密码后提交首次初始化,并在成功后立即清空输入。 */ + const handleInitialize = async (event: React.FormEvent): Promise => { + event.preventDefault(); + setFormError(''); + if (initialPassword.length < 8) { + setFormError('密码至少需要 8 个字符'); + return; + } + if (initialPassword !== initialPasswordConfirm) { + setFormError('两次输入的密码不一致'); + return; + } + + setIsSubmitting(true); + try { + // response 是首次初始化接口返回的公开认证结果。 + const response = await initialize(initialPassword); + if (!response.success) { + setFormError(response.message || '初始化失败,请重试'); + return; + } + setInitialPassword(''); + setInitialPasswordConfirm(''); + } catch (error /* error 是初始化请求失败原因,不输出用户输入的密码。 */) { + setFormError(error instanceof Error ? error.message || '初始化失败,请重试' : '初始化失败,请重试'); + } finally { + setIsSubmitting(false); + } + }; + + if (checkingAuth) { + return ( +
+ +
+ ); + } + + // heading 是当前认证流程的页面标题,保证初始化和登录表单使用一致视觉壳。 + const heading = needsInit ? '首次设置管理员密码' : '欢迎回来'; + // description 是当前认证流程的辅助说明,不泄露任何会话或账户敏感数据。 + const description = needsInit ? '设置完成后会自动进入系统,管理员账号为 admin。' : 'Ydisks闲鱼助手 · 自动发货与管家系统'; + + return ( +
+
+
+
+ +
+

{heading}

+

{description}

+
+ + {needsInit ? ( +
+ + + + + ) : ( +
+ + + + + )} + + {formError ?

{formError}

: null} +
+
+ ); +}; + +/** SubmitButton 为认证表单提供固定尺寸的提交控件,避免加载状态改变布局。 */ +const SubmitButton: React.FC<{ /** submitting 表示认证请求是否仍在执行。 */ submitting: boolean; /** text 是按钮在空闲时显示的操作名称。 */ text: string }> = ({ submitting, text }) => ( + +); diff --git a/frontend/app/features/settings/api.ts b/frontend/app/features/settings/api.ts index daad3f9..0e4d43f 100644 --- a/frontend/app/features/settings/api.ts +++ b/frontend/app/features/settings/api.ts @@ -1,2 +1,99 @@ -/** Settings feature 使用的系统配置与身份 API。 */ -export { fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings, verifySession } from '../../../services/api'; +import { get, post, put, type RequestControlOptions } from '../../../shared/http/client'; +import type { AIModelsResponse, OperationResponse, SystemSettings } from '../../../shared/api-contract'; + +/** 设置页面使用的会话状态传输契约,避免跨 feature 依赖。 */ +export interface SettingsSessionStatusResponse { + /** 当前浏览器会话是否已认证。 */ + authenticated: boolean; + /** 服务是否已经完成首次管理员初始化。 */ + initialized?: boolean; + /** 当前用户的数据库标识。 */ + user_id?: number; + /** 当前用户的登录名称。 */ + username?: string; + /** 当前用户是否具有管理员权限。 */ + is_admin?: boolean; +} + +/** 敏感系统设置的显式三态变更命令。 */ +export type SensitiveSettingChange = { + /** 敏感值的保存策略。 */ + action: 'retain' | 'replace' | 'clear'; + /** replace 策略需要保存的新值,只存在于提交请求中。 */ + value?: string; +}; + +/** 系统设置更新请求,将普通配置与敏感命令分开传输。 */ +export type SystemSettingsUpdate = { + /** 非敏感配置字段。 */ + values?: Record; + /** 由服务端解释的敏感值变更命令。 */ + secrets?: Record; +}; + +/** SENSITIVE_SYSTEM_SETTING_KEYS 标识不得写入普通 values 的秘密键。 */ +const SENSITIVE_SYSTEM_SETTING_KEYS = new Set(['ai_api_key', 'smtp_password', 'qq_reply_secret_key', 'captcha.remote_secret_key']); + +/** 将历史设置草稿转换为服务端要求的普通值与敏感命令结构。 */ +const normalizeSystemSettingsUpdate = (settings: Partial | SystemSettingsUpdate): Record => { + if ('values' in settings || 'secrets' in settings) return settings; + // values 保存普通设置,永不容纳秘密文本。 + const values: Record = {}; + // secrets 保存服务端需要独立处理的敏感设置命令。 + const secrets: Record = {}; + for (const /* key、value 是当前待分流的设置键和值。 */ [key, value] of Object.entries(settings)) { + if (value === undefined || value === null) continue; + if (SENSITIVE_SYSTEM_SETTING_KEYS.has(key)) { + secrets[key] = value === '' ? { action: 'clear' } : { action: 'replace', value: String(value) }; + continue; + } + values[key] = value; + } + return Object.keys(secrets).length > 0 ? { values, secrets } : values; +}; + +/** 将服务端可兼容的字符串和数值设置归一为 UI 可消费的只读契约。 */ +const normalizeSettings = (settings: Record): SystemSettings => { + // result 是不修改原始响应的设置副本。 + const result: Record = { ...settings }; + // sensitiveKey 是当前需要转为布尔状态的敏感键。 + for (const /* sensitiveKey 是当前需要读取配置状态的敏感设置键。 */ sensitiveKey of SENSITIVE_SYSTEM_SETTING_KEYS) { + // configuredKey 是敏感键对应的配置状态字段。 + const configuredKey = `${sensitiveKey}_configured`; + if (configuredKey in result) result[configuredKey] = result[configuredKey] === true || result[configuredKey] === 'true'; + } + if ('renewal_log_retention_days' in result) { + // days 是完成数值转换后的日志保留天数。 + const days = Number(result.renewal_log_retention_days); + result.renewal_log_retention_days = Number.isFinite(days) ? days : 10; + } + return result as SystemSettings; +}; + +/** 修改当前管理员的密码。 */ +export const changePassword = async (currentPassword: string, newPassword: string): Promise => post('/api/v1/session/password', { current_password: currentPassword, new_password: newPassword }); + +/** 修改当前管理员的登录名称与可选密码。 */ +export const updateLoginCredentials = async (data: { /** 当前密码用于服务端重新验证身份。 */ current_password: string; /** 新的管理员名称。 */ new_username: string; /** 可选的新密码。 */ new_password?: string }, options?: RequestControlOptions): Promise => put('/api/v1/session/credentials', data, options); + +/** 获取系统设置;仅保留敏感值是否已配置的状态,不接收敏感明文。 */ +export const getSystemSettings = async (options?: RequestControlOptions): Promise => { + // response 是服务端可能包裹在 data 中的设置响应。 + const response = await get<{ /** settings 是当前系统配置对象。 */ data?: Record; /** settings 是未包裹的兼容设置对象。 */ settings?: Record } & Record>('/api/v1/settings/system', undefined, options); + // settings 是去除 transport 包裹后的配置对象。 + const settings = response.data || response.settings || response; + return normalizeSettings(settings); +}; + +/** 保存普通系统配置和敏感设置命令。 */ +export const updateSystemSettings = async (settings: Partial | SystemSettingsUpdate, options?: RequestControlOptions): Promise => put('/api/v1/settings/system', normalizeSystemSettingsUpdate(settings), options); + +/** 向服务端请求指定人工智能服务的可用模型列表。 */ +export const fetchAIModels = async (baseURL: string, apiKey = '', options?: RequestControlOptions): Promise => { + // response 是模型发现接口的具名响应。 + const response = await post('/api/v1/settings/ai-models', { base_url: baseURL, api_key: apiKey }, options); + return Array.isArray(response.models) ? response.models : []; +}; + +/** 在保存登录凭据前读取当前会话状态。 */ +export const verifySession = async (options?: RequestControlOptions): Promise => get('/api/v1/session', undefined, options); diff --git a/frontend/app/features/settings/hooks.test.tsx b/frontend/app/features/settings/hooks.test.tsx index 8588809..0656fc3 100644 --- a/frontend/app/features/settings/hooks.test.tsx +++ b/frontend/app/features/settings/hooks.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { act, renderHook, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, test, vi } from 'vitest'; -import type { OperationResponse, SystemSettings } from '../../../types'; +import type { OperationResponse, SystemSettings } from '../../../shared/api-contract'; import { fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings, verifySession } from './api'; import { useSettings } from './hooks'; diff --git a/frontend/app/features/settings/hooks.ts b/frontend/app/features/settings/hooks.ts index 7b91f36..a6877d6 100644 --- a/frontend/app/features/settings/hooks.ts +++ b/frontend/app/features/settings/hooks.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import type React from 'react'; -import type { SystemSettings } from '../../../types'; +import type { SystemSettings } from '../../../shared/api-contract'; import { fetchAIModels, getSystemSettings, updateLoginCredentials, updateSystemSettings, verifySession } from './api'; import { DEFAULT_AI_API_URL } from './constants'; import { buildPersistableSettings, createCredentials, createCredentialsMessage, isCurrentSettingsRequest, isSettingsAbortError, settingsErrorMessage, validateCredentials } from './state'; diff --git a/frontend/components/Settings.tsx b/frontend/app/features/settings/pages/Settings.tsx similarity index 99% rename from frontend/components/Settings.tsx rename to frontend/app/features/settings/pages/Settings.tsx index 6a6eee5..bc1b821 100644 --- a/frontend/components/Settings.tsx +++ b/frontend/app/features/settings/pages/Settings.tsx @@ -4,8 +4,8 @@ import { Eye, EyeOff, RefreshCw, Database, ChevronDown, Check, LockKeyhole, UserRound, ShieldCheck } from 'lucide-react'; -import { DEFAULT_AI_API_URL, LOG_LEVELS } from '../app/features/settings/constants'; -import { useSettings } from '../app/features/settings/hooks'; +import { DEFAULT_AI_API_URL, LOG_LEVELS } from '../constants'; +import { useSettings } from '../hooks'; // Settings 展示系统配置、AI 模型和登录凭据编辑页面。 const Settings: React.FC = () => { diff --git a/frontend/app/features/settings/state.test.ts b/frontend/app/features/settings/state.test.ts index 5658895..77552f8 100644 --- a/frontend/app/features/settings/state.test.ts +++ b/frontend/app/features/settings/state.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest'; -import type { SystemSettings } from '../../../types'; +import type { SystemSettings } from '../../../shared/api-contract'; import { buildPersistableSettings, createCredentials, createCredentialsMessage, isCurrentSettingsRequest, validateCredentials } from './state'; // settingsFixture 是覆盖敏感字段过滤和系统配置保留字段的最小草稿。 diff --git a/frontend/app/features/settings/state.ts b/frontend/app/features/settings/state.ts index c8fe63a..1db4a17 100644 --- a/frontend/app/features/settings/state.ts +++ b/frontend/app/features/settings/state.ts @@ -1,4 +1,4 @@ -import type { SystemSettings } from '../../../types'; +import type { SystemSettings } from '../../../shared/api-contract'; import { SETTINGS_SAVE_OMIT_KEYS } from './constants'; import type { CredentialsForm, CredentialsMessage } from './types'; diff --git a/frontend/app/features/settings/types.ts b/frontend/app/features/settings/types.ts index 9b79e61..f127210 100644 --- a/frontend/app/features/settings/types.ts +++ b/frontend/app/features/settings/types.ts @@ -1,4 +1,4 @@ -import type { SystemSettings } from '../../../types'; +import type { SystemSettings } from '../../../shared/api-contract'; /** 登录凭据编辑表单。 */ export type CredentialsForm = { diff --git a/frontend/app/features/system/api.ts b/frontend/app/features/system/api.ts index f18a2b4..f31b1d1 100644 --- a/frontend/app/features/system/api.ts +++ b/frontend/app/features/system/api.ts @@ -1,3 +1,7 @@ -// System feature 只通过本适配层访问服务健康检查接口。 -export { getHealth } from '../../../services/api'; +import { get, type RequestControlOptions } from '../../../shared/http/client'; +import type { BuildInfo } from './types'; + +/** 读取服务健康检查与构建标识;请求支持随壳层卸载取消。 */ +export const getHealth = async (options?: RequestControlOptions): Promise => get('/health', undefined, options); + export type { BuildInfo } from './types'; diff --git a/frontend/app/providers/SessionProvider.tsx b/frontend/app/providers/SessionProvider.tsx index e5509ce..bbad408 100644 --- a/frontend/app/providers/SessionProvider.tsx +++ b/frontend/app/providers/SessionProvider.tsx @@ -1,6 +1,6 @@ import React, { createContext, useContext, useEffect, useState } from 'react'; import { initializeAdmin, login, logout, verifySession } from '../features/session/api'; -import type { SessionResponse } from '../../types'; +import type { SessionResponse } from '../../shared/api-contract'; // LoginCredentials 描述登录表单提交给会话服务的凭据字段。 export interface LoginCredentials { diff --git a/frontend/app/router/AppRouter.tsx b/frontend/app/router/AppRouter.tsx new file mode 100644 index 0000000..90d33b5 --- /dev/null +++ b/frontend/app/router/AppRouter.tsx @@ -0,0 +1,95 @@ +import React, { useEffect, useState } from 'react'; +import { readSidebarCollapsed, writeSidebarCollapsed } from '../../shared/browser/sidebarState'; +import { SessionGate } from '../features/session/pages/SessionGate'; +import { useSession } from '../providers/SessionProvider'; +import AuthenticatedShell, { type DeliveryRuleTarget } from '../shell/AuthenticatedShell'; +import { pathByRoute, routeFromLocation, type AppRoute } from './routes'; + +/** AppRouter 管理认证后的浏览器路由、侧边栏偏好与跨页面规则配置载荷。 */ +export const AppRouter: React.FC = () => { + // isLoggedIn 与 isAdmin 是 Provider 拥有的认证服务端状态,仅用于选择应用壳和授权路由。 + const { isLoggedIn, isAdmin, signOut } = useSession(); + // activeRoute 是当前 URL 对应的短暂导航状态,浏览器前进后退会同步更新。 + const [activeRoute, setActiveRoute] = useState(routeFromLocation); + // deliveryRuleTarget 是商品页发起、规则页消费后即清除的短暂跨页面载荷。 + const [deliveryRuleTarget, setDeliveryRuleTarget] = useState(); + // sidebarCollapsed 是用户本地偏好,不属于服务端业务数据。 + const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed); + + /** effect 同步浏览器历史事件,并在路由退回时拒绝非管理员设置页。 */ + useEffect(/* historyEffect 负责订阅并在卸载时移除浏览器历史监听。 */ () => { + /** handlePopState 读取历史记录对应的路由,不从异步请求恢复旧状态。 */ + const handlePopState = (): void => setActiveRoute(routeFromLocation()); + window.addEventListener('popstate', handlePopState); + return /* historyCleanup 在路由组件卸载时释放全局历史监听。 */ () => window.removeEventListener('popstate', handlePopState); + }, []); + + /** effect 在权限变化时将设置页改写为仪表盘,防止地址栏绕过客户端展示限制。 */ + useEffect(/* authorizationEffect 负责将失效的管理员页面安全回退。 */ () => { + if (isLoggedIn && !isAdmin && activeRoute === 'settings') { + window.history.replaceState({}, '', pathByRoute.dashboard); + setActiveRoute('dashboard'); + } + }, [activeRoute, isAdmin, isLoggedIn]); + + /** navigate 由侧边栏用户操作触发,写入规范 URL 并更新当前路由。 */ + const navigate = (route: AppRoute): void => { + // permittedRoute 是应用当前权限允许的最终路由。 + const permittedRoute = route === 'settings' && !isAdmin ? 'dashboard' : route; + // nextPath 是最终路由对应的规范浏览器地址。 + const nextPath = pathByRoute[permittedRoute]; + if (nextPath !== window.location.pathname) window.history.pushState({}, '', nextPath); + setActiveRoute(permittedRoute); + }; + + /** handleShellNavigation 接收侧边栏的字符串标识,并拒绝不在应用路由表中的遗留值。 */ + const handleShellNavigation = (tab: string): void => { + // route 是经规范路由表确认后的路由;未知标签一律回退到仪表盘。 + const route = Object.prototype.hasOwnProperty.call(pathByRoute, tab) ? tab as AppRoute : 'dashboard'; + navigate(route); + }; + + /** handleLogout 注销服务端会话;失败仍由 Provider 清理本地认证状态。 */ + const handleLogout = async (): Promise => { + try { + await signOut(); + } catch (error /* error 是注销请求失败原因,仅记录通用错误对象而不输出敏感会话内容。 */) { + console.error('退出登录失败', error); + } + }; + + /** handleToggleSidebar 由侧边栏按钮触发,并用函数式更新持久化下一次渲染所需偏好。 */ + const handleToggleSidebar = (): void => { + setSidebarCollapsed(/* preferenceUpdater 基于当前偏好计算并持久化下一次显示状态。 */ previousCollapsed /* previousCollapsed 是变更前的本地侧边栏偏好。 */ => { + // nextCollapsed 是本次点击后需要写入浏览器存储的偏好值。 + const nextCollapsed = !previousCollapsed; + writeSidebarCollapsed(nextCollapsed); + return nextCollapsed; + }); + }; + + /** handleConfigureDelivery 保存商品页选择的目标,并导航到消费该目标的规则页面。 */ + const handleConfigureDelivery = (target: DeliveryRuleTarget): void => { + setDeliveryRuleTarget(target); + navigate('rules'); + }; + + /** handleDeliveryTargetHandled 在规则页消费一次性联动目标后释放短暂 UI 状态。 */ + const handleDeliveryTargetHandled = (): void => setDeliveryRuleTarget(undefined); + + if (!isLoggedIn) return ; + + return ( + + ); +}; diff --git a/frontend/app/router/routes.ts b/frontend/app/router/routes.ts new file mode 100644 index 0000000..21e030b --- /dev/null +++ b/frontend/app/router/routes.ts @@ -0,0 +1,23 @@ +/** AppRoute 表示认证后可通过浏览器地址直接访问的业务页面。 */ +export type AppRoute = 'dashboard' | 'accounts' | 'chat' | 'orders' | 'cards' | 'items' | 'rules' | 'notifications' | 'settings'; + +/** routeByPath 保存浏览器地址到业务路由标识的唯一映射,避免页面各自解析 URL。 */ +export const routeByPath: Readonly> = { + '/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', +}; + +/** pathByRoute 保存业务路由标识的规范 URL,所有应用内跳转都使用该映射。 */ +export const pathByRoute: Readonly> = Object.fromEntries( + Object.entries(routeByPath).map(/* routePairMapper 将地址映射翻转为应用内导航所需的路由映射。 */ ([path, route] /* path 是规范地址;route 是对应业务页面。 */) => [route, path]), +) as Record; + +/** routeFromLocation 从当前浏览器地址解析业务路由,未知地址安全回退到仪表盘。 */ +export const routeFromLocation = (): AppRoute => routeByPath[window.location.pathname] ?? 'dashboard'; diff --git a/frontend/app/shell/AuthenticatedShell.test.tsx b/frontend/app/shell/AuthenticatedShell.test.tsx index e00a5c7..d6c336f 100644 --- a/frontend/app/shell/AuthenticatedShell.test.tsx +++ b/frontend/app/shell/AuthenticatedShell.test.tsx @@ -2,22 +2,22 @@ import React from 'react'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, describe, expect, test, vi } from 'vitest'; -import type { Item } from '../../types'; +import type { Item } from '../../shared/api-contract'; import type { DeliveryRuleTarget } from './AuthenticatedShell'; -vi.mock('../../components/Dashboard', /* dashboardMockFactory 提供仪表盘页面的轻量替身。 */ () => { +vi.mock('../features/dashboard/pages/Dashboard', /* dashboardMockFactory 提供仪表盘页面的轻量替身。 */ () => { // DashboardMock 渲染仪表盘页面标识,避免行为测试加载真实图表依赖。 const DashboardMock: React.FC = () =>
仪表盘
; return { default: DashboardMock }; }); -vi.mock('../../components/Settings', /* settingsMockFactory 提供设置页面的轻量替身。 */ () => { +vi.mock('../features/settings/pages/Settings', /* settingsMockFactory 提供设置页面的轻量替身。 */ () => { // SettingsMock 渲染设置页面标识,验证管理员权限分支。 const SettingsMock: React.FC = () =>
设置
; return { default: SettingsMock }; }); -vi.mock('../../components/ItemList', /* itemListMockFactory 提供商品页面的联动替身。 */ () => { +vi.mock('../features/items/pages/ItemList', /* itemListMockFactory 提供商品页面的联动替身。 */ () => { // MockItemListProps 描述商品页面替身接收的规则配置回调。 interface MockItemListProps { // onConfigureDelivery 负责通知父级打开商品规则配置。 @@ -32,7 +32,7 @@ vi.mock('../../components/ItemList', /* itemListMockFactory 提供商品页面 return { default: ItemListMock }; }); -vi.mock('../../components/Rules', /* rulesMockFactory 提供规则页面的轻量替身。 */ () => { +vi.mock('../features/rules/pages/Rules', /* rulesMockFactory 提供规则页面的轻量替身。 */ () => { // MockRulesProps 描述规则页面替身接收的联动参数。 interface MockRulesProps { // initialDeliveryTarget 保存商品页面传来的规则目标。 diff --git a/frontend/app/shell/AuthenticatedShell.tsx b/frontend/app/shell/AuthenticatedShell.tsx index d77a38a..ceaeb6c 100644 --- a/frontend/app/shell/AuthenticatedShell.tsx +++ b/frontend/app/shell/AuthenticatedShell.tsx @@ -1,6 +1,8 @@ -import React, { lazy, Suspense } from 'react'; -import Sidebar from '../../components/Sidebar'; -import type { Item } from '../../types'; +import React, { lazy, Suspense, useEffect, useState } from 'react'; +import Sidebar from '../../shared/ui/Sidebar'; +import type { Item } from '../../shared/api-contract'; +import { getHealth } from '../features/system/api'; +import type { BuildInfo } from '../features/system/types'; // DeliveryRuleTarget 描述商品页跳转到自动化规则页时需要携带的目标信息。 export interface DeliveryRuleTarget { @@ -35,23 +37,23 @@ export interface AuthenticatedShellProps { } // Dashboard 是按需加载的仪表盘页面,避免首屏同步载入图表依赖。 -const Dashboard = lazy(/* Dashboard 页面按路由激活时加载。 */ () => import('../../components/Dashboard')); +const Dashboard = lazy(/* Dashboard 页面按路由激活时加载。 */ () => import('../features/dashboard/pages/Dashboard')); // AccountList 是按需加载的账号管理页面,避免未访问时载入账号弹窗和二维码代码。 -const AccountList = lazy(/* AccountList 页面按路由激活时加载。 */ () => import('../../components/AccountList')); +const AccountList = lazy(/* AccountList 页面按路由激活时加载。 */ () => import('../features/accounts/pages/AccountList')); // OrderList 是按需加载的订单页面,避免首屏载入订单导入与刷新代码。 -const OrderList = lazy(/* OrderList 页面按路由激活时加载。 */ () => import('../../components/OrderList')); +const OrderList = lazy(/* OrderList 页面按路由激活时加载。 */ () => import('../features/orders/pages/OrderList')); // CardList 是按需加载的卡密页面,避免首屏载入卡密批量处理代码。 -const CardList = lazy(/* CardList 页面按路由激活时加载。 */ () => import('../../components/CardList')); +const CardList = lazy(/* CardList 页面按路由激活时加载。 */ () => import('../features/cards/pages/CardList')); // ItemList 是按需加载的商品页面,避免首屏载入商品发布编辑器代码。 -const ItemList = lazy(/* ItemList 页面按路由激活时加载。 */ () => import('../../components/ItemList')); +const ItemList = lazy(/* ItemList 页面按路由激活时加载。 */ () => import('../features/items/pages/ItemList')); // Settings 是按需加载的系统设置页面,仅在管理员访问时加载。 -const Settings = lazy(/* Settings 页面按路由激活时加载。 */ () => import('../../components/Settings')); +const Settings = lazy(/* Settings 页面按路由激活时加载。 */ () => import('../features/settings/pages/Settings')); // Rules 是按需加载的自动化规则页面,避免首屏载入规则编辑器代码。 -const Rules = lazy(/* Rules 页面按路由激活时加载。 */ () => import('../../components/Rules')); +const Rules = lazy(/* Rules 页面按路由激活时加载。 */ () => import('../features/rules/pages/Rules')); // Notifications 是按需加载的通知页面,避免首屏载入通知配置代码。 -const Notifications = lazy(/* Notifications 页面按路由激活时加载。 */ () => import('../../components/Notifications')); +const Notifications = lazy(/* Notifications 页面按路由激活时加载。 */ () => import('../features/notifications/pages/Notifications')); // Chat 是按需加载的聊天页面,避免未访问时载入聊天历史和 WebSocket 视图。 -const Chat = lazy(/* Chat 页面按路由激活时加载。 */ () => import('../../components/Chat')); +const Chat = lazy(/* Chat 页面按路由激活时加载。 */ () => import('../features/chat/pages/Chat')); // PageLoading 展示路由页面代码加载期间的统一占位状态。 const PageLoading: React.FC = () => ( @@ -128,8 +130,26 @@ const AuthenticatedShell: React.FC = ({ onLogout, onConfigureDelivery, onDeliveryTargetHandled, -}) => ( -
+}) => { + // buildInfo 保存壳层加载的公开构建版本,侧边栏保持为无请求的共享展示组件。 + const [buildInfo, setBuildInfo] = useState({ version: 'dev', commit: 'unknown' }); + + useEffect(/* effect 在壳层挂载时读取版本信息,并在卸载时中止尚未完成的请求。 */ () => { + // controller 取消壳层卸载后不再需要的健康检查请求。 + const controller = new AbortController(); + getHealth({ signal: controller.signal }) + .then(/* response 是健康接口返回的公开构建标识。 */ response => setBuildInfo({ + version: String(response.version || 'dev'), + commit: String(response.commit || 'unknown'), + })) + .catch(/* error 是健康检查失败原因,取消请求不需要改变默认展示版本。 */ error => { + if (error instanceof DOMException && error.name === 'AbortError') return; + }); + return /* cleanup 在壳层卸载时释放健康检查请求。 */ () => controller.abort(); + }, []); + + return ( +
= ({ onToggleCollapsed={onToggleCollapsed} onNavigate={onNavigate} onLogout={onLogout} + buildInfo={buildInfo} />
@@ -153,7 +174,8 @@ const AuthenticatedShell: React.FC = ({ />
-
-); +
+ ); +}; export default AuthenticatedShell; diff --git a/frontend/chatFeature.test.ts b/frontend/chatFeature.test.ts index 0bb4ba2..176b851 100644 --- a/frontend/chatFeature.test.ts +++ b/frontend/chatFeature.test.ts @@ -6,7 +6,7 @@ const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8'); describe('online chat UI contract', () => { test('uses account tabs above a two-column buyer/chat layout', () => { - const chat = source('components/Chat.tsx'); /* chat 表示chat。 */ + const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */ expect(chat).toContain('role="tablist"'); expect(chat).toContain('grid-cols-[320px_minmax(0,1fr)]'); expect(chat).toContain('min-h-0 min-w-0 flex-col overflow-hidden'); @@ -16,7 +16,7 @@ describe('online chat UI contract', () => { } /* 回调函数负责当前业务流程。 */); test('uses neutral user labels instead of assuming buyer role', () => { - const chat = source('components/Chat.tsx'); /* chat 表示chat。 */ + const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */ expect(chat).toContain('用户 ID:'); expect(chat).not.toContain('买家 ID:'); expect(chat).not.toContain('选择一个买家'); @@ -29,7 +29,7 @@ describe('online chat UI contract', () => { } /* 回调函数负责当前业务流程。 */); test('renders peer/self identity and verified media capabilities', () => { - const chat = source('components/Chat.tsx'); /* chat 表示chat。 */ + const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */ const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */ expect(chat).toContain('selectedSession.buyer_avatar_url'); expect(chat).toContain('activeAccount?.avatar_url'); @@ -39,13 +39,13 @@ describe('online chat UI contract', () => { } /* 回调函数负责当前业务流程。 */); test('renders official notices as neutral system messages', () => { - const chat = source('components/Chat.tsx'); /* chat 表示chat。 */ + const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */ expect(chat).toContain("message.message_type === 'system'"); expect(chat).toContain('justify-center py-1'); } /* 回调函数负责当前业务流程。 */); test('keeps the active chat at the bottom when new messages arrive', () => { - const chat = source('components/Chat.tsx'); /* chat 表示chat。 */ + const chat = source('app/features/chat/pages/Chat.tsx'); /* chat 表示chat。 */ const chatHook = source('app/features/chat/hooks.ts'); /* chatHook 表示chatHook。 */ expect(chatHook).toContain('shouldScrollToBottomRef'); expect(chatHook).toContain('skipNextMessageScrollRef'); @@ -55,7 +55,7 @@ describe('online chat UI contract', () => { } /* 回调函数负责当前业务流程。 */); test('sidebar exposes collapse control and chat primary navigation', () => { - const sidebar = source('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */ + const sidebar = source('shared/ui/Sidebar.tsx'); /* sidebar 表示sidebar。 */ expect(sidebar).toContain("id: 'chat'"); expect(sidebar).toContain('onToggleCollapsed'); expect(sidebar).toContain('collapsed ? \'w-16\' : \'w-64\''); diff --git a/frontend/colorTokens.test.ts b/frontend/colorTokens.test.ts index 9ce5a5f..a2bdb44 100644 --- a/frontend/colorTokens.test.ts +++ b/frontend/colorTokens.test.ts @@ -2,13 +2,23 @@ import { readdirSync, readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { describe, expect, test } from 'vitest'; -const componentsDir = resolve(__dirname, 'components'); /* componentsDir 表示componentsDir。 */ +// featureRoot 是 feature 页面与专属组件所在的目录;根 components 已由阶段七迁移移除。 +const featureRoot = resolve(__dirname, 'app/features'); +// sharedUIRoot 是跨 feature 复用的纯展示组件目录。 +const sharedUIRoot = resolve(__dirname, 'shared/ui'); +// collectTSXSources 递归收集目标目录内非测试 TSX,供设计令牌契约审计使用。 +const collectTSXSources = (directory: string): string[] => readdirSync(directory, { withFileTypes: true }).flatMap(/* sourceEntryMapper 处理当前目录的一个文件或子目录。 */ entry => { + // entryPath 是当前文件系统条目的绝对路径。 + const entryPath = resolve(directory, entry.name); + if (entry.isDirectory()) return collectTSXSources(entryPath); + return entry.name.endsWith('.tsx') && !entry.name.endsWith('.test.tsx') ? [entryPath] : []; +}); +// pageSources 是根应用、feature 页面和共享 UI 的生产 TSX 源码集合。 const pageSources = [ resolve(__dirname, 'App.tsx'), - ...readdirSync(componentsDir) - .filter((fileName) => fileName.endsWith('.tsx') && !fileName.endsWith('.test.tsx') /* 回调函数负责当前业务流程。 */) - .map((fileName) => resolve(componentsDir, fileName) /* 回调函数负责当前业务流程。 */), -]; /* pageSources 表示pageSources。 */ + ...collectTSXSources(featureRoot), + ...collectTSXSources(sharedUIRoot), +]; // rgb(var(--color-*)), CSS classes and the central index.css are references. // Literal colors in page code would bypass the design-token system. diff --git a/frontend/components/qrPolling.ts b/frontend/components/qrPolling.ts deleted file mode 100644 index ead72ca..0000000 --- a/frontend/components/qrPolling.ts +++ /dev/null @@ -1,9 +0,0 @@ -// 旧组件路径保留兼容导出,实际实现归属于账号 feature。 -export { - createLatestRequestGate, - createQRLoginPoller, -} from '../app/features/accounts/qrPolling'; -export type { - QRLoginPollHandlers, - QRLoginStatusResult, -} from '../app/features/accounts/qrPolling'; diff --git a/frontend/featureArchitecture.test.ts b/frontend/featureArchitecture.test.ts index f1d00f4..9e88d40 100644 --- a/frontend/featureArchitecture.test.ts +++ b/frontend/featureArchitecture.test.ts @@ -1,5 +1,5 @@ -import { readdirSync, readFileSync } from 'node:fs'; -import { resolve, relative } from 'node:path'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { dirname, resolve, relative } from 'node:path'; import { describe, expect, test } from 'vitest'; // sourceRoot 是前端源码根目录,所有架构规则都基于生产源码扫描。 @@ -25,12 +25,75 @@ const productionSources = (): Array<{ /* relativePath 表示relative当前路径 source: readFileSync(filePath, 'utf8'), }) /* 回调函数负责当前业务流程。 */); +// extractModuleSpecifiers 提取静态 import、re-export 与动态 import 的模块路径,用于检查目录边界而不依赖编译器私有 AST。 +const extractModuleSpecifiers = (source: string): string[] => { + // modulePattern 同时匹配带 from 的导入、仅副作用导入和 import() 懒加载路径。 + const modulePattern = /(?:\b(?:import|export)\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?|\bimport\s*\()\s*['"]([^'"]+)['"]/g; + // specifiers 保存源码中按书写顺序找到的模块路径。 + const specifiers: string[] = []; + // match 是当前正则匹配到的单个模块声明。 + for (const match /* match 是当前静态模块声明的完整正则匹配结果。 */ of source.matchAll(modulePattern)) { + // specifier 是当前导入的相对或包模块路径。 + const specifier = match[1]; + if (specifier) specifiers.push(specifier); + } + return specifiers; +}; + +// resolveImportPath 将相对导入转换为前端源码根目录下的标准路径;包名导入不属于本地架构图。 +const resolveImportPath = (sourcePath: string, specifier: string): string | null => { + // isRelativeImport 表示当前模块是否使用相对路径而不是 npm 包名或 Vite 别名。 + const isRelativeImport = specifier.startsWith('.'); + if (!isRelativeImport) return null; + // absoluteImportPath 是依据当前源码文件目录解析出的无扩展名绝对路径。 + const absoluteImportPath = resolve(dirname(resolve(sourceRoot, sourcePath)), specifier); + // normalizedPath 是相对于源码根目录的跨平台标准路径。 + const normalizedPath = relative(sourceRoot, absoluteImportPath).split('/').join('/'); + return normalizedPath.startsWith('..') ? null : normalizedPath; +}; + +// featureNameFromPath 从 feature 内任意源码路径提取其直属 feature 名称。 +const featureNameFromPath = (relativePath: string): string | null => { + // featureMatch 是 app/features 下第一个目录名的匹配结果。 + const featureMatch = relativePath.match(/^app\/features\/([^/]+)\//); + return featureMatch?.[1] || null; +}; + +// canonicalPageEntrypoints 是当前应用由路由壳按需加载的业务页和认证页清单。 +const canonicalPageEntrypoints = [ + 'app/features/accounts/pages/AccountList.tsx', + 'app/features/cards/pages/CardList.tsx', + 'app/features/chat/pages/Chat.tsx', + 'app/features/dashboard/pages/Dashboard.tsx', + 'app/features/items/pages/ItemList.tsx', + 'app/features/notifications/pages/Notifications.tsx', + 'app/features/orders/pages/OrderList.tsx', + 'app/features/rules/pages/Rules.tsx', + 'app/features/session/pages/SessionGate.tsx', + 'app/features/settings/pages/Settings.tsx', +]; + describe('React feature dependency boundaries', () => { + test('legacy centralized API entrypoint has been removed', () => { + // legacyEntrypoint 是不应重新引入的集中业务 API 文件。 + const legacyEntrypoint = resolve(sourceRoot, 'services/api.ts'); + // exists 标识旧集中 API 文件是否仍然存在。 + const exists = (/* legacyEntrypointReader 检查旧入口是否仍保留在源码树。 */ () => { + try { + readFileSync(legacyEntrypoint); + return true; + } catch { + return false; + } + })(); + expect(exists).toBe(false); + } /* 回调函数负责当前业务流程。 */); + test('network clients are only imported by feature API adapters', () => { // violations 保存页面、组件或非 API feature 文件中的共享网络客户端依赖。 const violations = productionSources() - .filter(file => file.source.includes("from './services/api'") || file.source.includes("from '../services/api'") || file.source.includes("from '../../../services/api'") /* 回调函数负责当前业务流程。 */) - .filter(file => file.relativePath !== 'services/api.ts' && !file.relativePath.endsWith('/api.ts') /* 回调函数负责当前业务流程。 */) + .filter(file => file.source.includes("from '../../../shared/http/client'") || file.source.includes("from '../../../../shared/http/client'") /* 回调函数负责当前业务流程。 */) + .filter(file => !/(?:\/api|Api)\.ts$/.test(file.relativePath) /* 回调函数负责当前业务流程。 */) .map(file => file.relativePath /* 回调函数负责当前业务流程。 */); expect(violations).toEqual([]); @@ -39,17 +102,17 @@ describe('React feature dependency boundaries', () => { test('production React code does not call fetch or axios outside the request boundary', () => { // violations 保存页面或组件中直接发起网络请求的源码路径。 const violations = productionSources() - .filter(file => file.relativePath !== 'request.ts' && /\bfetch\s*\(|\baxios\b/.test(file.source) /* 回调函数负责当前业务流程。 */) + .filter(file => file.relativePath !== 'shared/http/client.ts' && /\bfetch\s*\(|\baxios\b/.test(file.source) /* 回调函数负责当前业务流程。 */) .map(file => file.relativePath /* 回调函数负责当前业务流程。 */); expect(violations).toEqual([]); } /* 回调函数负责当前业务流程。 */); - test('feature API adapters are the only feature files allowed to depend on shared API', () => { + test('feature API adapters are the only feature files allowed to depend on shared HTTP', () => { // violations 保存 feature 内部绕过 API 适配层的共享服务依赖。 const violations = productionSources() - .filter(file => file.relativePath.startsWith('app/features/') && file.source.includes("from '../../../services/api'") /* 回调函数负责当前业务流程。 */) - .filter(file => !file.relativePath.endsWith('/api.ts') /* 回调函数负责当前业务流程。 */) + .filter(file => file.relativePath.startsWith('app/features/') && file.source.includes("shared/http/client") /* 回调函数负责当前业务流程。 */) + .filter(file => !/(?:\/api|Api)\.ts$/.test(file.relativePath) /* 回调函数负责当前业务流程。 */) .map(file => file.relativePath /* 回调函数负责当前业务流程。 */); expect(violations).toEqual([]); @@ -58,7 +121,7 @@ describe('React feature dependency boundaries', () => { test('production API adapters use versioned HTTP paths', () => { // violations 保存 API 适配层中仍然指向未版本化前缀的生产源码路径。 const violations = productionSources() - .filter(file => file.relativePath === 'services/api.ts' || file.relativePath.endsWith('/api.ts') /* 回调函数负责当前业务流程。 */) + .filter(file => /(?:\/api|Api)\.ts$/.test(file.relativePath) /* 回调函数负责当前业务流程。 */) .filter(file => /['"`]\/api\/(?!v1(?:\/|['"`]))/.test(file.source) /* 回调函数负责当前业务流程。 */) .map(file => file.relativePath /* 回调函数负责当前业务流程。 */); @@ -86,4 +149,64 @@ describe('React feature dependency boundaries', () => { } } /* 回调函数负责当前业务流程。 */)).toEqual([]); } /* 回调函数负责当前业务流程。 */); + + test('feature source files do not import another feature implementation', () => { + // violations 保存 feature 源文件解析后指向其他 feature 目录的导入关系。 + const violations = productionSources().flatMap(/* featureDependencyScanner 扫描单个 feature 源文件的本地依赖方向。 */ file => { + // owningFeature 是当前源码文件所属 feature;非 feature 文件不受本规则约束。 + const owningFeature = featureNameFromPath(file.relativePath); + if (!owningFeature) return []; + // importedPaths 是当前 feature 文件解析后的本地相对导入路径。 + const importedPaths = extractModuleSpecifiers(file.source) + .map(/* importPathResolver 将单个模块路径解析为源码根目录路径。 */ specifier => resolveImportPath(file.relativePath, specifier)) + .filter(/* localImportFilter 忽略包名、别名和源码根目录外的导入。 */ (importPath): importPath is string => importPath !== null); + return importedPaths + .filter(/* crossFeatureFilter 仅保留明确落在另一 feature 目录的导入。 */ importPath => { + // importedFeature 是被当前导入路径指向的直属 feature 名称。 + const importedFeature = featureNameFromPath(importPath); + return importedFeature !== null && importedFeature !== owningFeature; + }) + .map(/* violationFormatter 输出可定位的跨 feature 依赖。 */ importPath => `${file.relativePath} -> ${importPath}`); + }); + + expect(violations).toEqual([]); + } /* 回调函数负责当前业务流程。 */); + + test('shared source files do not import application or feature implementations', () => { + // violations 保存 shared 代码反向依赖 app 或 feature 的本地导入关系。 + const violations = productionSources() + .filter(/* sharedSourceFilter 只检查 shared 目录生产源码。 */ file => file.relativePath.startsWith('shared/')) + .flatMap(file => extractModuleSpecifiers(file.source) + .map(/* sharedImportResolver 解析 shared 文件的本地模块路径。 */ specifier => resolveImportPath(file.relativePath, specifier)) + .filter(/* reverseDependencyFilter 保留 shared 反向依赖 app 的路径。 */ (importPath): importPath is string => importPath?.startsWith('app/') === true) + .map(/* reverseViolationFormatter 输出可定位的反向依赖。 */ importPath => `${file.relativePath} -> ${importPath}`)); + + expect(violations).toEqual([]); + } /* 回调函数负责当前业务流程。 */); + + test('application root only composes global boundaries and no legacy root components remain', () => { + // appRootEntries 是 app 目录允许存在的顶层架构职责目录。 + const appRootEntries = ['errors', 'features', 'providers', 'router', 'shell']; + // actualAppEntries 是当前 app 目录的顶层文件与目录名称。 + const actualAppEntries = readdirSync(resolve(sourceRoot, 'app')).sort(); + // appSource 是应用根组件源码,只允许装配错误边界、Provider 和路由。 + const appSource = readFileSync(resolve(sourceRoot, 'App.tsx'), 'utf8'); + + expect(actualAppEntries).toEqual(appRootEntries); + expect(appSource).toContain("from './app/errors/AppErrorBoundary'"); + expect(appSource).toContain("from './app/providers/SessionProvider'"); + expect(appSource).toContain("from './app/router/AppRouter'"); + expect(appSource).not.toMatch(/app\/features|services\/|shared\/http/); + expect(existsSync(resolve(sourceRoot, 'components'))).toBe(false); + } /* 回调函数负责当前业务流程。 */); + + test('all canonical page entrypoints live under their owning feature pages directory', () => { + // actualPageEntrypoints 是全部位于 feature pages 目录的生产页面入口;认证页可使用具名导出,其余页面由路由壳懒加载默认导出。 + const actualPageEntrypoints = productionSources() + .filter(/* pageSourceFilter 只保留 feature 的 pages 目录 TSX 文件。 */ file => /^app\/features\/[^/]+\/pages\/[^/]+\.tsx$/.test(file.relativePath)) + .map(/* pagePathMapper 提取页面入口相对路径。 */ file => file.relativePath) + .sort(); + + expect(actualPageEntrypoints).toEqual([...canonicalPageEntrypoints].sort()); + } /* 回调函数负责当前业务流程。 */); } /* 回调函数负责当前业务流程。 */); diff --git a/frontend/itemListVisual.test.ts b/frontend/itemListVisual.test.ts index dc47d61..b37f880 100644 --- a/frontend/itemListVisual.test.ts +++ b/frontend/itemListVisual.test.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { describe, expect, test } from 'vitest'; -const itemList = readFileSync(resolve(__dirname, 'components/ItemList.tsx'), 'utf8'); /* itemList 表示当前商品List。 */ +const itemList = readFileSync(resolve(__dirname, 'app/features/items/pages/ItemList.tsx'), 'utf8'); /* itemList 表示当前商品List。 */ describe('item list primary action colors', () => { test('uses the shared primary blue for batch publishing', () => { diff --git a/frontend/routing.test.ts b/frontend/routing.test.ts index 791a2b7..5000c1d 100644 --- a/frontend/routing.test.ts +++ b/frontend/routing.test.ts @@ -17,7 +17,7 @@ const extractSingleQuotedValues = (source: string, pattern: RegExp) => { describe('frontend navigation routing', () => { test('sidebar entries and App activeTab routes stay in sync', () => { - const sidebar = readFrontendFile('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */ + const sidebar = readFrontendFile('shared/ui/Sidebar.tsx'); /* sidebar 表示sidebar。 */ const app = readFrontendFile('app/shell/AuthenticatedShell.tsx'); /* app 表示认证后页面组合器源码。 */ const sidebarIDs = extractSingleQuotedValues(sidebar, /id:\s*'([^']+)'/g); /* sidebarIDs 表示sidebarIDs。 */ @@ -27,7 +27,7 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('active navigation uses the primary action blue', () => { - const sidebar = readFrontendFile('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */ + const sidebar = readFrontendFile('shared/ui/Sidebar.tsx'); /* sidebar 表示sidebar。 */ expect(sidebar).toContain("'bg-brand text-white shadow-brand-active'"); expect(sidebar).not.toContain("'bg-sky-500 text-white'"); @@ -41,10 +41,11 @@ describe('frontend navigation routing', () => { expect(app).toContain('const PageLoading: React.FC'); expect(app).toContain('}>'); expect(app).not.toContain("import Dashboard from '../../components/Dashboard'"); + expect(app).toContain("import('../features/dashboard/pages/Dashboard')"); } /* 回调函数负责当前业务流程。 */); test('authenticated shell owns sidebar and page composition', () => { - const app = readFrontendFile('App.tsx'); /* app 表示认证状态根组件源码。 */ + const app = readFrontendFile('app/router/AppRouter.tsx'); /* app 表示认证后的路由组合器源码。 */ const shell = readFrontendFile('app/shell/AuthenticatedShell.tsx'); /* shell 表示认证后应用壳源码。 */ expect(app).toContain("import AuthenticatedShell, { type DeliveryRuleTarget }"); @@ -55,17 +56,17 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('logout button invalidates the backend session before clearing UI state', () => { - const app = readFrontendFile('App.tsx'); /* app 表示app。 */ + const app = readFrontendFile('app/router/AppRouter.tsx'); /* app 表示认证后路由组合器源码。 */ const sessionProvider = readFrontendFile('app/providers/SessionProvider.tsx'); /* sessionProvider 表示认证 Provider 源码。 */ - expect(app).toContain("import { SessionProvider, useSession }"); + expect(app).toContain("import { useSession }"); expect(sessionProvider).toContain('await logout();'); expect(sessionProvider).toContain("window.addEventListener('auth:logout'"); expect(app).toContain('onLogout={handleLogout}'); } /* 回调函数负责当前业务流程。 */); test('settings page does not expose backend-inactive system controls', () => { - const settings = readFrontendFile('components/Settings.tsx'); /* settings 表示settings。 */ + const settings = readFrontendFile('app/features/settings/pages/Settings.tsx'); /* settings 表示settings。 */ const settingsConstants = readFrontendFile('app/features/settings/constants.ts'); /* settingsConstants 表示settingsConstants。 */ expect(settings).not.toContain('允许用户注册'); @@ -78,15 +79,15 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('admin-only settings navigation is gated by session role', () => { - const app = readFrontendFile('App.tsx'); /* app 表示app。 */ + const app = readFrontendFile('app/router/AppRouter.tsx'); /* app 表示认证后路由组合器源码。 */ const sessionProvider = readFrontendFile('app/providers/SessionProvider.tsx'); /* sessionProvider 表示认证 Provider 源码。 */ const shell = readFrontendFile('app/shell/AuthenticatedShell.tsx'); /* shell 表示认证后应用壳源码。 */ - const sidebar = readFrontendFile('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */ + const sidebar = readFrontendFile('shared/ui/Sidebar.tsx'); /* sidebar 表示sidebar。 */ const settingsHook = readFrontendFile('app/features/settings/hooks.ts'); /* settingsHook 表示settingsHook。 */ - expect(app).toContain('const { checkingAuth, isLoggedIn, isAdmin, needsInit, signIn, initialize, signOut } = useSession();'); + expect(app).toContain('const { isLoggedIn, isAdmin, signOut } = useSession();'); expect(sessionProvider).toContain('setIsAdmin(response.is_admin === true)'); - expect(app).toContain("activeTab === 'settings'"); + expect(app).toContain("activeRoute === 'settings'"); expect(shell).toContain('isAdmin ? : '); expect(sidebar).toContain('isAdmin = false'); expect(sidebar).toContain("...(isAdmin ? [{ id: 'settings'"); @@ -94,7 +95,7 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('captcha remote settings expose the reference privacy and fallback semantics', () => { - const settings = readFrontendFile('components/Settings.tsx'); /* settings 表示settings。 */ + const settings = readFrontendFile('app/features/settings/pages/Settings.tsx'); /* settings 表示settings。 */ expect(settings).toContain('远程过滑块配置'); expect(settings).toContain("'captcha.remote_service_url'"); @@ -105,7 +106,7 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('email notification config separates system and custom SMTP modes', () => { - const notifications = readFrontendFile('components/Notifications.tsx'); /* notifications 表示notifications。 */ + const notifications = readFrontendFile('app/features/notifications/pages/Notifications.tsx'); /* notifications 表示notifications。 */ const notificationState = readFrontendFile('app/features/notifications/state.ts'); /* notificationState 表示notificationState。 */ const notificationModal = readFrontendFile('app/features/notifications/components/NotificationChannelModal.tsx'); /* notificationModal 表示notificationModal。 */ @@ -119,7 +120,7 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('keyword reply UI matches contains-based backend behavior', () => { - const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */ + const rules = readFrontendFile('app/features/rules/pages/Rules.tsx'); /* rules 表示规则集合。 */ expect(rules).toContain('包含匹配'); expect(rules).not.toContain('精确匹配'); @@ -158,7 +159,7 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('automation editor keeps multiple delivery contents for normal products', () => { - const rules = readFrontendFile('components/Rules.tsx'); /* rules 表示规则集合。 */ + const rules = readFrontendFile('app/features/rules/pages/Rules.tsx'); /* rules 表示规则集合。 */ const actions = readFrontendFile('app/features/rules/ruleActions.ts'); /* actions 表示规则动作协调器源码。 */ expect(rules).toContain('添加发货内容'); @@ -168,7 +169,7 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('batch publishing help explains card fields without required-field jargon', () => { - const itemList = readFrontendFile('components/ItemList.tsx'); /* itemList 表示当前商品List。 */ + const itemList = readFrontendFile('app/features/items/pages/ItemList.tsx'); /* itemList 表示当前商品List。 */ expect(itemList).not.toContain('条件必填'); expect(itemList).toContain('“付款后发送的卡密”怎么填'); @@ -186,9 +187,9 @@ describe('frontend navigation routing', () => { } /* 回调函数负责当前业务流程。 */); test('QR verification removes the external link and clearly requires in-app risk verification', () => { - const accounts = readFrontendFile('components/AccountList.tsx'); /* accounts 表示账号集合。 */ + const accounts = readFrontendFile('app/features/accounts/pages/AccountList.tsx'); /* accounts 表示账号集合。 */ const qrModal = readFrontendFile('app/features/accounts/components/AccountQRCodeModal.tsx'); /* qrModal 表示二维码登录弹窗。 */ - const riskPanel = readFrontendFile('components/RiskVerificationPanel.tsx'); /* riskPanel 表示riskPanel。 */ + const riskPanel = readFrontendFile('app/features/accounts/components/RiskVerificationPanel.tsx'); /* riskPanel 表示riskPanel。 */ expect(accounts).not.toContain('href={verificationUrl}'); expect(accounts).not.toContain('setVerificationUrl'); expect(qrModal).toContain('RiskVerificationPanel'); @@ -202,7 +203,7 @@ describe('frontend navigation routing', () => { test('account editor exposes password-login refresh and never renders its verification URL', () => { const accounts = [ - readFrontendFile('components/AccountList.tsx'), + readFrontendFile('app/features/accounts/pages/AccountList.tsx'), readFrontendFile('app/features/accounts/components/AccountEditModal.tsx'), readFrontendFile('app/features/accounts/submoduleHooks.ts'), ].join('\n'); /* accounts 表示账号集合。 */ diff --git a/frontend/rulesFeature.test.ts b/frontend/rulesFeature.test.ts index 5a1c525..fb15d7f 100644 --- a/frontend/rulesFeature.test.ts +++ b/frontend/rulesFeature.test.ts @@ -7,7 +7,7 @@ const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8'); describe('responsive rules layout', () => { test('allows the rules page to shrink inside the sidebar layout', () => { const app = source('app/shell/AuthenticatedShell.tsx'); /* app 表示认证后应用壳源码。 */ - const rules = source('components/Rules.tsx'); /* rules 表示规则集合。 */ + const rules = source('app/features/rules/pages/Rules.tsx'); /* rules 表示规则集合。 */ expect(app).toContain('h-screen min-w-0 flex-1 overflow-x-hidden'); expect(rules).toContain('min-w-0 space-y-8'); expect(rules).toContain('xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]'); @@ -17,8 +17,8 @@ describe('responsive rules layout', () => { describe('rules summary counts', () => { test('uses server-side aggregate counts instead of the current page length', () => { - const rules = source('components/Rules.tsx'); /* rules 表示规则集合。 */ - const api = source('services/api.ts'); /* api 表示api。 */ + const rules = source('app/features/rules/pages/Rules.tsx'); /* rules 表示规则集合。 */ + const api = source('app/features/rules/api.ts'); /* api 表示自动化规则 feature 的接口适配器源码。 */ expect(rules).toContain('automationTriggerCounts'); expect(rules).toContain('{automationTriggerCounts[trigger] || 0}'); expect(rules).toContain('筛选结果构成'); diff --git a/frontend/services/amapLocation.ts b/frontend/services/amapLocation.ts index 2a7f684..d2c8f1b 100644 --- a/frontend/services/amapLocation.ts +++ b/frontend/services/amapLocation.ts @@ -1,4 +1,4 @@ -import type { PublishLocation } from './api'; +import type { PublishLocation } from '../shared/api-contract'; const AMAP_SCRIPT_ID = 'ydisks-amap-js-api'; /* AMAP_SCRIPT_ID 表示AMAPSCRIPTID。 */ // 高德 JS API 的 Key 是前端公开 Key;部署时可通过 VITE_AMAP_JS_KEY 覆盖。 diff --git a/frontend/services/api.ts b/frontend/services/api.ts deleted file mode 100644 index 30ce323..0000000 --- a/frontend/services/api.ts +++ /dev/null @@ -1,1338 +0,0 @@ -import { get, post, put, del, postForm, type RequestControlOptions } from '../request'; -import { - SessionResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse, - AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics, - Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType, - NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope, - CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, OrderRefreshJobCancelResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse -} from '../types'; -import { formatLocalDate } from '../dateRange'; - -// normalizeSettings 归一化系统配置。 -const normalizeSettings = (settings: Record): SystemSettings => { - // out 配置副本,用于当前 API 处理流程。 - const out: Record = { ...settings }; - // sensitiveKey 是后端只返回配置状态、不返回明文的敏感配置键。 - const sensitiveKeys = ['ai_api_key', 'smtp_password', 'qq_reply_secret_key', 'captcha.remote_secret_key']; - for (const sensitiveKey /* sensitiveKey 表示当前处理的敏感配置键。 */ of sensitiveKeys) { - // configuredKey 是敏感配置是否已设置的状态字段。 - const configuredKey = `${sensitiveKey}_configured`; - if (configuredKey in out) { - out[configuredKey] = out[configuredKey] === true || out[configuredKey] === 'true'; - } - } - if ('renewal_log_retention_days' in out) { - // parsed 转换后的数值,用于当前 API 处理流程。 - const parsed = Number(out.renewal_log_retention_days); - out.renewal_log_retention_days = Number.isFinite(parsed) ? parsed : 10; - } - return out as SystemSettings; -}; - -// Auth -// login 登录,用于当前 API 处理流程。 -export const login = async (data: { /** username 表示用户名。 */ username?: string; /** password 表示密码。 */ password?: string; /** email 表示邮箱。 */ email?: string; /** verification_code 表示登录验证码。 */ verification_code?: string }): Promise => { - return post('/api/v1/session/login', data, { skipAuthLogout: true }); -}; - -// initializeAdmin 初始化管理员并建立会话。 -export const initializeAdmin = async (password: string): Promise => { - return post('/api/v1/session/initialize', { password }, { skipAuthLogout: true }); -}; - -// verifySession 验证会话。 -export const verifySession = async (options?: RequestControlOptions): Promise<{ /** authenticated 表示当前会话是否已认证。 */ authenticated: boolean; /** initialized 表示系统是否已完成初始化。 */ initialized?: boolean; /** user_id 表示当前用户标识。 */ user_id?: number; /** username 表示用户名。 */ username?: string; /** is_admin 表示当前用户是否为管理员。 */ is_admin?: boolean }> => { - return get('/api/v1/session', undefined, options); -}; - -// getHealth 读取服务健康检查和构建版本信息。 -export const getHealth = async (options?: RequestControlOptions): Promise<{ /** version 表示版本。 */ version?: string; /** commit 表示提交版本。 */ commit?: string }> => { - return get('/health', undefined, options); -}; - -// logout 注销当前会话。 -export const logout = async (): Promise => { - return post('/api/v1/session/logout', {}); -}; - -// changePassword 修改当前用户密码。 -export const changePassword = async (currentPassword: string, newPassword: string): Promise => { - return post('/api/v1/session/password', { current_password: currentPassword, new_password: newPassword }); -}; - -// updateLoginCredentials 更新当前用户登录凭据。 -export const updateLoginCredentials = async (data: { - /** current_password 表示当前密码。 */ current_password: string; - /** new_username 表示新用户名。 */ new_username: string; - /** new_password 表示新密码。 */ new_password?: string; -}, options?: RequestControlOptions): Promise => { - return put('/api/v1/session/credentials', data, options); -}; - -// Accounts -// addAccount 新增账号。 -export const addAccount = async (id: string, value: string, loginMethod?: string): Promise => { - return post('/api/v1/accounts', { id, value, login_method: loginMethod }); -}; - -// accountAvatarURL 生成账号头像地址。 -const accountAvatarURL = (item: AccountSummaryResponse, version: string): string => { - // raw 原始值,用于当前 API 处理流程。 - const raw = item.avatar_url || ''; - if (!raw) return ''; - - try { - // url 解析后的地址,用于当前 API 处理流程。 - const url = new URL(raw, window.location.origin); - if (url.hostname.endsWith('alicdn.com')) { - url.searchParams.set('_v', version); - } - return url.toString(); - } catch { - return raw; - } -}; - -// getAccountDetails 读取账号详情。 -export const getAccountDetails = async (options?: RequestControlOptions): Promise => { - // data 数据,用于当前 API 处理流程。 - const data = await get('/api/v1/accounts/details', undefined, options); - // avatarVersion 头像缓存版本,用于当前 API 处理流程。 - const avatarVersion = Date.now().toString(); - return data.map(/* 当前回调用于处理集合元素或接口响应。 */ item => ({ - id: item.id, - value: '', - enabled: item.enabled, - auto_confirm: item.auto_confirm, - remark: item.remark, - pause_duration: item.pause_duration, - paused_until: Number(item.paused_until || 0), - paused: item.paused === true, - username: item.username || '', - login_password: '', - show_browser: item.show_browser === true || item.show_browser === 1 || item.show_browser === '1' || item.show_browser === 'true', - nickname: item.nickname || item.remark || `账号 ${item.id.substring(0,6)}`, - avatar_url: accountAvatarURL(item, avatarVersion), - profile_error: item.profile_error || '', - ai_enabled: false, - auto_rate_enabled: item.auto_rate_enabled, - rate_content: item.rate_content || '不错的买家,交易愉快', - auto_polish_enabled: item.auto_polish_enabled, - polish_time: item.polish_time || '03:00', - last_rate_scan_at: Number(item.last_rate_scan_at || 0), - last_polish_date: item.last_polish_date || '', - last_polish_at: Number(item.last_polish_at || 0), - })); -}; - -// getAccountTaskSettings 读取账号计划任务设置。 -export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise => - get(`/api/v1/account-tasks/${id}`, undefined, options); - -// updateAccountTaskSettings 更新账号计划任务设置。 -export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise => - put(`/api/v1/account-tasks/${id}`, settings, options); - -// runAccountTask 立即执行账号计划任务。 -export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise => - post(`/api/v1/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options }); - -export interface ChatSessionPage { /** sessions 表示聊天会话列表。 */ sessions: ChatSession[]; /** has_more 表示是否存在更多数据。 */ has_more: boolean; /** next_cursor 表示下一页游标。 */ next_cursor?: number } - -// getChatSessionPage 分页读取聊天会话。 -export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get('/api/v1/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined }, - refresh ? { timeoutMs: 60_000, ...options } : options); - return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor }; -}; - -// getChatSessions 读取聊天会话列表。 -export const getChatSessions = async (accountId: string, options?: RequestControlOptions): Promise => - (await getChatSessionPage(accountId, undefined, options)).sessions; - -export interface ChatMessagePage { - /** messages 表示聊天消息列表。 */ messages: ChatMessage[]; - /** has_more 表示是否存在更多数据。 */ has_more: boolean; - /** next_cursor 表示下一页游标。 */ next_cursor?: number; - /** session 表示会话。 */ session?: ChatSession; -} - -// getChatMessagePage 分页读取聊天消息。 -export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get('/api/v1/chat/messages', { - account_id: accountId, chat_id: chatId, cursor, before_id: beforeId, - }, options); - return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session }; -}; - -// getChatMessages 读取聊天消息列表。 -export const getChatMessages = async (accountId: string, chatId: string, beforeId?: number, options?: RequestControlOptions): Promise => - (await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages; - -// sendChatMessage 发送聊天文本消息。 -export const sendChatMessage = async (input: { - /** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string; - /** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** text 表示文本。 */ text: string; -}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => post('/api/v1/chat/messages', input, options); - -// sendChatImage 发送聊天图片消息。 -export const sendChatImage = async (input: { - /** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string; - /** buyer_avatar_url 表示买家头像地址。 */ buyer_avatar_url?: string; /** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** image 表示图片数据。 */ image: File; -}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => { - // form 消息表单,用于当前 API 处理流程。 - const form = new FormData(); - Object.entries(input).forEach(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => form.append(key, value)); - return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options }); -}; - -// markChatRead 标记聊天消息已读。 -export const markChatRead = async (accountId: string, chatId: string, options?: RequestControlOptions): Promise => - post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId }, options); - -export interface AccountRuntimeStatus { - /** state 表示状态。 */ state: NonNullable; - /** message 表示消息数据。 */ message?: string; - /** connected 表示连接状态。 */ connected: boolean; - /** failures 表示失败次数。 */ failures: number; - /** updated_at 表示最后更新时间。 */ updated_at: string; -} - -// getAccountRuntimeStatuses 读取账号运行状态。 -export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise> => { - return get('/api/v1/accounts/runtime-status', undefined, options); -}; - -// generateQRLogin 生成二维码登录会话。 -export const generateQRLogin = async (options?: RequestControlOptions): Promise => { - // 风控后匿名 token 接口可能超过通用的 30 秒请求窗口;后端总生成窗口为 2 分钟。 - return post('/api/v1/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 }); -}; - -// checkQRLoginStatus 查询二维码登录状态。 -export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise => { - return get(`/api/v1/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 }); -}; - -// completeQRVerification 完成二维码登录验证。 -export const completeQRVerification = async ( - sessionId: string, - targetAccountId?: string, -): Promise => { - return post(`/api/v1/qr-login/complete-verification/${sessionId}`, { - target_account_id: targetAccountId || '', - }); -}; - - - - - - -// updateAccountStatus 更新账号状态。 -export const updateAccountStatus = async (id: string, enabled: boolean): Promise => { - return put(`/api/v1/accounts/${id}/status`, { enabled }); -}; - -// deleteAccount 删除账号。 -export const deleteAccount = async (id: string): Promise => { - return del(`/api/v1/accounts/${id}`); -}; - -// updateAccountRemark 更新账号备注。 -export const updateAccountRemark = async (id: string, remark: string): Promise => { - return put(`/api/v1/accounts/${id}/remark`, { remark }); -}; - -// updateAccountAutoConfirm 更新账号自动确认设置。 -export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise => { - return put(`/api/v1/accounts/${id}/auto-confirm`, { auto_confirm: autoConfirm }); -}; - -// updateAccountPauseDuration 更新账号暂停时长。 -export const updateAccountPauseDuration = async (id: string, pauseDuration: number, options?: RequestControlOptions): Promise => { - return put(`/api/v1/accounts/${id}/pause-duration`, { pause_duration: pauseDuration }, options); -}; - -// updateAccountCookie 更新账号登录凭证。 -export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise => { - return put(`/api/v1/accounts/${id}`, { id, value, login_method: loginMethod }); -}; - -export interface AccountSettingsUpdate { - /** cookie 表示登录凭证。 */ cookie?: string; - /** remark 表示备注。 */ remark?: string; - /** auto_confirm 表示自动确认状态。 */ auto_confirm?: boolean; - /** pause_duration 表示暂停时长。 */ pause_duration?: number; - /** username 表示用户名。 */ username?: string; - /** login_password 表示登录密码。 */ login_password?: string; - /** clear_password 表示是否清理登录密码。 */ clear_password?: boolean; - /** show_browser 表示是否显示浏览器。 */ show_browser?: boolean; - /** channel_ids 表示通知渠道标识列表。 */ channel_ids?: number[]; -} - -// updateAccountSettings 更新账号设置。 -export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate, options?: RequestControlOptions): Promise => { - return put(`/api/v1/accounts/${id}/settings`, data, options); -}; - -export interface LongLoginSettings { - /** can_open_long_login 表示是否允许开启长期登录。 */ can_open_long_login: boolean; - /** enabled 表示启用状态。 */ enabled: boolean; -} - -// getLongLoginSettings 读取长期登录设置。 -export const getLongLoginSettings = async (id: string, options?: RequestControlOptions): Promise => { - return get(`/api/v1/accounts/${id}/long-login`, undefined, options); -}; - -// setLongLoginSettings 设置长期登录开关。 -export const setLongLoginSettings = async (id: string, enabled: boolean, options?: RequestControlOptions): Promise => { - return put(`/api/v1/accounts/${id}/long-login`, { enabled }, options); -}; - -export interface PasswordLoginStartResponse { - /** success 表示是否成功。 */ success: boolean; - /** session_id 表示会话标识。 */ session_id?: string; - /** status 表示状态值。 */ status?: 'processing' | 'failed'; - /** message 表示消息数据。 */ message?: string; -} - -export interface PasswordLoginStatusResponse { - /** status 表示状态值。 */ status: 'processing' | 'success' | 'failed' | 'verification_required' | 'not_found' | 'error'; - /** message 表示消息数据。 */ message?: string; - /** account_id 表示账号标识。 */ account_id?: string; - /** is_new_account 表示是否为新账号。 */ is_new_account?: boolean; - /** cookie_count 表示登录凭证数量。 */ cookie_count?: number; - /** verification_url 表示验证地址。 */ verification_url?: string; - /** screenshot_path 表示验证截图路径。 */ screenshot_path?: string; - /** qr_code_url 表示二维码地址。 */ qr_code_url?: string; - /** error 表示错误信息。 */ error?: string; - /** reason 表示失败原因。 */ reason?: string; -} - -// passwordLogin 执行密码登录。 -export const passwordLogin = async (data: { - /** account_id 表示账号标识。 */ account_id: string; - /** account 表示账号。 */ account: string; - /** password 表示密码。 */ password: string; - /** show_browser 表示是否显示浏览器。 */ show_browser?: boolean; -}, options?: RequestControlOptions): Promise => { - return post('/api/v1/password-login', data, options); -}; - -// checkPasswordLoginStatus 查询密码登录状态。 -export const checkPasswordLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise => { - return get(`/api/v1/password-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 }); -}; - -// cancelPasswordLogin 取消密码登录。 -export const cancelPasswordLogin = async (sessionId: string, options?: RequestControlOptions): Promise => { - return del(`/api/v1/password-login/cancel/${sessionId}`, undefined, options); -}; - -// refreshAccountProfile 刷新账号资料。 -export const refreshAccountProfile = async (id: string): Promise => { - return post(`/api/v1/accounts/${id}/refresh-profile`, {}); -}; - -// updateAccountLoginInfo 更新账号登录信息。 -export const updateAccountLoginInfo = async (id: string, data: { - /** username 表示用户名。 */ username?: string; - /** login_password 表示登录密码。 */ login_password?: string; - /** clear_password 表示是否清理登录密码。 */ clear_password?: boolean; - /** show_browser 表示是否显示浏览器。 */ show_browser?: boolean; -}): Promise => { - return put(`/api/v1/accounts/${id}/login-info`, data); -}; - -// getAllAISettings 读取全部人工智能设置。 -export const getAllAISettings = async (options?: RequestControlOptions): Promise> => { - return get('/api/v1/settings/ai-reply', undefined, options); -}; - -// Orders -// normalizeOrderStatus 归一化订单状态。 -const normalizeOrderStatus = (value: unknown): Order['status'] => { - // status 状态值,用于当前 API 处理流程。 - const status = String(value || ''); - if (status === 'paid') return 'pending_ship'; - return ['processing', 'pending_ship', 'shipped', 'completed', 'cancelled', 'refunding'].includes(status) - ? status as Order['status'] - : 'unknown'; -}; - -// getOrders 读取订单列表。 -export const getOrders = async ( - cookieId?: string, - status?: string, - page: number = 1, - pageSize: number = 20, - search?: string, - options?: RequestControlOptions, -): Promise> => { - // params 请求参数,用于当前 API 处理流程。 - const params: any = { page, page_size: pageSize }; - if (cookieId) params.cookie_id = cookieId; - if (status && status !== 'all') params.status = status; - if (search?.trim()) params.search = search.trim(); - - // res 接口响应结果,用于当前 API 处理流程。 - const res = await get & { orders?: Order[] /* 后端兼容的订单列表字段。 */ }>('/api/v1/orders', params, options); - - // Handle backend response variations - // rawOrders 原始订单列表,用于当前 API 处理流程。 - const rawOrders = res.orders || res.data || []; - // orders 订单列表,用于当前 API 处理流程。 - const orders = rawOrders.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ - ...item, - id: item.id || item.order_id, - status: normalizeOrderStatus(item.status || item.order_status), - quantity: Number(item.quantity || 1), - })); - return { - success: true, - data: orders, - total: res.total || orders.length, - page: res.page || page, - page_size: res.page_size || pageSize, - total_pages: res.total_pages || 1 - }; -}; - -// getOrderDetail 读取订单详情。 -export const getOrderDetail = async (orderId: string): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: OrderDTOResponse }> => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get(`/api/v1/orders/${orderId}`); - return { - success: true, - data: result.data - }; -}; - -// updateOrder 更新订单。 -export const updateOrder = async (orderId: string, data: Partial): Promise => { - return put(`/api/v1/orders/${orderId}`, data); -}; - -// deleteOrder 删除订单。 -export const deleteOrder = async (orderId: string): Promise => { - return del(`/api/v1/orders/${orderId}`); -}; - -// syncOrders 同步订单。 -export const syncOrders = async (cookieId?: string, status?: string, options?: RequestControlOptions): Promise => { - // formData 表单数据,用于当前 API 处理流程。 - const formData = new FormData(); - if (cookieId) formData.append('cookie_id', cookieId); - if (status) formData.append('status', status); - - // start 表示后台订单刷新任务创建响应。 - const start = await postForm('/api/v1/orders/refresh', formData, options); - // cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务。 - const cancelOnAbort = () => { - void cancelOrderRefreshJob(start.job_id).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined); - }; - options?.signal?.addEventListener('abort', cancelOnAbort, { once: true }); - // pollLimit 限制前端等待后台任务的轮询次数。 - const pollLimit = 180; - // pollIndex 表示当前订单刷新任务状态轮询次数。 - let pollIndex = 0; - try { - while (pollIndex < pollLimit) { - // job 表示当前轮询得到的后台任务状态。 - const job = await get(`/api/v1/orders/refresh/${start.job_id}`, undefined, options); - if (job.status === 'succeeded' && job.result) { - return job.result; - } - if (job.status === 'failed' || job.status === 'cancelled') { - throw new Error(job.error_message || '订单刷新任务失败'); - } - // waitMs 是下一次任务状态轮询前的等待时间。 - const waitMs = 500; - await new Promise(/* 轮询等待器负责等待下一次任务状态查询。 */ (resolve, reject) => { - // abort 负责响应调用方取消轮询。 - const abort = () => { - globalThis.clearTimeout(timer); - reject(new Error('请求已取消')); - }; - // timer 表示当前轮询等待定时器。 - const timer = globalThis.setTimeout(/* 轮询完成回调清理取消监听并结束等待。 */ () => { - options?.signal?.removeEventListener('abort', abort); - resolve(); - }, waitMs); - if (!options?.signal) return; - if (options.signal.aborted) abort(); - else options.signal.addEventListener('abort', abort, { once: true }); - }); - pollIndex += 1; - } - } finally { - options?.signal?.removeEventListener('abort', cancelOnAbort); - } - throw new Error('订单刷新任务等待超时'); -}; - -// cancelOrderRefreshJob 请求取消当前用户的订单刷新后台任务。 -export const cancelOrderRefreshJob = async (jobId: string): Promise => { - return del(`/api/v1/orders/refresh/${jobId}`); -}; - -// syncSingleOrder 同步单个订单。 -export const syncSingleOrder = async (orderId: string): Promise => { - return post(`/api/v1/orders/${orderId}/refresh`); -}; - -// manualShipOrder 手动发货订单。 -export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise => { - return post('/api/v1/orders/manual-ship', { - order_ids: orderIds, - ship_mode: shipMode, - }); -} - -// importOrders 导入订单。 -export const importOrders = async (data: Partial[] | FormData, options?: RequestControlOptions): Promise => { - // isFormData 是否为表单请求,用于当前 API 处理流程。 - const isFormData = data instanceof FormData; - return isFormData ? postForm('/api/v1/orders/import', data, options) : post('/api/v1/orders/import', data, options); -} - -// Stats -// getAdminStats 读取管理员统计数据。 -export const getAdminStats = async (): Promise => { - return get('/api/v1/admin/stats'); -}; - -// getDashboardStats 读取仪表盘统计数据。 -export const getDashboardStats = async (options?: RequestControlOptions): Promise => { - return get('/api/v1/analytics/dashboard', undefined, options); -}; - -// getOrderAnalytics 读取订单分析数据。 -export const getOrderAnalytics = async (daysOrParams: number | {/** start_date 表示开始日期。 */ start_date: string; /** end_date 表示结束日期。 */ end_date: string} = 7, options?: RequestControlOptions): Promise => { - // params 请求参数,用于当前 API 处理流程。 - let params: {/** start_date 表示开始日期。 */ start_date: string; /** end_date 表示结束日期。 */ end_date: string}; - - if (typeof daysOrParams === 'number') { - // endDate 结束日期,用于当前 API 处理流程。 - const endDate = new Date(); - // startDate 启动日期。 - const startDate = new Date(); - startDate.setDate(startDate.getDate() - daysOrParams); - params = { - start_date: formatLocalDate(startDate), - end_date: formatLocalDate(endDate) - }; - } else { - params = daysOrParams; - } - - return get('/api/v1/analytics/orders', { - ...params, - timezone_offset_minutes: -new Date().getTimezoneOffset(), - }, options); -} - -export interface ValidOrdersResult { - /** orders 表示订单列表。 */ orders: Order[]; - /** total 表示总数。 */ total: number; - /** truncated 表示是否截断。 */ truncated: boolean; -} - -// getValidOrders 读取有效订单列表。 -export const getValidOrders = async (dateRange: {/** start_date 表示开始日期。 */ start_date: string; /** end_date 表示结束日期。 */ end_date: string}, options?: RequestControlOptions): Promise => { - // res 接口响应结果,用于当前 API 处理流程。 - const res = await get('/api/v1/analytics/orders/valid', { - start_date: dateRange.start_date, - end_date: dateRange.end_date, - timezone_offset_minutes: -new Date().getTimezoneOffset(), - }, options); - // orders 订单列表,用于当前 API 处理流程。 - const orders = Array.isArray(res) ? res : (res.orders || []); - // normalized 归一化结果,用于当前 API 处理流程。 - const normalized = orders.map(/* 当前回调用于处理集合元素或接口响应。 */ (order: any) => ({ - ...order, - id: order.id || order.order_id, - status: normalizeOrderStatus(order.status || order.order_status), - quantity: Number(order.quantity || 1), - })); - return { - orders: normalized, - total: Array.isArray(res) ? normalized.length : Number(res.total ?? normalized.length), - truncated: Array.isArray(res) ? false : res.truncated === true, - }; -} - -// Cards -// normalizeCard 归一化卡密数据。 -const normalizeCard = (item: any): Card => { - // apiConfig 卡密接口配置,用于当前 API 处理流程。 - let apiConfig = item.api_config; - if (typeof apiConfig === 'string' && apiConfig.trim()) { - try { - apiConfig = JSON.parse(apiConfig); - } catch { - apiConfig = undefined; - } - } - return {...item, api_config: apiConfig || undefined} as Card; -}; - -// cardPayload 卡密请求载荷,用于当前 API 处理流程。 -const cardPayload = (data: Partial): Record => ({ - ...data, - api_config: data.api_config ? JSON.stringify(data.api_config) : '', -}); - -// getCards 读取卡密列表。 -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 || []); - return cards.map(normalizeCard); -}; - -// createCard 创建卡密组。 -export const createCard = async (data: Partial): Promise => { - return post('/api/v1/cards', cardPayload(data)); -}; - -// updateCard 更新卡密组。 -export const updateCard = async (cardId: string | number, data: Partial): Promise => { - return put(`/api/v1/cards/${cardId}`, cardPayload(data)); -}; - -// deleteCard 删除卡密组。 -export const deleteCard = async (cardId: string | number): Promise => { - return del(`/api/v1/cards/${cardId}`); -}; - -// getCardDetails 读取卡密组详情。 -export const getCardDetails = async (cardId: string | number): Promise => { - // card 卡密详情,用于当前 API 处理流程。 - const card = await get(`/api/v1/cards/${cardId}/details`); - return normalizeCard(card); -}; - -// 批量创建卡密组(上传表格) -export const batchCreateCards = async (file: File, options?: RequestControlOptions): Promise => { - // 批量创建接口返回总行数、成功数、失败数和逐行结果。 - // CardBatchResponse 保留旧字段名称,调用方无需转换统计字段。 - // rows 中的 id 只在创建成功时返回。 - // rows 中的 error 只在对应行失败时返回。 - // 表单上传方式和接口路径保持不变。 - // 此处只收紧 TypeScript 响应契约。 - const body = new FormData(); - body.append('file', file); - return postForm('/api/v1/cards/batch', body, options); -}; - -// 往 data 类型卡密组批量追加卡密号 -export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise => { - return post(`/api/v1/cards/${cardId}/append-data`, { content }, options); -}; - -// Items -// normalizeBooleanFlag 归一化布尔标记。 -const normalizeBooleanFlag = (value: unknown): boolean => - value === true || value === 1 || value === '1'; - -// getItems 读取商品列表。 -export const getItems = async (cookieId?: string, options?: RequestControlOptions): Promise => { - // res 接口响应结果,用于当前 API 处理流程。 - const res = await get('/api/v1/items', cookieId ? { cookie_id: cookieId } : undefined, options); - // items 商品列表,用于当前 API 处理流程。 - const items = Array.isArray(res) ? res : (res.items || []); - return items.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ - ...item, - id: item.id || `${item.cookie_id}-${item.item_id}`, - is_multi_spec: normalizeBooleanFlag(item.is_multi_spec), - is_multi_qty_ship: normalizeBooleanFlag(item.is_multi_qty_ship ?? item.multi_quantity_delivery), - multi_quantity_delivery: normalizeBooleanFlag(item.multi_quantity_delivery ?? item.is_multi_qty_ship), - })); -} - -// syncItemsFromAccount 从账号同步商品。 -export const syncItemsFromAccount = async (cookieId: string): Promise => { - return post('/api/v1/items/get-all-from-account', { cookie_id: cookieId }); -} - -// deleteItem 删除商品。 -export const deleteItem = async (cookieId: string, itemId: string): Promise => { - return del(`/api/v1/items/${cookieId}/${itemId}`); -} - -// createItem 创建商品。 -export const createItem = async (cookieId: string, data: Partial): Promise => { - return post(`/api/v1/items/${cookieId}`, data); -} - -// publishItem 发布商品。 -export const publishItem = async (form: { - /** cookie_id 表示登录凭证标识。 */ cookie_id: string; - /** title 表示标题。 */ title: string; - /** description 表示描述。 */ description: string; - /** price 表示售价。 */ price: string; - /** original_price 表示原始售价。 */ original_price?: string; - /** quantity 表示数量。 */ quantity: string | number; - /** postage_mode 表示运费模式。 */ postage_mode: string; - /** postage 表示运费。 */ postage?: string; - /** images 表示图片列表。 */ images: File[]; - /** location 表示地址。 */ location?: PublishLocation; -}): Promise => { - // body 请求体,用于当前 API 处理流程。 - const body = new FormData(); - body.set('cookie_id', form.cookie_id); - body.set('title', form.title); - body.set('description', form.description); - body.set('price', form.price); - body.set('original_price', form.original_price || ''); - body.set('quantity', String(form.quantity)); - body.set('postage_mode', form.postage_mode); - body.set('postage', form.postage || ''); - if (form.location) body.set('location', JSON.stringify(form.location)); - for (const // file 上传文件,用于当前 API 处理流程。 -file of form.images) { - body.append('images', file); - } - return postForm('/api/v1/items/publish', body); -} - -export interface PublishLocation { - /** area 表示地区。 */ area: string; - /** city 表示城市。 */ city: string; - /** division_id 表示行政区划标识。 */ division_id: string; - /** longitude 表示经度。 */ longitude: number; - /** latitude 表示纬度。 */ latitude: number; - /** poi_id 表示地点标识。 */ poi_id: string; - /** poi_name 表示地点名称。 */ poi_name: string; - /** province 表示省份。 */ province: string; -} - -// recommendPublishCategory 推荐商品发布分类。 -export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise => { - // 类目推荐成功响应使用共享 CategoryRecommendationResponse。 - // category 字段保留平台类目 ID、名称和频道类目 ID。 - // tb_cat_id 继续保持可选,兼容电子资料类目。 - // 请求仍携带账号 ID 和关键词。 - // 失败响应由共享 HTTP 错误结构处理。 - // 该类型收口不改变凭证刷新和错误处理。 - // 前端批量发布流程可直接复用 category。 - // 旧路径继续由现有 Vite 代理转发。 - return post('/api/v1/items/publish-categories/recommend', { cookie_id: cookieId, keyword }); -}; - -// previewItemPublishBatch 预览商品批量发布。 -export const previewItemPublishBatch = async (form: { - /** file 表示上传文件。 */ file: File; - /** imagesZip 表示图片压缩包。 */ imagesZip?: File | null; - /** defaultCookieId 表示默认账号凭证标识。 */ defaultCookieId?: string; - /** fallbackCategory 表示备用分类。 */ fallbackCategory: { - /** catId 表示分类标识。 */ catId: string; - /** catName 表示分类名称。 */ catName: string; - /** channelCatId 表示渠道分类标识。 */ channelCatId?: string; - /** tbCatId 表示淘宝分类标识。 */ tbCatId?: string; - }; - /** location 表示地址。 */ location?: PublishLocation; -}): Promise => { - // body 请求体,用于当前 API 处理流程。 - const body = new FormData(); - body.set('file', form.file); - if (form.imagesZip) body.set('images_zip', form.imagesZip); - if (form.defaultCookieId) body.set('default_cookie_id', form.defaultCookieId); - body.set('fallback_category_id', form.fallbackCategory.catId); - body.set('fallback_category_name', form.fallbackCategory.catName); - body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || ''); - body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || ''); - if (form.location) body.set('location', JSON.stringify(form.location)); - return postForm('/api/v1/items/publish-batches/preview', body); -} - -// startItemPublishBatch 启动商品批量发布。 -export const startItemPublishBatch = async (previewId: string): Promise => { - return post('/api/v1/items/publish-batches', { preview_id: previewId }); -} - -// getItemPublishBatch 读取商品发布批次。 -export const getItemPublishBatch = async (batchId: string): Promise => { - return get(`/api/v1/items/publish-batches/${batchId}`); -} - -// getItemPublishBatches 读取商品发布批次列表。 -export const getItemPublishBatches = async (limit = 20): Promise => { - // res 接口响应结果,用于当前 API 处理流程。 - const res = await get('/api/v1/items/publish-batches', { limit }); - return Array.isArray(res) ? res : (res.batches || []); -} - -// deleteItemPublishBatch 删除商品发布批次。 -export const deleteItemPublishBatch = async (batchId: string): Promise => { - return del(`/api/v1/items/publish-batches/${batchId}`); -} - -// cancelItemPublishBatch 取消商品发布批次。 -export const cancelItemPublishBatch = async (batchId: string): Promise => { - return post(`/api/v1/items/publish-batches/${batchId}/cancel`, {}); -} - -// retryFailedItemPublishBatch 重试失败的商品发布任务。 -export const retryFailedItemPublishBatch = async (batchId: string): Promise => { - return post(`/api/v1/items/publish-batches/${batchId}/retry-failed`, {}); -} - -// updateItem 更新商品。 -export const updateItem = async (cookieId: string, itemId: string, data: Partial): Promise => { - return put(`/api/v1/items/${cookieId}/${itemId}`, data); -} - -// Rules - 自动化规则 -const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ - id: String(item.id), - name: item.name || '', - trigger_type: item.trigger_type || 'order_paid', - item_keyword: item.item_title || item.item_id || '', - cookie_id: item.cookie_id || '', - item_id: item.item_id || '', - item_title: item.item_title || '', - card_group_id: Number((item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_id || 0), - card_group_name: (item.actions || []).find(/* 当前回调用于处理集合元素或接口响应。 */ (a: any) => a.action_type === 'send_card')?.card_name || '', - priority: item.priority || 100, - enabled: item.enabled || false, - config_json: item.config_json || '{}', - actions: (item.actions || []).map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => ({ - id: action.id ? String(action.id) : undefined, - action_type: action.action_type, - card_id: Number(action.card_id || 0), - card_name: action.card_name || '', - delivery_count: Number(action.delivery_count || 1), - message_template: action.message_template || '', - delay_seconds: Number(action.delay_seconds || 0), - config_json: action.config_json || '{}', - enabled: action.enabled !== false, - sort_order: Number(action.sort_order || 0), - })), - variants: (item.actions || []) - .filter(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => action.action_type === 'send_card') - .map(/* 当前回调用于处理集合元素或接口响应。 */ (action: any) => { - // cfg 动作配置,用于当前 API 处理流程。 - let cfg: any = {}; - try { cfg = JSON.parse(action.config_json || '{}'); } catch {} - return { - id: action.id ? String(action.id) : undefined, - spec_name: cfg.spec_name || '', - spec_value: cfg.spec_value || '', - card_id: Number(action.card_id || 0), - card_name: action.card_name || '', - delivery_count: Number(action.delivery_count || 1), - enabled: action.enabled !== false, - delay_override: cfg.delay_override === true, - delay_seconds: Number(action.delay_seconds || 0), - config_json: action.config_json || '{}', - }; - }), - })); - -// getShippingRules 读取发货规则列表。 -export const getShippingRules = async (): Promise => { - // res 接口响应结果,用于当前 API 处理流程。 - const res = await get('/api/v1/automation-rules'); - // rules 规则列表,用于当前 API 处理流程。 - const rules = Array.isArray(res) ? res : (res.data || []); - return normalizeShippingRules(rules); -} - -export interface ShippingRuleListParams { - /** cookieId 表示登录凭证标识。 */ cookieId?: string; - /** triggerType 表示触发类型。 */ triggerType?: AutomationTriggerType | ''; - /** enabled 表示启用状态。 */ enabled?: boolean; - /** search 表示搜索条件。 */ search?: string; - /** page 表示页码。 */ page?: number; - /** pageSize 表示每页数量。 */ pageSize?: number; -} - -// getShippingRulesPage 分页读取发货规则。 -export const getShippingRulesPage = async ({ - cookieId, - triggerType, - enabled, - search, - page = 1, - pageSize = 10, -}: ShippingRuleListParams = {}): Promise> => { - // res 接口响应结果,用于当前 API 处理流程。 - const res = await get('/api/v1/automation-rules', { - page, - page_size: pageSize, - cookie_id: cookieId || undefined, - trigger_type: triggerType || undefined, - enabled, - search: search?.trim() || undefined, - }); - // rules 规则列表,用于当前 API 处理流程。 - const rules = normalizeShippingRules(Array.isArray(res) ? res : (res.data || [])); - return { - success: true, - data: rules, - total: Number(Array.isArray(res) ? rules.length : (res.total ?? rules.length)), - page: Number(Array.isArray(res) ? page : (res.page ?? page)), - page_size: Number(Array.isArray(res) ? pageSize : (res.page_size ?? pageSize)), - total_pages: Number(Array.isArray(res) ? (rules.length ? 1 : 0) : (res.total_pages ?? (rules.length ? 1 : 0))), - trigger_counts: Object.fromEntries( - Object.entries(Array.isArray(res) ? {} : res.trigger_counts || {}).map(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => [key, Number(value)]), - ), - }; -} - -// orderAutomationActions 构建订单自动化动作。 -const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => { - if (triggerType !== 'order_paid') { - return actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: action.sort_order || index + 1 })); - } - // sendCards 发送Cards。 - const sendCards = actions - .filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type === 'send_card') - .map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: index + 1 })); - // others 其他动作列表,用于当前 API 处理流程。 - const others = actions.filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment'); - return [ - ...sendCards, - ...others.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ ...action, sort_order: sendCards.length + index + 1 })), - { action_type: 'confirm_shipment' as const, enabled: true, sort_order: sendCards.length + others.length + 1 }, - ]; -}; - -// updateShippingRule 更新发货规则。 -export const updateShippingRule = async (rule: Partial): Promise => { - // triggerType 触发类型,用于当前 API 处理流程。 - const triggerType = rule.trigger_type || 'order_paid'; - // triggerName 触发名称,用于当前 API 处理流程。 - const triggerName: Record = { - order_paid: '付款后自动发货', - buyer_reviewed: '评价后发送赠品', - review_missing_timeout: '超时未评价求评价', - }; - // generatedName 生成d名称。 - const generatedName = [ - triggerName[triggerType] || '自动化规则', - rule.item_title || rule.item_id || rule.cookie_id || '', - ].filter(Boolean).join(' - '); - // preservedNonCardActions 保留的非卡密动作,用于当前 API 处理流程。 - const preservedNonCardActions = (rule.actions || []).filter(/* 当前回调用于处理集合元素或接口响应。 */ action => action.action_type !== 'send_card' && action.action_type !== 'confirm_shipment'); - // baseActions 基础动作列表,用于当前 API 处理流程。 - const baseActions: AutomationAction[] = rule.variants && rule.variants.length > 0 - ? [...rule.variants.map(/* 当前回调用于处理集合元素或接口响应。 */ (variant, index) => ({ - action_type: 'send_card' as const, - card_id: variant.card_id, - delivery_count: variant.delivery_count || 1, - enabled: variant.enabled !== false, - sort_order: index + 1, - delay_seconds: variant.delay_seconds || 0, - config_json: JSON.stringify({ - spec_name: variant.spec_name || '', - spec_value: variant.spec_value || '', - delay_override: variant.delay_override === true, - }), - })), ...preservedNonCardActions] - : (rule.actions && rule.actions.length > 0 ? rule.actions : [{ - action_type: 'send_card' as const, - card_id: rule.card_group_id || 0, - delivery_count: 1, - enabled: true, - sort_order: 1, - }]); - // actions 动作列表,用于当前 API 处理流程。 - const actions = orderAutomationActions(triggerType, baseActions); - // payload 请求载荷,用于当前 API 处理流程。 - const payload = { - cookie_id: rule.cookie_id || '', - item_id: rule.item_id || '', - name: (rule.name || '').trim() || generatedName || '自动化规则', - trigger_type: triggerType, - enabled: rule.enabled ?? true, - priority: rule.priority || 100, - config_json: rule.config_json || '{}', - actions: actions.map(/* 当前回调用于处理集合元素或接口响应。 */ (action, index) => ({ - action_type: action.action_type, - card_id: action.card_id || 0, - delivery_count: action.delivery_count || 1, - message_template: action.message_template || '', - delay_seconds: action.delay_seconds || 0, - config_json: action.config_json || '{}', - enabled: action.enabled !== false, - sort_order: action.sort_order || index + 1, - })), - }; - return rule.id ? put(`/api/v1/automation-rules/${rule.id}`, payload) : post('/api/v1/automation-rules', payload); -} - -// deleteShippingRule 删除发货规则。 -export const deleteShippingRule = async (id: string): Promise => del(`/api/v1/automation-rules/${id}`); - -export interface AutomationRunIssue { - /** id 表示标识。 */ id: number; - /** cookie_id 表示登录凭证标识。 */ cookie_id: string; - /** order_id 表示订单标识。 */ order_id: string; - /** trigger_type 表示触发条件类型。 */ trigger_type: string; - /** error_message 表示错误消息。 */ error_message: string; - /** issue_kind 表示问题类型。 */ issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed'; - /** allowed_resolutions 表示允许的解决方式。 */ allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>; - /** action_cursor 表示动作游标。 */ action_cursor: number; - /** sent_count 表示已发送数量。 */ sent_count: number; - /** updated_at 表示最后更新时间。 */ updated_at: string; -} - -export interface DeferredAutomationIssue { - /** id 表示标识。 */ id: number; - /** cookie_id 表示登录凭证标识。 */ cookie_id: string; - /** trigger_type 表示触发条件类型。 */ trigger_type: string; - /** error_message 表示错误消息。 */ error_message: string; - /** attempt_count 表示尝试次数。 */ attempt_count: number; - /** updated_at 表示最后更新时间。 */ updated_at: string; -} - -// getAutomationIssues 读取自动化问题列表。 -export const getAutomationIssues = async (): Promise<{ /** runs 表示运行记录。 */ runs: AutomationRunIssue[]; /** pending_tasks 表示待处理任务列表。 */ pending_tasks: DeferredAutomationIssue[] }> => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get('/api/v1/automation-issues'); - return { - runs: Array.isArray(result?.runs) ? result.runs : [], - pending_tasks: Array.isArray(result?.pending_tasks) ? result.pending_tasks : [], - }; -}; - -// resolveAutomationRun 处理自动化运行记录。 -export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise => - post(`/api/v1/automation-runs/${id}/resolve`, { resolution }); - -// resolveDeferredAutomationTask 处理延迟自动化任务。 -export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise => - post(`/api/v1/automation-pending-tasks/${id}/resolve`, { resolution }); - -// Rules - 关键词回复规则 (使用关键词API) -type KeywordRowPayload = { - /** id 表示标识。 */ id: string; - /** keyword 表示关键词。 */ keyword: string; - /** reply 表示回复内容。 */ reply: string; - /** item_id 表示商品标识。 */ item_id: string; - /** type 表示规则类型。 */ type: 'text' | 'image'; - /** image_url 表示图片地址。 */ image_url: string; -}; - -// normalizeKeywordRow 归一化关键词规则。 -const normalizeKeywordRow = (item: any): KeywordRowPayload => ({ - id: String(item?.id || ''), - keyword: item?.keyword || '', - reply: item?.reply || '', - item_id: item?.item_id || '', - type: item?.type === 'image' ? 'image' : 'text', - image_url: item?.image_url || '', -}); - -// getKeywordRowsWithType 读取带类型的关键词规则。 -const getKeywordRowsWithType = async (cookieId: string): Promise => { - // existing 已有规则,用于当前 API 处理流程。 - const existing = await get(`/api/v1/reply-rules/${cookieId}/typed`); - return Array.isArray(existing) ? existing.map(normalizeKeywordRow) : []; -}; - -// getReplyRules 读取回复规则。 -export const getReplyRules = async (cookieId?: string): Promise => { - if (!cookieId) return []; - // keywords keywords,用于当前 API 处理流程。 - const keywords = await getKeywordRowsWithType(cookieId); - return keywords.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ - id: item.id, - keyword: item.keyword || '', - reply_content: item.reply || '', - match_type: 'fuzzy' as const, - enabled: true, - item_id: item.item_id || '', - type: item.type === 'image' ? 'image' : 'text', - image_url: item.image_url || '' - })); -} - -// updateReplyRule 更新回复规则。 -export const updateReplyRule = async (rule: Partial, cookieId: string): Promise => { - // type 规则类型,用于当前 API 处理流程。 - const type = rule.type || 'text'; - // payload 请求载荷,用于当前 API 处理流程。 - const payload = { - keyword: rule.keyword || '', - reply: type === 'text' ? (rule.reply_content || '') : '', - item_id: rule.item_id || '', - type, - image_url: type === 'image' ? (rule.image_url || '') : '', - }; - return rule.id - ? put(`/api/v1/reply-rules/${cookieId}/typed/${rule.id}`, payload) - : post(`/api/v1/reply-rules/${cookieId}/items`, payload); -} - -// deleteReplyRule 删除回复规则。 -export const deleteReplyRule = async (id: string, cookieId: string): Promise => { - return del(`/api/v1/reply-rules/${cookieId}/typed/${id}`); -} - -// Settings -/** 敏感系统设置的显式三态变更命令。 */ -export type SensitiveSettingChange = { - /** 敏感设置的三态动作。 */ - action: 'retain' | 'replace' | 'clear'; - /** replace 动作要保存的新秘密。 */ - value?: string; -}; - -/** 系统设置批量更新请求,敏感值只能通过 secrets 命令提交。 */ -export type SystemSettingsUpdate = { - /** 普通系统设置字段集合。 */ - values?: Record; - /** 敏感系统设置命令集合。 */ - secrets?: Record; -}; - -// SENSITIVE_SYSTEM_SETTING_KEYS 保存不能进入普通 values 的秘密配置键。 -const SENSITIVE_SYSTEM_SETTING_KEYS = new Set(['ai_api_key', 'smtp_password', 'qq_reply_secret_key', 'captcha.remote_secret_key']); - -/** 将兼容的设置草稿转换为普通值与敏感命令分离的请求。 */ -const normalizeSystemSettingsUpdate = (settings: Partial | SystemSettingsUpdate): Record => { - if ('values' in settings || 'secrets' in settings) return settings as Record; - // values 保存不会泄露秘密的普通设置。 - const values: Record = {}; - // secrets 保存需要服务端执行的敏感设置命令。 - const secrets: Record = {}; - // entry 表示当前遍历的设置键值对。 - for (const entry /* entry 表示当前遍历的设置键值对。 */ of Object.entries(settings)) { - // key、value 是当前设置键和值。 - const [key, value] = entry; - if (value === undefined || value === null) continue; - if (SENSITIVE_SYSTEM_SETTING_KEYS.has(key)) { - secrets[key] = value === '' ? { action: 'clear' } : { action: 'replace', value: String(value) }; - } else { - values[key] = value; - } - } - return Object.keys(secrets).length > 0 ? { values, secrets } : values; -}; - -// getSystemSettings 读取系统设置。 -export const getSystemSettings = async (options?: RequestControlOptions): Promise => { - // res 接口响应结果,用于当前 API 处理流程。 - const res = await get<{/** data 表示数据。 */ data: SystemSettings}>('/api/v1/settings/system', undefined, options); - return normalizeSettings(res.data || res); // handle {success:true, data: {...}} wrapper if exists -}; - -// updateSystemSettings 更新系统设置。 -export const updateSystemSettings = async (settings: Partial | SystemSettingsUpdate, options?: RequestControlOptions): Promise => { - // payload 是普通设置与敏感变更命令分离后的请求体。 - const payload = normalizeSystemSettingsUpdate(settings); - return put('/api/v1/settings/system', payload, options); -}; - -// getAccountAISettings 读取账号人工智能设置。 -export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise => { - return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options); -} - -// updateAccountAISettings 更新账号人工智能设置。 -export const updateAccountAISettings = async (cookieId: string, settings: Partial, options?: RequestControlOptions): Promise => { - // payload 请求载荷,用于当前 API 处理流程。 - const payload = { - ai_enabled: settings.ai_enabled ?? false, - max_discount_percent: settings.max_discount_percent ?? 10, - max_discount_amount: settings.max_discount_amount ?? 100, - max_bargain_rounds: settings.max_bargain_rounds ?? 3, - custom_prompts: settings.custom_prompts ?? '' - }; - return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options); -} - -// fetchAIModels 读取人工智能模型列表。 -export const fetchAIModels = async (baseUrl: string, apiKey: string = '', options?: RequestControlOptions): Promise => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await post('/api/v1/settings/ai-models', { - base_url: baseUrl, - api_key: apiKey, - }, options); - return result.models || []; -}; - -// Notification Channels -// parseNotificationEventTypes 解析通知事件类型。 -const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => { - if (Array.isArray(raw)) return raw.filter(Boolean) as NotificationEventType[]; - if (typeof raw !== 'string' || !raw.trim()) return []; - try { - // parsed 转换后的数值,用于当前 API 处理流程。 - const parsed = JSON.parse(raw); - if (Array.isArray(parsed)) return parsed.filter(Boolean) as NotificationEventType[]; - } catch { - // fall back to legacy comma/semicolon separated values - } - return raw.split(/[,\s;]+/).map(/* 当前回调用于处理集合元素或接口响应。 */ v => v.trim()).filter(Boolean) as NotificationEventType[]; -}; - -// stringifyNotificationEventTypes 序列化通知事件类型。 -const stringifyNotificationEventTypes = (events?: NotificationEventType[]): string => { - // clean 清理后的事件类型列表,用于当前 API 处理流程。 - const clean = Array.from(new Set((events || []).filter(Boolean))); - return clean.length > 0 ? JSON.stringify(clean) : ''; -}; - -// getNotificationChannels 读取通知渠道。 -export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationChannel[] }> => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get('/api/v1/notifications/channels', undefined, options); - // channels 通知渠道列表,用于当前 API 处理流程。 - const channels = (result || []).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => { - // parsedConfig 解析后的通知配置,用于当前 API 处理流程。 - let parsedConfig; - try { - parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config; - } catch { - parsedConfig = {}; - } - return { - id: String(item.id), - name: item.name, - type: item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type), - config: parsedConfig, - event_types: parseNotificationEventTypes(item.event_types), - enabled: item.enabled, - created_at: item.created_at, - updated_at: item.updated_at, - }; - }); - return { success: true, data: channels }; -} - -// createNotificationChannel 创建通知渠道。 -export const createNotificationChannel = async (data: { /** name 表示名称。 */ name: string; /** type 表示规则类型。 */ type: string; /** config 表示配置对象。 */ config: Record; /** event_types 表示通知事件类型列表。 */ event_types?: NotificationEventType[]; /** enabled 表示启用状态。 */ enabled?: boolean }, options?: RequestControlOptions): Promise => { - return post('/api/v1/notifications/channels', { - ...data, - config: JSON.stringify(data.config), - event_types: stringifyNotificationEventTypes(data.event_types) - }, options); -} - -// updateNotificationChannel 更新通知渠道。 -export const updateNotificationChannel = async (channelId: string, data: { /** name 表示名称。 */ name?: string; /** type 表示规则类型。 */ type?: string; /** config 表示配置对象。 */ config?: Record; /** event_types 表示通知事件类型列表。 */ event_types?: NotificationEventType[]; /** enabled 表示启用状态。 */ enabled?: boolean }, options?: RequestControlOptions): Promise => { - // payload 请求载荷,用于当前 API 处理流程。 - const payload: Record = { ...data }; - if ('config' in data) { - payload.config = JSON.stringify(data.config); - } - if ('event_types' in data) { - payload.event_types = stringifyNotificationEventTypes(data.event_types); - } - return put(`/api/v1/notifications/channels/${channelId}`, payload, options); -} - -// deleteNotificationChannel 删除通知渠道。 -export const deleteNotificationChannel = async (channelId: string, options?: RequestControlOptions): Promise => { - return del(`/api/v1/notifications/channels/${channelId}`, undefined, options); -} - -// Message Notifications -// getMessageNotifications 读取消息通知。 -export const getMessageNotifications = async (): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationBinding[] }> => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get>('/api/v1/notifications/messages'); - // notifications 通知列表,用于当前 API 处理流程。 - const notifications: NotificationBinding[] = []; - for (const // [cookieId, channelList] [cookieId,通知渠道List],用于当前 API 处理流程。 -[cookieId, channelList] of Object.entries(result || {})) { - if (Array.isArray(channelList)) { - for (const // item 当前条目,用于当前 API 处理流程。 -item of channelList) { - notifications.push({ - cookie_id: cookieId, - channel_id: item.channel_id, - channel_name: item.channel_name, - enabled: item.enabled, - }); - } - } - } - return { success: true, data: notifications }; -} - -// setMessageNotification 设置消息通知。 -export const setMessageNotification = async (cookieId: string, channelId: number, enabled: boolean): Promise => { - return post(`/api/v1/notifications/accounts/${cookieId}/bindings`, { channel_id: channelId, enabled }); -} - -// deleteMessageNotification 删除消息通知。 -export const deleteMessageNotification = async (notificationId: string): Promise => { - return del(`/api/v1/notifications/messages/${notificationId}`); -} - -// deleteAccountNotifications 删除账号通知。 -export const deleteAccountNotifications = async (cookieId: string): Promise => { - return del(`/api/v1/notifications/messages/account/${cookieId}`); -} - -// 账号 ↔ 渠道 绑定(覆盖式) -export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get(`/api/v1/notifications/accounts/${cookieId}/bindings`, undefined, options); - return result?.channel_ids || []; -} - -// setAccountBindings 设置账号通知绑定。 -export const setAccountBindings = async (cookieId: string, channelIds: number[]): Promise => { - return post(`/api/v1/notifications/accounts/${cookieId}/bindings`, { channel_ids: channelIds }); -} - -// 测试发送 -export const testNotificationChannel = async (channelId: string, options?: RequestControlOptions): Promise => { - return post(`/api/v1/notifications/channels/${channelId}/test`, {}, options); -} - -// Default Reply -// getDefaultReplies 读取默认回复列表。 -export const getDefaultReplies = async (): Promise> => { - return get('/api/v1/default-replies'); -}; - -// getDefaultReply 读取默认回复。 -export const getDefaultReply = async (cookieId: string): Promise => { - // result 接口响应结果,用于当前 API 处理流程。 - const result = await get(`/api/v1/default-replies/${cookieId}`); - return { - cookie_id: cookieId, - enabled: result.enabled || false, - reply_content: result.reply_content || '', - reply_once: result.reply_once || false, - reply_image_url: result.reply_image_url || '' - }; -}; - -// updateDefaultReply 更新默认回复。 -export const updateDefaultReply = async (cookieId: string, data: Partial): Promise => { - return put(`/api/v1/default-replies/${cookieId}`, { - enabled: data.enabled ?? false, - reply_content: data.reply_content || '', - reply_once: data.reply_once ?? false, - reply_image_url: data.reply_image_url || '' - }); -}; - -// deleteDefaultReply 删除默认回复。 -export const deleteDefaultReply = async (cookieId: string): Promise => { - return del(`/api/v1/default-replies/${cookieId}`); -}; - -// clearDefaultReplyRecords 清理默认回复记录。 -export const clearDefaultReplyRecords = async (cookieId: string): Promise => { - return post(`/api/v1/default-replies/${cookieId}/clear-records`, {}); -}; - -// getItemDetail 获取指定账号下单个商品的详情。 -export const getItemDetail = async (cookieId: string, itemId: string): Promise => { - return get(`/api/v1/items/${cookieId}/${itemId}`); -}; diff --git a/frontend/types.ts b/frontend/shared/api-contract/index.ts similarity index 97% rename from frontend/types.ts rename to frontend/shared/api-contract/index.ts index c4f6f03..1c7a565 100644 --- a/frontend/types.ts +++ b/frontend/shared/api-contract/index.ts @@ -33,12 +33,32 @@ export interface SessionResponse { is_admin?: boolean; } +/** 商品发布和发货地选择共用的只读地点契约。 */ +export interface PublishLocation { + /** 行政区划展示名称。 */ + area: string; + /** 城市展示名称。 */ + city: string; + /** 平台使用的行政区划标识。 */ + division_id: string; + /** 地点经度。 */ + longitude: number; + /** 地点纬度。 */ + latitude: number; + /** 平台兴趣点标识。 */ + poi_id: string; + /** 平台兴趣点展示名称。 */ + poi_name: string; + /** 省份展示名称。 */ + province: string; +} + // Accounts export interface AccountDetail { /** 闲鱼账号稳定标识。 */ id: string; - /** 账号当前 Cookie 值,仅在编辑或需要凭证的响应中使用。 */ - value?: string; // cookie value from backend + /** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */ + cookie_configured?: boolean; /** 账号是否允许运行。 */ enabled: boolean; /** 是否自动确认订单。 */ @@ -54,8 +74,8 @@ export interface AccountDetail { // 登录信息 /** 用于密码登录的闲鱼用户名。 */ username?: string; - /** 用于密码登录的登录密码。 */ - login_password?: string; + /** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */ + login_password_configured?: boolean; /** 是否在密码登录时显示浏览器。 */ show_browser?: boolean; // Frontend helpers @@ -1193,6 +1213,10 @@ export interface NotificationChannelResponse { enabled: boolean; /** 所属用户主键。 */ user_id?: number; + /** 创建时间;旧接口可能省略。 */ + created_at?: string; + /** 更新时间;旧接口可能省略。 */ + updated_at?: string; } /** 卡券列表接口的兼容包装响应。 */ diff --git a/frontend/components/latestRequest.test.ts b/frontend/shared/async/latestRequest.test.ts similarity index 100% rename from frontend/components/latestRequest.test.ts rename to frontend/shared/async/latestRequest.test.ts diff --git a/frontend/components/latestRequest.ts b/frontend/shared/async/latestRequest.ts similarity index 100% rename from frontend/components/latestRequest.ts rename to frontend/shared/async/latestRequest.ts diff --git a/frontend/components/sidebarState.test.ts b/frontend/shared/browser/sidebarState.test.ts similarity index 100% rename from frontend/components/sidebarState.test.ts rename to frontend/shared/browser/sidebarState.test.ts diff --git a/frontend/components/sidebarState.ts b/frontend/shared/browser/sidebarState.ts similarity index 100% rename from frontend/components/sidebarState.ts rename to frontend/shared/browser/sidebarState.ts diff --git a/frontend/request.test.ts b/frontend/shared/http/client.test.ts similarity index 99% rename from frontend/request.test.ts rename to frontend/shared/http/client.test.ts index a3f49e4..c581372 100644 --- a/frontend/request.test.ts +++ b/frontend/shared/http/client.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, test, vi } from 'vitest'; -import { del, get, post, postForm, put } from './request'; +import { del, get, post, postForm, put } from './client'; afterEach(() => vi.unstubAllGlobals() /* 回调函数负责当前业务流程。 */); diff --git a/frontend/request.ts b/frontend/shared/http/client.ts similarity index 99% rename from frontend/request.ts rename to frontend/shared/http/client.ts index b8e8524..dbdb0a5 100644 --- a/frontend/request.ts +++ b/frontend/shared/http/client.ts @@ -158,4 +158,4 @@ const errorMessageFromPayload = (payload: unknown, status: number): string => { return `请求失败: ${status}`; }; -import type { ApiErrorResponse } from './types'; +import type { ApiErrorResponse } from '../api-contract'; diff --git a/frontend/shared/http/contract.test.ts b/frontend/shared/http/contract.test.ts new file mode 100644 index 0000000..11e4360 --- /dev/null +++ b/frontend/shared/http/contract.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, test } from 'vitest'; +import { collectionFrom, objectFrom } from './contract'; + +/** ContractRow 是集合归一测试使用的最小具名行模型。 */ +interface ContractRow { + /** id 是测试集合项的稳定标识。 */ + id: number; +} + +describe('HTTP transport contract normalizers', () => { + test('集合归一器接受数组、null、命名包裹和双层 data 包裹', /* 回调验证集合响应的兼容归一规则。 */ () => { + // rows 是不同发布版本可能返回的集合响应形状。 + const rows = [{ + // id 是测试集合项的稳定标识。 + id: 1, + }]; + expect(collectionFrom(rows)).toEqual(rows); + expect(collectionFrom(null)).toEqual([]); + expect(collectionFrom({ items: rows }, ['items'])).toEqual(rows); + expect(collectionFrom({ data: { results: rows } }, ['results'])).toEqual(rows); + }); + + test('对象归一器保留直接对象并展开 data/result 历史包裹', /* 回调验证对象响应的兼容归一规则。 */ () => { + // direct 是当前版本直接返回的对象契约。 + const direct = { /** enabled 表示测试对象的启用状态。 */ enabled: true }; + expect(objectFrom(direct)).toEqual(direct); + expect(objectFrom({ data: direct })).toEqual(direct); + expect(objectFrom({ result: direct })).toEqual(direct); + expect(objectFrom(null)).toBeUndefined(); + }); +}); diff --git a/frontend/shared/http/contract.ts b/frontend/shared/http/contract.ts new file mode 100644 index 0000000..1b1b7cb --- /dev/null +++ b/frontend/shared/http/contract.ts @@ -0,0 +1,60 @@ +/** HTTP transport 响应的兼容归一工具;这里只处理 JSON 形状,不承载任何业务规则。 */ + +/** JSON 对象的最小运行时视图,避免业务 API 适配器依赖 any。 */ +export type JsonObject = Record; + +/** 判断未知值是否可以作为 JSON 对象读取。 */ +export const isJsonObject = (value: unknown): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/** + * 从数组、空值或历史包裹对象中提取集合。 + * 空值、缺失字段和非数组字段统一返回新建空数组,避免页面把 null 当作可迭代值。 + */ +export const collectionFrom = (payload: unknown, keys: readonly string[] = ['data', 'items', 'results']): T[] => { + // currentPayload 保存当前待检查的响应层,允许兼容 data 嵌套对象但不跨越无关字段。 + let currentPayload: unknown = payload; + // depth 防止异常响应对象造成无限递归;服务端契约最多允许两层历史包裹。 + let depth = 0; + for (; depth < 2; depth += 1) { + if (Array.isArray(currentPayload)) return currentPayload as T[]; + if (!isJsonObject(currentPayload)) return []; + // key 表示当前兼容契约允许的集合字段名。 + for (const key /* key 是当前允许读取的集合字段名。 */ of keys) { + // candidate 表示候选集合字段;null 视为服务端空集合。 + const candidate = currentPayload[key]; + if (Array.isArray(candidate)) return candidate as T[]; + if (candidate === null) return []; + } + // nestedPayload 兼容 { data: { items: [...] } } 这一历史包裹形状。 + const nestedPayload = currentPayload.data; + if (isJsonObject(nestedPayload)) { + currentPayload = nestedPayload; + continue; + } + return []; + } + return []; +}; + +/** + * 从直接对象或 data/result 包裹对象中提取对象。 + * 非对象和 null 都返回 undefined,由 feature 适配器决定默认值。 + */ +export const objectFrom = (payload: unknown, keys: readonly string[] = ['data', 'result']): T | undefined => { + // currentPayload 保存当前待检查的响应层,兼容最多两层历史包裹。 + let currentPayload: unknown = payload; + // depth 限制兼容层深度,防止错误响应触发无限遍历。 + let depth = 0; + for (; depth < 2; depth += 1) { + if (!isJsonObject(currentPayload)) return undefined; + // key 表示当前兼容契约允许的对象字段名。 + for (const key /* key 是当前允许读取的对象字段名。 */ of keys) { + // candidate 表示候选对象字段;null 表示没有可用对象。 + const candidate = currentPayload[key]; + if (isJsonObject(candidate)) return candidate as T; + } + return currentPayload as T; + } + return undefined; +}; diff --git a/frontend/components/Sidebar.tsx b/frontend/shared/ui/Sidebar.tsx similarity index 85% rename from frontend/components/Sidebar.tsx rename to frontend/shared/ui/Sidebar.tsx index 11f4a10..ed573ec 100644 --- a/frontend/components/Sidebar.tsx +++ b/frontend/shared/ui/Sidebar.tsx @@ -1,11 +1,17 @@ -import React, { useEffect, useState } from 'react'; +import React from 'react'; import { Bell, Box, ChevronLeft, ChevronRight, CreditCard, LayoutDashboard, GitCommitHorizontal, LogOut, MessageCircleMore, Settings, ShoppingBag, Users, Zap, } from 'lucide-react'; import { YdisksBrandIcon } from './YdisksLogo'; -import { getHealth } from '../app/features/system/api'; -import type { BuildInfo } from '../app/features/system/types'; + +// SidebarBuildInfo 描述应用壳传递给侧边栏的公开构建版本信息。 +export interface SidebarBuildInfo { + // version 是当前服务构建版本,只用于界面展示。 + version: string; + // commit 是当前服务构建提交标识,只用于界面展示。 + commit: string; +} // SidebarProps 描述侧边栏所需的导航和会话回调。 interface SidebarProps { @@ -15,29 +21,13 @@ interface SidebarProps { /** onToggleCollapsed 表示切换侧边栏折叠状态的回调。 */ onToggleCollapsed: () => void; /** onNavigate 表示切换主导航页面的回调。 */ onNavigate: (tab: string) => void; /** onLogout 表示注销当前会话的回调。 */ onLogout: () => void; + /** buildInfo 是由应用壳加载并传入的公开构建版本信息。 */ buildInfo: SidebarBuildInfo; } // Sidebar 渲染侧边栏导航组件。 const Sidebar: React.FC = ({ - activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout, + activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout, buildInfo, }) => { - // [buildInfo, 解构得到当前 Hook 返回的状态和操作函数。 - const [buildInfo, setBuildInfo] = useState({ version: 'dev', commit: 'unknown' }); - - useEffect(/* 当前回调同步 React 副作用和资源生命周期。 */ () => { - // controller 控制健康检查请求的取消。 - const controller = new AbortController(); - getHealth({ signal: controller.signal }) - .then(/* 当前回调处理异步操作结果。 */ data => setBuildInfo({ - version: String(data.version || 'dev'), - commit: String(data.commit || 'unknown'), - })) - .catch(/* 当前回调处理异步操作结果。 */ error => { - if (error instanceof DOMException && error.name === 'AbortError') return; - }); - return /* 当前回调处理用户交互或异步状态变化。 */ () => controller.abort(); - }, []); - // menuItems 侧边栏菜单项。 const menuItems = [ { id: 'dashboard', icon: LayoutDashboard, label: '仪表盘' }, diff --git a/frontend/components/YdisksLogo.test.tsx b/frontend/shared/ui/YdisksLogo.test.tsx similarity index 100% rename from frontend/components/YdisksLogo.test.tsx rename to frontend/shared/ui/YdisksLogo.test.tsx diff --git a/frontend/components/YdisksLogo.tsx b/frontend/shared/ui/YdisksLogo.tsx similarity index 100% rename from frontend/components/YdisksLogo.tsx rename to frontend/shared/ui/YdisksLogo.tsx diff --git a/internal/adapter/account_cookie_writer.go b/internal/adapter/account_cookie_writer.go new file mode 100644 index 0000000..d641bfa --- /dev/null +++ b/internal/adapter/account_cookie_writer.go @@ -0,0 +1,91 @@ +package adapter + +import ( + "context" + "errors" + "log/slog" + + accountapp "xianyu-go/internal/application/account" +) + +// AccountCookieWriter 将手动登录产生的明文 Cookie 限制在账号基础设施适配器内。 +// 该类型同时实现新增和更新两个应用端口;Cookie 只在当前请求创建的实例中短暂存在。 +type AccountCookieWriter struct { + // repository 提供凭证锁、归属校验、加密写入和旧 Token 清理能力。 + repository accountapp.CredentialRepository + // platformCredentials 提供更新既有账号时所需的平台窄凭证视图。 + platformCredentials accountapp.PlatformCredentialViewPort + // cookies 保存当前请求的明文 Cookie;禁止写入日志、HTTP 响应或长期状态。 + cookies string + // logger 记录旧 Token 清理失败;日志中不得包含 Cookie 内容。 + logger *slog.Logger +} + +// NewAccountCookieWriter 构造一次请求范围的 Cookie 写入适配器。 +// 调用方应在使用后丢弃返回实例,避免明文 Cookie 跨请求存活。 +func NewAccountCookieWriter( + repository accountapp.CredentialRepository, + platformCredentials accountapp.PlatformCredentialViewPort, + cookies string, + logger *slog.Logger, +) *AccountCookieWriter { + return &AccountCookieWriter{ + repository: repository, platformCredentials: platformCredentials, cookies: cookies, logger: logger, + } +} + +// CreateOwnedCookie 在凭证锁内原子校验归属、写入 Cookie 并清理旧连接 Token。 +// 锁只覆盖数据库凭证变更,不跨越外部网络或运行时操作;清理失败不会回滚主写入。 +func (w *AccountCookieWriter) CreateOwnedCookie(ctx context.Context, accountID string, userID int64) error { + if w == nil || w.repository == nil { + return errors.New("账号登录凭证 repository 未初始化") + } + // unlock 保护同一账号的凭证写入与旧连接 Token 清理,外部网络和运行时操作在锁外执行。 + unlock := w.repository.LockCredentials(accountID) + defer unlock() + // writeErr 保存凭证写入错误;归属校验失败时直接返回且不清理 Token。 + writeErr := w.repository.CreateCookieOwned(ctx, accountID, w.cookies, userID) + if writeErr != nil { + return writeErr + } + // clearErr 保存旧连接 Token 清理错误;清理失败不回滚已经成功写入的 Cookie。 + clearErr := w.repository.ClearTokens(ctx, accountID) + if clearErr != nil && w.logger != nil { + w.logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr) + } + return nil +} + +// UpdateOwnedCookie 在账号凭证短锁内完成归属复核、版本检查、Cookie 写入和旧 Token 清理。 +// 资料刷新等慢速后续动作由应用服务在释放锁后触发。 +func (w *AccountCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID string, userID, expectedRevision int64) error { + if w == nil || w.repository == nil || w.platformCredentials == nil { + return errors.New("账号登录凭证端口未初始化") + } + // unlock 只保护凭证快照读取、数据库写入和旧 Token 清理,不跨越网络或运行时 I/O。 + unlock := w.repository.LockCredentials(accountID) + defer unlock() + // detail 保存锁内读取的平台凭证窄视图;该视图不会把登录密码传入应用层。 + detail, loadErr := w.platformCredentials.LoadPlatformDetail(ctx, accountID) + if loadErr != nil { + return loadErr + } + if detail == nil || detail.UserID != userID { + return accountapp.ErrForbidden + } + if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision { + return accountapp.ErrCredentialConflict + } + // updateErr 保存归属已确认后的 Cookie 持久化结果;适配器负责清除旧完整快照。 + if updateErr := w.repository.UpdateFlatCookieOwned(ctx, detail, w.cookies); updateErr != nil { + return updateErr + } + // clearErr 保存旧连接 Token 清理错误;凭证已成功写入时清理失败仅记录并继续。 + if clearErr := w.repository.ClearTokens(ctx, accountID); clearErr != nil && w.logger != nil { + w.logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr) + } + return nil +} + +var _ accountapp.CookieWriter = (*AccountCookieWriter)(nil) +var _ accountapp.CookieUpdater = (*AccountCookieWriter)(nil) diff --git a/internal/adapter/account_cookie_writer_test.go b/internal/adapter/account_cookie_writer_test.go new file mode 100644 index 0000000..aa773fa --- /dev/null +++ b/internal/adapter/account_cookie_writer_test.go @@ -0,0 +1,179 @@ +package adapter + +import ( + "context" + "errors" + "io" + "log/slog" + "testing" + + accountapp "xianyu-go/internal/application/account" +) + +// TestAccountCookieWriterRejectsMissingPorts 验证请求范围凭证 writer 缺少仓储时不会伪装成功。 +func TestAccountCookieWriterRejectsMissingPorts(t *testing.T) { + // writer 模拟尚未完成基础设施装配但已经携带明文 Cookie 的请求实例。 + writer := NewAccountCookieWriter(nil, nil, "sid=short-lived", nil) + // createErr 保存新增凭证写入的装配错误。 + createErr := writer.CreateOwnedCookie(context.Background(), "cid", 1) + if createErr == nil { + t.Fatal("缺少凭证仓储时新增 Cookie 不应伪装成功") + } + // updateErr 保存既有凭证更新的装配错误。 + updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", 1, 0) + if updateErr == nil { + t.Fatal("缺少凭证端口时更新 Cookie 不应伪装成功") + } +} + +// TestAccountCookieWriterUpdatesOwnedCookie 验证更新成功、跨用户拒绝和版本冲突均发生在适配器内。 +func TestAccountCookieWriterUpdatesOwnedCookie(t *testing.T) { + // store、cleanup 保存包含测试账号凭证的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的账号凭证仓储。 + repository := NewAccountLoginRepository(store) + // platformCredentials 是只暴露平台窄视图的读取服务。 + platformCredentials, serviceErr := accountapp.NewPlatformCredentialService(repository) + if serviceErr != nil { + t.Fatalf("构造平台凭证服务失败: %v", serviceErr) + } + // detail、detailErr 保存更新前的凭证版本与归属信息。 + detail, detailErr := repository.LoadPlatformDetail(context.Background(), "cid") + if detailErr != nil { + t.Fatalf("读取测试凭证失败: %v", detailErr) + } + // writer 是只在本次更新请求中持有明文 Cookie 的适配器。 + writer := NewAccountCookieWriter(repository, platformCredentials, "sid=updated", nil) + // updateErr 保存归属正确且版本匹配时的更新结果。 + updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", detail.UserID, detail.LastRefreshAt) + if updateErr != nil { + t.Fatalf("更新账号 Cookie 失败: %v", updateErr) + } + // updated、updatedErr 保存数据库中更新后的平台凭证视图。 + updated, updatedErr := repository.LoadPlatformDetail(context.Background(), "cid") + if updatedErr != nil || updated.Value != "sid=updated" { + t.Fatalf("更新后的 Cookie 不符合预期: detail=%+v err=%v", updated, updatedErr) + } + // forbiddenErr 保存跨用户更新的稳定应用错误。 + forbiddenErr := writer.UpdateOwnedCookie(context.Background(), "cid", detail.UserID+1, 0) + if !errors.Is(forbiddenErr, accountapp.ErrForbidden) { + t.Fatalf("跨用户更新应拒绝,got %v", forbiddenErr) + } + // conflictErr 保存客户端版本落后时的并发冲突错误。 + conflictErr := writer.UpdateOwnedCookie(context.Background(), "cid", detail.UserID, detail.LastRefreshAt-1) + if !errors.Is(conflictErr, accountapp.ErrCredentialConflict) { + t.Fatalf("过期版本应返回冲突,got %v", conflictErr) + } +} + +// TestAccountCookieWriterHonorsContext 验证平台视图查询收到取消信号后不会继续写入 Cookie。 +func TestAccountCookieWriterHonorsContext(t *testing.T) { + // store、cleanup 保存用于取消路径验证的 SQLite 存储及清理函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // repository 是绑定测试数据库的账号凭证仓储。 + repository := NewAccountLoginRepository(store) + // platformCredentials 是更新流程使用的窄凭证视图服务。 + platformCredentials, serviceErr := accountapp.NewPlatformCredentialService(repository) + if serviceErr != nil { + t.Fatalf("构造平台凭证服务失败: %v", serviceErr) + } + // writer 是待接收取消上下文的凭证更新适配器。 + writer := NewAccountCookieWriter(repository, platformCredentials, "sid=cancelled", nil) + // ctx、cancel 保存已取消的请求上下文及其取消函数。 + ctx, cancel := context.WithCancel(context.Background()) + cancel() + // updateErr 保存取消后的数据库查询结果。 + updateErr := writer.UpdateOwnedCookie(ctx, "cid", 1, 0) + if updateErr == nil { + t.Fatal("取消上下文不应继续完成凭证更新") + } +} + +// cookieWriterRepositoryFake 是凭证 writer 测试使用的最小仓储替身,可注入清理失败和写入失败。 +type cookieWriterRepositoryFake struct { + // detail 是平台窄视图查询返回的账号归属与版本。 + detail *accountapp.CredentialDetail + // createErr 是新增 Cookie 持久化时注入的错误。 + createErr error + // updateErr 是更新 Cookie 持久化时注入的错误。 + updateErr error + // clearErr 是旧 Token 清理时注入的错误。 + clearErr error + // clearCalls 记录旧 Token 清理调用次数,用于确认主写入后仍执行补偿清理。 + clearCalls int + // receivedCookies 保存适配器传入的明文 Cookie,仅用于当前测试断言,不输出到失败日志。 + receivedCookies string +} + +// LockCredentials 返回测试用的无阻塞解锁函数。 +func (f *cookieWriterRepositoryFake) LockCredentials(string) func() { + return func() {} +} + +// CreateCookieOwned 记录新增 Cookie 并返回注入的数据库结果。 +func (f *cookieWriterRepositoryFake) CreateCookieOwned(_ context.Context, _ string, cookies string, _ int64) error { + f.receivedCookies = cookies + return f.createErr +} + +// LoadPlatformDetail 返回测试用的平台窄凭证视图。 +func (f *cookieWriterRepositoryFake) LoadPlatformDetail(ctx context.Context, _ string) (*accountapp.CredentialDetail, error) { + if ctx.Err() != nil { + return nil, ctx.Err() + } + return f.detail, nil +} + +// UpdateFlatCookieOwned 记录更新 Cookie 并返回注入的数据库结果。 +func (f *cookieWriterRepositoryFake) UpdateFlatCookieOwned(_ context.Context, _ *accountapp.CredentialDetail, cookies string) error { + f.receivedCookies = cookies + return f.updateErr +} + +// UpdateRenewalCookie 满足凭证仓储接口的会话写回方法;本测试不使用该路径。 +func (f *cookieWriterRepositoryFake) UpdateRenewalCookie(context.Context, string, string, string, int64) error { + return nil +} + +// ClearTokens 记录清理次数并返回注入的清理结果。 +func (f *cookieWriterRepositoryFake) ClearTokens(context.Context, string) error { + f.clearCalls++ + return f.clearErr +} + +// GetStatus 满足凭证仓储接口的账号状态查询方法;本测试不使用该路径。 +func (f *cookieWriterRepositoryFake) GetStatus(context.Context, string) bool { + return true +} + +// UpdateProfile 满足凭证仓储接口的资料更新方法;本测试不使用该路径。 +func (f *cookieWriterRepositoryFake) UpdateProfile(context.Context, string, string, string) error { + return nil +} + +// TestAccountCookieWriterKeepsPrimaryWriteWhenTokenCleanupFails 验证旧 Token 清理失败不回滚已成功的 Cookie 写入。 +func TestAccountCookieWriterKeepsPrimaryWriteWhenTokenCleanupFails(t *testing.T) { + // cleanupErr 是模拟旧连接 Token 已不可清理的基础设施错误。 + cleanupErr := errors.New("token cleanup unavailable") + // repository 是可注入清理失败的凭证仓储替身。 + repository := &cookieWriterRepositoryFake{ + detail: &accountapp.CredentialDetail{ID: "cid", UserID: 1, LastRefreshAt: 7}, + clearErr: cleanupErr, + } + // logger 将脱敏清理告警写入丢弃流,避免测试输出任何凭证内容。 + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + // writer 是携带本次请求 Cookie 的适配器实例。 + writer := NewAccountCookieWriter(repository, repository, "sid=new", logger) + // createErr 保存新增 Cookie 主写入结果。 + createErr := writer.CreateOwnedCookie(context.Background(), "cid", 1) + if createErr != nil || repository.receivedCookies != "sid=new" || repository.clearCalls != 1 { + t.Fatalf("清理失败不应回滚新增写入: err=%v cookies=%q clears=%d", createErr, repository.receivedCookies, repository.clearCalls) + } + // updateErr 保存既有 Cookie 主写入结果。 + updateErr := writer.UpdateOwnedCookie(context.Background(), "cid", 1, 7) + if updateErr != nil || repository.receivedCookies != "sid=new" || repository.clearCalls != 2 { + t.Fatalf("清理失败不应回滚更新写入: err=%v cookies=%q clears=%d", updateErr, repository.receivedCookies, repository.clearCalls) + } +} diff --git a/internal/adapter/account_dependencies.go b/internal/adapter/account_dependencies.go new file mode 100644 index 0000000..0bb3fe0 --- /dev/null +++ b/internal/adapter/account_dependencies.go @@ -0,0 +1,71 @@ +package adapter + +import ( + "errors" + + accountapp "xianyu-go/internal/application/account" + "xianyu-go/internal/db" +) + +// AccountDependencies 封装账号登录、认证和扫码用例所需的窄适配器构造能力。 +// 它只在 adapter 内部持有 Store,避免 Server 通过通用设施容器隐式获取账号仓储。 +type AccountDependencies struct { + // store 是账号适配器共享的数据库入口,不向 Server 或应用层暴露。 + store *db.Store +} + +// NewAccountDependencies 构造账号专用依赖,并在缺少数据库入口时立即返回错误。 +func NewAccountDependencies(store *db.Store) (*AccountDependencies, error) { + if store == nil { + return nil, errors.New("账号依赖 Store 不能为空") + } + return &AccountDependencies{store: store}, nil +} + +// NewAccountLoginRepository 创建账号凭证和资料仓储。 +func (d *AccountDependencies) NewAccountLoginRepository() *AccountLoginRepository { + if d == nil { + return nil + } + return NewAccountLoginRepository(d.store) +} + +// NewAccountSettingsRepository 创建账号设置仓储。 +func (d *AccountDependencies) NewAccountSettingsRepository() *AccountSettingsRepository { + if d == nil { + return nil + } + return NewAccountSettingsRepository(d.store) +} + +// NewAccountSummaryRepository 创建不读取敏感凭证的账号摘要仓储。 +func (d *AccountDependencies) NewAccountSummaryRepository() *AccountSummaryRepository { + if d == nil { + return nil + } + return NewAccountSummaryRepository(d.store) +} + +// NewQRLoginRepository 创建扫码登录成功写入所需的凭证端口。 +func (d *AccountDependencies) NewQRLoginRepository() accountapp.QRLoginRepository { + if d == nil { + return nil + } + return NewQRLoginRepository(d.store) +} + +// NewAuthenticationRepository 创建用户认证仓储。 +func (d *AccountDependencies) NewAuthenticationRepository() *AuthenticationRepository { + if d == nil { + return nil + } + return NewAuthenticationRepository(d.store) +} + +// NewAccountLoginAuditRepository 创建账号登录审计仓储。 +func (d *AccountDependencies) NewAccountLoginAuditRepository() *AccountLoginAuditRepository { + if d == nil { + return nil + } + return NewAccountLoginAuditRepository(d.store) +} diff --git a/internal/adapter/account_dependencies_test.go b/internal/adapter/account_dependencies_test.go new file mode 100644 index 0000000..2f094f0 --- /dev/null +++ b/internal/adapter/account_dependencies_test.go @@ -0,0 +1,39 @@ +package adapter + +import ( + "testing" + + "xianyu-go/internal/db" +) + +// TestNewAccountDependenciesRejectsNilStore 确保账号专用依赖不会在缺少数据库入口时构造成功。 +func TestNewAccountDependenciesRejectsNilStore(t *testing.T) { + // dependencies、err 分别保存构造结果和缺少 Store 时的错误。 + dependencies, err := NewAccountDependencies(nil) + if dependencies != nil { + t.Fatal("缺少 Store 时不应返回账号依赖") + } + if err == nil { + t.Fatal("缺少 Store 时应返回构造错误") + } +} + +// TestNewAccountDependenciesCreatesTypedFactory 确保有效 Store 可创建全部账号窄适配器。 +func TestNewAccountDependenciesCreatesTypedFactory(t *testing.T) { + // store 仅用于验证构造类型,不执行数据库读写。 + store := db.NewStore(nil, db.DialectSQLite) + // dependencies、err 分别保存账号工厂和构造错误。 + dependencies, err := NewAccountDependencies(store) + if err != nil { + t.Fatalf("NewAccountDependencies: %v", err) + } + if dependencies == nil { + t.Fatal("有效 Store 应返回账号依赖") + } + if dependencies.NewAccountLoginRepository() == nil || dependencies.NewAccountSettingsRepository() == nil || dependencies.NewAccountSummaryRepository() == nil { + t.Fatal("账号工厂应返回账号仓储") + } + if dependencies.NewQRLoginRepository() == nil || dependencies.NewAuthenticationRepository() == nil || dependencies.NewAccountLoginAuditRepository() == nil { + t.Fatal("账号工厂应返回认证与扫码端口") + } +} diff --git a/internal/adapter/account_login_lifecycle.go b/internal/adapter/account_login_lifecycle.go new file mode 100644 index 0000000..eb1f538 --- /dev/null +++ b/internal/adapter/account_login_lifecycle.go @@ -0,0 +1,72 @@ +package adapter + +import ( + "context" + "log/slog" + + accountapp "xianyu-go/internal/application/account" +) + +// AccountLoginLifecycle 将登录审计、资料刷新、账号重启和扫码清理告警收口到适配器。 +// 它只组合应用层端口与日志能力,不持有 Server 或明文凭证。 +type AccountLoginLifecycle struct { + // audit 负责记录登录方式、启用账号和写入审计日志。 + audit *accountapp.LoginAuditService + // success 负责登录成功后的资料刷新与启用账号运行时重启。 + success *accountapp.LoginSuccessService + // logger 记录不影响主流程的审计或清理告警,日志中不得包含 Cookie 内容。 + logger *slog.Logger +} + +// NewAccountLoginLifecycle 构造手动登录和扫码登录共用的生命周期适配器。 +func NewAccountLoginLifecycle(audit *accountapp.LoginAuditService, success *accountapp.LoginSuccessService, logger *slog.Logger) *AccountLoginLifecycle { + return &AccountLoginLifecycle{audit: audit, success: success, logger: logger} +} + +// AfterSuccessfulLogin 在凭证写入并释放凭证锁后记录审计并执行登录后续编排。 +func (l *AccountLoginLifecycle) AfterSuccessfulLogin(ctx context.Context, userID int64, accountID, method string) { + if l == nil { + return + } + // l.recordAudit 记录审计失败但不阻断已完成的凭证登录结果。 + l.recordAudit(ctx, userID, accountID, method, "账号登录成功") + if l.success != nil { + l.success.AfterSuccessfulLogin(ctx, userID, accountID) + } +} + +// AfterSuccessfulQRLogin 在扫码凭证写入并释放凭证锁后记录扫码审计并执行后续编排。 +func (l *AccountLoginLifecycle) AfterSuccessfulQRLogin(ctx context.Context, userID int64, accountID string) { + if l == nil { + return + } + // l.recordAudit 记录扫码登录审计失败但不回滚已经写入的凭证。 + l.recordAudit(ctx, userID, accountID, accountapp.LoginMethodQRScan, "扫码登录成功") + if l.success != nil { + l.success.AfterSuccessfulLogin(ctx, userID, accountID) + } +} + +// ReportQRLoginCleanupFailure 记录扫码成功后旧 Token 清理失败,不泄露 Cookie 内容。 +func (l *AccountLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, accountID string, err error) { + if l != nil && l.logger != nil { + l.logger.Warn("扫码登录后清理旧连接凭证失败", "cookie_id", accountID, "err", err) + } +} + +// recordAudit 将登录审计错误降级为脱敏告警,保持凭证写入主流程的既有成功语义。 +func (l *AccountLoginLifecycle) recordAudit(ctx context.Context, userID int64, accountID, method, message string) { + if l.audit == nil { + return + } + // auditErr 保存审计应用服务返回的基础设施错误;错误日志不包含明文凭证。 + auditErr := l.audit.RecordSuccessfulLogin(ctx, accountapp.SuccessfulLoginInput{ + AccountID: accountID, UserID: userID, Method: method, Message: message, + }) + if auditErr != nil && l.logger != nil { + l.logger.Warn("记录账号登录审计失败", "cookie_id", accountID, "method", method, "err", auditErr) + } +} + +var _ accountapp.LoginLifecyclePort = (*AccountLoginLifecycle)(nil) +var _ accountapp.QRLoginLifecycle = (*AccountLoginLifecycle)(nil) diff --git a/internal/adapter/account_login_lifecycle_test.go b/internal/adapter/account_login_lifecycle_test.go new file mode 100644 index 0000000..a8b2de0 --- /dev/null +++ b/internal/adapter/account_login_lifecycle_test.go @@ -0,0 +1,56 @@ +package adapter + +import ( + "context" + "testing" + + accountapp "xianyu-go/internal/application/account" +) + +// lifecycleAuditRepositoryFake 是生命周期适配器测试使用的登录审计仓储替身。 +type lifecycleAuditRepositoryFake struct { + // methods 记录适配器提交的归一化登录方式。 + methods []string +} + +// MarkLogin 记录最近成功登录方式。 +func (f *lifecycleAuditRepositoryFake) MarkLogin(_ context.Context, _ string, method string, _ int64) error { + f.methods = append(f.methods, method) + return nil +} + +// SetStatusWithReason 满足审计仓储接口;生命周期测试不关心状态写入细节。 +func (f *lifecycleAuditRepositoryFake) SetStatusWithReason(context.Context, string, bool, string) error { + return nil +} + +// AddLoginLog 满足审计仓储接口;登录方式已由 MarkLogin 记录。 +func (f *lifecycleAuditRepositoryFake) AddLoginLog(context.Context, accountapp.LoginAuditLog) error { + return nil +} + +// TestAccountLoginLifecycleRoutesManualAndQRSuccess 验证手动登录与扫码登录共用审计和后续编排端口。 +func TestAccountLoginLifecycleRoutesManualAndQRSuccess(t *testing.T) { + // repository 保存测试登录审计调用记录。 + repository := &lifecycleAuditRepositoryFake{} + // audit 保存使用测试仓储的应用审计服务。 + audit := accountapp.NewLoginAuditService(repository) + // lifecycle 是不持有 Server 的登录生命周期适配器。 + lifecycle := NewAccountLoginLifecycle(audit, nil, nil) + // manualErr 保存手动登录生命周期调用结果;该方法本身不返回审计错误。 + lifecycle.AfterSuccessfulLogin(context.Background(), 1, "manual-account", accountapp.LoginMethodManual) + // lifecycle.AfterSuccessfulQRLogin 记录扫码登录方式并保持同一审计端口。 + lifecycle.AfterSuccessfulQRLogin(context.Background(), 1, "qr-account") + if len(repository.methods) != 2 || repository.methods[0] != accountapp.LoginMethodManual || repository.methods[1] != accountapp.LoginMethodQRScan { + t.Fatalf("登录生命周期未正确路由审计方式: %+v", repository.methods) + } +} + +// TestAccountLoginLifecycleAllowsMissingOptionalPorts 验证缺少可选应用服务和日志端口时仍安全返回。 +func TestAccountLoginLifecycleAllowsMissingOptionalPorts(t *testing.T) { + // lifecycle 是仅用于验证 nil 安全性的零依赖适配器。 + lifecycle := NewAccountLoginLifecycle(nil, nil, nil) + lifecycle.AfterSuccessfulLogin(context.Background(), 1, "account", accountapp.LoginMethodManual) + lifecycle.AfterSuccessfulQRLogin(context.Background(), 1, "account") + lifecycle.ReportQRLoginCleanupFailure(context.Background(), "account", nil) +} diff --git a/internal/adapter/account_runtime.go b/internal/adapter/account_runtime.go new file mode 100644 index 0000000..44e36b2 --- /dev/null +++ b/internal/adapter/account_runtime.go @@ -0,0 +1,109 @@ +package adapter + +import ( + "context" + + accountmanager "xianyu-go/internal/account" + accountapp "xianyu-go/internal/application/account" +) + +// AccountRuntimePort 将账号 Manager 的 engine 状态和生命周期能力映射为应用层运行时端口。 +type AccountRuntimePort struct { + // manager 持有账号运行实例及其并发关闭语义;Server 不直接读取其 engine 状态。 + manager *accountmanager.Manager +} + +// NewAccountRuntimePort 创建账号运行时适配器;nil Manager 表示当前进程未启用账号运行实例。 +func NewAccountRuntimePort(manager *accountmanager.Manager) accountapp.RuntimePort { + if manager == nil { + return nil + } + return AccountRuntimePort{manager: manager} +} + +// AccountRunningLookup 创建订单等应用适配器使用的账号在线查询函数。 +// Manager 的具体运行实例和锁语义只在 adapter 内部读取,调用方只获得布尔结果。 +func AccountRunningLookup(manager *accountmanager.Manager) func(string) bool { + return func(accountID string) bool { + if manager == nil { + return false + } + // _, running 保存账号运行实例是否存在。 + _, running := manager.GetInstance(accountID) + return running + } +} + +// UpdateCookie 将凭证同步到已运行的账号实例;不存在实例时保持幂等成功。 +func (p AccountRuntimePort) UpdateCookie(ctx context.Context, accountID, value string) error { + // contextErr 保存同步前检查到的取消错误。 + if contextErr := contextError(ctx); contextErr != nil { + return contextErr + } + if p.manager == nil { + return nil + } + // sender、ok 保存账号运行实例发送句柄及其存在性。 + sender, ok := p.manager.GetInstance(accountID) + if !ok || sender == nil { + return nil + } + sender.UpdateCookie(value) + return nil +} + +// RuntimeStatuses 返回应用层状态快照,避免上层依赖 engine.RuntimeStatus。 +func (p AccountRuntimePort) RuntimeStatuses(ctx context.Context) (map[string]accountapp.RuntimeStatus, error) { + // contextErr 保存状态读取前检查到的取消错误。 + if contextErr := contextError(ctx); contextErr != nil { + return nil, contextErr + } + // result 保存转换为应用 DTO 后的账号状态快照。 + result := make(map[string]accountapp.RuntimeStatus) + if p.manager == nil { + return result, nil + } + // accountID、status 表示当前遍历的账号标识及其 engine 状态快照。 + for accountID, status := range p.manager.RuntimeStatuses() { + result[accountID] = accountapp.RuntimeStatus{ + State: status.State, Message: status.Message, Connected: status.Connected, Failures: status.Failures, + UpdatedAt: status.UpdatedAt, TokenAcquiredAt: status.TokenAcquiredAt, TokenExpiresAt: status.TokenExpiresAt, + TokenRefreshAt: status.TokenRefreshAt, TokenRemainingSeconds: status.TokenRemainingSeconds, + TokenRefreshStatus: status.TokenRefreshStatus, + } + } + return result, nil +} + +// Restart 重启账号运行实例;取消和数据库读取错误沿 Manager 原语向上返回。 +func (p AccountRuntimePort) Restart(ctx context.Context, accountID string) error { + // contextErr 保存重启前检查到的取消错误。 + if contextErr := contextError(ctx); contextErr != nil { + return contextErr + } + if p.manager == nil { + return nil + } + return p.manager.Restart(ctx, accountID) +} + +// RecoverExpiredCredential 将平台会话失效恢复请求转发给账号 Manager。 +func (p AccountRuntimePort) RecoverExpiredCredential(ctx context.Context, accountID string) bool { + if contextError(ctx) != nil || p.manager == nil { + return false + } + return p.manager.RecoverExpiredCredential(ctx, accountID) +} + +// contextError 检查运行时适配器执行前的取消状态,避免取消请求仍触发实例副作用。 +func contextError(ctx context.Context) error { + if ctx == nil { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + default: + return nil + } +} diff --git a/internal/adapter/account_runtime_test.go b/internal/adapter/account_runtime_test.go new file mode 100644 index 0000000..f3d17a6 --- /dev/null +++ b/internal/adapter/account_runtime_test.go @@ -0,0 +1,12 @@ +package adapter + +import "testing" + +// TestAccountRunningLookupRejectsMissingManager 验证账号在线查询适配器在缺少管理器时安全返回离线。 +func TestAccountRunningLookupRejectsMissingManager(t *testing.T) { + // lookup 保存未装配管理器时的在线查询函数。 + lookup := AccountRunningLookup(nil) + if lookup("account") { + t.Fatal("missing manager must report account offline") + } +} diff --git a/internal/adapter/adapter.go b/internal/adapter/adapter.go index feebe87..710fafe 100644 --- a/internal/adapter/adapter.go +++ b/internal/adapter/adapter.go @@ -14,6 +14,8 @@ import ( "sync" "time" + accountapp "xianyu-go/internal/application/account" + automationapp "xianyu-go/internal/application/automation" "xianyu-go/internal/automation" "xianyu-go/internal/browser" "xianyu-go/internal/chat" @@ -70,17 +72,19 @@ type Adapter struct { logger *slog.Logger automation *automation.Center notifier notifyNotifier - renewSvc xrenew.Service - cooldown *renewal.CooldownManager - captchaReq tokenCaptchaRequester - orderMTop orderDetailClient - chat *chat.Service + // credentialWake 负责凭证写回后的自动化任务唤醒;Adapter 只依赖应用端口,不直接决定任务状态。 + credentialWake accountapp.CredentialWakePort + renewSvc xrenew.Service + cooldown *renewal.CooldownManager + captchaReq tokenCaptchaRequester + orderMTop orderDetailClient + chat *chat.Service orderFetchMu sync.Mutex lastOrderFetch time.Time - passwordMu sync.Mutex - passwordProcessing map[string]struct{} + // passwordCoordinator 按账号协调协议凭证恢复,避免重复外部续期并允许不同账号并行执行。 + passwordCoordinator *accountapp.CredentialRefreshCoordinator } // notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包 @@ -103,16 +107,32 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter { logger = slog.Default() } return &Adapter{ - store: store, - browser: browserManagerOrNil(bm), - logger: logger, - cooldown: renewal.GlobalCooldown, - captchaReq: mtop.NewClient(), - orderMTop: mtop.NewClient(), - passwordProcessing: make(map[string]struct{}), + store: store, + browser: browserManagerOrNil(bm), + logger: logger, + credentialWake: newCredentialWakeService(store), + cooldown: renewal.GlobalCooldown, + captchaReq: mtop.NewClient(), + orderMTop: mtop.NewClient(), + passwordCoordinator: accountapp.NewCredentialRefreshCoordinator(), } } +// newCredentialWakeService 构造凭证唤醒应用服务;数据库仓储仅在适配器边界内创建并隐藏。 +func newCredentialWakeService(store *db.Store) accountapp.CredentialWakePort { + if store == nil { + return nil + } + // repository 保存凭证唤醒所需的窄数据库适配器。 + repository := NewAutomationCredentialWakeRepository(store) + // service、err 保存凭证唤醒应用服务及其装配错误。 + service, err := automationapp.NewCredentialWakeService(repository) + if err != nil { + return nil + } + return service +} + // browserManagerOrNil 把 *browser.Manager 转为接口;nil 时返回 nil 接口。 func browserManagerOrNil(bm *browser.Manager) browserManager { if bm == nil { @@ -121,27 +141,30 @@ func browserManagerOrNil(bm *browser.Manager) browserManager { return bm } -// SetAutomation 注入自动化中心(系统事件转发目标)。 +// SetAutomation 注入系统事件的自动化中心;该 setter 仅保留给构造环过渡和隔离测试,待生产装配改为构造注入且旧测试清零后删除。 func (a *Adapter) SetAutomation(c *automation.Center) { a.automation = c } -// SetNotifier 注入通知器(账号告警推送目标)。 +// SetNotifier 注入账号告警通知器;该 setter 仅保留给构造环过渡和隔离测试,待生产装配改为构造注入且旧测试清零后删除。 func (a *Adapter) SetNotifier(n notifyNotifier) { a.notifier = n } -// SetBrowser 覆盖浏览器实现,便于测试注入桩。 +// SetCredentialWakeService 注入凭证恢复后的自动化唤醒端口;仅供构造环过渡和隔离测试,待统一应用装配后删除。 +func (a *Adapter) SetCredentialWakeService(service accountapp.CredentialWakePort) { + a.credentialWake = service +} + +// SetBrowser 覆盖浏览器实现;生产启动后不得替换必需依赖,待测试改用构造选项后删除此兼容入口。 func (a *Adapter) SetBrowser(b browserManager) { a.browser = b } -// SetRenewService 覆盖轻量续期服务,便于测试注入本地 HTTP 服务。 +// SetRenewService 覆盖轻量续期服务;该 setter 是测试替身覆盖点,待续期端口构造注入并迁移现有测试后删除。 func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s } -// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器,便于测试隔离网络。 +// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器;仅供测试隔离网络,冻结验证码生产路径不得运行时替换。 func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaReq = r } -// SetOrderDetailClient 覆盖纯 Go 订单详情客户端,便于测试隔离网络。 +// SetOrderDetailClient 覆盖纯 Go 订单详情客户端;该 setter 是测试替身覆盖点,待订单端口构造注入并迁移测试后删除。 func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c } -// SetChatService installs the user-facing chat side channel. It persists and -// broadcasts messages without changing the automatic reply path. -// SetChatService 设置聊天Service。 +// SetChatService 注入用户聊天旁路服务;它只负责持久化和广播,不改变自动回复路径,待构造环拆除后删除兼容 setter。 func (a *Adapter) SetChatService(service *chat.Service) { a.chat = service } // HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。 @@ -541,11 +564,11 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID // wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。 func (a *Adapter) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) { - if a.store == nil || a.store.Automation == nil { + if a.credentialWake == nil { return } if // err 保存err,供当前处理流程使用 - err := a.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil { + err := a.credentialWake.WakeCredentialBlocked(ctx, cookieID); err != nil { a.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err) } } @@ -588,21 +611,39 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second))) return false } - if !a.beginPasswordLogin(cookieID) { - a.logger.Warn("协议续期已在处理中", "account", cookieID) + // platformData 保存成功或失败时用于审计的账号平台运行数据;明文凭证只在续期工作闭包内短暂使用。 + var platformData db.CookiePlatformRuntimeData + // lookupFailed 标识是否在调用协议续期前读取账号数据失败,以保持历史审计原因。 + lookupFailed := false + // accepted、renewed、renewErr 保存协调器登记结果、续期结果和底层错误。 + accepted, renewed, renewErr := a.passwordCoordinator.Run(ctx, cookieID, func(runCtx context.Context) (bool, error) { + // loaded、loadErr 保存账号平台运行数据及其读取错误。 + loaded, loadErr := a.store.Cookies.GetCookiePlatformRuntimeData(runCtx, cookieID) + if loadErr != nil { + lookupFailed = true + return false, loadErr + } + platformData = loaded + return a.tryProtocolCredentialRenew(runCtx, &platformData) + }) + if !accepted { + if errors.Is(renewErr, accountapp.ErrCredentialRefreshInFlight) { + a.logger.Warn("协议续期已在处理中", "account", cookieID) + return false + } + a.logger.Warn("协议续期协调器不可用", "account", cookieID, "err", renewErr) return false } - defer a.finishPasswordLogin(cookieID) - - platformData, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) // platformData 是协议续期所需的 Cookie、metadata 和日志归属信息。 - if err != nil { - a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", err) - a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", err.Error()) + if lookupFailed { + a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", renewErr) + // message 保存账号详情读取失败时写入登录审计的脱敏说明。 + message := "读取账号详情失败" + if renewErr != nil { + message = renewErr.Error() + } + a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", message) return false } - - // renewed、renewErr 保存renewed、renewErr,供当前处理流程使用 - renewed, renewErr := a.tryProtocolCredentialRenew(ctx, &platformData) if renewed { a.wakeCredentialBlockedAutomation(ctx, cookieID) a.recordPasswordLogin(ctx, cookieID, platformData.UserID, "success", "", "Go 协议续期成功") @@ -634,26 +675,19 @@ func (a *Adapter) OnTransportReady(ctx context.Context, cookieID string) { a.wakeCredentialBlockedAutomation(ctx, cookieID) } -// beginPasswordLogin 负责begin密码登录相关处理。 +// beginPasswordLogin 兼容旧测试对账号恢复登记的访问;生产路径统一使用 account.CredentialRefreshCoordinator.Run。 func (a *Adapter) beginPasswordLogin(cookieID string) bool { - a.passwordMu.Lock() - defer a.passwordMu.Unlock() - if a.passwordProcessing == nil { - a.passwordProcessing = make(map[string]struct{}) - } - if // ok 保存ok,供当前处理流程使用 - _, ok := a.passwordProcessing[cookieID]; ok { + if a.passwordCoordinator == nil { return false } - a.passwordProcessing[cookieID] = struct{}{} - return true + return a.passwordCoordinator.TryBegin(cookieID) } -// finishPasswordLogin 负责finish密码登录相关处理。 +// finishPasswordLogin 兼容旧测试对账号恢复收尾的访问;正式调用必须由协调器 Run 自动释放状态。 func (a *Adapter) finishPasswordLogin(cookieID string) { - a.passwordMu.Lock() - defer a.passwordMu.Unlock() - delete(a.passwordProcessing, cookieID) + if a.passwordCoordinator != nil { + a.passwordCoordinator.Finish(cookieID) + } } // recordPasswordLogin 负责record密码登录相关处理。 diff --git a/internal/adapter/admin_repository.go b/internal/adapter/admin_repository.go index 4012b3d..a557de2 100644 --- a/internal/adapter/admin_repository.go +++ b/internal/adapter/admin_repository.go @@ -38,6 +38,14 @@ func (r *AdminRepository) ListUsers(ctx context.Context) ([]adminapp.UserSummary return users, nil } +// ListOwnedAccountIDs 返回用户拥有的账号标识;适配器不会读取或解密 Cookie 内容。 +func (r *AdminRepository) ListOwnedAccountIDs(ctx context.Context, userID int64) ([]string, error) { + if r == nil || r.store == nil || r.store.Cookies == nil { + return nil, errors.New("管理员账号查询适配器未初始化") + } + return r.store.Cookies.ListOwnedIDs(ctx, userID) +} + // DeleteUser 删除指定用户及其关联账号。 func (r *AdminRepository) DeleteUser(ctx context.Context, userID int64) error { if r == nil || r.store == nil || r.store.Users == nil { diff --git a/internal/adapter/admin_repository_test.go b/internal/adapter/admin_repository_test.go index 8e01070..309aa78 100644 --- a/internal/adapter/admin_repository_test.go +++ b/internal/adapter/admin_repository_test.go @@ -34,6 +34,11 @@ func TestAdminRepositoryMapsUsersStatsAndDelete(t *testing.T) { if targetErr != nil || target == nil { t.Fatalf("查询待删除用户失败 target=%v err=%v", target, targetErr) } + // ownedIDs、ownedErr 保存管理员删除前读取的非敏感账号标识。 + ownedIDs, ownedErr := repository.ListOwnedAccountIDs(ctx, target.ID) + if ownedErr != nil || ownedIDs == nil { + t.Fatalf("读取用户账号标识异常 ids=%v err=%v", ownedIDs, ownedErr) + } // deleteErr 保存管理员删除操作的错误。 if deleteErr := repository.DeleteUser(ctx, target.ID); deleteErr != nil { t.Fatalf("删除用户失败: %v", deleteErr) diff --git a/internal/adapter/admin_settings_dependencies.go b/internal/adapter/admin_settings_dependencies.go new file mode 100644 index 0000000..d744856 --- /dev/null +++ b/internal/adapter/admin_settings_dependencies.go @@ -0,0 +1,36 @@ +package adapter + +import ( + adminapp "xianyu-go/internal/application/admin" + "xianyu-go/internal/db" +) + +// AdminSettingsDependencies 封装管理员和系统设置应用服务所需的数据库适配器。 +type AdminSettingsDependencies struct { + // store 保存管理员与设置适配器共享的数据库入口,仅在 adapter 内部使用。 + store *db.Store +} + +// NewAdminSettingsDependencies 从数据库 Store 构造管理员设置专用依赖组。 +func NewAdminSettingsDependencies(store *db.Store) *AdminSettingsDependencies { + if store == nil { + return nil + } + return &AdminSettingsDependencies{store: store} +} + +// NewAdminRepository 创建管理员用户与统计适配器。 +func (d *AdminSettingsDependencies) NewAdminRepository() adminapp.Repository { + if d == nil { + return nil + } + return NewAdminRepository(d.store) +} + +// NewSettingsRepository 创建系统设置适配器。 +func (d *AdminSettingsDependencies) NewSettingsRepository() *SettingsRepository { + if d == nil { + return nil + } + return NewSettingsRepository(d.store) +} diff --git a/internal/adapter/admin_settings_dependencies_test.go b/internal/adapter/admin_settings_dependencies_test.go new file mode 100644 index 0000000..cac5272 --- /dev/null +++ b/internal/adapter/admin_settings_dependencies_test.go @@ -0,0 +1,11 @@ +package adapter + +import "testing" + +// TestNewAdminSettingsDependenciesRejectsNilStore 确保管理员设置依赖不会接受缺少数据库入口的构造请求。 +func TestNewAdminSettingsDependenciesRejectsNilStore(t *testing.T) { + // dependencies 保存缺少 Store 时的管理员设置依赖结果。 + if dependencies := NewAdminSettingsDependencies(nil); dependencies != nil { + t.Fatal("缺少 Store 时不应返回管理员设置依赖") + } +} diff --git a/internal/adapter/automation_dependencies.go b/internal/adapter/automation_dependencies.go new file mode 100644 index 0000000..ce1a30f --- /dev/null +++ b/internal/adapter/automation_dependencies.go @@ -0,0 +1,62 @@ +package adapter + +import ( + "errors" + + "xianyu-go/internal/db" +) + +// AutomationDependencies 封装自动化、默认回复和关键词用例所需的窄适配器构造能力。 +// 它只在 adapter 内部持有 Store,避免 Server 通过通用设施容器隐藏领域依赖。 +type AutomationDependencies struct { + // store 保存自动化相关适配器共享的数据库入口,不向 Server 或应用层暴露。 + store *db.Store +} + +// NewAutomationDependencies 构造自动化领域专用依赖,并在缺少数据库入口时立即返回错误。 +func NewAutomationDependencies(store *db.Store) (*AutomationDependencies, error) { + if store == nil { + return nil, errors.New("自动化依赖 Store 不能为空") + } + return &AutomationDependencies{store: store}, nil +} + +// NewAutomationCredentialWakeRepository 创建凭证恢复后的自动化任务唤醒适配器。 +func (d *AutomationDependencies) NewAutomationCredentialWakeRepository() *AutomationCredentialWakeRepository { + if d == nil { + return nil + } + return NewAutomationCredentialWakeRepository(d.store) +} + +// NewAutomationRepository 创建自动化规则、异常和发布规则共用的数据库适配器。 +func (d *AutomationDependencies) NewAutomationRepository() *AutomationRepository { + if d == nil { + return nil + } + return NewAutomationRepository(d.store) +} + +// NewAccountTaskRepository 创建账号自动化任务设置与运行记录适配器。 +func (d *AutomationDependencies) NewAccountTaskRepository() *AccountTaskRepository { + if d == nil { + return nil + } + return NewAccountTaskRepository(d.store) +} + +// NewDefaultReplyRepository 创建默认回复配置与投递记录适配器。 +func (d *AutomationDependencies) NewDefaultReplyRepository() *DefaultReplyRepository { + if d == nil { + return nil + } + return NewDefaultReplyRepository(d.store) +} + +// NewKeywordRepository 创建关键词和指定商品回复适配器。 +func (d *AutomationDependencies) NewKeywordRepository() *KeywordRepository { + if d == nil { + return nil + } + return NewKeywordRepository(d.store) +} diff --git a/internal/adapter/automation_dependencies_test.go b/internal/adapter/automation_dependencies_test.go new file mode 100644 index 0000000..a2e2a95 --- /dev/null +++ b/internal/adapter/automation_dependencies_test.go @@ -0,0 +1,39 @@ +package adapter + +import ( + "testing" + + "xianyu-go/internal/db" +) + +// TestNewAutomationDependenciesRejectsNilStore 确保自动化依赖组不会接受缺失数据库入口的半初始化状态。 +func TestNewAutomationDependenciesRejectsNilStore(t *testing.T) { + // dependencies、err 分别保存构造结果和缺少 Store 时的错误。 + dependencies, err := NewAutomationDependencies(nil) + if dependencies != nil { + t.Fatal("缺少 Store 时不应返回自动化依赖") + } + if err == nil { + t.Fatal("缺少 Store 时应返回构造错误") + } +} + +// TestNewAutomationDependenciesCreatesTypedFactory 确保有效 Store 可创建自动化与回复领域的全部窄适配器。 +func TestNewAutomationDependenciesCreatesTypedFactory(t *testing.T) { + // store 仅用于验证构造类型,不执行数据库读写。 + store := db.NewStore(nil, db.DialectSQLite) + // dependencies、err 分别保存自动化工厂和构造错误。 + dependencies, err := NewAutomationDependencies(store) + if err != nil { + t.Fatalf("NewAutomationDependencies: %v", err) + } + if dependencies == nil { + t.Fatal("有效 Store 应返回自动化依赖") + } + if dependencies.NewAutomationCredentialWakeRepository() == nil || dependencies.NewAutomationRepository() == nil || dependencies.NewAccountTaskRepository() == nil { + t.Fatal("自动化工厂应返回自动化仓储") + } + if dependencies.NewDefaultReplyRepository() == nil || dependencies.NewKeywordRepository() == nil { + t.Fatal("自动化工厂应返回回复规则仓储") + } +} diff --git a/internal/adapter/chat_dependencies.go b/internal/adapter/chat_dependencies.go new file mode 100644 index 0000000..498b082 --- /dev/null +++ b/internal/adapter/chat_dependencies.go @@ -0,0 +1,30 @@ +package adapter + +import ( + "xianyu-go/internal/account" + chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/chat" + "xianyu-go/internal/db" +) + +// ChatDependencies 封装聊天应用服务所需的数据库适配器工厂,避免 Server 依赖通用设施容器。 +type ChatDependencies struct { + // store 保存聊天仓储共享的数据库入口,仅在 adapter 内部使用。 + store *db.Store +} + +// NewChatDependencies 从数据库 Store 构造聊天专用依赖组。 +func NewChatDependencies(store *db.Store) *ChatDependencies { + if store == nil { + return nil + } + return &ChatDependencies{store: store} +} + +// NewChatSendingApplication 创建聊天应用服务及其平台、运行时和持久化适配器。 +func (d *ChatDependencies) NewChatSendingApplication(service *chat.Service, manager *account.Manager, client func() MTOPClient) *chatapp.Service { + if d == nil { + return NewChatSendingApplication(service, nil, manager, client) + } + return NewChatSendingApplication(service, d.store, manager, client) +} diff --git a/internal/adapter/chat_refresh.go b/internal/adapter/chat_refresh.go new file mode 100644 index 0000000..4bc38aa --- /dev/null +++ b/internal/adapter/chat_refresh.go @@ -0,0 +1,96 @@ +package adapter + +import ( + "context" + "errors" + "fmt" + + "xianyu-go/internal/account" + chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/automation" + domainchat "xianyu-go/internal/chat" +) + +// chatRefreshProvider 将账号运行时的平台分页能力与聊天领域落库服务收敛到应用端口。 +type chatRefreshProvider struct { + // service 保存联系人和消息页的领域解析、幂等写入能力。 + service *domainchat.Service + // lookup 按账号查找在线运行实例;运行时管理器只在适配器装配边界出现。 + lookup func(string) (automation.MessageSender, bool) +} + +// NewChatRefreshProvider 创建聊天平台刷新适配器。 +func NewChatRefreshProvider(service *domainchat.Service, manager *account.Manager) chatapp.RefreshProvider { + if service == nil || manager == nil { + return nil + } + return chatRefreshProvider{service: service, lookup: func(accountID string) (automation.MessageSender, bool) { + return manager.GetInstance(accountID) + }} +} + +// RefreshConversations 拉取联系人页并在领域服务中完成解析和持久化。 +func (p chatRefreshProvider) RefreshConversations(ctx context.Context, accountID string, cursor int64, limit int) (chatapp.ConversationPage, error) { + if p.service == nil || p.lookup == nil { + return chatapp.ConversationPage{}, chatapp.ErrRefreshUnavailable + } + // sender 和 ok 保存指定账号的在线运行实例及其存在性。 + sender, ok := p.lookup(accountID) + if !ok || sender == nil { + return chatapp.ConversationPage{}, chatapp.ErrOffline + } + // fetcher 和 supported 保存联系人平台分页能力及接口支持状态。 + fetcher, supported := sender.(interface { + FetchChatConversations(context.Context, int64, int) (map[string]any, string, error) + }) + if !supported { + return chatapp.ConversationPage{}, errors.New("当前账号不支持聊天联系人刷新") + } + // body、myID 和 fetchErr 保存平台原始响应、当前账号身份及请求错误。 + body, myID, fetchErr := fetcher.FetchChatConversations(ctx, cursor, limit) + if fetchErr != nil { + return chatapp.ConversationPage{}, fetchErr + } + // page 和 saveErr 保存领域解析后的联系人分页结果及持久化错误。 + page, saveErr := p.service.RecordConversationPage(ctx, accountID, myID, body) + if saveErr != nil { + return chatapp.ConversationPage{}, fmt.Errorf("%w: %v", chatapp.ErrRefreshPersist, saveErr) + } + return chatapp.ConversationPage{HasMore: page.HasMore, NextCursor: page.NextCursor}, nil +} + +// RefreshHistory 拉取聊天历史页并在领域服务中完成解析和持久化。 +func (p chatRefreshProvider) RefreshHistory(ctx context.Context, accountID, chatID string, cursor int64, limit int, session chatapp.Session) (chatapp.HistoryPage, error) { + if p.service == nil || p.lookup == nil { + return chatapp.HistoryPage{}, chatapp.ErrRefreshUnavailable + } + // sender 和 ok 保存指定账号的在线运行实例及其存在性。 + sender, ok := p.lookup(accountID) + if !ok || sender == nil { + return chatapp.HistoryPage{}, chatapp.ErrOffline + } + // fetcher 和 supported 保存历史平台分页能力及接口支持状态。 + fetcher, supported := sender.(interface { + FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error) + }) + if !supported { + return chatapp.HistoryPage{}, errors.New("当前账号不支持聊天历史刷新") + } + // body、myID 和 fetchErr 保存平台原始响应、当前账号身份及请求错误。 + body, myID, fetchErr := fetcher.FetchChatHistory(ctx, chatID, cursor, limit) + if fetchErr != nil { + return chatapp.HistoryPage{}, fetchErr + } + // page 和 saveErr 保存领域解析后的消息分页结果及持久化错误。 + page, saveErr := p.service.RecordHistoryPage(ctx, accountID, chatID, myID, ChatSessionFromApplication(session), body) + if saveErr != nil { + return chatapp.HistoryPage{}, fmt.Errorf("%w: %v", chatapp.ErrRefreshPersist, saveErr) + } + return chatapp.HistoryPage{ + Messages: ChatMessagesFromDB(page.Messages), Session: session, + HasMore: page.HasMore, NextCursor: page.NextCursor, + }, nil +} + +// 确保聊天刷新适配器覆盖应用层定义的全部能力。 +var _ chatapp.RefreshProvider = chatRefreshProvider{} diff --git a/internal/adapter/chat_repository_test.go b/internal/adapter/chat_repository_test.go index 001b5c0..883d9cf 100644 --- a/internal/adapter/chat_repository_test.go +++ b/internal/adapter/chat_repository_test.go @@ -6,10 +6,79 @@ import ( "testing" chatapp "xianyu-go/internal/application/chat" + "xianyu-go/internal/automation" + domainchat "xianyu-go/internal/chat" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/mtop" ) +// subscriptionDomainRepository 是领域聊天订阅测试使用的最小内存仓储。 +type subscriptionDomainRepository struct{} + +// ListOwnedIDs 返回实时订阅测试账号归属。 +func (subscriptionDomainRepository) ListOwnedIDs(context.Context, int64) ([]string, error) { + return []string{"cid"}, nil +} + +// DeleteSession 满足领域聊天仓储接口的删除能力。 +func (subscriptionDomainRepository) DeleteSession(context.Context, string, string) error { return nil } + +// UpsertSession 满足领域聊天仓储接口的会话写入能力。 +func (subscriptionDomainRepository) UpsertSession(context.Context, db.ChatSession) error { return nil } + +// SyncSessionSummary 满足领域聊天仓储接口的会话摘要同步能力。 +func (subscriptionDomainRepository) SyncSessionSummary(context.Context, string, string, string, int64, int64, int) error { + return nil +} + +// SaveMessage 返回领域事件需要的消息副本,模拟幂等首次写入。 +func (subscriptionDomainRepository) SaveMessage(_ context.Context, _ db.ChatSession, message db.ChatMessage, _ bool) (*db.ChatMessage, bool, error) { + return &message, true, nil +} + +// UpdateMessageType 满足领域聊天仓储接口的消息类型更新能力。 +func (subscriptionDomainRepository) UpdateMessageType(context.Context, string, string, string) error { + return nil +} + +// UpdateMessageStatus 满足领域聊天仓储接口的消息状态更新能力。 +func (subscriptionDomainRepository) UpdateMessageStatus(context.Context, string, string, string) (*db.ChatMessage, error) { + return &db.ChatMessage{}, nil +} + +// TestChatSubscriptionProviderConvertsAndCleansEvents 验证领域事件转换和订阅取消可重复执行。 +func TestChatSubscriptionProviderConvertsAndCleansEvents(t *testing.T) { + // service 是使用内存仓储构造的领域聊天事件中心。 + service := domainchat.NewWithRepository(subscriptionDomainRepository{}) + // provider 是隐藏领域模型并输出应用事件的适配器。 + provider := NewChatSubscriptionProvider(service) + // events、cancel、err 保存适配器订阅结果。 + events, cancel, err := provider.Subscribe(context.Background(), 42) + if err != nil { + t.Fatalf("Subscribe() error=%v", err) + } + // _, _, recordErr 保存领域入站消息写入结果。 + _, _, recordErr := service.RecordIncoming(context.Background(), domainchat.Incoming{ + AccountID: "cid", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家", Text: "你好", + Raw: map[string]any{"messageId": "msg-1"}, + }) + if recordErr != nil { + t.Fatalf("RecordIncoming() error=%v", recordErr) + } + // event 保存转换后的应用层事件。 + event := <-events + if event.Type != "message.created" || event.Message == nil || event.Message.MessageKey != "msg-1" || event.Message.Content != "你好" { + t.Fatalf("event=%+v", event) + } + cancel() + cancel() + // closed 表示取消后转发通道已完成清理并关闭。 + _, closed := <-events + if closed { + t.Fatal("取消订阅后事件通道仍保持开启") + } +} + // fakeChatUploadClient 只实现聊天图片上传能力,用于隔离平台网络请求。 type fakeChatUploadClient struct { // mtop.Client 保留其余平台能力占位,测试只关注图片上传方法。 @@ -33,6 +102,47 @@ type fakeChatIdentityClient struct { info *mtop.ChatUserInfo } +// fakeChatRefreshFetcher 提供联系人和历史分页的最小运行时能力,用于隔离账号管理器与平台连接。 +type fakeChatRefreshFetcher struct { + // MessageSender 占位实现聊天发送端口未涉及的其余运行时方法。 + automation.MessageSender +} + +// FetchChatConversations 返回空联系人页,验证刷新适配器调用边界。 +func (fakeChatRefreshFetcher) FetchChatConversations(context.Context, int64, int) (map[string]any, string, error) { + return map[string]any{"hasMore": true, "nextCursor": int64(8)}, "self", nil +} + +// FetchChatHistory 返回空历史页,验证刷新适配器调用边界。 +func (fakeChatRefreshFetcher) FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error) { + return map[string]any{"hasMore": true, "nextCursor": int64(9)}, "self", nil +} + +// TestChatRefreshProviderKeepsPlatformAndDomainInsideAdapter 验证平台分页与领域落库均停留在适配器内。 +func TestChatRefreshProviderKeepsPlatformAndDomainInsideAdapter(t *testing.T) { + // provider 保存使用内存领域仓储和测试运行时查找函数的刷新适配器。 + provider := chatRefreshProvider{ + service: domainchat.NewWithRepository(subscriptionDomainRepository{}), + lookup: func(string) (automation.MessageSender, bool) { return fakeChatRefreshFetcher{}, true }, + } + // conversations 和 conversationErr 保存联系人刷新结果及错误。 + conversations, conversationErr := provider.RefreshConversations(context.Background(), "cid", 0, 10) + if conversationErr != nil || !conversations.HasMore || conversations.NextCursor != 8 { + t.Fatalf("conversations=%+v err=%v", conversations, conversationErr) + } + // history 和 historyErr 保存历史刷新结果及错误。 + history, historyErr := provider.RefreshHistory(context.Background(), "cid", "chat", 0, 10, chatapp.Session{AccountID: "cid", ChatID: "chat"}) + if historyErr != nil || !history.HasMore || history.NextCursor != 9 { + t.Fatalf("history=%+v err=%v", history, historyErr) + } + // unavailable 保存缺失运行实例查找函数时的应用端口错误。 + unavailable := chatRefreshProvider{service: provider.service} + // unavailableErr 保存缺失运行时查找函数时的应用端口错误。 + if _, unavailableErr := unavailable.RefreshConversations(context.Background(), "cid", 0, 10); !errors.Is(unavailableErr, chatapp.ErrRefreshUnavailable) { + t.Fatalf("unavailable error=%v", unavailableErr) + } +} + // FetchChatUserInfo 返回预设聊天身份,并记录适配器已能调用动态能力。 func (c fakeChatIdentityClient) FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error) { return c.info, nil diff --git a/internal/adapter/chat_sending.go b/internal/adapter/chat_sending.go index b408031..374f7c1 100644 --- a/internal/adapter/chat_sending.go +++ b/internal/adapter/chat_sending.go @@ -20,11 +20,17 @@ type chatOutgoingRepository struct { // NewChatSendingApplication 装配聊天历史、实时发送、图片上传和身份补全端口。 func NewChatSendingApplication(domainService *domainchat.Service, store *db.Store, manager *account.Manager, clientProvider func() mtop.Client) *chatapp.Service { - return chatapp.NewWithSending( + if domainService == nil { + // service 保留历史查询应用对象,但不伪造未装配的发送、订阅和刷新端口。 + return chatapp.NewWithSendingSubscriptionAndRefresh(NewChatRepository(store), nil, nil, nil, nil, nil, NewChatIdentityResolver(store, clientProvider)) + } + return chatapp.NewWithSendingSubscriptionAndRefresh( NewChatRepository(store), NewChatOutgoingRepository(domainService), NewChatSenderProvider(manager), NewChatImageUploader(store, clientProvider, manager), + NewChatSubscriptionProvider(domainService), + NewChatRefreshProvider(domainService, manager), NewChatIdentityResolver(store, clientProvider), ) } diff --git a/internal/adapter/chat_subscription.go b/internal/adapter/chat_subscription.go new file mode 100644 index 0000000..247119e --- /dev/null +++ b/internal/adapter/chat_subscription.go @@ -0,0 +1,112 @@ +package adapter + +import ( + "context" + "sync" + + chatapp "xianyu-go/internal/application/chat" + domainchat "xianyu-go/internal/chat" + "xianyu-go/internal/db" +) + +// chatSubscriptionProvider 将聊天领域事件转换为不暴露数据库模型的应用事件。 +type chatSubscriptionProvider struct { + // service 保存聊天领域事件中心;HTTP 层只接收应用层事件。 + service *domainchat.Service +} + +// NewChatSubscriptionProvider 创建实时聊天订阅适配器。 +func NewChatSubscriptionProvider(service *domainchat.Service) chatapp.SubscriptionProvider { + if service == nil { + return nil + } + return chatSubscriptionProvider{service: service} +} + +// Subscribe 转发指定用户有权接收的领域事件,并由取消函数负责释放领域订阅和转发协程。 +func (p chatSubscriptionProvider) Subscribe(ctx context.Context, userID int64) (<-chan chatapp.Event, func(), error) { + if p.service == nil || userID <= 0 { + return nil, nil, chatapp.ErrSubscriptionUnavailable + } + // source 和 sourceCancel 保存领域订阅通道及其幂等清理函数。 + source, sourceCancel, err := p.service.Subscribe(ctx, userID) + if err != nil { + return nil, nil, err + } + // forwardCtx 控制事件转换协程的退出;父请求结束时会自动取消。 + forwardCtx, cancelForward := context.WithCancel(ctx) + // output 保存转换后的应用层事件,缓冲避免短暂写入抖动阻塞领域发布者。 + output := make(chan chatapp.Event, 128) + // forwardDone 标记转发 goroutine 已退出,取消方等待它后再返回,避免留下游离后台任务。 + forwardDone := make(chan struct{}) + // stopOnce 保证调用方重复清理时不会重复关闭资源。 + var stopOnce sync.Once + // stop 取消转发并释放领域订阅;调用方可在 WebSocket 握手失败和正常关闭路径重复调用。 + stop := func() { + stopOnce.Do(func() { + cancelForward() + sourceCancel() + }) + <-forwardDone + } + go func() { + defer close(forwardDone) + defer close(output) + defer stopOnce.Do(func() { + cancelForward() + sourceCancel() + }) + for { + select { + case <-forwardCtx.Done(): + return + case // event、ok 保存领域事件及源订阅通道是否仍然开放。 + event, ok := <-source: + if !ok { + return + } + // converted 保存转换后的应用层事件,避免领域数据库模型越过适配器。 + converted := chatApplicationEvent(event) + select { + case output <- converted: + case <-forwardCtx.Done(): + return + } + } + } + }() + return output, stop, nil +} + +// chatApplicationEvent 将领域事件中的数据库模型转换为敏感数据隔离后的应用模型。 +func chatApplicationEvent(event domainchat.Event) chatapp.Event { + // converted 保存实时事件的非敏感应用层表示。 + converted := chatapp.Event{Type: event.Type} + if event.Message != nil { + // message 保存转换后的非敏感消息指针。 + message := chatApplicationMessage(event.Message) + converted.Message = &message + } + if event.Session != nil { + // session 保存转换后的非敏感会话摘要指针。 + session := chatApplicationSession(event.Session) + converted.Session = &session + } + return converted +} + +// chatApplicationSession 将领域会话摘要转换为应用层会话摘要。 +func chatApplicationSession(session *db.ChatSession) chatapp.Session { + if session == nil { + return chatapp.Session{} + } + return chatapp.Session{ + AccountID: session.CookieID, 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.SubscriptionProvider = chatSubscriptionProvider{} diff --git a/internal/adapter/cookie_session.go b/internal/adapter/cookie_session.go index df797c5..233a7f1 100644 --- a/internal/adapter/cookie_session.go +++ b/internal/adapter/cookie_session.go @@ -47,7 +47,7 @@ func HasStoredCookieCredential(detail *accountapp.CredentialDetail) bool { // PersistCookieSessionLocked 持久化平台响应后的 Cookie 会话;调用方必须已持有凭证锁。 func PersistCookieSessionLocked( ctx context.Context, - repository accountapp.CredentialRepository, + repository accountapp.CredentialSessionPort, detail *accountapp.CredentialDetail, session *CookieSession, ) (value string, valueChanged, handled bool, err error) { diff --git a/internal/adapter/cookie_session_test.go b/internal/adapter/cookie_session_test.go index a24da2d..f6b9573 100644 --- a/internal/adapter/cookie_session_test.go +++ b/internal/adapter/cookie_session_test.go @@ -9,6 +9,18 @@ import ( "xianyu-go/internal/xianyu/cookierefresh" ) +// minimalCredentialSessionPortFake 仅实现会话写回所需的方法,证明适配器不依赖完整账号仓储。 +type minimalCredentialSessionPortFake struct { + // calls 记录平台会话写回次数。 + calls int +} + +// UpdateRenewalCookie 记录一次脱敏 Cookie 写回请求,不保存明文内容。 +func (f *minimalCredentialSessionPortFake) UpdateRenewalCookie(context.Context, string, string, string, int64) error { + f.calls++ + return nil +} + // TestCookieSessionAdapterPersistsAuthoritativeSnapshot 验证平台 Cookie 会话快照经凭证 Port 写回并保留作用域。 func TestCookieSessionAdapterPersistsAuthoritativeSnapshot(t *testing.T) { // store、cleanup 保存测试数据库及其资源清理函数。 @@ -57,6 +69,22 @@ func TestCookieSessionAdapterRejectsMissingRepository(t *testing.T) { } } +// TestCookieSessionAdapterAcceptsMinimalSessionPort 验证会话写回只要求最小凭证端口。 +func TestCookieSessionAdapterAcceptsMinimalSessionPort(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: "/"}}) + // port 保存仅实现 Cookie 写回能力的最小端口替身。 + port := &minimalCredentialSessionPortFake{} + // _, changed、handled、persistErr 保存使用最小端口写回后的结果。 + _, changed, handled, persistErr := PersistCookieSessionLocked(ctx, port, detail, session) + if persistErr != nil || !changed || !handled || port.calls != 1 { + t.Fatalf("最小凭证端口写回异常: changed=%v handled=%v calls=%d err=%v", changed, handled, port.calls, persistErr) + } +} + // TestCookieSessionAdapterHasStoredCredential 验证扁平 Cookie 和完整快照均被识别为可用凭证。 func TestCookieSessionAdapterHasStoredCredential(t *testing.T) { // flat 是只含扁平 Cookie 的历史平台凭证视图。 diff --git a/internal/adapter/item_dependencies.go b/internal/adapter/item_dependencies.go new file mode 100644 index 0000000..e3adf0d --- /dev/null +++ b/internal/adapter/item_dependencies.go @@ -0,0 +1,80 @@ +package adapter + +import ( + "context" + "errors" + "log/slog" + + "xianyu-go/internal/db" +) + +// ItemDependencies 封装商品目录、发布、批量和同步用例所需的窄适配器构造能力。 +// 它只在 adapter 内部持有 Store,避免商品装配依赖通用设施容器。 +type ItemDependencies struct { + // store 是商品适配器共享的数据库入口,不向 Server 或应用层暴露。 + store *db.Store +} + +// NewItemDependencies 构造商品专用依赖,并在缺少数据库入口时立即返回错误。 +func NewItemDependencies(store *db.Store) (*ItemDependencies, error) { + if store == nil { + return nil, errors.New("商品依赖 Store 不能为空") + } + return &ItemDependencies{store: store}, nil +} + +// NewItemBatchRepository 创建批量发布状态仓储。 +func (d *ItemDependencies) NewItemBatchRepository() *ItemBatchRepository { + if d == nil { + return nil + } + return NewItemBatchRepository(d.store) +} + +// NewItemBatchPreviewPort 创建批量预检所需的归属和本地文件端口。 +func (d *ItemDependencies) NewItemBatchPreviewPort() *ItemBatchPreviewPort { + if d == nil { + return nil + } + return NewItemBatchPreviewPort(d.store) +} + +// NewItemBatchPublishPort 创建批量远端发布端口,并接收平台会话与图片 I/O 回调。 +func (d *ItemDependencies) NewItemBatchPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error), readFile ReadPublishImageFile, download DownloadPublishImageURL) *ItemBatchPublishPort { + if d == nil { + return nil + } + return NewItemBatchPublishPort(d.store, client, logger, update, recover, readFile, download) +} + +// NewItemPublishPort 创建单商品发布与类目推荐共用的平台端口。 +func (d *ItemDependencies) NewItemPublishPort(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemPublishPort { + if d == nil { + return nil + } + return NewItemPublishPort(d.store, client, logger, update, recover) +} + +// NewItemPublishRepository 创建单商品发布结果仓储。 +func (d *ItemDependencies) NewItemPublishRepository() *ItemPublishRepository { + if d == nil { + return nil + } + return NewItemPublishRepository(d.store) +} + +// NewItemCatalogRepository 创建商品目录读写仓储。 +func (d *ItemDependencies) NewItemCatalogRepository() *ItemCatalogRepository { + if d == nil { + return nil + } + return NewItemCatalogRepository(d.store) +} + +// NewItemSyncRepository 创建商品同步端口,并接收平台会话回调。 +func (d *ItemDependencies) NewItemSyncRepository(client func() MTOPClient, logger *slog.Logger, update func(context.Context, string, string), recover func(context.Context, string, error)) *ItemSyncRepository { + if d == nil { + return nil + } + return NewItemSyncRepository(d.store, client, logger, update, recover) +} diff --git a/internal/adapter/item_dependencies_test.go b/internal/adapter/item_dependencies_test.go new file mode 100644 index 0000000..4053492 --- /dev/null +++ b/internal/adapter/item_dependencies_test.go @@ -0,0 +1,36 @@ +package adapter + +import ( + "testing" + + "xianyu-go/internal/db" +) + +// TestNewItemDependenciesRejectsNilStore 确保商品专用依赖不会在缺少数据库入口时构造成功。 +func TestNewItemDependenciesRejectsNilStore(t *testing.T) { + // dependencies、err 分别保存构造结果和缺少 Store 时的错误。 + dependencies, err := NewItemDependencies(nil) + if dependencies != nil { + t.Fatal("缺少 Store 时不应返回商品依赖") + } + if err == nil { + t.Fatal("缺少 Store 时应返回构造错误") + } +} + +// TestNewItemDependenciesCreatesTypedFactory 确保有效 Store 可创建商品领域全部窄适配器。 +func TestNewItemDependenciesCreatesTypedFactory(t *testing.T) { + // store 仅用于验证构造类型,不执行数据库读写。 + store := db.NewStore(nil, db.DialectSQLite) + // dependencies、err 分别保存商品工厂和构造错误。 + dependencies, err := NewItemDependencies(store) + if err != nil { + t.Fatalf("NewItemDependencies: %v", err) + } + if dependencies == nil { + t.Fatal("有效 Store 应返回商品依赖") + } + if dependencies.NewItemBatchRepository() == nil || dependencies.NewItemBatchPreviewPort() == nil || dependencies.NewItemPublishRepository() == nil || dependencies.NewItemCatalogRepository() == nil { + t.Fatal("商品工厂应返回本地仓储和预检端口") + } +} diff --git a/internal/adapter/misc_dependencies.go b/internal/adapter/misc_dependencies.go new file mode 100644 index 0000000..23ef06a --- /dev/null +++ b/internal/adapter/misc_dependencies.go @@ -0,0 +1,55 @@ +package adapter + +import ( + "errors" + + notificationsapp "xianyu-go/internal/application/notifications" + "xianyu-go/internal/db" +) + +// MiscDependencies 封装通知、订单分析和卡券应用服务所需的数据库适配器构造能力。 +// 该依赖组只在适配器内部持有 Store,Server 通过领域方法获得窄接口,避免继续扩大通用设施容器的职责。 +type MiscDependencies struct { + // store 保存通知、分析和卡券适配器共享的数据库入口,不向 HTTP 层或应用服务暴露。 + store *db.Store +} + +// NewMiscDependencies 构造通知、分析和卡券领域专用依赖,并拒绝缺少数据库入口的半初始化实例。 +func NewMiscDependencies(store *db.Store) (*MiscDependencies, error) { + if store == nil { + return nil, errors.New("通知、分析和卡券依赖 Store 不能为空") + } + return &MiscDependencies{store: store}, nil +} + +// NewNotificationUncertainRepository 创建通知不确定状态查询适配器。 +func (d *MiscDependencies) NewNotificationUncertainRepository() notificationsapp.Repository { + if d == nil { + return nil + } + return NewNotificationUncertainRepository(d.store) +} + +// NewNotificationChannelRepository 创建通知渠道及账号绑定适配器。 +func (d *MiscDependencies) NewNotificationChannelRepository() notificationsapp.ChannelRepository { + if d == nil { + return nil + } + return NewNotificationChannelRepository(d.store) +} + +// NewAnalyticsRepository 创建订单分析只读适配器。 +func (d *MiscDependencies) NewAnalyticsRepository() *AnalyticsRepository { + if d == nil { + return nil + } + return NewAnalyticsRepository(d.store) +} + +// NewCardsRepository 创建卡券库存适配器。 +func (d *MiscDependencies) NewCardsRepository() *CardsRepository { + if d == nil { + return nil + } + return NewCardsRepository(d.store) +} diff --git a/internal/adapter/misc_dependencies_test.go b/internal/adapter/misc_dependencies_test.go new file mode 100644 index 0000000..f102a51 --- /dev/null +++ b/internal/adapter/misc_dependencies_test.go @@ -0,0 +1,51 @@ +package adapter + +import ( + "testing" + + "xianyu-go/internal/db" +) + +// TestNewMiscDependenciesRejectsNilStore 确保通知、分析和卡券依赖不会以缺失数据库入口的状态构造。 +func TestNewMiscDependenciesRejectsNilStore(t *testing.T) { + // dependencies、err 分别保存构造结果和缺少 Store 时的错误。 + dependencies, err := NewMiscDependencies(nil) + if dependencies != nil { + t.Fatal("缺少 Store 时不应返回杂项依赖") + } + if err == nil { + t.Fatal("缺少 Store 时应返回构造错误") + } +} + +// TestNewMiscDependenciesCreatesTypedFactories 确保有效 Store 能创建三个领域的窄适配器。 +func TestNewMiscDependenciesCreatesTypedFactories(t *testing.T) { + // store 仅用于验证工厂构造,不执行数据库读写。 + store := db.NewStore(nil, db.DialectSQLite) + // dependencies、err 分别保存杂项领域工厂和构造错误。 + dependencies, err := NewMiscDependencies(store) + if err != nil { + t.Fatalf("NewMiscDependencies: %v", err) + } + if dependencies == nil { + t.Fatal("有效 Store 应返回杂项领域依赖") + } + if dependencies.NewNotificationUncertainRepository() == nil || dependencies.NewNotificationChannelRepository() == nil { + t.Fatal("通知工厂应返回两个通知应用仓储") + } + if dependencies.NewAnalyticsRepository() == nil { + t.Fatal("分析工厂应返回分析仓储") + } + if dependencies.NewCardsRepository() == nil { + t.Fatal("卡券工厂应返回卡券仓储") + } +} + +// TestMiscDependenciesNilReceiverReturnsNil 确保测试或关闭流程中的空依赖不会伪造适配器。 +func TestMiscDependenciesNilReceiverReturnsNil(t *testing.T) { + // dependencies 表示未装配的杂项依赖接收者。 + var dependencies *MiscDependencies + if dependencies.NewNotificationUncertainRepository() != nil || dependencies.NewNotificationChannelRepository() != nil || dependencies.NewAnalyticsRepository() != nil || dependencies.NewCardsRepository() != nil { + t.Fatal("空杂项依赖不应创建任何适配器") + } +} diff --git a/internal/adapter/order_dependencies.go b/internal/adapter/order_dependencies.go new file mode 100644 index 0000000..d9111d8 --- /dev/null +++ b/internal/adapter/order_dependencies.go @@ -0,0 +1,55 @@ +package adapter + +import ( + "errors" + "log/slog" + + orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" +) + +// OrderDependencies 只封装订单用例所需的持久化与运行时适配器构造,避免订单装配依赖万能设施容器。 +type OrderDependencies struct { + // store 是订单适配器共享的数据库入口,仅在 adapter 内部用于创建窄接口实现。 + store *db.Store +} + +// NewOrderDependencies 构造订单专用依赖并拒绝缺失数据库入口。 +func NewOrderDependencies(store *db.Store) (*OrderDependencies, error) { + if store == nil { + return nil, errors.New("订单依赖 Store 不能为空") + } + return &OrderDependencies{store: store}, nil +} + +// NewOrderRepository 创建订单读写仓储,供订单应用服务共享同一适配器实例。 +func (d *OrderDependencies) NewOrderRepository() *OrderRepository { + if d == nil { + return nil + } + return NewOrderRepository(d.store) +} + +// NewOrderReconciliationRepository 创建订单补偿记录仓储,供跨外部动作的异常收口使用。 +func (d *OrderDependencies) NewOrderReconciliationRepository() *OrderReconciliationRepository { + if d == nil { + return nil + } + return NewOrderReconciliationRepository(d.store) +} + +// NewOrderRuntime 创建订单平台运行时,调用方通过 hooks 注入账号、自动化和通知能力。 +func (d *OrderDependencies) NewOrderRuntime(hooks OrderRuntimeHooks, reconciliation orderapp.ReconciliationRecorder, logger *slog.Logger) *OrderRuntime { + if d == nil { + return nil + } + return NewOrderRuntime(d.store, hooks, reconciliation, logger) +} + +// NewOrderRefreshJobRepository 创建订单刷新任务仓储,隐藏任务租约与状态的持久化模型。 +func (d *OrderDependencies) NewOrderRefreshJobRepository() orderapp.RefreshJobRepository { + if d == nil { + return nil + } + return NewOrderRefreshJobRepository(d.store) +} diff --git a/internal/adapter/order_dependencies_test.go b/internal/adapter/order_dependencies_test.go new file mode 100644 index 0000000..3230a9c --- /dev/null +++ b/internal/adapter/order_dependencies_test.go @@ -0,0 +1,42 @@ +package adapter + +import ( + "testing" + + "xianyu-go/internal/db" +) + +// TestNewOrderDependenciesRejectsNilStore 确保订单专用依赖不会在缺少数据库入口时构造成功。 +func TestNewOrderDependenciesRejectsNilStore(t *testing.T) { + // dependencies、err 分别保存构造结果和缺少 Store 时的错误。 + dependencies, err := NewOrderDependencies(nil) + if dependencies != nil { + t.Fatal("缺少 Store 时不应返回订单依赖") + } + if err == nil { + t.Fatal("缺少 Store 时应返回构造错误") + } +} + +// TestNewOrderDependenciesCreatesTypedFactory 确保有效 Store 能创建订单专用工厂并生成窄仓储。 +func TestNewOrderDependenciesCreatesTypedFactory(t *testing.T) { + // store 使用已初始化的仓储聚合仅验证装配类型,不执行数据库读写。 + store := db.NewStore(nil, db.DialectSQLite) + // dependencies、err 分别保存订单工厂和构造错误。 + dependencies, err := NewOrderDependencies(store) + if err != nil { + t.Fatalf("NewOrderDependencies: %v", err) + } + if dependencies == nil { + t.Fatal("有效 Store 应返回订单依赖") + } + if dependencies.NewOrderRepository() == nil { + t.Fatal("订单工厂应返回订单仓储") + } + if dependencies.NewOrderReconciliationRepository() == nil { + t.Fatal("订单工厂应返回补偿仓储") + } + if dependencies.NewOrderRefreshJobRepository() == nil { + t.Fatal("订单工厂应返回刷新任务仓储") + } +} diff --git a/internal/adapter/order_runtime.go b/internal/adapter/order_runtime.go index 5593a2b..63bffa9 100644 --- a/internal/adapter/order_runtime.go +++ b/internal/adapter/order_runtime.go @@ -8,12 +8,25 @@ import ( "strings" "time" + accountmanager "xianyu-go/internal/account" orderapp "xianyu-go/internal/application/orders" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/mtop" ) +// OrderAutomation 定义订单手动发货所需的最小自动化能力,避免订单适配器依赖具体 Center 类型。 +type OrderAutomation interface { + // ManualFullDelivery 执行一次订单完整发货并返回实际发送数量。 + ManualFullDelivery(context.Context, *db.Order) (int, error) +} + +// OrderNotifier 定义订单发货结果所需的最小通知能力,通知实现不进入订单应用层。 +type OrderNotifier interface { + // NotifyDelivery 发送订单发货结果通知。 + NotifyDelivery(string, string, string, string, string, string) +} + // orderDetailMTop 是订单运行时需要的可选详情接口能力。 type orderDetailMTop interface { // FetchOrderDetail 请求订单详情并返回平台响应中的订单字段。 @@ -42,6 +55,29 @@ type OrderRuntimeHooks struct { ReportPersistenceFailure func(string, error) } +// NewOrderRuntimeHooks 将账号、自动化和通知依赖转换为订单运行时回调;闭包只存在于 adapter 装配边界。 +func NewOrderRuntimeHooks(client func() mtop.Client, manager *accountmanager.Manager, automation OrderAutomation, notifier OrderNotifier, updateCookie func(context.Context, string, string), recoverSession func(context.Context, string, error) bool) OrderRuntimeHooks { + return OrderRuntimeHooks{ + Client: client, + ClientAvailable: func() bool { return client != nil && client() != nil }, + AccountRunning: AccountRunningLookup(manager), + AutomationReady: func() bool { return manager != nil && automation != nil }, + ManualFullDelivery: func(ctx context.Context, order *orderapp.Order) (int, error) { + if automation == nil { + return 0, errors.New("自动化中心未初始化") + } + return automation.ManualFullDelivery(ctx, OrderForAutomation(order)) + }, + UpdateRunningCookie: updateCookie, + NotifyDelivery: func(cookieID, buyerID, itemID, chatID, message string) { + if notifier != nil { + notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID) + } + }, + RecoverExpiredSession: recoverSession, + } +} + // OrderRuntime 将订单应用 Port 适配到数据库凭证、MTOP 和账号运行时。 type OrderRuntime struct { // store 提供订单确认发货所需的平台凭证读取和 Cookie 写回能力。 diff --git a/internal/adapter/order_runtime_test.go b/internal/adapter/order_runtime_test.go index f4e5ae1..9415b07 100644 --- a/internal/adapter/order_runtime_test.go +++ b/internal/adapter/order_runtime_test.go @@ -6,9 +6,33 @@ import ( "testing" orderapp "xianyu-go/internal/application/orders" + "xianyu-go/internal/db" "xianyu-go/internal/xianyu/mtop" ) +// orderRuntimeAutomationFake 是订单运行时测试使用的自动化能力替身。 +type orderRuntimeAutomationFake struct { + // calls 记录自动化完整发货调用次数。 + calls int +} + +// ManualFullDelivery 返回固定发送数量,验证 adapter 的订单模型转换回调。 +func (f *orderRuntimeAutomationFake) ManualFullDelivery(context.Context, *db.Order) (int, error) { + f.calls++ + return 2, nil +} + +// orderRuntimeNotifierFake 是订单运行时测试使用的通知能力替身。 +type orderRuntimeNotifierFake struct { + // calls 记录发货通知调用次数。 + calls int +} + +// NotifyDelivery 记录一次发货通知调用。 +func (f *orderRuntimeNotifierFake) NotifyDelivery(string, string, string, string, string, string) { + f.calls++ +} + // orderRuntimeMTopFake 是订单运行时测试使用的平台客户端替身。 type orderRuntimeMTopFake struct { // consign 保存确认发货调用结果函数。 @@ -51,6 +75,38 @@ func (f *orderRuntimeMTopFake) RefreshTokenWithDeviceIDContext(context.Context, return nil, errors.New("订单测试未预期令牌请求") } +// TestNewOrderRuntimeHooksUsesTypedOptionalServices 验证订单运行时依赖由 adapter typed port 统一转换并安全处理空依赖。 +func TestNewOrderRuntimeHooksUsesTypedOptionalServices(t *testing.T) { + // emptyHooks 保存缺少可选服务时的回调集合。 + emptyHooks := NewOrderRuntimeHooks(nil, nil, nil, nil, nil, nil) + if emptyHooks.AutomationReady() || emptyHooks.ClientAvailable() || emptyHooks.AccountRunning("missing") { + t.Fatal("空依赖不应报告订单运行时能力可用") + } + // err 保存空自动化能力执行完整发货时返回的初始化错误。 + if _, err := emptyHooks.ManualFullDelivery(context.Background(), &orderapp.Order{}); err == nil { + t.Fatal("空自动化依赖应返回错误") + } + emptyHooks.NotifyDelivery("cookie", "buyer", "item", "chat", "message") + + // automation、notifier 保存 typed port 测试替身。 + automation := &orderRuntimeAutomationFake{} + // notifier 保存记录通知调用次数的 typed port 测试替身。 + notifier := &orderRuntimeNotifierFake{} + // hooks 保存已装配可选服务的订单运行时回调集合。 + hooks := NewOrderRuntimeHooks(nil, nil, automation, notifier, nil, nil) + if hooks.AutomationReady() { + t.Fatal("缺少账号 Manager 时不应报告完整自动化已就绪") + } + // sent、err 保存完整发货回调的发送数量和执行错误。 + if sent, err := hooks.ManualFullDelivery(context.Background(), &orderapp.Order{OrderID: "order-1"}); err != nil || sent != 2 || automation.calls != 1 { + t.Fatalf("自动化回调未正确转发: sent=%d err=%v calls=%d", sent, err, automation.calls) + } + hooks.NotifyDelivery("cookie", "buyer", "item", "chat", "message") + if notifier.calls != 1 { + t.Fatalf("通知回调次数=%d,期望 1", notifier.calls) + } +} + // TestOrderRuntimeConfirmShipmentPersistsCookie 验证确认发货成功会写回平台返回的新 Cookie。 func TestOrderRuntimeConfirmShipmentPersistsCookie(t *testing.T) { // store、cleanup 保存测试数据库和资源清理函数。 diff --git a/internal/adapter/platform_compat.go b/internal/adapter/platform_compat.go new file mode 100644 index 0000000..65b2fb4 --- /dev/null +++ b/internal/adapter/platform_compat.go @@ -0,0 +1,38 @@ +package adapter + +import ( + "context" + "log/slog" + + "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/qrlogin" + xrenew "xianyu-go/internal/xianyu/renew" +) + +// MTOPClient 是平台装配边界使用的客户端别名,避免上层依赖具体 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) +} + +// 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{} +} diff --git a/internal/adapter/platform_dependencies.go b/internal/adapter/platform_dependencies.go new file mode 100644 index 0000000..b64c21d --- /dev/null +++ b/internal/adapter/platform_dependencies.go @@ -0,0 +1,64 @@ +package adapter + +import ( + "errors" + "log/slog" +) + +// PlatformDependencies 保存 HTTP 应用装配所需的平台客户端;Server 只能通过本类型读取这些能力。 +// 旧的 Server 字段仅作为阶段性测试兼容入口保留,待所有调用方迁移后删除。 +type PlatformDependencies struct { + // mtopClient 承担 MTOP 请求与订单、商品、账号资料等平台操作。 + mtopClient MTOPClient + // longLoginClient 承担长登录状态查询、更新及响应 Cookie 返回。 + longLoginClient LongLoginClient + // qrLoginService 承担二维码生成、状态轮询和风控验证完成。 + qrLoginService QRLoginService +} + +// NewPlatformDependencies 构造并校验平台客户端集合,拒绝半初始化依赖进入 Server。 +func NewPlatformDependencies(mtopClient MTOPClient, longLoginClient LongLoginClient, qrLoginService QRLoginService) (*PlatformDependencies, error) { + if mtopClient == nil { + return nil, errors.New("平台依赖 MTOP 客户端不能为空") + } + if longLoginClient == nil { + return nil, errors.New("平台依赖长登录客户端不能为空") + } + if qrLoginService == nil { + return nil, errors.New("平台依赖二维码服务不能为空") + } + return &PlatformDependencies{ + mtopClient: mtopClient, + longLoginClient: longLoginClient, + qrLoginService: qrLoginService, + }, nil +} + +// NewDefaultPlatformDependencies 创建生产环境使用的完整平台客户端集合。 +func NewDefaultPlatformDependencies(logger *slog.Logger) (*PlatformDependencies, error) { + return NewPlatformDependencies(NewMTOPClient(), NewLongLoginClient(), NewQRLoginService(logger)) +} + +// MTOPClient 返回已校验的 MTOP 客户端;返回值不含账号 Cookie 或其他敏感数据。 +func (d *PlatformDependencies) MTOPClient() MTOPClient { + if d == nil { + return nil + } + return d.mtopClient +} + +// LongLoginClient 返回已校验的长登录客户端;调用方负责控制凭证读取和持久化范围。 +func (d *PlatformDependencies) LongLoginClient() LongLoginClient { + if d == nil { + return nil + } + return d.longLoginClient +} + +// QRLoginService 返回已校验的二维码服务;平台会话状态仍由该服务自身负责生命周期。 +func (d *PlatformDependencies) QRLoginService() QRLoginService { + if d == nil { + return nil + } + return d.qrLoginService +} diff --git a/internal/adapter/platform_dependencies_test.go b/internal/adapter/platform_dependencies_test.go new file mode 100644 index 0000000..564d965 --- /dev/null +++ b/internal/adapter/platform_dependencies_test.go @@ -0,0 +1,91 @@ +package adapter + +import ( + "context" + "strings" + "testing" + + "xianyu-go/internal/xianyu/renew" +) + +// platformDependenciesQRFake 是平台依赖测试使用的二维码服务替身。 +type platformDependenciesQRFake struct{} + +// GenerateQRCode 返回固定会话数据,验证依赖边界不会改写二维码协议。 +func (platformDependenciesQRFake) GenerateQRCode(context.Context) (string, string, error) { + return "session", "https://example.test/qr", nil +} + +// GetSessionStatus 返回最小状态对象,验证二维码服务可以通过边界读取。 +func (platformDependenciesQRFake) GetSessionStatus(string) map[string]any { + return map[string]any{"status": "waiting"} +} + +// CompleteVerification 返回固定验证结果,避免测试输出任何真实凭证。 +func (platformDependenciesQRFake) CompleteVerification(context.Context, string) (string, string, error) { + return "masked-cookie", "account", nil +} + +// TestNewPlatformDependenciesRejectsIncomplete 验证平台依赖不得以半初始化状态进入 Server。 +func TestNewPlatformDependenciesRejectsIncomplete(t *testing.T) { + // qrService 是测试使用的二维码能力替身。 + qrService := platformDependenciesQRFake{} + // cases 保存每个缺失必需能力的构造场景和预期错误关键字。 + cases := []struct { + name string + mtop MTOPClient + long LongLoginClient + qr QRLoginService + want string + }{ + {name: "mtop", long: renew.Service{}, qr: qrService, want: "MTOP"}, + {name: "long_login", mtop: NewMTOPClient(), qr: qrService, want: "长登录"}, + {name: "qr_login", mtop: NewMTOPClient(), long: renew.Service{}, want: "二维码"}, + } + // testCase 表示当前平台能力缺失场景,循环变量仅用于表格驱动测试。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // dependencies、err 保存本次构造结果及校验错误。 + dependencies, err := NewPlatformDependencies(testCase.mtop, testCase.long, testCase.qr) + if err == nil || !strings.Contains(err.Error(), testCase.want) { + t.Fatalf("NewPlatformDependencies error = %v, want substring %q", err, testCase.want) + } + if dependencies != nil { + t.Fatalf("缺失依赖时不应返回平台依赖实例") + } + }) + } +} + +// TestPlatformDependenciesAccessorsExposeInjectedClients 验证访问器只返回构造时注入的客户端。 +func TestPlatformDependenciesAccessorsExposeInjectedClients(t *testing.T) { + // mtopClient、longLoginClient 和 qrService 保存本测试注入的三个独立能力。 + mtopClient := NewMTOPClient() + // longLoginClient 是本测试注入的长登录协议替身。 + longLoginClient := renew.Service{} + // qrService 是本测试注入的二维码协议替身。 + qrService := platformDependenciesQRFake{} + // dependencies、err 保存平台依赖边界及构造结果。 + dependencies, err := NewPlatformDependencies(mtopClient, longLoginClient, qrService) + if err != nil { + t.Fatalf("NewPlatformDependencies: %v", err) + } + if dependencies.MTOPClient() != mtopClient { + t.Fatalf("MTOPClient 未返回注入客户端") + } + if dependencies.LongLoginClient() != longLoginClient { + t.Fatalf("LongLoginClient 未返回注入客户端") + } + if dependencies.QRLoginService() != qrService { + t.Fatalf("QRLoginService 未返回注入客户端") + } +} + +// TestPlatformDependenciesNilAccessors 验证 nil 接收者访问器安全返回 nil,便于错误路径诊断。 +func TestPlatformDependenciesNilAccessors(t *testing.T) { + // dependencies 显式保持 nil,模拟 Server 构造前的平台依赖缺失。 + var dependencies *PlatformDependencies + if dependencies.MTOPClient() != nil || dependencies.LongLoginClient() != nil || dependencies.QRLoginService() != nil { + t.Fatalf("nil 平台依赖访问器必须返回 nil") + } +} diff --git a/internal/adapter/server_dependencies.go b/internal/adapter/server_dependencies.go deleted file mode 100644 index ba02473..0000000 --- a/internal/adapter/server_dependencies.go +++ /dev/null @@ -1,216 +0,0 @@ -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/session_recovery.go b/internal/adapter/session_recovery.go new file mode 100644 index 0000000..9673b18 --- /dev/null +++ b/internal/adapter/session_recovery.go @@ -0,0 +1,24 @@ +package adapter + +import ( + "context" + "log/slog" +) + +// SessionRecoveryHandler 是平台会话错误到账号恢复运行时的最小适配回调。 +// 回调只在确认错误属于 Session 失效时触发,调用方不会收到 Cookie 或 Token。 +type SessionRecoveryHandler func(context.Context, string, error) bool + +// NewSessionRecoveryHandler 创建统一的平台会话恢复回调。 +// recoverFunc 只负责请求账号运行时恢复;本适配器负责识别平台错误和记录脱敏诊断。 +func NewSessionRecoveryHandler(logger *slog.Logger, recoverFunc func(context.Context, string) bool) SessionRecoveryHandler { + return func(ctx context.Context, accountID string, err error) bool { + if !IsSessionExpiredError(err) || recoverFunc == nil { + return false + } + if logger != nil { + logger.Warn("MTOP API 检测到 Session 过期,停止业务请求并开始即时续期", "account", accountID, "err", err) + } + return recoverFunc(ctx, accountID) + } +} diff --git a/internal/adapter/session_recovery_test.go b/internal/adapter/session_recovery_test.go new file mode 100644 index 0000000..5657377 --- /dev/null +++ b/internal/adapter/session_recovery_test.go @@ -0,0 +1,42 @@ +package adapter + +import ( + "context" + "errors" + "testing" +) + +// TestSessionRecoveryHandlerFiltersNonExpiredErrors 验证普通平台错误不会触发账号恢复。 +func TestSessionRecoveryHandlerFiltersNonExpiredErrors(t *testing.T) { + // calls 记录恢复端口被调用次数。 + calls := 0 + // handler 是绑定测试恢复端口的会话恢复适配器。 + handler := NewSessionRecoveryHandler(nil, func(context.Context, string) bool { + calls++ + return true + }) + // recovered 表示普通错误的恢复结果。 + recovered := handler(context.Background(), "acc1", errors.New("ordinary failure")) + if recovered || calls != 0 { + t.Fatalf("普通错误不应触发恢复: recovered=%v calls=%d", recovered, calls) + } +} + +// TestSessionRecoveryHandlerDelegatesExpiredErrors 验证 Session 失效只触发一次恢复端口。 +func TestSessionRecoveryHandlerDelegatesExpiredErrors(t *testing.T) { + // calls 记录恢复端口被调用次数。 + calls := 0 + // handler 是绑定测试恢复端口的会话恢复适配器。 + handler := NewSessionRecoveryHandler(nil, func(_ context.Context, accountID string) bool { + if accountID != "acc1" { + t.Fatalf("恢复账号错误: %q", accountID) + } + calls++ + return true + }) + // recovered 表示已识别 Session 失效后的恢复结果。 + recovered := handler(context.Background(), "acc1", errors.New("FAIL_SYS_SESSION_EXPIRED")) + if !recovered || calls != 1 { + t.Fatalf("Session 失效未正确委托: recovered=%v calls=%d", recovered, calls) + } +} diff --git a/internal/adapter/system_dependencies.go b/internal/adapter/system_dependencies.go new file mode 100644 index 0000000..bf2aa7c --- /dev/null +++ b/internal/adapter/system_dependencies.go @@ -0,0 +1,38 @@ +package adapter + +import ( + "log/slog" + + "xianyu-go/internal/db" + "xianyu-go/internal/reconciliation" +) + +// SystemDependencies 封装健康检查与订单补偿扫描所需的系统级适配器。 +type SystemDependencies struct { + // store 保存系统适配器共享的数据库入口,仅在 adapter 内部使用。 + store *db.Store +} + +// NewSystemDependencies 从数据库 Store 构造系统专用依赖组。 +func NewSystemDependencies(store *db.Store) *SystemDependencies { + if store == nil { + return nil + } + return &SystemDependencies{store: store} +} + +// NewDatabaseHealth 创建数据库健康检查适配器。 +func (d *SystemDependencies) NewDatabaseHealth() *DatabaseHealth { + if d == nil { + return nil + } + return NewDatabaseHealth(d.store) +} + +// NewReconciliationService 创建外部发货成功后的本地补偿扫描服务。 +func (d *SystemDependencies) NewReconciliationService(logger *slog.Logger) *reconciliation.Service { + if d == nil { + return nil + } + return reconciliation.New(d.store, logger) +} diff --git a/internal/adapter/system_dependencies_test.go b/internal/adapter/system_dependencies_test.go new file mode 100644 index 0000000..55e27a1 --- /dev/null +++ b/internal/adapter/system_dependencies_test.go @@ -0,0 +1,12 @@ +package adapter + +import "testing" + +// TestNewSystemDependenciesRejectsNilStore 确保系统级适配器不会在缺少数据库入口时构造成功。 +func TestNewSystemDependenciesRejectsNilStore(t *testing.T) { + // dependencies 保存缺少 Store 时的系统依赖构造结果。 + dependencies := NewSystemDependencies(nil) + if dependencies != nil { + t.Fatal("缺少 Store 时不应返回系统依赖") + } +} diff --git a/internal/adapter/transaction_test.go b/internal/adapter/transaction_test.go index 85a8e78..696cf2d 100644 --- a/internal/adapter/transaction_test.go +++ b/internal/adapter/transaction_test.go @@ -3,6 +3,7 @@ package adapter import ( "context" "database/sql" + "errors" "testing" "xianyu-go/internal/db" @@ -31,3 +32,53 @@ func TestTransactionRepositoryRejectsMissingDependencies(t *testing.T) { t.Fatal("缺少事务工作函数时不应伪装成功") } } + +// TestTransactionRepositoryCommitsAndRollsBack 验证事务适配器提交成功操作并回滚失败操作。 +func TestTransactionRepositoryCommitsAndRollsBack(t *testing.T) { + // database、dialect 和 openErr 保存最小 SQLite 数据库装配结果。 + database, dialect, openErr := db.Open(context.Background(), t.TempDir()+"/transaction-commit.db") + if openErr != nil { + t.Fatalf("打开测试数据库失败: %v", openErr) + } + defer database.Close() + // repository 是当前测试使用的数据库事务适配器。 + repository := NewTransactionRepository(db.NewStore(database, dialect)) + // ctx 是本测试使用的背景上下文。 + ctx := context.Background() + // createErr 表示创建事务测试表时的数据库错误。 + if _, createErr := database.ExecContext(ctx, `CREATE TABLE transaction_probe (id INTEGER PRIMARY KEY, value TEXT NOT NULL)`); createErr != nil { + t.Fatalf("创建事务测试表失败: %v", createErr) + } + // commitErr 表示成功事务的执行结果。 + commitErr := repository.WithTransaction(ctx, func(tx *sql.Tx) error { + // execErr 表示事务内插入成功记录时的数据库错误。 + _, execErr := tx.ExecContext(ctx, `INSERT INTO transaction_probe (id, value) VALUES (1, 'committed')`) + return execErr + }) + if commitErr != nil { + t.Fatalf("事务提交失败: %v", commitErr) + } + // rollbackErr 是故意返回的错误,用于验证事务不会提交部分写入。 + rollbackErr := errors.New("故意回滚") + // returnedErr 表示回滚事务向调用方传播的错误。 + returnedErr := repository.WithTransaction(ctx, func(tx *sql.Tx) error { + // execErr 表示事务内插入回滚记录时的数据库错误。 + _, execErr := tx.ExecContext(ctx, `INSERT INTO transaction_probe (id, value) VALUES (2, 'rolled back')`) + if execErr != nil { + return execErr + } + return rollbackErr + }) + if !errors.Is(returnedErr, rollbackErr) { + t.Fatalf("事务回滚错误不匹配: %v", returnedErr) + } + // count 是事务最终提交后测试表中的记录数。 + var count int + // scanErr 表示读取事务测试表统计结果时的数据库错误。 + if scanErr := database.QueryRowContext(ctx, `SELECT COUNT(*) FROM transaction_probe`).Scan(&count); scanErr != nil { + t.Fatalf("查询事务测试结果失败: %v", scanErr) + } + if count != 1 { + t.Fatalf("事务回滚后记录数应为 1,got %d", count) + } +} diff --git a/internal/adapter/typed_dependencies_contract_test.go b/internal/adapter/typed_dependencies_contract_test.go new file mode 100644 index 0000000..ffc45d3 --- /dev/null +++ b/internal/adapter/typed_dependencies_contract_test.go @@ -0,0 +1,31 @@ +package adapter + +import "testing" + +// TestTypedDependenciesCoverServerAssembly 验证领域依赖组覆盖 Server 应用装配所需的全部基础设施边界。 +func TestTypedDependenciesCoverServerAssembly(t *testing.T) { + // store、cleanup 保存测试用数据库聚合及其资源释放函数。 + store, cleanup := newAdapterTestStore(t) + defer cleanup() + // orderDependencies 保存订单应用所需的显式依赖组。 + orderDependencies, orderErr := NewOrderDependencies(store) + // accountDependencies 保存账号应用所需的显式依赖组。 + accountDependencies, accountErr := NewAccountDependencies(store) + // itemDependencies 保存商品应用所需的显式依赖组。 + itemDependencies, itemErr := NewItemDependencies(store) + // automationDependencies 保存自动化应用所需的显式依赖组。 + automationDependencies, automationErr := NewAutomationDependencies(store) + // miscDependencies 保存通知、分析和卡券应用所需的显式依赖组。 + miscDependencies, miscErr := NewMiscDependencies(store) + // chatDependencies 保存聊天应用所需的显式依赖组。 + chatDependencies := NewChatDependencies(store) + // systemDependencies 保存系统健康检查和补偿扫描所需的显式依赖组。 + systemDependencies := NewSystemDependencies(store) + // adminSettingsDependencies 保存管理员和设置应用所需的显式依赖组。 + adminSettingsDependencies := NewAdminSettingsDependencies(store) + // platformDependencies 保存平台客户端和二维码能力所需的显式依赖组。 + platformDependencies, platformErr := NewDefaultPlatformDependencies(nil) + if orderErr != nil || accountErr != nil || itemErr != nil || automationErr != nil || miscErr != nil || orderDependencies == nil || accountDependencies == nil || itemDependencies == nil || automationDependencies == nil || miscDependencies == nil || chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil || platformErr != nil || platformDependencies == nil { + t.Fatalf("显式领域依赖组未完整覆盖 Server 装配: order=%v account=%v item=%v automation=%v misc=%v chat=%v system=%v admin=%v platform=%v", orderErr, accountErr, itemErr, automationErr, miscErr, chatDependencies != nil, systemDependencies != nil, adminSettingsDependencies != nil, platformErr) + } +} diff --git a/internal/application/account/credential_refresh_coordinator.go b/internal/application/account/credential_refresh_coordinator.go new file mode 100644 index 0000000..68c84cf --- /dev/null +++ b/internal/application/account/credential_refresh_coordinator.go @@ -0,0 +1,72 @@ +package account + +import ( + "context" + "errors" + "sync" +) + +// ErrCredentialRefreshInFlight 表示同一账号已有凭证恢复操作正在执行。 +var ErrCredentialRefreshInFlight = errors.New("账号凭证恢复正在执行") + +// CredentialRefreshWork 执行一次账号凭证恢复;返回值表示是否已恢复可用凭证,错误保留底层失败原因。 +type CredentialRefreshWork func(context.Context) (bool, error) + +// CredentialRefreshCoordinator 按账号串行化凭证恢复,保证慢速外部 I/O 不在锁内执行。 +// mu 只保护 inFlight;work 在释放协调状态后仍由调用方负责其自身凭证快照和提交边界。 +type CredentialRefreshCoordinator struct { + // mu 保护 inFlight 的账号集合;持锁期间只做集合操作,不调用外部服务。 + mu sync.Mutex + // inFlight 记录当前正在恢复的账号,任务结束、报错、取消或 panic 后必须移除。 + inFlight map[string]struct{} +} + +// NewCredentialRefreshCoordinator 创建空的账号凭证恢复协调器。 +func NewCredentialRefreshCoordinator() *CredentialRefreshCoordinator { + return &CredentialRefreshCoordinator{inFlight: make(map[string]struct{})} +} + +// TryBegin 尝试登记账号恢复;成功时调用方必须在 defer 中执行 Finish,即使工作返回错误或 panic。 +func (c *CredentialRefreshCoordinator) TryBegin(accountID string) bool { + if c == nil { + return false + } + c.mu.Lock() + defer c.mu.Unlock() + if c.inFlight == nil { + c.inFlight = make(map[string]struct{}) + } + // exists 表示该账号是否已有恢复工作登记,命中时拒绝并发外部续期。 + if _, exists := c.inFlight[accountID]; exists { + return false + } + c.inFlight[accountID] = struct{}{} + return true +} + +// Finish 清除账号恢复登记;重复调用保持幂等,便于兼容旧调用方的收尾路径。 +func (c *CredentialRefreshCoordinator) Finish(accountID string) { + if c == nil { + return + } + c.mu.Lock() + defer c.mu.Unlock() + delete(c.inFlight, accountID) +} + +// Run 在账号范围内执行一项恢复工作,并在所有返回路径后释放登记状态。 +// accepted 为 false 时表示已有同账号工作在执行;work 的错误和取消上下文由调用方继续记录。 +func (c *CredentialRefreshCoordinator) Run(ctx context.Context, accountID string, work CredentialRefreshWork) (accepted, renewed bool, err error) { + if c == nil { + return false, false, errors.New("账号凭证恢复协调器未初始化") + } + if !c.TryBegin(accountID) { + return false, false, ErrCredentialRefreshInFlight + } + defer c.Finish(accountID) + if work == nil { + return true, false, errors.New("账号凭证恢复工作未提供") + } + renewed, err = work(ctx) + return true, renewed, err +} diff --git a/internal/application/account/credential_refresh_coordinator_test.go b/internal/application/account/credential_refresh_coordinator_test.go new file mode 100644 index 0000000..636a9ef --- /dev/null +++ b/internal/application/account/credential_refresh_coordinator_test.go @@ -0,0 +1,146 @@ +package account + +import ( + "context" + "errors" + "sync" + "testing" +) + +// TestCredentialRefreshCoordinatorSerializesSameAccount 验证同一账号只允许一个恢复回调运行。 +func TestCredentialRefreshCoordinatorSerializesSameAccount(t *testing.T) { + // coordinator 保存待测试的账号恢复协调器。 + coordinator := NewCredentialRefreshCoordinator() + // entered 用于让首个恢复回调保持执行状态。 + entered := make(chan struct{}) + // release 用于控制首个恢复回调何时完成。 + release := make(chan struct{}) + // firstDone 保存首个恢复调用的结果。 + firstDone := make(chan error, 1) + go func() { + // accepted、renewed、runErr 保存首个恢复回调的协调结果。 + // accepted、renewed、runErr 保存首个恢复回调的登记结果、凭证结果和错误。 + accepted, renewed, runErr := coordinator.Run(context.Background(), "account-1", func(context.Context) (bool, error) { + close(entered) + <-release + return true, nil + }) + if !accepted || !renewed { + firstDone <- errors.New("首个恢复调用未成功登记") + return + } + firstDone <- runErr + }() + <-entered + // accepted、renewed、runErr 保存重复恢复调用的协调结果。 + accepted, renewed, runErr := coordinator.Run(context.Background(), "account-1", func(context.Context) (bool, error) { + return true, nil + }) + if accepted || renewed || !errors.Is(runErr, ErrCredentialRefreshInFlight) { + t.Fatalf("重复恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr) + } + close(release) + // runErr 保存首个恢复回调完成后的错误。 + if runErr := <-firstDone; runErr != nil { + t.Fatalf("首个恢复错误: %v", runErr) + } + // accepted、renewed、runErr 保存首个调用结束后再次恢复的结果。 + accepted, renewed, runErr = coordinator.Run(context.Background(), "account-1", func(context.Context) (bool, error) { + return true, nil + }) + if !accepted || !renewed || runErr != nil { + t.Fatalf("完成后恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr) + } +} + +// TestCredentialRefreshCoordinatorReleasesOnErrorAndCancellation 验证错误与取消均不会遗留账号占用状态。 +func TestCredentialRefreshCoordinatorReleasesOnErrorAndCancellation(t *testing.T) { + // coordinator 保存待测试的账号恢复协调器。 + coordinator := NewCredentialRefreshCoordinator() + // expectedErr 保存恢复回调预置的业务错误。 + expectedErr := errors.New("renew failed") + // accepted、renewed、runErr 保存错误恢复回调的协调结果。 + accepted, renewed, runErr := coordinator.Run(context.Background(), "account-2", func(context.Context) (bool, error) { + return false, expectedErr + }) + if !accepted || renewed || !errors.Is(runErr, expectedErr) { + t.Fatalf("错误恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr) + } + // canceled、cancel 保存已取消的恢复上下文及其释放函数。 + canceled, cancel := context.WithCancel(context.Background()) + cancel() + // accepted、renewed、runErr 保存取消恢复回调的协调结果。 + accepted, renewed, runErr = coordinator.Run(canceled, "account-2", func(ctx context.Context) (bool, error) { + return false, ctx.Err() + }) + if !accepted || renewed || !errors.Is(runErr, context.Canceled) { + t.Fatalf("取消恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr) + } +} + +// TestCredentialRefreshCoordinatorReleasesAfterPanic 验证回调 panic 仍会释放账号登记状态。 +func TestCredentialRefreshCoordinatorReleasesAfterPanic(t *testing.T) { + // coordinator 保存待测试的账号恢复协调器。 + coordinator := NewCredentialRefreshCoordinator() + // panicked 标记是否捕获到预期 panic。 + panicked := false + func() { + defer func() { + if recover() != nil { + panicked = true + } + }() + coordinator.Run(context.Background(), "account-3", func(context.Context) (bool, error) { + panic("test panic") + }) + }() + if !panicked { + t.Fatal("恢复回调 panic 应向调用方传播") + } + // accepted、renewed、runErr 保存 panic 后重新执行的结果。 + accepted, renewed, runErr := coordinator.Run(context.Background(), "account-3", func(context.Context) (bool, error) { + return true, nil + }) + if !accepted || !renewed || runErr != nil { + t.Fatalf("panic 后恢复结果 accepted=%v renewed=%v err=%v", accepted, renewed, runErr) + } +} + +// TestCredentialRefreshCoordinatorSupportsConcurrentDifferentAccounts 验证不同账号可以并行恢复且不共享占用状态。 +func TestCredentialRefreshCoordinatorSupportsConcurrentDifferentAccounts(t *testing.T) { + // coordinator 保存待测试的账号恢复协调器。 + coordinator := NewCredentialRefreshCoordinator() + // start 用于同步两个账号的回调开始时机。 + start := make(chan struct{}) + // results 保存两个账号恢复调用的结果。 + results := make(chan error, 2) + // waitGroup 等待两个独立账号的恢复调用结束。 + var waitGroup sync.WaitGroup + waitGroup.Add(2) + // accountID 表示当前并行恢复测试正在处理的账号标识。 + for _, accountID := range []string{"account-4", "account-5"} { + // currentAccount 保存当前并行恢复的账号标识。 + currentAccount := accountID + go func() { + defer waitGroup.Done() + // accepted、renewed、runErr 保存当前账号恢复结果。 + accepted, renewed, runErr := coordinator.Run(context.Background(), currentAccount, func(context.Context) (bool, error) { + <-start + return true, nil + }) + if !accepted || !renewed { + results <- errors.New("独立账号未成功恢复") + return + } + results <- runErr + }() + } + close(start) + waitGroup.Wait() + for range 2 { + // runErr 保存并行账号恢复回调的错误。 + if runErr := <-results; runErr != nil { + t.Fatalf("并行恢复错误: %v", runErr) + } + } +} diff --git a/internal/application/account/credential_repository.go b/internal/application/account/credential_repository.go index abbb5d3..06975b2 100644 --- a/internal/application/account/credential_repository.go +++ b/internal/application/account/credential_repository.go @@ -43,3 +43,10 @@ type CredentialRepository interface { // UpdateProfile 保存不含凭证的账号展示资料。 UpdateProfile(context.Context, string, string, string) error } + +// CredentialSessionPort 定义平台响应 Cookie 会话写回所需的最小凭证端口。 +// 该端口不包含账号查询、锁管理或登录秘密方法,调用方必须在外层完成凭证锁和快照复核。 +type CredentialSessionPort interface { + // UpdateRenewalCookie 保存平台返回的 Cookie 与 metadata;明文仅在适配器内短暂存在。 + UpdateRenewalCookie(context.Context, string, string, string, int64) error +} diff --git a/internal/application/account/login_success_service.go b/internal/application/account/login_success_service.go new file mode 100644 index 0000000..81cbb32 --- /dev/null +++ b/internal/application/account/login_success_service.go @@ -0,0 +1,67 @@ +package account + +import "context" + +// LoginStatusPort 定义登录成功后判断账号是否启用所需的最小状态查询能力。 +type LoginStatusPort interface { + // GetStatus 返回账号当前是否启用;该查询不读取或解密凭证内容。 + GetStatus(context.Context, string) bool +} + +// LoginRestartPort 定义登录成功后重启账号运行时所需的最小能力。 +type LoginRestartPort interface { + // Restart 使用刚写入的持久化凭证重启账号运行实例。 + Restart(context.Context, string) error +} + +// LoginSuccessService 编排登录成功后的资料刷新与运行时重启,不依赖 HTTP 或 Server。 +type LoginSuccessService struct { + // summaries 提供不含秘密的账号归属确认能力。 + summaries ProfileSummaryRepository + // profile 负责平台资料刷新和本地资料持久化。 + profile *ProfileService + // statuses 提供账号启用状态查询能力。 + statuses LoginStatusPort + // runtime 提供账号运行时重启能力。 + runtime LoginRestartPort + // report 记录不含凭证的后续动作错误;为空时忽略诊断。 + report func(string, error) +} + +// NewLoginSuccessService 构造登录成功后的应用编排服务。 +func NewLoginSuccessService(summaries ProfileSummaryRepository, profile *ProfileService, statuses LoginStatusPort, runtime LoginRestartPort, report func(string, error)) *LoginSuccessService { + return &LoginSuccessService{summaries: summaries, profile: profile, statuses: statuses, runtime: runtime, report: report} +} + +// AfterSuccessfulLogin 在凭证锁释放后刷新资料并按账号启用状态重启运行时。 +func (s *LoginSuccessService) AfterSuccessfulLogin(ctx context.Context, userID int64, accountID string) { + if s == nil { + return + } + if s.summaries != nil { + // summaryErr 保存登录成功后归属摘要复核错误;失败时跳过资料刷新但不阻断重启。 + _, summaryErr := s.summaries.GetOwnedSummary(ctx, userID, accountID) + if summaryErr == nil && s.profile != nil { + // result 和 profileErr 保存资料刷新结果及基础设施错误。 + result, profileErr := s.profile.RefreshProfile(ctx, userID, accountID) + if profileErr != nil { + s.reportError("登录后刷新账号资料失败", profileErr) + } else if result.ErrorMessage != "" { + s.reportError("登录后刷新账号资料返回业务错误", nil) + } + } + } + if s.statuses != nil && s.statuses.GetStatus(ctx, accountID) && s.runtime != nil { + // restartErr 保存登录成功后运行时重启错误。 + if restartErr := s.runtime.Restart(ctx, accountID); restartErr != nil { + s.reportError("账号登录后重启账号失败", restartErr) + } + } +} + +// reportError 统一传递登录成功后续动作的脱敏诊断。 +func (s *LoginSuccessService) reportError(message string, err error) { + if s.report != nil { + s.report(message, err) + } +} diff --git a/internal/application/account/login_success_service_test.go b/internal/application/account/login_success_service_test.go new file mode 100644 index 0000000..a0e914d --- /dev/null +++ b/internal/application/account/login_success_service_test.go @@ -0,0 +1,48 @@ +package account + +import ( + "context" + "testing" +) + +// loginSuccessStatusFake 保存登录成功编排测试中的启用状态。 +type loginSuccessStatusFake struct{ enabled bool } + +// GetStatus 返回测试账号启用状态。 +func (f loginSuccessStatusFake) GetStatus(context.Context, string) bool { return f.enabled } + +// loginSuccessRuntimeFake 记录登录成功后的重启请求。 +type loginSuccessRuntimeFake struct{ restarts int } + +// Restart 记录一次账号运行时重启。 +func (f *loginSuccessRuntimeFake) Restart(context.Context, string) error { + f.restarts++ + return nil +} + +// TestLoginSuccessServiceSkipsMissingOptionalPorts 验证缺少可选后续端口时不产生副作用。 +func TestLoginSuccessServiceSkipsMissingOptionalPorts(t *testing.T) { + // service 保存未装配后续端口的登录成功服务。 + service := NewLoginSuccessService(nil, nil, nil, nil, nil) + service.AfterSuccessfulLogin(context.Background(), 1, "account") +} + +// TestLoginSuccessServiceRestartsEnabledAccount 验证登录成功后仅对启用账号触发运行时重启。 +func TestLoginSuccessServiceRestartsEnabledAccount(t *testing.T) { + // runtime 保存登录成功后重启调用的测试端口。 + runtime := &loginSuccessRuntimeFake{} + // service 保存启用账号的登录成功编排服务。 + service := NewLoginSuccessService(nil, nil, loginSuccessStatusFake{enabled: true}, runtime, nil) + service.AfterSuccessfulLogin(context.Background(), 1, "account") + if runtime.restarts != 1 { + t.Fatalf("restarts=%d", runtime.restarts) + } + // disabledRuntime 保存停用账号使用的独立运行时端口。 + disabledRuntime := &loginSuccessRuntimeFake{} + // disabledService 保存停用账号的登录成功编排服务。 + disabledService := NewLoginSuccessService(nil, nil, loginSuccessStatusFake{}, disabledRuntime, nil) + disabledService.AfterSuccessfulLogin(context.Background(), 1, "account") + if disabledRuntime.restarts != 0 { + t.Fatalf("disabled account restarts=%d", disabledRuntime.restarts) + } +} diff --git a/internal/application/account/platform_credential_service.go b/internal/application/account/platform_credential_service.go new file mode 100644 index 0000000..5338c03 --- /dev/null +++ b/internal/application/account/platform_credential_service.go @@ -0,0 +1,77 @@ +package account + +import ( + "context" + "errors" +) + +// ErrCredentialEmpty 表示账号存在但没有可供平台调用的 Cookie。 +var ErrCredentialEmpty = errors.New("账号 Cookie 为空") + +// PlatformCredentialViewPort 定义读取平台调用窄凭证视图的最小消费者端口。 +// 实现方负责数据库查询与解密;调用方不得把返回的明文写入摘要、日志或 HTTP DTO。 +type PlatformCredentialViewPort interface { + // LoadPlatformDetail 读取指定账号的平台 Cookie 视图,不读取登录密码。 + LoadPlatformDetail(context.Context, string) (*CredentialDetail, error) +} + +// PlatformCredentialService 编排平台凭证窄视图读取和当前用户归属复核。 +// 该服务只在确有平台调用需要时返回 Cookie 明文,普通所有权检查不会返回敏感值。 +type PlatformCredentialService struct { + // port 保存由适配器实现的平台凭证读取端口;服务本身不依赖数据库类型。 + port PlatformCredentialViewPort +} + +// NewPlatformCredentialService 构造平台凭证只读应用服务并校验端口。 +func NewPlatformCredentialService(port PlatformCredentialViewPort) (*PlatformCredentialService, error) { + if port == nil { + return nil, errors.New("平台凭证读取端口未初始化") + } + return &PlatformCredentialService{port: port}, nil +} + +// LoadPlatformDetail 读取平台运行所需的窄视图;登录密码不会进入该调用链。 +func (s *PlatformCredentialService) LoadPlatformDetail(ctx context.Context, accountID string) (*CredentialDetail, error) { + if s == nil || s.port == nil { + return nil, errors.New("平台凭证读取服务未初始化") + } + return s.port.LoadPlatformDetail(ctx, accountID) +} + +// ValidateOwned 验证平台账号归属和 Cookie 可用性,只返回非敏感用户标识。 +func (s *PlatformCredentialService) ValidateOwned(ctx context.Context, userID int64, accountID string) (int64, error) { + // detail、loadErr 保存平台凭证窄视图及其读取错误;Cookie 只在本方法内部用于可用性判断。 + detail, loadErr := s.LoadPlatformDetail(ctx, accountID) + if loadErr != nil { + return 0, loadErr + } + if detail == nil || detail.ID == "" || detail.UserID == 0 { + return 0, ErrCredentialNotFound + } + if detail.UserID != userID { + return 0, ErrForbidden + } + if detail.Value == "" { + return 0, ErrCredentialEmpty + } + return detail.UserID, nil +} + +// LoadOwnedValue 读取已通过所有权复核的 Cookie 明文;返回值只用于当前平台请求。 +func (s *PlatformCredentialService) LoadOwnedValue(ctx context.Context, userID int64, accountID string) (string, error) { + // detail、loadErr 保存所有权复核使用的平台凭证视图及其读取错误。 + detail, loadErr := s.LoadPlatformDetail(ctx, accountID) + if loadErr != nil { + return "", loadErr + } + if detail == nil || detail.ID == "" || detail.UserID == 0 { + return "", ErrCredentialNotFound + } + if detail.UserID != userID { + return "", ErrCredentialNotFound + } + if detail.Value == "" { + return "", ErrCredentialEmpty + } + return detail.Value, nil +} diff --git a/internal/application/account/platform_credential_service_test.go b/internal/application/account/platform_credential_service_test.go new file mode 100644 index 0000000..6168a40 --- /dev/null +++ b/internal/application/account/platform_credential_service_test.go @@ -0,0 +1,89 @@ +package account + +import ( + "context" + "errors" + "testing" +) + +// platformCredentialPortFake 保存测试用平台凭证窄视图,不模拟数据库或加密实现。 +type platformCredentialPortFake struct { + // detail 是端口返回的最小平台凭证视图。 + detail *CredentialDetail + // err 是端口返回的读取错误。 + err error +} + +// TestNewPlatformCredentialServiceRejectsMissingPort 验证凭证读取服务不会接受半初始化端口。 +func TestNewPlatformCredentialServiceRejectsMissingPort(t *testing.T) { + // service、serviceErr 保存缺失端口时的构造结果。 + service, serviceErr := NewPlatformCredentialService(nil) + if service != nil || serviceErr == nil { + t.Fatalf("缺失凭证端口不应构造成功: service=%v err=%v", service, serviceErr) + } +} + +// LoadPlatformDetail 返回固定平台凭证视图,验证应用服务不要求数据库具体类型。 +func (f platformCredentialPortFake) LoadPlatformDetail(context.Context, string) (*CredentialDetail, error) { + return f.detail, f.err +} + +// TestPlatformCredentialServiceValidatesOwnedWithoutReturningCookie 验证归属校验只返回用户标识。 +func TestPlatformCredentialServiceValidatesOwnedWithoutReturningCookie(t *testing.T) { + // service 是使用最小凭证端口构造的平台凭证应用服务。 + service, serviceErr := NewPlatformCredentialService(platformCredentialPortFake{detail: &CredentialDetail{ID: "acc1", UserID: 7, Value: "sid=masked"}}) + if serviceErr != nil { + t.Fatalf("构造凭证服务失败: %v", serviceErr) + } + // ownerID、validationErr 保存归属校验的非敏感结果及错误。 + ownerID, validationErr := service.ValidateOwned(context.Background(), 7, "acc1") + if validationErr != nil || ownerID != 7 { + t.Fatalf("归属校验结果异常: owner=%d err=%v", ownerID, validationErr) + } +} + +// TestPlatformCredentialServiceRejectsForeignAndEmptyCredentials 验证越权和空 Cookie 均 fail closed。 +func TestPlatformCredentialServiceRejectsForeignAndEmptyCredentials(t *testing.T) { + // cases 描述不同平台凭证状态及期望的稳定应用错误。 + cases := []struct { + name string + detail *CredentialDetail + want error + }{ + {name: "foreign", detail: &CredentialDetail{ID: "acc1", UserID: 8, Value: "sid=masked"}, want: ErrForbidden}, + {name: "empty", detail: &CredentialDetail{ID: "acc1", UserID: 7}, want: ErrCredentialEmpty}, + } + // testCase 表示当前遍历的平台凭证状态用例。 + // testCase 表示当前遍历的凭证状态与预期错误。 + for _, testCase := range cases { + // testCase 是当前凭证状态用例,防止闭包捕获后续迭代变量。 + t.Run(testCase.name, func(t *testing.T) { + // service 是当前状态用例使用的平台凭证应用服务。 + service, serviceErr := NewPlatformCredentialService(platformCredentialPortFake{detail: testCase.detail}) + if serviceErr != nil { + t.Fatalf("构造凭证服务失败: %v", serviceErr) + } + // _, validationErr 保存归属校验错误;明文结果不会被测试输出。 + _, validationErr := service.ValidateOwned(context.Background(), 7, "acc1") + if !errors.Is(validationErr, testCase.want) { + t.Fatalf("错误类型=%v,期望=%v", validationErr, testCase.want) + } + }) + } +} + +// TestPlatformCredentialServicePropagatesPortErrors 验证基础设施错误不会被伪装成成功。 +func TestPlatformCredentialServicePropagatesPortErrors(t *testing.T) { + // portErr 是模拟凭证存储不可用的脱敏错误。 + portErr := errors.New("credential store unavailable") + // service 是绑定故障端口的平台凭证应用服务。 + service, serviceErr := NewPlatformCredentialService(platformCredentialPortFake{err: portErr}) + if serviceErr != nil { + t.Fatalf("构造凭证服务失败: %v", serviceErr) + } + // _, loadErr 保存平台凭证读取错误。 + _, loadErr := service.LoadPlatformDetail(context.Background(), "acc1") + if !errors.Is(loadErr, portErr) { + t.Fatalf("错误未透传: %v", loadErr) + } +} diff --git a/internal/application/account/qr_login_session_registry.go b/internal/application/account/qr_login_session_registry.go new file mode 100644 index 0000000..4762883 --- /dev/null +++ b/internal/application/account/qr_login_session_registry.go @@ -0,0 +1,232 @@ +package account + +import ( + "errors" + "sync" + "time" +) + +// ErrQRLoginSessionNotFound 表示扫码会话不存在或已经超过服务端保留期限。 +var ErrQRLoginSessionNotFound = errors.New("扫码会话不存在或已过期") + +// ErrQRLoginSessionForbidden 表示当前用户不是扫码会话的创建者。 +var ErrQRLoginSessionForbidden = errors.New("扫码会话不属于当前用户") + +// QRLoginSessionPersistence 是扫码成功后缓存的非敏感持久化结果,避免重复写入账号凭证。 +type QRLoginSessionPersistence struct { + // AccountID 是扫码结果最终写入的本地账号标识。 + AccountID string + // IsNew 表示本次扫码是否创建了新的本地账号。 + IsNew bool + // UserID 是创建该扫码会话的本地用户标识,用于阻止跨用户复用幂等结果。 + UserID int64 + // CreatedAt 是结果写入缓存的时间,仅用于诊断和生命周期观测。 + CreatedAt time.Time +} + +// QRLoginSessionRegistry 持有扫码会话所有权和幂等结果,Server 只通过方法访问这些状态。 +// mu 保护 owners 与 persisted;persistLocks 为每个会话串行化慢速凭证写入,锁内禁止持有 mu 调用外部 I/O。 +type QRLoginSessionRegistry struct { + mu sync.Mutex + owners map[string]qrLoginSessionOwner + persisted map[string]QRLoginSessionPersistence + persistLocks map[string]*qrLoginPersistenceLock + ownerLifetime time.Duration + now func() time.Time +} + +// qrLoginSessionOwner 保存扫码会话创建者和创建时间,不包含 Cookie 或平台 Token。 +type qrLoginSessionOwner struct { + // userID 是创建扫码会话的本地用户标识。 + userID int64 + // createdAt 是会话创建时间,用于服务端过期回收。 + createdAt time.Time +} + +// qrLoginPersistenceLock 保存单个扫码会话的串行锁及等待者计数,用于安全回收锁对象。 +type qrLoginPersistenceLock struct { + // mu 串行化该会话的凭证持久化回调;不与注册表主锁同时持有。 + mu sync.Mutex + // refs 统计已经取得该锁或正在等待该锁的调用数,避免回收时制造第二把锁。 + refs int +} + +// NewQRLoginSessionRegistry 创建扫码会话状态注册表,并设置默认三十分钟的 HTTP 所有权期限。 +func NewQRLoginSessionRegistry() *QRLoginSessionRegistry { + return &QRLoginSessionRegistry{ + owners: make(map[string]qrLoginSessionOwner), + persisted: make(map[string]QRLoginSessionPersistence), + persistLocks: make(map[string]*qrLoginPersistenceLock), + ownerLifetime: 30 * time.Minute, + now: time.Now, + } +} + +// Register 记录新扫码会话的创建者;重复会话标识会覆盖旧所有权,平台层负责保证标识唯一。 +func (r *QRLoginSessionRegistry) Register(sessionID string, userID int64, createdAt time.Time) { + if r == nil || sessionID == "" { + return + } + if createdAt.IsZero() { + createdAt = r.currentTime() + } + r.mu.Lock() + if r.owners == nil { + r.owners = make(map[string]qrLoginSessionOwner) + } + r.owners[sessionID] = qrLoginSessionOwner{userID: userID, createdAt: createdAt} + r.mu.Unlock() +} + +// Authorize 校验扫码会话归属;过期或不存在统一返回 NotFound,归属不符返回 Forbidden。 +func (r *QRLoginSessionRegistry) Authorize(sessionID string, userID int64) error { + if r == nil || sessionID == "" { + return ErrQRLoginSessionNotFound + } + r.mu.Lock() + // owner 保存会话创建者;ok 表示注册表中存在该会话。 + owner, ok := r.owners[sessionID] + // expired 表示会话创建时间已经超过 HTTP 所有权期限。 + expired := ok && owner.createdAt.Before(r.currentTime().Add(-r.ownerLifetime)) + if expired { + delete(r.owners, sessionID) + r.deletePersistedLocked(sessionID) + r.deletePersistLockIfIdleLocked(sessionID) + } + r.mu.Unlock() + if !ok || expired { + return ErrQRLoginSessionNotFound + } + if owner.userID != userID { + return ErrQRLoginSessionForbidden + } + return nil +} + +// Cleanup 删除超过所有权期限的会话并返回应同步释放的平台会话标识。 +func (r *QRLoginSessionRegistry) Cleanup(now time.Time) []string { + if r == nil { + return nil + } + if now.IsZero() { + now = r.currentTime() + } + // cutoff 是本次清理允许保留的最早会话创建时间。 + cutoff := now.Add(-r.ownerLifetime) + // expired 收集需要同步释放的平台扫码会话标识。 + expired := make([]string, 0) + r.mu.Lock() + // sessionID、owner 分别表示当前遍历的扫码会话标识及其创建者记录。 + for sessionID, owner := range r.owners { + if owner.createdAt.Before(cutoff) { + delete(r.owners, sessionID) + r.deletePersistedLocked(sessionID) + r.deletePersistLockIfIdleLocked(sessionID) + expired = append(expired, sessionID) + } + } + r.mu.Unlock() + return expired +} + +// Delete 移除指定扫码会话的所有权和幂等结果;平台会话释放由调用方按返回标识执行。 +func (r *QRLoginSessionRegistry) Delete(sessionID string) { + if r == nil || sessionID == "" { + return + } + r.mu.Lock() + delete(r.owners, sessionID) + r.deletePersistedLocked(sessionID) + r.deletePersistLockIfIdleLocked(sessionID) + r.mu.Unlock() +} + +// PersistOnce 以会话为粒度串行执行凭证持久化,并缓存成功后的非敏感结果。 +// work 仅在该会话锁内执行,不能把 Cookie 写入注册表或日志;失败不会留下幂等结果。 +func (r *QRLoginSessionRegistry) PersistOnce(sessionID string, userID int64, work func() (QRLoginSessionPersistence, error)) (QRLoginSessionPersistence, error) { + if r == nil || sessionID == "" || work == nil { + return QRLoginSessionPersistence{}, errors.New("扫码会话注册表未初始化") + } + // persistLock 串行化同一扫码会话的慢速凭证写入,避免重复创建账号。 + persistLock := r.acquirePersistLock(sessionID) + persistLock.mu.Lock() + defer r.releasePersistLock(sessionID, persistLock) + + r.mu.Lock() + // persisted、ok 保存已完成的幂等结果及其存在性。 + if persisted, ok := r.persisted[sessionID]; ok { + r.mu.Unlock() + if persisted.UserID != userID { + return QRLoginSessionPersistence{}, ErrQRLoginSessionForbidden + } + return persisted, nil + } + r.mu.Unlock() + + // persisted 保存工作函数返回的非敏感结果;Cookie 明文只在 work 的调用链内短暂存在。 + persisted, err := work() + if err != nil { + return QRLoginSessionPersistence{}, err + } + persisted.UserID = userID + if persisted.CreatedAt.IsZero() { + persisted.CreatedAt = r.currentTime() + } + r.mu.Lock() + if r.persisted == nil { + r.persisted = make(map[string]QRLoginSessionPersistence) + } + r.persisted[sessionID] = persisted + r.mu.Unlock() + return persisted, nil +} + +// currentTime 返回可测试的当前时间;测试可在包内替换 now 而不影响生产时钟。 +func (r *QRLoginSessionRegistry) currentTime() time.Time { + if r != nil && r.now != nil { + return r.now().UTC() + } + return time.Now().UTC() +} + +// acquirePersistLock 获取会话级持久化锁,并在注册表主锁内登记等待者数量。 +func (r *QRLoginSessionRegistry) acquirePersistLock(sessionID string) *qrLoginPersistenceLock { + r.mu.Lock() + if r.persistLocks == nil { + r.persistLocks = make(map[string]*qrLoginPersistenceLock) + } + // persistLock 保存该会话共享的锁对象,所有等待者都复用同一实例。 + persistLock := r.persistLocks[sessionID] + if persistLock == nil { + persistLock = &qrLoginPersistenceLock{} + r.persistLocks[sessionID] = persistLock + } + persistLock.refs++ + r.mu.Unlock() + return persistLock +} + +// releasePersistLock 释放会话级持久化锁,并在没有等待者时回收锁对象。 +func (r *QRLoginSessionRegistry) releasePersistLock(sessionID string, persistLock *qrLoginPersistenceLock) { + persistLock.mu.Unlock() + r.mu.Lock() + persistLock.refs-- + if persistLock.refs == 0 && r.persistLocks[sessionID] == persistLock { + delete(r.persistLocks, sessionID) + } + r.mu.Unlock() +} + +// deletePersistLockIfIdleLocked 在调用方持有注册表主锁时回收没有并发等待者的锁对象。 +func (r *QRLoginSessionRegistry) deletePersistLockIfIdleLocked(sessionID string) { + // persistLock 保存待回收的会话级锁对象;调用方已持有注册表主锁。 + persistLock := r.persistLocks[sessionID] + if persistLock != nil && persistLock.refs == 0 { + delete(r.persistLocks, sessionID) + } +} + +// deletePersistedLocked 删除会话缓存;调用方必须已经持有 mu。 +func (r *QRLoginSessionRegistry) deletePersistedLocked(sessionID string) { + delete(r.persisted, sessionID) +} diff --git a/internal/application/account/qr_login_session_registry_test.go b/internal/application/account/qr_login_session_registry_test.go new file mode 100644 index 0000000..0116e42 --- /dev/null +++ b/internal/application/account/qr_login_session_registry_test.go @@ -0,0 +1,99 @@ +package account + +import ( + "errors" + "sync" + "testing" + "time" +) + +// TestQRLoginSessionRegistryAuthorizesAndExpires 验证扫码会话所有权校验和过期回收不暴露凭证状态。 +func TestQRLoginSessionRegistryAuthorizesAndExpires(t *testing.T) { + // now 固定测试时钟,使会话生命周期断言不依赖真实墙钟。 + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + // registry 保存当前测试的扫码会话状态。 + registry := NewQRLoginSessionRegistry() + registry.now = func() time.Time { return now } + registry.Register("session-1", 7, now) + // err 保存会话所有者访问校验结果。 + if err := registry.Authorize("session-1", 7); err != nil { + t.Fatalf("会话所有者应能访问: %v", err) + } + if !errors.Is(registry.Authorize("session-1", 8), ErrQRLoginSessionForbidden) { + t.Fatal("其他用户访问会话应被拒绝") + } + now = now.Add(31 * time.Minute) + // err 保存过期会话访问校验结果。 + if !errors.Is(registry.Authorize("session-1", 7), ErrQRLoginSessionNotFound) { + t.Fatal("过期会话应视为不存在") + } + // got 保存重复清理返回的平台会话标识列表。 + if got := registry.Cleanup(now); len(got) != 0 { + t.Fatalf("过期会话已在授权检查中清理,不应重复返回: %v", got) + } +} + +// TestQRLoginSessionRegistryCleanupReturnsPlatformSessions 验证批量清理返回需要释放的平台会话标识。 +func TestQRLoginSessionRegistryCleanupReturnsPlatformSessions(t *testing.T) { + // now 固定测试时钟并构造一个已经超时的会话。 + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + // registry 保存当前测试的扫码会话状态。 + registry := NewQRLoginSessionRegistry() + registry.now = func() time.Time { return now } + registry.Register("expired", 7, now.Add(-31*time.Minute)) + registry.Register("active", 7, now) + // expired 保存注册表报告的过期平台会话标识。 + expired := registry.Cleanup(now) + if len(expired) != 1 || expired[0] != "expired" { + t.Fatalf("过期会话列表异常: %v", expired) + } + // err 保存活动会话访问校验结果。 + if err := registry.Authorize("active", 7); err != nil { + t.Fatalf("活动会话不应被清理: %v", err) + } +} + +// TestQRLoginSessionRegistryPersistOnceIsIdempotent 验证同一扫码会话并发持久化只执行一次工作函数。 +func TestQRLoginSessionRegistryPersistOnceIsIdempotent(t *testing.T) { + // registry 保存当前测试的扫码会话状态。 + registry := NewQRLoginSessionRegistry() + // workCalls 统计慢速持久化工作函数被实际执行的次数。 + workCalls := 0 + // workMu 保护测试计数器,避免并发断言产生数据竞争。 + var workMu sync.Mutex + // work 模拟应用层凭证写入并只返回非敏感结果。 + work := func() (QRLoginSessionPersistence, error) { + workMu.Lock() + workCalls++ + workMu.Unlock() + time.Sleep(time.Millisecond) + return QRLoginSessionPersistence{AccountID: "account-1", IsNew: true}, nil + } + // results 保存两个并发调用得到的幂等结果。 + results := make([]QRLoginSessionPersistence, 2) + // errs 保存两个并发调用的错误结果。 + errs := make([]error, 2) + // waitGroup 等待两个并发持久化调用结束。 + var waitGroup sync.WaitGroup + waitGroup.Add(2) + // index 表示当前并发持久化调用在测试结果数组中的位置。 + for index := range results { + go func(index int) { + defer waitGroup.Done() + results[index], errs[index] = registry.PersistOnce("session-1", 7, work) + }(index) + } + waitGroup.Wait() + if workCalls != 1 { + t.Fatalf("同一会话工作函数执行次数=%d,期望 1", workCalls) + } + // index、err 分别表示当前并发调用下标及其错误结果。 + for index, err := range errs { + if err != nil { + t.Fatalf("并发调用 %d 失败: %v", index, err) + } + if results[index].AccountID != "account-1" || !results[index].IsNew { + t.Fatalf("并发调用 %d 返回结果异常: %+v", index, results[index]) + } + } +} diff --git a/internal/application/account/runtime_service.go b/internal/application/account/runtime_service.go new file mode 100644 index 0000000..007f60f --- /dev/null +++ b/internal/application/account/runtime_service.go @@ -0,0 +1,159 @@ +package account + +import ( + "context" + "errors" + "strings" + "time" +) + +// RuntimeStatus 是账号运行时对外提供的非持久化连接状态快照;不包含 Cookie、Token 或其他凭证。 +type RuntimeStatus struct { + // State 是运行时状态机当前状态,例如 online、error 或 auth_expired。 + State string `json:"state"` + // Message 是面向管理页面的非敏感诊断信息。 + Message string `json:"message,omitempty"` + // Connected 表示当前账号是否仍有可用的实时连接。 + Connected bool `json:"connected"` + // Failures 是最近连接失败次数,具体统计窗口由运行时实现决定。 + Failures int `json:"failures"` + // UpdatedAt 是最近一次状态变化的 UTC 时间。 + UpdatedAt time.Time `json:"updated_at"` + // TokenAcquiredAt 是最近一次获得平台会话令牌的时间。 + TokenAcquiredAt time.Time `json:"token_acquired_at,omitempty"` + // TokenExpiresAt 是当前平台会话令牌的预计过期时间。 + TokenExpiresAt time.Time `json:"token_expires_at,omitempty"` + // TokenRefreshAt 是最近一次或下一次令牌续期时间,具体语义由运行时实现保持兼容。 + TokenRefreshAt time.Time `json:"token_refresh_at,omitempty"` + // TokenRemainingSeconds 是当前令牌剩余有效秒数。 + TokenRemainingSeconds int64 `json:"token_remaining_seconds,omitempty"` + // TokenRefreshStatus 是令牌续期阶段的非敏感状态标签。 + TokenRefreshStatus string `json:"token_refresh_status,omitempty"` +} + +// RuntimePort 定义账号应用层需要的最小运行时控制能力;实现方不得把 HTTP 或 engine 类型泄漏给调用者。 +type RuntimePort interface { + // UpdateCookie 把新 Cookie 同步到已存在的账号运行实例;缺少实例时应保持幂等无副作用。 + UpdateCookie(context.Context, string, string) error + // RuntimeStatuses 返回当前已登记账号的状态快照;调用方可安全修改返回的 map。 + RuntimeStatuses(context.Context) (map[string]RuntimeStatus, error) + // Restart 使用持久化凭证重启指定账号运行实例,并在完成后返回运行时错误。 + Restart(context.Context, string) error + // RecoverExpiredCredential 在平台会话失效时触发账号凭证恢复;返回是否接受了恢复请求。 + RecoverExpiredCredential(context.Context, string) bool +} + +// CredentialWakePort 定义凭证恢复后唤醒自动化任务的最小能力,避免账号应用层依赖自动化实现包。 +type CredentialWakePort interface { + // WakeCredentialBlocked 唤醒指定账号因凭证失效而暂停的任务。 + WakeCredentialBlocked(context.Context, string) error +} + +// RuntimeService 编排账号凭证写回后的运行时同步、重启和状态快照读取。 +type RuntimeService struct { + // runtime 提供账号运行实例的生命周期与状态能力;可为空以兼容离线测试或未启用运行时的进程。 + runtime RuntimePort + // wake 在凭证更新或重启完成后唤醒被凭证失效阻塞的自动化任务。 + wake CredentialWakePort +} + +// NewRuntimeService 构造账号运行时应用服务;运行时和唤醒端口都允许为空以保持无浏览器测试可运行。 +func NewRuntimeService(runtime RuntimePort, wake CredentialWakePort) *RuntimeService { + return &RuntimeService{runtime: runtime, wake: wake} +} + +// UpdateCookie 同步运行时 Cookie 并唤醒凭证阻塞任务;外部端口错误向调用者保留但不泄漏敏感值。 +func (s *RuntimeService) UpdateCookie(ctx context.Context, accountID, value string) error { + if s == nil { + return errors.New("账号运行时服务未初始化") + } + // validationErr 保存 Cookie 同步输入校验错误。 + if validationErr := validateRuntimeInput(ctx, accountID); validationErr != nil { + return validationErr + } + // wakeErr 保存自动化任务唤醒失败;该失败不阻断 Cookie 同步,避免凭证已更新但运行实例仍持有旧值。 + var wakeErr error + if s.wake != nil { + wakeErr = s.wake.WakeCredentialBlocked(ctx, accountID) + } + if s.runtime == nil { + return wakeErr + } + // updateErr 保存运行实例 Cookie 同步错误;运行时错误优先于非阻断的唤醒错误返回。 + updateErr := s.runtime.UpdateCookie(ctx, accountID, value) + if updateErr != nil { + return updateErr + } + return wakeErr +} + +// RuntimeStatuses 读取账号运行状态快照;未装配运行时返回空集合而不是伪造在线状态。 +func (s *RuntimeService) RuntimeStatuses(ctx context.Context) (map[string]RuntimeStatus, error) { + if s == nil { + return nil, errors.New("账号运行时服务未初始化") + } + // contextErr 保存状态快照读取前的取消错误。 + if contextErr := contextError(ctx); contextErr != nil { + return nil, contextErr + } + if s.runtime == nil { + return map[string]RuntimeStatus{}, nil + } + return s.runtime.RuntimeStatuses(ctx) +} + +// Restart 重启指定账号运行实例,并在成功后唤醒凭证阻塞任务。 +func (s *RuntimeService) Restart(ctx context.Context, accountID string) error { + if s == nil { + return errors.New("账号运行时服务未初始化") + } + // validationErr 保存账号运行时重启输入校验错误。 + if validationErr := validateRuntimeInput(ctx, accountID); validationErr != nil { + return validationErr + } + if s.runtime != nil { + // restartErr 保存运行实例重启错误;失败时不执行后续唤醒。 + if restartErr := s.runtime.Restart(ctx, accountID); restartErr != nil { + return restartErr + } + } + if s.wake != nil { + // wakeErr 保存重启成功后的自动化任务唤醒结果。 + wakeErr := s.wake.WakeCredentialBlocked(ctx, accountID) + return wakeErr + } + return nil +} + +// RecoverExpiredCredential 将平台会话失效恢复请求转发给运行时端口,不让 Server 直接持有 Manager 业务调用。 +func (s *RuntimeService) RecoverExpiredCredential(ctx context.Context, accountID string) bool { + if s == nil || s.runtime == nil || validateRuntimeInput(ctx, accountID) != nil { + return false + } + return s.runtime.RecoverExpiredCredential(ctx, accountID) +} + +// validateRuntimeInput 统一校验账号运行时调用的上下文和账号标识。 +func validateRuntimeInput(ctx context.Context, accountID string) error { + // contextErr 保存账号标识校验前检查到的取消错误。 + if contextErr := contextError(ctx); contextErr != nil { + return contextErr + } + if strings.TrimSpace(accountID) == "" { + return errors.New("账号标识不能为空") + } + return nil +} + +// contextError 将 nil Context 视为可继续执行,并在已取消时阻止任何运行时副作用。 +func contextError(ctx context.Context) error { + if ctx == nil { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + default: + return nil + } +} diff --git a/internal/application/account/runtime_service_test.go b/internal/application/account/runtime_service_test.go new file mode 100644 index 0000000..c4f819f --- /dev/null +++ b/internal/application/account/runtime_service_test.go @@ -0,0 +1,132 @@ +package account + +import ( + "context" + "errors" + "testing" + "time" +) + +// runtimePortFake 记录账号运行时端口调用并返回预置结果。 +type runtimePortFake struct { + // updateErr 是 Cookie 同步操作的预置错误。 + updateErr error + // restartErr 是账号重启操作的预置错误。 + restartErr error + // statuses 是运行状态快照。 + statuses map[string]RuntimeStatus + // updates 记录已同步的账号 Cookie。 + updates []string + // restarts 记录已请求重启的账号。 + restarts []string +} + +// UpdateCookie 记录运行时 Cookie 同步请求。 +func (f *runtimePortFake) UpdateCookie(_ context.Context, accountID, value string) error { + f.updates = append(f.updates, accountID+":"+value) + return f.updateErr +} + +// RuntimeStatuses 返回预置状态快照。 +func (f *runtimePortFake) RuntimeStatuses(_ context.Context) (map[string]RuntimeStatus, error) { + return f.statuses, nil +} + +// RecoverExpiredCredential 记录测试中的会话恢复请求并返回预设结果。 +func (f *runtimePortFake) RecoverExpiredCredential(context.Context, string) bool { return true } + +// Restart 记录账号重启请求。 +func (f *runtimePortFake) Restart(_ context.Context, accountID string) error { + f.restarts = append(f.restarts, accountID) + return f.restartErr +} + +// wakePortFake 记录自动化任务唤醒请求。 +type wakePortFake struct { + // err 是唤醒操作的预置错误。 + err error + // accounts 记录已唤醒的账号。 + accounts []string +} + +// WakeCredentialBlocked 记录凭证阻塞任务唤醒请求。 +func (f *wakePortFake) WakeCredentialBlocked(_ context.Context, accountID string) error { + f.accounts = append(f.accounts, accountID) + return f.err +} + +// TestRuntimeServiceUpdateCookieSuccess 验证 Cookie 同步和任务唤醒的成功路径。 +func TestRuntimeServiceUpdateCookieSuccess(t *testing.T) { + // runtime 保存运行时端口替身。 + runtime := &runtimePortFake{} + // wake 保存自动化唤醒端口替身。 + wake := &wakePortFake{} + // service 保存待测试的账号运行时应用服务。 + service := NewRuntimeService(runtime, wake) + // updateErr 保存 Cookie 同步结果。 + if updateErr := service.UpdateCookie(context.Background(), "acc1", "cookie"); updateErr != nil { + t.Fatalf("UpdateCookie returned error: %v", updateErr) + } + if len(runtime.updates) != 1 || runtime.updates[0] != "acc1:cookie" || len(wake.accounts) != 1 { + t.Fatalf("unexpected side effects: runtime=%+v wake=%+v", runtime, wake) + } +} + +// TestRuntimeServiceUpdateCookieMissingRuntime 验证未装配运行时仍保持凭证写回幂等。 +func TestRuntimeServiceUpdateCookieMissingRuntime(t *testing.T) { + // service 保存未装配运行时但已装配唤醒端口的应用服务。 + service := NewRuntimeService(nil, &wakePortFake{}) + // updateErr 保存未装配运行时的同步结果。 + if updateErr := service.UpdateCookie(context.Background(), "acc1", "cookie"); updateErr != nil { + t.Fatalf("missing runtime should be idempotent: %v", updateErr) + } +} + +// TestRuntimeServiceCancellationAndErrors 验证取消、唤醒错误和运行时错误不会伪造成功。 +func TestRuntimeServiceCancellationAndErrors(t *testing.T) { + // canceled 保存已取消的调用上下文。 + canceled, cancel := context.WithCancel(context.Background()) + cancel() + // service 保存可执行错误路径的应用服务。 + service := NewRuntimeService(&runtimePortFake{updateErr: errors.New("runtime failed")}, &wakePortFake{}) + // canceledErr 保存取消上下文的同步错误。 + if canceledErr := service.UpdateCookie(canceled, "acc1", "cookie"); !errors.Is(canceledErr, context.Canceled) { + t.Fatalf("canceled context error=%v", canceledErr) + } + // wakeErrService 保存唤醒失败的应用服务。 + wakeErrService := NewRuntimeService(&runtimePortFake{}, &wakePortFake{err: errors.New("wake failed")}) + // wakeErr 保存唤醒失败但 Cookie 同步仍完成后的返回错误。 + if wakeErr := wakeErrService.UpdateCookie(context.Background(), "acc1", "cookie"); wakeErr == nil || wakeErr.Error() != "wake failed" { + t.Fatalf("wake error=%v", wakeErr) + } +} + +// TestRuntimeServiceRuntimeStatusesSnapshot 验证状态快照字段按应用 DTO 原样返回。 +func TestRuntimeServiceRuntimeStatusesSnapshot(t *testing.T) { + // updatedAt 保存状态更新时间,确认时间字段不被 transport 层丢失。 + updatedAt := time.Now().UTC() + // statuses 保存运行时端口提供的非敏感状态快照。 + statuses := map[string]RuntimeStatus{"acc1": {State: "online", Connected: true, UpdatedAt: updatedAt}} + // service 保存状态读取应用服务。 + service := NewRuntimeService(&runtimePortFake{statuses: statuses}, nil) + // got、statusErr 保存读取到的快照和错误。 + got, statusErr := service.RuntimeStatuses(context.Background()) + if statusErr != nil || got["acc1"].State != "online" || !got["acc1"].Connected || !got["acc1"].UpdatedAt.Equal(updatedAt) { + t.Fatalf("snapshot=%+v err=%v", got, statusErr) + } +} + +// TestRuntimeServiceRecoversExpiredCredential 验证会话失效恢复由运行时端口接管并尊重取消上下文。 +func TestRuntimeServiceRecoversExpiredCredential(t *testing.T) { + // service 保存绑定运行时端口的账号应用服务。 + service := NewRuntimeService(&runtimePortFake{}, nil) + if !service.RecoverExpiredCredential(context.Background(), "acc1") { + t.Fatal("expected runtime recovery to be accepted") + } + // canceled 保存已取消的请求上下文。 + canceled, cancel := context.WithCancel(context.Background()) + cancel() + if service.RecoverExpiredCredential(canceled, "acc1") { + t.Fatal("canceled recovery must not reach runtime port") + } +} diff --git a/internal/application/admin/service.go b/internal/application/admin/service.go index fe29a4c..d44042e 100644 --- a/internal/application/admin/service.go +++ b/internal/application/admin/service.go @@ -4,6 +4,7 @@ package admin import ( "context" "errors" + "fmt" ) // ErrInvalidUser 表示请求没有提供有效的管理员身份。 @@ -12,6 +13,9 @@ var ErrInvalidUser = errors.New("管理员身份无效") // ErrSelfDelete 表示管理员试图删除当前会话对应的用户。 var ErrSelfDelete = errors.New("不能删除当前登录用户") +// ErrRuntimeStop 表示删除用户前停止其账号运行实例失败;此时持久化删除不会继续执行。 +var ErrRuntimeStop = errors.New("停止用户账号运行时失败") + // UserSummary 是管理员用户列表使用的非敏感摘要。 type UserSummary struct { // ID 是用户稳定标识。 @@ -50,21 +54,37 @@ type Stats struct { type Repository interface { // ListUsers 返回不包含密码和凭证的用户摘要。 ListUsers(context.Context) ([]UserSummary, error) + // ListOwnedAccountIDs 返回用户拥有的账号 ID,不读取 Cookie 或其他凭证内容。 + ListOwnedAccountIDs(context.Context, int64) ([]string, error) // DeleteUser 删除用户及其由数据库层管理的关联资源。 DeleteUser(context.Context, int64) error // Stats 返回管理员仪表盘聚合计数。 Stats(context.Context) (Stats, error) } +// Runtime 定义管理员删除用户前停止账号运行实例所需的最小能力。 +// 实现不得暴露 account.Manager 或其他运行时具体类型。 +type Runtime interface { + // StopContext 在调用方 Context 约束内停止一个账号并等待其运行协程退出。 + StopContext(context.Context, string) error +} + // Service 编排管理员用户管理和仪表盘查询。 type Service struct { // repository 保存管理员用例的窄持久化端口。 repository Repository + // runtime 保存管理员删除用户前收束账号运行实例的窄运行时端口;为空时兼容无运行时的离线用例。 + runtime Runtime } // NewService 构造管理员应用服务。 func NewService(repository Repository) *Service { - return &Service{repository: repository} + return NewServiceWithRuntime(repository, nil) +} + +// NewServiceWithRuntime 构造管理员应用服务并注入账号运行时收束能力。 +func NewServiceWithRuntime(repository Repository, runtime Runtime) *Service { + return &Service{repository: repository, runtime: runtime} } // ListUsers 查询管理员用户摘要。 @@ -86,6 +106,20 @@ func (s *Service) DeleteUser(ctx context.Context, currentUserID, targetUserID in if s == nil || s.repository == nil { return errors.New("管理员服务未初始化") } + // accountIDs、listErr 保存目标用户拥有的账号 ID 及读取错误;查询只返回非敏感标识。 + accountIDs, listErr := s.repository.ListOwnedAccountIDs(ctx, targetUserID) + if listErr != nil { + return listErr + } + if s.runtime != nil { + // accountID 表示当前待收束的目标用户账号;停止失败会阻止用户及其关联数据删除。 + for _, accountID := range accountIDs { + // stopErr 表示当前账号运行实例停止或等待退出时的错误。 + if stopErr := s.runtime.StopContext(ctx, accountID); stopErr != nil { + return fmt.Errorf("%w: %w", ErrRuntimeStop, stopErr) + } + } + } return s.repository.DeleteUser(ctx, targetUserID) } diff --git a/internal/application/admin/service_test.go b/internal/application/admin/service_test.go index d1c6362..dda5985 100644 --- a/internal/application/admin/service_test.go +++ b/internal/application/admin/service_test.go @@ -12,6 +12,10 @@ type adminRepositoryStub struct { listResult []UserSummary // listErr 保存用户列表错误。 listErr error + // accountIDs 保存目标用户拥有的账号标识。 + accountIDs []string + // accountIDsErr 保存账号标识查询错误。 + accountIDsErr error // deleteErr 保存用户删除错误。 deleteErr error // statsResult 保存统计返回值。 @@ -27,6 +31,11 @@ func (r *adminRepositoryStub) ListUsers(context.Context) ([]UserSummary, error) return r.listResult, r.listErr } +// ListOwnedAccountIDs 返回测试预置的用户账号标识及查询错误。 +func (r *adminRepositoryStub) ListOwnedAccountIDs(context.Context, int64) ([]string, error) { + return r.accountIDs, r.accountIDsErr +} + // DeleteUser 记录删除目标并返回测试预置错误。 func (r *adminRepositoryStub) DeleteUser(_ context.Context, userID int64) error { r.deletedUserID = userID @@ -38,6 +47,27 @@ func (r *adminRepositoryStub) Stats(context.Context) (Stats, error) { return r.statsResult, r.statsErr } +// adminRuntimeStub 保存管理员删除测试中的停止调用顺序及可控错误。 +type adminRuntimeStub struct { + // stoppedIDs 保存收到停止请求的账号标识。 + stoppedIDs []string + // stopErrByID 保存指定账号停止失败的错误。 + stopErrByID map[string]error +} + +// StopContext 记录账号停止请求,并按账号返回预置错误。 +func (r *adminRuntimeStub) StopContext(ctx context.Context, accountID string) error { + // err 表示测试上下文是否已经取消;取消时模拟运行时立即拒绝停止。 + if err := ctx.Err(); err != nil { + return err + } + r.stoppedIDs = append(r.stoppedIDs, accountID) + if r.stopErrByID == nil { + return nil + } + return r.stopErrByID[accountID] +} + // TestServiceListUsersAndStats 验证管理员摘要与统计成功、错误和空服务分支。 func TestServiceListUsersAndStats(t *testing.T) { // expectedUsers、expectedStats 保存成功路径的应用模型结果。 @@ -115,3 +145,56 @@ func TestServiceDeleteUser(t *testing.T) { t.Fatal("空管理员服务应拒绝删除") } } + +// TestServiceDeleteUserStopsAllAccounts 验证删除用户前会依次停止其全部账号且成功后才持久化删除。 +func TestServiceDeleteUserStopsAllAccounts(t *testing.T) { + // repository 保存目标用户账号及删除调用记录。 + repository := &adminRepositoryStub{accountIDs: []string{"acc-a", "acc-b"}} + // runtime 保存账号停止调用记录。 + runtime := &adminRuntimeStub{} + // service 保存注入运行时端口的管理员应用服务。 + service := NewServiceWithRuntime(repository, runtime) + // err 表示所有账号停止并完成删除的结果。 + if err := service.DeleteUser(context.Background(), 1, 2); err != nil { + t.Fatalf("删除用户失败: %v", err) + } + if len(runtime.stoppedIDs) != 2 || runtime.stoppedIDs[0] != "acc-a" || runtime.stoppedIDs[1] != "acc-b" { + t.Fatalf("停止账号顺序异常: %v", runtime.stoppedIDs) + } + if repository.deletedUserID != 2 { + t.Fatalf("停止全部账号后才应删除用户,deleted=%d", repository.deletedUserID) + } +} + +// TestServiceDeleteUserStopsFailureAndCancellation 验证停止失败或请求取消时不会删除用户。 +func TestServiceDeleteUserStopsFailureAndCancellation(t *testing.T) { + // stopFailure 保存第二个账号停止失败的原因。 + stopFailure := errors.New("runtime stop failed") + // repository 保存多个目标账号及删除调用记录。 + repository := &adminRepositoryStub{accountIDs: []string{"acc-a", "acc-b"}} + // runtime 保存指定账号的失败行为。 + runtime := &adminRuntimeStub{stopErrByID: map[string]error{"acc-b": stopFailure}} + // service 保存停止失败路径的应用服务。 + service := NewServiceWithRuntime(repository, runtime) + // err 表示第二个账号停止失败后的应用错误。 + if err := service.DeleteUser(context.Background(), 1, 2); !errors.Is(err, ErrRuntimeStop) { + t.Fatalf("停止失败应返回 ErrRuntimeStop,err=%v", err) + } + if repository.deletedUserID != 0 { + t.Fatal("停止失败时不应删除用户") + } + // canceledCtx 保存已取消的请求上下文。 + canceledCtx, cancel := context.WithCancel(context.Background()) + cancel() + // canceledRepository 保存取消路径的目标账号和删除记录。 + canceledRepository := &adminRepositoryStub{accountIDs: []string{"acc-c"}} + // canceledRuntime 保存取消路径的运行时桩。 + canceledRuntime := &adminRuntimeStub{} + // err 表示已取消请求阻止停止和持久化删除的错误。 + if err := NewServiceWithRuntime(canceledRepository, canceledRuntime).DeleteUser(canceledCtx, 1, 2); !errors.Is(err, context.Canceled) { + t.Fatalf("请求取消应保留 context.Canceled,err=%v", err) + } + if canceledRepository.deletedUserID != 0 { + t.Fatal("请求取消时不应删除用户") + } +} diff --git a/internal/application/chat/send.go b/internal/application/chat/send.go index 564e2a2..eee7599 100644 --- a/internal/application/chat/send.go +++ b/internal/application/chat/send.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strings" + "sync" ) var ( @@ -91,6 +92,67 @@ func NewWithSending(repository Repository, outgoing OutgoingRepository, senders return service } +// NewWithSendingAndSubscription 创建同时支持发送和实时订阅的聊天应用服务。 +func NewWithSendingAndSubscription(repository Repository, outgoing OutgoingRepository, senders SenderProvider, uploader ImageUploader, subscription SubscriptionProvider, identity ...IdentityResolver) *Service { + // service 保存聊天历史、发送和实时订阅能力的统一应用服务。 + service := NewWithSending(repository, outgoing, senders, uploader, identity...) + service.subscription = subscription + return service +} + +// NewWithSendingSubscriptionAndRefresh 创建同时支持发送、订阅和平台刷新的聊天应用服务。 +func NewWithSendingSubscriptionAndRefresh(repository Repository, outgoing OutgoingRepository, senders SenderProvider, uploader ImageUploader, subscription SubscriptionProvider, refresh RefreshProvider, identity ...IdentityResolver) *Service { + // service 保存聊天用例所需的持久化、平台刷新、发送和订阅端口。 + service := NewWithSendingAndSubscription(repository, outgoing, senders, uploader, subscription, identity...) + service.refresh = refresh + return service +} + +// SendingAvailable 报告文字/媒体消息所需的应用端口是否已完成装配。 +// 该查询只反映依赖生命周期,不触碰账号凭证或外部平台。 +func (s *Service) SendingAvailable() bool { + return s != nil && s.outgoing != nil && s.senders != nil +} + +// ImageUploadAvailable 报告图片上传所需的应用端口是否已完成装配。 +func (s *Service) ImageUploadAvailable() bool { + return s != nil && s.uploader != nil +} + +// Subscribe 订阅当前用户有权接收的实时聊天事件;取消函数可安全重复调用。 +func (s *Service) Subscribe(ctx context.Context, userID int64) (<-chan Event, func(), error) { + if s == nil || s.subscription == nil || userID <= 0 { + return nil, nil, ErrSubscriptionUnavailable + } + // events、cancel、err 保存订阅事件流、幂等清理函数和底层错误。 + events, cancel, err := s.subscription.Subscribe(ctx, userID) + if err != nil { + return nil, nil, err + } + // once 保证应用层向 HTTP 暴露的清理函数可安全重复调用。 + var once sync.Once + return events, func() { once.Do(cancel) }, nil +} + +// RefreshConversations 刷新并保存指定账号的联系人页;原始平台数据不会离开应用端口。 +func (s *Service) RefreshConversations(ctx context.Context, accountID string, cursor int64, limit int) (ConversationPage, error) { + accountID = strings.TrimSpace(accountID) + if s == nil || s.refresh == nil || accountID == "" || limit <= 0 { + return ConversationPage{}, ErrRefreshUnavailable + } + return s.refresh.RefreshConversations(ctx, accountID, cursor, limit) +} + +// RefreshHistory 刷新并保存指定会话的消息页;session 只包含非敏感展示字段。 +func (s *Service) RefreshHistory(ctx context.Context, accountID, chatID string, cursor int64, limit int, session Session) (HistoryPage, error) { + accountID = strings.TrimSpace(accountID) + chatID = strings.TrimSpace(chatID) + if s == nil || s.refresh == nil || accountID == "" || chatID == "" || limit <= 0 { + return HistoryPage{}, ErrRefreshUnavailable + } + return s.refresh.RefreshHistory(ctx, accountID, chatID, cursor, limit, session) +} + // SendText 创建并发送一条文字消息,失败时尽力保留本地 failed 状态。 func (s *Service) SendText(ctx context.Context, input OutgoingInput) (*Message, error) { // session 和 text 保存规范化后的会话及消息内容。 diff --git a/internal/application/chat/send_test.go b/internal/application/chat/send_test.go index b2e443f..66638ed 100644 --- a/internal/application/chat/send_test.go +++ b/internal/application/chat/send_test.go @@ -52,6 +52,20 @@ type sendProvider struct { sender *sendSender } +// TestServiceAvailabilityReportsRequiredPorts 验证发送和图片上传能力只由应用端口装配状态决定。 +func TestServiceAvailabilityReportsRequiredPorts(t *testing.T) { + // unavailable 是没有任何外发端口的聊天应用服务。 + unavailable := NewWithSending(nil, nil, nil, nil) + if unavailable.SendingAvailable() || unavailable.ImageUploadAvailable() { + t.Fatal("缺少外发端口时不应报告聊天能力可用") + } + // available 是同时装配文字发送和图片上传端口的聊天应用服务。 + available := NewWithSending(nil, &sendRepository{}, sendProvider{}, sendUploader{}) + if !available.SendingAvailable() || !available.ImageUploadAvailable() { + t.Fatal("完整装配的聊天能力应报告可用") + } +} + // Sender 返回测试发送器或模拟离线。 func (p sendProvider) Sender(string) (Sender, bool) { return p.sender, p.sender != nil diff --git a/internal/application/chat/service.go b/internal/application/chat/service.go index a26d201..82ccbeb 100644 --- a/internal/application/chat/service.go +++ b/internal/application/chat/service.go @@ -15,6 +15,15 @@ var ErrInvalidInput = errors.New("聊天历史查询参数无效") // ErrSessionUnavailable 表示会话清理、归属或身份持久化端口未装配。 var ErrSessionUnavailable = errors.New("聊天会话服务未启用") +// ErrSubscriptionUnavailable 表示实时聊天事件订阅端口尚未装配。 +var ErrSubscriptionUnavailable = errors.New("聊天实时订阅服务未启用") + +// ErrRefreshUnavailable 表示聊天平台刷新端口尚未装配。 +var ErrRefreshUnavailable = errors.New("聊天刷新服务未启用") + +// ErrRefreshPersist 表示平台刷新成功但本地聊天历史持久化失败。 +var ErrRefreshPersist = errors.New("聊天刷新结果保存失败") + // Message 是聊天历史用例对外暴露的非敏感消息模型。 type Message struct { // ID 是本地消息主键。 @@ -80,6 +89,51 @@ type IdentityResolver interface { Resolve(ctx context.Context, accountID, chatID string) (Identity, error) } +// Event 是实时聊天推送使用的非敏感应用层事件模型。 +type Event struct { + // Type 表示事件类别,例如 message.created。 + Type string `json:"type"` + // Message 保存事件关联的聊天消息;非消息事件可以为空。 + Message *Message `json:"message,omitempty"` + // Session 保存事件关联的会话摘要;无会话信息时为空。 + Session *Session `json:"session,omitempty"` +} + +// SubscriptionProvider 定义实时聊天订阅所需的最小能力。 +type SubscriptionProvider interface { + // Subscribe 按用户归属订阅实时事件,并返回幂等取消函数。 + Subscribe(ctx context.Context, userID int64) (<-chan Event, func(), error) +} + +// ConversationPage 是平台联系人刷新后返回的非敏感分页结果。 +type ConversationPage struct { + // HasMore 表示平台是否还存在更早的联系人页。 + HasMore bool + // NextCursor 保存下一次联系人刷新使用的平台游标。 + NextCursor int64 +} + +// HistoryPage 是平台聊天历史刷新后返回的非敏感分页结果。 +type HistoryPage struct { + // Messages 保存已写入本地仓储的聊天消息。 + Messages []Message + // Session 保存当前会话的非敏感摘要。 + Session Session + // HasMore 表示平台是否还存在更早的消息页。 + HasMore bool + // NextCursor 保存下一次历史刷新使用的平台游标。 + NextCursor int64 +} + +// RefreshProvider 定义聊天平台刷新和本地落库所需的最小适配能力。 +// 原始平台响应、运行时实例和数据库模型均由适配器持有,不进入 Server。 +type RefreshProvider interface { + // RefreshConversations 拉取并保存指定账号的联系人页。 + RefreshConversations(context.Context, string, int64, int) (ConversationPage, error) + // RefreshHistory 拉取并保存指定会话的消息页。 + RefreshHistory(context.Context, string, string, int64, int, Session) (HistoryPage, error) +} + // Page 是聊天历史查询的分页结果。 type Page struct { // Messages 是按时间正序排列的当前页消息。 @@ -124,6 +178,10 @@ type Service struct { uploader ImageUploader // identityResolver 保存平台身份查询端口,凭证只在适配器内部短暂存在。 identityResolver IdentityResolver + // subscription 保存实时事件订阅端口;平台和领域实现不会泄露到 HTTP 层。 + subscription SubscriptionProvider + // refresh 保存平台聊天刷新端口;原始响应只在适配器内部解析和持久化。 + refresh RefreshProvider } // New 创建聊天历史应用服务;空端口会导致构造结果不可用。 diff --git a/internal/application/chat/service_test.go b/internal/application/chat/service_test.go index a1c3e0f..121a0d8 100644 --- a/internal/application/chat/service_test.go +++ b/internal/application/chat/service_test.go @@ -3,9 +3,129 @@ package chat import ( "context" "errors" + "sync" "testing" ) +// fakeSubscriptionProvider 是实时订阅应用端口的内存替身,记录取消函数调用次数。 +type fakeSubscriptionProvider struct { + // events 保存测试用实时事件通道。 + events chan Event + // mu 保护取消计数,允许清理回调和断言并发执行。 + mu sync.Mutex + // cancelCalls 记录底层订阅清理次数,验证应用层不会重复释放。 + cancelCalls int +} + +// fakeRefreshProvider 记录刷新应用端口收到的请求参数,并返回预设分页结果。 +type fakeRefreshProvider struct { + // conversation 保存联系人刷新返回值。 + conversation ConversationPage + // history 保存历史刷新返回值。 + history HistoryPage + // calls 记录联系人与历史刷新调用次数。 + calls int +} + +// RefreshConversations 返回测试联系人页并记录调用次数。 +func (p *fakeRefreshProvider) RefreshConversations(context.Context, string, int64, int) (ConversationPage, error) { + p.calls++ + return p.conversation, nil +} + +// RefreshHistory 返回测试历史页并记录调用次数。 +func (p *fakeRefreshProvider) RefreshHistory(context.Context, string, string, int64, int, Session) (HistoryPage, error) { + p.calls++ + return p.history, nil +} + +// TestRefreshDelegatesOnlyValidRequests 验证刷新应用服务只向已装配端口转发有效请求。 +func TestRefreshDelegatesOnlyValidRequests(t *testing.T) { + // provider 保存刷新端口替身及其预设结果。 + provider := &fakeRefreshProvider{ + conversation: ConversationPage{HasMore: true, NextCursor: 7}, + history: HistoryPage{HasMore: true, NextCursor: 9, Messages: []Message{{MessageKey: "m1"}}}, + } + // service 保存绑定刷新端口的聊天应用服务。 + service := NewWithSendingSubscriptionAndRefresh(nil, nil, nil, nil, nil, provider) + // conversation 和 err 保存联系人刷新结果。 + conversation, err := service.RefreshConversations(context.Background(), "account", 2, 10) + if err != nil || conversation.NextCursor != 7 || !conversation.HasMore { + t.Fatalf("conversation=%+v err=%v", conversation, err) + } + // history 和 err 保存历史刷新结果。 + history, err := service.RefreshHistory(context.Background(), "account", "chat", 3, 10, Session{AccountID: "account", ChatID: "chat"}) + if err != nil || history.NextCursor != 9 || len(history.Messages) != 1 { + t.Fatalf("history=%+v err=%v", history, err) + } + if provider.calls != 2 { + t.Fatalf("refresh calls=%d", provider.calls) + } + // _, err 保存无效账号请求的应用层错误。 + _, err = service.RefreshConversations(context.Background(), "", 0, 10) + if !errors.Is(err, ErrRefreshUnavailable) { + t.Fatalf("invalid request error=%v", err) + } +} + +// Subscribe 返回测试事件流,并提供可重复调用的清理函数。 +func (p *fakeSubscriptionProvider) Subscribe(context.Context, int64) (<-chan Event, func(), error) { + return p.events, func() { + p.mu.Lock() + p.cancelCalls++ + p.mu.Unlock() + }, nil +} + +// TestSubscribeRejectsUnavailableAndInvalidUser 验证实时订阅缺少端口或用户身份时快速失败。 +func TestSubscribeRejectsUnavailableAndInvalidUser(t *testing.T) { + // service 是未装配实时订阅端口的聊天应用服务。 + service := New(nil) + // _, _, err 保存无效用户订阅请求的返回值。 + _, _, err := service.Subscribe(context.Background(), 1) + if !errors.Is(err, ErrSubscriptionUnavailable) { + t.Fatalf("nil subscription error=%v", err) + } + // provider 是可用实时订阅端口的测试替身。 + provider := &fakeSubscriptionProvider{events: make(chan Event)} + service = NewWithSendingAndSubscription(nil, nil, nil, nil, provider) + // _, _, err 保存缺少用户身份时的返回值。 + _, _, err = service.Subscribe(context.Background(), 0) + if !errors.Is(err, ErrSubscriptionUnavailable) { + t.Fatalf("invalid user error=%v", err) + } +} + +// TestSubscribeDelegatesAndAllowsIdempotentCleanup 验证事件订阅转发和重复清理语义。 +func TestSubscribeDelegatesAndAllowsIdempotentCleanup(t *testing.T) { + // provider 是记录清理次数的实时订阅端口替身。 + provider := &fakeSubscriptionProvider{events: make(chan Event, 1)} + // service 是绑定实时订阅端口的聊天应用服务。 + service := NewWithSendingAndSubscription(nil, nil, nil, nil, provider) + // events、cancel、err 保存应用层订阅结果。 + events, cancel, err := service.Subscribe(context.Background(), 42) + if err != nil { + t.Fatalf("Subscribe() error=%v", err) + } + // wantEvent 是发送到应用层事件流的测试事件。 + wantEvent := Event{Type: "message.created", Message: &Message{MessageKey: "event-1"}} + provider.events <- wantEvent + // gotEvent 保存应用层接收到的实时事件。 + gotEvent := <-events + if gotEvent.Type != wantEvent.Type || gotEvent.Message == nil || gotEvent.Message.MessageKey != "event-1" { + t.Fatalf("event=%+v", gotEvent) + } + cancel() + cancel() + provider.mu.Lock() + // cancelCalls 保存底层订阅清理次数快照。 + cancelCalls := provider.cancelCalls + provider.mu.Unlock() + if cancelCalls != 1 { + t.Fatalf("application service must clean subscription once, calls=%d", cancelCalls) + } +} + // fakeRepository 保存测试聊天历史数据,并记录最近一次用户归属参数。 type fakeRepository struct { // messages 是模拟聊天消息列表。 diff --git a/internal/application/items/batch_management.go b/internal/application/items/batch_management.go index cce8a9c..a538f52 100644 --- a/internal/application/items/batch_management.go +++ b/internal/application/items/batch_management.go @@ -61,7 +61,7 @@ type BatchManagementRepository interface { // BatchManagementRuntime 定义批次管理服务控制后台 worker 的最小端口。 type BatchManagementRuntime interface { // StartBatch 启动指定批次的后台 worker。 - StartBatch(int64, string, string) + StartBatch(int64, string, string) error // CancelBatch 请求停止指定批次的后台 worker。 CancelBatch(string, string) } @@ -137,7 +137,14 @@ func (s *BatchManagementService) StartBatch(ctx context.Context, userID int64, b if s.runtime == nil { return batch.ID, nil } - s.runtime.StartBatch(userID, batch.ID, workerToken) + // startErr 保存生命周期协调器登记 worker 时的错误。 + if startErr := s.runtime.StartBatch(userID, batch.ID, workerToken); startErr != nil { + // releaseErr 保存 worker 启动失败后的租约释放错误。 + if releaseErr := s.releaseClaim(ctx, batch.ID, workerToken); releaseErr != nil { + return "", errors.Join(startErr, releaseErr) + } + return "", startErr + } return batch.ID, nil } @@ -304,7 +311,14 @@ func (s *BatchManagementService) RetryFailedBatch(ctx context.Context, userID in return "", ErrBatchNoRows } if s.runtime != nil { - s.runtime.StartBatch(userID, batchID, workerToken) + // startErr 保存重试 worker 登记失败错误。 + if startErr := s.runtime.StartBatch(userID, batchID, workerToken); startErr != nil { + // releaseErr 保存重试 worker 启动失败后的租约释放错误。 + if releaseErr := s.releaseClaim(ctx, batchID, workerToken); releaseErr != nil { + return "", errors.Join(startErr, releaseErr) + } + return "", startErr + } } return batchID, nil } diff --git a/internal/application/items/batch_management_test.go b/internal/application/items/batch_management_test.go index 0ceb0ad..ece0f79 100644 --- a/internal/application/items/batch_management_test.go +++ b/internal/application/items/batch_management_test.go @@ -141,13 +141,16 @@ type batchManagementRuntimeFake struct { started []string // canceled 保存取消 worker 的参数。 canceled []string + // startErr 模拟生命周期协调器登记 worker 失败。 + startErr error } // StartBatch 记录批次 worker 启动。 -func (runtime *batchManagementRuntimeFake) StartBatch(userID int64, batchID, workerToken string) { +func (runtime *batchManagementRuntimeFake) StartBatch(userID int64, batchID, workerToken string) error { // command 保存便于断言的 worker 启动参数。 command := batchID + ":" + workerToken runtime.started = append(runtime.started, command) + return runtime.startErr } // CancelBatch 记录批次 worker 取消。 @@ -282,6 +285,40 @@ func TestBatchManagementRetryFailed(t *testing.T) { } } +// TestBatchManagementStartFailureReleasesClaim 验证批次 worker 登记失败时会释放刚声明的租约。 +func TestBatchManagementStartFailureReleasesClaim(t *testing.T) { + // startErr 是生命周期协调器拒绝 worker 的原始错误。 + startErr := errors.New("worker 启动失败") + // repository、runtime 和 service 保存批次启动失败测试依赖。 + repository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "batch-start-fail", Status: "preview"}, claimed: true, pending: []BatchRow{{ID: 1}}} + // runtime 模拟协调器在登记批次 worker 时返回错误。 + runtime := &batchManagementRuntimeFake{startErr: startErr} + // service 使用测试端口执行租约声明和 worker 登记编排。 + service := newBatchManagementServiceForTest(t, repository, runtime) + // batchID、err 保存 worker 登记失败后的批次启动结果。 + batchID, err := service.StartBatch(context.Background(), 7, "batch-start-fail", time.Minute) + if batchID != "" || !errors.Is(err, startErr) || !repository.released { + t.Fatalf("start result=%q err=%v released=%v", batchID, err, repository.released) + } +} + +// TestBatchManagementRetryStartFailureReleasesClaim 验证重试 worker 登记失败时也会释放新租约。 +func TestBatchManagementRetryStartFailureReleasesClaim(t *testing.T) { + // startErr 是重试 worker 生命周期登记失败的原始错误。 + startErr := errors.New("重试 worker 启动失败") + // repository、runtime 和 service 保存批次重试失败测试依赖。 + repository := &batchManagementRepositoryFake{batch: BatchInfo{ID: "batch-retry-fail", Status: "completed"}, claimed: true, pending: []BatchRow{{ID: 2}}} + // runtime 模拟协调器在登记重试 worker 时返回错误。 + runtime := &batchManagementRuntimeFake{startErr: startErr} + // service 使用测试端口执行重试租约和 worker 登记编排。 + service := newBatchManagementServiceForTest(t, repository, runtime) + // batchID、err 保存重试 worker 登记失败后的结果。 + batchID, err := service.RetryFailedBatch(context.Background(), 7, "batch-retry-fail", time.Minute) + if batchID != "" || !errors.Is(err, startErr) || !repository.released { + t.Fatalf("retry result=%q err=%v released=%v", batchID, err, repository.released) + } +} + // TestBatchManagementCleanupExpiredUploads 验证过期目录清理的成功、失败聚合与取消语义。 func TestBatchManagementCleanupExpiredUploads(t *testing.T) { // repository 保存过期批次和清理错误替身。 diff --git a/internal/application/items/batch_publish_test.go b/internal/application/items/batch_publish_test.go index 8a7721f..48e1d24 100644 --- a/internal/application/items/batch_publish_test.go +++ b/internal/application/items/batch_publish_test.go @@ -3,6 +3,7 @@ package items import ( "context" "errors" + "sync" "testing" "time" ) @@ -17,6 +18,10 @@ type batchRunnerRepository struct { failed map[int64]string // finalized 保存最终状态收口次数。 finalized int + // workerToken 保存最近一次续租收到的令牌,允许协调器测试模拟租约切换。 + workerToken string + // mu 保护协调器并发测试中的租约令牌和批次快照。 + mu sync.Mutex } // PendingRows 返回预置的批量明细。 @@ -25,12 +30,20 @@ func (r *batchRunnerRepository) PendingRows(_ context.Context, _ string, _ bool) } // RenewBatchLease 保持内存批次租约有效。 -func (r *batchRunnerRepository) RenewBatchLease(_ context.Context, _, _ string, _ int64) (bool, error) { +func (r *batchRunnerRepository) RenewBatchLease(_ context.Context, _, workerToken string, _ int64) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.workerToken = workerToken return true, nil } // GetBatch 返回当前批次快照。 func (r *batchRunnerRepository) GetBatch(_ context.Context, _ int64, _ string) (BatchInfo, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.workerToken != "" { + r.batch.WorkerToken = r.workerToken + } return r.batch, nil } @@ -41,6 +54,8 @@ func (r *batchRunnerRepository) ClaimRow(_ context.Context, _ int64, _ string) ( // BatchStatus 返回当前批次状态。 func (r *batchRunnerRepository) BatchStatus(_ context.Context, _ string) (string, error) { + r.mu.Lock() + defer r.mu.Unlock() return r.batch.Status, nil } @@ -50,6 +65,8 @@ func (r *batchRunnerRepository) MarkClaimedRowFailed(ctx context.Context, rowID if err := ctx.Err(); err != nil { return false, err } + r.mu.Lock() + defer r.mu.Unlock() if r.failed == nil { r.failed = make(map[int64]string) } @@ -62,18 +79,24 @@ func (r *batchRunnerRepository) RecountBatch(_ context.Context, _ string) error // FinalizeBatch 记录正常收口并返回完成状态。 func (r *batchRunnerRepository) FinalizeBatch(_ context.Context, _, _ string) (string, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() r.finalized++ return "completed", true, nil } // FinalizeCanceled 记录取消收口。 func (r *batchRunnerRepository) FinalizeCanceled(_ context.Context, _, _ string) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() r.finalized++ return true, nil } // FinalizeInterrupted 记录中断收口。 func (r *batchRunnerRepository) FinalizeInterrupted(_ context.Context, _, _, _ string) (string, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() r.finalized++ return "failed", true, nil } diff --git a/internal/application/items/batch_recovery.go b/internal/application/items/batch_recovery.go index 32e57c6..5da63b8 100644 --- a/internal/application/items/batch_recovery.go +++ b/internal/application/items/batch_recovery.go @@ -30,9 +30,13 @@ type BatchRecoveryRepository interface { } // BatchWorkerStarter 是恢复服务启动批量 worker 的生命周期回调。 -// 回调由 Server 提供,因此应用服务不持有 HTTP Server、锁或取消映射。 +// 回调由应用装配层提供,因此恢复服务不持有 HTTP Server、锁或取消映射。 type BatchWorkerStarter func(context.Context, int64, string, string) +// BatchWorkerStarterWithError 是可报告 worker 启动失败的恢复回调。 +// 恢复服务据此在租约已抢占但 worker 无法登记时执行租约释放补偿。 +type BatchWorkerStarterWithError func(context.Context, int64, string, string) error + // BatchRecoveryOptions 配置恢复扫描器的租约、时钟、令牌和 worker 回调。 type BatchRecoveryOptions struct { // LeaseDuration 是恢复后重新声明的批次租约时长。 @@ -58,9 +62,6 @@ func NewBatchRecoveryService(repository BatchRecoveryRepository, options BatchRe 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 } @@ -75,9 +76,37 @@ func NewBatchRecoveryService(repository BatchRecoveryRepository, options BatchRe // Recover 扫描并接管可恢复批次;单个批次失败时继续处理其他批次。 func (service *BatchRecoveryService) Recover(ctx context.Context) error { - if service == nil || service.repository == nil || service.options.StartWorker == nil { + if service == nil || service.options.StartWorker == nil { + return errors.New("批量恢复 worker 回调未初始化") + } + if ctx == nil { + return errors.New("批量恢复 Context 不能为空") + } + // startWorker 将历史无错误回调适配为可报告启动错误的边界。 + startWorker := func(startCtx context.Context, userID int64, batchID, workerToken string) error { + service.options.StartWorker(startCtx, userID, batchID, workerToken) + return nil + } + return service.RecoverWithStarter(ctx, startWorker) +} + +// RecoverWithStarter 使用调用方提供的 worker 启动回调执行一轮恢复扫描。 +// 回调由生命周期协调器提供,避免恢复服务反向依赖 Server 或复制取消表。 +func (service *BatchRecoveryService) RecoverWithStarter(ctx context.Context, startWorker BatchWorkerStarterWithError) error { + if service == nil || service.repository == nil { return errors.New("批量恢复服务未初始化") } + if startWorker == nil { + return errors.New("批量恢复 worker 回调未初始化") + } + if ctx == nil { + return errors.New("批量恢复 Context 不能为空") + } + return service.recoverWithStarter(ctx, startWorker) +} + +// recoverWithStarter 执行恢复扫描主体,允许不同生命周期协调器接管 worker 启动。 +func (service *BatchRecoveryService) recoverWithStarter(ctx context.Context, startWorker BatchWorkerStarterWithError) error { // now 保存本轮扫描的当前 Unix 秒,确保查询和租约计算使用同一时间基准。 now := service.options.Now().UTC() // batches 保存数据库返回的可恢复批次快照。 @@ -126,7 +155,10 @@ func (service *BatchRecoveryService) Recover(ctx context.Context) error { _, _, _ = service.repository.FinalizeBatch(ctx, batch.ID, workerToken) continue } - service.options.StartWorker(ctx, batch.UserID, batch.ID, workerToken) + // startErr 保存生命周期协调器启动 worker 时的错误。 + if startErr := startWorker(ctx, batch.UserID, batch.ID, workerToken); startErr != nil { + service.releaseClaimedBatch(ctx, batch.ID, workerToken) + } } return nil } diff --git a/internal/application/items/batch_recovery_test.go b/internal/application/items/batch_recovery_test.go index b417843..58d6b22 100644 --- a/internal/application/items/batch_recovery_test.go +++ b/internal/application/items/batch_recovery_test.go @@ -202,3 +202,29 @@ func TestBatchRecoveryReportsScanFailure(t *testing.T) { t.Fatalf("恢复扫描错误=%v,期望=%v", runErr, scanErr) } } + +// TestBatchRecoveryAllowsCoordinatorStarter 验证恢复服务可由外部协调器注入 worker 回调,而不必在构造时绑定 Server。 +func TestBatchRecoveryAllowsCoordinatorStarter(t *testing.T) { + // repository 保存一个待恢复批次及可处理明细。 + repository := &batchRecoveryRepositoryFake{batches: []BatchInfo{{ID: "batch-coordinator", UserID: 7, Status: "running"}}, pending: map[string][]BatchRow{"batch-coordinator": {{ID: 1}}}} + // service、err 保存不绑定默认 worker 回调的恢复服务。 + service, err := NewBatchRecoveryService(repository, BatchRecoveryOptions{}) + if err != nil { + t.Fatalf("构造无回调恢复服务失败: %v", err) + } + // recoverErr 保存旧 Recover 入口在没有默认回调时返回的边界错误。 + recoverErr := service.Recover(context.Background()) + if recoverErr == nil { + t.Fatal("无默认回调时 Recover 应返回边界错误") + } + // started 保存外部协调器回调收到的批次启动次数。 + started := 0 + // err 保存外部回调驱动恢复扫描的错误。 + err = service.RecoverWithStarter(context.Background(), func(context.Context, int64, string, string) error { + started++ + return nil + }) + if err != nil || started != 1 { + t.Fatalf("外部回调恢复异常: err=%v started=%d", err, started) + } +} diff --git a/internal/application/items/batch_worker_coordinator.go b/internal/application/items/batch_worker_coordinator.go new file mode 100644 index 0000000..bb50faf --- /dev/null +++ b/internal/application/items/batch_worker_coordinator.go @@ -0,0 +1,320 @@ +package items + +import ( + "context" + "errors" + "strings" + "sync" + "time" +) + +const ( + // defaultBatchWorkerTimeout 限制单个商品批次 worker 的最长运行时间。 + defaultBatchWorkerTimeout = 2 * time.Hour + // defaultBatchRecoveryInterval 控制商品批次恢复扫描的默认轮询周期。 + defaultBatchRecoveryInterval = time.Minute +) + +var ( + // ErrBatchWorkerCoordinatorStopped 表示批次 worker 协调器已关闭,不能再接收新 worker。 + ErrBatchWorkerCoordinatorStopped = errors.New("批量发布 worker 协调器已停止") + // ErrBatchWorkerCoordinatorInvalidJob 表示批次标识、用户标识或租约令牌无效。 + ErrBatchWorkerCoordinatorInvalidJob = errors.New("批量发布 worker 参数无效") +) + +// BatchWorkerCoordinatorOptions 配置批量 worker 超时、恢复扫描和异步错误观测策略。 +type BatchWorkerCoordinatorOptions struct { + // WorkerTimeout 是单个批次 worker 的最长运行时间,非正值使用默认值。 + WorkerTimeout time.Duration + // RecoveryInterval 是恢复扫描循环两次扫描之间的等待时间,非正值使用默认值。 + RecoveryInterval time.Duration + // OnWorkerError 接收异步 worker 的业务或终态错误;nil 时错误不向外传播。 + OnWorkerError func(string, error) + // OnRecoveryError 接收恢复扫描的基础设施错误;nil 时错误只结束当前扫描。 + OnRecoveryError func(error) +} + +// batchWorkerHandle 保存批次 worker 的租约令牌和取消控制。 +type batchWorkerHandle struct { + // token 是当前 worker 持有的批次租约令牌。 + token string + // cancel 取消当前 worker 的超时 Context。 + cancel context.CancelFunc +} + +// BatchWorkerCoordinator 拥有批次 worker 取消表、超时、恢复扫描和关闭等待生命周期。 +// mu 保护 workers、active、done、recoveryCancel 与 stopped;锁内只修改内存状态或触发取消,不执行仓储、平台或文件 I/O。 +type BatchWorkerCoordinator struct { + // runner 执行逐行发布、租约续期和批次状态收口。 + runner *BatchRunner + // recovery 编排过期批次的租约接管和恢复准备。 + recovery *BatchRecoveryService + // options 保存 worker 生命周期与错误观测策略。 + options BatchWorkerCoordinatorOptions + // mu 保护 worker 表和生命周期计数。 + mu sync.Mutex + // workers 保存按批次标识索引的可取消 worker。 + workers map[string]*batchWorkerHandle + // active 保存 worker 与恢复扫描 goroutine 的总数。 + active int + // done 在 active 归零时关闭;下一批活动任务开始时重新创建。 + done chan struct{} + // recoveryCancel 取消当前恢复扫描循环;同一协调器最多运行一个循环。 + recoveryCancel context.CancelFunc + // stopped 表示协调器不再接受新的 worker 或恢复扫描。 + stopped bool +} + +// NewBatchWorkerCoordinator 创建批量 worker 生命周期协调器并校验必需应用端口。 +func NewBatchWorkerCoordinator(runner *BatchRunner, recovery *BatchRecoveryService, options BatchWorkerCoordinatorOptions) (*BatchWorkerCoordinator, error) { + if runner == nil { + return nil, errors.New("批量 worker runner 不能为空") + } + if recovery == nil { + return nil, errors.New("批量 worker 恢复服务不能为空") + } + if options.WorkerTimeout <= 0 { + options.WorkerTimeout = defaultBatchWorkerTimeout + } + if options.RecoveryInterval <= 0 { + options.RecoveryInterval = defaultBatchRecoveryInterval + } + return &BatchWorkerCoordinator{runner: runner, recovery: recovery, options: options, workers: make(map[string]*batchWorkerHandle), done: closedBatchWorkerSignal()}, nil +} + +// Start 启动一个已经由应用服务声明租约的批次 worker。 +// ctx 必须来自应用生命周期;HTTP 请求 Context 不得直接作为后台 worker 的父 Context。 +func (coordinator *BatchWorkerCoordinator) Start(ctx context.Context, userID int64, batchID, workerToken string) error { + if coordinator == nil || coordinator.runner == nil || coordinator.recovery == nil { + return errors.New("批量 worker 协调器未初始化") + } + if ctx == nil { + return errors.New("批量 worker 生命周期 Context 不能为空") + } + if userID <= 0 || strings.TrimSpace(batchID) == "" || strings.TrimSpace(workerToken) == "" { + return ErrBatchWorkerCoordinatorInvalidJob + } + // workerCtx、cancel 限制批次 worker 最长运行时间并继承应用关闭信号。 + workerCtx, cancel := context.WithTimeout(ctx, coordinator.options.WorkerTimeout) + coordinator.mu.Lock() + if coordinator.stopped { + coordinator.mu.Unlock() + cancel() + return ErrBatchWorkerCoordinatorStopped + } + // previous 保存同一批次旧 worker 的控制句柄;租约切换时必须先取消旧 worker。 + previous := coordinator.workers[batchID] + if previous != nil && previous.cancel != nil { + previous.cancel() + } + // worker 保存新登记的批次控制句柄;指针身份防止旧 worker 退出时误删新 worker。 + worker := &batchWorkerHandle{token: workerToken, cancel: cancel} + coordinator.workers[batchID] = worker + coordinator.beginActiveLocked() + coordinator.mu.Unlock() + go coordinator.runWorker(workerCtx, cancel, userID, batchID, workerToken, worker) + return nil +} + +// Cancel 取消仍登记在协调器中的指定批次 worker,并校验租约令牌避免误取消新 worker。 +func (coordinator *BatchWorkerCoordinator) Cancel(batchID, workerToken string) bool { + if coordinator == nil || strings.TrimSpace(batchID) == "" || strings.TrimSpace(workerToken) == "" { + return false + } + coordinator.mu.Lock() + // worker 保存当前批次的内存取消控制句柄。 + worker := coordinator.workers[batchID] + coordinator.mu.Unlock() + if worker == nil || worker.token != workerToken || worker.cancel == nil { + return false + } + worker.cancel() + return true +} + +// RunRecovery 执行一轮批次恢复扫描,并由协调器接管恢复 worker 的生命周期。 +func (coordinator *BatchWorkerCoordinator) RunRecovery(ctx context.Context) error { + if coordinator == nil || coordinator.runner == nil || coordinator.recovery == nil { + return errors.New("批量 worker 协调器未初始化") + } + if ctx == nil { + return errors.New("批量恢复 Context 不能为空") + } + // startWorker 将恢复服务的 worker 启动回调绑定到当前协调器。 + startWorker := func(startCtx context.Context, userID int64, batchID, workerToken string) error { + return coordinator.Start(startCtx, userID, batchID, workerToken) + } + return coordinator.recovery.RecoverWithStarter(ctx, startWorker) +} + +// StartRecovery 启动单一批次恢复扫描循环,并纳入协调器 Stop/Wait 生命周期。 +func (coordinator *BatchWorkerCoordinator) StartRecovery(parent context.Context) error { + if coordinator == nil || coordinator.runner == nil || coordinator.recovery == nil { + return errors.New("批量 worker 协调器未初始化") + } + if parent == nil { + return errors.New("批量恢复生命周期 Context 不能为空") + } + coordinator.mu.Lock() + if coordinator.stopped { + coordinator.mu.Unlock() + return ErrBatchWorkerCoordinatorStopped + } + if coordinator.recoveryCancel != nil { + coordinator.mu.Unlock() + return nil + } + // recoveryCtx、cancel 只负责恢复循环本身;Close 时由协调器统一取消。 + recoveryCtx, cancel := context.WithCancel(parent) + coordinator.recoveryCancel = cancel + coordinator.beginActiveLocked() + coordinator.mu.Unlock() + go coordinator.runRecoveryLoop(recoveryCtx, cancel) + return nil +} + +// Stop 取消全部批次 worker 和恢复扫描循环;方法可安全重复调用。 +func (coordinator *BatchWorkerCoordinator) Stop() { + if coordinator == nil { + return + } + coordinator.mu.Lock() + if coordinator.stopped { + coordinator.mu.Unlock() + return + } + coordinator.stopped = true + // cancels 保存锁内快照,解锁后调用取消函数,避免取消操作重入生命周期锁。 + cancels := make([]context.CancelFunc, 0, len(coordinator.workers)+1) + // worker 表示当前仍登记在内存取消表中的批次控制句柄。 + for _, worker := range coordinator.workers { + if worker != nil && worker.cancel != nil { + cancels = append(cancels, worker.cancel) + } + } + if coordinator.recoveryCancel != nil { + cancels = append(cancels, coordinator.recoveryCancel) + } + // coordinator.workers 立即清空,保证 Stop 返回后不会继续暴露已停止的取消句柄。 + coordinator.workers = make(map[string]*batchWorkerHandle) + coordinator.mu.Unlock() + // cancel 保存当前待触发的取消函数;取消本身不执行平台、数据库或文件 I/O。 + for _, cancel := range cancels { + cancel() + } +} + +// Wait 等待当前协调器登记的 worker 和恢复扫描循环全部退出。 +func (coordinator *BatchWorkerCoordinator) Wait() { + if coordinator == nil { + return + } + coordinator.mu.Lock() + // done 保存当前 active 归零信号;读取后立即解锁,避免阻塞生命周期变更。 + done := coordinator.done + coordinator.mu.Unlock() + <-done +} + +// Close 停止协调器并在 Context 截止前等待全部后台任务退出。 +func (coordinator *BatchWorkerCoordinator) Close(ctx context.Context) error { + if coordinator == nil { + return nil + } + if ctx == nil { + return errors.New("关闭批量 worker 协调器的 Context 不能为空") + } + coordinator.Stop() + coordinator.mu.Lock() + // done 保存 Stop 后仍在退出的 worker 与恢复循环完成信号。 + done := coordinator.done + coordinator.mu.Unlock() + select { + case <-done: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// runWorker 执行批次发布业务,并在退出时清除租约对应的取消句柄和活动计数。 +func (coordinator *BatchWorkerCoordinator) runWorker(ctx context.Context, cancel context.CancelFunc, userID int64, batchID, workerToken string, worker *batchWorkerHandle) { + defer cancel() + defer coordinator.finishWorker(batchID, workerToken, worker) + // err 保存批次发布业务或状态收口错误,交给装配层观测回调。 + err := coordinator.runner.Run(ctx, userID, batchID, workerToken, false) + if err != nil && coordinator.options.OnWorkerError != nil { + coordinator.options.OnWorkerError(batchID, err) + } +} + +// runRecoveryLoop 按固定间隔执行批次恢复扫描,直到生命周期 Context 取消。 +func (coordinator *BatchWorkerCoordinator) runRecoveryLoop(ctx context.Context, cancel context.CancelFunc) { + defer cancel() + defer coordinator.finishRecovery() + // err 保存首次恢复扫描错误;报告后继续等待下一轮。 + if err := coordinator.RunRecovery(ctx); err != nil && coordinator.options.OnRecoveryError != nil && !errors.Is(err, context.Canceled) { + coordinator.options.OnRecoveryError(err) + } + // ticker 保存恢复扫描间隔计时器,由当前 goroutine 独占并负责停止。 + ticker := time.NewTicker(coordinator.options.RecoveryInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + // err 保存本轮恢复扫描错误;单轮失败不阻塞后续轮次。 + if err := coordinator.RunRecovery(ctx); err != nil && coordinator.options.OnRecoveryError != nil && !errors.Is(err, context.Canceled) { + coordinator.options.OnRecoveryError(err) + } + } + } +} + +// beginActiveLocked 登记一个批次 worker 或恢复循环;调用方必须持有 coordinator.mu。 +func (coordinator *BatchWorkerCoordinator) beginActiveLocked() { + if coordinator.active == 0 { + coordinator.done = make(chan struct{}) + } + coordinator.active++ +} + +// finishWorker 清除仍匹配当前租约的 worker 控制句柄并减少活动计数。 +func (coordinator *BatchWorkerCoordinator) finishWorker(batchID, workerToken string, worker *batchWorkerHandle) { + coordinator.mu.Lock() + // current 保存批次当前登记的控制句柄,用于防止旧 worker 删除新租约。 + current := coordinator.workers[batchID] + if current == worker && current.token == workerToken { + delete(coordinator.workers, batchID) + } + coordinator.finishActiveLocked() + coordinator.mu.Unlock() +} + +// finishRecovery 清除恢复循环句柄并减少活动计数。 +func (coordinator *BatchWorkerCoordinator) finishRecovery() { + coordinator.mu.Lock() + coordinator.recoveryCancel = nil + coordinator.finishActiveLocked() + coordinator.mu.Unlock() +} + +// finishActiveLocked 减少活动计数并在归零时关闭 done;调用方必须持有 coordinator.mu。 +func (coordinator *BatchWorkerCoordinator) finishActiveLocked() { + if coordinator.active <= 0 { + return + } + coordinator.active-- + if coordinator.active == 0 { + close(coordinator.done) + } +} + +// closedBatchWorkerSignal 创建已关闭的生命周期信号,供没有活动任务的 Wait 立即返回。 +func closedBatchWorkerSignal() chan struct{} { + // done 保存初始无活动任务状态的关闭信号。 + done := make(chan struct{}) + close(done) + return done +} diff --git a/internal/application/items/batch_worker_coordinator_test.go b/internal/application/items/batch_worker_coordinator_test.go new file mode 100644 index 0000000..9b1c82c --- /dev/null +++ b/internal/application/items/batch_worker_coordinator_test.go @@ -0,0 +1,187 @@ +package items + +import ( + "context" + "errors" + "testing" + "time" +) + +// batchCoordinatorBlockingPublisher 在收到 worker Context 后等待取消,用于验证协调器取消传播。 +type batchCoordinatorBlockingPublisher struct { + // started 通知测试 worker 已经进入平台发布阶段。 + started chan struct{} +} + +// PublishRow 等待 Context 取消并返回取消错误,模拟不可控外部发布调用。 +func (publisher *batchCoordinatorBlockingPublisher) PublishRow(ctx context.Context, _ int64, _ BatchRow, _ string) error { + select { + case publisher.started <- struct{}{}: + default: + } + <-ctx.Done() + return ctx.Err() +} + +// batchCoordinatorEmptyPublisher 立即返回成功,用于恢复扫描的生命周期收口。 +type batchCoordinatorEmptyPublisher struct{} + +// PublishRow 返回成功,避免测试等待真实平台调用。 +func (batchCoordinatorEmptyPublisher) PublishRow(context.Context, int64, BatchRow, string) error { + return nil +} + +// newBatchWorkerCoordinatorFixture 创建批次协调器测试共用的 runner 和仓储替身。 +func newBatchWorkerCoordinatorFixture(t *testing.T, publisher BatchPublisher) (*BatchWorkerCoordinator, *batchRunnerRepository) { + // repository 保存一个正在运行且包含一条待发布明细的批次。 + repository := &batchRunnerRepository{rows: []BatchRow{{ID: 1, BatchID: "batch-1"}}, batch: BatchInfo{ID: "batch-1", UserID: 7, Status: "running", WorkerToken: "token-1"}} + // runner、err 保存应用层批次 worker。 + runner, err := NewBatchRunner(repository, publisher, BatchRunOptions{Wait: func(context.Context, time.Duration) error { return nil }, JobDelay: func(int) time.Duration { return 0 }}) + if err != nil { + t.Fatalf("构造批次 runner: %v", err) + } + // recovery、recoveryErr 保存最小恢复服务;协调器通过 RecoverWithStarter 注入自身启动回调。 + recovery, recoveryErr := NewBatchRecoveryService(&batchRecoveryRepositoryFake{}, BatchRecoveryOptions{StartWorker: func(context.Context, int64, string, string) {}}) + if recoveryErr != nil { + t.Fatalf("构造批次恢复服务: %v", recoveryErr) + } + // coordinator、coordinatorErr 保存批次 worker 生命周期协调器。 + coordinator, coordinatorErr := NewBatchWorkerCoordinator(runner, recovery, BatchWorkerCoordinatorOptions{WorkerTimeout: time.Minute}) + if coordinatorErr != nil { + t.Fatalf("构造批次协调器: %v", coordinatorErr) + } + return coordinator, repository +} + +// TestBatchWorkerCoordinatorCancelClose 验证 worker 取消表、超时 Context 和 Close/Wait 生命周期。 +func TestBatchWorkerCoordinatorCancelClose(t *testing.T) { + // publisher 等待协调器取消,以证明后台 worker 没有脱离 Context。 + publisher := &batchCoordinatorBlockingPublisher{started: make(chan struct{}, 1)} + // coordinator、repository 保存生命周期测试对象。 + coordinator, repository := newBatchWorkerCoordinatorFixture(t, publisher) + // ctx 是协调器 worker 的应用生命周期 Context。 + ctx := context.Background() + // err 保存 worker 启动阶段的生命周期校验错误。 + if err := coordinator.Start(ctx, 7, "batch-1", "token-1"); err != nil { + t.Fatalf("启动批次 worker: %v", err) + } + select { + case <-publisher.started: + case <-time.After(time.Second): + t.Fatal("批次 worker 未进入发布阶段") + } + if coordinator.Cancel("batch-1", "stale-token") { + t.Fatal("旧租约令牌不应取消当前 worker") + } + if !coordinator.Cancel("batch-1", "token-1") { + t.Fatal("当前租约令牌未取消 worker") + } + // closeCtx 限制关闭等待,防止 worker 生命周期回归测试无限阻塞。 + closeCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // err 保存批次协调器关闭错误。 + if err := coordinator.Close(closeCtx); err != nil { + t.Fatalf("关闭批次协调器: %v", err) + } + coordinator.Wait() + if coordinator.Cancel("batch-1", "token-1") { + t.Fatal("worker 退出后不应仍可取消") + } + if repository.finalized == 0 { + t.Fatal("取消 worker 未执行批次中断收口") + } +} + +// TestBatchWorkerCoordinatorTokenFencing 验证同一批次的新租约会取消旧 worker,旧 token 不能取消新 worker。 +func TestBatchWorkerCoordinatorTokenFencing(t *testing.T) { + // publisher 等待 Context 取消,方便观察旧 worker 是否被 fencing。 + publisher := &batchCoordinatorBlockingPublisher{started: make(chan struct{}, 4)} + // coordinator、repository 保存 token fencing 测试对象。 + coordinator, _ := newBatchWorkerCoordinatorFixture(t, publisher) + // err 保存旧 worker 启动阶段的错误。 + if err := coordinator.Start(context.Background(), 7, "batch-1", "token-old"); err != nil { + t.Fatalf("启动旧 worker: %v", err) + } + select { + case <-publisher.started: + case <-time.After(time.Second): + t.Fatal("旧 worker 未进入发布阶段") + } + // err 保存新 worker 替换旧 worker 时的错误。 + if err := coordinator.Start(context.Background(), 7, "batch-1", "token-new"); err != nil { + t.Fatalf("启动新 worker: %v", err) + } + if coordinator.Cancel("batch-1", "token-old") { + t.Fatal("旧 token 不应取消新 worker") + } + if !coordinator.Cancel("batch-1", "token-new") { + t.Fatal("新 token 未取消当前 worker") + } + // closeCtx 限制 fencing worker 的退出等待时间。 + closeCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // err 保存 fencing 协调器关闭错误。 + if err := coordinator.Close(closeCtx); err != nil { + t.Fatalf("关闭 fencing 协调器: %v", err) + } +} + +// TestBatchWorkerCoordinatorRecoveryLifecycle 验证恢复扫描由协调器启动、观测错误并纳入 Close 等待。 +func TestBatchWorkerCoordinatorRecoveryLifecycle(t *testing.T) { + // scanErr 模拟恢复扫描数据库错误。 + scanErr := errors.New("恢复扫描失败") + // recoveryRepository 保存错误配置和恢复扫描端口。 + recoveryRepository := &batchRecoveryRepositoryFake{scanErr: scanErr} + // recovery、err 保存恢复服务。 + recovery, err := NewBatchRecoveryService(recoveryRepository, BatchRecoveryOptions{StartWorker: func(context.Context, int64, string, string) {}}) + if err != nil { + t.Fatalf("构造恢复服务: %v", err) + } + // runner、runnerErr 保存不执行商品行的最小 worker。 + runner, runnerErr := NewBatchRunner(&batchRunnerRepository{}, batchCoordinatorEmptyPublisher{}, BatchRunOptions{}) + if runnerErr != nil { + t.Fatalf("构造 runner: %v", runnerErr) + } + // observed 通知测试已收到恢复错误回调。 + observed := make(chan error, 1) + // coordinator、coordinatorErr 保存恢复生命周期协调器。 + coordinator, coordinatorErr := NewBatchWorkerCoordinator(runner, recovery, BatchWorkerCoordinatorOptions{RecoveryInterval: time.Hour, OnRecoveryError: func(err error) { observed <- err }}) + if coordinatorErr != nil { + t.Fatalf("构造协调器: %v", coordinatorErr) + } + // err 保存恢复循环启动错误。 + if err := coordinator.StartRecovery(context.Background()); err != nil { + t.Fatalf("启动恢复循环: %v", err) + } + select { + // observedErr 保存恢复错误回调传递的基础设施错误。 + case observedErr := <-observed: + if !errors.Is(observedErr, scanErr) { + t.Fatalf("恢复错误不匹配: %v", observedErr) + } + case <-time.After(time.Second): + t.Fatal("未收到恢复错误回调") + } + // closeCtx 限制恢复循环关闭等待时间。 + closeCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // err 保存恢复协调器关闭错误。 + if err := coordinator.Close(closeCtx); err != nil { + t.Fatalf("关闭恢复协调器: %v", err) + } +} + +// TestBatchWorkerCoordinatorRejectsAfterStop 验证 Stop 后不再接受 worker 或恢复扫描。 +func TestBatchWorkerCoordinatorRejectsAfterStop(t *testing.T) { + // coordinator 保存最小生命周期协调器。 + coordinator, _ := newBatchWorkerCoordinatorFixture(t, batchCoordinatorEmptyPublisher{}) + coordinator.Stop() + // err 保存 Stop 后启动 worker 的错误。 + if err := coordinator.Start(context.Background(), 7, "batch-1", "token-1"); !errors.Is(err, ErrBatchWorkerCoordinatorStopped) { + t.Fatalf("Stop 后仍接受 worker: %v", err) + } + // err 保存 Stop 后启动恢复循环的错误。 + if err := coordinator.StartRecovery(context.Background()); !errors.Is(err, ErrBatchWorkerCoordinatorStopped) { + t.Fatalf("Stop 后仍接受恢复循环: %v", err) + } +} diff --git a/internal/application/lifecycle/coordinator.go b/internal/application/lifecycle/coordinator.go new file mode 100644 index 0000000..5b52f79 --- /dev/null +++ b/internal/application/lifecycle/coordinator.go @@ -0,0 +1,298 @@ +// Package lifecycle 提供应用组件统一的启动、取消、关闭和等待协调。 +// 组件由 cmd 在进程边界装配;协调器不依赖 HTTP、数据库或平台实现。 +package lifecycle + +import ( + "context" + "errors" + "fmt" + "sync" + "time" +) + +// ErrStopped 表示生命周期协调器已经关闭,不能再次启动。 +var ErrStopped = errors.New("应用生命周期协调器已关闭") + +// Component 定义一个可被进程生命周期拥有者启动和关闭的组件。 +type Component interface { + // Start 在给定进程 Context 下启动组件;返回错误时协调器会回滚已启动组件。 + Start(context.Context) error + // Close 在给定关闭 Context 下停止组件并等待其后台任务收束。 + Close(context.Context) error +} + +// NamedComponent 将稳定名称与生命周期组件绑定,便于失败日志定位。 +type NamedComponent struct { + // Name 是组件的稳定诊断名称,不承载敏感数据。 + Name string + // Component 是实际拥有后台任务的生命周期组件。 + Component Component +} + +// FuncComponent 将两个函数适配为生命周期组件;函数内部必须自行保证重复关闭幂等。 +type FuncComponent struct { + // StartFunc 执行组件启动;为空时视为无需启动。 + StartFunc func(context.Context) error + // CloseFunc 执行组件关闭;为空时视为无需关闭。 + CloseFunc func(context.Context) error +} + +// Start 启动函数适配组件。 +func (component FuncComponent) Start(ctx context.Context) error { + if component.StartFunc == nil { + return nil + } + return component.StartFunc(ctx) +} + +// Close 关闭函数适配组件。 +func (component FuncComponent) Close(ctx context.Context) error { + if component.CloseFunc == nil { + return nil + } + return component.CloseFunc(ctx) +} + +// Coordinator 统一拥有进程级 Context、组件启动顺序和反向关闭顺序。 +// mu 只保护状态与取消函数;组件 Start/Close 始终在锁外执行,避免持锁等待外部 I/O。 +type Coordinator struct { + // mu 保护 started、closing、closed、parentCancel 和关闭结果。 + mu sync.Mutex + // components 保存按启动顺序登记的组件。 + components []NamedComponent + // startedCount 表示已经成功或正在启动的组件数量;失败回滚时包含当前组件。 + startedCount int + // lifecycleCtx 是所有后台组件共享的进程生命周期 Context。 + lifecycleCtx context.Context + // parentCancel 取消所有组件继承的生命周期 Context。 + parentCancel context.CancelFunc + // started 表示协调器是否已接受启动请求。 + started bool + // starting 表示组件启动回调正在执行;关闭调用必须等待该阶段结束。 + starting bool + // startDone 在启动阶段结束后关闭,供并发 Close 等待而不持锁阻塞。 + startDone chan struct{} + // closing 表示当前是否已有关闭调用在执行。 + closing bool + // closed 表示协调器已完成关闭且不再允许启动。 + closed bool + // done 在关闭完成后关闭,供并发 Close/Wait 调用等待。 + done chan struct{} + // closeErr 保存首次关闭或启动回滚的聚合错误。 + closeErr error +} + +// NewCoordinator 创建空的生命周期协调器;组件必须在 Start 前通过 Add 登记。 +func NewCoordinator() *Coordinator { + return &Coordinator{done: make(chan struct{})} +} + +// Add 登记一个生命周期组件;启动后或关闭后禁止修改组件集合。 +func (coordinator *Coordinator) Add(component NamedComponent) error { + if coordinator == nil { + return errors.New("生命周期协调器未初始化") + } + if component.Component == nil { + return errors.New("生命周期组件不能为空") + } + if component.Name == "" { + return errors.New("生命周期组件名称不能为空") + } + coordinator.mu.Lock() + defer coordinator.mu.Unlock() + if coordinator.started || coordinator.closing || coordinator.closed { + return errors.New("生命周期协调器已开始运行,不能追加组件") + } + coordinator.components = append(coordinator.components, component) + return nil +} + +// Context 返回应用组件共享的生命周期 Context;未启动时返回可取消前的空闲 Context。 +func (coordinator *Coordinator) Context() context.Context { + if coordinator == nil { + return context.Background() + } + coordinator.mu.Lock() + defer coordinator.mu.Unlock() + if coordinator.lifecycleCtx == nil { + return context.Background() + } + return coordinator.lifecycleCtx +} + +// Start 按登记顺序启动全部组件;任一组件失败时按逆序关闭已启动组件并拒绝再次启动。 +func (coordinator *Coordinator) Start(parent context.Context) error { + if coordinator == nil { + return errors.New("生命周期协调器未初始化") + } + if parent == nil { + return errors.New("生命周期父 Context 不能为空") + } + coordinator.mu.Lock() + if coordinator.closed || coordinator.closing { + coordinator.mu.Unlock() + return ErrStopped + } + if coordinator.started { + coordinator.mu.Unlock() + return nil + } + coordinator.starting = true + coordinator.startDone = make(chan struct{}) + // lifecycleCtx、cancel 保存全部组件共享的生命周期上下文和取消函数。 + lifecycleCtx, cancel := context.WithCancel(parent) + coordinator.lifecycleCtx = lifecycleCtx + coordinator.parentCancel = cancel + coordinator.started = true + // components 是启动阶段的组件快照,避免组件回调期间持有协调器锁。 + components := append([]NamedComponent(nil), coordinator.components...) + coordinator.mu.Unlock() + + // index、component 分别表示当前启动组件在登记快照中的序号和定义。 + for index, component := range components { + coordinator.mu.Lock() + coordinator.startedCount = index + 1 + coordinator.mu.Unlock() + // err 表示当前组件启动失败;失败会触发包含当前组件的逆序回滚。 + if err := component.Component.Start(lifecycleCtx); err != nil { + // rollbackErr 表示回滚已启动组件时追加产生的关闭错误。 + rollbackErr := coordinator.rollback(components[:index+1], cancel) + return fmt.Errorf("启动生命周期组件 %q 失败: %w", component.Name, errors.Join(err, rollbackErr)) + } + } + coordinator.mu.Lock() + coordinator.starting = false + close(coordinator.startDone) + coordinator.mu.Unlock() + return nil +} + +// rollback 在启动失败时逆序关闭已开始的组件,并永久结束协调器。 +func (coordinator *Coordinator) rollback(components []NamedComponent, cancel context.CancelFunc) error { + if cancel != nil { + cancel() + } + // rollbackContext 限制启动失败后的组件关闭时间;rollbackCancel 负责释放定时器。 + rollbackContext, rollbackCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer rollbackCancel() + // rollbackErr 聚合回滚期间各组件的关闭错误。 + var rollbackErr error + // index 表示当前逆序回滚的组件下标。 + for index := len(components) - 1; index >= 0; index-- { + // err 表示当前组件回滚关闭失败。 + if err := components[index].Component.Close(rollbackContext); err != nil { + rollbackErr = errors.Join(rollbackErr, fmt.Errorf("回滚生命周期组件 %q 失败: %w", components[index].Name, err)) + } + } + coordinator.mu.Lock() + coordinator.closed = true + coordinator.starting = false + if coordinator.startDone != nil { + close(coordinator.startDone) + } + coordinator.closing = false + coordinator.closeErr = rollbackErr + close(coordinator.done) + coordinator.mu.Unlock() + return rollbackErr +} + +// Close 取消进程 Context,并按登记逆序关闭所有组件;重复调用保持幂等。 +func (coordinator *Coordinator) Close(ctx context.Context) error { + if coordinator == nil { + return nil + } + if ctx == nil { + return errors.New("生命周期关闭 Context 不能为空") + } + for { + coordinator.mu.Lock() + if !coordinator.starting { + break + } + // startDone 是当前启动阶段的结束信号;等待时不持有协调器锁。 + startDone := coordinator.startDone + coordinator.mu.Unlock() + select { + case <-startDone: + continue + case <-ctx.Done(): + return ctx.Err() + } + } + if coordinator.closed { + // err 保存已完成关闭的历史错误,重复关闭直接复用该结果。 + err := coordinator.closeErr + coordinator.mu.Unlock() + return err + } + if coordinator.closing { + // done 是首个关闭调用完成时关闭的信号。 + done := coordinator.done + coordinator.mu.Unlock() + select { + case <-done: + coordinator.mu.Lock() + // err 保存首个关闭调用的聚合结果。 + err := coordinator.closeErr + coordinator.mu.Unlock() + return err + case <-ctx.Done(): + return ctx.Err() + } + } + coordinator.closing = true + // components 保存已经成功启动的组件快照,关闭时按其登记顺序逆序处理。 + components := append([]NamedComponent(nil), coordinator.components[:coordinator.startedCount]...) + // cancel 是协调器共享 Context 的取消函数;组件关闭前先广播取消。 + cancel := coordinator.parentCancel + coordinator.mu.Unlock() + + if cancel != nil { + cancel() + } + // closeErr 聚合全部组件关闭错误,确保后续组件仍有机会收束。 + var closeErr error + // index 表示当前逆序关闭的组件下标。 + for index := len(components) - 1; index >= 0; index-- { + // err 表示当前组件关闭失败。 + if err := components[index].Component.Close(ctx); err != nil { + closeErr = errors.Join(closeErr, fmt.Errorf("关闭生命周期组件 %q 失败: %w", components[index].Name, err)) + } + } + coordinator.mu.Lock() + coordinator.closed = true + coordinator.closing = false + coordinator.closeErr = closeErr + close(coordinator.done) + coordinator.mu.Unlock() + return closeErr +} + +// Wait 等待协调器关闭;未启动且未关闭的协调器会阻塞,调用者应先调用 Start 或 Close。 +func (coordinator *Coordinator) Wait() { + if coordinator == nil { + return + } + <-coordinator.done +} + +// WaitContext 在 Context 截止前等待协调器完成关闭。 +func (coordinator *Coordinator) WaitContext(ctx context.Context) error { + if coordinator == nil { + return nil + } + if ctx == nil { + return errors.New("生命周期等待 Context 不能为空") + } + select { + case <-coordinator.done: + coordinator.mu.Lock() + // err 保存协调器关闭时记录的聚合错误。 + err := coordinator.closeErr + coordinator.mu.Unlock() + return err + case <-ctx.Done(): + return ctx.Err() + } +} diff --git a/internal/application/lifecycle/coordinator_test.go b/internal/application/lifecycle/coordinator_test.go new file mode 100644 index 0000000..8a33e43 --- /dev/null +++ b/internal/application/lifecycle/coordinator_test.go @@ -0,0 +1,234 @@ +package lifecycle + +import ( + "context" + "errors" + "sync" + "testing" + "time" +) + +// lifecycleComponentFake 记录组件启动、关闭和顺序,用于验证协调器的所有权语义。 +type lifecycleComponentFake struct { + // name 是测试替身的诊断名称。 + name string + // events 记录启动和关闭事件。 + events *[]string + // mu 保护共享事件切片。 + mu *sync.Mutex + // startErr 是预置的启动失败。 + startErr error + // closeErr 是预置的关闭失败。 + closeErr error +} + +// Start 记录组件启动并按预置结果返回。 +func (fake *lifecycleComponentFake) Start(context.Context) error { + fake.mu.Lock() + *fake.events = append(*fake.events, "start:"+fake.name) + fake.mu.Unlock() + return fake.startErr +} + +// Close 记录组件关闭并按预置结果返回。 +func (fake *lifecycleComponentFake) Close(context.Context) error { + fake.mu.Lock() + *fake.events = append(*fake.events, "close:"+fake.name) + fake.mu.Unlock() + return fake.closeErr +} + +// TestCoordinatorStartsAndClosesInDeterministicOrder 验证正常启动、重复调用和逆序关闭。 +func TestCoordinatorStartsAndClosesInDeterministicOrder(t *testing.T) { + // events 保存生命周期事件顺序;mu 保护并发回调写入。 + events := make([]string, 0, 4) + // mu 串行化测试组件对事件切片的并发追加。 + mu := &sync.Mutex{} + // first、second 保存按顺序登记的两个组件。 + first := &lifecycleComponentFake{name: "first", events: &events, mu: mu} + // second 保存第二个按顺序启动、逆序关闭的测试组件。 + second := &lifecycleComponentFake{name: "second", events: &events, mu: mu} + // coordinator 保存待验证的生命周期协调器。 + coordinator := NewCoordinator() + // err 表示登记第一个组件时的参数校验错误。 + if err := coordinator.Add(NamedComponent{Name: "first", Component: first}); err != nil { + t.Fatalf("登记第一个组件失败: %v", err) + } + // err 表示登记第二个组件时的参数校验错误。 + if err := coordinator.Add(NamedComponent{Name: "second", Component: second}); err != nil { + t.Fatalf("登记第二个组件失败: %v", err) + } + // parent 保存进程级生命周期 Context。 + parent := context.Background() + // err 表示首次启动协调器的失败原因。 + if err := coordinator.Start(parent); err != nil { + t.Fatalf("启动协调器失败: %v", err) + } + // err 表示重复启动协调器的非预期错误。 + if err := coordinator.Start(parent); err != nil { + t.Fatalf("重复启动应幂等: %v", err) + } + if coordinator.Context() == context.Background() { + t.Fatal("启动后应返回专用生命周期 Context") + } + // err 表示首次关闭协调器的聚合错误。 + if err := coordinator.Close(context.Background()); err != nil { + t.Fatalf("关闭协调器失败: %v", err) + } + // err 表示重复关闭协调器的幂等结果。 + if err := coordinator.Close(context.Background()); err != nil { + t.Fatalf("重复关闭应幂等: %v", err) + } + // want 是生命周期回调必须产生的确定性顺序。 + want := []string{"start:first", "start:second", "close:second", "close:first"} + if !equalStrings(events, want) { + t.Fatalf("生命周期顺序=%v,期望=%v", events, want) + } +} + +// TestCoordinatorRollsBackOnStartFailure 验证启动失败会取消 Context、逆序回滚并拒绝后续启动。 +func TestCoordinatorRollsBackOnStartFailure(t *testing.T) { + // events 保存启动失败回滚过程中的事件顺序;mu 保护共享切片。 + events := make([]string, 0, 4) + // mu 串行化测试组件对事件切片的并发追加。 + mu := &sync.Mutex{} + // first、second 保存成功组件和失败组件。 + first := &lifecycleComponentFake{name: "first", events: &events, mu: mu} + // second 保存会在启动阶段返回错误的测试组件。 + second := &lifecycleComponentFake{name: "second", events: &events, mu: mu, startErr: errors.New("start failed")} + // coordinator 保存待验证的生命周期协调器。 + coordinator := NewCoordinator() + _ = coordinator.Add(NamedComponent{Name: "first", Component: first}) + _ = coordinator.Add(NamedComponent{Name: "second", Component: second}) + // err 表示启动失败回滚返回的聚合错误。 + if err := coordinator.Start(context.Background()); err == nil { + t.Fatal("组件启动失败应返回错误") + } + // err 表示回滚后再次启动收到的停止错误。 + if err := coordinator.Start(context.Background()); !errors.Is(err, ErrStopped) { + t.Fatalf("失败回滚后应拒绝再次启动: %v", err) + } + // want 是启动失败后包含失败组件在内的逆序回滚顺序。 + want := []string{"start:first", "start:second", "close:second", "close:first"} + if !equalStrings(events, want) { + t.Fatalf("回滚顺序=%v,期望=%v", events, want) + } +} + +// TestCoordinatorRejectsAddAfterStart 验证启动后不能追加组件,防止部分构造状态被观察。 +func TestCoordinatorRejectsAddAfterStart(t *testing.T) { + // coordinator 保存待验证的生命周期协调器。 + coordinator := NewCoordinator() + _ = coordinator.Add(NamedComponent{Name: "one", Component: FuncComponent{}}) + // err 表示单组件协调器启动错误。 + if err := coordinator.Start(context.Background()); err != nil { + t.Fatalf("启动协调器失败: %v", err) + } + // err 表示启动后追加组件返回的拒绝错误。 + if err := coordinator.Add(NamedComponent{Name: "late", Component: FuncComponent{}}); err == nil { + t.Fatal("启动后追加组件应失败") + } + // err 表示单组件协调器关闭错误。 + if err := coordinator.Close(context.Background()); err != nil { + t.Fatalf("关闭协调器失败: %v", err) + } +} + +// TestCoordinatorCloseContextBoundsConcurrentClose 验证并发关闭等待遵守调用方 Context。 +func TestCoordinatorCloseContextBoundsConcurrentClose(t *testing.T) { + // entered、release 同步第一个关闭调用的阻塞窗口。 + entered := make(chan struct{}) + // release 允许首个关闭回调结束,完成并发关闭测试。 + release := make(chan struct{}) + // component 保存阻塞关闭的测试组件。 + component := FuncComponent{ + CloseFunc: func(context.Context) error { + close(entered) + <-release + return nil + }, + } + // coordinator 保存待验证的生命周期协调器。 + coordinator := NewCoordinator() + _ = coordinator.Add(NamedComponent{Name: "blocking", Component: component}) + _ = coordinator.Start(context.Background()) + // firstDone 接收首个关闭调用的最终错误。 + firstDone := make(chan error, 1) + go func() { + firstDone <- coordinator.Close(context.Background()) + }() + <-entered + // timeoutCtx、cancel 控制第二个关闭调用的等待时限。 + timeoutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) + defer cancel() + // err 表示第二个关闭调用在等待首个关闭时收到的超时错误。 + if err := coordinator.Close(timeoutCtx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("并发关闭应返回等待超时: %v", err) + } + close(release) + // err 表示首个关闭调用在释放阻塞后返回的最终结果。 + if err := <-firstDone; err != nil { + t.Fatalf("首个关闭失败: %v", err) + } +} + +// TestCoordinatorCloseWaitsForStart 验证关闭不会越过仍在执行的组件启动回调。 +func TestCoordinatorCloseWaitsForStart(t *testing.T) { + // entered、release 控制组件启动回调的阻塞窗口。 + entered := make(chan struct{}) + // release 允许阻塞的启动回调继续完成。 + release := make(chan struct{}) + // component 保存会阻塞启动、随后允许正常关闭的测试组件。 + component := FuncComponent{ + StartFunc: func(context.Context) error { + close(entered) + <-release + return nil + }, + } + // coordinator 保存待验证的启动与关闭协调器。 + coordinator := NewCoordinator() + // err 表示登记阻塞组件时的参数校验错误。 + if err := coordinator.Add(NamedComponent{Name: "starting", Component: component}); err != nil { + t.Fatalf("登记阻塞组件失败: %v", err) + } + // startDone 接收组件启动结果。 + startDone := make(chan error, 1) + go func() { + startDone <- coordinator.Start(context.Background()) + }() + <-entered + // closeDone 接收并发关闭结果;关闭必须等待启动回调结束。 + closeDone := make(chan error, 1) + go func() { + closeDone <- coordinator.Close(context.Background()) + }() + select { + case <-closeDone: + t.Fatal("组件启动未结束时关闭不应提前返回") + case <-time.After(20 * time.Millisecond): + } + close(release) + // err 表示组件启动完成后的最终启动结果。 + if err := <-startDone; err != nil { + t.Fatalf("组件启动失败: %v", err) + } + // err 表示等待启动完成后执行的关闭结果。 + if err := <-closeDone; err != nil { + t.Fatalf("等待启动完成后的关闭失败: %v", err) + } +} + +// equalStrings 比较两个生命周期事件列表。 +func equalStrings(left, right []string) bool { + if len(left) != len(right) { + return false + } + // index 表示当前比较的生命周期事件下标。 + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} diff --git a/internal/application/orders/reconciliation_runner.go b/internal/application/orders/reconciliation_runner.go new file mode 100644 index 0000000..dbae111 --- /dev/null +++ b/internal/application/orders/reconciliation_runner.go @@ -0,0 +1,138 @@ +package orders + +import ( + "context" + "errors" + "sync" +) + +// ReconciliationRecovery 定义订单补偿扫描器的最小生命周期能力。 +type ReconciliationRecovery interface { + // Run 持续扫描待补偿订单,直到传入 Context 被取消。 + Run(context.Context) +} + +// ErrReconciliationRecoveryStopped 表示补偿扫描器已经关闭,不能再次启动。 +var ErrReconciliationRecoveryStopped = errors.New("订单补偿扫描器已关闭") + +// ReconciliationRecoveryCoordinator 拥有订单补偿扫描器的启动、取消、等待和关闭生命周期。 +// mu 保护 cancel、done 与 stopped;锁内只更新状态,不调用补偿数据库或平台 I/O。 +type ReconciliationRecoveryCoordinator struct { + // recovery 执行补偿扫描业务,具体数据库访问由 adapter 实现。 + recovery ReconciliationRecovery + // mu 保护生命周期字段并串行化重复 Start/Stop 调用。 + mu sync.Mutex + // cancel 取消当前补偿扫描循环;为空表示当前未运行。 + cancel context.CancelFunc + // done 在当前扫描循环退出时关闭;无运行循环时保持已关闭信号。 + done chan struct{} + // stopped 表示协调器已拒绝后续启动。 + stopped bool +} + +// NewReconciliationRecoveryCoordinator 创建订单补偿扫描生命周期协调器。 +func NewReconciliationRecoveryCoordinator(recovery ReconciliationRecovery) (*ReconciliationRecoveryCoordinator, error) { + if recovery == nil { + return nil, errors.New("订单补偿扫描器不能为空") + } + return &ReconciliationRecoveryCoordinator{recovery: recovery, done: closedReconciliationSignal()}, nil +} + +// Start 启动单一补偿扫描循环;重复启动保持幂等,生命周期 Context 由调用方提供。 +func (coordinator *ReconciliationRecoveryCoordinator) Start(parent context.Context) error { + if coordinator == nil || coordinator.recovery == nil { + return errors.New("订单补偿扫描协调器未初始化") + } + if parent == nil { + return errors.New("订单补偿扫描生命周期 Context 不能为空") + } + coordinator.mu.Lock() + if coordinator.stopped { + coordinator.mu.Unlock() + return ErrReconciliationRecoveryStopped + } + if coordinator.cancel != nil { + coordinator.mu.Unlock() + return nil + } + // recoveryCtx、cancel 控制当前补偿扫描循环;Stop/Close 通过 cancel 触发退出。 + recoveryCtx, cancel := context.WithCancel(parent) + // done 保存当前补偿扫描循环的退出信号。 + done := make(chan struct{}) + coordinator.cancel = cancel + coordinator.done = done + coordinator.mu.Unlock() + go coordinator.run(recoveryCtx, done) + return nil +} + +// Stop 取消补偿扫描循环并拒绝后续启动;重复调用保持幂等。 +func (coordinator *ReconciliationRecoveryCoordinator) Stop() { + if coordinator == nil { + return + } + coordinator.mu.Lock() + if coordinator.stopped { + coordinator.mu.Unlock() + return + } + coordinator.stopped = true + // cancel 保存当前循环取消函数;解锁后调用避免回调重入生命周期锁。 + cancel := coordinator.cancel + coordinator.mu.Unlock() + if cancel != nil { + cancel() + } +} + +// Wait 等待当前补偿扫描循环退出;未启动时立即返回。 +func (coordinator *ReconciliationRecoveryCoordinator) Wait() { + if coordinator == nil { + return + } + coordinator.mu.Lock() + // done 保存当前生命周期的退出信号;读取后立即解锁以允许扫描器收尾。 + done := coordinator.done + coordinator.mu.Unlock() + <-done +} + +// Close 停止补偿扫描器并在 Context 截止前等待 goroutine 退出。 +func (coordinator *ReconciliationRecoveryCoordinator) Close(ctx context.Context) error { + if coordinator == nil { + return nil + } + if ctx == nil { + return errors.New("关闭订单补偿扫描器的 Context 不能为空") + } + coordinator.Stop() + coordinator.mu.Lock() + // done 保存 Stop 后仍可能运行的补偿扫描循环退出信号。 + done := coordinator.done + coordinator.mu.Unlock() + select { + case <-done: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// run 执行补偿扫描并在退出时发布生命周期信号。 +func (coordinator *ReconciliationRecoveryCoordinator) run(ctx context.Context, done chan struct{}) { + defer close(done) + coordinator.recovery.Run(ctx) + coordinator.mu.Lock() + if coordinator.done == done { + coordinator.cancel = nil + } + coordinator.mu.Unlock() +} + +// closedReconciliationSignal 创建已关闭信号,供未启动的 Wait/Close 立即返回。 +func closedReconciliationSignal() chan struct{} { + // done 保存无活动扫描器状态的关闭信号。 + done := make(chan struct{}) + close(done) + return done +} diff --git a/internal/application/orders/reconciliation_runner_test.go b/internal/application/orders/reconciliation_runner_test.go new file mode 100644 index 0000000..b88893e --- /dev/null +++ b/internal/application/orders/reconciliation_runner_test.go @@ -0,0 +1,92 @@ +package orders + +import ( + "context" + "errors" + "sync" + "testing" + "time" +) + +// reconciliationRecoveryFake 是可观测补偿扫描器测试替身。 +type reconciliationRecoveryFake struct { + // started 通知扫描循环已经启动。 + started chan struct{} + // stopped 通知扫描循环收到取消并退出。 + stopped chan struct{} + // once 防止测试替身重复关闭通知 channel。 + once sync.Once +} + +// Run 等待 Context 取消,模拟真实补偿服务的长期扫描循环。 +func (f *reconciliationRecoveryFake) Run(ctx context.Context) { + close(f.started) + <-ctx.Done() + f.once.Do(func() { close(f.stopped) }) +} + +// TestReconciliationRecoveryCoordinatorLifecycle 验证补偿扫描器启动、停止、等待和重复关闭语义。 +func TestReconciliationRecoveryCoordinatorLifecycle(t *testing.T) { + // recovery 保存可观测补偿扫描器替身。 + recovery := &reconciliationRecoveryFake{started: make(chan struct{}), stopped: make(chan struct{})} + // coordinator 保存当前补偿扫描生命周期协调器。 + // coordinator 保存补偿扫描生命周期协调器;err 保存构造失败原因。 + coordinator, err := NewReconciliationRecoveryCoordinator(recovery) + if err != nil { + t.Fatalf("构造补偿扫描协调器失败: %v", err) + } + // err 保存首次启动补偿扫描器的生命周期错误。 + if err := coordinator.Start(context.Background()); err != nil { + t.Fatalf("启动补偿扫描失败: %v", err) + } + select { + case <-recovery.started: + case <-time.After(time.Second): + t.Fatal("补偿扫描未启动") + } + // err 保存重复启动补偿扫描器的生命周期错误。 + if err := coordinator.Start(context.Background()); err != nil { + t.Fatalf("重复启动应保持幂等: %v", err) + } + // err 保存首次关闭补偿扫描器的生命周期错误。 + if err := coordinator.Close(context.Background()); err != nil { + t.Fatalf("关闭补偿扫描失败: %v", err) + } + select { + case <-recovery.stopped: + case <-time.After(time.Second): + t.Fatal("补偿扫描未收到停止信号") + } + coordinator.Wait() + if !errors.Is(coordinator.Start(context.Background()), ErrReconciliationRecoveryStopped) { + t.Fatal("关闭后的补偿扫描器应拒绝再次启动") + } + // err 保存重复关闭补偿扫描器的生命周期错误。 + if err := coordinator.Close(context.Background()); err != nil { + t.Fatalf("重复关闭应保持幂等: %v", err) + } +} + +// TestReconciliationRecoveryCoordinatorRequiresDependencies 验证缺失依赖、Context 和关闭参数会快速失败。 +func TestReconciliationRecoveryCoordinatorRequiresDependencies(t *testing.T) { + // missingErr 保存缺少补偿扫描器时的构造错误。 + _, missingErr := NewReconciliationRecoveryCoordinator(nil) + if missingErr == nil { + t.Fatal("缺失补偿扫描器应构造失败") + } + // missingContext 表示调用方未提供生命周期上下文,验证协调器的 fail-closed 行为。 + var missingContext context.Context + // coordinator、err 保存可观测补偿扫描器替身及其构造错误。 + coordinator, err := NewReconciliationRecoveryCoordinator(&reconciliationRecoveryFake{started: make(chan struct{}), stopped: make(chan struct{})}) + if err != nil { + t.Fatalf("构造补偿扫描协调器失败: %v", err) + } + // err 保存缺少启动 Context 时的生命周期错误。 + if err := coordinator.Start(missingContext); err == nil { + t.Fatal("缺失启动 Context 应失败") + } + // err 保存缺少关闭 Context 时的生命周期错误。 + if err := coordinator.Close(missingContext); err == nil { + t.Fatal("缺失关闭 Context 应失败") + } +} diff --git a/internal/application/orders/refresh_job_service.go b/internal/application/orders/refresh_job_service.go new file mode 100644 index 0000000..6dacb4f --- /dev/null +++ b/internal/application/orders/refresh_job_service.go @@ -0,0 +1,230 @@ +package orders + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "strconv" + "strings" + "time" +) + +// RefreshJobOwner 定义创建刷新任务时验证账号归属所需的最小端口。 +type RefreshJobOwner interface { + // OwnsAccount 判断指定账号是否属于当前用户;错误时调用方应拒绝继续创建任务。 + OwnsAccount(context.Context, int64, string) (bool, error) +} + +// RefreshJobIDFactory 生成不携带业务信息的订单刷新任务标识。 +type RefreshJobIDFactory func() string + +// RefreshJobServiceOptions 配置刷新任务创建时使用的标识、令牌、时钟和租约策略。 +type RefreshJobServiceOptions struct { + // LeaseDuration 是新任务抢占后的租约时长,非正值使用运行器默认租约。 + LeaseDuration time.Duration + // Now 返回创建和抢占任务时使用的当前时间。 + Now func() time.Time + // NewJobID 生成新任务标识;nil 时使用随机实现。 + NewJobID RefreshJobIDFactory + // NewToken 生成新 worker 租约令牌;nil 时使用随机实现。 + NewToken func() string +} + +// RefreshJobStartResult 是创建刷新任务并成功启动 worker 后返回的应用结果。 +type RefreshJobStartResult struct { + // Job 是已经持有 running 租约的任务快照。 + Job *RefreshJob + // Token 是本次 worker 使用的租约令牌,仅供应用内部生命周期关联。 + Token string `json:"-"` +} + +// RefreshJobCancelResult 是用户取消刷新任务后的状态结果。 +type RefreshJobCancelResult struct { + // Job 是取消请求完成后的最新任务快照;已取消时状态为 cancelled。 + Job *RefreshJob + // Cancelled 表示本次调用是否原子地将 queued 或 running 任务改为 cancelled。 + Cancelled bool +} + +// RefreshJobService 编排刷新任务的创建、归属校验、租约声明、读取和取消。 +// 业务 worker 的取消与恢复生命周期由 runner 持有,本服务不复制取消表。 +type RefreshJobService struct { + // repository 保存刷新任务的持久化状态和租约。 + repository RefreshJobRepository + // owner 执行账号归属校验,不读取或解密平台凭证。 + owner RefreshJobOwner + // runner 持有 worker 取消表和后台生命周期。 + runner *RefreshJobRunner + // options 保存任务 ID、令牌和租约策略。 + options RefreshJobServiceOptions +} + +// NewRefreshJobService 创建刷新任务应用 facade 并校验必需端口。 +func NewRefreshJobService(repository RefreshJobRepository, owner RefreshJobOwner, runner *RefreshJobRunner, options RefreshJobServiceOptions) (*RefreshJobService, error) { + if repository == nil { + return nil, errors.New("订单刷新任务 facade 仓储端口不能为空") + } + if owner == nil { + return nil, errors.New("订单刷新任务账号归属端口不能为空") + } + if runner == nil { + return nil, errors.New("订单刷新任务运行器不能为空") + } + if options.LeaseDuration <= 0 { + options.LeaseDuration = defaultRefreshJobLease + } + if options.Now == nil { + options.Now = time.Now + } + if options.NewJobID == nil { + options.NewJobID = randomRefreshJobID + } + if options.NewToken == nil { + options.NewToken = randomRefreshJobToken + } + return &RefreshJobService{repository: repository, owner: owner, runner: runner, options: options}, nil +} + +// CreateAndStart 校验账号归属、创建任务、声明租约并启动应用层 worker。 +// requestCtx 仅用于数据库操作;lifecycleCtx 必须来自应用生命周期,不能使用 HTTP 请求 Context。 +func (service *RefreshJobService) CreateAndStart(requestCtx, lifecycleCtx context.Context, userID int64, cookieID, status string) (RefreshJobStartResult, error) { + if service == nil || service.repository == nil || service.owner == nil || service.runner == nil { + return RefreshJobStartResult{}, errors.New("订单刷新任务 facade 未初始化") + } + if requestCtx == nil || lifecycleCtx == nil { + return RefreshJobStartResult{}, errors.New("订单刷新任务 Context 不能为空") + } + if userID <= 0 { + return RefreshJobStartResult{}, ErrForbidden + } + if cookieID != "" { + // owned、ownerErr 保存账号归属校验结果;归属失败时不创建任务,避免泄露账号存在性。 + owned, ownerErr := service.owner.OwnsAccount(requestCtx, userID, cookieID) + if ownerErr != nil { + return RefreshJobStartResult{}, ownerErr + } + if !owned { + return RefreshJobStartResult{}, ErrForbidden + } + } + // job 保存新创建的应用层任务快照;仓储负责将初始状态规范化为 queued。 + job := &RefreshJob{ID: service.options.NewJobID(), UserID: userID, CookieID: cookieID, FilterStatus: status} + if strings.TrimSpace(job.ID) == "" { + return RefreshJobStartResult{}, errors.New("订单刷新任务 ID 生成失败") + } + // token 保存本次 worker 的不透明租约令牌;校验通过后才创建任务,避免生成空令牌的孤儿任务。 + token := service.options.NewToken() + if strings.TrimSpace(token) == "" { + return RefreshJobStartResult{}, errors.New("订单刷新任务租约令牌生成失败") + } + // err 保存任务创建持久化错误。 + if err := service.repository.Create(requestCtx, job); err != nil { + return RefreshJobStartResult{}, err + } + // leaseExpiresAt 保存新 worker 租约截止 Unix 秒。 + leaseExpiresAt := service.options.Now().UTC().Add(service.options.LeaseDuration).Unix() + // claimed、claimErr 保存数据库原子抢占结果及错误。 + claimed, claimErr := service.repository.Claim(requestCtx, job.ID, token, leaseExpiresAt) + if claimErr != nil { + return RefreshJobStartResult{}, claimErr + } + if !claimed { + return RefreshJobStartResult{}, ErrRefreshJobCompletionNotApplied + } + // err 保存 worker 注册到应用生命周期时的错误。 + if err := service.runner.StartJob(lifecycleCtx, job, token); err != nil { + // _, releaseErr 保存 worker 启动失败后的租约收口错误;优先保留启动错误。 + _, releaseErr := service.repository.Complete(requestCtx, job.ID, token, "failed", "{}", err.Error()) + if releaseErr != nil { + return RefreshJobStartResult{}, errors.Join(err, releaseErr) + } + return RefreshJobStartResult{}, err + } + job.Status = "running" + job.WorkerToken = token + job.LeaseExpiresAt = leaseExpiresAt + return RefreshJobStartResult{Job: job, Token: token}, nil +} + +// GetJob 按用户归属读取订单刷新任务,避免 transport 层直接调用任务仓储。 +func (service *RefreshJobService) GetJob(ctx context.Context, userID int64, jobID string) (*RefreshJob, error) { + if service == nil || service.repository == nil { + return nil, errors.New("订单刷新任务 facade 未初始化") + } + if ctx == nil || userID <= 0 || strings.TrimSpace(jobID) == "" { + return nil, ErrRefreshJobNotFound + } + return service.repository.Get(ctx, userID, jobID) +} + +// CancelForUser 按用户归属原子取消任务,并通知 runner 停止仍在内存中的 worker。 +func (service *RefreshJobService) CancelForUser(ctx context.Context, userID int64, jobID string) (RefreshJobCancelResult, error) { + if service == nil || service.repository == nil || service.runner == nil { + return RefreshJobCancelResult{}, errors.New("订单刷新任务 facade 未初始化") + } + if ctx == nil || userID <= 0 || strings.TrimSpace(jobID) == "" { + return RefreshJobCancelResult{}, ErrRefreshJobNotFound + } + // cancelled、cancelErr 保存数据库原子取消结果及错误。 + cancelled, cancelErr := service.repository.Cancel(ctx, userID, jobID) + if cancelErr != nil { + return RefreshJobCancelResult{}, cancelErr + } + if cancelled { + service.runner.CancelJob(jobID) + return RefreshJobCancelResult{Job: &RefreshJob{ID: jobID, UserID: userID, Status: "cancelled"}, Cancelled: true}, nil + } + // job、getErr 保存取消未生效时的最新任务状态及查询错误。 + job, getErr := service.repository.Get(ctx, userID, jobID) + if getErr != nil { + return RefreshJobCancelResult{}, getErr + } + return RefreshJobCancelResult{Job: job}, nil +} + +// StartRecovery 启动订单刷新任务恢复扫描,并由 runner 管理其停止与等待。 +func (service *RefreshJobService) StartRecovery(ctx context.Context) error { + if service == nil || service.runner == nil { + return errors.New("订单刷新任务 facade 未初始化") + } + return service.runner.StartRecovery(ctx) +} + +// Close 停止恢复扫描和全部订单刷新 worker,并等待其退出。 +func (service *RefreshJobService) Close(ctx context.Context) error { + if service == nil || service.runner == nil { + return nil + } + return service.runner.Close(ctx) +} + +// Wait 等待应用层拥有的恢复扫描和刷新 worker 全部退出。 +func (service *RefreshJobService) Wait() { + if service == nil || service.runner == nil { + return + } + service.runner.Wait() +} + +// OwnsAccount 让 RefreshService 复用其已有刷新仓储的非敏感归属查询能力。 +func (service *RefreshService) OwnsAccount(ctx context.Context, userID int64, cookieID string) (bool, error) { + if service == nil || service.repository == nil { + return false, errors.New("订单刷新服务未初始化") + } + if ctx == nil || userID <= 0 || strings.TrimSpace(cookieID) == "" { + return false, nil + } + return service.repository.ExistsOwned(ctx, userID, cookieID) +} + +// randomRefreshJobID 生成任务 ID;随机源失败时使用高精度时间戳保证进程内唯一性。 +func randomRefreshJobID() string { + // buffer 保存任务 ID 的随机二进制部分,不包含用户或账号信息。 + buffer := make([]byte, 16) + // _, err 保存系统随机源读取结果。 + if _, err := rand.Read(buffer); err == nil { + return "order-refresh-" + hex.EncodeToString(buffer) + } + return "order-refresh-" + strconv.FormatInt(time.Now().UTC().UnixNano(), 36) +} diff --git a/internal/application/orders/refresh_job_service_test.go b/internal/application/orders/refresh_job_service_test.go new file mode 100644 index 0000000..c9c69be --- /dev/null +++ b/internal/application/orders/refresh_job_service_test.go @@ -0,0 +1,134 @@ +package orders + +import ( + "context" + "errors" + "testing" + "time" +) + +// refreshJobOwnerTestDouble 是刷新任务 facade 使用的最小账号归属测试端口。 +type refreshJobOwnerTestDouble struct { + // owned 控制账号归属查询结果。 + owned bool + // err 控制账号归属查询错误。 + err error + // calls 保存归属查询调用次数。 + calls int +} + +// OwnsAccount 返回预置的账号归属结果。 +func (owner *refreshJobOwnerTestDouble) OwnsAccount(context.Context, int64, string) (bool, error) { + owner.calls++ + return owner.owned, owner.err +} + +// TestRefreshJobServiceCreateAndStart 验证 facade 会先校验账号、创建任务、声明租约再启动 worker。 +func TestRefreshJobServiceCreateAndStart(t *testing.T) { + // repository 记录 facade 的创建、抢占和 worker 终态写入。 + repository := completeAppliedRepository() + // owner 返回账号属于当前用户,允许继续创建任务。 + owner := &refreshJobOwnerTestDouble{owned: true} + // refresher 返回立即完成的结果,便于 Close 确定收口。 + refresher := &refreshRunnerTestRefresher{result: RefreshResult{Message: "完成"}} + // runner、err 保存 facade 依赖的 worker 运行器。 + runner, err := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{}) + if err != nil { + t.Fatalf("构造运行器: %v", err) + } + // fixedNow 是租约计算使用的固定时间。 + fixedNow := time.Date(2026, 8, 17, 12, 0, 0, 0, time.UTC) + // service、constructErr 保存 facade 及其构造错误。 + service, constructErr := NewRefreshJobService(repository, owner, runner, RefreshJobServiceOptions{ + LeaseDuration: time.Minute, + Now: func() time.Time { return fixedNow }, + NewJobID: func() string { return "job-created" }, + NewToken: func() string { return "token-created" }, + }) + if constructErr != nil { + t.Fatalf("构造 facade: %v", constructErr) + } + // result、startErr 保存创建任务并启动 worker 的结果。 + result, startErr := service.CreateAndStart(context.Background(), context.Background(), 7, "cookie-1", "pending_ship") + if startErr != nil { + t.Fatalf("创建并启动任务: %v", startErr) + } + if owner.calls != 1 || result.Job == nil || result.Job.ID != "job-created" || result.Job.Status != "running" || result.Token != "token-created" { + t.Fatalf("创建结果不正确: owner=%d result=%+v", owner.calls, result) + } + repository.mu.Lock() + // createdJobs 保存 facade 交给仓储的初始任务。 + createdJobs := append([]RefreshJob(nil), repository.createdJobs...) + // claimCalls 保存 facade 声明 worker 租约的参数。 + claimCalls := append([]refreshRunnerClaimCall(nil), repository.claimCalls...) + repository.mu.Unlock() + if len(createdJobs) != 1 || createdJobs[0].UserID != 7 || len(claimCalls) != 1 || claimCalls[0].leaseExpiresAt != fixedNow.Add(time.Minute).Unix() { + t.Fatalf("创建或抢占参数不正确: jobs=%v claims=%v", createdJobs, claimCalls) + } + // closeCtx 限制测试等待异步 worker 收口的时间。 + closeCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // closeErr 保存运行器关闭错误。 + if closeErr := runner.Close(closeCtx); closeErr != nil { + t.Fatalf("关闭运行器: %v", closeErr) + } +} + +// TestRefreshJobServiceCreateRejectsUnownedAccount 验证账号不属于用户时不会创建或抢占任务。 +func TestRefreshJobServiceCreateRejectsUnownedAccount(t *testing.T) { + // repository 记录不应发生的创建和抢占调用。 + repository := completeAppliedRepository() + // owner 返回账号不属于当前用户。 + owner := &refreshJobOwnerTestDouble{} + // runner、err 保存最小运行器。 + runner, err := NewRefreshJobRunner(repository, &refreshRunnerTestRefresher{}, RefreshJobRunnerOptions{}) + if err != nil { + t.Fatalf("构造运行器: %v", err) + } + // service、constructErr 保存 facade 构造结果。 + service, constructErr := NewRefreshJobService(repository, owner, runner, RefreshJobServiceOptions{NewJobID: func() string { return "unused" }, NewToken: func() string { return "unused" }}) + if constructErr != nil { + t.Fatalf("构造 facade: %v", constructErr) + } + // _, err 保存归属失败返回的创建结果和应用错误。 + _, err = service.CreateAndStart(context.Background(), context.Background(), 7, "cookie-1", "") + if !errors.Is(err, ErrForbidden) { + t.Fatalf("无权账号未被拒绝") + } + if len(repository.createdJobs) != 0 || len(repository.claimCalls) != 0 { + t.Fatalf("无权账号不应创建或抢占任务") + } +} + +// TestRefreshJobServiceGetAndCancel 验证查询和取消都通过用户归属仓储端口完成。 +func TestRefreshJobServiceGetAndCancel(t *testing.T) { + // repository 预置用户任务,供 facade 查询和取消。 + repository := completeAppliedRepository() + repository.getJob = &RefreshJob{ID: "job-existing", UserID: 7, Status: "succeeded"} + // runner、err 保存取消通知所需的运行器。 + runner, err := NewRefreshJobRunner(repository, &refreshRunnerTestRefresher{}, RefreshJobRunnerOptions{}) + if err != nil { + t.Fatalf("构造运行器: %v", err) + } + // service、constructErr 保存 facade 构造结果。 + service, constructErr := NewRefreshJobService(repository, &refreshJobOwnerTestDouble{owned: true}, runner, RefreshJobServiceOptions{}) + if constructErr != nil { + t.Fatalf("构造 facade: %v", constructErr) + } + // job、getErr 保存 facade 查询结果。 + job, getErr := service.GetJob(context.Background(), 7, "job-existing") + if getErr != nil || job == nil || job.Status != "succeeded" { + t.Fatalf("查询任务不正确: job=%+v err=%v", job, getErr) + } + // result、cancelErr 保存取消未生效时的当前状态。 + result, cancelErr := service.CancelForUser(context.Background(), 7, "job-existing") + if cancelErr != nil || result.Cancelled || result.Job == nil || result.Job.Status != "succeeded" { + t.Fatalf("结束任务不应被取消: result=%+v err=%v", result, cancelErr) + } + repository.cancelResult = true + // cancelled、cancelErr 保存原子取消成功结果。 + cancelled, cancelErr := service.CancelForUser(context.Background(), 7, "job-existing") + if cancelErr != nil || !cancelled.Cancelled || cancelled.Job == nil || cancelled.Job.Status != "cancelled" { + t.Fatalf("取消结果不正确: result=%+v err=%v", cancelled, cancelErr) + } +} diff --git a/internal/application/orders/refresh_runner.go b/internal/application/orders/refresh_runner.go new file mode 100644 index 0000000..73990a8 --- /dev/null +++ b/internal/application/orders/refresh_runner.go @@ -0,0 +1,566 @@ +package orders + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + "sync" + "time" +) + +const ( + // defaultRefreshJobTimeout 限制单个订单刷新 worker 的最长运行时间。 + defaultRefreshJobTimeout = 30 * time.Minute + // defaultRefreshJobLease 为运行中的订单刷新任务提供可恢复租约。 + defaultRefreshJobLease = defaultRefreshJobTimeout + time.Minute + // defaultRefreshRecoveryInterval 控制恢复扫描器的默认轮询周期。 + defaultRefreshRecoveryInterval = time.Minute + // defaultRefreshRecoveryBatchSize 限制每次恢复扫描接管的任务数量。 + defaultRefreshRecoveryBatchSize = 20 +) + +var ( + // ErrRefreshJobRunnerStopped 表示运行器已经进入关闭状态,不能再接收新任务。 + ErrRefreshJobRunnerStopped = errors.New("订单刷新任务运行器已停止") + // ErrRefreshJobRunnerInvalidJob 表示调用方没有提供可执行的任务或租约令牌。 + ErrRefreshJobRunnerInvalidJob = errors.New("订单刷新任务或租约令牌无效") + // ErrRefreshJobCompletionNotApplied 表示终态写入没有命中当前 worker 的租约。 + ErrRefreshJobCompletionNotApplied = errors.New("订单刷新任务终态未写入") +) + +// RefreshJobRefresher 定义运行器执行一次订单刷新所需的最小业务端口。 +type RefreshJobRefresher interface { + // Refresh 按任务所属用户、账号和状态筛选条件执行订单刷新。 + Refresh(context.Context, int64, string, string) (RefreshResult, error) +} + +// RefreshJobResult 是订单刷新任务持久化和跨应用边界传递的稳定结果模型。 +// 字段标签固定为既有任务存储契约的 snake_case 形状,不依赖 HTTP 包或 Server DTO。 +type RefreshJobResult struct { + // PartialFailure 表示本次批量刷新是否有部分账号或订单失败。 + PartialFailure bool `json:"partial_failure"` + // Message 是面向管理界面的刷新结果说明。 + Message string `json:"message"` + // Summary 保存本次刷新各阶段的数量统计。 + Summary RefreshJobSummary `json:"summary"` + // Results 保存按账号或订单拆分的稳定结果行。 + Results []RefreshJobResultItem `json:"results"` +} + +// RefreshJobSummary 是订单刷新任务结果中的统计摘要。 +type RefreshJobSummary struct { + // Discovered 是从平台发现并导入的新订单数量。 + Discovered int `json:"discovered"` + // ListUpdated 是订单列表阶段发生字段变化的数量。 + ListUpdated int `json:"list_updated"` + // SoftDeleted 是平台已不存在而被本地标记删除的数量。 + SoftDeleted int `json:"soft_deleted"` + // DetailTotal 是进入详情补全阶段的订单数量。 + DetailTotal int `json:"detail_total"` + // Total 是本次详情补全处理的订单总数量。 + Total int `json:"total"` + // Updated 是详情补全后状态或字段发生变化的数量。 + Updated int `json:"updated"` + // NoChange 是详情补全后没有变化的数量。 + NoChange int `json:"no_change"` + // Failed 是刷新过程中失败的数量。 + Failed int `json:"failed"` +} + +// RefreshJobResultItem 是订单刷新任务结果中的单条兼容结果行。 +type RefreshJobResultItem struct { + // Success 表示当前账号或订单阶段是否完成。 + Success bool `json:"success"` + // CookieID 是当前结果关联的账号标识。 + CookieID string `json:"cookie_id,omitempty"` + // Discovered 是当前账号发现的新订单数量;非账号结果保持为空。 + Discovered *int `json:"discovered,omitempty"` + // Updated 是当前账号订单列表更新数量;非账号结果保持为空。 + Updated *int `json:"updated,omitempty"` + // SoftDeleted 表示当前账号是否标记了失效订单;非账号结果保持为空。 + SoftDeleted *bool `json:"soft_deleted,omitempty"` + // OrderID 是单订单刷新结果关联的平台订单标识。 + OrderID string `json:"order_id,omitempty"` + // Stage 是当前结果所处的 discover、detail 或 persist_cookie 阶段。 + Stage string `json:"stage,omitempty"` + // Message 是面向客户端的结果说明。 + Message string `json:"message,omitempty"` + // Error 是当前结果的兼容错误文本。 + Error string `json:"error,omitempty"` + // OldStatus 是详情刷新前的订单状态。 + OldStatus string `json:"old_status,omitempty"` + // NewStatus 是详情刷新后的订单状态。 + NewStatus string `json:"new_status,omitempty"` +} + +// NewRefreshJobResult 将订单刷新应用结果转换为稳定的任务持久化模型。 +func NewRefreshJobResult(result RefreshResult) RefreshJobResult { + // items 保存转换后的结果行;即使没有结果也使用非 nil 空切片维持 [] 契约。 + items := make([]RefreshJobResultItem, 0, len(result.Results)) + // item 表示当前待转换的应用层刷新结果行。 + for _, item := range result.Results { + // converted 保存当前结果行的基础字段。 + converted := RefreshJobResultItem{ + Success: item.Success, CookieID: item.CookieID, OrderID: item.OrderID, + Stage: item.Stage, Message: item.Message, Error: item.Error, + OldStatus: item.OldStatus, NewStatus: item.NewStatus, + } + if item.CookieID != "" { + // discovered 保存账号发现阶段的数量,即使值为零也必须显式持久化。 + discovered := item.Discovered + // updated 保存账号订单列表阶段的变化数量,即使值为零也必须显式持久化。 + updated := item.Updated + converted.Discovered, converted.Updated = &discovered, &updated + if item.Success { + // softDeleted 保存成功账号刷新是否标记了远端缺失订单。 + softDeleted := item.SoftDeleted != 0 + converted.SoftDeleted = &softDeleted + } + } + items = append(items, converted) + } + return RefreshJobResult{ + PartialFailure: result.PartialFailure, + Message: result.Message, + Summary: RefreshJobSummary{ + Discovered: result.Summary.Discovered, ListUpdated: result.Summary.ListUpdated, + SoftDeleted: result.Summary.SoftDeleted, DetailTotal: result.Summary.DetailTotal, + Total: result.Summary.Total, Updated: result.Summary.Updated, + NoChange: result.Summary.NoChange, Failed: result.Summary.Failed, + }, + Results: items, + } +} + +// RefreshJobResultMarshaler 将应用层结果模型编码为任务仓储保存的 JSON。 +type RefreshJobResultMarshaler func(RefreshJobResult) ([]byte, error) + +// RefreshJobRunnerOptions 配置 worker 超时、租约、恢复扫描和可测试时间源。 +type RefreshJobRunnerOptions struct { + // JobTimeout 是单个刷新 worker 的超时时长,非正值使用默认值。 + JobTimeout time.Duration + // LeaseDuration 是 worker 抢占任务后写入的租约时长,非正值使用默认值。 + LeaseDuration time.Duration + // RecoveryInterval 是恢复扫描器两次扫描之间的等待时长,非正值使用默认值。 + RecoveryInterval time.Duration + // RecoveryBatchSize 是每轮恢复扫描最多接管的任务数,非正值使用默认值。 + RecoveryBatchSize int + // Now 返回当前时间,用于恢复截止时间和租约计算。 + Now func() time.Time + // NewToken 生成不携带用户信息的 worker 租约令牌。 + NewToken func() string + // MarshalResult 编码带 snake_case 标签的应用结果;nil 时使用标准 JSON 编码器。 + MarshalResult RefreshJobResultMarshaler + // OnWorkerError 接收异步 worker 的业务或终态错误;nil 时错误不向外部传播。 + OnWorkerError func(string, error) + // OnRecoveryError 接收恢复扫描的数据库错误;nil 时错误只结束本轮扫描。 + OnRecoveryError func(error) +} + +// refreshJobWorker 保存单个订单刷新 worker 的租约和取消控制。 +type refreshJobWorker struct { + // token 是当前 worker 持有的数据库租约令牌。 + token string + // cancel 取消当前 worker 的超时 Context。 + cancel context.CancelFunc +} + +// RefreshJobRunner 拥有订单刷新 worker、恢复扫描器和关闭等待生命周期。 +// mu 保护 workers、active、done、stopped 与 recoveryCancel;锁内只执行内存状态变更和取消,不调用仓储或平台 I/O。 +type RefreshJobRunner struct { + // repository 保存订单刷新任务状态、租约和终态。 + repository RefreshJobRepository + // refresher 执行实际订单刷新业务。 + refresher RefreshJobRefresher + // options 保存运行器生命周期和时间策略。 + options RefreshJobRunnerOptions + // mu 保护 worker 表和生命周期计数,避免 Stop 与异步 worker 竞争。 + mu sync.Mutex + // workers 保存按任务 ID 索引的可取消 worker;指针身份用于区分相同令牌的重复启动。 + workers map[string]*refreshJobWorker + // active 是正在运行的 worker 与恢复扫描 goroutine 数量。 + active int + // done 在 active 归零时关闭;下一轮有任务时重新创建。 + done chan struct{} + // recoveryCancel 取消当前恢复扫描循环;同时只能存在一个恢复扫描循环。 + recoveryCancel context.CancelFunc + // stopped 表示运行器不再接受新 worker 或恢复扫描。 + stopped bool +} + +// NewRefreshJobRunner 创建订单刷新任务运行器并校验必需端口。 +func NewRefreshJobRunner(repository RefreshJobRepository, refresher RefreshJobRefresher, options RefreshJobRunnerOptions) (*RefreshJobRunner, error) { + if repository == nil { + return nil, errors.New("订单刷新任务仓储端口不能为空") + } + if refresher == nil { + return nil, errors.New("订单刷新业务端口不能为空") + } + if options.JobTimeout <= 0 { + options.JobTimeout = defaultRefreshJobTimeout + } + if options.LeaseDuration <= 0 { + options.LeaseDuration = defaultRefreshJobLease + } + if options.RecoveryInterval <= 0 { + options.RecoveryInterval = defaultRefreshRecoveryInterval + } + if options.RecoveryBatchSize <= 0 { + options.RecoveryBatchSize = defaultRefreshRecoveryBatchSize + } + if options.Now == nil { + options.Now = time.Now + } + if options.NewToken == nil { + options.NewToken = randomRefreshJobToken + } + if options.MarshalResult == nil { + options.MarshalResult = func(result RefreshJobResult) ([]byte, error) { + return json.Marshal(result) + } + } + return &RefreshJobRunner{repository: repository, refresher: refresher, options: options, workers: make(map[string]*refreshJobWorker), done: closedRefreshJobSignal()}, nil +} + +// StartJob 启动一个已经由调用方声明租约的订单刷新任务。 +// parent 是应用生命周期 Context;调用方不能传入 HTTP 请求 Context,以免请求结束误取消后台任务。 +func (runner *RefreshJobRunner) StartJob(parent context.Context, job *RefreshJob, token string) error { + if runner == nil || runner.repository == nil || runner.refresher == nil { + return errors.New("订单刷新任务运行器未初始化") + } + if parent == nil { + return errors.New("订单刷新任务生命周期 Context 不能为空") + } + if job == nil || strings.TrimSpace(job.ID) == "" || strings.TrimSpace(token) == "" { + return ErrRefreshJobRunnerInvalidJob + } + // jobCtx、cancel 限制后台刷新最长执行时间,并继承应用生命周期取消信号。 + jobCtx, cancel := context.WithTimeout(parent, runner.options.JobTimeout) + runner.mu.Lock() + if runner.stopped { + runner.mu.Unlock() + cancel() + return ErrRefreshJobRunnerStopped + } + // previous 保存同一任务旧 worker 的取消控制;旧 worker 必须停止以避免并发写入终态。 + previous := runner.workers[job.ID] + if previous != nil && previous.cancel != nil { + previous.cancel() + } + // worker 保存新登记的任务控制句柄;指针身份避免旧 worker 退出时误删新 worker。 + worker := &refreshJobWorker{token: token, cancel: cancel} + runner.workers[job.ID] = worker + runner.beginActiveLocked() + runner.mu.Unlock() + go runner.runWorker(jobCtx, cancel, job, token, worker) + return nil +} + +// CancelJob 取消指定任务当前登记的 worker,不改变数据库中的任务终态。 +func (runner *RefreshJobRunner) CancelJob(jobID string) bool { + if runner == nil || strings.TrimSpace(jobID) == "" { + return false + } + runner.mu.Lock() + // worker 保存当前任务的内存取消控制句柄。 + worker, ok := runner.workers[jobID] + runner.mu.Unlock() + if !ok || worker == nil || worker.cancel == nil { + return false + } + worker.cancel() + return true +} + +// RunJob 同步执行一次订单刷新 worker,供恢复、集成测试和生命周期封装复用。 +func (runner *RefreshJobRunner) RunJob(ctx context.Context, job *RefreshJob, token string) error { + if runner == nil || runner.repository == nil || runner.refresher == nil { + return errors.New("订单刷新任务运行器未初始化") + } + if ctx == nil { + return errors.New("订单刷新任务 Context 不能为空") + } + if job == nil || strings.TrimSpace(job.ID) == "" || strings.TrimSpace(token) == "" { + return ErrRefreshJobRunnerInvalidJob + } + // result、err 保存刷新业务结果及错误。 + result, err := runner.refresher.Refresh(ctx, job.UserID, job.CookieID, job.FilterStatus) + if err != nil { + // completionErr 保存失败终态写入错误;业务根因始终保留在返回值中。 + completionErr := runner.complete(ctx, job.ID, token, "failed", "{}", err.Error()) + if completionErr != nil { + return errors.Join(err, completionErr) + } + return err + } + // resultJSON、marshalErr 保存成功结果的 snake_case JSON 及序列化错误。 + resultJSON, marshalErr := runner.options.MarshalResult(NewRefreshJobResult(result)) + if marshalErr != nil { + // completionErr 保存序列化失败后的失败终态写入错误。 + completionErr := runner.complete(ctx, job.ID, token, "failed", "{}", marshalErr.Error()) + if completionErr != nil { + return errors.Join(marshalErr, completionErr) + } + return marshalErr + } + return runner.complete(ctx, job.ID, token, "succeeded", string(resultJSON), "") +} + +// RunRecovery 扫描一次租约过期的订单刷新任务并启动可恢复 worker。 +func (runner *RefreshJobRunner) RunRecovery(ctx context.Context) error { + if runner == nil || runner.repository == nil || runner.refresher == nil { + return errors.New("订单刷新任务运行器未初始化") + } + if ctx == nil { + return errors.New("订单刷新恢复 Context 不能为空") + } + // now 保存本轮扫描统一使用的当前时间,保证截止时间和新租约计算一致。 + now := runner.options.Now().UTC() + // jobs、err 保存仓储返回的可恢复任务及扫描错误。 + jobs, err := runner.repository.Recoverable(ctx, now.Unix(), runner.options.RecoveryBatchSize) + if err != nil { + return err + } + // job 表示当前待重新入队并接管的任务快照。 + for _, job := range jobs { + // err 表示恢复扫描上下文是否已被取消。 + if err := ctx.Err(); err != nil { + return err + } + // requeued、requeueErr 保存过期任务重新入队的结果及错误。 + requeued, requeueErr := runner.repository.RequeueExpired(ctx, job.ID, now.Unix()) + if requeueErr != nil || !requeued { + continue + } + // token 保存本轮恢复 worker 的新租约令牌。 + token := runner.options.NewToken() + if strings.TrimSpace(token) == "" { + continue + } + // leaseExpiresAt 保存本轮恢复 worker 的租约截止 Unix 秒。 + leaseExpiresAt := now.Add(runner.options.LeaseDuration).Unix() + // claimed、claimErr 保存恢复 worker 的原子抢占结果及错误。 + claimed, claimErr := runner.repository.Claim(ctx, job.ID, token, leaseExpiresAt) + if claimErr != nil || !claimed { + continue + } + // jobCopy 保存当前恢复任务的独立副本,避免异步 worker 捕获 range 变量。 + jobCopy := job + // startErr 保存恢复任务加入应用生命周期 worker 表的错误。 + if startErr := runner.StartJob(ctx, &jobCopy, token); startErr != nil { + // _, releaseErr 保存恢复 worker 启动失败后的租约终态收口错误。 + _, releaseErr := runner.repository.Complete(ctx, job.ID, token, "failed", "{}", startErr.Error()) + if releaseErr != nil { + startErr = errors.Join(startErr, releaseErr) + } + if runner.options.OnRecoveryError != nil { + runner.options.OnRecoveryError(fmt.Errorf("启动订单刷新恢复任务 %s: %w", job.ID, startErr)) + } + } + } + return nil +} + +// StartRecovery 启动单一恢复扫描循环,并将其纳入运行器 Stop/Wait 生命周期。 +func (runner *RefreshJobRunner) StartRecovery(parent context.Context) error { + if runner == nil { + return errors.New("订单刷新任务运行器未初始化") + } + if parent == nil { + return errors.New("订单刷新恢复生命周期 Context 不能为空") + } + runner.mu.Lock() + if runner.stopped { + runner.mu.Unlock() + return ErrRefreshJobRunnerStopped + } + if runner.recoveryCancel != nil { + runner.mu.Unlock() + return nil + } + // recoveryCtx、cancel 只负责恢复循环本身;Close 时由运行器统一触发取消。 + recoveryCtx, cancel := context.WithCancel(parent) + runner.recoveryCancel = cancel + runner.beginActiveLocked() + runner.mu.Unlock() + go runner.runRecoveryLoop(recoveryCtx, cancel) + return nil +} + +// Stop 取消所有已登记 worker 和恢复循环;方法可安全重复调用。 +func (runner *RefreshJobRunner) Stop() { + if runner == nil { + return + } + runner.mu.Lock() + if runner.stopped { + runner.mu.Unlock() + return + } + runner.stopped = true + // cancels 保存锁内快照,解锁后再调用取消函数,避免回调重入生命周期锁。 + cancels := make([]context.CancelFunc, 0, len(runner.workers)+1) + // worker 表示当前仍登记在内存取消表中的任务控制句柄。 + for _, worker := range runner.workers { + if worker != nil && worker.cancel != nil { + cancels = append(cancels, worker.cancel) + } + } + if runner.recoveryCancel != nil { + cancels = append(cancels, runner.recoveryCancel) + } + // runner.workers 立即清空,保证 Stop 返回后新的取消请求不会继续引用已停止任务。 + runner.workers = make(map[string]*refreshJobWorker) + runner.mu.Unlock() + // cancel 保存当前待触发的取消函数;取消本身不执行网络、数据库或浏览器 I/O。 + for _, cancel := range cancels { + cancel() + } +} + +// Wait 等待运行器当前已登记的 worker 和恢复循环全部退出。 +func (runner *RefreshJobRunner) Wait() { + if runner == nil { + return + } + runner.mu.Lock() + // done 保存当前 active 计数归零信号;读取后立即解锁避免阻塞生命周期变更。 + done := runner.done + runner.mu.Unlock() + <-done +} + +// Close 停止运行器并在给定 Context 内等待所有异步任务退出。 +func (runner *RefreshJobRunner) Close(ctx context.Context) error { + if runner == nil { + return nil + } + if ctx == nil { + return errors.New("关闭订单刷新任务运行器的 Context 不能为空") + } + runner.Stop() + runner.mu.Lock() + // done 保存 Stop 后仍在退出的 worker 和恢复循环完成信号。 + done := runner.done + runner.mu.Unlock() + select { + case <-done: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// runWorker 执行异步 worker,并负责清除租约对应的取消句柄和 active 计数。 +func (runner *RefreshJobRunner) runWorker(ctx context.Context, cancel context.CancelFunc, job *RefreshJob, token string, worker *refreshJobWorker) { + defer cancel() + defer runner.finishWorker(job.ID, token, worker) + // err 保存业务刷新或终态写入错误;异步错误通过可选回调交给装配层观测。 + err := runner.RunJob(ctx, job, token) + if err != nil && runner.options.OnWorkerError != nil { + runner.options.OnWorkerError(job.ID, err) + } +} + +// runRecoveryLoop 按固定间隔执行恢复扫描,直到 Context 取消。 +func (runner *RefreshJobRunner) runRecoveryLoop(ctx context.Context, cancel context.CancelFunc) { + defer cancel() + defer runner.finishRecovery() + // err 保存首次恢复扫描的错误;错误通过可选回调报告后继续下一轮。 + if err := runner.RunRecovery(ctx); err != nil && runner.options.OnRecoveryError != nil && !errors.Is(err, context.Canceled) { + runner.options.OnRecoveryError(err) + } + // ticker 保存恢复扫描间隔计时器,由本 goroutine 独占并负责停止。 + ticker := time.NewTicker(runner.options.RecoveryInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + // err 保存本轮恢复扫描错误;单轮失败不阻塞后续轮次。 + if err := runner.RunRecovery(ctx); err != nil && runner.options.OnRecoveryError != nil && !errors.Is(err, context.Canceled) { + runner.options.OnRecoveryError(err) + } + } + } +} + +// complete 将当前 worker 的结果以租约令牌写入任务终态,并拒绝租约失配。 +func (runner *RefreshJobRunner) complete(ctx context.Context, jobID, token, status, resultJSON, errorMessage string) error { + if ctx == nil { + return errors.New("订单刷新任务终态写入 Context 不能为空") + } + // applied、err 保存终态写入是否命中当前租约及仓储错误。 + applied, err := runner.repository.Complete(ctx, jobID, token, status, resultJSON, errorMessage) + if err != nil { + return fmt.Errorf("订单刷新任务终态写入失败: %w", err) + } + if !applied { + return fmt.Errorf("%w: job_id=%s", ErrRefreshJobCompletionNotApplied, jobID) + } + return nil +} + +// beginActiveLocked 登记一个 worker 或恢复循环;调用方必须持有 runner.mu。 +func (runner *RefreshJobRunner) beginActiveLocked() { + if runner.active == 0 { + runner.done = make(chan struct{}) + } + runner.active++ +} + +// finishWorker 清除仍匹配当前租约的 worker 控制句柄并减少生命周期计数。 +func (runner *RefreshJobRunner) finishWorker(jobID, token string, worker *refreshJobWorker) { + runner.mu.Lock() + // current 保存任务当前登记的控制句柄,用于防止旧 worker 删除新租约。 + current := runner.workers[jobID] + if current == worker && current.token == token { + delete(runner.workers, jobID) + } + runner.finishActiveLocked() + runner.mu.Unlock() +} + +// finishRecovery 清除恢复循环句柄并减少生命周期计数。 +func (runner *RefreshJobRunner) finishRecovery() { + runner.mu.Lock() + runner.recoveryCancel = nil + runner.finishActiveLocked() + runner.mu.Unlock() +} + +// finishActiveLocked 减少活动任务计数并在归零时关闭 done;调用方必须持有 runner.mu。 +func (runner *RefreshJobRunner) finishActiveLocked() { + if runner.active <= 0 { + return + } + runner.active-- + if runner.active == 0 { + close(runner.done) + } +} + +// closedRefreshJobSignal 创建已经关闭的生命周期信号,供没有后台任务的 Wait 立即返回。 +func closedRefreshJobSignal() chan struct{} { + // done 保存初始无活动任务状态的关闭信号。 + done := make(chan struct{}) + close(done) + return done +} + +// randomRefreshJobToken 生成不携带用户信息的订单刷新 worker 租约令牌。 +func randomRefreshJobToken() string { + // buffer 保存系统随机源生成的租约令牌二进制内容。 + buffer := make([]byte, 16) + // _, err 保存系统随机源读取结果;异常时回退到不可预测的时间戳文本。 + if _, err := rand.Read(buffer); err == nil { + return hex.EncodeToString(buffer) + } + return "refresh-" + strconv.FormatInt(time.Now().UTC().UnixNano(), 36) +} diff --git a/internal/application/orders/refresh_runner_test.go b/internal/application/orders/refresh_runner_test.go new file mode 100644 index 0000000..b993d10 --- /dev/null +++ b/internal/application/orders/refresh_runner_test.go @@ -0,0 +1,386 @@ +package orders + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync" + "testing" + "time" +) + +// refreshRunnerTestRefresher 是测试用的订单刷新业务端口,可固定返回结果或等待取消。 +type refreshRunnerTestRefresher struct { + // result 保存测试刷新成功时返回的应用结果。 + result RefreshResult + // err 保存测试刷新失败时返回的业务错误。 + err error + // waitForCancel 表示是否等待调用方取消 Context 后再返回。 + waitForCancel bool + // called 保存刷新调用次数,供生命周期断言使用。 + called int + // mu 保护 called,允许 worker 测试与主 goroutine 并发读取。 + mu sync.Mutex +} + +// Refresh 返回固定结果,或在 Context 取消后返回取消错误。 +func (refresher *refreshRunnerTestRefresher) Refresh(ctx context.Context, _ int64, _, _ string) (RefreshResult, error) { + refresher.mu.Lock() + refresher.called++ + refresher.mu.Unlock() + if refresher.waitForCancel { + <-ctx.Done() + return RefreshResult{}, ctx.Err() + } + return refresher.result, refresher.err +} + +// refreshRunnerTestRepository 是测试用任务仓储,记录租约操作和终态写入参数。 +type refreshRunnerTestRepository struct { + // jobs 保存恢复扫描需要返回的任务快照。 + jobs []RefreshJob + // createdJobs 保存 facade 创建的任务快照。 + createdJobs []RefreshJob + // createErr 控制 facade 创建任务时返回的持久化错误。 + createErr error + // getJob 保存 facade 查询任务时返回的快照。 + getJob *RefreshJob + // getErr 控制 facade 查询任务时返回的错误。 + getErr error + // cancelResult 控制 facade 取消任务是否原子生效。 + cancelResult bool + // cancelErr 控制 facade 取消任务时返回的错误。 + cancelErr error + // completeCalls 保存终态写入调用,顺序与 worker 完成顺序一致。 + completeCalls []refreshRunnerCompleteCall + // recoverCalls 保存恢复扫描收到的截止时间和数量限制。 + recoverCalls []refreshRunnerRecoverCall + // requeueCalls 保存重新入队的任务标识和扫描时间。 + requeueCalls []string + // claimCalls 保存恢复抢占的任务标识、令牌和租约截止时间。 + claimCalls []refreshRunnerClaimCall + // completeApplied 控制 Complete 是否命中当前 worker 租约。 + completeApplied bool + // completeErr 控制 Complete 返回的持久化错误。 + completeErr error + // recoverErr 控制 Recoverable 返回的扫描错误。 + recoverErr error + // mu 保护测试仓储的可变记录,避免异步 worker 与断言竞争。 + mu sync.Mutex +} + +// refreshRunnerCompleteCall 保存一次订单刷新任务终态写入的完整参数。 +type refreshRunnerCompleteCall struct { + // jobID 是终态任务标识。 + jobID string + // token 是终态写入使用的 worker 租约令牌。 + token string + // status 是 succeeded 或 failed 终态。 + status string + // resultJSON 是成功结果或失败时的空对象 JSON。 + resultJSON string + // errorMessage 是失败终态的错误文本。 + errorMessage string +} + +// refreshRunnerRecoverCall 保存一次恢复扫描的查询参数。 +type refreshRunnerRecoverCall struct { + // now 是恢复查询使用的 Unix 秒截止时间。 + now int64 + // limit 是恢复查询的批量上限。 + limit int +} + +// refreshRunnerClaimCall 保存一次恢复任务租约抢占参数。 +type refreshRunnerClaimCall struct { + // jobID 是待抢占任务标识。 + jobID string + // token 是新 worker 租约令牌。 + token string + // leaseExpiresAt 是新租约截止 Unix 秒。 + leaseExpiresAt int64 +} + +// Create 满足刷新任务仓储接口;运行器测试不会创建任务。 +func (repository *refreshRunnerTestRepository) Create(_ context.Context, job *RefreshJob) error { + if repository.createErr != nil { + return repository.createErr + } + repository.mu.Lock() + defer repository.mu.Unlock() + if job != nil { + repository.createdJobs = append(repository.createdJobs, *job) + } + return nil +} + +// Get 满足刷新任务仓储接口;运行器测试不会读取用户任务。 +func (repository *refreshRunnerTestRepository) Get(context.Context, int64, string) (*RefreshJob, error) { + if repository.getErr != nil { + return nil, repository.getErr + } + if repository.getJob == nil { + return nil, ErrRefreshJobNotFound + } + // job 是返回给 facade 的任务快照副本,避免测试调用方改写仓储原值。 + job := *repository.getJob + return &job, nil +} + +// Claim 记录租约抢占并返回成功。 +func (repository *refreshRunnerTestRepository) Claim(_ context.Context, jobID, token string, leaseExpiresAt int64) (bool, error) { + repository.mu.Lock() + defer repository.mu.Unlock() + repository.claimCalls = append(repository.claimCalls, refreshRunnerClaimCall{jobID: jobID, token: token, leaseExpiresAt: leaseExpiresAt}) + return true, nil +} + +// Cancel 满足刷新任务仓储接口;运行器测试通过 Runner.CancelJob 验证内存取消。 +func (repository *refreshRunnerTestRepository) Cancel(context.Context, int64, string) (bool, error) { + return repository.cancelResult, repository.cancelErr +} + +// Complete 记录任务终态并按测试配置返回租约命中结果。 +func (repository *refreshRunnerTestRepository) Complete(_ context.Context, jobID, token, status, resultJSON, errorMessage string) (bool, error) { + repository.mu.Lock() + defer repository.mu.Unlock() + repository.completeCalls = append(repository.completeCalls, refreshRunnerCompleteCall{jobID: jobID, token: token, status: status, resultJSON: resultJSON, errorMessage: errorMessage}) + return repository.completeApplied, repository.completeErr +} + +// Recoverable 返回测试预置的过期任务。 +func (repository *refreshRunnerTestRepository) Recoverable(_ context.Context, now int64, limit int) ([]RefreshJob, error) { + repository.mu.Lock() + defer repository.mu.Unlock() + repository.recoverCalls = append(repository.recoverCalls, refreshRunnerRecoverCall{now: now, limit: limit}) + if repository.recoverErr != nil { + return nil, repository.recoverErr + } + return append([]RefreshJob(nil), repository.jobs...), nil +} + +// RequeueExpired 记录重新入队操作并返回成功。 +func (repository *refreshRunnerTestRepository) RequeueExpired(_ context.Context, jobID string, _ int64) (bool, error) { + repository.mu.Lock() + defer repository.mu.Unlock() + repository.requeueCalls = append(repository.requeueCalls, jobID) + return true, nil +} + +// completeAppliedRepository 创建默认命中租约的测试仓储。 +func completeAppliedRepository() *refreshRunnerTestRepository { + return &refreshRunnerTestRepository{completeApplied: true} +} + +// TestNewRefreshJobResultUsesStableSnakeCase 验证任务结果持久化模型保持 HTTP 兼容的 snake_case JSON。 +func TestNewRefreshJobResultUsesStableSnakeCase(t *testing.T) { + // zero 是待转换的空刷新结果,确保空集合编码为 [] 而不是 null。 + zero := NewRefreshJobResult(RefreshResult{}) + // encoded、err 保存结果模型的 JSON 编码。 + encoded, err := json.Marshal(zero) + if err != nil { + t.Fatalf("编码刷新结果: %v", err) + } + if string(encoded) != `{"partial_failure":false,"message":"","summary":{"discovered":0,"list_updated":0,"soft_deleted":0,"detail_total":0,"total":0,"updated":0,"no_change":0,"failed":0},"results":[]}` { + t.Fatalf("刷新结果 JSON 不兼容: %s", encoded) + } + + // source 是包含账号和订单结果的应用刷新结果。 + source := RefreshResult{Results: []RefreshOrderResult{{CookieID: "cookie-1", Success: true, Discovered: 2, Updated: 3, SoftDeleted: 1}, {OrderID: "order-1", Stage: "detail"}}} + // converted 是带可选字段的任务结果模型。 + converted := NewRefreshJobResult(source) + if converted.Results[0].Discovered == nil || converted.Results[0].SoftDeleted == nil || converted.Results[1].Discovered != nil { + t.Fatalf("结果可选字段映射不正确: %+v", converted.Results) + } + // failedSource 验证失败账号结果不会新增旧响应未提供的 soft_deleted 字段。 + failedSource := NewRefreshJobResult(RefreshResult{Results: []RefreshOrderResult{{CookieID: "cookie-failed", Success: false, SoftDeleted: 1}}}) + if failedSource.Results[0].SoftDeleted != nil { + t.Fatalf("失败账号不应持久化 soft_deleted: %+v", failedSource.Results[0]) + } +} + +// TestRefreshJobRunnerRunJobSuccess 验证成功刷新会写入带稳定 JSON 的 succeeded 终态。 +func TestRefreshJobRunnerRunJobSuccess(t *testing.T) { + // repository 保存本用例的终态写入记录。 + repository := completeAppliedRepository() + // refresher 返回固定统计,验证 runner 调用应用业务而非 HTTP DTO。 + refresher := &refreshRunnerTestRefresher{result: RefreshResult{Message: "完成", Summary: RefreshSummary{Total: 1}}} + // runner、err 保存订单刷新运行器及构造错误。 + runner, err := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{}) + if err != nil { + t.Fatalf("构造运行器: %v", err) + } + // job 是本次执行的应用层任务模型。 + job := &RefreshJob{ID: "job-1", UserID: 7, CookieID: "cookie-1", FilterStatus: "pending_ship"} + // err 保存同步执行刷新任务的错误。 + if err := runner.RunJob(context.Background(), job, "token-1"); err != nil { + t.Fatalf("执行刷新任务: %v", err) + } + repository.mu.Lock() + // calls 保存终态写入快照。 + calls := append([]refreshRunnerCompleteCall(nil), repository.completeCalls...) + repository.mu.Unlock() + if len(calls) != 1 || calls[0].status != "succeeded" || calls[0].token != "token-1" { + t.Fatalf("成功终态参数不正确: %+v", calls) + } + if !strings.Contains(calls[0].resultJSON, `"partial_failure"`) || strings.Contains(calls[0].resultJSON, `"PartialFailure"`) { + t.Fatalf("成功终态 JSON 未使用稳定字段: %s", calls[0].resultJSON) + } +} + +// TestRefreshJobRunnerFailurePaths 验证业务失败、序列化失败和租约失配都保留可观测错误并写入失败终态。 +func TestRefreshJobRunnerFailurePaths(t *testing.T) { + // businessErr 是刷新业务返回的根因。 + businessErr := errors.New("平台请求失败") + // repository 保存业务失败终态记录。 + repository := completeAppliedRepository() + // refresher 返回预置业务错误。 + refresher := &refreshRunnerTestRefresher{err: businessErr} + // runner、err 保存业务失败场景的运行器构造结果。 + runner, err := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{}) + if err != nil { + t.Fatalf("构造业务失败运行器: %v", err) + } + // job 是业务失败场景的任务。 + job := &RefreshJob{ID: "job-failure", UserID: 7} + // err 保存业务失败任务返回的根因。 + if !errors.Is(runner.RunJob(context.Background(), job, "token-failure"), businessErr) { + t.Fatalf("业务错误未原样返回") + } + repository.mu.Lock() + // failedCall 保存业务失败终态快照。 + failedCall := repository.completeCalls[len(repository.completeCalls)-1] + repository.mu.Unlock() + if failedCall.status != "failed" || failedCall.resultJSON != "{}" || failedCall.errorMessage != businessErr.Error() { + t.Fatalf("业务失败终态不正确: %+v", failedCall) + } + + // marshalErr 是结果编码失败的根因。 + marshalErr := errors.New("编码失败") + // marshalRepository 保存序列化失败场景的终态记录。 + marshalRepository := completeAppliedRepository() + // marshalRefresher 返回固定成功结果。 + marshalRefresher := &refreshRunnerTestRefresher{result: RefreshResult{Message: "完成"}} + // marshalRunner、constructErr 保存注入编码器后的运行器。 + marshalRunner, constructErr := NewRefreshJobRunner(marshalRepository, marshalRefresher, RefreshJobRunnerOptions{MarshalResult: func(RefreshJobResult) ([]byte, error) { + return nil, marshalErr + }}) + if constructErr != nil { + t.Fatalf("构造序列化失败运行器: %v", constructErr) + } + if !errors.Is(marshalRunner.RunJob(context.Background(), job, "token-marshal"), marshalErr) { + t.Fatalf("序列化错误未原样返回") + } + + // lostLeaseRepository 模拟终态写入未命中租约。 + lostLeaseRepository := completeAppliedRepository() + lostLeaseRepository.completeApplied = false + // lostLeaseRunner、lostErr 保存租约失配运行器。 + lostLeaseRunner, lostErr := NewRefreshJobRunner(lostLeaseRepository, &refreshRunnerTestRefresher{result: RefreshResult{}}, RefreshJobRunnerOptions{}) + if lostErr != nil { + t.Fatalf("构造租约失配运行器: %v", lostErr) + } + if !errors.Is(lostLeaseRunner.RunJob(context.Background(), job, "token-lost"), ErrRefreshJobCompletionNotApplied) { + t.Fatalf("租约失配未转换为可观测错误") + } +} + +// TestRefreshJobRunnerCancelCloseAndStop 验证 worker 取消表、Stop/Close 和 Wait 能收口后台任务。 +func TestRefreshJobRunnerCancelCloseAndStop(t *testing.T) { + // repository 保存取消场景的失败终态。 + repository := completeAppliedRepository() + // refresher 等待 Context 取消后返回,模拟无法立即结束的外部请求。 + refresher := &refreshRunnerTestRefresher{waitForCancel: true} + // runner、err 保存短超时运行器。 + runner, err := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{JobTimeout: time.Hour}) + if err != nil { + t.Fatalf("构造取消运行器: %v", err) + } + // job 是等待取消的后台任务。 + job := &RefreshJob{ID: "job-cancel", UserID: 7} + // err 保存启动后台任务时的生命周期校验错误。 + if err := runner.StartJob(context.Background(), job, "token-cancel"); err != nil { + t.Fatalf("启动取消任务: %v", err) + } + if !runner.CancelJob(job.ID) { + t.Fatalf("未找到可取消 worker") + } + // closeCtx 限制本用例等待后台任务退出的时间。 + closeCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // err 保存运行器关闭和 worker 等待过程的错误。 + if err := runner.Close(closeCtx); err != nil { + t.Fatalf("关闭运行器: %v", err) + } + runner.Wait() + if runner.CancelJob(job.ID) { + t.Fatalf("worker 退出后不应仍可取消") + } + + // stoppedRunner 验证 Stop 后不能再次启动任务。 + stoppedRunner, err := NewRefreshJobRunner(completeAppliedRepository(), &refreshRunnerTestRefresher{}, RefreshJobRunnerOptions{}) + if err != nil { + t.Fatalf("构造停止运行器: %v", err) + } + stoppedRunner.Stop() + if !errors.Is(stoppedRunner.StartJob(context.Background(), job, "token-after-stop"), ErrRefreshJobRunnerStopped) { + t.Fatalf("Stop 后仍接受新 worker") + } +} + +// TestRefreshJobRunnerRecovery 验证恢复扫描会按过期任务重新入队、抢占租约并启动 worker。 +func TestRefreshJobRunnerRecovery(t *testing.T) { + // fixedNow 是恢复扫描使用的固定时间。 + fixedNow := time.Date(2026, 8, 17, 12, 0, 0, 0, time.UTC) + // repository 保存恢复任务和调用记录。 + repository := completeAppliedRepository() + repository.jobs = []RefreshJob{{ID: "job-recover", UserID: 9, CookieID: "cookie-9"}} + // refresher 返回立即成功的固定结果,使恢复 worker 可确定结束。 + refresher := &refreshRunnerTestRefresher{result: RefreshResult{Message: "恢复完成"}} + // runner、err 保存注入固定时间和令牌后的运行器。 + runner, err := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{Now: func() time.Time { return fixedNow }, NewToken: func() string { return "recovery-token" }, LeaseDuration: 2 * time.Minute}) + if err != nil { + t.Fatalf("构造恢复运行器: %v", err) + } + // err 保存单轮恢复扫描返回的错误。 + if err := runner.RunRecovery(context.Background()); err != nil { + t.Fatalf("执行恢复扫描: %v", err) + } + // closeCtx 限制恢复 worker 退出等待时间。 + closeCtx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + // err 保存关闭恢复 worker 的错误。 + if err := runner.Close(closeCtx); err != nil { + t.Fatalf("关闭恢复运行器: %v", err) + } + repository.mu.Lock() + // claims 保存恢复抢占记录。 + claims := append([]refreshRunnerClaimCall(nil), repository.claimCalls...) + // requeues 保存恢复重新入队记录。 + requeues := append([]string(nil), repository.requeueCalls...) + repository.mu.Unlock() + if len(requeues) != 1 || requeues[0] != "job-recover" || len(claims) != 1 || claims[0].token != "recovery-token" { + t.Fatalf("恢复接管记录不正确: requeues=%v claims=%v", requeues, claims) + } + if claims[0].leaseExpiresAt != fixedNow.Add(2*time.Minute).Unix() { + t.Fatalf("恢复租约截止时间不正确: %d", claims[0].leaseExpiresAt) + } +} + +// TestRefreshJobRunnerRecoveryError 验证恢复仓储错误直接返回,便于生命周期层观测并决定下一轮重试。 +func TestRefreshJobRunnerRecoveryError(t *testing.T) { + // scanErr 是恢复扫描仓储返回的错误。 + scanErr := errors.New("扫描失败") + // repository 保存扫描错误配置。 + repository := completeAppliedRepository() + repository.recoverErr = scanErr + // runner、err 保存恢复运行器构造结果。 + runner, err := NewRefreshJobRunner(repository, &refreshRunnerTestRefresher{}, RefreshJobRunnerOptions{}) + if err != nil { + t.Fatalf("构造扫描错误运行器: %v", err) + } + if !errors.Is(runner.RunRecovery(context.Background()), scanErr) { + t.Fatalf("恢复扫描错误未返回") + } +} diff --git a/internal/automation/account_tasks.go b/internal/automation/account_tasks.go index 06b79aa..5958db5 100644 --- a/internal/automation/account_tasks.go +++ b/internal/automation/account_tasks.go @@ -45,11 +45,11 @@ type AccountTaskSummary struct { type accountTaskCoordinator struct { // repository 提供账号任务所需的最小持久化能力。 repository AccountTaskRepository - // client 返回当前生效的账号任务平台客户端。 + // client 返回构造期固定的账号任务平台客户端。 client func() AccountTaskClient // senders 用于把任务响应 Cookie 同步到在线账号运行时。 senders SenderProvider - // recoverer 返回当前生效的凭证恢复器。 + // recoverer 返回构造期固定的凭证恢复器。 recoverer func() CredentialRecoverer // logger 记录账号任务扫描、凭证恢复和 Cookie 持久化异常。 logger interface { diff --git a/internal/automation/account_tasks_test.go b/internal/automation/account_tasks_test.go index a76629a..ab7df43 100644 --- a/internal/automation/account_tasks_test.go +++ b/internal/automation/account_tasks_test.go @@ -85,8 +85,7 @@ func TestAccountTaskRateIsOrderIdempotent(t *testing.T) { // client 保存client,供当前处理流程使用 client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-1"}, {TradeID: "order-2"}}} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // ctx 保存ctx,供当前处理流程使用 ctx := context.Background() if // err 保存err,供当前处理流程使用 @@ -123,8 +122,7 @@ func TestAccountTaskRateFinishFailureQuarantinesExternalSuccess(t *testing.T) { // client 记录远端评价调用次数,验证本地状态异常不会触发同一轮的重复外部动作。 client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-finish-failure"}}} // center 是待验证账号任务结果隔离逻辑的自动化中心。 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // settingsErr 表示写入自动评价设置时的数据库错误。 if settingsErr := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true, RateContent: "交易愉快", PolishTime: "03:00"}); settingsErr != nil { @@ -170,8 +168,7 @@ func TestAccountTaskRateFinishAndQuarantineFailureJoinsErrors(t *testing.T) { // client 记录已经成功执行的远端评价动作。 client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-double-failure"}}} // center 是待验证双重落库错误传播逻辑的自动化中心。 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // settingsErr 表示写入自动评价设置时的数据库错误。 if settingsErr := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true, RateContent: "交易愉快", PolishTime: "03:00"}); settingsErr != nil { @@ -209,8 +206,7 @@ func TestAccountTaskRateCancellationQuarantinesAndBlocksRetry(t *testing.T) { cancel: cancel, } // center 是待验证取消后补偿收口逻辑的自动化中心。 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // runErr 保存外部评价已完成但调用方取消后的人工核对错误。 _, runErr := center.RunAccountTask(requestCtx, "cid", TaskAutoRate) if !errors.Is(runErr, errAutomationNeedsReview) || !strings.Contains(runErr.Error(), "保存账号任务运行结果失败") { @@ -261,8 +257,7 @@ func TestAccountTaskPolishMarkFailureQuarantinesExternalSuccess(t *testing.T) { // client 记录远端擦亮调用次数,验证本地状态异常不会导致同一轮重复执行。 client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-mark-failure"}}} // center 是待验证擦亮结果隔离逻辑的自动化中心。 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // runErr 保存外部擦亮成功但日期索引收口失败后的人工核对错误。 _, runErr := center.RunAccountTask(ctx, "cid", TaskAutoPolish) if !errors.Is(runErr, errAutomationNeedsReview) || !strings.Contains(runErr.Error(), "保存商品擦亮日期") { @@ -297,9 +292,10 @@ func TestAccountTaskSessionExpiredRecoversOnceAndBlocksFurtherAPIRequests(t *tes // recoverer 保存recoverer,供当前处理流程使用 recoverer := &fakeCredentialRecoverer{store: store, fail: true} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) - center.SetOrderDetailFetcher(recoverer) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{ + AccountTaskClient: client, + OrderDetailFetcher: recoverer, + }) if // err 保存err,供当前处理流程使用 err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true, RateContent: "交易愉快", PolishTime: "03:00"}); err != nil { @@ -352,9 +348,10 @@ func TestAccountTaskStopsRemainingOrdersOnSessionExpired(t *testing.T) { // recoverer 保存recoverer,供当前处理流程使用 recoverer := &fakeCredentialRecoverer{store: store, fail: true} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) - center.SetOrderDetailFetcher(recoverer) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{ + AccountTaskClient: client, + OrderDetailFetcher: recoverer, + }) if // err 保存err,供当前处理流程使用 err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true, RateContent: "交易愉快", PolishTime: "03:00"}); err != nil { @@ -378,8 +375,7 @@ func TestAccountTaskPolishRunsOncePerBeijingDay(t *testing.T) { // client 保存client,供当前处理流程使用 client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}, {ID: "item-2"}}} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // ctx 保存ctx,供当前处理流程使用 ctx := context.Background() if // err 保存err,供当前处理流程使用 @@ -415,8 +411,7 @@ func TestManualPolishReportsItemFailures(t *testing.T) { // client 保存client,供当前处理流程使用 client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, polishErr: errors.New("both polish APIs failed")} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // ctx 保存ctx,供当前处理流程使用 ctx := context.Background() if // err 保存err,供当前处理流程使用 @@ -439,8 +434,7 @@ func TestManualPolishCanRetryImmediatelyAfterFailure(t *testing.T) { // client 保存client,供当前处理流程使用 client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, fetchItemsErr: errors.New("upstream 502")} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetAccountTaskClient(client) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{AccountTaskClient: client}) // ctx 保存ctx,供当前处理流程使用 ctx := context.Background() if // err 保存err,供当前处理流程使用 diff --git a/internal/automation/action_executor.go b/internal/automation/action_executor.go index 024f79e..e8e881f 100644 --- a/internal/automation/action_executor.go +++ b/internal/automation/action_executor.go @@ -2,6 +2,7 @@ package automation import ( "context" + "crypto/sha256" "encoding/json" "errors" "fmt" @@ -22,13 +23,13 @@ type automationActionExecutor struct { store *db.Store // senders 提供账号当前在线的消息发送器。 senders SenderProvider - // mtop 返回当前生效的 MTOP 客户端,支持测试替换和运行时注入。 + // mtop 返回构造期固定的 MTOP 客户端,外部调用期间不允许替换。 mtop func() mtop.Client - // recoverer 返回当前生效的凭证恢复器。 + // recoverer 返回构造期固定的凭证恢复器。 recoverer func() CredentialRecoverer // logger 记录确认发货和本地状态持久化异常。 logger *slog.Logger - // cookieSource 读取测试或运行时覆盖的账号 Cookie。 + // cookieSource 读取构造期注入或仓储提供的账号 Cookie。 cookieSource func(context.Context, string) (string, error) // wakeCredentialBlocked 在 Cookie 更新后唤醒凭证阻塞的自动化任务。 wakeCredentialBlocked func(context.Context, string) @@ -80,22 +81,18 @@ func (e *automationActionExecutor) confirmShipment(ctx context.Context, task Tas return e.confirmShipmentAttempt(ctx, task, true) } -// confirmShipmentAttempt 在凭证锁内调用 Consign,处理 Cookie 合并、凭证恢复和本地状态收口;远端成功但订单事实落库失败时创建可重试补偿记录。 +// confirmShipmentAttempt 使用凭证快照调用 Consign,并以指纹条件写回 Cookie;远端成功但订单事实落库失败时创建可重试补偿记录。 func (e *automationActionExecutor) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error { - // credentialUnlock 是账号凭证锁的释放函数。 + // credentialUnlock 是账号凭证锁的释放函数;锁只保护快照读取。 credentialUnlock := e.store.LockAccountCredentials(task.AccountID) - // credentialLocked 标记当前调用是否仍持有凭证锁。 - credentialLocked := true - defer func() { - if credentialLocked { - credentialUnlock() - } - }() // runtimeData 是确认发货所需的最小 Cookie 与 metadata 运行视图,不包含登录密码和账号资料。 runtimeData, err := e.store.Cookies.GetCookieRuntimeData(ctx, task.AccountID) + credentialUnlock() if err != nil { return err } + // runtimeFingerprint 是外部请求开始前的凭证指纹,用于阻止旧响应覆盖并发更新。 + runtimeFingerprint := credentialRuntimeFingerprint(runtimeData) // completeSnapshot 表示 metadata 中是否包含可恢复的完整 Cookie Jar。 _, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON) if strings.TrimSpace(runtimeData.Value) == "" && !completeSnapshot { @@ -140,33 +137,44 @@ func (e *automationActionExecutor) confirmShipmentAttempt(ctx context.Context, t value, snapshot, changed := cookieSession.State() // sessionHandled 表示本次请求是否由完整 Cookie Jar 接管。 sessionHandled := snapshot != nil - if changed { - // metadata 是准备写回数据库的 Cookie metadata。 - metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON) - if snapshot != nil { - metadata = cookierefresh.MetadataWithSnapshot(runtimeData.MetadataJSON, snapshot) - } - // saveErr 保存 Cookie Jar 写回数据库时的错误。 - if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil { - persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr)) - } else if value != cookieStr { - runtimeCookie = value - runtimeCookieChanged = true + // responseChanged 表示外部响应合并出了新的 Cookie 状态。 + responseChanged := changed || (!sessionHandled && callErr == nil && updated != "" && updated != cookieStr) + if responseChanged { + // persistUnlock 保护重新读取凭证和条件写回,外部 MTOP I/O 已经结束。 + persistUnlock := e.store.LockAccountCredentials(task.AccountID) + // currentData 保存写回前的最新凭证快照。 + currentData, currentErr := e.store.Cookies.GetCookieRuntimeData(ctx, task.AccountID) + if currentErr != nil { + persistenceErrs = append(persistenceErrs, fmt.Errorf("读取确认发货最新 Cookie: %w", currentErr)) + } else if credentialRuntimeFingerprint(currentData) != runtimeFingerprint { + // 并发更新已经产生新凭证,旧 MTOP 响应不得覆盖新状态。 + persistenceErrs = append(persistenceErrs, errors.New("确认发货响应 Cookie 与并发更新冲突,已跳过旧响应写回")) + } else if changed { + // metadata 是准备写回数据库的 Cookie metadata。 + metadata := cookierefresh.MetadataWithoutSnapshot(currentData.MetadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(currentData.MetadataJSON, snapshot) + } + // saveErr 保存 Cookie Jar 写回数据库时的错误。 + if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil { + persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr)) + } else if value != currentData.Value { + runtimeCookie = value + runtimeCookieChanged = true + } + } else if callErr == nil && updated != "" && updated != currentData.Value { + // 没有权威快照的历史账号保留扁平 Cookie 兼容路径,并清除可能过期的旧 Jar。 + metadata := cookierefresh.MetadataWithoutSnapshot(currentData.MetadataJSON) + // saveErr 保存扁平 Cookie 写回数据库时的错误。 + if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil { + persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr)) + } else { + runtimeCookie = updated + runtimeCookieChanged = true + } } + persistUnlock() } - if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr { - // 没有权威快照的历史账号保留扁平 Cookie 兼容路径,并清除可能过期的旧 Jar。 - metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON) - // saveErr 保存扁平 Cookie 写回数据库时的错误。 - if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil { - persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr)) - } else { - runtimeCookie = updated - runtimeCookieChanged = true - } - } - credentialUnlock() - credentialLocked = false if runtimeCookieChanged && e.senders != nil { // sender 是当前账号的在线消息发送器。 // running 表示账号是否仍处于运行状态。 @@ -309,17 +317,17 @@ func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, acti return sent, nil } -// sendDataCard 在卡券锁内原子消费数据卡密,并在确定未发送时恢复库存。 +// sendDataCard 只在卡券锁内完成库存预留与恢复,把外部消息发送放到锁外。 func (e *automationActionExecutor) sendDataCard(ctx context.Context, task Task, card *db.CardFull, count int) (int, error) { - // unlock 释放当前卡密组的并发消费锁。 - unlock := e.lockCard(card.ID) - defer unlock() // sent 是已经成功发送的数据卡密数量。 sent := 0 // i 表示当前数据卡密消费序号。 for i := 0; i < count; i++ { + // unlock 释放当前卡密组的并发消费锁;锁只覆盖本地库存操作。 + unlock := e.lockCard(card.ID) // content 是从库存中原子消费出的数据卡密。 content, err := e.store.Cards.ConsumeBatchData(ctx, card.ID) + unlock() if err != nil { return sent, err } @@ -327,8 +335,12 @@ func (e *automationActionExecutor) sendDataCard(ctx context.Context, task Task, // sendErr 保存数据卡密消息发送错误。 if sendErr := e.sendText(ctx, task, renderTemplate(content, task)); sendErr != nil { if errors.Is(sendErr, ErrMessageNotSent) { + // restoreUnlock 释放恢复库存所需的卡密组锁。 + restoreUnlock := e.lockCard(card.ID) // restoreErr 保存确定未发送时恢复库存的错误。 - if restoreErr := e.store.Cards.RestoreBatchData(ctx, card.ID, content); restoreErr != nil { + restoreErr := e.store.Cards.RestoreBatchData(ctx, card.ID, content) + restoreUnlock() + if restoreErr != nil { return sent, uncertainAction(errors.Join(sendErr, fmt.Errorf("恢复未发送卡密库存: %w", restoreErr))) } return sent, sendErr @@ -415,6 +427,13 @@ func (e *automationActionExecutor) lockCard(cardID int64) func() { return mu.Unlock } +// credentialRuntimeFingerprint 生成不暴露凭证内容的运行时指纹,用于条件写回冲突检测。 +func credentialRuntimeFingerprint(data db.CookieRuntimeData) string { + // sum 是 Cookie 与 metadata 拼接后的稳定摘要,不会被写入日志或响应。 + sum := sha256.Sum256([]byte(data.Value + "\x00" + data.MetadataJSON)) + return fmt.Sprintf("%x", sum[:]) +} + // actionMatchesOrderSpec 判断动作配置的规格是否匹配订单。 func actionMatchesOrderSpec(task Task, action db.AutomationAction) bool { // cfg 保存卡密动作的规格过滤配置。 diff --git a/internal/automation/action_executor_test.go b/internal/automation/action_executor_test.go index 51614a6..f338820 100644 --- a/internal/automation/action_executor_test.go +++ b/internal/automation/action_executor_test.go @@ -4,11 +4,58 @@ import ( "context" "errors" "fmt" + "sync/atomic" "testing" + "time" "xianyu-go/internal/db" ) +// blockingAutomationSender 在发送入口阻塞,用于验证库存锁不会覆盖外部消息 I/O。 +type blockingAutomationSender struct { + // calls 记录进入发送入口的并发调用次数。 + calls int32 + // firstEntered 通知第一个发送调用已经拿到卡密并进入外部 I/O。 + firstEntered chan struct{} + // secondEntered 通知第二个发送调用也已经进入外部 I/O。 + secondEntered chan struct{} + // release 允许被阻塞的外部发送继续完成。 + release chan struct{} +} + +// blockingSenderProvider 为并发测试提供阻塞发送器。 +type blockingSenderProvider struct { + // sender 保存待注入的阻塞发送器。 + sender MessageSender +} + +// Sender 返回并发测试使用的阻塞发送器。 +func (p blockingSenderProvider) Sender(string) (MessageSender, bool) { + return p.sender, true +} + +// SendText 模拟一个可控的慢速外部发送。 +func (s *blockingAutomationSender) SendText(context.Context, string, string, string) error { + // callNumber 保存本次发送在测试中的并发序号。 + callNumber := atomic.AddInt32(&s.calls, 1) + if callNumber == 1 { + close(s.firstEntered) + } + if callNumber == 2 { + close(s.secondEntered) + } + <-s.release + return nil +} + +// SendImage 满足消息发送接口;数据卡测试不会调用图片发送。 +func (s *blockingAutomationSender) SendImage(context.Context, string, string, string, int64) error { + return nil +} + +// UpdateCookie 满足消息发送接口;本测试不需要更新运行时 Cookie。 +func (s *blockingAutomationSender) UpdateCookie(string) {} + // TestAutomationActionExecutorPreservesMessageNotSent 验证动作执行器保留“确定未发送”错误,供运行协调器安全重试。 func TestAutomationActionExecutorPreservesMessageNotSent(t *testing.T) { // sender 是返回确定未发送错误的测试发送器。 @@ -25,3 +72,65 @@ func TestAutomationActionExecutorPreservesMessageNotSent(t *testing.T) { t.Fatalf("确定未发送错误未保留: sent=%d err=%v", sent, err) } } + +// TestSendDataCardReleasesInventoryLockBeforeExternalSend 验证第二个库存操作不会等待第一个外部发送完成。 +func TestSendDataCardReleasesInventoryLockBeforeExternalSend(t *testing.T) { + // store、cleanup 保存测试数据库及其清理函数。 + store, cleanup := newAutomationTestStore(t) + defer cleanup() + // ctx 保存本测试共用的上下文。 + ctx := context.Background() + // admin 保存创建卡券组所需的管理员用户。 + admin, err := store.Users.GetByUsername(ctx, "admin") + if err != nil { + t.Fatal(err) + } + // cardID 保存包含两条库存数据的卡券组标识。 + cardID, err := store.Cards.Create(ctx, &db.CardFull{ + Name: "concurrent-data", Type: "data", DataContent: "secret-1\nsecret-2", Enabled: true, UserID: admin.ID, + }) + if err != nil { + t.Fatal(err) + } + // sender 保存可控制外部发送完成时机的测试发送器。 + sender := &blockingAutomationSender{ + firstEntered: make(chan struct{}), + secondEntered: make(chan struct{}), + release: make(chan struct{}), + } + // center 保存注入测试发送器的自动化中心。 + center := New(store, blockingSenderProvider{sender: sender}, nil) + // result 保存两个并发动作的返回结果。 + result := make(chan error, 2) + // task 保存两个动作共用的订单消息上下文。 + task := Task{AccountID: "cid", ChatID: "chat", BuyerID: "buyer"} + // action 保存每次发送一条数据卡密的动作配置。 + action := db.AutomationAction{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, ConfigJSON: `{}`} + go func() { + // runErr 保存第一个并发卡密动作的执行错误。 + _, runErr := center.sendCard(ctx, task, action) + result <- runErr + }() + select { + case <-sender.firstEntered: + case <-time.After(time.Second): + t.Fatal("第一个发送调用未进入外部 I/O") + } + go func() { + // runErr 保存第二个并发卡密动作的执行错误。 + _, runErr := center.sendCard(ctx, task, action) + result <- runErr + }() + select { + case <-sender.secondEntered: + case <-time.After(300 * time.Millisecond): + t.Fatal("第二个库存操作被第一个外部发送阻塞") + } + close(sender.release) + for range 2 { + // runErr 保存并发动作收口时的执行错误。 + if runErr := <-result; runErr != nil { + t.Fatalf("并发数据卡发送失败: %v", runErr) + } + } +} diff --git a/internal/automation/center.go b/internal/automation/center.go index f8c017a..baa41fe 100644 --- a/internal/automation/center.go +++ b/internal/automation/center.go @@ -90,9 +90,10 @@ type CredentialRecoverer interface { RecoverExpiredCredential(ctx context.Context, cookieID string) bool } -// Notifier 发货结果通知器(多渠道)。可选依赖,未注入时跳过通知。 +// Notifier 发货结果通知器(多渠道)。可选依赖,未注入时跳过通知;实现必须按自动化运行和终态持久化去重。 type Notifier interface { - NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) + // NotifyAutomationRun 将自动化运行终态写入可持久化去重的通知链路;runID 和 status 共同标识同一次结果。 + NotifyAutomationRun(ctx context.Context, runID int64, accountID, buyerID, itemID, status, message, chatID string) } // Center 是统一自动化处理中心。 @@ -112,49 +113,103 @@ type Center struct { // notifications 负责把运行结果转换为可选的发货通知。 notifications deliveryNotifier // taskRunner 协调账号任务执行、凭证阻断和账号状态门禁。 - taskRunner accountTaskCoordinator - store *db.Store - senders SenderProvider - fetcher OrderDetailFetcher - recoverer CredentialRecoverer - notifier Notifier - mtop mtop.Client - accountTaskClient AccountTaskClient - logger *slog.Logger - cookieSrc func(context.Context, string) (string, error) + taskRunner accountTaskCoordinator + store *db.Store + senders SenderProvider + logger *slog.Logger + // dependencies 拥有生产构造时固定的外部依赖快照,运行期间不可替换。 + dependencies centerDependencies } -// New 构造自动化中心。 +// centerDependencies 集中拥有自动化中心构造后不可变的外部依赖。 +type centerDependencies struct { + // mtop 是确认发货使用的 MTOP 客户端。 + mtop mtop.Client + // accountTaskClient 是账号任务使用的平台客户端。 + accountTaskClient AccountTaskClient + // fetcher 是订单详情查询器。 + fetcher OrderDetailFetcher + // recoverer 是凭证恢复器。 + recoverer CredentialRecoverer + // notifier 是发货结果通知器。 + notifier Notifier + // cookieSrc 是构造期注入的 Cookie 读取函数。 + cookieSrc func(context.Context, string) (string, error) +} + +// CenterDependencies 保存自动化中心启动时必须固定的外部协作依赖。 +type CenterDependencies struct { + // MTop 提供确认发货使用的 MTOP 协议客户端;为空时使用默认实现。 + MTop mtop.Client + // AccountTaskClient 提供自动评价与商品擦亮的协议调用;使用默认 MTOP 时可自动复用其任务能力。 + AccountTaskClient AccountTaskClient + // OrderDetailFetcher 提供自动发货前的订单详情查询能力。 + OrderDetailFetcher OrderDetailFetcher + // Notifier 接收发货结果通知;为空时不发送通知。 + Notifier Notifier + // CookieSource 提供自动发货读取 Cookie 的可替换边界;为空时读取仓储。 + CookieSource func(context.Context, string) (string, error) +} + +// New 构造使用默认协议实现的自动化中心。 func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center { + return NewWithDependencies(store, senders, logger, CenterDependencies{}) +} + +// NewWithDependencies 构造依赖固定的自动化中心,生产装配应通过该入口注入外部能力。 +func NewWithDependencies(store *db.Store, senders SenderProvider, logger *slog.Logger, dependencies CenterDependencies) *Center { if logger == nil { logger = slog.Default() } - // client 保存client,供当前处理流程使用 - client := mtop.NewClient() + // client 保存确认发货使用的固定 MTOP 客户端。 + client := dependencies.MTop + // defaultTaskClient 保存默认 MTOP 实现同时提供的账号任务能力。 + var defaultTaskClient AccountTaskClient + if client == nil { + // defaultClient 保存默认协议客户端的具体实现,供两个消费者共享。 + defaultClient := mtop.NewClient() + client = defaultClient + defaultTaskClient = defaultClient + } + // accountTaskClient 保存自动评价和商品擦亮使用的固定协议客户端。 + accountTaskClient := dependencies.AccountTaskClient + if accountTaskClient == nil { + accountTaskClient = defaultTaskClient + } // center 保存center,供当前处理流程使用 center := &Center{ - facts: newEventFactRecorder(store), - rules: newRuleMatcher(store), - planner: actionPlanner{}, - store: store, - senders: senders, - mtop: client, - accountTaskClient: client, - logger: logger.With("subsys", "automation"), + facts: newEventFactRecorder(store), + rules: newRuleMatcher(store), + planner: actionPlanner{}, + store: store, + senders: senders, + dependencies: centerDependencies{ + mtop: client, + accountTaskClient: accountTaskClient, + fetcher: dependencies.OrderDetailFetcher, + notifier: dependencies.Notifier, + cookieSrc: dependencies.CookieSource, + }, + logger: logger.With("subsys", "automation"), + } + if // recoverer、ok 保存订单详情查询器提供的凭证恢复能力及类型判断结果 + recoverer, ok := center.dependencies.fetcher.(CredentialRecoverer); ok { + center.dependencies.recoverer = recoverer } center.actions = automationActionExecutor{ store: store, senders: senders, mtop: func() mtop.Client { - return center.mtop + return center.dependencies.mtop }, recoverer: func() CredentialRecoverer { - return center.recoverer + return center.dependencies.recoverer }, logger: center.logger, cookieSource: func(ctx context.Context, cookieID string) (string, error) { - if center.cookieSrc != nil { - return center.cookieSrc(ctx, cookieID) + // source 是构造期固定的 Cookie 读取函数;为空时回退到仓储。 + if source := center.dependencies.cookieSrc; source != nil { + return source(ctx, cookieID) } return center.store.Cookies.GetValue(ctx, cookieID) }, @@ -162,15 +217,15 @@ func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center { } center.notifications = deliveryNotifier{ current: func() Notifier { - return center.notifier + return center.dependencies.notifier }, } center.taskRunner = accountTaskCoordinator{ repository: newStoreAccountTaskRepository(store), - client: func() AccountTaskClient { return center.accountTaskClient }, + client: func() AccountTaskClient { return center.dependencies.accountTaskClient }, senders: senders, recoverer: func() CredentialRecoverer { - return center.recoverer + return center.dependencies.recoverer }, logger: center.logger, } @@ -183,20 +238,12 @@ func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center { accountAutomationAllowed: center.accountAutomationAllowed, deferTask: center.deferTask, executeAction: center.executeAction, - hasNotifier: func() bool { return center.notifier != nil }, + hasNotifier: func() bool { return center.dependencies.notifier != nil }, notifyResult: center.notifyResult, } return center } -// SetMTop 注入 mtop 客户端(确认发货用)。未注入时使用默认 HTTP 实现。 -func (c *Center) SetMTop(m mtop.Client) { c.mtop = m } - -// SetAccountTaskClient overrides automatic rating/polish transport for tests. -// SetAccountTaskClient 注入自动评价和商品擦亮的任务客户端。 -// SetAccountTaskClient 设置账号任务Client。 -func (c *Center) SetAccountTaskClient(client AccountTaskClient) { c.accountTaskClient = client } - // RunAccountTask 执行指定账号任务,并保持 Center 的公开兼容入口。 func (c *Center) RunAccountTask(ctx context.Context, accountID, taskType string) (AccountTaskSummary, error) { return c.taskRunner.runAccountTask(ctx, accountID, taskType) @@ -207,25 +254,6 @@ func (c *Center) scanAccountTasks(ctx context.Context) { c.taskRunner.scanAccountTasks(ctx) } -// SetOrderDetailFetcher 注入订单详情查询能力。 -func (c *Center) SetOrderDetailFetcher(fetcher OrderDetailFetcher) { - c.fetcher = fetcher - if // recoverer、ok 保存recoverer、ok,供当前处理流程使用 - recoverer, ok := fetcher.(CredentialRecoverer); ok { - c.recoverer = recoverer - } -} - -// SetNotifier 注入发货结果通知器。 -func (c *Center) SetNotifier(n Notifier) { - c.notifier = n -} - -// SetCookieSource 覆盖 cookie 读取逻辑,便于测试。 -func (c *Center) SetCookieSource(fn func(context.Context, string) (string, error)) { - c.cookieSrc = fn -} - // HandleTask 处理一条自动化任务。无匹配规则时安全忽略。 func (c *Center) HandleTask(ctx context.Context, task Task) error { // err 保存err,供当前处理流程使用 @@ -534,18 +562,18 @@ func (c *Center) executeRunActions(ctx context.Context, task Task, ruleID int64, } // notifyResult 根据规则执行结果发送通知。成功且实际发出了内容才通知, -// 避免无匹配动作的空跑刷屏;失败时发失败通知。 +// 避免无匹配动作的空跑刷屏;每次通知都以运行 ID 和终态持久化去重。 // notifyResult 负责notify结果相关处理。 -func (c *Center) notifyResult(task Task, status string, sent int, errMsg string) { - c.notifications.notifyResult(task, status, sent, errMsg) +func (c *Center) notifyResult(ctx context.Context, task Task, runID int64, status string, sent int, errMsg string) { + c.notifications.notifyResult(ctx, task, runID, status, sent, errMsg) } // notifyRunNeedsReview 负责notify运行NeedsReview相关处理。 -func (c *Center) notifyRunNeedsReview(run db.AutomationRun, reason string) { +func (c *Center) notifyRunNeedsReview(ctx context.Context, run db.AutomationRun, reason string) { if c == nil { return } - c.notifications.notifyRunNeedsReview(run, reason) + c.notifications.notifyRunNeedsReview(ctx, run, reason) } // actionDelaySeconds 统一卡密默认延时和动作覆盖语义。旧动作没有 @@ -602,7 +630,9 @@ func (c *Center) prepareTask(ctx context.Context, task Task) (Task, error) { needsDetail = true } } - if !needsDetail || c.fetcher == nil { + // fetcher 是构造期固定的订单详情查询器;执行过程中不允许替换依赖。 + fetcher := c.dependencies.fetcher + if !needsDetail || fetcher == nil { return task, nil } // cookieStr 保存登录凭证Str,供当前处理流程使用 @@ -616,7 +646,7 @@ func (c *Center) prepareTask(ctx context.Context, task Task) (Task, error) { } } // detail、err 保存detail、err,供当前处理流程使用 - detail, err := c.fetcher.FetchOrderDetail(ctx, task.AccountID, task.OrderID, task.ItemID, task.BuyerID, cookieStr) + detail, err := fetcher.FetchOrderDetail(ctx, task.AccountID, task.OrderID, task.ItemID, task.BuyerID, cookieStr) if err != nil { return task, err } diff --git a/internal/automation/center_dependencies_test.go b/internal/automation/center_dependencies_test.go new file mode 100644 index 0000000..47e685a --- /dev/null +++ b/internal/automation/center_dependencies_test.go @@ -0,0 +1,58 @@ +package automation + +import "testing" + +// TestNewWithDependenciesFixesCenterDependencies 验证自动化中心在构造阶段固定所有生产协作依赖。 +func TestNewWithDependenciesFixesCenterDependencies(t *testing.T) { + // store、cleanup 保存测试数据库及其清理函数。 + store, cleanup := newAutomationTestStore(t) + defer cleanup() + // sender 保存中心使用的消息发送器提供者。 + sender := testSenderProvider{sender: &testSender{}} + // fetcher 保存同时提供订单详情与凭证恢复能力的测试依赖。 + fetcher := &fakeCredentialRecoverer{store: store} + // notifier 保存发货通知测试依赖。 + notifier := &recordingNotifier{} + // client 保存确认发货使用的协议客户端。 + client := &fakeMTop{} + // taskClient 保存账号任务使用的独立协议客户端。 + taskClient := &fakeAccountTaskClient{} + // center 保存通过显式依赖构造器创建的自动化中心。 + center := NewWithDependencies(store, sender, nil, CenterDependencies{ + MTop: client, + AccountTaskClient: taskClient, + OrderDetailFetcher: fetcher, + Notifier: notifier, + }) + if center.dependencies.mtop != client || center.dependencies.accountTaskClient != taskClient { + t.Fatal("协议依赖未在构造阶段固定") + } + if center.dependencies.fetcher != fetcher || center.dependencies.recoverer != fetcher || center.dependencies.notifier != notifier { + t.Fatal("订单详情、凭证恢复或通知依赖未在构造阶段固定") + } + if center.dependencies.cookieSrc != nil { + t.Fatal("未注入 CookieSource 时不应保存读取函数") + } + if center.actions.store != store || center.actions.senders != sender { + t.Fatal("动作执行器未继承中心构造依赖") + } +} + +// TestNewWithDependenciesCopiesConfiguration 验证构造器复制依赖字段,调用方后续修改配置结构不会改变中心状态。 +func TestNewWithDependenciesCopiesConfiguration(t *testing.T) { + // store、cleanup 保存测试数据库及其清理函数。 + store, cleanup := newAutomationTestStore(t) + defer cleanup() + // baseClient 是构造阶段固定的协议客户端。 + baseClient := &fakeMTop{} + // replacementClient 是调用方在构造完成后写回配置结构的无关客户端。 + replacementClient := &fakeMTop{} + // dependencies 保存交给构造器的外部依赖配置。 + dependencies := CenterDependencies{MTop: baseClient} + // center 保存使用构造期配置创建的自动化中心。 + center := NewWithDependencies(store, nil, nil, dependencies) + dependencies.MTop = replacementClient + if center.dependencies.mtop != baseClient { + t.Fatal("构造完成后的配置修改不应改写中心依赖") + } +} diff --git a/internal/automation/center_mock_mtop_test.go b/internal/automation/center_mock_mtop_test.go index 9e08556..3b2e584 100644 --- a/internal/automation/center_mock_mtop_test.go +++ b/internal/automation/center_mock_mtop_test.go @@ -24,6 +24,10 @@ type fakeMTop struct { consignOrderIn string consignCookies []string consignResults []fakeConsignResult + // consignStarted 通知测试外部 Consign 调用已经开始。 + consignStarted chan struct{} + // consignRelease 控制测试外部 Consign 调用何时返回。 + consignRelease chan struct{} } // fakeConsignResult 保存fakeConsign结果,供当前处理流程使用 @@ -41,6 +45,12 @@ func (f *fakeMTop) FetchUserProfile(context.Context, string) (*mtop.UserProfileR // ConsignContext 负责Consign上下文相关处理。 func (f *fakeMTop) ConsignContext(_ context.Context, cookiesStr, orderID string) (bool, []string, string, error) { + if f.consignStarted != nil { + close(f.consignStarted) + } + if f.consignRelease != nil { + <-f.consignRelease + } f.consignCalls++ f.consignCookieIn = cookiesStr f.consignOrderIn = orderID @@ -54,6 +64,107 @@ func (f *fakeMTop) ConsignContext(_ context.Context, cookiesStr, orderID string) return f.consignOk, f.consignRet, f.consignUpdated, f.consignErr } +// TestConfirmShipmentReleasesCredentialLockBeforeExternalIO 验证 MTOP 外部调用期间同账号凭证锁可以被其他流程获取。 +func TestConfirmShipmentReleasesCredentialLockBeforeExternalIO(t *testing.T) { + // store、cleanup 保存测试数据库及其清理函数。 + store, cleanup := newAutomationTestStore(t) + defer cleanup() + // ctx 保存本测试共用的上下文。 + ctx := context.Background() + // fake 保存带有可控阻塞点的 MTOP 客户端。 + fake := &fakeMTop{ + consignOk: false, + consignRet: []string{"blocked"}, + consignStarted: make(chan struct{}), + consignRelease: make(chan struct{}), + } + // center 保存注入测试 MTOP 客户端的自动化中心。 + center := NewWithDependencies(store, nil, nil, CenterDependencies{MTop: fake}) + // result 保存确认发货流程的最终错误。 + result := make(chan error, 1) + go func() { + // runErr 保存阻塞 MTOP 确认发货流程的错误。 + result <- center.confirmShipment(ctx, Task{AccountID: "cid", OrderID: "lock-free-mtop", ForceConfirmShipment: true}) + }() + select { + case <-fake.consignStarted: + case <-time.After(time.Second): + t.Fatal("MTOP 调用未开始") + } + // acquired 表示另一个流程已经成功获取并释放同账号凭证锁。 + acquired := make(chan struct{}) + go func() { + // unlock 释放探测流程取得的账号凭证锁。 + unlock := store.LockAccountCredentials("cid") + unlock() + close(acquired) + }() + select { + case <-acquired: + case <-time.After(300 * time.Millisecond): + t.Fatal("MTOP 外部调用仍持有账号凭证锁") + } + close(fake.consignRelease) + // runErr 保存确认发货业务失败流程的返回错误。 + if runErr := <-result; runErr == nil { + t.Fatal("确认发货业务失败应返回错误") + } +} + +// TestConfirmShipmentDoesNotOverwriteConcurrentCredentialUpdate 验证旧 MTOP 响应不会覆盖并发完成的新凭证。 +func TestConfirmShipmentDoesNotOverwriteConcurrentCredentialUpdate(t *testing.T) { + // store、cleanup 保存测试数据库及其清理函数。 + store, cleanup := newAutomationTestStore(t) + defer cleanup() + // ctx 保存本测试共用的上下文。 + ctx := context.Background() + // initial 保存外部请求开始前的旧 Cookie。 + initial := "sid=old" + // err 保存写入外部请求初始凭证的错误。 + if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initial, `{"origin":"old"}`, 1); err != nil { + t.Fatal(err) + } + // fake 保存返回旧请求结果但可控阻塞的 MTOP 客户端。 + fake := &fakeMTop{ + consignOk: false, + consignRet: []string{"business-failure"}, + consignUpdated: "sid=stale-response", + consignStarted: make(chan struct{}), + consignRelease: make(chan struct{}), + } + // center 保存注入测试 MTOP 客户端的自动化中心。 + center := NewWithDependencies(store, nil, nil, CenterDependencies{MTop: fake}) + // result 保存确认发货流程的最终错误。 + result := make(chan error, 1) + go func() { + result <- center.confirmShipment(ctx, Task{AccountID: "cid", OrderID: "credential-conflict", ForceConfirmShipment: true}) + }() + select { + case <-fake.consignStarted: + case <-time.After(time.Second): + t.Fatal("MTOP 调用未开始") + } + // latest 保存并发凭证更新后的新 Cookie,旧响应不允许覆盖它。 + latest := "sid=new-runtime" + // err 保存写入并发新凭证的错误。 + if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", latest, `{"origin":"new"}`, 2); err != nil { + t.Fatal(err) + } + close(fake.consignRelease) + // runErr 保存并发凭证冲突场景的确认发货错误。 + if runErr := <-result; runErr == nil || !strings.Contains(runErr.Error(), "business-failure") { + t.Fatalf("确认发货应保留业务失败: %v", runErr) + } + // detail 保存最终凭证运行视图。 + detail, err := store.Cookies.GetDetails(ctx, "cid") + if err != nil { + t.Fatal(err) + } + if detail.Value != latest { + t.Fatalf("并发新凭证被旧响应覆盖: got=%q want=%q", detail.Value, latest) + } +} + // FetchItemsPage 负责Fetch商品列表页码相关处理。 func (f *fakeMTop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) { return nil, nil @@ -137,9 +248,10 @@ func TestConfirmShipmentRetriesFromCheckpointWithoutResendingCard(t *testing.T) // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(mtopMock) - center.SetOrderDetailFetcher(recoverer) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: mtopMock, + OrderDetailFetcher: recoverer, + }) // task 保存任务,供当前处理流程使用 task := Task{AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "checkpoint-order", ItemID: "checkpoint-item", BuyerID: "buyer", ChatID: "chat", Quantity: "1", Amount: "9.9"} @@ -188,9 +300,10 @@ func TestConfirmShipmentRecoversExpiredSessionAndRetriesOnlyConsign(t *testing.T // recoverer 保存recoverer,供当前处理流程使用 recoverer := &fakeCredentialRecoverer{store: store} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetMTop(mtopMock) - center.SetOrderDetailFetcher(recoverer) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{ + MTop: mtopMock, + OrderDetailFetcher: recoverer, + }) if // err 保存err,供当前处理流程使用 err := center.confirmShipment(ctx, Task{AccountID: "cid", OrderID: "session-order", ItemID: "item", BuyerID: "buyer", ChatID: "chat"}); err != nil { t.Fatal(err) @@ -236,9 +349,10 @@ func TestCenterConfirmShipment_MockMTopConsigError(t *testing.T) { // ConsignContext 报错。 mtopMock := &fakeMTop{consignErr: errors.New("network down")} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetMTop(mtopMock) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{Quantity: "1", Amount: "9.9"}}) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{ + MTop: mtopMock, + OrderDetailFetcher: testFetcher{detail: &OrderDetail{Quantity: "1", Amount: "9.9"}}, + }) // HandleTask 内部记录 executeRule 失败到 automation_runs(不向上透传错误)。 _ = center.HandleTask(ctx, Task{ @@ -269,9 +383,10 @@ func TestCenterConfirmShipment_MockMTopConsigError(t *testing.T) { // 第二轮:ConsignContext 返回 ok=false(业务失败),run 同样记 failed。 _ = store.Orders.Upsert(ctx, "order-mock2", db.OrderUpsertOpts{CookieID: "cid", ItemID: "item-1", BuyerID: "buyer-1"}) // center2 保存center2,供当前处理流程使用 - center2 := New(store, testSenderProvider{sender: &testSender{}}, nil) - center2.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}}) - center2.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{Quantity: "1", Amount: "9.9"}}) + center2 := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{ + MTop: &fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}}, + OrderDetailFetcher: testFetcher{detail: &OrderDetail{Quantity: "1", Amount: "9.9"}}, + }) _ = center2.HandleTask(ctx, Task{ Source: "ws", AccountID: "cid", CookieStr: "unb=1; _m_h5_tk=tk;", TriggerType: TriggerOrderPaid, ChatID: "chat-2", OrderID: "order-mock2", ItemID: "item-1", BuyerID: "buyer-1", @@ -303,8 +418,7 @@ func TestConfirmShipmentQuarantinesKnownRemoteSuccessWhenLocalPersistenceFails(t // mtopMock 保存mtopMock,供当前处理流程使用 mtopMock := &fakeMTop{consignOk: true, consignUpdated: "unb=123; _m_h5_tk=updated_1;"} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetMTop(mtopMock) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{MTop: mtopMock}) // err 保存err,供当前处理流程使用 err := center.confirmShipment(ctx, Task{ AccountID: "cid", OrderID: "persist-failure", ItemID: "item-1", BuyerID: "buyer", ChatID: "chat", @@ -379,8 +493,9 @@ func TestConfirmShipmentKeepsAuthoritativeSnapshotWhenSessionUnchanged(t *testin // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: &fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated}, + }) // err 保存err,供当前处理流程使用 err := center.confirmShipment(ctx, Task{ AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true, @@ -426,8 +541,9 @@ func TestConfirmShipmentKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: &fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated}, + }) // err 保存err,供当前处理流程使用 err := center.confirmShipment(ctx, Task{ AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true, diff --git a/internal/automation/center_test.go b/internal/automation/center_test.go index a50e865..0e9a3c2 100644 --- a/internal/automation/center_test.go +++ b/internal/automation/center_test.go @@ -460,8 +460,9 @@ func TestReviewAutomationsDoNotRequireOrderDetail(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetOrderDetailFetcher(testFetcher{err: errors.New("must not fetch"), calls: &calls}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{err: errors.New("must not fetch"), calls: &calls}, + }) // i、trigger 表示当前遍历过程中的i、trigger for i, trigger := range []string{TriggerBuyerReviewed, TriggerReviewMissingTimeout} { // task 保存任务,供当前处理流程使用 @@ -497,8 +498,9 @@ func TestOrderPaidPreparationFailureIsPersistedAndRecovered(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetOrderDetailFetcher(testFetcher{err: errors.New("temporary order API failure")}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{err: errors.New("temporary order API failure")}, + }) // task 保存任务,供当前处理流程使用 task := Task{Source: "ws", AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "pending-order", ItemID: "pending-item", ChatID: "chat", BuyerID: "buyer", Raw: map[string]any{"message_id": "paid-1"}} if // err 保存err,供当前处理流程使用 @@ -512,9 +514,12 @@ func TestOrderPaidPreparationFailureIsPersistedAndRecovered(t *testing.T) { if pending != 1 || runs != 0 { t.Fatalf("pending=%d runs=%d", pending, runs) } - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{SpecName: "套餐", SpecValue: "恢复版", Quantity: "1", Amount: "9.9"}}) + // recoveredCenter 模拟进程重启后以可用详情查询器重新装配自动化中心。 + recoveredCenter := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{detail: &OrderDetail{SpecName: "套餐", SpecValue: "恢复版", Quantity: "1", Amount: "9.9"}}, + }) _, _ = store.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0`) - NewScheduler(center).runDeferredTasks(ctx) + NewScheduler(recoveredCenter).runDeferredTasks(ctx) if len(sender.texts) != 1 || sender.texts[0] != "RECOVERED-CARD" { t.Fatalf("recovered sends=%v", sender.texts) } @@ -1001,10 +1006,11 @@ func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{ - SpecName: "套餐", SpecValue: "90天", Quantity: "2", Amount: "19.8", OrderStatus: "pending_ship", - }}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{detail: &OrderDetail{ + SpecName: "套餐", SpecValue: "90天", Quantity: "2", Amount: "19.8", OrderStatus: "pending_ship", + }}, + }) err = center.HandleTask(ctx, Task{ Source: "ws", AccountID: "cid", CookieStr: "unb=123; _m_h5_tk=tk_1;", TriggerType: TriggerOrderPaid, @@ -1130,10 +1136,11 @@ func TestCenterOrderPaidSendsAllCardActionsForSameSpec(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{ - SpecName: "套餐", SpecValue: "组合版", Quantity: "1", Amount: "29.9", - }}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{detail: &OrderDetail{ + SpecName: "套餐", SpecValue: "组合版", Quantity: "1", Amount: "29.9", + }}, + }) if // err 保存err,供当前处理流程使用 err := center.HandleTask(ctx, Task{ @@ -1184,8 +1191,9 @@ func TestCenterOrderPaidDoesNotConfirmWhenNoCardSpecMatches(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{SpecName: "套餐", SpecValue: "90天", Quantity: "1"}}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{detail: &OrderDetail{SpecName: "套餐", SpecValue: "90天", Quantity: "1"}}, + }) err = center.HandleTask(ctx, Task{ Source: "ws", AccountID: "cid", CookieStr: "unb=123; _m_h5_tk=tk_1;", TriggerType: TriggerOrderPaid, @@ -1245,9 +1253,10 @@ func TestCenterOrderPaidSendsCardBeforeConfirmShipment(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{events: &events} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(&mtop.ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{Quantity: "1", Amount: "9.9"}}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: &mtop.ClientImpl{HTTPClient: server.Client(), ConsignURL: server.URL + "/"}, + OrderDetailFetcher: testFetcher{detail: &OrderDetail{Quantity: "1", Amount: "9.9"}}, + }) if // err 保存err,供当前处理流程使用 err := center.HandleTask(ctx, Task{ @@ -1327,8 +1336,9 @@ func TestConfirmShipmentPersistsAuthoritativeSessionBeforeParseError(t *testing. } }} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: &mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI}, + }) // err 保存err,供当前处理流程使用 err := center.confirmShipment(ctx, Task{ AccountID: "cid", OrderID: "session-parse-error", ForceConfirmShipment: true, @@ -1419,8 +1429,9 @@ func TestConfirmShipmentPropagatesAuthoritativeEmptySession(t *testing.T) { // sender 保存sender,供当前处理流程使用 sender := &testSender{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: &mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI}, + }) // err 保存err,供当前处理流程使用 err := center.confirmShipment(ctx, Task{ AccountID: "cid", OrderID: "authoritative-empty-session", ForceConfirmShipment: true, @@ -1481,9 +1492,10 @@ func TestManualFullDeliveryIsImmediateIdempotentAndForcesConfirmation(t *testing // mtopMock 保存mtopMock,供当前处理流程使用 mtopMock := &fakeMTop{consignOk: true} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(mtopMock) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{Quantity: "1", OrderStatus: "pending_ship"}}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: mtopMock, + OrderDetailFetcher: testFetcher{detail: &OrderDetail{Quantity: "1", OrderStatus: "pending_ship"}}, + }) // order 保存订单,供当前处理流程使用 order := &db.Order{OrderID: "manual-order", CookieID: "cid", ItemID: "manual-item", BuyerID: "buyer", ChatID: "chat"} @@ -1543,9 +1555,10 @@ func newManualDeliveryFixture(t *testing.T, orderID string) (context.Context, *d // mtopMock 记录远端确认发货调用。 mtopMock := &fakeMTop{consignOk: true} // center 是待验证的自动化中心。 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetMTop(mtopMock) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{Quantity: "1", OrderStatus: "pending_ship"}}) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + MTop: mtopMock, + OrderDetailFetcher: testFetcher{detail: &OrderDetail{Quantity: "1", OrderStatus: "pending_ship"}}, + }) // order 保存夹具使用的订单输入。 order := &db.Order{OrderID: orderID, CookieID: "cid", ItemID: "manual-item", BuyerID: "buyer", ChatID: "chat"} return ctx, store, center, sender, mtopMock, order, cleanup @@ -1635,21 +1648,27 @@ func TestPrepareTaskUpsertFailureStopsBeforeExternalAction(t *testing.T) { } } -// recordingNotifier 记录所有 NotifyDelivery 调用,用于断言 automation.Center 接线。 +// recordingNotifier 记录所有按自动化运行幂等的通知调用,用于断言 automation.Center 接线。 type recordingNotifier struct { mu sync.Mutex calls []struct { - accountID, buyerID, itemID, message, chatID string + runID int64 + contextCanceled bool + accountID, buyerID, itemID, status, message, chatID string } } -// NotifyDelivery 负责Notify发货相关处理。 -func (r *recordingNotifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) { +// NotifyAutomationRun 记录自动化运行终态通知;测试替身只记录参数,不模拟持久化 outbox。 +func (r *recordingNotifier) NotifyAutomationRun(ctx context.Context, runID int64, accountID, buyerID, itemID, status, message, chatID string) { + // contextCanceled 记录入队上下文是否已被取消;正常运行收口必须在取消前持久化通知。 + contextCanceled := ctx.Err() != nil r.mu.Lock() defer r.mu.Unlock() r.calls = append(r.calls, struct { - accountID, buyerID, itemID, message, chatID string - }{accountID, buyerID, itemID, message, chatID}) + runID int64 + contextCanceled bool + accountID, buyerID, itemID, status, message, chatID string + }{runID, contextCanceled, accountID, buyerID, itemID, status, message, chatID}) } // messages 负责消息列表相关处理。 @@ -1665,6 +1684,19 @@ func (r *recordingNotifier) messages() []string { return out } +// hasCanceledContext 返回是否存在使用已取消上下文的自动化终态通知调用。 +func (r *recordingNotifier) hasCanceledContext() bool { + r.mu.Lock() + defer r.mu.Unlock() + // call 表示当前遍历到的终态通知调用记录。 + for _, call := range r.calls { + if call.contextCanceled { + return true + } + } + return false +} + // TestCenterNotifiesOnDeliverySuccess 验证规则执行成功(实际发出卡券)时触发成功通知。 func TestCenterNotifiesOnDeliverySuccess(t *testing.T) { // store、cleanup 保存store、cleanup,供当前处理流程使用 @@ -1694,11 +1726,12 @@ func TestCenterNotifiesOnDeliverySuccess(t *testing.T) { // notifier 保存notifier,供当前处理流程使用 notifier := &recordingNotifier{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{ - SpecName: "套餐", SpecValue: "标准", Quantity: "1", Amount: "9.9", OrderStatus: "pending_ship", - }}) - center.SetNotifier(notifier) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{detail: &OrderDetail{ + SpecName: "套餐", SpecValue: "标准", Quantity: "1", Amount: "9.9", OrderStatus: "pending_ship", + }}, + Notifier: notifier, + }) if // err 保存err,供当前处理流程使用 err := center.HandleTask(ctx, Task{ @@ -1716,6 +1749,9 @@ func TestCenterNotifiesOnDeliverySuccess(t *testing.T) { if !strings.Contains(msgs[0], "成功") || !strings.Contains(msgs[0], "order-n") { t.Fatalf("通知文案异常: %q", msgs[0]) } + if notifier.hasCanceledContext() { + t.Fatal("运行收口通知不应使用已取消上下文,否则 outbox 无法持久化") + } } // TestCenterNotifiesOnDeliveryFailure 验证无匹配规格动作导致失败时触发失败通知。 @@ -1748,11 +1784,12 @@ func TestCenterNotifiesOnDeliveryFailure(t *testing.T) { // notifier 保存notifier,供当前处理流程使用 notifier := &recordingNotifier{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: sender}, nil) - center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{ - SpecName: "套餐", SpecValue: "90天", Quantity: "1", Amount: "9.9", OrderStatus: "pending_ship", - }}) - center.SetNotifier(notifier) + center := NewWithDependencies(store, testSenderProvider{sender: sender}, nil, CenterDependencies{ + OrderDetailFetcher: testFetcher{detail: &OrderDetail{ + SpecName: "套餐", SpecValue: "90天", Quantity: "1", Amount: "9.9", OrderStatus: "pending_ship", + }}, + Notifier: notifier, + }) // HandleTask 对单条规则失败只记录日志不返回错误,但通知应已发出。 _ = center.HandleTask(ctx, Task{ @@ -1781,8 +1818,7 @@ func TestCenterNoNotifyWhenNoMatchingRule(t *testing.T) { // notifier 保存notifier,供当前处理流程使用 notifier := &recordingNotifier{} // center 保存center,供当前处理流程使用 - center := New(store, testSenderProvider{sender: &testSender{}}, nil) - center.SetNotifier(notifier) + center := NewWithDependencies(store, testSenderProvider{sender: &testSender{}}, nil, CenterDependencies{Notifier: notifier}) _ = center.HandleTask(ctx, Task{ Source: "ws", AccountID: "cid", TriggerType: TriggerOrderPaid, diff --git a/internal/automation/delivery_notifier.go b/internal/automation/delivery_notifier.go index d9fff76..296d218 100644 --- a/internal/automation/delivery_notifier.go +++ b/internal/automation/delivery_notifier.go @@ -1,19 +1,21 @@ package automation import ( + "context" "fmt" "xianyu-go/internal/db" ) -// deliveryNotifier 将自动化运行状态转换为可选的多渠道发货结果通知,并通过回调读取运行时替换的通知器。 +// deliveryNotifier 将自动化运行状态转换为可选的多渠道发货结果通知,并通过回调读取构造期固定的通知器。 type deliveryNotifier struct { - // current 返回当前生效的通知器实例。 + // current 返回构造期固定的通知器实例;为空时不发送外部通知。 current func() Notifier } // notifyResult 根据规则执行结果发送通知,成功且实际发出内容时才发送成功通知。 -func (n deliveryNotifier) notifyResult(task Task, status string, sent int, errMsg string) { +// runID 与 status 会传给持久化 outbox,防止恢复扫描对同一运行重复排队。 +func (n deliveryNotifier) notifyResult(ctx context.Context, task Task, runID int64, status string, sent int, errMsg string) { // notifier 是当前可选的外部通知器。 notifier := n.current() if notifier == nil { @@ -34,16 +36,16 @@ func (n deliveryNotifier) notifyResult(task Task, status string, sent int, errMs } // message 是成功通知正文。 message := fmt.Sprintf("✅ %s成功(订单 %s,已发送 %d 条)", triggerName, task.OrderID, sent) - notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, message, task.ChatID) + notifier.NotifyAutomationRun(ctx, runID, task.AccountID, task.BuyerID, task.ItemID, status, message, task.ChatID) return } // message 是失败或人工核对通知正文。 message := fmt.Sprintf("🚨 %s失败(订单 %s):%s", triggerName, task.OrderID, errMsg) - notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, message, task.ChatID) + notifier.NotifyAutomationRun(ctx, runID, task.AccountID, task.BuyerID, task.ItemID, status, message, task.ChatID) } // notifyRunNeedsReview 通知运行需要人工核对,并复用统一结果通知格式。 -func (n deliveryNotifier) notifyRunNeedsReview(run db.AutomationRun, reason string) { +func (n deliveryNotifier) notifyRunNeedsReview(ctx context.Context, run db.AutomationRun, reason string) { if n.current() == nil { return } @@ -56,5 +58,5 @@ func (n deliveryNotifier) notifyRunNeedsReview(run db.AutomationRun, reason stri OrderID: run.OrderID, TriggerType: run.TriggerType, } - n.notifyResult(task, "needs_review", run.SentCount, "需要人工核对:"+reason) + n.notifyResult(ctx, task, run.ID, "needs_review", run.SentCount, "需要人工核对:"+reason) } diff --git a/internal/automation/run_coordinator.go b/internal/automation/run_coordinator.go index 60793d7..91aacc2 100644 --- a/internal/automation/run_coordinator.go +++ b/internal/automation/run_coordinator.go @@ -31,8 +31,8 @@ type automationRunCoordinator struct { executeAction func(context.Context, Task, db.AutomationAction) (int, error) // hasNotifier 判断当前是否注入了结果通知器。 hasNotifier func() bool - // notifyResult 将运行结果转换为用户可见的通知。 - notifyResult func(Task, string, int, string) + // notifyResult 将运行结果转换为用户可见的、按运行终态幂等的通知。 + notifyResult func(context.Context, Task, int64, string, int, string) } // executeRule 创建或恢复一次自动化运行,并统一处理运行成功、失败、延期和人工核对结果;resultErr 返回动作执行或结果收口错误。 @@ -107,6 +107,8 @@ func (r automationRunCoordinator) executeRule(ctx context.Context, task Task, ru } // finishCtx 限制运行收口不能被原始请求取消。 finishCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // cancel 在结果通知已使用 finishCtx 持久化入队后释放收口上下文,避免取消导致通知静默丢失。 + defer cancel() // finishErr 保存运行结果写入失败,避免覆盖原始动作错误。 if finishErr := r.store.Automation.FinishRun(finishCtx, run.ID, run.AttemptCount, status, sent, errMsg); finishErr != nil { // reason 说明结果落库失败后禁止自动重放的原因,并用于人工核对记录。 @@ -122,9 +124,8 @@ func (r automationRunCoordinator) executeRule(ctx context.Context, task Task, ru resultErr = errors.Join(resultErr, errAutomationNeedsReview, fmt.Errorf("保存自动化执行结果失败: %w", finishErr)) } } - cancel() if r.hasNotifier() { - r.notifyResult(task, status, sent, errMsg) + r.notifyResult(finishCtx, task, run.ID, status, sent, errMsg) } }() // actions 是当前规则生成的完整动作计划。 @@ -143,7 +144,7 @@ func (r automationRunCoordinator) executeRule(ctx context.Context, task Task, ru if errors.Is(err, errAutomationNeedsReview) { finish = false if r.hasNotifier() && !errors.Is(err, errAutomationQuarantine) { - r.notifyResult(task, "needs_review", sent, err.Error()) + r.notifyResult(ctx, task, run.ID, "needs_review", sent, err.Error()) } return err } @@ -159,7 +160,7 @@ func (r automationRunCoordinator) executeRule(ctx context.Context, task Task, ru } finish = false if r.hasNotifier() { - r.notifyResult(task, "needs_review", sent, reason) + r.notifyResult(ctx, task, run.ID, "needs_review", sent, reason) } return fmt.Errorf("%w: %v", errAutomationNeedsReview, err) } @@ -182,7 +183,7 @@ func (r automationRunCoordinator) executeRule(ctx context.Context, task Task, ru } finish = false if r.hasNotifier() { - r.notifyResult(task, "needs_review", sent, reason) + r.notifyResult(ctx, task, run.ID, "needs_review", sent, reason) } return fmt.Errorf("%w: %v", errAutomationNeedsReview, incrementErr) } diff --git a/internal/automation/scheduler.go b/internal/automation/scheduler.go index 0b84322..50987f6 100644 --- a/internal/automation/scheduler.go +++ b/internal/automation/scheduler.go @@ -250,7 +250,7 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) error { func (s *Scheduler) quarantineRunForReview(ctx context.Context, run db.AutomationRun, reason string) error { // quarantineErr 表示人工核对状态写入失败;失败时数据库中的原状态仍可能允许下一轮恢复。 quarantineErr := s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason) - s.center.notifyRunNeedsReview(run, reason) + s.center.notifyRunNeedsReview(ctx, run, reason) if quarantineErr == nil { return nil } diff --git a/internal/db/migrations/mysql/00034_notification_outbox_idempotency.sql b/internal/db/migrations/mysql/00034_notification_outbox_idempotency.sql new file mode 100644 index 0000000..0a190dc --- /dev/null +++ b/internal/db/migrations/mysql/00034_notification_outbox_idempotency.sql @@ -0,0 +1,10 @@ +-- +goose Up +-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。 +-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。 +ALTER TABLE notification_outbox ADD COLUMN idempotency_key VARCHAR(255) NULL; +CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency + ON notification_outbox(channel_id, idempotency_key); + +-- +goose Down +DROP INDEX idx_notification_outbox_channel_idempotency ON notification_outbox; +ALTER TABLE notification_outbox DROP COLUMN idempotency_key; diff --git a/internal/db/migrations/postgres/00034_notification_outbox_idempotency.sql b/internal/db/migrations/postgres/00034_notification_outbox_idempotency.sql new file mode 100644 index 0000000..fbb6bd5 --- /dev/null +++ b/internal/db/migrations/postgres/00034_notification_outbox_idempotency.sql @@ -0,0 +1,10 @@ +-- +goose Up +-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。 +-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。 +ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL; +CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency + ON notification_outbox(channel_id, idempotency_key); + +-- +goose Down +DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency; +ALTER TABLE notification_outbox DROP COLUMN idempotency_key; diff --git a/internal/db/migrations/sqlite/00034_notification_outbox_idempotency.sql b/internal/db/migrations/sqlite/00034_notification_outbox_idempotency.sql new file mode 100644 index 0000000..fbb6bd5 --- /dev/null +++ b/internal/db/migrations/sqlite/00034_notification_outbox_idempotency.sql @@ -0,0 +1,10 @@ +-- +goose Up +-- idempotency_key 让同一自动化运行终态对同一渠道只保留一条 outbox 记录。 +-- NULL 保持历史普通通知可重复投递;uncertain 记录保留原键,从而禁止恢复时自动重新入队。 +ALTER TABLE notification_outbox ADD COLUMN idempotency_key TEXT NULL; +CREATE UNIQUE INDEX idx_notification_outbox_channel_idempotency + ON notification_outbox(channel_id, idempotency_key); + +-- +goose Down +DROP INDEX IF EXISTS idx_notification_outbox_channel_idempotency; +ALTER TABLE notification_outbox DROP COLUMN idempotency_key; diff --git a/internal/db/notification_outbox_test.go b/internal/db/notification_outbox_test.go index d4f9e9b..6b3783c 100644 --- a/internal/db/notification_outbox_test.go +++ b/internal/db/notification_outbox_test.go @@ -105,6 +105,83 @@ func TestNotificationOutboxLeaseFencesStaleWorker(t *testing.T) { } } +// TestNotificationOutboxIdempotencyKeepsUncertainMessage 验证同一业务投递键不会重复入队, +// 且外部发送成功后本地确认失败形成 uncertain 时,恢复扫描也不能把它重新变为可发送状态。 +func TestNotificationOutboxIdempotencyKeepsUncertainMessage(t *testing.T) { + // store、cleanup 保存带完整迁移的 SQLite 存储与关闭责任。 + store, cleanup := newTestDB(t) + defer cleanup() + // ctx 限制本测试所有数据库操作的生命周期。 + ctx := context.Background() + // created、createErr 保存测试用户创建结果和数据库错误。 + created, createErr := store.Users.Create(ctx, "notify-idempotency", "notify-idempotency@example.com", "pw") + if createErr != nil || !created { + t.Fatalf("create owner: created=%v err=%v", created, createErr) + } + // owner、ownerErr 保存通知渠道所属用户和读取错误。 + owner, ownerErr := store.Users.GetByUsername(ctx, "notify-idempotency") + if ownerErr != nil { + t.Fatal(ownerErr) + } + // channelResult、channelErr 保存测试通知渠道插入结果和数据库错误。 + channelResult, channelErr := store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,1,?)`, "idempotency", "webhook", `{}`, owner.ID) + if channelErr != nil { + t.Fatal(channelErr) + } + // channelID、channelIDErr 保存测试渠道主键和读取错误。 + channelID, channelIDErr := channelResult.LastInsertId() + if channelIDErr != nil { + t.Fatal(channelIDErr) + } + // input 表示同一自动化运行成功终态对该渠道的稳定投递事实。 + input := NotificationOutboxInput{ChannelID: channelID, EventType: "delivery_result", Body: "自动化结果", IdempotencyKey: "automation-run:42:success"} + // enqueueErr 保存首次持久化业务投递键时的数据库错误。 + if enqueueErr := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{input}); enqueueErr != nil { + t.Fatal(enqueueErr) + } + // enqueueErr 保存同一业务投递键重复入队时的数据库错误;冲突应被仓储忽略而非作为错误返回。 + if enqueueErr := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{input}); enqueueErr != nil { + t.Fatal(enqueueErr) + } + // queued 保存第一次重复入队后的记录数;同一渠道只能保留一条该业务键。 + var queued int + // queryErr 保存读取去重后记录数时的数据库错误。 + if queryErr := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM notification_outbox WHERE channel_id=? AND idempotency_key=?`, channelID, input.IdempotencyKey).Scan(&queued); queryErr != nil { + t.Fatal(queryErr) + } + if queued != 1 { + t.Fatalf("duplicate queue count=%d want 1", queued) + } + // claimed、claimErr 保存本次投递领取的记录和数据库错误。 + claimed, claimErr := store.Notifications.ClaimOutbox(ctx, "idempotency-worker", time.Now(), 1) + if claimErr != nil || len(claimed) != 1 { + t.Fatalf("claim: messages=%+v err=%v", claimed, claimErr) + } + // isolated、isolateErr 保存外部投递成功但本地确认失败后的隔离结果和数据库错误。 + isolated, isolateErr := store.Notifications.MarkOutboxUncertain(ctx, claimed[0].ID, "idempotency-worker", "local completion failed") + if isolateErr != nil || !isolated { + t.Fatalf("mark uncertain: isolated=%v err=%v", isolated, isolateErr) + } + // enqueueErr 保存 uncertain 运行被恢复流程再次报告时的数据库错误;同一键必须继续被忽略。 + if enqueueErr := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{input}); enqueueErr != nil { + t.Fatal(enqueueErr) + } + // status 保存恢复后仍应保留的 uncertain 状态,禁止重新变为 pending。 + var status string + // queryErr 保存读取 uncertain 状态时的数据库错误。 + if queryErr := store.DB.QueryRowContext(ctx, `SELECT status FROM notification_outbox WHERE channel_id=? AND idempotency_key=?`, channelID, input.IdempotencyKey).Scan(&status); queryErr != nil { + t.Fatal(queryErr) + } + if status != "uncertain" { + t.Fatalf("status=%q want uncertain", status) + } + // recoveredClaim、recoveredErr 保存重复恢复后可领取消息和数据库错误;uncertain 消息必须不可领取。 + recoveredClaim, recoveredErr := store.Notifications.ClaimOutbox(ctx, "recovery-worker", time.Now().Add(time.Hour), 10) + if recoveredErr != nil || len(recoveredClaim) != 0 { + t.Fatalf("uncertain message became claimable: messages=%+v err=%v", recoveredClaim, recoveredErr) + } +} + // TestNotificationOutboxPermanentRetry 将达到重试上限的发送失败消息标记为 dead 隔离。 func TestNotificationOutboxPermanentRetry(t *testing.T) { // store、cleanup 保存测试数据库及其关闭责任。 diff --git a/internal/db/notifications.go b/internal/db/notifications.go index a61d5ab..427b0a0 100644 --- a/internal/db/notifications.go +++ b/internal/db/notifications.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "strconv" + "strings" "time" ) @@ -36,9 +37,14 @@ func (n *Notifications) OwnsChannel(ctx context.Context, channelID, userID int64 // NotificationOutboxInput 保存通知OutboxInput,供当前处理流程使用 type NotificationOutboxInput struct { + // ChannelID 是接收本次通知的渠道主键;幂等约束以渠道为粒度,避免一个渠道的重复入队影响其他渠道。 ChannelID int64 + // EventType 是通知类别,仅用于渠道订阅过滤和运维分类,不携带业务正文。 EventType string - Body string + // Body 是 worker 投递给外部渠道的格式化正文,只能留在 outbox 内部处理流程。 + Body string + // IdempotencyKey 是可选的业务投递键;非空时同一渠道只保留一条该键对应的记录,包括 uncertain 隔离记录。 + IdempotencyKey string } // NotificationOutboxMessage 保存通知Outbox消息,供当前处理流程使用 @@ -271,6 +277,8 @@ func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([ } // EnqueueOutbox 在一个事务中持久化同一事件的各渠道投递,避免进程退出造成部分丢失。 +// IdempotencyKey 非空时,(channel_id,idempotency_key) 唯一约束会忽略重复入队;这样 uncertain +// 消息不会因业务运行恢复而重新变为 pending,外部投递成功但本地确认失败时不会自动重发。 func (n *Notifications) EnqueueOutbox(ctx context.Context, messages []NotificationOutboxInput) error { if len(messages) == 0 { return nil @@ -281,19 +289,33 @@ func (n *Notifications) EnqueueOutbox(ctx context.Context, messages []Notificati return err } defer tx.Rollback() - // message 表示当前遍历过程中的消息 + // insertSQL 使用方言一致的冲突忽略语义,只把同一渠道的相同业务投递键视为重复。 + insertSQL := dialectInsertIgnorePrefix(n.Dialect) + ` INTO notification_outbox + (channel_id,event_type,body,idempotency_key,status,attempt_count,next_attempt_at,lease_expires_at,worker_token,last_error) + VALUES (?,?,?,?, 'pending',0,0,0,'','')` + dialectInsertIgnore(n.Dialect, []string{"channel_id", "idempotency_key"}) + // message 表示当前事务中待写入的单渠道通知。 for _, message := range messages { + // idempotencyKey 将空字符串转换为 NULL,使未指定业务幂等键的历史通知保持可重复发送语义。 + idempotencyKey := nullableOutboxIdempotencyKey(message.IdempotencyKey) if // err 保存err,供当前处理流程使用 - _, err := tx.ExecContext(ctx, `INSERT INTO notification_outbox - (channel_id,event_type,body,status,attempt_count,next_attempt_at,lease_expires_at,worker_token,last_error) - VALUES (?,?,?,'pending',0,0,0,'','')`, - message.ChannelID, message.EventType, message.Body); err != nil { + _, err := tx.ExecContext(ctx, insertSQL, message.ChannelID, message.EventType, message.Body, idempotencyKey); err != nil { return err } } return tx.Commit() } +// nullableOutboxIdempotencyKey 将未声明幂等语义的空键写为 SQL NULL。 +// SQL 唯一索引允许多个 NULL,因此普通账号告警和手动通知不会被错误去重。 +func nullableOutboxIdempotencyKey(key string) any { + // trimmedKey 是移除无意义空白后的业务投递键;调用方只能用稳定键触发持久化去重。 + trimmedKey := strings.TrimSpace(key) + if trimmedKey == "" { + return nil + } + return trimmedKey +} + // ClaimOutbox 原子领取到期投递。过期 running 任务可以被重新接管,worker token // 用于隔离迟到的旧 worker。 // ClaimOutbox 负责ClaimOutbox相关处理。 diff --git a/internal/engine/account.go b/internal/engine/account.go index 0a3bce2..67f9dd0 100644 --- a/internal/engine/account.go +++ b/internal/engine/account.go @@ -8,18 +8,15 @@ package engine import ( "context" "crypto/rand" - "crypto/sha256" "errors" "fmt" "log/slog" "math/big" "strings" - "sync" "time" "xianyu-go/internal/automation" "xianyu-go/internal/db" - "xianyu-go/internal/logsafe" "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/mtop" "xianyu-go/internal/xianyu/protocol" @@ -194,28 +191,10 @@ const ( type Account struct { // CookieID 是账号在数据库中的稳定标识。 CookieID string - // credentialState 独立保护 Cookie、Token、设备指纹和刷新状态。 - credentialState - - // accountRuntimeState 独立保护连接状态、失败计数和离线告警状态。 - accountRuntimeState - // lifecycle 独立保护业务任务接入、取消和等待语义。 - lifecycle accountLifecycle - // messageDispatcher 独立保护消息去重、防抖和并发投递状态。 - messageDispatcher - - store *db.Store - mtop mtop.Client - renewer cookieRenewer - wsDialer WSDialer - handler Handler - logger *slog.Logger - - reply *ReplyService - // recorder 管理 WebSocket 报文记录 worker 的队列和等待。 - recorder *wsRecorder - - pendingRenewWG sync.WaitGroup + // accountRuntimeComponents 统一拥有该账号的可变运行状态与任务生命周期。 + accountRuntimeComponents + // accountDependencies 固定该账号运行时使用的基础设施和业务端口。 + accountDependencies } // debounceEntry 保存debounceEntry,供当前处理流程使用 @@ -315,28 +294,26 @@ func New(cfg Config) *Account { if wsDialer == nil { wsDialer = defaultDialer{} } - // a 保存a,供当前处理流程使用 + // a 保存已经完成依赖快照和状态组件装配的账号 facade。 a := &Account{ - CookieID: cfg.CookieID, - store: cfg.Store, - mtop: mtopClient, - renewer: renewer, - wsDialer: wsDialer, - handler: cfg.Handler, - logger: logger.With("account", cfg.CookieID), - lifecycle: accountLifecycle{accepting: true}, - accountRuntimeState: accountRuntimeState{ - runtimeState: RuntimeStarting, - runtimeMessage: "正在启动账号服务", - runtimeUpdatedAt: time.Now(), - }, - recorder: newWSRecorder(cfg.Store, cfg.CookieID, logger), - credentialState: credentialState{ - CookieStr: cfg.CookieStr, - UserID: myid, - deviceID: protocol.GenerateDeviceID(myid), - credentialFP: credentialStateFingerprint(cfg.CookieStr, ""), + CookieID: cfg.CookieID, + accountRuntimeComponents: accountRuntimeComponents{ + lifecycle: accountLifecycle{accepting: true}, + accountRuntimeState: accountRuntimeState{ + runtimeState: RuntimeStarting, + runtimeMessage: "正在启动账号服务", + runtimeUpdatedAt: time.Now(), + }, + credentialState: credentialState{ + refreshGate: newRefreshGate(), + CookieStr: cfg.CookieStr, + UserID: myid, + deviceID: protocol.GenerateDeviceID(myid), + credentialFP: credentialStateFingerprint(cfg.CookieStr, ""), + }, + pendingRenewal: pendingRenewalCoordinator{}, }, + accountDependencies: newAccountDependencies(cfg.Store, mtopClient, renewer, wsDialer, cfg.Handler, logger.With("account", cfg.CookieID), nil, newWSRecorder(cfg.Store, cfg.CookieID, logger)), } if cfg.Store != nil { a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger) @@ -351,254 +328,20 @@ func New(cfg Config) *Account { FinishTask: a.lifecycle.finishTask, RecordMessage: a.recordMessageReceived, }) + // connection 保存绑定当前账号 facade 的连接编排组件;它只在构造完成后才可被 Run 调用。 + a.connection = connectionCoordinator{account: a} + // outgoing 保存绑定当前账号 facade 的出站消息协调器;它只读取连接快照后执行外部 I/O。 + a.outgoing = outgoingMessageCoordinator{account: a} + // credentials 保存绑定当前账号 facade 的凭证协调器;外部凭证 I/O 均由它控制锁边界。 + a.credentials = credentialCoordinator{account: a} return a } // Run 阻塞运行账号主循环,直到 ctx 取消或不可恢复错误。 // 调用方应在独立 goroutine 中运行;Stop 可优雅停止。 -// Run 执行当前值。 +// Account 只保留稳定 facade;WebSocket 拨号、注册和重连编排由 connectionCoordinator 独立拥有。 func (a *Account) Run(parent context.Context) error { - // ctx、cancel 保存ctx、cancel,供当前处理流程使用 - ctx, cancel := context.WithCancel(parent) - defer func() { - cancel() - if a.recorder != nil { - a.recorder.wait() - } - a.pendingRenewWG.Wait() - }() - a.lifecycle.start(ctx, cancel) - if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) { - a.logger.Info("账号在启动续期前已禁用") - return nil - } - a.startWSRecorder(ctx) - // 官网 /im 启动时执行 auto-login plugin;成功后 location.reload() 会重建 - // FishEngine 和页面级 device ID。Go 客户端用 HTTP 复刻续期,并在成功时 - // 只重建这一本地运行时身份。续期失败不能用网页 DOM 阻断 token + WS; - // Chromium 仅用于读取本机指纹和处理 token 滑块。 - if a.renewer != nil { - if a.tryAPIRenew(ctx) { - a.rotatePageDeviceID() - } - if ctx.Err() != nil { - return ctx.Err() - } - } - for { - if ctx.Err() != nil { - return ctx.Err() - } - // 账号是否被禁用。 - if !a.store.Cookies.GetStatus(ctx, a.CookieID) { - a.logger.Info("账号已禁用,停止主循环") - return nil - } - - // 每次新建 IM 连接前吸收数据库中的最新 Cookie。健康连接不会被续期任务 - // 主动打断;Cookie 变化只会使本次重连放弃旧 token 并重新派生。 - a.reloadCookieFromDB(ctx) - - // 官网先完成原生 WebSocket 握手,再从 authTokenCallback 获取本次 - // 连接专用 token,最后发送 /reg。 - // conn、err 保存conn、err,供当前处理流程使用 - conn, err := a.wsDialer.Dial(ctx, ws.Config{Recorder: a.wsRecorder()}, a.logger) - if err != nil { - if ctx.Err() != nil { - return ctx.Err() - } - a.logger.Error("WS 握手失败", "err", err) - if // retryErr 保存重试Err,供当前处理流程使用 - retryErr := a.handleWSConnectFailure(ctx, err); retryErr != nil { - return retryErr - } - continue - } - // The official web client calls - // mtop.taobao.idlemessage.pc.login.token from authTokenCallback for every - // loginV2/reConnect attempt. Do the same here: an access token belongs to - // one connection attempt and must never be reused for a later /reg. - // token、cookieStr、err 保存token、cookieStr、err,供当前处理流程使用 - token, cookieStr, err := a.acquireFreshConnectionToken(ctx) - if err != nil { - _ = conn.Close() - if ctx.Err() != nil { - return ctx.Err() - } - a.logger.Error("获取 token 失败", "err", err) - a.mu.Lock() - // status 保存状态,供当前处理流程使用 - status := a.lastTokenStatus - // nonCounted 保存nonCounted,供当前处理流程使用 - nonCounted := tokenFailureIsNonCounted(status) - if !nonCounted { - a.tokenFetchFailures++ - } - // tokenFailures 保存令牌Failures,供当前处理流程使用 - tokenFailures := a.tokenFetchFailures - a.mu.Unlock() - a.setRuntimeError(ctx, err) - _ = tokenFailures // 仅用于诊断;官网不会按次数永久禁用账号。 - if mtop.IsRiskVerificationErr(err) { - a.logger.Warn("闲鱼要求安全验证,停止本次消息登录", "err", err) - a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证", - "账号触发闲鱼风控验证(滑块/人脸等),需要重新登录或完成人工验证。") - return err - } - if mtop.IsSessionExpiredErr(err) { - // reason 保存原因,供当前处理流程使用 - reason := "登录凭证已失效,正在立即续期" - a.logger.Warn("token API 检测到 Session 过期,停止重试并开始即时续期", "err", err) - a.clearTokenCache(ctx) - a.setRuntimeState(RuntimeReconnecting, reason) - a.notifyOffline(ctx, reason+":"+errString(err)) - if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) { - a.reloadCookieFromDB(ctx) - a.clearCurrentToken() - a.resetFailures() - a.setRuntimeState(RuntimeConnecting, "Session 续期成功,正在重新连接") - continue - } - reason = "登录凭证已失效,自动续期失败,请重新扫码登录" - a.setRuntimeState(RuntimeAuthExpired, reason) - a.notifyOffline(ctx, reason+":"+errString(err)) - return err - } - // 网络或服务端瞬时错误不能让账号运行时永久退出。只要登录 Session - // 没有明确失效,就持续重试获取连接级 Token。 - a.setRuntimeState(RuntimeReconnecting, "获取消息凭证失败,正在重试") - a.notifyOffline(ctx, "获取消息凭证失败,正在自动重试:"+errString(err)) - if // sleepErr 保存sleepErr,供当前处理流程使用 - sleepErr := sleepCtx(ctx, a.tokenRetryDelay()); sleepErr != nil { - return sleepErr - } - continue - } - a.mu.Lock() - a.currentToken = token - a.CookieStr = cookieStr - a.tokenFetchFailures = 0 - a.mu.Unlock() - a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务") - a.logger.Info("token 刷新成功") - - // 2) 使用刚获得的 token 注册已经打开的 WS。 - a.mu.Lock() - // deviceID 保存deviceID,供当前处理流程使用 - deviceID := a.deviceID - // tokenCredentialFP 保存令牌CredentialFP,供当前处理流程使用 - tokenCredentialFP := a.tokenCredentialFP - a.mu.Unlock() - // registerResult 是凭证快照复核与 WebSocket 注册的窄边界结果。 - registerResult := a.registerConnection(ctx, conn, deviceID, token, tokenCredentialFP) - if !registerResult.Registered { - _ = conn.Close() - a.reloadCookieFromDB(ctx) - continue - } - err = registerResult.Err - if err != nil { - _ = conn.Close() - if ctx.Err() != nil { - return ctx.Err() - } - a.logger.Error("WS 注册失败", "err", err) - if // retryErr 保存重试Err,供当前处理流程使用 - retryErr := a.handleWSConnectFailure(ctx, err); retryErr != nil { - return retryErr - } - continue - } - a.runtimeMu.Lock() - a.conn = conn - a.connStartedAt = time.Now() - a.connFailures = 0 - a.networkFailures = 0 - a.authExpiredAlerted = false // 连接成功,复位 auth_expired 告警标记 - shouldRecovered := a.offlineNotified - // offlineSince 保存offlineSince,供当前处理流程使用 - offlineSince := a.offlineSince - a.offlineNotified = false - a.offlineSince = time.Time{} - a.lastOfflineReason = "" - a.runtimeMu.Unlock() - a.setRuntimeState(RuntimeOnline, "消息服务连接正常") - a.notifyTransportReady(ctx) - if shouldRecovered { - a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线", - fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince))) - } - - // 3) 健康连接维持心跳和收包,并在服务端 Token 过期前主动关闭, - // 进入下一轮连接以重新调用 Token API 和 /reg。 - // refreshAt 和 expiresAt 是本次连接 Token 的轮换时间与服务端过期时间快照。 - a.mu.Lock() - // refreshAt 保存refreshAt,供当前处理流程使用 - refreshAt := a.tokenRefreshAt - // expiresAt 保存expiresAt,供当前处理流程使用 - expiresAt := a.tokenExpiresAt - a.mu.Unlock() - // session 是本次已注册连接的心跳、接收和 Token 轮换收束结果。 - session := a.runConnectionSession(ctx, conn, refreshAt) - if ctx.Err() != nil { - return ctx.Err() - } - - // 连接结束:只有认证类失败才清 token。已经建立后的网络断线继续 - // 使用内存 token 与数据库缓存,避免无意义调用 Token API。 - if session.Rotated { - a.logger.Info("WS Token 到达提前轮换时间,正在重新获取 Token", "expires_at", expiresAt, "remaining", time.Until(expiresAt).Round(time.Second)) - a.clearConnectionToken(ctx) - a.setRuntimeState(RuntimeReconnecting, "WS Token 即将到期,正在主动轮换") - continue - } - if ws.IsConnectLimitError(session.ReceiveErr) { - a.clearConnectionToken(ctx) - // reason 保存原因,供当前处理流程使用 - reason := "消息会话已被服务端移除" - a.setRuntimeState(RuntimeAuthExpired, reason) - a.notifyOffline(ctx, reason) - return nil - } - if ws.IsAuthenticationError(session.ReceiveErr) { - // 官网把 /push/kickout 转成 UNCONNECTED,页面监听器随后立即 - // reConnect,并由 authTokenCallback 获取新的连接凭证。 - a.clearConnectionToken(ctx) - a.setRuntimeState(RuntimeReconnecting, "消息会话被服务端踢下线,正在重新连接") - continue - } - // 心跳失败会先关闭连接,ReceiveLoop 往往只观察到 context canceled。 - // 官网以心跳 Promise 的 reject 为真实断线原因并立即 reConnect。 - // receiveErr 是后续错误分类使用的本地副本;心跳错误优先于 context canceled。 - // receiveErr 保存receiveErr,供当前处理流程使用 - receiveErr := session.ReceiveErr - if session.HeartbeatErr != nil && !errors.Is(session.HeartbeatErr, context.Canceled) && - (receiveErr == nil || errors.Is(receiveErr, context.Canceled)) { - receiveErr = session.HeartbeatErr - } - - // 正常 close 的 async-for 会直接进入下一轮,不计任何失败。 - if receiveErr == nil { - a.clearConnectionToken(ctx) - a.setRuntimeState(RuntimeReconnecting, "消息连接已结束,正在重新连接") - continue - } - - if isEstablishedNetworkError(receiveErr) || errors.Is(receiveErr, context.Canceled) { - a.clearConnectionToken(ctx) - a.setRuntimeState(RuntimeReconnecting, "网络连接已断开,正在重新连接") - a.logger.Warn("WS 网络连接结束", "err", receiveErr, "connected_duration", session.ConnectedDuration.Round(time.Second), "heartbeat_err", session.HeartbeatErr) - // 官网当前页面在 CONN_UNCONNECTED 事件后立即调用 reConnect。 - continue - } - - // 其他已经建立后的非认证错误同样进入 UNCONNECTED;不升级为 - // 密码登录、指数退避或永久禁用。 - a.clearConnectionToken(ctx) - a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,正在重新连接") - a.logger.Warn("WS 连接结束", "err", receiveErr, "heartbeat_err", session.HeartbeatErr) - continue - } + return a.connection.run(parent) } // wsRecorder 返回供 WebSocket 连接记录报文的非阻塞回调。 @@ -647,7 +390,10 @@ func (a *Account) clearConnectionToken(ctx context.Context) { // Stop 优雅停止并兼容不需要错误返回值的旧调用方。 func (a *Account) Stop() { - _ = a.StopContext(context.Background()) + // stopCtx、stopCancel 为旧 Stop 入口提供有限的 Join 预算,避免不响应取消的外部实现永久阻塞调用方。 + stopCtx, stopCancel := context.WithTimeout(context.Background(), connectionShutdownJoinTimeout) + defer stopCancel() + _ = a.StopContext(stopCtx) } // StopContext 在 ctx 约束内停止账号,并等待已登记任务完成。 @@ -704,22 +450,11 @@ func (a *Account) handleMaxFailures(ctx context.Context) error { a.resetFailures() return sleepCtx(ctx, 2*time.Second) } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := func() {} - // credentialLocked 标识当前调用是否持有账号凭证锁。 - credentialLocked := false - if a.store != nil { - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - credentialLocked = true - } - defer func() { - if credentialLocked { - credentialUnlock() - } - }() a.logger.Warn("连续失败达上限,触发 Go 协议续期", "failures", MaxConnectionFailures) a.notifyRecoveringOffline(ctx, fmt.Sprintf("消息服务连续认证/连接失败 %d 次,开始自动恢复", MaxConnectionFailures)) - if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) { + // passwordRefreshResult 保存外部凭证恢复调用结果;恢复调用不得持有账号凭证锁。 + passwordRefreshResult := a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) + if passwordRefreshResult { if cookieValue, err := a.store.Cookies.GetValue(ctx, a.CookieID); err == nil && cookieValue != "" { // cookieValue 是恢复回调刚写入的 Cookie 明文。 a.replaceCookieStr(cookieValue) a.clearCurrentToken() @@ -817,441 +552,6 @@ func formatTimeOrUnknown(t time.Time) string { return t.Format("2006-01-02 15:04:05") } -// tryLoginStatusCheck 调用 mtop.taobao.idlemessage.pc.loginuser.get 做轻量登录态确认。 -// 这个接口的成本低于完整 token 刷新,且可能顺手下发新的签名 Cookie; -// 因此在 session 失效后、接口续期前先跑一遍,避免已实现的登录态检查能力闲置。 -// tryLoginStatusCheck 负责try登录状态Check相关处理。 -func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResult { - // checker、ok 保存checker、ok,供当前处理流程使用 - checker, ok := a.mtop.(loginStatusChecker) - if !ok { - return loginStatusCheckResult{} - } - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := func() {} - // credentialLocked 标识当前调用是否持有账号凭证锁。 - credentialLocked := false - if a.store != nil { - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - credentialLocked = true - } - defer func() { - if credentialLocked { - credentialUnlock() - } - }() - a.mu.Lock() - // cookieStr 保存登录凭证Str,供当前处理流程使用 - cookieStr := a.CookieStr - a.mu.Unlock() - // requestCtx 保存请求Ctx,供当前处理流程使用 - requestCtx := ctx - // cookieSession 保存登录凭证会话,供当前处理流程使用 - var cookieSession *mtop.CookieSession - // metadataJSON 保存metadataJSON,供当前处理流程使用 - metadataJSON := "" - if a.store != nil && a.store.Cookies != nil { - runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含登录态检查所需的 Cookie 与 metadata。 - if detailErr != nil { - a.logger.Warn("登录态检查前读取最新 Cookie 失败", "err", detailErr) - return loginStatusCheckResult{} - } - cookieStr = runtimeData.Value - metadataJSON = runtimeData.MetadataJSON - // runtimeData 已在凭证锁内读取,下面只负责根据 metadata 建立 Cookie 会话。 - // metadataJSON 保留完整 Jar 信息,不能退化为仅使用扁平 Cookie。 - // snapshot 分支继续沿用登录态检查原有的请求作用域和持久化顺序。 - if // snapshot、complete 保存snapshot、complete,供当前处理流程使用 - snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete { - requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot) - } else { - requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr) - } - } - // 登录态检查只使用当前凭证快照;慢速外部调用不得持有共享账号锁。 - if credentialLocked { - credentialUnlock() - credentialLocked = false - } - // res、err 保存res、err,供当前处理流程使用 - res, err := checker.CheckLoginStatusContext(requestCtx, cookieStr) - if a.store != nil && a.store.Cookies != nil { - // credentialUnlock 保存外部检查完成后重新进入提交临界区的释放函数。 - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - credentialLocked = true - // latestRuntimeData 和 reloadErr 保存外部检查完成后的最新凭证视图及重读错误。 - latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) - if reloadErr != nil { - a.logger.Warn("登录态检查完成后读取最新 Cookie 失败", "err", reloadErr) - return loginStatusCheckResult{} - } - // credentialSnapshotChanged 表示外部检查期间已有其他流程更新 Cookie 或 metadata。 - credentialSnapshotChanged := latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON - cookieStr = latestRuntimeData.Value - metadataJSON = latestRuntimeData.MetadataJSON - if credentialSnapshotChanged { - // 外部响应基于旧快照,当前切片不具备可安全重放的 Cookie 集合,因此丢弃旧响应状态。 - cookieSession = nil - if res != nil { - res.UpdatedCookies = cookieStr - } - } - } - if cookieSession != nil { - // value、snapshot、changed 保存value、snapshot、changed,供当前处理流程使用 - value, snapshot, changed := cookieSession.State() - if changed { - // metadata 保存metadata,供当前处理流程使用 - metadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON) - if snapshot != nil { - metadata = cookierefresh.MetadataWithSnapshot(metadataJSON, snapshot) - } - if // persistErr 保存persistErr,供当前处理流程使用 - persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, value, metadata, time.Now().Unix()); persistErr != nil { - a.logger.Warn("登录态检查保存响应 Cookie Jar 失败", "err", persistErr) - return loginStatusCheckResult{} - } - a.replaceCredentialState(value, credentialStateFingerprint(value, metadata)) - a.clearTokenCache(ctx) - a.notifyCredentialUpdated(ctx) - if err != nil { - a.logger.Warn("登录态检查失败,已保存响应 Cookie", "err", err) - } - return loginStatusCheckResult{recovered: res != nil && res.Status == mtop.LoginStatusTokenRefreshed} - } - } - if err != nil { - a.logger.Warn("登录态检查失败", "err", err) - return loginStatusCheckResult{} - } - if res == nil { - return loginStatusCheckResult{} - } - if res.Status == mtop.LoginStatusRiskRequired { - a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证") - a.logger.Warn("登录态检查命中风控验证", "ret", strings.Join(res.Ret, ","), "verification_url", logsafe.URL(res.VerificationURL)) - return loginStatusCheckResult{riskRequired: true, verificationURL: res.VerificationURL} - } - if res.Status == mtop.LoginStatusTokenRefreshed && len(cookierefresh.ChangedCookieNames(cookieStr, res.UpdatedCookies)) > 0 && a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") { - a.logger.Info("登录态检查刷新了 Cookie", "status", res.Status, "message", res.Message) - return loginStatusCheckResult{recovered: true} - } - a.logger.Info("登录态检查未产生可用 Cookie 更新", "status", res.Status, "message", res.Message) - return loginStatusCheckResult{} -} - -// tryAPIRenew 是密码登录前的轻量恢复层,只执行官网 auto-login plugin 的 -// 单次 silentHasLogin 流程。如果只拿到部分 Cookie,仍先保存并清 token, -// 但继续按 Go 协议执行后续恢复;仍失败时由上层要求重新扫码登录。 -// tryAPIRenew 负责tryAPIRenew相关处理。 -func (a *Account) tryAPIRenew(ctx context.Context) bool { - if a.renewer == nil { - return false - } - // renewed 保存renewed,供当前处理流程使用 - renewed, _ := a.tryAPIRenewUsing(ctx, func(runCtx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*renew.Result, error) { - return a.renewer.RenewAPIFirst(runCtx, cookieStr, snapshot) - }) - return renewed -} - -// tryAPIRenewUsing 负责tryAPIRenewUsing相关处理。 -func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Context, string, []cookierefresh.BrowserCookie) (*renew.Result, error)) (bool, error) { - a.refreshMu.Lock() - defer a.refreshMu.Unlock() - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := func() {} - // credentialLocked 标识当前调用是否持有账号凭证锁。 - credentialLocked := false - if a.store != nil { - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - credentialLocked = true - } - defer func() { - if credentialLocked { - credentialUnlock() - } - }() - if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) { - return false, nil - } - a.mu.Lock() - // cookieStr 保存登录凭证Str,供当前处理流程使用 - cookieStr := a.CookieStr - a.mu.Unlock() - // snapshot 保存snapshot,供当前处理流程使用 - var snapshot []cookierefresh.BrowserCookie - // metadataJSON 保存用于续期请求和提交比较的 Cookie metadata。 - metadataJSON := "" - if a.store != nil && a.store.Cookies != nil { - runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含接口续期所需的 Cookie 与 metadata。 - if detailErr != nil { - a.logger.Warn("接口续期前读取最新 Cookie 失败", "err", detailErr) - return false, detailErr - } - if runtimeData.Value != cookieStr { - cookieStr = runtimeData.Value - a.replaceCookieStr(cookieStr) - a.clearCurrentToken() - a.clearTokenCache(ctx) - } - metadataJSON = runtimeData.MetadataJSON - snapshot = cookierefresh.SnapshotFromMetadata(runtimeData.MetadataJSON) - // runtimeData 的 Cookie 用于续期请求,metadata 用于恢复浏览器 Cookie 快照。 - // 读取窄模型不会触碰登录用户名、密码等无关凭证字段。 - // API 续期仍沿用原有锁、Cookie 比较和 token 清理顺序。 - } - // API 续期只使用当前凭证快照;慢速外部续期回调不得持有共享账号锁。 - if credentialLocked { - credentialUnlock() - credentialLocked = false - } - // res、err 保存res、err,供当前处理流程使用 - res, err := call(ctx, cookieStr, snapshot) - // responseMetadataOverride 保存并发更新期间重放响应 Cookie 后的 metadata。 - responseMetadataOverride := "" - // responseMetadataOverridden 表示本次响应已经基于最新凭证快照重放。 - responseMetadataOverridden := false - if a.store != nil && a.store.Cookies != nil { - // credentialUnlock 保存外部续期完成后重新进入提交临界区的释放函数。 - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - credentialLocked = true - // latestRuntimeData 和 reloadErr 保存外部续期完成后的最新凭证视图及重读错误。 - latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) - if reloadErr != nil { - a.logger.Warn("接口续期完成后读取最新 Cookie 失败", "err", reloadErr) - return false, reloadErr - } - // credentialSnapshotChanged 表示外部续期期间已有其他流程更新 Cookie 或 metadata。 - credentialSnapshotChanged := latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON - cookieStr = latestRuntimeData.Value - metadataJSON = latestRuntimeData.MetadataJSON - if res != nil && credentialSnapshotChanged { - if len(res.SetCookies) > 0 { - // rebasedCookies、rebasedMetadata 保存基于最新快照重放 Set-Cookie 的结果。 - rebasedCookies, rebasedMetadata, _ := renew.RebaseResponseCookies(cookieStr, metadataJSON, res) - res.NewCookies = rebasedCookies - res.CookieSnapshot = nil - res.CookieSnapshotComplete = false - responseMetadataOverride = rebasedMetadata - responseMetadataOverridden = true - } else { - // 没有可重放的 Set-Cookie 时,拒绝把旧请求计算出的状态写回。 - res.NewCookies = cookieStr - res.CookieSnapshot = nil - res.CookieSnapshotComplete = false - } - } - } - if res == nil { - if err != nil { - a.logger.Warn("接口续期失败", "err", err) - } - return false, err - } - if res.HasPending() { - a.watchPendingAPIRenew(ctx, res) - } - // updated 保存updated,供当前处理流程使用 - updated := false - // persisted 保存persisted,供当前处理流程使用 - persisted := false - if responseMetadataOverridden && a.store != nil && a.store.Cookies != nil { - // err 保存并发重放结果写回错误。 - if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.NewCookies, responseMetadataOverride, time.Now().Unix()); err != nil { - a.logger.Warn("保存并发重放后的续期 Cookie 失败", "err", err) - return false, err - } - persisted = true - } else if res.CookieSnapshotComplete && a.store != nil && a.store.Cookies != nil { - runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含续期快照持久化所需字段。 - // 快照持久化只依赖 metadata,Cookie 明文由续期响应直接提供。 - // 保留统一运行时查询模型,避免为相同凭证路径恢复完整账号详情。 - // 下面的更新操作和错误处理保持原有续期语义不变。 - if detailErr != nil { - a.logger.Warn("保存续期 Cookie 快照失败", "err", detailErr) - return false, detailErr - } - // metadata 保存metadata,供当前处理流程使用 - metadata := cookierefresh.MetadataWithSnapshot(runtimeData.MetadataJSON, res.CookieSnapshot) - if // err 保存err,供当前处理流程使用 - err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.NewCookies, metadata, time.Now().Unix()); err != nil { - a.logger.Warn("保存续期 Cookie 快照失败", "err", err) - return false, err - } - persisted = true - } else if len(res.SetCookies) > 0 && a.store != nil && a.store.Cookies != nil { - if // err 保存err,供当前处理流程使用 - err := a.persistRenewFlatCookie(ctx, res.NewCookies); err != nil { - a.logger.Warn("保存接口续期扁平 Cookie 失败", "err", err) - return false, err - } - persisted = true - } - // credentialChanged 保存credentialChanged,供当前处理流程使用 - credentialChanged := res.NewCookies != cookieStr && (res.CookieSnapshotComplete || len(res.SetCookies) > 0 || res.NewCookies != "") - if credentialChanged { - if persisted || a.store == nil || a.store.Cookies == nil { - a.replaceCookieStr(res.NewCookies) - a.clearCurrentToken() - a.clearTokenCache(ctx) - a.setRuntimeState(RuntimeConnecting, "接口续期已更新登录凭证,正在重新连接") - updated = true - } else { - updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期") - } - if updated && persisted { - a.notifyCredentialUpdated(ctx) - } - } - if err != nil { - a.logger.Warn("接口续期失败,已保存响应 Cookie", "err", err) - return false, err - } - if res.Success { - if !updated { - a.setRuntimeState(RuntimeConnecting, "登录凭证已接口续期,正在重新连接") - } - a.logger.Info("接口续期成功", "method", res.RenewMethod, "updated", strings.Join(res.UpdatedCookieNames, ",")) - return true, nil - } - if updated { - a.logger.Info("接口续期返回部分 Cookie 更新,继续降级恢复", "updated", strings.Join(res.UpdatedCookieNames, ",")) - return false, nil - } - a.logger.Info("接口续期未产生可用恢复", "success", res.Success, "message", res.Message) - return false, nil -} - -// persistRenewFlatCookie 负责persistRenewFlat登录凭证相关处理。 -func (a *Account) persistRenewFlatCookie(ctx context.Context, newCookies string) error { - if a.store == nil || a.store.Cookies == nil { - return nil - } - metadata, err := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID) // metadata 只包含扁平 Cookie 写回所需的快照信息。 - if err != nil { - return err - } - // 该流程不需要读取现有 Cookie 明文或登录秘密。 - // metadata 已在 repository 层按账号作用域解密,下面只清理旧快照。 - // 更新操作继续由 UpdateRenewalCookie 负责加密和账号存在性校验。 - // 没有权威 Jar 时,接口 Set-Cookie 只能更新兼容扁平值。不能把 - // Domain/Path/HttpOnly/PartitionKey 均未知的 Cookie 伪造成完整快照。 - metadata = cookierefresh.MetadataWithoutSnapshot(metadata) - return a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()) -} - -// watchPendingAPIRenew 负责watchPendingAPIRenew相关处理。 -func (a *Account) watchPendingAPIRenew(parent context.Context, result *renew.Result) { - if result == nil || !result.HasPending() { - return - } - // taskCtx 是迟到续期任务继承的账号生命周期上下文;Stop 会先取消它,再等待任务收束。 - taskCtx, accepted := a.beginTask() - if !accepted { - return - } - if parent != nil { - // Run 传入的 parent 就是账号运行上下文;直接沿用它可同时响应调用方取消和 Stop 的取消。 - taskCtx = parent - } - a.pendingRenewWG.Add(1) - go func() { - defer a.lifecycle.finishTask() - defer a.pendingRenewWG.Done() - // ctx、cancel 保存ctx、cancel,供当前处理流程使用 - ctx, cancel := context.WithTimeout(taskCtx, 35*time.Second) - defer cancel() - // late、waitErr 保存late、waitErr,供当前处理流程使用 - late, waitErr := result.AwaitPending(ctx) - if late == nil { - if waitErr != nil { - a.logger.Warn("等待静默续期底层响应失败", "err", waitErr) - } - return - } - if // persistErr 保存persistErr,供当前处理流程使用 - persistErr := a.persistPendingRenewCookies(ctx, late); persistErr != nil { - a.logger.Warn("保存静默续期迟到 Cookie 失败", "err", persistErr) - return - } - if waitErr != nil { - a.logger.Warn("静默续期底层响应失败,已保存响应 Cookie", "err", waitErr) - } - }() -} - -// persistPendingRenewCookies 负责persistPendingRenewCookies相关处理。 -func (a *Account) persistPendingRenewCookies(ctx context.Context, result *renew.Result) error { - if result == nil || len(result.SetCookies) == 0 || a.store == nil || a.store.Cookies == nil { - return nil - } - a.refreshMu.Lock() - defer a.refreshMu.Unlock() - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := a.store.LockAccountCredentials(a.CookieID) - defer credentialUnlock() - runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含迟到续期合并所需的 Cookie 与 metadata。 - if err != nil { - return err - } - // runtimeData 已在凭证锁内读取,避免迟到响应覆盖并发写入的最新凭证状态。 - // RebaseResponseCookies 继续根据当前 Cookie 与 metadata 重放 Set-Cookie。 - // 下面的 UpdateRenewalCookie、运行时状态和通知顺序保持原有行为。 - // newCookies、metadata、changed 保存newCookies、metadata、changed,供当前处理流程使用 - newCookies, metadata, changed := renew.RebaseResponseCookies(runtimeData.Value, runtimeData.MetadataJSON, result) - if !changed { - return nil - } - if // err 保存err,供当前处理流程使用 - err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()); err != nil { - return err - } - a.replaceCredentialState(newCookies, credentialStateFingerprint(newCookies, metadata)) - a.clearTokenCache(ctx) - a.notifyCredentialUpdated(ctx) - a.logger.Info("已异步接收官网静默续期迟到 Cookie", "updated", strings.Join(result.UpdatedCookieNames, ",")) - return nil -} - -// adoptRecoveredCookie 统一接收“轻量检查/接口续期”拿到的新 Cookie。 -// 官网页面在普通 Set-Cookie 更新后保持当前 FishEngine/device ID 与健康 WS; -// 下一次重连才使用新 Cookie 获取新的连接级 accessToken。 -// adoptRecoveredCookie 负责adoptRecovered登录凭证相关处理。 -func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source string) bool { - if strings.TrimSpace(newCookies) == "" { - return false - } - a.mu.Lock() - // oldCookies 保存oldCookies,供当前处理流程使用 - oldCookies := a.CookieStr - a.mu.Unlock() - if newCookies == oldCookies { - return false - } - if a.store != nil && a.store.Cookies != nil { - if // err 保存err,供当前处理流程使用 - err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, newCookies); err != nil { - a.logger.Error(source+"后保存 cookie 失败", "cookie_id", a.CookieID, "err", err) - return false - } - } - a.replaceCookieStr(newCookies) - a.clearCurrentToken() - a.clearTokenCache(ctx) - a.setRuntimeState(RuntimeConnecting, source+"已更新登录凭证,正在重新连接") - a.notifyCredentialUpdated(ctx) - return true -} - -// notifyCredentialUpdated 负责notifyCredentialUpdated相关处理。 -func (a *Account) notifyCredentialUpdated(ctx context.Context) { - if // handler、ok 保存handler、ok,供当前处理流程使用 - handler, ok := a.handler.(credentialUpdateHandler); ok { - handler.OnCredentialUpdated(ctx, a.CookieID) - } -} - // retryDelay 按错误类型计算退避,并加入 0-30% 抖动。 // 多账号同时断线时,纯固定退避会让所有账号在同一秒重连,容易形成重连风暴。 // retryDelay 负责重试延迟相关处理。 @@ -1365,305 +665,6 @@ func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool { return len(a.shortDisconnects) >= FrequentDisconnectLimit } -// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。 -// 成功时记录 token 的服务端过期时间并保持 device_id 持久化,但连接流程 -// 不会复用该 token;下一次 loginV2/reConnect 仍会重新调用本方法。 -// refreshToken 负责refresh令牌相关处理。 -func (a *Account) refreshToken(ctx context.Context) (string, string, error) { - return a.refreshTokenWithMinGap(ctx, false) -} - -// refreshTokenWithMinGap 保留旧签名以避免影响调用方;参考实现没有额外的一分钟 -// Token 防抖,因此 enforceMinGap 不参与行为。 -// refreshTokenWithMinGap 负责refresh令牌WithMinGap相关处理。 -func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) { - a.refreshMu.Lock() - defer a.refreshMu.Unlock() - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := func() {} - // credentialLocked 标识当前调用是否持有账号凭证锁。 - credentialLocked := false - if a.store != nil { - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - credentialLocked = true - } - defer func() { - if credentialLocked { - credentialUnlock() - } - }() - - // refreshMu serializes the complete token/Cookie update transaction for an - // account. A failed automatic verification also suppresses repeated token API - // calls until the caller-side cooldown expires. - if // remaining 保存remaining,供当前处理流程使用 - remaining := a.tokenCaptchaCooldownRemaining(); remaining > 0 { - a.setLastTokenStatus(tokenRefreshSkippedCooldown) - return "", "", fmt.Errorf("%w,剩余 %s", errTokenCaptchaCooldown, remaining.Round(time.Second)) - } - - a.reloadCookieFromDB(ctx) - - a.mu.Lock() - // cookieStr 保存登录凭证Str,供当前处理流程使用 - cookieStr := a.CookieStr - // metadataJSON 保存当前凭证快照对应的 metadata。 - metadataJSON := "" - a.lastTokenRefresh = time.Now() - a.lastTokenStatus = tokenRefreshStarted - a.mu.Unlock() - - // deviceID 保存deviceID,供当前处理流程使用 - deviceID := strings.TrimSpace(a.deviceID) - if deviceID == "" { - if // unb 保存unb,供当前处理流程使用 - unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" { - deviceID = protocol.GenerateDeviceID(unb) - a.mu.Lock() - a.deviceID = deviceID - a.mu.Unlock() - } - } - if a.store != nil && a.store.Cookies != nil { - // runtimeData 保存 Token 请求开始前的最小凭证快照。 - runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) - if detailErr != nil { - return "", "", detailErr - } - cookieStr = runtimeData.Value - metadataJSON = runtimeData.MetadataJSON - } - // Token 网络请求和风控恢复都必须在共享凭证锁外执行。 - if credentialLocked { - credentialUnlock() - credentialLocked = false - } - for // captchaRetry 保存captcha重试,供当前处理流程使用 - captchaRetry := 0; captchaRetry < 3; captchaRetry++ { - // res 保存响应,供当前处理流程使用 - var res *mtop.RefreshResult - // err 保存err,供当前处理流程使用 - var err error - if // scoped、ok 保存scoped、ok,供当前处理流程使用 - scoped, ok := a.mtop.(scopedTokenClient); ok { - // snapshot 保存snapshot,供当前处理流程使用 - var snapshot []cookierefresh.BrowserCookie - if a.store != nil && a.store.Cookies != nil { - if metadata, metadataErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID); metadataErr == nil { // metadata 是 token 请求所需的 Cookie 快照信息。 - snapshot = cookierefresh.SnapshotFromMetadata(metadata) - } - } - res, err = scoped.RefreshTokenWithCredentialContext(ctx, cookieStr, deviceID, snapshot) - } else { - res, err = a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID) - } - if a.store != nil && a.store.Cookies != nil { - // credentialUnlock 保存 Token 响应提交临界区的释放函数。 - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - credentialLocked = true - // latestRuntimeData 和 reloadErr 保存网络请求完成后的最新凭证视图及重读错误。 - latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) - if reloadErr != nil { - a.setLastTokenStatus(tokenRefreshFailedAPI) - a.clearCurrentToken() - return "", "", reloadErr - } - if latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON { - // 并发流程已经更新凭证,丢弃旧请求的 Token 和 Cookie 响应,下一轮使用最新快照重试。 - cookieStr = latestRuntimeData.Value - metadataJSON = latestRuntimeData.MetadataJSON - credentialUnlock() - credentialLocked = false - continue - } - } - // 参考实现无论业务结果为何,都先合并响应 Set-Cookie。本地还必须先把 - // 完整 Jar 持久化成功,避免当前 /reg 成功而下次重连回滚到旧凭证。 - // persistErr 保存persistErr,供当前处理流程使用 - var persistErr error - cookieStr, persistErr = a.adoptTokenResponseCookies(ctx, cookieStr, res) - if persistErr != nil { - a.setLastTokenStatus(tokenRefreshFailedAPI) - a.clearCurrentToken() - return "", "", fmt.Errorf("保存 token 响应 Cookie: %w", persistErr) - } - if err != nil && mtop.IsRiskVerificationErr(err) { - // 风控恢复是外部调用,不能在共享凭证锁内执行。 - if credentialLocked { - credentialUnlock() - credentialLocked = false - } - if // recovered、ok 保存recovered、ok,供当前处理流程使用 - recovered, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, deviceID, err); ok { - cookieStr = recovered.UpdatedCookies - // 重取地址时即使拿到了 accessToken,参考实现也不会直接采用; - // 它会清缓存后重新走一次标准 token 请求。 - continue - } - a.markTokenCaptchaFailure() - a.setLastTokenStatus(tokenRefreshFailedCaptcha) - a.clearCurrentToken() - a.clearTokenCache(ctx) - return "", "", err - } - if err != nil { - // status 保存状态,供当前处理流程使用 - status := classifyTokenFailure(err) - a.setLastTokenStatus(status) - a.clearCurrentToken() - if status != tokenRefreshFailedNetwork && status != tokenRefreshFailedTimeout { - a.clearTokenCache(ctx) - } - return "", "", err - } - if res == nil || strings.TrimSpace(res.AccessToken) == "" { - a.setLastTokenStatus(tokenRefreshFailedAPI) - a.clearCurrentToken() - a.clearTokenCache(ctx) - return "", "", fmt.Errorf("token API 未返回结果") - } - // credentialFP、fingerprintErr 保存credentialFP、fingerprintErr,供当前处理流程使用 - credentialFP, fingerprintErr := a.databaseCredentialFingerprint(ctx, cookieStr) - if fingerprintErr != nil { - a.setLastTokenStatus(tokenRefreshFailedAPI) - a.clearCurrentToken() - a.clearTokenCache(ctx) - return "", "", fmt.Errorf("绑定 token 凭证状态: %w", fingerprintErr) - } - a.saveTokenCache(ctx, deviceID, res.AccessToken, res.AccessTokenExpireAt, credentialFP) - a.mu.Lock() - a.credentialFP = credentialFP - a.tokenCredentialFP = credentialFP - a.lastCaptchaFailure = time.Time{} - a.tokenFetchFailures = 0 - a.lastTokenStatus = tokenRefreshSuccess - a.mu.Unlock() - a.runtimeMu.Lock() - a.lastMsgReceived = time.Time{} - a.runtimeMu.Unlock() - return res.AccessToken, cookieStr, nil - } - - a.setLastTokenStatus(tokenRefreshFailedCaptcha) - a.clearCurrentToken() - a.clearTokenCache(ctx) - return "", "", fmt.Errorf("滑块验证重试次数已达上限") -} - -// clearCurrentToken 负责clearCurrent令牌相关处理。 -func (a *Account) clearCurrentToken() { - a.mu.Lock() - a.currentToken = "" - a.tokenCredentialFP = "" - a.mu.Unlock() -} - -// adoptTokenResponseCookies 负责adopt令牌响应Cookies相关处理。 -func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr string, res *mtop.RefreshResult) (string, error) { - if res == nil { - return cookieStr, nil - } - if !res.CookieSnapshotComplete && !res.CookieStateChanged && strings.TrimSpace(res.UpdatedCookies) == "" { - return cookieStr, nil - } - if !res.CookieSnapshotComplete && !res.CookieStateChanged && res.UpdatedCookies == cookieStr && len(res.CookieSnapshot) == 0 { - return cookieStr, nil - } - if a.store != nil && a.store.Cookies != nil { - metadata, detailErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID) // metadata 只包含 token 响应 Cookie 合并所需的快照信息。 - if detailErr != nil { - return cookieStr, detailErr - } - // metadata 已在 repository 层按账号作用域解密,不读取旧 Cookie 或登录秘密。 - // 下面继续根据响应类型合并已有快照,并由 UpdateRenewalCookie 统一持久化。 - // 错误返回和运行时状态更新顺序保持原有 token 响应语义。 - // 只有 token 响应本身发生变化时才进入后续快照合并逻辑。 - if res.CookieSnapshotComplete { - // snapshot 保存snapshot,供当前处理流程使用 - snapshot := cookierefresh.NormalizeSnapshot(res.CookieSnapshot) - if snapshot == nil { - snapshot = []cookierefresh.BrowserCookie{} - } - metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) - } else if // snapshot、snapshotOK 保存snapshot、snapshotOK,供当前处理流程使用 - snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(metadata); snapshotOK { - // 扁平结果不能凭空证明 Jar 完整;仅在已有权威 Jar 时按已知 - // Domain/Path 身份对值做兼容合并。 - snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies) - metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) - } else { - metadata = cookierefresh.MetadataWithoutSnapshot(metadata) - } - if // err 保存err,供当前处理流程使用 - err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil { - return cookieStr, err - } - a.replaceCredentialState(res.UpdatedCookies, credentialStateFingerprint(res.UpdatedCookies, metadata)) - a.notifyCredentialUpdated(ctx) - return res.UpdatedCookies, nil - } - if res.UpdatedCookies != cookieStr { - a.replaceCookieStr(res.UpdatedCookies) - } - return res.UpdatedCookies, nil -} - -// tryTokenCaptchaRecovery 负责try令牌CaptchaRecovery相关处理。 -func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, deviceID string, err error) (*mtop.RefreshResult, bool) { - // h、ok 保存h、ok,供当前处理流程使用 - h, ok := a.handler.(tokenCaptchaHandler) - if !ok { - return nil, false - } - // riskErr 保存riskErr,供当前处理流程使用 - var riskErr *mtop.RiskVerificationError - if !errors.As(err, &riskErr) || strings.TrimSpace(riskErr.VerificationURL) == "" { - return nil, false - } - a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求滑块验证", - "token 刷新触发闲鱼风控验证,系统将尝试自动完成滑块并合并 x5sec。") - // result、ok 保存result、ok,供当前处理流程使用 - result, ok := h.OnTokenCaptchaVerification(ctx, a.CookieID, cookieStr, riskErr.VerificationURL, deviceID) - if !ok || result == nil || strings.TrimSpace(result.UpdatedCookies) == "" { - return nil, false - } - // updatedCookies、persistErr 保存updatedCookies、persistErr,供当前处理流程使用 - updatedCookies, persistErr := a.adoptTokenResponseCookies(ctx, cookieStr, result) - if persistErr != nil { - a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", persistErr) - return nil, false - } - result.UpdatedCookies = updatedCookies - a.replaceCookieStr(updatedCookies) - a.clearTokenCache(ctx) - a.setRuntimeState(RuntimeConnecting, tokenRiskRecoveryMessage) - return result, true -} - -// markTokenCaptchaFailure 负责mark令牌CaptchaFailure相关处理。 -func (a *Account) markTokenCaptchaFailure() { - a.mu.Lock() - a.lastCaptchaFailure = time.Now() - a.mu.Unlock() -} - -// tokenCaptchaCooldownRemaining 负责令牌CaptchaCooldownRemaining相关处理。 -func (a *Account) tokenCaptchaCooldownRemaining() time.Duration { - a.mu.Lock() - // lastFailure 保存lastFailure,供当前处理流程使用 - lastFailure := a.lastCaptchaFailure - a.mu.Unlock() - if lastFailure.IsZero() { - return 0 - } - // remaining 保存remaining,供当前处理流程使用 - remaining := TokenCaptchaFailureCooldown - time.Since(lastFailure) - if remaining < 0 { - return 0 - } - return remaining -} - // acquireToken is kept for internal callers and tests, but intentionally does // not reuse the persisted accessToken. Official web reconnects always invoke // the login.token API before /reg. @@ -1688,7 +689,9 @@ func (a *Account) acquireTokenWithMinGap(ctx context.Context, _ bool) (string, s } // setLastTokenStatus 负责setLast令牌状态相关处理。 -func (a *Account) setLastTokenStatus(status string) { +func (c *credentialCoordinator) setLastTokenStatus(status string) { + // a 是本凭证协调器绑定的账号 facade,持有刷新诊断状态。 + a := c.account a.mu.Lock() a.lastTokenStatus = status a.mu.Unlock() @@ -1723,158 +726,6 @@ func tokenFailureIsNonCounted(status string) bool { } } -// saveTokenCache records the server expiry and current page-runtime identity. -// It is diagnostic state only: acquireToken never reads the accessToken back -// for a later WebSocket registration. -// saveTokenCache 负责save令牌Cache相关处理。 -func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, credentialFP string) { - if accessToken == "" { - return - } - // now 保存now,供当前处理流程使用 - now := time.Now() - // expiresAt、refreshAt 保存expiresAt、refreshAt,供当前处理流程使用 - expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now) - // tokenFP 保存令牌FP,供当前处理流程使用 - tokenFP := tokenFingerprint(accessToken) - a.mu.Lock() - // previousTokenFP 保存previous令牌FP,供当前处理流程使用 - previousTokenFP := a.tokenFingerprint - a.tokenFingerprint = tokenFP - a.tokenAcquiredAt = now - a.tokenExpiresAt = expiresAt - a.tokenRefreshAt = refreshAt - a.mu.Unlock() - a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP) - if a.store == nil || a.store.Tokens == nil { - return - } - // expireAt 保存expireAt,供当前处理流程使用 - expireAt := effectiveTokenExpireAt(serverExpireAt, now) - if expireAt == 0 { - // 服务端未给有效期时仍使用保守运行时轮换时间,但不把推测期限 - // 伪装成服务端缓存期限。 - a.logger.Warn("token API 未返回可用过期时间,使用保守轮换时间", "refresh_at", refreshAt) - a.clearTokenCache(ctx) - return - } - if // err 保存err,供当前处理流程使用 - err := a.store.Tokens.SaveBound(ctx, a.CookieID, deviceID, accessToken, expireAt, credentialFP); err != nil { - a.logger.Warn("缓存 accessToken 失败", "err", err) - } -} - -// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token, -// 同时避免日志泄露可用于 WS 注册的凭证原文。 -// tokenFingerprint 负责令牌Fingerprint相关处理。 -func tokenFingerprint(token string) string { - // sum 保存sum,供当前处理流程使用 - sum := sha256.Sum256([]byte(token)) - return fmt.Sprintf("%x", sum[:6]) -} - -// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。 -func (a *Account) clearTokenCache(ctx context.Context) { - a.mu.Lock() - a.tokenFingerprint = "" - a.mu.Unlock() - if a.store == nil || a.store.Tokens == nil { - return - } - if // err 保存err,供当前处理流程使用 - err := a.store.Tokens.Clear(ctx, a.CookieID); err != nil { - a.logger.Warn("清除 token 缓存失败", "err", err) - } -} - -// databaseCredentialFingerprint returns the complete DB credential state that -// produced cookieStr. It must be called while the account credential lock is -// held when a Store is present. -// databaseCredentialFingerprint 负责databaseCredentialFingerprint相关处理。 -func (a *Account) databaseCredentialFingerprint(ctx context.Context, cookieStr string) (string, error) { - if a.store == nil || a.store.Cookies == nil { - return credentialStateFingerprint(cookieStr, ""), nil - } - runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 token 凭证一致性校验所需的 Cookie 与 metadata。 - if err != nil { - return "", err - } - // runtimeData 已在调用方凭证锁内读取,避免校验期间混入另一笔 Cookie 更新。 - // Cookie 与 metadata 均由 repository 按账号作用域解密,登录密码不会进入此流程。 - // 后续空值判断、指纹比较和错误文案保持原有 token 绑定语义。 - // snapshotComplete 保存snapshotComplete,供当前处理流程使用 - _, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON) - if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete { - return "", fmt.Errorf("数据库 Cookie 为空且没有权威 Jar") - } - if credentialCookieFingerprint(runtimeData.Value) != credentialCookieFingerprint(cookieStr) { - return "", fmt.Errorf("token 请求期间数据库 Cookie 已变化") - } - return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON), nil -} - -// reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存。普通 Cookie -// 更新不轮换页面生命周期内的 device ID;显式登录由 Manager 重建 Account。 -// reloadCookieFromDB 负责reload登录凭证FromDB相关处理。 -func (a *Account) reloadCookieFromDB(ctx context.Context) bool { - if a.store == nil || a.store.Cookies == nil { - return false - } - runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含检测外部凭证更新所需的 Cookie 与 metadata。 - if err != nil { - return false - } - if strings.TrimSpace(runtimeData.Value) == "" { - if // complete 保存complete,供当前处理流程使用 - _, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete { - return false - } - } - // databaseFP 保存databaseFP,供当前处理流程使用 - databaseFP := credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON) - a.mu.Lock() - // currentFP 保存currentFP,供当前处理流程使用 - currentFP := a.credentialFP - if currentFP == "" { - currentFP = credentialStateFingerprint(a.CookieStr, "") - } - a.mu.Unlock() - if databaseFP == currentFP { - return false - } - a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID) - a.replaceCredentialState(runtimeData.Value, databaseFP) - a.clearCurrentToken() - a.clearTokenCache(ctx) - a.mu.Lock() - a.lastCaptchaFailure = time.Time{} - a.mu.Unlock() - return true -} - -// cookieSnapshotMatchesDB 负责登录凭证SnapshotMatchesDB相关处理。 -func (a *Account) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string) bool { - if a.store == nil || a.store.Cookies == nil { - return true - } - runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 WS 注册前凭证一致性校验所需的 Cookie 与 metadata。 - if err != nil { - a.logger.Warn("WS 注册前读取最新 Cookie 失败,放弃本次连接", "err", err) - return false - } - // snapshotComplete 保存snapshotComplete,供当前处理流程使用 - _, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON) - if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete { - a.logger.Warn("WS 注册前最新 Cookie 为空且没有权威 Jar,放弃本次连接") - return false - } - if expectedFP == "" { - a.logger.Warn("WS 注册 token 缺少绑定的凭证状态,放弃本次连接") - return false - } - return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON) == expectedFP -} - // RuntimeStatus 返回账号当前连接状态的线程安全快照。 func (a *Account) RuntimeStatus() RuntimeStatus { a.runtimeMu.Lock() @@ -1984,76 +835,12 @@ func (a *Account) setRuntimeError(ctx context.Context, err error) { // SendText 通过当前 WebSocket 给买家发送文本消息。 func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) error { - text = strings.TrimSpace(text) - if text == "" { - return nil - } - // conn、myID、err 保存conn、myID、err,供当前处理流程使用 - conn, myID, err := a.currentSenderState() - if err != nil { - return err - } - // sendCtx、cancel 保存sendCtx、cancel,供当前处理流程使用 - sendCtx, cancel := context.WithTimeout(ctx, 5*time.Second) - defer cancel() - if // err 保存err,供当前处理流程使用 - err := conn.SendText(sendCtx, myID, chatID, toUserID, text); err != nil { - return err - } - if // observer、ok 保存observer、ok,供当前处理流程使用 - observer, ok := a.handler.(outgoingChatHandler); ok { - // key 保存key,供当前处理流程使用 - key, _ := ctx.Value(outgoingMessageKeyContextKey{}).(string) - if // err 保存err,供当前处理流程使用 - err := observer.HandleOutgoingChatMessage(ctx, OutgoingChatMessage{ - AccountID: a.CookieID, ChatID: chatID, BuyerID: toUserID, Text: text, MessageKey: key, - }); err != nil { - a.logger.Warn("保存出站聊天旁路失败", "account", a.CookieID, "chat_id", chatID, "err", err) - } - } - return nil + return a.outgoing.sendText(ctx, chatID, toUserID, text) } // SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。 func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error { - imageURL = strings.TrimSpace(imageURL) - if imageURL == "" { - return nil - } - if strings.HasPrefix(imageURL, "/static/") || strings.HasPrefix(imageURL, "static/") { - return fmt.Errorf("当前运行时暂不支持本地图片自动上传到闲鱼 CDN: %s", imageURL) - } - // conn、myID、err 保存conn、myID、err,供当前处理流程使用 - conn, myID, err := a.currentSenderState() - if err != nil { - return err - } - // sendCtx、cancel 保存sendCtx、cancel,供当前处理流程使用 - sendCtx, cancel := context.WithTimeout(ctx, 8*time.Second) - defer cancel() - return conn.SendImage(sendCtx, myID, chatID, toUserID, imageURL, 800, 600) -} - -// currentSenderState 负责currentSender状态相关处理。 -func (a *Account) currentSenderState() (WSConn, string, error) { - a.runtimeMu.Lock() - // conn 是当前连接快照;后续读取账号身份字段使用 Account 自身的凭证锁。 - conn := a.conn - a.runtimeMu.Unlock() - if conn == nil { - return nil, "", fmt.Errorf("%w: 账号 %s 当前没有可用 WebSocket 连接", automation.ErrMessageNotSent, a.CookieID) - } - a.mu.Lock() - defer a.mu.Unlock() - // myID 保存myID,供当前处理流程使用 - myID := strings.TrimSpace(a.UserID) - if myID == "" { - myID = protocol.TransCookies(a.CookieStr)["unb"] - } - if myID == "" { - return nil, "", fmt.Errorf("%w: 账号 %s 缺少 unb,无法发送消息", automation.ErrMessageNotSent, a.CookieID) - } - return conn, myID, nil + return a.outgoing.sendImage(ctx, chatID, toUserID, imageURL, cardID) } // FetchChatHistory reuses the account's registered IM connection. Keeping this @@ -2061,64 +848,17 @@ func (a *Account) currentSenderState() (WSConn, string, error) { // implement history retrieval. // FetchChatHistory 负责Fetch聊天History相关处理。 func (a *Account) FetchChatHistory(ctx context.Context, chatID string, cursor int64, limit int) (map[string]any, string, error) { - // conn、myID、err 保存conn、myID、err,供当前处理流程使用 - conn, myID, err := a.currentSenderState() - if err != nil { - return nil, "", err - } - // history、ok 保存history、ok,供当前处理流程使用 - history, ok := conn.(interface { - ListUserMessages(context.Context, string, int64, int) (map[string]any, error) - }) - if !ok { - return nil, "", errors.New("当前 WebSocket 连接不支持聊天历史") - } - // body、err 保存body、err,供当前处理流程使用 - body, err := history.ListUserMessages(ctx, chatID, cursor, limit) - return body, myID, err + return a.outgoing.fetchChatHistory(ctx, chatID, cursor, limit) } // FetchChatConversations 负责Fetch聊天Conversations相关处理。 func (a *Account) FetchChatConversations(ctx context.Context, cursor int64, limit int) (map[string]any, string, error) { - // conn、myID、err 保存conn、myID、err,供当前处理流程使用 - conn, myID, err := a.currentSenderState() - if err != nil { - return nil, "", err - } - // fetcher、ok 保存fetcher、ok,供当前处理流程使用 - fetcher, ok := conn.(interface { - ListConversations(context.Context, int64, int) (map[string]any, error) - }) - if !ok { - return nil, "", errors.New("当前 WebSocket 连接不支持历史会话") - } - // body、err 保存body、err,供当前处理流程使用 - body, err := fetcher.ListConversations(ctx, cursor, limit) - return body, myID, err + return a.outgoing.fetchChatConversations(ctx, cursor, limit) } // AutomationReady 报告自动化消息是否可以立即使用当前 WS 连接发送。 func (a *Account) AutomationReady() bool { - a.runtimeMu.Lock() - defer a.runtimeMu.Unlock() - return a.conn != nil && a.runtimeState == RuntimeOnline -} - -// replaceCookieStr 负责replace登录凭证Str相关处理。 -func (a *Account) replaceCookieStr(cookieStr string) { - a.replaceCredentialState(cookieStr, credentialStateFingerprint(cookieStr, "")) -} - -// replaceCredentialState 负责replaceCredential状态相关处理。 -func (a *Account) replaceCredentialState(cookieStr, credentialFP string) { - a.mu.Lock() - defer a.mu.Unlock() - a.CookieStr = cookieStr - a.credentialFP = credentialFP - if // unb 保存unb,供当前处理流程使用 - unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" { - a.UserID = unb - } + return a.outgoing.automationReady() } // rotatePageDeviceID 对应官网 auto-login 成功后的 location.reload(): @@ -2134,52 +874,3 @@ func (a *Account) rotatePageDeviceID() { a.deviceID = protocol.GenerateDeviceID(userID) a.mu.Unlock() } - -// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。 -func (a *Account) UpdateCookie(cookieStr string) { - if strings.TrimSpace(cookieStr) == "" && (a.store == nil || a.store.Cookies == nil) { - return - } - a.refreshMu.Lock() - defer a.refreshMu.Unlock() - // credentialUnlock 保存credentialUnlock,供当前处理流程使用 - credentialUnlock := func() {} - if a.store != nil { - credentialUnlock = a.store.LockAccountCredentials(a.CookieID) - } - defer credentialUnlock() - // 外部调用通常发生在一次网络请求写回之后。调用排队期间可能已有更新的 - // Cookie 落库,因此参数只作为无 Store 场景的兼容值;有 Store 时始终 - // 复读权威数据库,绝不把较旧的请求结果重新写回运行时。 - // metadataJSON 保存metadataJSON,供当前处理流程使用 - metadataJSON := "" - if a.store != nil && a.store.Cookies != nil { - runtimeData, err := a.store.Cookies.GetCookieRuntimeData(context.Background(), a.CookieID) // runtimeData 只包含同步运行时 Cookie 所需的 Cookie 与 metadata。 - if err != nil { - a.logger.Warn("同步运行时 Cookie 前读取数据库失败", "err", err) - return - } - if strings.TrimSpace(runtimeData.Value) == "" { - if // complete 保存complete,供当前处理流程使用 - _, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete { - a.logger.Warn("同步运行时 Cookie 时数据库值为空且无权威 Jar") - return - } - } - cookieStr = runtimeData.Value - metadataJSON = runtimeData.MetadataJSON - } - // credentialFP 保存credentialFP,供当前处理流程使用 - credentialFP := credentialStateFingerprint(cookieStr, metadataJSON) - a.mu.Lock() - // changed 保存changed,供当前处理流程使用 - changed := credentialFP != a.credentialFP - a.mu.Unlock() - if !changed { - return - } - a.replaceCredentialState(cookieStr, credentialFP) - // Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie - // 会在下一次自然重连前被重新读取并用于获取新的 accessToken。 - a.clearTokenCache(context.Background()) -} diff --git a/internal/engine/account_components.go b/internal/engine/account_components.go new file mode 100644 index 0000000..700aa13 --- /dev/null +++ b/internal/engine/account_components.go @@ -0,0 +1,62 @@ +package engine + +import ( + "log/slog" + + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +// accountRuntimeComponents 统一拥有单账号运行时的可变状态、任务生命周期和消息分发器。 +// 各子组件继续分别保护自己的字段与锁;该聚合对象只负责明确它们属于同一个账号运行时, +// 不允许把这些状态提升为包级共享变量,也不负责执行外部 I/O。 +type accountRuntimeComponents struct { + // credentialState 拥有 Cookie、Token、设备指纹和刷新串行化状态。 + credentialState + // credentials 拥有凭证读取、续期、Token 缓存和外部回调边界;它固定服务于本账号 facade。 + credentials credentialCoordinator + // accountRuntimeState 拥有 WebSocket 连接、状态快照和失败诊断计数。 + accountRuntimeState + // lifecycle 拥有账号运行 Context、任务接入 fencing 以及 Stop/Wait 语义。 + lifecycle accountLifecycle + // connection 连接协调器拥有 WebSocket 拨号、注册、重连和会话轮换编排。 + connection connectionCoordinator + // messageDispatcher 拥有消息去重、防抖和并发投递状态。 + messageDispatcher + // outgoing 拥有出站消息、聊天历史和会话查询的连接快照边界。 + outgoing outgoingMessageCoordinator + // pendingRenewal 拥有迟到续期任务的登记、取消和 Join 语义。 + pendingRenewal pendingRenewalCoordinator +} + +// accountDependencies 固定单账号运行时所需的基础设施和业务端口。 +// 这些依赖在 New 中一次性装配,运行期间不可通过 setter 替换;需要替身的测试应使用 Config 注入。 +type accountDependencies struct { + // store 提供账号凭证、Token 缓存和自动回复所需的持久化端口。 + store *db.Store + // mtop 提供 Token、登录态和平台 API 调用能力。 + mtop mtop.Client + // renewer 提供启动阶段的 API 优先 Cookie 续期能力;为空表示不启用该流程。 + renewer cookieRenewer + // wsDialer 提供 WebSocket 拨号能力,并隔离真实网络握手。 + wsDialer WSDialer + // handler 接收系统事件、账号告警和凭证恢复回调。 + handler Handler + // logger 记录账号运行时诊断信息,不得写入凭证原文。 + logger *slog.Logger + // reply 提供账号内部的聊天回复链;它由 store 存在时创建。 + reply *ReplyService + // recorder 拥有 WebSocket 报文记录 worker 的队列与等待边界。 + recorder *wsRecorder +} + +// newAccountDependencies 创建通过构造函数验证后的账号基础设施依赖快照。 +// store 是账号运行时使用的持久化端口;client 是固定 MTOP 客户端;renewer 是可选续期端口; +// dialer 是 WebSocket 拨号器;handler 是事件与告警端口;logger 是脱敏日志器;reply 是回复服务; +// recorder 是报文记录 worker owner。 +func newAccountDependencies(store *db.Store, client mtop.Client, renewer cookieRenewer, dialer WSDialer, handler Handler, logger *slog.Logger, reply *ReplyService, recorder *wsRecorder) accountDependencies { + return accountDependencies{ + store: store, mtop: client, renewer: renewer, wsDialer: dialer, + handler: handler, logger: logger, reply: reply, recorder: recorder, + } +} diff --git a/internal/engine/account_extra_test.go b/internal/engine/account_extra_test.go index 9454f4f..a5bec69 100644 --- a/internal/engine/account_extra_test.go +++ b/internal/engine/account_extra_test.go @@ -12,6 +12,7 @@ import ( "time" "xianyu-go/internal/automation" + "xianyu-go/internal/db" "xianyu-go/internal/xianyu" "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/mtop" @@ -816,6 +817,34 @@ type failingRefreshHandler struct { events []string } +// lockAwareRefreshHandler 在外部恢复回调内重新获取账号凭证锁,用于验证锁边界。 +type lockAwareRefreshHandler struct { + // store 提供测试账号凭证锁。 + store *db.Store + // acquired 表示回调是否成功获取并释放凭证锁。 + acquired bool +} + +// HandleChatMessage 满足 Engine Handler 接口的聊天处理方法。 +func (h *lockAwareRefreshHandler) HandleChatMessage(context.Context, ChatMessage) error { return nil } + +// HandleSystemEvent 满足 Engine Handler 接口的系统事件处理方法。 +func (h *lockAwareRefreshHandler) HandleSystemEvent(context.Context, automation.Task) error { + return nil +} + +// OnPasswordLoginRefresh 在恢复回调中获取凭证锁,证明调用方未跨外部 I/O 持锁。 +func (h *lockAwareRefreshHandler) OnPasswordLoginRefresh(context.Context, string) bool { + // unlock 释放恢复回调取得的账号凭证锁。 + unlock := h.store.LockAccountCredentials("cid") + unlock() + h.acquired = true + return false +} + +// OnAccountAlert 满足 Engine Handler 接口的告警处理方法。 +func (h *lockAwareRefreshHandler) OnAccountAlert(context.Context, string, string, string, string) {} + // HandleChatMessage 处理聊天消息。 func (f *failingRefreshHandler) HandleChatMessage(context.Context, ChatMessage) error { return nil } @@ -838,6 +867,29 @@ func (f *failingRefreshHandler) OnAccountEvent(_ context.Context, _, eventType, f.alerts = append(f.alerts, level) } +// TestHandleMaxFailuresReleasesCredentialLockBeforeExternalRecovery 验证外部凭证恢复回调执行时账号锁已释放。 +func TestHandleMaxFailuresReleasesCredentialLockBeforeExternalRecovery(t *testing.T) { + // acc、store、cleanup 保存账号运行时、凭证存储及清理函数。 + acc, _, store, cleanup := newAccountForTest(t) + defer cleanup() + // handler 保存会尝试重新获取账号锁的恢复回调。 + handler := &lockAwareRefreshHandler{store: store} + acc.handler = handler + // ctx 保存本测试共用的上下文。 + ctx := context.Background() + acc.mu.Lock() + acc.lastMsgReceived = time.Time{} + acc.connFailures = MaxConnectionFailures + acc.mu.Unlock() + // err 保存连续失败恢复流程返回的错误。 + if err := acc.handleMaxFailures(ctx); err == nil || !strings.Contains(err.Error(), "自动恢复失败") { + t.Fatalf("恢复失败应返回终止错误: %v", err) + } + if !handler.acquired { + t.Fatal("外部恢复回调未成功获取账号凭证锁") + } +} + // TestHandleMaxFailures_PasswordLoginFailure 密码登录刷新失败后终止账号主循环。 func TestHandleMaxFailures_PasswordLoginFailure(t *testing.T) { // acc、cleanup 保存acc、cleanup,供当前处理流程使用 diff --git a/internal/engine/account_lifecycle.go b/internal/engine/account_lifecycle.go index 925ed22..72316c6 100644 --- a/internal/engine/account_lifecycle.go +++ b/internal/engine/account_lifecycle.go @@ -6,7 +6,7 @@ import ( ) // accountLifecycle 管理单账号运行上下文和业务任务生命周期。 -// mu 保护 stopFn、stopped、runtimeCtx、accepting 以及 taskWG.Add 与停止切换的顺序; +// mu 保护 stopFn、stopped、runtimeCtx、accepting、任务计数和停止完成信号; // 持有 mu 时只做内存操作,不执行 I/O。Stop 先禁止新任务、再取消上下文,最后等待已有任务。 // accountLifecycle 是账号业务任务生命周期组件。 @@ -21,23 +21,30 @@ type accountLifecycle struct { runtimeCtx context.Context // accepting 表示是否仍允许新的消息或自动化任务进入。 accepting bool - // taskWG 等待所有已经通过 beginTask 的业务任务退出。 - taskWG sync.WaitGroup // activeTasks 记录尚未完成的任务数量,用于在超时 Stop 后由最后一个任务关闭 stopDone。 activeTasks int - // stopDone 在第一次 Stop 的清理完成后关闭,保证并发 Stop 调用也等待完整收束。 + // tasksFinished 表示 stopDone 已关闭,避免重复 finishTask 破坏共享停止信号。 + tasksFinished bool + // stopDone 在 Stop 前已登记的业务任务全部退出后关闭;它由 lifecycle 保存, + // 所有等待者直接订阅该信号,不为每次带超时的等待创建无法 Join 的协程。 stopDone chan struct{} } // start 注册一次 Run 的上下文和取消函数,并重新开放业务任务入口。 -func (l *accountLifecycle) start(ctx context.Context, cancel context.CancelFunc) { +// 若 Stop 已经先于 Run 建立了不可逆的停止 fencing,则返回 false,拒绝迟到的启动。 +func (l *accountLifecycle) start(ctx context.Context, cancel context.CancelFunc) bool { l.mu.Lock() + if l.stopped { + l.mu.Unlock() + return false + } l.stopFn = cancel l.runtimeCtx = ctx l.accepting = true - l.stopped = false l.stopDone = nil + l.tasksFinished = false l.mu.Unlock() + return true } // stopContext 原子地禁止新任务并取出取消函数;并发停止调用会受 ctx 限制地等待首次清理完成。 @@ -64,7 +71,7 @@ func (l *accountLifecycle) stopContext(ctx context.Context) (context.CancelFunc, l.stopDone = make(chan struct{}) if l.activeTasks == 0 { close(l.stopDone) - l.stopDone = nil + l.tasksFinished = true } // cancel 是当前账号 Run 上下文的取消函数。 cancel := l.stopFn @@ -87,36 +94,36 @@ func (l *accountLifecycle) beginTask() (context.Context, bool) { if ctx.Err() != nil { return nil, false } - l.taskWG.Add(1) l.activeTasks++ return ctx, true } // finishTask 标记一个已登记的业务任务退出。 func (l *accountLifecycle) finishTask() { - l.taskWG.Done() l.mu.Lock() if l.activeTasks > 0 { l.activeTasks-- } - if l.stopped && l.activeTasks == 0 && l.stopDone != nil { + if l.stopped && l.activeTasks == 0 && !l.tasksFinished && l.stopDone != nil { close(l.stopDone) - l.stopDone = nil + l.tasksFinished = true } l.mu.Unlock() } -// waitContext 等待已登记业务任务结束,并在 ctx 到期时及时返回。 +// waitContext 等待 Stop 前已登记的业务任务结束,并在 ctx 到期时及时返回。 +// stopDone 由最后一个任务关闭,因而超时返回不遗留等待协程;调用方可用新的上下文再次等待同一信号。 func (l *accountLifecycle) waitContext(ctx context.Context) bool { if ctx == nil { ctx = context.Background() } - // done 是所有已登记任务完成后关闭的等待信号。 - done := make(chan struct{}) - go func() { - l.taskWG.Wait() - close(done) - }() + l.mu.Lock() + // done 是 Stop 为当前收束周期创建、由最后一个已登记任务关闭的共享信号。 + done := l.stopDone + l.mu.Unlock() + if done == nil { + return true + } select { case <-done: return true diff --git a/internal/engine/account_lifecycle_test.go b/internal/engine/account_lifecycle_test.go index d6376f4..628b983 100644 --- a/internal/engine/account_lifecycle_test.go +++ b/internal/engine/account_lifecycle_test.go @@ -104,3 +104,73 @@ func TestAccountStopContextBoundsTaskWait(t *testing.T) { t.Fatal("第一次 Stop 超时后,重试未在任务完成后返回") } } + +// TestAccountLifecycleWaitContextCanRetryAfterTimeout 验证超时等待不占用额外协程,且后续调用能继续等待同一任务收束信号。 +func TestAccountLifecycleWaitContextCanRetryAfterTimeout(t *testing.T) { + // lifecycle 是独立的账号业务任务生命周期组件。 + lifecycle := accountLifecycle{} + // runCtx 是任务共享的运行上下文;cancel 用于测试结束时释放资源。 + runCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + if !lifecycle.start(runCtx, cancel) { + t.Fatal("生命周期应允许首次启动") + } + // taskCtx 是登记任务继承的运行上下文;accepted 表示任务已成功进入停止收束范围。 + taskCtx, accepted := lifecycle.beginTask() + if !accepted || taskCtx == nil { + t.Fatal("业务任务应成功登记") + } + // shouldStop 表示本次调用创建了停止收束信号;stopErr 表示停止切换错误。 + _, shouldStop, stopErr := lifecycle.stopContext(context.Background()) + if stopErr != nil || !shouldStop { + t.Fatalf("停止生命周期失败:shouldStop=%v err=%v", shouldStop, stopErr) + } + // timeoutCtx 是短超时等待上下文;timeoutCancel 释放其计时器。 + timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer timeoutCancel() + if lifecycle.waitContext(timeoutCtx) { + t.Fatal("未完成任务时 waitContext 应受上下文超时限制") + } + // waited 表示第二次等待是否在任务完成前返回,证明它继续订阅原停止信号。 + waited := make(chan bool, 1) + go func() { + waited <- lifecycle.waitContext(context.Background()) + }() + select { + case <-waited: + t.Fatal("任务未完成时,重试等待不应提前返回") + case <-time.After(20 * time.Millisecond): + } + lifecycle.finishTask() + select { + // completed 表示第二次等待在任务收束后得到正常完成结果。 + case completed := <-waited: + if !completed { + t.Fatal("任务完成后 waitContext 应返回 true") + } + case <-time.After(time.Second): + t.Fatal("任务完成后 waitContext 未返回") + } +} + +// TestAccountLifecycleRejectsLateStart 验证 Stop 先于 Run 时不会重新开放已停止的生命周期。 +func TestAccountLifecycleRejectsLateStart(t *testing.T) { + // lifecycle 是尚未运行但允许被停止的账号生命周期组件。 + lifecycle := accountLifecycle{accepting: true} + // stopErr 表示预先停止生命周期时的错误结果。 + _, shouldStop, stopErr := lifecycle.stopContext(context.Background()) + if stopErr != nil || !shouldStop { + t.Fatalf("预先停止生命周期失败:shouldStop=%v err=%v", shouldStop, stopErr) + } + // runCtx 是迟到 Run 尝试注册的运行上下文;cancel 负责释放该上下文。 + runCtx, cancel := context.WithCancel(context.Background()) + defer cancel() + if lifecycle.start(runCtx, cancel) { + t.Fatal("Stop 先于 Run 时不应重新启动生命周期") + } + // taskCtx 是停止后尝试登记业务任务得到的上下文,必须被拒绝。 + taskCtx, accepted := lifecycle.beginTask() + if accepted || taskCtx != nil { + t.Fatalf("停止后的生命周期不应接收任务:ctx=%v accepted=%v", taskCtx, accepted) + } +} diff --git a/internal/engine/connection_attempt.go b/internal/engine/connection_attempt.go index ed1349c..95242b4 100644 --- a/internal/engine/connection_attempt.go +++ b/internal/engine/connection_attempt.go @@ -12,8 +12,7 @@ type registerConnectionResult struct { Err error } -// registerConnection 在账号凭证锁内完成快照复核和 WebSocket 注册。 -// 凭证锁只覆盖快照读取与 Register,不覆盖后续连接循环或任何通知 I/O; +// registerConnection 在锁内复核凭证快照、锁外执行 WebSocket 注册,并在返回前再次确认凭证未变。 // Account facade 继续负责根据 Registered/Err 决定重载 Cookie、重试或结束运行。 // registerConnection 是凭证校验与 WebSocket 注册的生命周期入口。 @@ -23,9 +22,22 @@ func (a *Account) registerConnection(ctx context.Context, conn WSConn, deviceID, if a.store != nil { credentialUnlock = a.store.LockAccountCredentials(a.CookieID) } - defer credentialUnlock() if !a.cookieSnapshotMatchesDB(ctx, tokenCredentialFP) { + credentialUnlock() return registerConnectionResult{} } - return registerConnectionResult{Registered: true, Err: conn.Register(ctx, deviceID, accessToken)} + credentialUnlock() + // registerErr 保存锁外 WebSocket 注册的结果。 + registerErr := conn.Register(ctx, deviceID, accessToken) + if a.store != nil { + // verifyUnlock 保护注册完成后的凭证一致性复核,避免旧连接继续进入在线状态。 + verifyUnlock := a.store.LockAccountCredentials(a.CookieID) + // stillCurrent 表示注册完成后数据库凭证仍与 Token 绑定指纹一致。 + stillCurrent := a.cookieSnapshotMatchesDB(ctx, tokenCredentialFP) + verifyUnlock() + if !stillCurrent { + return registerConnectionResult{} + } + } + return registerConnectionResult{Registered: true, Err: registerErr} } diff --git a/internal/engine/connection_coordinator.go b/internal/engine/connection_coordinator.go new file mode 100644 index 0000000..d9cc217 --- /dev/null +++ b/internal/engine/connection_coordinator.go @@ -0,0 +1,295 @@ +package engine + +import ( + "context" + "errors" + "fmt" + "time" + + "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/ws" +) + +// connectionShutdownJoinTimeout 是连接协调器取消账号运行 Context 后等待自有 worker 退出的总预算。 +// recorder 的单次数据库 I/O 已使用同一数量级的超时;该预算避免不响应取消的底层实现永久阻塞 Run。 +const connectionShutdownJoinTimeout = WSRecordWriteTimeout + +// connectionCoordinator 拥有单账号 WebSocket 拨号、注册、重连和会话轮换编排。 +// account 是构造完成后固定的 facade;协调器不单独启动 goroutine,所有任务都继承 +// Account.Run 创建的 Context,并在返回前使用有限预算等待 recorder 与迟到续期任务收束。 +type connectionCoordinator struct { + // account 是本协调器唯一服务的账号 facade,New 在对象对外可见前写入。 + account *Account +} + +// run 阻塞执行单账号连接主循环,直到调用方取消、账号禁用或不可恢复的认证错误。 +// parent 是 account.Manager 提供的运行上下文;返回值保留原 Account.Run 的错误语义。 +func (c *connectionCoordinator) run(parent context.Context) error { + // a 是当前连接协调器绑定的账号 facade;其状态与固定依赖均已在 New 中完成装配。 + a := c.account + if a == nil { + return errors.New("账号连接协调器未初始化") + } + // ctx、cancel 保存当前 Run 派生的可取消运行上下文及其取消函数。 + ctx, cancel := context.WithCancel(parent) + defer func() { + cancel() + // shutdownCtx、shutdownCancel 提供独立于 parent 取消状态的有限 Join 预算; + // 这样父 Context 已取消时仍优先收束正常 worker,而不响应取消的外部实现最多占用该预算。 + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), connectionShutdownJoinTimeout) + defer shutdownCancel() + c.waitForOwnedWorkers(shutdownCtx) + }() + // lifecycleStarted 表示 Stop 是否已经在 Run 建立生命周期前完成;false 时必须放弃迟到启动。 + lifecycleStarted := a.lifecycle.start(ctx, cancel) + if !lifecycleStarted { + return context.Canceled + } + if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) { + a.logger.Info("账号在启动续期前已禁用") + return nil + } + a.startWSRecorder(ctx) + // 官网 /im 启动时执行 auto-login plugin;成功后 location.reload() 会重建 + // FishEngine 和页面级 device ID。Go 客户端用 HTTP 复刻续期,并在成功时 + // 只重建这一本地运行时身份。续期失败不能用网页 DOM 阻断 token + WS; + // Chromium 仅用于读取本机指纹和处理 token 滑块。 + if a.renewer != nil { + if a.tryAPIRenew(ctx) { + a.rotatePageDeviceID() + } + if ctx.Err() != nil { + return ctx.Err() + } + } + for { + if ctx.Err() != nil { + return ctx.Err() + } + // 账号是否被禁用。 + if !a.store.Cookies.GetStatus(ctx, a.CookieID) { + a.logger.Info("账号已禁用,停止主循环") + return nil + } + + // 每次新建 IM 连接前吸收数据库中的最新 Cookie。健康连接不会被续期任务 + // 主动打断;Cookie 变化只会使本次重连放弃旧 token 并重新派生。 + a.reloadCookieFromDB(ctx) + + // 官网先完成原生 WebSocket 握手,再从 authTokenCallback 获取本次 + // 连接专用 token,最后发送 /reg。 + // conn、err 保存当前 WebSocket 连接及拨号或后续认证阶段的错误。 + conn, err := a.wsDialer.Dial(ctx, ws.Config{Recorder: a.wsRecorder()}, a.logger) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + a.logger.Error("WS 握手失败", "err", err) + // retryErr 保存握手失败处理后的终止错误;非 nil 时连接循环必须退出。 + if retryErr := a.handleWSConnectFailure(ctx, err); retryErr != nil { + return retryErr + } + continue + } + // The official web client calls + // mtop.taobao.idlemessage.pc.login.token from authTokenCallback for every + // loginV2/reConnect attempt. Do the same here: an access token belongs to + // one connection attempt and must never be reused for a later /reg. + // token、cookieStr、err 保存本次连接专用 Token、其绑定 Cookie 快照与获取错误。 + token, cookieStr, err := a.acquireFreshConnectionToken(ctx) + if err != nil { + _ = conn.Close() + if ctx.Err() != nil { + return ctx.Err() + } + a.logger.Error("获取 token 失败", "err", err) + a.mu.Lock() + // status 是刷新失败分类快照,用于决定是否累加失败计数。 + status := a.lastTokenStatus + // nonCounted 表示验证码与冷却失败不计入连接 Token 获取失败次数。 + nonCounted := tokenFailureIsNonCounted(status) + if !nonCounted { + a.tokenFetchFailures++ + } + // tokenFailures 是当前失败次数快照,只用于保留原有诊断路径。 + tokenFailures := a.tokenFetchFailures + a.mu.Unlock() + a.setRuntimeError(ctx, err) + _ = tokenFailures // 仅用于诊断;官网不会按次数永久禁用账号。 + if mtop.IsRiskVerificationErr(err) { + a.logger.Warn("闲鱼要求安全验证,停止本次消息登录", "err", err) + a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证", + "账号触发闲鱼风控验证(滑块/人脸等),需要重新登录或完成人工验证。") + return err + } + if mtop.IsSessionExpiredErr(err) { + // reason 是当前凭证失效或恢复失败时展示给运行状态与通知的原因。 + reason := "登录凭证已失效,正在立即续期" + a.logger.Warn("token API 检测到 Session 过期,停止重试并开始即时续期", "err", err) + a.clearTokenCache(ctx) + a.setRuntimeState(RuntimeReconnecting, reason) + a.notifyOffline(ctx, reason+":"+errString(err)) + if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) { + a.reloadCookieFromDB(ctx) + a.clearCurrentToken() + a.resetFailures() + a.setRuntimeState(RuntimeConnecting, "Session 续期成功,正在重新连接") + continue + } + reason = "登录凭证已失效,自动续期失败,请重新扫码登录" + a.setRuntimeState(RuntimeAuthExpired, reason) + a.notifyOffline(ctx, reason+":"+errString(err)) + return err + } + // 网络或服务端瞬时错误不能让账号运行时永久退出。只要登录 Session + // 没有明确失效,就持续重试获取连接级 Token。 + a.setRuntimeState(RuntimeReconnecting, "获取消息凭证失败,正在重试") + a.notifyOffline(ctx, "获取消息凭证失败,正在自动重试:"+errString(err)) + // sleepErr 是本次重试退避等待被取消或到期时返回的错误。 + if sleepErr := sleepCtx(ctx, a.tokenRetryDelay()); sleepErr != nil { + return sleepErr + } + continue + } + a.mu.Lock() + a.currentToken = token + a.CookieStr = cookieStr + a.tokenFetchFailures = 0 + a.mu.Unlock() + a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务") + a.logger.Info("token 刷新成功") + + // 2) 使用刚获得的 token 注册已经打开的 WS。 + a.mu.Lock() + // deviceID 是本次注册使用的页面生命周期设备标识快照。 + deviceID := a.deviceID + // tokenCredentialFP 是本次 Token 绑定的完整凭证指纹快照。 + tokenCredentialFP := a.tokenCredentialFP + a.mu.Unlock() + // registerResult 是凭证快照复核与 WebSocket 注册的窄边界结果。 + registerResult := a.registerConnection(ctx, conn, deviceID, token, tokenCredentialFP) + if !registerResult.Registered { + _ = conn.Close() + a.reloadCookieFromDB(ctx) + continue + } + err = registerResult.Err + if err != nil { + _ = conn.Close() + if ctx.Err() != nil { + return ctx.Err() + } + a.logger.Error("WS 注册失败", "err", err) + // retryErr 保存注册失败处理后的终止错误;非 nil 时连接循环必须退出。 + if retryErr := a.handleWSConnectFailure(ctx, err); retryErr != nil { + return retryErr + } + continue + } + a.runtimeMu.Lock() + a.conn = conn + a.connStartedAt = time.Now() + a.connFailures = 0 + a.networkFailures = 0 + a.authExpiredAlerted = false // 连接成功,复位 auth_expired 告警标记 + // shouldRecovered 表示本次连接是否结束了一个已告警的离线周期。 + shouldRecovered := a.offlineNotified + // offlineSince 是本次恢复前离线周期的起始时间快照。 + offlineSince := a.offlineSince + a.offlineNotified = false + a.offlineSince = time.Time{} + a.lastOfflineReason = "" + a.runtimeMu.Unlock() + a.setRuntimeState(RuntimeOnline, "消息服务连接正常") + a.notifyTransportReady(ctx) + if shouldRecovered { + a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线", + fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince))) + } + + // 3) 健康连接维持心跳和收包,并在服务端 Token 过期前主动关闭, + // 进入下一轮连接以重新调用 Token API 和 /reg。 + // refreshAt 和 expiresAt 是本次连接 Token 的轮换时间与服务端过期时间快照。 + a.mu.Lock() + // refreshAt 是本次已注册连接主动轮换 Token 的时间点。 + refreshAt := a.tokenRefreshAt + // expiresAt 是服务端声明的 Token 过期时间,仅用于诊断日志。 + expiresAt := a.tokenExpiresAt + a.mu.Unlock() + // session 是本次已注册连接的心跳、接收和 Token 轮换收束结果。 + session := a.runConnectionSession(ctx, conn, refreshAt) + if ctx.Err() != nil { + return ctx.Err() + } + + // 连接结束:只有认证类失败才清 token。已经建立后的网络断线继续 + // 使用内存 token 与数据库缓存,避免无意义调用 Token API。 + if session.Rotated { + a.logger.Info("WS Token 到达提前轮换时间,正在重新获取 Token", "expires_at", expiresAt, "remaining", time.Until(expiresAt).Round(time.Second)) + a.clearConnectionToken(ctx) + a.setRuntimeState(RuntimeReconnecting, "WS Token 即将到期,正在主动轮换") + continue + } + if ws.IsConnectLimitError(session.ReceiveErr) { + a.clearConnectionToken(ctx) + // reason 是服务端移除会话时记录给用户与通知的认证失效原因。 + reason := "消息会话已被服务端移除" + a.setRuntimeState(RuntimeAuthExpired, reason) + a.notifyOffline(ctx, reason) + return nil + } + if ws.IsAuthenticationError(session.ReceiveErr) { + // 官网把 /push/kickout 转成 UNCONNECTED,页面监听器随后立即 + // reConnect,并由 authTokenCallback 获取新的连接凭证。 + a.clearConnectionToken(ctx) + a.setRuntimeState(RuntimeReconnecting, "消息会话被服务端踢下线,正在重新连接") + continue + } + // 心跳失败会先关闭连接,ReceiveLoop 往往只观察到 context canceled。 + // 官网以心跳 Promise 的 reject 为真实断线原因并立即 reConnect。 + // receiveErr 是后续错误分类使用的本地副本;心跳错误优先于 context canceled。 + // receiveErr 是用于下方重连分类的最终接收错误。 + receiveErr := session.ReceiveErr + if session.HeartbeatErr != nil && !errors.Is(session.HeartbeatErr, context.Canceled) && + (receiveErr == nil || errors.Is(receiveErr, context.Canceled)) { + receiveErr = session.HeartbeatErr + } + + // 正常 close 的 async-for 会直接进入下一轮,不计任何失败。 + if receiveErr == nil { + a.clearConnectionToken(ctx) + a.setRuntimeState(RuntimeReconnecting, "消息连接已结束,正在重新连接") + continue + } + + if isEstablishedNetworkError(receiveErr) || errors.Is(receiveErr, context.Canceled) { + a.clearConnectionToken(ctx) + a.setRuntimeState(RuntimeReconnecting, "网络连接已断开,正在重新连接") + a.logger.Warn("WS 网络连接结束", "err", receiveErr, "connected_duration", session.ConnectedDuration.Round(time.Second), "heartbeat_err", session.HeartbeatErr) + // 官网当前页面在 CONN_UNCONNECTED 事件后立即调用 reConnect。 + continue + } + + // 其他已经建立后的非认证错误同样进入 UNCONNECTED;不升级为 + // 密码登录、指数退避或永久禁用。 + a.clearConnectionToken(ctx) + a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,正在重新连接") + a.logger.Warn("WS 连接结束", "err", receiveErr, "heartbeat_err", session.HeartbeatErr) + } +} + +// waitForOwnedWorkers 在 shutdownCtx 的总预算内等待连接协调器启动的 recorder 与迟到续期任务。 +// 两类任务都继承 Account.Run 的 Context;本方法只观察各自完成信号,不创建新的等待 goroutine。 +func (c *connectionCoordinator) waitForOwnedWorkers(shutdownCtx context.Context) { + // a 是当前连接协调器绑定的账号 facade;run 已在调用本方法前校验其非空。 + a := c.account + if a == nil { + return + } + if a.recorder != nil && !a.recorder.waitContext(shutdownCtx) { + a.logger.Warn("等待账号 WS 记录 worker 退出超时") + } + if !a.pendingRenewal.waitContext(shutdownCtx) { + a.logger.Warn("等待账号迟到续期任务退出超时") + } +} diff --git a/internal/engine/credential_coordinator.go b/internal/engine/credential_coordinator.go new file mode 100644 index 0000000..77e8a7f --- /dev/null +++ b/internal/engine/credential_coordinator.go @@ -0,0 +1,1156 @@ +package engine + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "strings" + "time" + + "xianyu-go/internal/logsafe" + "xianyu-go/internal/xianyu/cookierefresh" + "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/protocol" + "xianyu-go/internal/xianyu/renew" +) + +// credentialCoordinator 统一编排单账号的 Cookie、登录态、API 续期与 Token 缓存。 +// account 在 New 完成所有固定依赖和状态装配后写入;协调器不持有独立锁,凭证字段 +// 始终由 credentialState.mu 保护,数据库凭证锁只覆盖快照读取和条件提交,绝不覆盖 +// Handler、通知、MTOP 或浏览器等可扩展外部 I/O。 +type credentialCoordinator struct { + // account 是本协调器唯一服务的账号 facade,运行期间不会替换。 + account *Account +} + +// tryLoginStatusCheck 保留 Account 的稳定内部入口,并委托给凭证协调器。 +func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResult { + return a.credentials.tryLoginStatusCheck(ctx) +} + +// tryAPIRenew 保留启动续期入口,并委托给凭证协调器。 +func (a *Account) tryAPIRenew(ctx context.Context) bool { + return a.credentials.tryAPIRenew(ctx) +} + +// tryAPIRenewUsing 保留注入续期调用的测试兼容入口,并委托给凭证协调器。 +func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Context, string, []cookierefresh.BrowserCookie) (*renew.Result, error)) (bool, error) { + return a.credentials.tryAPIRenewUsing(ctx, call) +} + +// persistRenewFlatCookie 保留扁平 Cookie 写回的测试兼容入口,并委托给凭证协调器。 +func (a *Account) persistRenewFlatCookie(ctx context.Context, newCookies string) error { + return a.credentials.persistRenewFlatCookie(ctx, newCookies) +} + +// watchPendingAPIRenew 保留迟到续期任务登记入口,并委托给凭证协调器。 +func (a *Account) watchPendingAPIRenew(parent context.Context, result *renew.Result) { + a.credentials.watchPendingAPIRenew(parent, result) +} + +// persistPendingRenewCookies 保留迟到响应持久化入口,并委托给凭证协调器。 +func (a *Account) persistPendingRenewCookies(ctx context.Context, result *renew.Result) error { + return a.credentials.persistPendingRenewCookies(ctx, result) +} + +// adoptRecoveredCookie 保留轻量恢复 Cookie 的兼容入口,并委托给凭证协调器。 +func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source string) bool { + return a.credentials.adoptRecoveredCookie(ctx, newCookies, source) +} + +// notifyCredentialUpdated 保留凭证变更通知入口,并委托给凭证协调器。 +func (a *Account) notifyCredentialUpdated(ctx context.Context) { + a.credentials.notifyCredentialUpdated(ctx) +} + +// refreshToken 保留连接前新 Token 获取入口,并委托给凭证协调器。 +func (a *Account) refreshToken(ctx context.Context) (string, string, error) { + return a.credentials.refreshToken(ctx) +} + +// refreshTokenWithMinGap 保留旧签名测试入口,并委托给凭证协调器。 +func (a *Account) refreshTokenWithMinGap(ctx context.Context, enforceMinGap bool) (string, string, error) { + return a.credentials.refreshTokenWithMinGap(ctx, enforceMinGap) +} + +// clearCurrentToken 保留连接 Token 清理入口,并委托给凭证协调器。 +func (a *Account) clearCurrentToken() { + a.credentials.clearCurrentToken() +} + +// adoptTokenResponseCookies 保留 Token 响应 Cookie 合并入口,并委托给凭证协调器。 +func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr string, result *mtop.RefreshResult) (string, error) { + return a.credentials.adoptTokenResponseCookies(ctx, cookieStr, result) +} + +// tryTokenCaptchaRecovery 保留风控恢复入口,并委托给凭证协调器。 +func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, deviceID string, refreshErr error) (*mtop.RefreshResult, bool) { + return a.credentials.tryTokenCaptchaRecovery(ctx, cookieStr, deviceID, refreshErr) +} + +// markTokenCaptchaFailure 保留风控冷却记录入口,并委托给凭证协调器。 +func (a *Account) markTokenCaptchaFailure() { + a.credentials.markTokenCaptchaFailure() +} + +// tokenCaptchaCooldownRemaining 保留风控冷却查询入口,并委托给凭证协调器。 +func (a *Account) tokenCaptchaCooldownRemaining() time.Duration { + return a.credentials.tokenCaptchaCooldownRemaining() +} + +// setLastTokenStatus 保留 Token 刷新诊断状态入口,并委托给凭证协调器。 +func (a *Account) setLastTokenStatus(status string) { + a.credentials.setLastTokenStatus(status) +} + +// saveTokenCache 保留 Token 缓存写入入口,并委托给凭证协调器。 +func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, credentialFP string) { + a.credentials.saveTokenCache(ctx, deviceID, accessToken, serverExpireAt, credentialFP) +} + +// clearTokenCache 保留 Token 缓存删除入口,并委托给凭证协调器。 +func (a *Account) clearTokenCache(ctx context.Context) { + a.credentials.clearTokenCache(ctx) +} + +// databaseCredentialFingerprint 保留凭证指纹校验入口,并委托给凭证协调器。 +func (a *Account) databaseCredentialFingerprint(ctx context.Context, cookieStr string) (string, error) { + return a.credentials.databaseCredentialFingerprint(ctx, cookieStr) +} + +// reloadCookieFromDB 保留数据库 Cookie 同步入口,并委托给凭证协调器。 +func (a *Account) reloadCookieFromDB(ctx context.Context) bool { + return a.credentials.reloadCookieFromDB(ctx) +} + +// cookieSnapshotMatchesDB 保留 WS 注册前凭证复核入口,并委托给凭证协调器。 +func (a *Account) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string) bool { + return a.credentials.cookieSnapshotMatchesDB(ctx, expectedFP) +} + +// replaceCookieStr 保留内存 Cookie 替换入口,并委托给凭证协调器。 +func (a *Account) replaceCookieStr(cookieStr string) { + a.credentials.replaceCookieStr(cookieStr) +} + +// replaceCredentialState 保留完整凭证状态替换入口,并委托给凭证协调器。 +func (a *Account) replaceCredentialState(cookieStr, credentialFP string) { + a.credentials.replaceCredentialState(cookieStr, credentialFP) +} + +// UpdateCookie 是外部刷新 Cookie 同步的稳定导出入口,并委托给凭证协调器。 +func (a *Account) UpdateCookie(cookieStr string) { + a.credentials.updateCookie(cookieStr) +} + +// tryLoginStatusCheck 调用 mtop.taobao.idlemessage.pc.loginuser.get 做轻量登录态确认。 +// 这个接口的成本低于完整 token 刷新,且可能顺手下发新的签名 Cookie; +// 因此在 session 失效后、接口续期前先跑一遍,避免已实现的登录态检查能力闲置。 +// tryLoginStatusCheck 负责try登录状态Check相关处理。 +func (c *credentialCoordinator) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResult { + // a 是本凭证协调器绑定的账号 facade,提供状态与固定依赖访问。 + a := c.account + // checker、ok 保存checker、ok,供当前处理流程使用 + checker, ok := a.mtop.(loginStatusChecker) + if !ok { + return loginStatusCheckResult{} + } + // credentialUnlock 保存credentialUnlock,供当前处理流程使用 + credentialUnlock := func() {} + // credentialLocked 标识当前调用是否持有账号凭证锁。 + credentialLocked := false + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + credentialLocked = true + } + defer func() { + if credentialLocked { + credentialUnlock() + } + }() + a.mu.Lock() + // cookieStr 保存登录凭证Str,供当前处理流程使用 + cookieStr := a.CookieStr + a.mu.Unlock() + // requestCtx 保存请求Ctx,供当前处理流程使用 + requestCtx := ctx + // cookieSession 保存登录凭证会话,供当前处理流程使用 + var cookieSession *mtop.CookieSession + // metadataJSON 保存metadataJSON,供当前处理流程使用 + metadataJSON := "" + if a.store != nil && a.store.Cookies != nil { + runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含登录态检查所需的 Cookie 与 metadata。 + if detailErr != nil { + a.logger.Warn("登录态检查前读取最新 Cookie 失败", "err", detailErr) + return loginStatusCheckResult{} + } + cookieStr = runtimeData.Value + metadataJSON = runtimeData.MetadataJSON + // runtimeData 已在凭证锁内读取,下面只负责根据 metadata 建立 Cookie 会话。 + // metadataJSON 保留完整 Jar 信息,不能退化为仅使用扁平 Cookie。 + // snapshot 分支继续沿用登录态检查原有的请求作用域和持久化顺序。 + if // snapshot、complete 保存snapshot、complete,供当前处理流程使用 + snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete { + requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot) + } else { + requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr) + } + } + // 登录态检查只使用当前凭证快照;慢速外部调用不得持有共享账号锁。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + // res、err 保存res、err,供当前处理流程使用 + res, err := checker.CheckLoginStatusContext(requestCtx, cookieStr) + if a.store != nil && a.store.Cookies != nil { + // credentialUnlock 保存外部检查完成后重新进入提交临界区的释放函数。 + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + credentialLocked = true + // latestRuntimeData 和 reloadErr 保存外部检查完成后的最新凭证视图及重读错误。 + latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) + if reloadErr != nil { + a.logger.Warn("登录态检查完成后读取最新 Cookie 失败", "err", reloadErr) + return loginStatusCheckResult{} + } + // credentialSnapshotChanged 表示外部检查期间已有其他流程更新 Cookie 或 metadata。 + credentialSnapshotChanged := latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON + cookieStr = latestRuntimeData.Value + metadataJSON = latestRuntimeData.MetadataJSON + if credentialSnapshotChanged { + // 外部响应基于旧快照,当前切片不具备可安全重放的 Cookie 集合,因此丢弃旧响应状态。 + cookieSession = nil + if res != nil { + res.UpdatedCookies = cookieStr + } + } + } + if cookieSession != nil { + // value、snapshot、changed 保存value、snapshot、changed,供当前处理流程使用 + value, snapshot, changed := cookieSession.State() + if changed { + // metadata 保存metadata,供当前处理流程使用 + metadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON) + if snapshot != nil { + metadata = cookierefresh.MetadataWithSnapshot(metadataJSON, snapshot) + } + if // persistErr 保存persistErr,供当前处理流程使用 + persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, value, metadata, time.Now().Unix()); persistErr != nil { + a.logger.Warn("登录态检查保存响应 Cookie Jar 失败", "err", persistErr) + return loginStatusCheckResult{} + } + a.replaceCredentialState(value, credentialStateFingerprint(value, metadata)) + a.clearTokenCache(ctx) + // Handler 实现可执行通知或其他外部 I/O,不能让其占用凭证提交锁。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + a.notifyCredentialUpdated(ctx) + if err != nil { + a.logger.Warn("登录态检查失败,已保存响应 Cookie", "err", err) + } + return loginStatusCheckResult{recovered: res != nil && res.Status == mtop.LoginStatusTokenRefreshed} + } + } + // 以下恢复路径会触发可扩展 Handler;提交阶段已经结束,必须先释放凭证锁。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + if err != nil { + a.logger.Warn("登录态检查失败", "err", err) + return loginStatusCheckResult{} + } + if res == nil { + return loginStatusCheckResult{} + } + if res.Status == mtop.LoginStatusRiskRequired { + a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证") + a.logger.Warn("登录态检查命中风控验证", "ret", strings.Join(res.Ret, ","), "verification_url", logsafe.URL(res.VerificationURL)) + return loginStatusCheckResult{riskRequired: true, verificationURL: res.VerificationURL} + } + if res.Status == mtop.LoginStatusTokenRefreshed && len(cookierefresh.ChangedCookieNames(cookieStr, res.UpdatedCookies)) > 0 && a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") { + a.logger.Info("登录态检查刷新了 Cookie", "status", res.Status, "message", res.Message) + return loginStatusCheckResult{recovered: true} + } + a.logger.Info("登录态检查未产生可用 Cookie 更新", "status", res.Status, "message", res.Message) + return loginStatusCheckResult{} +} + +// tryAPIRenew 是密码登录前的轻量恢复层,只执行官网 auto-login plugin 的 +// 单次 silentHasLogin 流程。如果只拿到部分 Cookie,仍先保存并清 token, +// 但继续按 Go 协议执行后续恢复;仍失败时由上层要求重新扫码登录。 +// tryAPIRenew 负责tryAPIRenew相关处理。 +func (c *credentialCoordinator) tryAPIRenew(ctx context.Context) bool { + // a 是本凭证协调器绑定的账号 facade,提供可选续期端口。 + a := c.account + if a.renewer == nil { + return false + } + // renewed 保存renewed,供当前处理流程使用 + renewed, _ := a.tryAPIRenewUsing(ctx, func(runCtx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*renew.Result, error) { + return a.renewer.RenewAPIFirst(runCtx, cookieStr, snapshot) + }) + return renewed +} + +// tryAPIRenewUsing 负责tryAPIRenewUsing相关处理。 +func (c *credentialCoordinator) tryAPIRenewUsing(ctx context.Context, call func(context.Context, string, []cookierefresh.BrowserCookie) (*renew.Result, error)) (bool, error) { + // a 是本凭证协调器绑定的账号 facade,统一提供凭证状态与运行时状态。 + a := c.account + // releaseRefreshGate 释放当前账号刷新流程的通道令牌。 + releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx) + if gateErr != nil { + return false, gateErr + } + defer releaseRefreshGate() + // credentialUnlock 保存credentialUnlock,供当前处理流程使用 + credentialUnlock := func() {} + // credentialLocked 标识当前调用是否持有账号凭证锁。 + credentialLocked := false + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + credentialLocked = true + } + defer func() { + if credentialLocked { + credentialUnlock() + } + }() + if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) { + return false, nil + } + a.mu.Lock() + // cookieStr 保存登录凭证Str,供当前处理流程使用 + cookieStr := a.CookieStr + a.mu.Unlock() + // snapshot 保存snapshot,供当前处理流程使用 + var snapshot []cookierefresh.BrowserCookie + // metadataJSON 保存用于续期请求和提交比较的 Cookie metadata。 + metadataJSON := "" + if a.store != nil && a.store.Cookies != nil { + runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含接口续期所需的 Cookie 与 metadata。 + if detailErr != nil { + a.logger.Warn("接口续期前读取最新 Cookie 失败", "err", detailErr) + return false, detailErr + } + if runtimeData.Value != cookieStr { + cookieStr = runtimeData.Value + a.replaceCookieStr(cookieStr) + a.clearCurrentToken() + a.clearTokenCache(ctx) + } + metadataJSON = runtimeData.MetadataJSON + snapshot = cookierefresh.SnapshotFromMetadata(runtimeData.MetadataJSON) + // runtimeData 的 Cookie 用于续期请求,metadata 用于恢复浏览器 Cookie 快照。 + // 读取窄模型不会触碰登录用户名、密码等无关凭证字段。 + // API 续期仍沿用原有锁、Cookie 比较和 token 清理顺序。 + } + // API 续期只使用当前凭证快照;慢速外部续期回调不得持有共享账号锁。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + // res、err 保存res、err,供当前处理流程使用 + res, err := call(ctx, cookieStr, snapshot) + // responseMetadataOverride 保存并发更新期间重放响应 Cookie 后的 metadata。 + responseMetadataOverride := "" + // responseMetadataOverridden 表示本次响应已经基于最新凭证快照重放。 + responseMetadataOverridden := false + if a.store != nil && a.store.Cookies != nil { + // credentialUnlock 保存外部续期完成后重新进入提交临界区的释放函数。 + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + credentialLocked = true + // latestRuntimeData 和 reloadErr 保存外部续期完成后的最新凭证视图及重读错误。 + latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) + if reloadErr != nil { + a.logger.Warn("接口续期完成后读取最新 Cookie 失败", "err", reloadErr) + return false, reloadErr + } + // credentialSnapshotChanged 表示外部续期期间已有其他流程更新 Cookie 或 metadata。 + credentialSnapshotChanged := latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON + cookieStr = latestRuntimeData.Value + metadataJSON = latestRuntimeData.MetadataJSON + if res != nil && credentialSnapshotChanged { + if len(res.SetCookies) > 0 { + // rebasedCookies、rebasedMetadata 保存基于最新快照重放 Set-Cookie 的结果。 + rebasedCookies, rebasedMetadata, _ := renew.RebaseResponseCookies(cookieStr, metadataJSON, res) + res.NewCookies = rebasedCookies + res.CookieSnapshot = nil + res.CookieSnapshotComplete = false + responseMetadataOverride = rebasedMetadata + responseMetadataOverridden = true + } else { + // 没有可重放的 Set-Cookie 时,拒绝把旧请求计算出的状态写回。 + res.NewCookies = cookieStr + res.CookieSnapshot = nil + res.CookieSnapshotComplete = false + } + } + } + if res == nil { + if err != nil { + a.logger.Warn("接口续期失败", "err", err) + } + return false, err + } + // updated 保存updated,供当前处理流程使用 + updated := false + // persisted 保存persisted,供当前处理流程使用 + persisted := false + if responseMetadataOverridden && a.store != nil && a.store.Cookies != nil { + // err 保存并发重放结果写回错误。 + if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.NewCookies, responseMetadataOverride, time.Now().Unix()); err != nil { + a.logger.Warn("保存并发重放后的续期 Cookie 失败", "err", err) + return false, err + } + persisted = true + } else if res.CookieSnapshotComplete && a.store != nil && a.store.Cookies != nil { + runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含续期快照持久化所需字段。 + // 快照持久化只依赖 metadata,Cookie 明文由续期响应直接提供。 + // 保留统一运行时查询模型,避免为相同凭证路径恢复完整账号详情。 + // 下面的更新操作和错误处理保持原有续期语义不变。 + if detailErr != nil { + a.logger.Warn("保存续期 Cookie 快照失败", "err", detailErr) + return false, detailErr + } + // metadata 保存metadata,供当前处理流程使用 + metadata := cookierefresh.MetadataWithSnapshot(runtimeData.MetadataJSON, res.CookieSnapshot) + if // err 保存err,供当前处理流程使用 + err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.NewCookies, metadata, time.Now().Unix()); err != nil { + a.logger.Warn("保存续期 Cookie 快照失败", "err", err) + return false, err + } + persisted = true + } else if len(res.SetCookies) > 0 && a.store != nil && a.store.Cookies != nil { + if // err 保存err,供当前处理流程使用 + err := a.persistRenewFlatCookie(ctx, res.NewCookies); err != nil { + a.logger.Warn("保存接口续期扁平 Cookie 失败", "err", err) + return false, err + } + persisted = true + } + // 续期写入已经提交,迟到续期 watcher 与 Handler 回调必须在凭证锁外启动。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + if res.HasPending() { + a.watchPendingAPIRenew(ctx, res) + } + // credentialChanged 保存credentialChanged,供当前处理流程使用 + credentialChanged := res.NewCookies != cookieStr && (res.CookieSnapshotComplete || len(res.SetCookies) > 0 || res.NewCookies != "") + if credentialChanged { + if persisted || a.store == nil || a.store.Cookies == nil { + a.replaceCookieStr(res.NewCookies) + a.clearCurrentToken() + a.clearTokenCache(ctx) + a.setRuntimeState(RuntimeConnecting, "接口续期已更新登录凭证,正在重新连接") + updated = true + } else { + updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期") + } + if updated && persisted { + a.notifyCredentialUpdated(ctx) + } + } + if err != nil { + a.logger.Warn("接口续期失败,已保存响应 Cookie", "err", err) + return false, err + } + if res.Success { + if !updated { + a.setRuntimeState(RuntimeConnecting, "登录凭证已接口续期,正在重新连接") + } + a.logger.Info("接口续期成功", "method", res.RenewMethod, "updated", strings.Join(res.UpdatedCookieNames, ",")) + return true, nil + } + if updated { + a.logger.Info("接口续期返回部分 Cookie 更新,继续降级恢复", "updated", strings.Join(res.UpdatedCookieNames, ",")) + return false, nil + } + a.logger.Info("接口续期未产生可用恢复", "success", res.Success, "message", res.Message) + return false, nil +} + +// persistRenewFlatCookie 负责persistRenewFlat登录凭证相关处理。 +func (c *credentialCoordinator) persistRenewFlatCookie(ctx context.Context, newCookies string) error { + // a 是本凭证协调器绑定的账号 facade,提供窄 Cookie repository。 + a := c.account + if a.store == nil || a.store.Cookies == nil { + return nil + } + metadata, err := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID) // metadata 只包含扁平 Cookie 写回所需的快照信息。 + if err != nil { + return err + } + // 该流程不需要读取现有 Cookie 明文或登录秘密。 + // metadata 已在 repository 层按账号作用域解密,下面只清理旧快照。 + // 更新操作继续由 UpdateRenewalCookie 负责加密和账号存在性校验。 + // 没有权威 Jar 时,接口 Set-Cookie 只能更新兼容扁平值。不能把 + // Domain/Path/HttpOnly/PartitionKey 均未知的 Cookie 伪造成完整快照。 + metadata = cookierefresh.MetadataWithoutSnapshot(metadata) + return a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()) +} + +// watchPendingAPIRenew 负责watchPendingAPIRenew相关处理。 +func (c *credentialCoordinator) watchPendingAPIRenew(parent context.Context, result *renew.Result) { + // a 是本凭证协调器绑定的账号 facade,提供生命周期任务登记。 + a := c.account + a.pendingRenewal.watch(parent, a.beginTask, a.lifecycle.finishTask, result, a.persistPendingRenewCookies, a.logger) +} + +// persistPendingRenewCookies 负责persistPendingRenewCookies相关处理。 +func (c *credentialCoordinator) persistPendingRenewCookies(ctx context.Context, result *renew.Result) error { + // a 是本凭证协调器绑定的账号 facade,提供凭证存储与脱敏日志。 + a := c.account + if result == nil || len(result.SetCookies) == 0 || a.store == nil || a.store.Cookies == nil { + return nil + } + // releaseRefreshGate 释放迟到 Cookie 收口占用的刷新通道令牌。 + releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx) + if gateErr != nil { + return gateErr + } + defer releaseRefreshGate() + // credentialUnlock 保存credentialUnlock,供当前处理流程使用 + credentialUnlock := a.store.LockAccountCredentials(a.CookieID) + // credentialLocked 表示延迟清理是否仍拥有数据库凭证锁。 + credentialLocked := true + defer func() { + if credentialLocked { + credentialUnlock() + } + }() + runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含迟到续期合并所需的 Cookie 与 metadata。 + if err != nil { + return err + } + // runtimeData 已在凭证锁内读取,避免迟到响应覆盖并发写入的最新凭证状态。 + // RebaseResponseCookies 继续根据当前 Cookie 与 metadata 重放 Set-Cookie。 + // 下面的 UpdateRenewalCookie、运行时状态和通知顺序保持原有行为。 + // newCookies、metadata、changed 保存newCookies、metadata、changed,供当前处理流程使用 + newCookies, metadata, changed := renew.RebaseResponseCookies(runtimeData.Value, runtimeData.MetadataJSON, result) + if !changed { + return nil + } + if // err 保存err,供当前处理流程使用 + err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()); err != nil { + return err + } + a.replaceCredentialState(newCookies, credentialStateFingerprint(newCookies, metadata)) + a.clearTokenCache(ctx) + // Handler 回调可以执行网络通知,必须在释放数据库凭证锁后进行。 + credentialUnlock() + credentialLocked = false + a.notifyCredentialUpdated(ctx) + a.logger.Info("已异步接收官网静默续期迟到 Cookie", "updated", strings.Join(result.UpdatedCookieNames, ",")) + return nil +} + +// adoptRecoveredCookie 统一接收“轻量检查/接口续期”拿到的新 Cookie。 +// 官网页面在普通 Set-Cookie 更新后保持当前 FishEngine/device ID 与健康 WS; +// 下一次重连才使用新 Cookie 获取新的连接级 accessToken。 +// adoptRecoveredCookie 负责adoptRecovered登录凭证相关处理。 +func (c *credentialCoordinator) adoptRecoveredCookie(ctx context.Context, newCookies, source string) bool { + // a 是本凭证协调器绑定的账号 facade,提供当前凭证状态与状态通知。 + a := c.account + if strings.TrimSpace(newCookies) == "" { + return false + } + a.mu.Lock() + // oldCookies 保存oldCookies,供当前处理流程使用 + oldCookies := a.CookieStr + a.mu.Unlock() + if newCookies == oldCookies { + return false + } + if a.store != nil && a.store.Cookies != nil { + if // err 保存err,供当前处理流程使用 + err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, newCookies); err != nil { + a.logger.Error(source+"后保存 cookie 失败", "cookie_id", a.CookieID, "err", err) + return false + } + } + a.replaceCookieStr(newCookies) + a.clearCurrentToken() + a.clearTokenCache(ctx) + a.setRuntimeState(RuntimeConnecting, source+"已更新登录凭证,正在重新连接") + a.notifyCredentialUpdated(ctx) + return true +} + +// notifyCredentialUpdated 负责notifyCredentialUpdated相关处理。 +func (c *credentialCoordinator) notifyCredentialUpdated(ctx context.Context) { + // a 是本凭证协调器绑定的账号 facade;调用点已经完成凭证锁释放。 + a := c.account + if // handler、ok 保存handler、ok,供当前处理流程使用 + handler, ok := a.handler.(credentialUpdateHandler); ok { + handler.OnCredentialUpdated(ctx, a.CookieID) + } +} + +// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。 +// 成功时记录 token 的服务端过期时间并保持 device_id 持久化,但连接流程 +// 不会复用该 token;下一次 loginV2/reConnect 仍会重新调用本方法。 +// refreshToken 负责refresh令牌相关处理。 +func (c *credentialCoordinator) refreshToken(ctx context.Context) (string, string, error) { + // a 是本凭证协调器绑定的账号 facade,保留连接流程使用的返回契约。 + a := c.account + return a.refreshTokenWithMinGap(ctx, false) +} + +// refreshTokenWithMinGap 保留旧签名以避免影响调用方;参考实现没有额外的一分钟 +// Token 防抖,因此 enforceMinGap 不参与行为。 +// refreshTokenWithMinGap 负责refresh令牌WithMinGap相关处理。 +func (c *credentialCoordinator) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) { + // a 是本凭证协调器绑定的账号 facade,集中访问 MTOP、Cookie repository 和状态。 + a := c.account + // releaseRefreshGate 释放 Token 刷新占用的通道令牌。 + releaseRefreshGate, gateErr := a.acquireRefreshGate(ctx) + if gateErr != nil { + return "", "", gateErr + } + defer releaseRefreshGate() + // credentialUnlock 保存credentialUnlock,供当前处理流程使用 + credentialUnlock := func() {} + // credentialLocked 标识当前调用是否持有账号凭证锁。 + credentialLocked := false + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + credentialLocked = true + } + defer func() { + if credentialLocked { + credentialUnlock() + } + }() + + // refreshGate 串行化完整 Token/Cookie 更新事务;风控失败冷却仍由调用方状态控制。 + if // remaining 保存remaining,供当前处理流程使用 + remaining := a.tokenCaptchaCooldownRemaining(); remaining > 0 { + a.setLastTokenStatus(tokenRefreshSkippedCooldown) + return "", "", fmt.Errorf("%w,剩余 %s", errTokenCaptchaCooldown, remaining.Round(time.Second)) + } + + a.reloadCookieFromDB(ctx) + + a.mu.Lock() + // cookieStr 保存登录凭证Str,供当前处理流程使用 + cookieStr := a.CookieStr + // metadataJSON 保存当前凭证快照对应的 metadata。 + metadataJSON := "" + a.lastTokenRefresh = time.Now() + a.lastTokenStatus = tokenRefreshStarted + a.mu.Unlock() + + // deviceID 保存deviceID,供当前处理流程使用 + deviceID := strings.TrimSpace(a.deviceID) + if deviceID == "" { + if // unb 保存unb,供当前处理流程使用 + unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" { + deviceID = protocol.GenerateDeviceID(unb) + a.mu.Lock() + a.deviceID = deviceID + a.mu.Unlock() + } + } + if a.store != nil && a.store.Cookies != nil { + // runtimeData 保存 Token 请求开始前的最小凭证快照。 + runtimeData, detailErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) + if detailErr != nil { + return "", "", detailErr + } + cookieStr = runtimeData.Value + metadataJSON = runtimeData.MetadataJSON + } + // Token 网络请求和风控恢复都必须在共享凭证锁外执行。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + for // captchaRetry 保存captcha重试,供当前处理流程使用 + captchaRetry := 0; captchaRetry < 3; captchaRetry++ { + // res 保存响应,供当前处理流程使用 + var res *mtop.RefreshResult + // err 保存err,供当前处理流程使用 + var err error + if // scoped、ok 保存scoped、ok,供当前处理流程使用 + scoped, ok := a.mtop.(scopedTokenClient); ok { + // snapshot 保存snapshot,供当前处理流程使用 + var snapshot []cookierefresh.BrowserCookie + if a.store != nil && a.store.Cookies != nil { + if metadata, metadataErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID); metadataErr == nil { // metadata 是 token 请求所需的 Cookie 快照信息。 + snapshot = cookierefresh.SnapshotFromMetadata(metadata) + } + } + res, err = scoped.RefreshTokenWithCredentialContext(ctx, cookieStr, deviceID, snapshot) + } else { + res, err = a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID) + } + if a.store != nil && a.store.Cookies != nil { + // credentialUnlock 保存 Token 响应提交临界区的释放函数。 + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + credentialLocked = true + // latestRuntimeData 和 reloadErr 保存网络请求完成后的最新凭证视图及重读错误。 + latestRuntimeData, reloadErr := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) + if reloadErr != nil { + a.setLastTokenStatus(tokenRefreshFailedAPI) + a.clearCurrentToken() + return "", "", reloadErr + } + if latestRuntimeData.Value != cookieStr || latestRuntimeData.MetadataJSON != metadataJSON { + // 并发流程已经更新凭证,丢弃旧请求的 Token 和 Cookie 响应,下一轮使用最新快照重试。 + cookieStr = latestRuntimeData.Value + metadataJSON = latestRuntimeData.MetadataJSON + credentialUnlock() + credentialLocked = false + continue + } + } + // 参考实现无论业务结果为何,都先合并响应 Set-Cookie。本地还必须先把 + // 完整 Jar 持久化成功,避免当前 /reg 成功而下次重连回滚到旧凭证。 + // 响应处理会广播给 Handler,因此先释放凭证锁,成功 Token 绑定前会重新校验。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + // persistErr 保存persistErr,供当前处理流程使用 + var persistErr error + cookieStr, persistErr = a.adoptTokenResponseCookies(ctx, cookieStr, res) + if persistErr != nil { + a.setLastTokenStatus(tokenRefreshFailedAPI) + a.clearCurrentToken() + return "", "", fmt.Errorf("保存 token 响应 Cookie: %w", persistErr) + } + if err != nil && mtop.IsRiskVerificationErr(err) { + // 风控恢复是外部调用,不能在共享凭证锁内执行。 + if credentialLocked { + credentialUnlock() + credentialLocked = false + } + if // recovered、ok 保存recovered、ok,供当前处理流程使用 + recovered, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, deviceID, err); ok { + cookieStr = recovered.UpdatedCookies + // 重取地址时即使拿到了 accessToken,参考实现也不会直接采用; + // 它会清缓存后重新走一次标准 token 请求。 + continue + } + a.markTokenCaptchaFailure() + a.setLastTokenStatus(tokenRefreshFailedCaptcha) + a.clearCurrentToken() + a.clearTokenCache(ctx) + return "", "", err + } + if err != nil { + // status 保存状态,供当前处理流程使用 + status := classifyTokenFailure(err) + a.setLastTokenStatus(status) + a.clearCurrentToken() + if status != tokenRefreshFailedNetwork && status != tokenRefreshFailedTimeout { + a.clearTokenCache(ctx) + } + return "", "", err + } + if res == nil || strings.TrimSpace(res.AccessToken) == "" { + a.setLastTokenStatus(tokenRefreshFailedAPI) + a.clearCurrentToken() + a.clearTokenCache(ctx) + return "", "", fmt.Errorf("token API 未返回结果") + } + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + credentialLocked = true + } + // credentialFP、fingerprintErr 保存credentialFP、fingerprintErr,供当前处理流程使用 + credentialFP, fingerprintErr := a.databaseCredentialFingerprint(ctx, cookieStr) + if fingerprintErr != nil { + a.setLastTokenStatus(tokenRefreshFailedAPI) + a.clearCurrentToken() + a.clearTokenCache(ctx) + return "", "", fmt.Errorf("绑定 token 凭证状态: %w", fingerprintErr) + } + a.saveTokenCache(ctx, deviceID, res.AccessToken, res.AccessTokenExpireAt, credentialFP) + a.mu.Lock() + a.credentialFP = credentialFP + a.tokenCredentialFP = credentialFP + a.lastCaptchaFailure = time.Time{} + a.tokenFetchFailures = 0 + a.lastTokenStatus = tokenRefreshSuccess + a.mu.Unlock() + a.runtimeMu.Lock() + a.lastMsgReceived = time.Time{} + a.runtimeMu.Unlock() + return res.AccessToken, cookieStr, nil + } + + a.setLastTokenStatus(tokenRefreshFailedCaptcha) + a.clearCurrentToken() + a.clearTokenCache(ctx) + return "", "", fmt.Errorf("滑块验证重试次数已达上限") +} + +// clearCurrentToken 负责clearCurrent令牌相关处理。 +func (c *credentialCoordinator) clearCurrentToken() { + // a 是本凭证协调器绑定的账号 facade,持有 Token 状态锁。 + a := c.account + a.mu.Lock() + a.currentToken = "" + a.tokenCredentialFP = "" + a.mu.Unlock() +} + +// adoptTokenResponseCookies 负责adopt令牌响应Cookies相关处理。 +func (c *credentialCoordinator) adoptTokenResponseCookies(ctx context.Context, cookieStr string, res *mtop.RefreshResult) (string, error) { + // a 是本凭证协调器绑定的账号 facade,提供 Cookie 持久化与回调端口。 + a := c.account + if res == nil { + return cookieStr, nil + } + if !res.CookieSnapshotComplete && !res.CookieStateChanged && strings.TrimSpace(res.UpdatedCookies) == "" { + return cookieStr, nil + } + if !res.CookieSnapshotComplete && !res.CookieStateChanged && res.UpdatedCookies == cookieStr && len(res.CookieSnapshot) == 0 { + return cookieStr, nil + } + if a.store != nil && a.store.Cookies != nil { + metadata, detailErr := a.store.Cookies.GetCookieMetadata(ctx, a.CookieID) // metadata 只包含 token 响应 Cookie 合并所需的快照信息。 + if detailErr != nil { + return cookieStr, detailErr + } + // metadata 已在 repository 层按账号作用域解密,不读取旧 Cookie 或登录秘密。 + // 下面继续根据响应类型合并已有快照,并由 UpdateRenewalCookie 统一持久化。 + // 错误返回和运行时状态更新顺序保持原有 token 响应语义。 + // 只有 token 响应本身发生变化时才进入后续快照合并逻辑。 + if res.CookieSnapshotComplete { + // snapshot 保存snapshot,供当前处理流程使用 + snapshot := cookierefresh.NormalizeSnapshot(res.CookieSnapshot) + if snapshot == nil { + snapshot = []cookierefresh.BrowserCookie{} + } + metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) + } else if // snapshot、snapshotOK 保存snapshot、snapshotOK,供当前处理流程使用 + snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(metadata); snapshotOK { + // 扁平结果不能凭空证明 Jar 完整;仅在已有权威 Jar 时按已知 + // Domain/Path 身份对值做兼容合并。 + snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies) + metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot) + } else { + metadata = cookierefresh.MetadataWithoutSnapshot(metadata) + } + if // err 保存err,供当前处理流程使用 + err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil { + return cookieStr, err + } + a.replaceCredentialState(res.UpdatedCookies, credentialStateFingerprint(res.UpdatedCookies, metadata)) + a.notifyCredentialUpdated(ctx) + return res.UpdatedCookies, nil + } + if res.UpdatedCookies != cookieStr { + a.replaceCookieStr(res.UpdatedCookies) + } + return res.UpdatedCookies, nil +} + +// tryTokenCaptchaRecovery 负责try令牌CaptchaRecovery相关处理。 +func (c *credentialCoordinator) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, deviceID string, err error) (*mtop.RefreshResult, bool) { + // a 是本凭证协调器绑定的账号 facade,提供风控 Handler 与运行时状态。 + a := c.account + // h、ok 保存h、ok,供当前处理流程使用 + h, ok := a.handler.(tokenCaptchaHandler) + if !ok { + return nil, false + } + // riskErr 保存riskErr,供当前处理流程使用 + var riskErr *mtop.RiskVerificationError + if !errors.As(err, &riskErr) || strings.TrimSpace(riskErr.VerificationURL) == "" { + return nil, false + } + a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求滑块验证", + "token 刷新触发闲鱼风控验证,系统将尝试自动完成滑块并合并 x5sec。") + // result、ok 保存result、ok,供当前处理流程使用 + result, ok := h.OnTokenCaptchaVerification(ctx, a.CookieID, cookieStr, riskErr.VerificationURL, deviceID) + if !ok || result == nil || strings.TrimSpace(result.UpdatedCookies) == "" { + return nil, false + } + // updatedCookies、persistErr 保存updatedCookies、persistErr,供当前处理流程使用 + updatedCookies, persistErr := a.adoptTokenResponseCookies(ctx, cookieStr, result) + if persistErr != nil { + a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", persistErr) + return nil, false + } + result.UpdatedCookies = updatedCookies + a.replaceCookieStr(updatedCookies) + a.clearTokenCache(ctx) + a.setRuntimeState(RuntimeConnecting, tokenRiskRecoveryMessage) + return result, true +} + +// markTokenCaptchaFailure 负责mark令牌CaptchaFailure相关处理。 +func (c *credentialCoordinator) markTokenCaptchaFailure() { + // a 是本凭证协调器绑定的账号 facade,持有风控冷却状态。 + a := c.account + a.mu.Lock() + a.lastCaptchaFailure = time.Now() + a.mu.Unlock() +} + +// tokenCaptchaCooldownRemaining 负责令牌CaptchaCooldownRemaining相关处理。 +func (c *credentialCoordinator) tokenCaptchaCooldownRemaining() time.Duration { + // a 是本凭证协调器绑定的账号 facade,持有风控冷却状态。 + a := c.account + a.mu.Lock() + // lastFailure 保存lastFailure,供当前处理流程使用 + lastFailure := a.lastCaptchaFailure + a.mu.Unlock() + if lastFailure.IsZero() { + return 0 + } + // remaining 保存remaining,供当前处理流程使用 + remaining := TokenCaptchaFailureCooldown - time.Since(lastFailure) + if remaining < 0 { + return 0 + } + return remaining +} + +// saveTokenCache records the server expiry and current page-runtime identity. +// It is diagnostic state only: acquireToken never reads the accessToken back +// for a later WebSocket registration. +// saveTokenCache 负责save令牌Cache相关处理。 +func (c *credentialCoordinator) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, credentialFP string) { + // a 是本凭证协调器绑定的账号 facade,提供 Token repository 与诊断日志。 + a := c.account + if accessToken == "" { + return + } + // now 保存now,供当前处理流程使用 + now := time.Now() + // expiresAt、refreshAt 保存expiresAt、refreshAt,供当前处理流程使用 + expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now) + // tokenFP 保存令牌FP,供当前处理流程使用 + tokenFP := tokenFingerprint(accessToken) + a.mu.Lock() + // previousTokenFP 保存previous令牌FP,供当前处理流程使用 + previousTokenFP := a.tokenFingerprint + a.tokenFingerprint = tokenFP + a.tokenAcquiredAt = now + a.tokenExpiresAt = expiresAt + a.tokenRefreshAt = refreshAt + a.mu.Unlock() + a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP) + if a.store == nil || a.store.Tokens == nil { + return + } + // expireAt 保存expireAt,供当前处理流程使用 + expireAt := effectiveTokenExpireAt(serverExpireAt, now) + if expireAt == 0 { + // 服务端未给有效期时仍使用保守运行时轮换时间,但不把推测期限 + // 伪装成服务端缓存期限。 + a.logger.Warn("token API 未返回可用过期时间,使用保守轮换时间", "refresh_at", refreshAt) + a.clearTokenCache(ctx) + return + } + if // err 保存err,供当前处理流程使用 + err := a.store.Tokens.SaveBound(ctx, a.CookieID, deviceID, accessToken, expireAt, credentialFP); err != nil { + a.logger.Warn("缓存 accessToken 失败", "err", err) + } +} + +// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token, +// 同时避免日志泄露可用于 WS 注册的凭证原文。 +// tokenFingerprint 负责令牌Fingerprint相关处理。 +func tokenFingerprint(token string) string { + // sum 保存sum,供当前处理流程使用 + sum := sha256.Sum256([]byte(token)) + return fmt.Sprintf("%x", sum[:6]) +} + +// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。 +func (c *credentialCoordinator) clearTokenCache(ctx context.Context) { + // a 是本凭证协调器绑定的账号 facade,提供 Token repository 与内存状态。 + a := c.account + a.mu.Lock() + a.tokenFingerprint = "" + a.mu.Unlock() + if a.store == nil || a.store.Tokens == nil { + return + } + if // err 保存err,供当前处理流程使用 + err := a.store.Tokens.Clear(ctx, a.CookieID); err != nil { + a.logger.Warn("清除 token 缓存失败", "err", err) + } +} + +// databaseCredentialFingerprint returns the complete DB credential state that +// produced cookieStr. It must be called while the account credential lock is +// held when a Store is present. +// databaseCredentialFingerprint 负责databaseCredentialFingerprint相关处理。 +func (c *credentialCoordinator) databaseCredentialFingerprint(ctx context.Context, cookieStr string) (string, error) { + // a 是本凭证协调器绑定的账号 facade,提供当前账号的窄凭证查询端口。 + a := c.account + if a.store == nil || a.store.Cookies == nil { + return credentialStateFingerprint(cookieStr, ""), nil + } + runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 token 凭证一致性校验所需的 Cookie 与 metadata。 + if err != nil { + return "", err + } + // runtimeData 已在调用方凭证锁内读取,避免校验期间混入另一笔 Cookie 更新。 + // Cookie 与 metadata 均由 repository 按账号作用域解密,登录密码不会进入此流程。 + // 后续空值判断、指纹比较和错误文案保持原有 token 绑定语义。 + // snapshotComplete 保存snapshotComplete,供当前处理流程使用 + _, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON) + if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete { + return "", fmt.Errorf("数据库 Cookie 为空且没有权威 Jar") + } + if credentialCookieFingerprint(runtimeData.Value) != credentialCookieFingerprint(cookieStr) { + return "", fmt.Errorf("token 请求期间数据库 Cookie 已变化") + } + return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON), nil +} + +// reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存。普通 Cookie +// 更新不轮换页面生命周期内的 device ID;显式登录由 Manager 重建 Account。 +// reloadCookieFromDB 负责reload登录凭证FromDB相关处理。 +func (c *credentialCoordinator) reloadCookieFromDB(ctx context.Context) bool { + // a 是本凭证协调器绑定的账号 facade,提供运行时状态与 Cookie repository。 + a := c.account + if a.store == nil || a.store.Cookies == nil { + return false + } + runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含检测外部凭证更新所需的 Cookie 与 metadata。 + if err != nil { + return false + } + if strings.TrimSpace(runtimeData.Value) == "" { + if // complete 保存complete,供当前处理流程使用 + _, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete { + return false + } + } + // databaseFP 保存databaseFP,供当前处理流程使用 + databaseFP := credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON) + a.mu.Lock() + // currentFP 保存currentFP,供当前处理流程使用 + currentFP := a.credentialFP + if currentFP == "" { + currentFP = credentialStateFingerprint(a.CookieStr, "") + } + a.mu.Unlock() + if databaseFP == currentFP { + return false + } + a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID) + a.replaceCredentialState(runtimeData.Value, databaseFP) + a.clearCurrentToken() + a.clearTokenCache(ctx) + a.mu.Lock() + a.lastCaptchaFailure = time.Time{} + a.mu.Unlock() + return true +} + +// cookieSnapshotMatchesDB 负责登录凭证SnapshotMatchesDB相关处理。 +func (c *credentialCoordinator) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string) bool { + // a 是本凭证协调器绑定的账号 facade,提供 WS 注册前的窄凭证查询端口。 + a := c.account + if a.store == nil || a.store.Cookies == nil { + return true + } + runtimeData, err := a.store.Cookies.GetCookieRuntimeData(ctx, a.CookieID) // runtimeData 只包含 WS 注册前凭证一致性校验所需的 Cookie 与 metadata。 + if err != nil { + a.logger.Warn("WS 注册前读取最新 Cookie 失败,放弃本次连接", "err", err) + return false + } + // snapshotComplete 保存snapshotComplete,供当前处理流程使用 + _, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON) + if strings.TrimSpace(runtimeData.Value) == "" && !snapshotComplete { + a.logger.Warn("WS 注册前最新 Cookie 为空且没有权威 Jar,放弃本次连接") + return false + } + if expectedFP == "" { + a.logger.Warn("WS 注册 token 缺少绑定的凭证状态,放弃本次连接") + return false + } + return credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON) == expectedFP +} + +// replaceCookieStr 负责replace登录凭证Str相关处理。 +func (c *credentialCoordinator) replaceCookieStr(cookieStr string) { + // a 是本凭证协调器绑定的账号 facade,持有运行时 Cookie 状态。 + a := c.account + a.replaceCredentialState(cookieStr, credentialStateFingerprint(cookieStr, "")) +} + +// replaceCredentialState 负责replaceCredential状态相关处理。 +func (c *credentialCoordinator) replaceCredentialState(cookieStr, credentialFP string) { + // a 是本凭证协调器绑定的账号 facade,持有凭证状态锁与用户身份快照。 + a := c.account + a.mu.Lock() + defer a.mu.Unlock() + a.CookieStr = cookieStr + a.credentialFP = credentialFP + if // unb 保存unb,供当前处理流程使用 + unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" { + a.UserID = unb + } +} + +// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。 +func (c *credentialCoordinator) updateCookie(cookieStr string) { + // a 是本凭证协调器绑定的账号 facade,提供权威 Cookie repository 与刷新门。 + a := c.account + if strings.TrimSpace(cookieStr) == "" && (a.store == nil || a.store.Cookies == nil) { + return + } + // releaseRefreshGate 释放运行时 Cookie 同步占用的通道令牌。 + releaseRefreshGate, gateErr := a.acquireRefreshGate(context.Background()) + if gateErr != nil { + a.logger.Warn("同步运行时 Cookie 时刷新通道被取消", "err", gateErr) + return + } + defer releaseRefreshGate() + // credentialUnlock 保存credentialUnlock,供当前处理流程使用 + credentialUnlock := func() {} + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + } + defer credentialUnlock() + // 外部调用通常发生在一次网络请求写回之后。调用排队期间可能已有更新的 + // Cookie 落库,因此参数只作为无 Store 场景的兼容值;有 Store 时始终 + // 复读权威数据库,绝不把较旧的请求结果重新写回运行时。 + // metadataJSON 保存metadataJSON,供当前处理流程使用 + metadataJSON := "" + if a.store != nil && a.store.Cookies != nil { + runtimeData, err := a.store.Cookies.GetCookieRuntimeData(context.Background(), a.CookieID) // runtimeData 只包含同步运行时 Cookie 所需的 Cookie 与 metadata。 + if err != nil { + a.logger.Warn("同步运行时 Cookie 前读取数据库失败", "err", err) + return + } + if strings.TrimSpace(runtimeData.Value) == "" { + if // complete 保存complete,供当前处理流程使用 + _, complete := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); !complete { + a.logger.Warn("同步运行时 Cookie 时数据库值为空且无权威 Jar") + return + } + } + cookieStr = runtimeData.Value + metadataJSON = runtimeData.MetadataJSON + } + // credentialFP 保存credentialFP,供当前处理流程使用 + credentialFP := credentialStateFingerprint(cookieStr, metadataJSON) + a.mu.Lock() + // changed 保存changed,供当前处理流程使用 + changed := credentialFP != a.credentialFP + a.mu.Unlock() + if !changed { + return + } + a.replaceCredentialState(cookieStr, credentialFP) + // Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie + // 会在下一次自然重连前被重新读取并用于获取新的 accessToken。 + a.clearTokenCache(context.Background()) +} diff --git a/internal/engine/credential_coordinator_test.go b/internal/engine/credential_coordinator_test.go index 7fbbf5b..b8e4ffb 100644 --- a/internal/engine/credential_coordinator_test.go +++ b/internal/engine/credential_coordinator_test.go @@ -12,6 +12,21 @@ import ( "xianyu-go/internal/xianyu/renew" ) +// blockingCredentialUpdateHandler 在凭证更新通知中阻塞,用于探测通知期间是否仍持有数据库凭证锁。 +type blockingCredentialUpdateHandler struct { + recordingHandler + // started 表示凭证通知已经进入可扩展 Handler。 + started chan struct{} + // release 允许测试结束通知回调。 + release chan struct{} +} + +// OnCredentialUpdated 阻塞凭证通知,模拟真实通知器可能进行的慢速外部 I/O。 +func (h *blockingCredentialUpdateHandler) OnCredentialUpdated(context.Context, string) { + close(h.started) + <-h.release +} + // blockingTokenMtop 在 Token 请求期间阻塞,用于验证 Engine 不跨越网络 I/O 持有凭证锁。 type blockingTokenMtop struct { fakeRunMtop @@ -23,6 +38,70 @@ type blockingTokenMtop struct { calls atomic.Int32 } +// TestRefreshGateAcquireHonorsContext 验证等待中的续期不会阻塞账号停止流程。 +func TestRefreshGateAcquireHonorsContext(t *testing.T) { + // state 是持有单令牌刷新通道的最小凭证状态。 + state := credentialState{refreshGate: newRefreshGate()} + // release 是第一个续期所有者归还通道令牌的释放函数。 + release, acquireErr := state.acquireRefreshGate(context.Background()) + if acquireErr != nil { + t.Fatalf("取得初始刷新通道: %v", acquireErr) + } + defer release() + // ctx、cancel 表示等待第二次续期时由账号停止触发的取消信号。 + ctx, cancel := context.WithCancel(context.Background()) + cancel() + // blockedRelease、blockedErr 保存已取消等待的返回结果。 + blockedRelease, blockedErr := state.acquireRefreshGate(ctx) + if blockedRelease != nil || blockedErr != context.Canceled { + t.Fatalf("已取消的刷新通道等待结果 release=%v err=%v", blockedRelease != nil, blockedErr) + } +} + +// TestPendingRenewNotificationRunsOutsideCredentialLock 验证迟到续期通知在锁外执行。 +func TestPendingRenewNotificationRunsOutsideCredentialLock(t *testing.T) { + // acc、store、cleanup 是待验证凭证通知锁边界的账号、数据库和清理函数。 + acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "token"}) + defer cleanup() + // handler 是会阻塞通知的可扩展回调实现。 + handler := &blockingCredentialUpdateHandler{started: make(chan struct{}), release: make(chan struct{})} + acc.handler = handler + // finished 表示迟到续期持久化及通知调用结束。 + finished := make(chan struct{}) + go func() { + // persistErr 是迟到续期写回失败原因。 + persistErr := acc.persistPendingRenewCookies(context.Background(), &renew.Result{SetCookies: []string{"late=1; Path=/"}}) + if persistErr != nil { + t.Errorf("迟到续期写回失败: %v", persistErr) + } + close(finished) + }() + select { + case <-handler.started: + case <-time.After(time.Second): + t.Fatal("凭证更新通知未开始") + } + // acquired 表示通知阻塞期间另一个流程取得并释放了同账号凭证锁。 + acquired := make(chan struct{}) + go func() { + // unlock 释放探测流程取得的凭证锁。 + unlock := store.LockAccountCredentials(acc.CookieID) + unlock() + close(acquired) + }() + select { + case <-acquired: + case <-time.After(300 * time.Millisecond): + t.Fatal("凭证更新通知仍持有数据库凭证锁") + } + close(handler.release) + select { + case <-finished: + case <-time.After(time.Second): + t.Fatal("迟到续期通知未结束") + } +} + // RefreshTokenWithDeviceIDContext 阻塞第一个请求并返回成功 Token。 func (c *blockingTokenMtop) RefreshTokenWithDeviceIDContext(ctx context.Context, _ string, _ string) (*mtop.RefreshResult, error) { // callNumber 是当前 Token 请求序号。 @@ -49,6 +128,26 @@ type blockingStatusMtop struct { result *mtop.LoginStatusResult } +// blockingRegisterConn 在 WebSocket 注册期间阻塞,用于验证注册网络 I/O 不持有凭证锁。 +type blockingRegisterConn struct { + fakeWSConn + // started 通知注册外部调用已经开始。 + started chan struct{} + // release 允许注册外部调用返回。 + release chan struct{} +} + +// Register 阻塞到测试显式释放后完成注册。 +func (c *blockingRegisterConn) Register(ctx context.Context, _, _ string) error { + close(c.started) + select { + case <-c.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + // CheckLoginStatusContext 阻塞到测试显式释放后返回登录态结果。 func (c *blockingStatusMtop) CheckLoginStatusContext(ctx context.Context, _ string) (*mtop.LoginStatusResult, error) { close(c.started) @@ -245,3 +344,50 @@ func TestRefreshTokenReleasesCredentialLockAndRetriesAfterConcurrentUpdate(t *te t.Fatalf("并发 Cookie 未保留: value=%q err=%v", saved, savedErr) } } + +// TestRegisterConnectionReleasesCredentialLockBeforeExternalIO 验证 WebSocket Register 在锁外执行。 +func TestRegisterConnectionReleasesCredentialLockBeforeExternalIO(t *testing.T) { + // acc、store、cleanup 是待验证 Engine 连接注册行为的账号、数据库和清理函数。 + acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "token"}) + defer cleanup() + // runtimeData 保存注册前的权威凭证快照。 + runtimeData, err := store.Cookies.GetCookieRuntimeData(context.Background(), acc.CookieID) + if err != nil { + t.Fatal(err) + } + // conn 保存可控阻塞的 WebSocket 连接。 + conn := &blockingRegisterConn{started: make(chan struct{}), release: make(chan struct{})} + // result 保存注册边界的最终结果。 + result := make(chan registerConnectionResult, 1) + go func() { + result <- acc.registerConnection(context.Background(), conn, acc.deviceID, "token", credentialStateFingerprint(runtimeData.Value, runtimeData.MetadataJSON)) + }() + select { + case <-conn.started: + case <-time.After(time.Second): + t.Fatal("WebSocket Register 未开始") + } + // acquired 表示另一个流程已经成功获取并释放同账号凭证锁。 + acquired := make(chan struct{}) + go func() { + // unlock 释放探测流程取得的账号凭证锁。 + unlock := store.LockAccountCredentials(acc.CookieID) + unlock() + close(acquired) + }() + select { + case <-acquired: + case <-time.After(300 * time.Millisecond): + t.Fatal("WebSocket Register 外部调用仍持有账号凭证锁") + } + close(conn.release) + select { + // registered 保存 WebSocket 注册边界的结果快照。 + case registered := <-result: + if !registered.Registered || registered.Err != nil { + t.Fatalf("注册结果异常: %+v", registered) + } + case <-time.After(time.Second): + t.Fatal("注册边界未完成") + } +} diff --git a/internal/engine/credential_state.go b/internal/engine/credential_state.go index 6e599c0..e334884 100644 --- a/internal/engine/credential_state.go +++ b/internal/engine/credential_state.go @@ -1,20 +1,20 @@ package engine import ( + "context" "sync" "time" ) // credentialState 保存账号 Cookie、Token、设备指纹和刷新诊断状态。 // mu 保护本组件全部字段;持锁时不得执行数据库、网络或通知 I/O。 -// refreshMu 串行化完整的凭证刷新事务,允许在锁内执行必要的凭证 I/O, -// 但调用方不得在持有它时再次获取同一锁。 +// refreshGate 通过带令牌的通道串行化完整刷新流程,等待外部 I/O 时不持有互斥锁。 // credentialState 保存credential状态,供当前处理流程使用 type credentialState struct { // mu 保护 Cookie、Token、设备指纹和刷新诊断字段。 mu sync.Mutex - // refreshMu 串行化 Cookie 读取、Token 刷新和缓存清理事务。 - refreshMu sync.Mutex + // refreshGate 串行化 Cookie 读取、Token 刷新和缓存清理事务;通道令牌代表刷新所有权。 + refreshGate chan struct{} // CookieStr 是当前运行时使用的扁平 Cookie 快照。 CookieStr string @@ -45,3 +45,35 @@ type credentialState struct { // tokenFingerprint 是 Token 的不可逆诊断指纹,不保存 Token 原文。 tokenFingerprint string } + +// newRefreshGate 创建带有初始令牌的账号刷新通道。 +func newRefreshGate() chan struct{} { + // gate 保存刷新流程的单令牌通道。 + gate := make(chan struct{}, 1) + gate <- struct{}{} + return gate +} + +// acquireRefreshGate 获取账号刷新流程的独占通道令牌。等待期间会响应 ctx 取消, +// 因此停止账号不会被另一个尚未完成的续期流程无限阻塞。 +func (s *credentialState) acquireRefreshGate(ctx context.Context) (func(), error) { + if ctx == nil { + // ctx 使用 Background 保持历史未传取消信号调用方的可用性。 + ctx = context.Background() + } + s.mu.Lock() + if s.refreshGate == nil { + s.refreshGate = make(chan struct{}, 1) + s.refreshGate <- struct{}{} + } + // gate 保存初始化后可在外部等待的刷新令牌通道。 + gate := s.refreshGate + s.mu.Unlock() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-gate: + // release 把令牌归还给同一个固定通道;调用者必须在所有提交路径上执行它。 + return func() { gate <- struct{}{} }, nil + } +} diff --git a/internal/engine/outgoing_message_coordinator.go b/internal/engine/outgoing_message_coordinator.go new file mode 100644 index 0000000..14ae667 --- /dev/null +++ b/internal/engine/outgoing_message_coordinator.go @@ -0,0 +1,165 @@ +package engine + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "xianyu-go/internal/automation" + "xianyu-go/internal/xianyu/protocol" +) + +// outgoingMessageCoordinator 拥有当前连接上的出站消息、聊天历史和会话查询边界。 +// 它只在锁内读取 WebSocket 与账号身份快照,任何发送或查询 I/O 都在锁外执行。 +type outgoingMessageCoordinator struct { + // account 是构造完成后固定的账号 facade,提供连接状态和出站旁路观察器。 + account *Account +} + +// sendText 使用当前已注册 WebSocket 发送文本,并在平台接受后通知可选的聊天旁路。 +// ctx 是调用方取消边界;chatID、toUserID 与 text 共同确定一次出站消息;错误保持原调用方语义。 +func (c *outgoingMessageCoordinator) sendText(ctx context.Context, chatID, toUserID, text string) error { + // a 是当前协调器绑定的账号 facade;它在 New 中写入且之后不可替换。 + a := c.account + if a == nil { + return errors.New("账号出站消息协调器未初始化") + } + text = strings.TrimSpace(text) + if text == "" { + return nil + } + // conn、myID、err 保存锁外发送所需的连接与账号身份快照,以及读取失败原因。 + conn, myID, err := c.currentSenderState() + if err != nil { + return err + } + // sendCtx、cancel 限制单次文本发送的最长等待,并在函数返回时释放计时器。 + sendCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + // err 是平台文本发送失败原因;此时调用方按是否确定未发送决定重试或人工核对。 + if err := conn.SendText(sendCtx, myID, chatID, toUserID, text); err != nil { + return err + } + // observer、ok 是可选出站旁路观察器及其接口匹配结果;旁路失败不能改变平台发送成功结果。 + if observer, ok := a.handler.(outgoingChatHandler); ok { + // key 是 UI 创建的待发送消息关联键,避免旁路重复插入同一文本。 + key, _ := ctx.Value(outgoingMessageKeyContextKey{}).(string) + // err 是旁路持久化或广播失败原因,仅记录脱敏告警。 + if err := observer.HandleOutgoingChatMessage(ctx, OutgoingChatMessage{ + AccountID: a.CookieID, ChatID: chatID, BuyerID: toUserID, Text: text, MessageKey: key, + }); err != nil { + a.logger.Warn("保存出站聊天旁路失败", "account", a.CookieID, "chat_id", chatID, "err", err) + } + } + return nil +} + +// sendImage 使用当前已注册 WebSocket 发送可直接访问的远程图片。 +// ctx 是调用方取消边界;cardID 仅用于兼容 MessageSender 契约,当前协议发送不直接使用它。 +func (c *outgoingMessageCoordinator) sendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error { + // a 是当前协调器绑定的账号 facade;它用于维持与文本发送一致的初始化检查。 + a := c.account + if a == nil { + return errors.New("账号出站消息协调器未初始化") + } + imageURL = strings.TrimSpace(imageURL) + if imageURL == "" { + return nil + } + if strings.HasPrefix(imageURL, "/static/") || strings.HasPrefix(imageURL, "static/") { + return fmt.Errorf("当前运行时暂不支持本地图片自动上传到闲鱼 CDN: %s", imageURL) + } + // conn、myID、err 保存锁外图片发送所需的连接与账号身份快照,以及读取失败原因。 + conn, myID, err := c.currentSenderState() + if err != nil { + return err + } + // sendCtx、cancel 限制单次图片发送的最长等待,并在函数返回时释放计时器。 + sendCtx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + _ = cardID // cardID 由上层动作检查点持久化,协议图片发送本身不携带该字段。 + return conn.SendImage(sendCtx, myID, chatID, toUserID, imageURL, 800, 600) +} + +// currentSenderState 返回可用 WebSocket 与账号 unb 身份快照;持锁范围只覆盖快照读取。 +func (c *outgoingMessageCoordinator) currentSenderState() (WSConn, string, error) { + // a 是当前协调器绑定的账号 facade;未初始化时不能安全读取连接状态。 + a := c.account + if a == nil { + return nil, "", errors.New("账号出站消息协调器未初始化") + } + a.runtimeMu.Lock() + // conn 是当前连接快照;后续读取账号身份字段使用 Account 自身的凭证锁。 + conn := a.conn + a.runtimeMu.Unlock() + if conn == nil { + return nil, "", fmt.Errorf("%w: 账号 %s 当前没有可用 WebSocket 连接", automation.ErrMessageNotSent, a.CookieID) + } + a.mu.Lock() + // myID 是发送协议所需的当前账号 unb 身份快照。 + myID := strings.TrimSpace(a.UserID) + if myID == "" { + myID = protocol.TransCookies(a.CookieStr)["unb"] + } + a.mu.Unlock() + if myID == "" { + return nil, "", fmt.Errorf("%w: 账号 %s 缺少 unb,无法发送消息", automation.ErrMessageNotSent, a.CookieID) + } + return conn, myID, nil +} + +// fetchChatHistory 使用当前已注册连接查询指定聊天的历史消息。 +// ctx、chatID、cursor 与 limit 直接传给平台连接;返回值保留账号身份快照与原始平台正文。 +func (c *outgoingMessageCoordinator) fetchChatHistory(ctx context.Context, chatID string, cursor int64, limit int) (map[string]any, string, error) { + // conn、myID、err 保存历史查询所需连接、账号身份快照与读取失败原因。 + conn, myID, err := c.currentSenderState() + if err != nil { + return nil, "", err + } + // history、ok 保存连接是否支持历史查询的可选能力及其类型判断结果。 + history, ok := conn.(interface { + ListUserMessages(context.Context, string, int64, int) (map[string]any, error) + }) + if !ok { + return nil, "", errors.New("当前 WebSocket 连接不支持聊天历史") + } + // body、err 保存平台返回的历史正文与查询错误。 + body, err := history.ListUserMessages(ctx, chatID, cursor, limit) + return body, myID, err +} + +// fetchChatConversations 使用当前已注册连接查询历史会话。 +// ctx、cursor 与 limit 直接传给平台连接;返回值保留账号身份快照与原始平台正文。 +func (c *outgoingMessageCoordinator) fetchChatConversations(ctx context.Context, cursor int64, limit int) (map[string]any, string, error) { + // conn、myID、err 保存会话查询所需连接、账号身份快照与读取失败原因。 + conn, myID, err := c.currentSenderState() + if err != nil { + return nil, "", err + } + // fetcher、ok 保存连接是否支持会话查询的可选能力及其类型判断结果。 + fetcher, ok := conn.(interface { + ListConversations(context.Context, int64, int) (map[string]any, error) + }) + if !ok { + return nil, "", errors.New("当前 WebSocket 连接不支持历史会话") + } + // body、err 保存平台返回的会话正文与查询错误。 + body, err := fetcher.ListConversations(ctx, cursor, limit) + return body, myID, err +} + +// automationReady 返回当前 WebSocket 是否已进入 online 状态,供 Automation 在发送前做无 I/O 门禁。 +func (c *outgoingMessageCoordinator) automationReady() bool { + // a 是当前协调器绑定的账号 facade;未初始化协调器不可能提供在线发送能力。 + a := c.account + if a == nil { + return false + } + a.runtimeMu.Lock() + // ready 表示连接存在且状态已进入 online 的瞬时快照。 + ready := a.conn != nil && a.runtimeState == RuntimeOnline + a.runtimeMu.Unlock() + return ready +} diff --git a/internal/engine/pending_renewal.go b/internal/engine/pending_renewal.go new file mode 100644 index 0000000..43d398d --- /dev/null +++ b/internal/engine/pending_renewal.go @@ -0,0 +1,126 @@ +package engine + +import ( + "context" + "log/slog" + "sync" + "time" + + "xianyu-go/internal/xianyu/renew" +) + +// pendingRenewalCoordinator 拥有静默续期迟到响应的后台等待与 Join 生命周期。 +type pendingRenewalCoordinator struct { + // mu 保护 activeTasks 与 done;持锁时只维护任务计数和完成信号,绝不等待外部 I/O。 + mu sync.Mutex + // activeTasks 记录当前仍在等待或持久化迟到续期响应的任务数量。 + activeTasks int + // done 由最后一个已登记任务关闭;等待者只订阅该共享信号,超时返回时不会遗留等待协程。 + done chan struct{} +} + +// beginTask 登记一个已获账号生命周期接纳的迟到续期任务,并在新一轮任务开始时创建完成信号。 +func (c *pendingRenewalCoordinator) beginTask() { + if c == nil { + return + } + c.mu.Lock() + if c.activeTasks == 0 { + c.done = make(chan struct{}) + } + c.activeTasks++ + c.mu.Unlock() +} + +// finishTask 标记一条迟到续期任务已退出,并在最后一条任务收束时通知所有 Join 等待者。 +func (c *pendingRenewalCoordinator) finishTask() { + if c == nil { + return + } + c.mu.Lock() + if c.activeTasks == 0 { + c.mu.Unlock() + return + } + c.activeTasks-- + // done 保存本轮迟到续期任务的共享完成信号;只有任务计数归零时才允许关闭。 + done := c.done + if c.activeTasks == 0 && done != nil { + close(done) + } + c.mu.Unlock() +} + +// waitContext 在 ctx 的关闭预算内等待所有已登记迟到续期任务退出。 +// 调用方取消账号运行 Context 后仍可使用独立关闭预算等待;任务不响应取消时返回 false, +// 但组件继续保留同一 done 信号,后续 StopContext 可再次 Join,且不创建旁路等待协程。 +func (c *pendingRenewalCoordinator) waitContext(ctx context.Context) bool { + if c == nil { + return true + } + if ctx == nil { + ctx = context.Background() + } + c.mu.Lock() + // done 保存当前任务轮次的共享完成信号;nil 表示没有任何待收束的迟到续期任务。 + done := c.done + c.mu.Unlock() + if done == nil { + return true + } + select { + case <-done: + return true + case <-ctx.Done(): + return false + } +} + +// watch 登记并异步等待一条迟到续期响应,所有持久化工作继承账号生命周期 Context。 +func (c *pendingRenewalCoordinator) watch( + parent context.Context, + beginTask func() (context.Context, bool), + finishTask func(), + result *renew.Result, + persist func(context.Context, *renew.Result) error, + logger *slog.Logger, +) { + if c == nil || result == nil || !result.HasPending() { + return + } + // taskCtx 是账号生命周期任务上下文,Stop 会先取消它再等待 Join。 + taskCtx, accepted := beginTask() + if !accepted { + return + } + if parent != nil { + taskCtx = parent + } + if logger == nil { + logger = slog.Default() + } + c.beginTask() + go func() { + defer c.finishTask() + defer finishTask() + // ctx、cancel 保存迟到响应等待的限时上下文及其取消函数。 + ctx, cancel := context.WithTimeout(taskCtx, 35*time.Second) + defer cancel() + // late、waitErr 保存底层迟到响应及等待错误。 + late, waitErr := result.AwaitPending(ctx) + if late == nil { + if waitErr != nil { + logger.Warn("等待静默续期底层响应失败", "err", waitErr) + } + return + } + // persistErr 保存迟到 Cookie 合并持久化错误。 + if persistErr := persist(ctx, late); persistErr != nil { + logger.Warn("保存静默续期迟到 Cookie 失败", "err", persistErr) + return + } + if waitErr != nil { + logger.Warn("静默续期底层响应失败,已保存响应 Cookie", "err", waitErr) + } + }() +} diff --git a/internal/engine/pending_renewal_test.go b/internal/engine/pending_renewal_test.go new file mode 100644 index 0000000..82a6c41 --- /dev/null +++ b/internal/engine/pending_renewal_test.go @@ -0,0 +1,81 @@ +package engine + +import ( + "context" + "log/slog" + "testing" + "time" +) + +// TestPendingRenewalCoordinatorWaitContextBoundsAndRetries 验证迟到续期任务未响应取消时,等待受调用方预算约束, +// 且超时不会创建旁路等待协程,后续调用仍能订阅同一个完成信号并在任务收束后成功 Join。 +func TestPendingRenewalCoordinatorWaitContextBoundsAndRetries(t *testing.T) { + // coordinator 是待验证的迟到续期任务 owner。 + coordinator := pendingRenewalCoordinator{} + coordinator.beginTask() + // timeoutCtx、timeoutCancel 提供刻意很短的关闭预算,用于模拟底层等待不响应取消。 + timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer timeoutCancel() + // waitStarted 记录本次有限等待的起始时间,以确认它不会无限阻塞。 + waitStarted := time.Now() + if coordinator.waitContext(timeoutCtx) { + t.Fatal("未完成的迟到续期任务不应在关闭预算内被误判为已退出") + } + // elapsed 是有限等待实际占用的时长,必须明显小于测试允许的上界。 + elapsed := time.Since(waitStarted) + if elapsed > 300*time.Millisecond { + t.Fatalf("迟到续期 Join 未受上下文限制: elapsed=%s", elapsed) + } + // retried 表示第二次 Join 的结果;它必须继续等待原任务完成,而非复用已超时的等待结果。 + retried := make(chan bool, 1) + go func() { + retried <- coordinator.waitContext(context.Background()) + }() + select { + case <-retried: + t.Fatal("迟到续期任务未完成时,重试 Join 不应提前返回") + case <-time.After(20 * time.Millisecond): + } + coordinator.finishTask() + select { + // joined 是重试 Join 在任务完成后收到的结果。 + case joined := <-retried: + if !joined { + t.Fatal("迟到续期任务收束后,重试 Join 应返回成功") + } + case <-time.After(time.Second): + t.Fatal("迟到续期任务收束后,重试 Join 未返回") + } +} + +// TestConnectionCoordinatorWaitForOwnedWorkersUsesSingleBoundedContext 验证连接协调器对 recorder 与迟到续期任务 +// 使用同一个关闭 Context;任一不可响应任务都不能令 Run 的 defer 永久阻塞。 +func TestConnectionCoordinatorWaitForOwnedWorkersUsesSingleBoundedContext(t *testing.T) { + // recorder 是模拟底层写入无法响应取消的记录 worker;done 不关闭表示它尚未退出。 + recorder := &wsRecorder{done: make(chan struct{})} + recorder.started.Store(true) + // account 只装配等待逻辑所需的组件与日志依赖,不启动真实账号运行时。 + account := &Account{ + accountRuntimeComponents: accountRuntimeComponents{}, + accountDependencies: accountDependencies{logger: slog.Default(), recorder: recorder}, + } + // account.pendingRenewal 是模拟仍在等待外部迟到响应的任务 owner。 + account.pendingRenewal.beginTask() + // coordinator 是待验证的连接生命周期协调器。 + coordinator := connectionCoordinator{account: account} + // shutdownCtx、shutdownCancel 提供总关闭预算;两个 worker 都不结束时应由该预算统一终止等待。 + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer shutdownCancel() + // waitStarted 记录协调器开始收束自有 worker 的时间。 + waitStarted := time.Now() + coordinator.waitForOwnedWorkers(shutdownCtx) + // elapsed 是总 Join 时间;共享 Context 要求它不能叠加成两倍等待预算。 + elapsed := time.Since(waitStarted) + if elapsed > 300*time.Millisecond { + t.Fatalf("连接协调器等待自有 worker 超出总预算: elapsed=%s", elapsed) + } + // recorderDone 解除模拟的 recorder worker,避免测试保留未关闭的完成信号。 + recorderDone := recorder.done + close(recorderDone) + account.pendingRenewal.finishTask() +} diff --git a/internal/engine/ws_recorder.go b/internal/engine/ws_recorder.go index dc70793..f4c87ab 100644 --- a/internal/engine/ws_recorder.go +++ b/internal/engine/ws_recorder.go @@ -11,7 +11,7 @@ import ( ) // wsRecorder 负责 WebSocket 报文诊断记录的有界队列和后台写入生命周期。 -// once 保护单次启动,wg 等待写入 worker;组件锁不覆盖数据库 I/O。 +// once 保护单次启动;done 是写入 worker 的 Context-aware Join 信号,组件锁不覆盖数据库 I/O。 // wsRecorder 保存wsRecorder,供当前处理流程使用 type wsRecorder struct { // store 提供 WebSocket 报文持久化 repository。 @@ -22,8 +22,6 @@ type wsRecorder struct { logger *slog.Logger // once 保证同一个账号运行时只启动一个 recorder worker。 once sync.Once - // wg 等待 recorder worker 退出。 - wg sync.WaitGroup // done 在 recorder worker 退出时关闭,供 Context-aware 等待直接选择而不创建旁路 goroutine。 done chan struct{} // started 表示 recorder worker 是否实际启动;未启动的 recorder 无需等待。 @@ -80,9 +78,7 @@ func (r *wsRecorder) start(ctx context.Context) { } r.once.Do(func() { r.started.Store(true) - r.wg.Add(1) go func() { - defer r.wg.Done() defer close(r.done) // cleanupCtx 是清理历史报文时的有限时长上下文。 cleanupCtx, cleanupCancel := context.WithTimeout(ctx, WSRecordWriteTimeout) @@ -133,13 +129,6 @@ func (r *wsRecorder) start(ctx context.Context) { }) } -// wait 等待 recorder worker 退出。 -func (r *wsRecorder) wait() { - if r != nil { - r.wg.Wait() - } -} - // waitContext 在 ctx 约束内等待 recorder worker 退出;数据库写入异常阻塞时及时把停止超时交给调用方。 func (r *wsRecorder) waitContext(ctx context.Context) bool { if r == nil { diff --git a/internal/notify/notifier.go b/internal/notify/notifier.go index 607f093..cdf2fe1 100644 --- a/internal/notify/notifier.go +++ b/internal/notify/notifier.go @@ -149,6 +149,30 @@ func (n *Notifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message }) } +// NotifyAutomationRun 将一个自动化运行的终态通知持久化到 outbox。 +// runID 与 status 共同构成稳定幂等键:同一次恢复重复报告同一终态时不会重复入队; +// 状态改变时保留独立通知,便于人工核对后继续执行的运行报告最终结果。 +func (n *Notifier) NotifyAutomationRun(ctx context.Context, runID int64, accountID, buyerID, itemID, status, message, chatID string) { + if n == nil || runID <= 0 || strings.TrimSpace(status) == "" { + return + } + // idempotencyKey 绑定自动化运行主键与终态,避免恢复扫描或状态收口重试创建新 outbox 消息。 + idempotencyKey := fmt.Sprintf("automation-run:%d:%s", runID, strings.TrimSpace(status)) + n.notifyEvent(ctx, NotificationEvent{ + AccountID: accountID, + Type: EventDeliveryResult, + Level: "info", + Title: "自动化运行通知", + Body: message, + Fields: map[string]string{ + "买家": fmt.Sprintf("(ID: %s)", buyerID), + "商品ID": itemID, + "聊天ID": fallback(chatID, "未知"), + "结果": message, + }, + }, idempotencyKey) +} + // NotifyAccountAlert 发送账号告警通知(token 失效/自动恢复失败/风控验证等)。 // level 取 AlertLevel* 常量。向该账号所有已启用渠道发送。 // NotifyAccountAlert 负责Notify账号Alert相关处理。 @@ -169,6 +193,11 @@ func (n *Notifier) NotifyAccountEvent(accountID, eventType, level, title, body s // NotifyEvent 根据事件类型筛选渠道并发送通知。 func (n *Notifier) NotifyEvent(ctx context.Context, ev NotificationEvent) { + n.notifyEvent(ctx, ev, "") +} + +// notifyEvent 根据事件类型筛选渠道并发送通知;idempotencyKey 只用于 outbox 持久化去重,不能为空时必须来自稳定业务事实。 +func (n *Notifier) notifyEvent(ctx context.Context, ev NotificationEvent, idempotencyKey string) { if n == nil || n.repository == nil { return } @@ -197,12 +226,14 @@ func (n *Notifier) NotifyEvent(ctx context.Context, ev NotificationEvent) { } eligible = append(eligible, ch) } - if n.started.Load() { - // messages 保存消息列表,供当前处理流程使用 + // 自动化运行终态必须先进入 outbox:即使 worker 尚未随应用生命周期启动,也不能回退到 + // 同步网络发送,否则会绕过业务幂等键和发送成功后的 uncertain 隔离。 + if n.started.Load() || strings.TrimSpace(idempotencyKey) != "" { + // messages 保存本事件每个允许渠道的一条 outbox 记录,并共享同一个业务投递键。 messages := make([]db.NotificationOutboxInput, 0, len(eligible)) // ch 表示当前遍历过程中的ch for _, ch := range eligible { - messages = append(messages, db.NotificationOutboxInput{ChannelID: ch.ID, EventType: ev.Type, Body: full}) + messages = append(messages, db.NotificationOutboxInput{ChannelID: ch.ID, EventType: ev.Type, Body: full, IdempotencyKey: idempotencyKey}) } if // err 保存err,供当前处理流程使用 err := n.repository.EnqueueOutbox(ctx, messages); err != nil { diff --git a/internal/notify/notifier_dispatch_test.go b/internal/notify/notifier_dispatch_test.go index 18fe8f9..953bf87 100644 --- a/internal/notify/notifier_dispatch_test.go +++ b/internal/notify/notifier_dispatch_test.go @@ -404,6 +404,47 @@ func TestNotifyDelivery_EmptyChatID(t *testing.T) { } } +// TestNotifyAutomationRunQueuesEachTerminalStateOnce 验证自动化运行通知即使 worker 尚未启动也写入 +// 持久化 outbox,同一运行同一终态重复恢复只保留一次;不同终态保留各自独立的人工核对记录。 +func TestNotifyAutomationRunQueuesEachTerminalStateOnce(t *testing.T) { + // store、cleanup 保存本测试的 SQLite 通知存储与关闭责任。 + store, cleanup := newNotifyStoreBare(t) + defer cleanup() + // channelID 保存绑定给自动化账号的 webhook 渠道主键。 + channelID := addWebhookChannel(t, store, "cid", "自动化幂等渠道", "http://127.0.0.1:1") + // notifier 保存未启动 worker 的真实 outbox 通知器;自动化终态仍不得降级为同步网络发送。 + notifier := New("cid", store, nil) + // notifyCtx 约束自动化结果入队操作,不携带网络或账号凭证。 + notifyCtx := context.Background() + notifier.NotifyAutomationRun(notifyCtx, 73, "cid", "buyer", "item", "success", "付款发货成功", "chat") + notifier.NotifyAutomationRun(notifyCtx, 73, "cid", "buyer", "item", "success", "付款发货成功", "chat") + notifier.NotifyAutomationRun(notifyCtx, 73, "cid", "buyer", "item", "needs_review", "付款发货需要人工核对", "chat") + // rows 保存该渠道上同一自动化运行的 outbox 终态键和记录数量。 + rows, queryErr := store.DB.QueryContext(notifyCtx, `SELECT idempotency_key FROM notification_outbox WHERE channel_id=? ORDER BY idempotency_key`, channelID) + if queryErr != nil { + t.Fatal(queryErr) + } + defer rows.Close() + // keys 保存已持久化的自动化运行终态键,用于断言重复 success 未产生第二条记录。 + keys := make([]string, 0, 2) + for rows.Next() { + // key 保存当前 outbox 行绑定的稳定自动化通知键。 + var key string + // scanErr 保存读取当前 outbox 幂等键时的数据库错误。 + if scanErr := rows.Scan(&key); scanErr != nil { + t.Fatal(scanErr) + } + keys = append(keys, key) + } + // rowsErr 保存遍历 outbox 查询结果结束时的数据库错误。 + if rowsErr := rows.Err(); rowsErr != nil { + t.Fatal(rowsErr) + } + if len(keys) != 2 || keys[0] != "automation-run:73:needs_review" || keys[1] != "automation-run:73:success" { + t.Fatalf("outbox keys=%v", keys) + } +} + // TestParseConfig_InvalidJSON 非法 JSON 走旧格式兼容分支。 func TestParseConfig_InvalidJSON(t *testing.T) { // m 保存m,供当前处理流程使用 diff --git a/internal/server/account_login_repository_boundary_test.go b/internal/server/account_login_repository_boundary_test.go index cd85cf6..644a6d0 100644 --- a/internal/server/account_login_repository_boundary_test.go +++ b/internal/server/account_login_repository_boundary_test.go @@ -1,22 +1,14 @@ package server -import ( - "context" - "testing" -) +import "testing" -// TestServerCookieWriterRejectsMissingRepository 验证 Server 凭证写入适配器缺少 Port 时快速失败。 +// TestServerCookieWriterRejectsMissingRepository 验证 Server 缺少窄凭证端口时快速失败。 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 不应伪装成功") + // srv 模拟尚未完成账号应用服务装配的 Server。 + srv := &Server{applications: &applicationServices{accountLogin: &accountLoginService{}}} + // sessionPort 保存缺少凭证仓储时的会话写回端口。 + sessionPort := srv.platformCredentialSessionPort() + if sessionPort != nil { + t.Fatal("缺少凭证 Port 时 Server 不应暴露伪造的会话端口") } } diff --git a/internal/server/account_login_service.go b/internal/server/account_login_service.go index 87db470..2d110bc 100644 --- a/internal/server/account_login_service.go +++ b/internal/server/account_login_service.go @@ -3,9 +3,7 @@ package server import ( "context" "errors" - "log/slog" "strings" - "sync" "time" "xianyu-go/internal/adapter" @@ -14,99 +12,23 @@ import ( // accountLoginService 是账号登录相关应用服务,负责凭证写入、登录审计、资料刷新和运行时重启编排。 type accountLoginService struct { - // server 提供账号存储、运行时管理器和扫码会话持久化依赖。 - server *Server - // repository 提供账号登录服务所需的最小凭证持久化能力。 - repository accountapp.CredentialRepository - // summaryRepository 提供不解密凭证的账号摘要和归属查询能力。 - summaryRepository accountapp.AccountSummaryRepository + // cookieWriterFactory 按请求创建新增 Cookie 写入端口;明文只进入返回的短生命周期实例。 + cookieWriterFactory func(string) accountapp.CookieWriter + // cookieUpdaterFactory 按请求创建既有 Cookie 更新端口;明文只进入返回的短生命周期实例。 + cookieUpdaterFactory func(string) accountapp.CookieUpdater + // sessionPort 提供平台会话写回所需的最小凭证能力,不暴露完整账号仓储。 + sessionPort accountapp.CredentialSessionPort // createApplication 提供已迁移的手动 Cookie 登录应用用例。 createApplication *accountapp.LoginService - // qrApplication 提供扫码成功凭证持久化应用用例;会话幂等状态仍由 Server 适配器拥有。 + // qrApplication 提供扫码成功凭证持久化应用用例。 qrApplication *accountapp.QRLoginService + // qrSessions 持有扫码会话所有权和幂等结果,Server 只负责 HTTP 适配。 + qrSessions *accountapp.QRLoginSessionRegistry } -// serverLoginLifecyclePort 将登录成功后的审计、资料刷新和运行时重启适配到应用层端口。 -type serverLoginLifecyclePort struct { - // server 提供现有 Server 运行时与审计适配能力。 - server *Server -} - -// AfterSuccessfulLogin 在凭证写入并释放凭证锁后执行 Server 侧登录后续编排。 -func (p serverLoginLifecyclePort) AfterSuccessfulLogin(ctx context.Context, userID int64, accountID, method string) { - if p.server == nil { - return - } - if strings.TrimSpace(method) != "" { - p.server.markSuccessfulLogin(ctx, accountID, userID, method, "账号登录成功") - } - p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID) -} - -// serverCookieWriter 将本次请求中的明文 Cookie 限制在 Server 基础设施适配器内。 -type serverCookieWriter struct { - // repository 提供凭证锁、写入和旧 Token 清理能力。 - repository accountapp.CredentialRepository - // cookies 保存当前请求明文 Cookie;仅在 CreateOwnedCookie 调用期间使用,不进入应用层模型。 - cookies string - // logger 提供旧 Token 清理失败的脱敏日志能力。 - logger *slog.Logger -} - -// CreateOwnedCookie 在凭证锁内原子校验归属、写入 Cookie 并清理旧连接 Token。 -func (w serverCookieWriter) CreateOwnedCookie(ctx context.Context, accountID string, userID int64) error { - if w.repository == nil { - return errors.New("账号登录凭证 repository 未初始化") - } - // unlock 保护凭证写入与旧连接 Token 清理,外部网络和运行时操作在锁外执行。 - unlock := w.repository.LockCredentials(accountID) - defer unlock() - // writeErr 保存凭证写入错误;归属校验失败时直接返回且不清理 Token。 - writeErr := w.repository.CreateCookieOwned(ctx, accountID, w.cookies, userID) - if writeErr != nil { - return writeErr - } - // clearErr 保存旧连接 Token 清理错误;清理失败不回滚已经成功写入的 Cookie。 - clearErr := w.repository.ClearTokens(ctx, accountID) - if clearErr != nil && w.logger != nil { - w.logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr) - } - return nil -} - -// UpdateOwnedCookie 在账号凭证短锁内完成归属复核、Cookie 写入和旧 Token 清理;慢速资料刷新由应用服务在解锁后触发。 -func (w serverCookieWriter) UpdateOwnedCookie(ctx context.Context, accountID string, userID, expectedRevision int64) error { - if w.repository == nil { - return errors.New("账号登录凭证 repository 未初始化") - } - // unlock 只保护凭证快照读取、数据库写入和旧 Token 清理,不跨越网络或运行时操作。 - unlock := w.repository.LockCredentials(accountID) - defer unlock() - // detail 保存锁内读取的平台凭证窄视图;该视图不会把登录密码传入应用层。 - detail, loadErr := w.repository.LoadPlatformDetail(ctx, accountID) - if loadErr != nil { - return loadErr - } - if detail == nil || detail.UserID != userID { - return accountapp.ErrForbidden - } - if expectedRevision != 0 && detail.LastRefreshAt != expectedRevision { - return accountapp.ErrCredentialConflict - } - // updateErr 保存归属已确认后的 Cookie 持久化结果;适配器负责清除旧完整快照。 - if updateErr := w.repository.UpdateFlatCookieOwned(ctx, detail, w.cookies); updateErr != nil { - return updateErr - } - // clearErr 保存旧连接 Token 清理错误;凭证已成功写入时清理失败仅记录并继续。 - if clearErr := w.repository.ClearTokens(ctx, accountID); clearErr != nil && w.logger != nil { - w.logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", accountID, "err", clearErr) - } - return nil -} - -// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其 Server 生命周期适配器。 -func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService, error) { - return accountapp.NewLoginService(serverLoginLifecyclePort{server: server}) +// newAccountLoginCreateApplication 构造手动 Cookie 登录应用服务及其生命周期适配器。 +func newAccountLoginCreateApplication(lifecycle accountapp.LoginLifecyclePort) (*accountapp.LoginService, error) { + return accountapp.NewLoginService(lifecycle) } // accountLoginApplication 返回当前 Server 绑定的账号登录应用服务。 @@ -114,9 +36,13 @@ func (s *Server) accountLoginApplication() *accountLoginService { return s.applicationServiceSet().accountLogin } -// accountLoginRepositoryForServer 返回当前 Server 装配的账号登录持久化边界。 -func (s *Server) accountLoginRepositoryForServer() accountapp.CredentialRepository { - return s.accountLoginApplication().repository +// platformCredentialSessionPort 返回平台 Cookie 会话写回所需的最小应用端口。 +// Server 不通过该端口读取账号或登录秘密;凭证锁仍由调用方在慢速平台 I/O 之外管理。 +func (s *Server) platformCredentialSessionPort() accountapp.CredentialSessionPort { + if s == nil || s.accountLoginApplication() == nil { + return nil + } + return s.accountLoginApplication().sessionPort } // accountLoginInput 是新增账号登录凭证用例的业务输入。 @@ -147,132 +73,74 @@ type accountCookieUpdateInput struct { // CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。 func (svc *accountLoginService) CreateCookie(ctx context.Context, input accountLoginInput) error { - if svc == nil || svc.createApplication == nil || svc.server == nil { + if svc == nil || svc.createApplication == nil { return errors.New("账号登录应用服务未初始化") } + if svc.cookieWriterFactory == nil { + return errors.New("账号 Cookie 写入端口未初始化") + } return svc.createApplication.CreateCookie(ctx, accountapp.CreateCookieInput{ AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod, - }, serverCookieWriter{repository: svc.repository, cookies: input.Cookies, logger: svc.server.Logger}) + }, svc.cookieWriterFactory(input.Cookies)) } // UpdateCookie 更新账号凭证并完成登录审计、资料刷新和运行时重启。 func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountCookieUpdateInput) error { - if svc == nil || svc.createApplication == nil || svc.server == nil { + if svc == nil || svc.createApplication == nil { return errors.New("账号登录应用服务未初始化") } + if svc.cookieUpdaterFactory == nil { + return errors.New("账号 Cookie 更新端口未初始化") + } return svc.createApplication.UpdateCookie(ctx, accountapp.UpdateCookieInput{ AccountID: input.AccountID, UserID: input.UserID, LoginMethod: input.LoginMethod, ExpectedRevision: input.ExpectedRevision, - }, serverCookieWriter{repository: svc.repository, cookies: input.Cookies, logger: svc.server.Logger}) -} - -// serverQRLoginLifecycle 将扫码登录成功后的审计、资料刷新和运行时同步适配到应用端口。 -type serverQRLoginLifecycle struct { - // server 提供审计、资料刷新、自动化唤醒和账号运行时管理能力。 - server *Server -} - -// AfterSuccessfulQRLogin 在凭证锁释放后执行扫码登录成功的后续编排。 -func (p serverQRLoginLifecycle) AfterSuccessfulQRLogin(ctx context.Context, userID int64, accountID string) { - if p.server == nil { - return - } - p.server.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功") - p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID) - p.server.wakeCredentialBlockedAutomation(ctx, accountID) -} - -// ReportQRLoginCleanupFailure 记录扫码登录后旧 Token 清理失败,不暴露 Cookie 内容且不回滚已写入凭证。 -func (p serverQRLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, accountID string, err error) { - if p.server != nil && p.server.Logger != nil { - p.server.Logger.Warn("扫码登录后清理旧连接凭证失败", "cookie_id", accountID, "err", err) - } + }, svc.cookieUpdaterFactory(input.Cookies)) } // PersistQRLoginSuccess 将 HTTP/平台 map 适配为纯应用 DTO,并复用会话级幂等锁。 func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) { - if svc == nil || svc.server == nil || svc.qrApplication == nil { + if svc == nil || svc.qrApplication == nil || svc.qrSessions == nil { return qrLoginPersistence{}, errors.New("扫码登录应用服务未初始化") } - // s 是当前账号登录应用服务依赖的 Server。 - s := svc.server - // lockValue 和 persistMu 保证同一扫码会话只执行一次持久化。 - lockValue, _ := s.qrPersistLocks.LoadOrStore(sessionID, &sync.Mutex{}) - // persistMu 是当前扫码会话的串行化锁。 - persistMu := lockValue.(*sync.Mutex) - persistMu.Lock() - defer persistMu.Unlock() - - s.qrMu.Lock() - if s.qrPersisted == nil { - s.qrPersisted = make(map[string]qrLoginPersistence) - } - // persisted 和 ok 保存已完成的幂等结果及其存在性。 - if persisted, ok := s.qrPersisted[sessionID]; ok { - s.qrMu.Unlock() - if persisted.UserID != userID { - return qrLoginPersistence{}, errors.New("扫码会话不属于当前用户") + // persisted 保存注册表执行凭证持久化后返回的非敏感幂等结果。 + persisted, persistErr := svc.qrSessions.PersistOnce(sessionID, userID, func() (accountapp.QRLoginSessionPersistence, error) { + // cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。 + cookies := qrString(result, "cookies") + // cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。 + cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result) + // scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。 + 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 = cookieSnapshot } - return persisted, nil - } - s.qrMu.Unlock() - // cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。 - cookies := qrString(result, "cookies") - // cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。 - cookieSnapshot, snapshotComplete := adapter.CookieSnapshotsFromResult(result) - // scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。 - 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 = cookieSnapshot - } - // resultValue 保存应用服务返回的非敏感持久化结果。 - resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input) + // resultValue 保存应用服务返回的非敏感持久化结果。 + resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input) + if persistErr != nil { + if errors.Is(persistErr, accountapp.ErrQRLoginIncomplete) { + return accountapp.QRLoginSessionPersistence{}, errors.New("扫码结果缺少 cookies 或 unb") + } + if errors.Is(persistErr, accountapp.ErrQRLoginAccountMismatch) { + return accountapp.QRLoginSessionPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖") + } + if errors.Is(persistErr, accountapp.ErrForbidden) { + return accountapp.QRLoginSessionPersistence{}, errors.New("该账号ID已存在且不属于当前用户") + } + if errors.Is(persistErr, accountapp.ErrAlreadyExists) { + return accountapp.QRLoginSessionPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态") + } + return accountapp.QRLoginSessionPersistence{}, persistErr + } + return accountapp.QRLoginSessionPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, CreatedAt: time.Now().UTC()}, nil + }) if persistErr != nil { - if errors.Is(persistErr, accountapp.ErrQRLoginIncomplete) { - return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb") - } - if errors.Is(persistErr, accountapp.ErrQRLoginAccountMismatch) { - return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖") - } - if errors.Is(persistErr, accountapp.ErrForbidden) { - return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户") - } - if errors.Is(persistErr, accountapp.ErrAlreadyExists) { - return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态") + if errors.Is(persistErr, accountapp.ErrQRLoginSessionForbidden) { + return qrLoginPersistence{}, errors.New("扫码会话不属于当前用户") } return qrLoginPersistence{}, persistErr } - // persisted 是扫码会话幂等返回值。 - persisted := qrLoginPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, UserID: userID, CreatedAt: time.Now().UTC()} - s.qrMu.Lock() - s.qrPersisted[sessionID] = persisted - s.qrMu.Unlock() - s.qrPersistLocks.Delete(sessionID) - return persisted, nil -} - -// refreshAndRestartAccount 在凭证锁释放后刷新资料并按账号状态重启运行时。 -func (svc *accountLoginService) refreshAndRestartAccount(ctx context.Context, userID int64, accountID string) { - // s 是当前账号登录应用服务依赖的 Server。 - s := svc.server - // detail 和 err 保存资料摘要查询结果。 - _, err := svc.summaryRepository.GetOwnedSummary(ctx, userID, accountID) - if err == nil { - // 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 表示账号运行时重启错误。 - if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil { - s.Logger.Warn("账号登录后重启账号失败", "cookie_id", accountID, "err", err) - } - } + return qrLoginPersistence{AccountID: persisted.AccountID, IsNew: persisted.IsNew, UserID: persisted.UserID, CreatedAt: persisted.CreatedAt}, nil } // ValidateCookieInput 校验账号标识和 Cookie 输入,供 HTTP 适配层复用一致规则。 diff --git a/internal/server/admin_handlers.go b/internal/server/admin_handlers.go index 71ca05d..375540c 100644 --- a/internal/server/admin_handlers.go +++ b/internal/server/admin_handlers.go @@ -48,15 +48,6 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) { } // 不允许删除自己;应用服务统一执行该业务规则。 sess := authSess(r) - if s.Manager != nil { - // accountIDs、listErr 保存应用服务返回的待停止账号 ID 列表及查询错误。 - if accountIDs, listErr := s.accountSummaryApplication().ListOwnedIDs(r.Context(), uid); listErr == nil { - // cookieID 表示待停止运行实例的账号标识。 - for _, cookieID := range accountIDs { - s.Manager.Stop(cookieID) - } - } - } // err 保存管理员删除应用用例的执行结果。 if err := s.applicationServiceSet().admin.DeleteUser(r.Context(), sess.UserID, uid); err != nil { if errors.Is(err, adminapp.ErrSelfDelete) { diff --git a/internal/server/application_services.go b/internal/server/application_services.go index 31c0abe..a09b3df 100644 --- a/internal/server/application_services.go +++ b/internal/server/application_services.go @@ -13,6 +13,7 @@ import ( defaultreplyapp "xianyu-go/internal/application/defaultreply" itemapp "xianyu-go/internal/application/items" keywordsapp "xianyu-go/internal/application/keywords" + lifecycleapp "xianyu-go/internal/application/lifecycle" notificationsapp "xianyu-go/internal/application/notifications" orderapp "xianyu-go/internal/application/orders" settingsapp "xianyu-go/internal/application/settings" @@ -20,14 +21,18 @@ import ( // applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。 type applicationServices struct { + // platformCredentials 负责按需读取平台凭证窄视图并执行归属复核。 + platformCredentials *accountapp.PlatformCredentialService // orders 是订单 HTTP 适配器;业务服务集合由应用层统一构造。 orders *orderHTTPAdapter + // orderRefreshJobs 是订单刷新任务创建、取消、恢复和 worker 生命周期应用服务。 + orderRefreshJobs *orderapp.RefreshJobService + // orderReconciliationRecovery 是订单补偿扫描器的应用层生命周期协调器。 + orderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator // itemSinglePublish 是仅负责单商品发布用例的纯应用服务。 itemSinglePublish *itemapp.Service - // itemBatchRunner 是商品批量发布 worker 的应用层编排器。 - itemBatchRunner *itemapp.BatchRunner - // itemBatchRecovery 是过期批量发布任务的租约接管应用服务。 - itemBatchRecovery *itemapp.BatchRecoveryService + // itemBatchCoordinator 是商品批量发布 worker、恢复扫描和关闭等待的生命周期拥有者。 + itemBatchCoordinator *itemapp.BatchWorkerCoordinator // itemBatchPreview 是商品批量发布表格预检应用服务。 itemBatchPreview *itemapp.BatchPreviewService // itemBatchManagement 是商品批次查询、取消和重试应用服务。 @@ -60,6 +65,8 @@ type applicationServices struct { accountLongLogin *accountapp.LongLoginService // accountSettings 是账号设置、登录信息、启停和暂停应用服务。 accountSettings *accountapp.SettingsService + // accountRuntime 是账号凭证写回后的运行时同步与状态快照应用服务。 + accountRuntime *accountapp.RuntimeService // accountSummaries 是账号摘要、所有权和管理员账号列表应用服务。 accountSummaries *accountapp.SummaryService // accountTasks 是账号任务设置、历史和手动执行应用服务。 @@ -92,28 +99,122 @@ type applicationServices struct { admin *adminapp.Service } +// ApplicationLifecycleComponents 返回 Server 装配的应用 worker 生命周期组件。 +// 组件只暴露 Start/Close 端口,启动顺序与进程取消责任由 cmd 的协调器拥有。 +func (s *Server) ApplicationLifecycleComponents() []lifecycleapp.NamedComponent { + if s == nil || s.applications == nil { + return nil + } + // components 保存按应用依赖登记的 worker 生命周期组件。 + components := make([]lifecycleapp.NamedComponent, 0, 3) + if s.applications.orderRefreshJobs != nil { + // service 保存订单刷新恢复与 worker 生命周期应用服务。 + service := s.applications.orderRefreshJobs + components = append(components, lifecycleapp.NamedComponent{ + Name: "order-refresh-recovery", + Component: lifecycleapp.FuncComponent{ + StartFunc: service.StartRecovery, + CloseFunc: service.Close, + }, + }) + } + if s.applications.itemBatchCoordinator != nil { + // coordinator 保存批量发布 worker 与恢复扫描生命周期协调器。 + coordinator := s.applications.itemBatchCoordinator + components = append(components, lifecycleapp.NamedComponent{ + Name: "publish-batch-workers", + Component: lifecycleapp.FuncComponent{ + StartFunc: coordinator.StartRecovery, + CloseFunc: coordinator.Close, + }, + }) + } + if s.applications.orderReconciliationRecovery != nil { + // coordinator 保存订单补偿扫描生命周期协调器。 + coordinator := s.applications.orderReconciliationRecovery + components = append(components, lifecycleapp.NamedComponent{ + Name: "order-reconciliation-recovery", + Component: lifecycleapp.FuncComponent{ + StartFunc: coordinator.Start, + CloseFunc: coordinator.Close, + }, + }) + } + return components +} + // newApplicationServices 为指定 Server 装配全部应用服务实例。 func newApplicationServices(server *Server) *applicationServices { // orderRepository 保存订单应用服务共享的基础设施适配器。 - orderRepository := server.dependencies.NewOrderRepository() + orderRepository := server.orderDependencies.NewOrderRepository() // orderReconciliation 保存订单补偿写入应用 Port 的数据库适配器。 - orderReconciliation := server.dependencies.NewOrderReconciliationRepository() + orderReconciliation := server.orderDependencies.NewOrderReconciliationRepository() // orderRuntime 保存订单服务共享的运行时能力适配器。 orderRuntime := newServerOrderRuntime(server, orderReconciliation) + // orderReconciliationRecovery 将补偿扫描器的启动、取消和等待收口到订单应用边界。 + orderReconciliationRecovery, orderReconciliationRecoveryErr := orderapp.NewReconciliationRecoveryCoordinator(server.systemDependencies.NewReconciliationService(server.Logger)) + if orderReconciliationRecoveryErr != nil { + panic(orderReconciliationRecoveryErr) + } // orderServices 保存应用层统一构造的订单业务服务集合。 - orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.dependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize) + orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, server.orderDependencies.NewOrderRefreshJobRepository(), refreshOrderChunkSize) + // orderRefreshRunner 是订单刷新后台 worker 与恢复扫描的生命周期拥有者。 + orderRefreshRunner, orderRefreshRunnerErr := orderapp.NewRefreshJobRunner( + orderServices.RefreshJobs, + orderServices.Refresh, + orderapp.RefreshJobRunnerOptions{ + OnWorkerError: func(jobID string, err error) { + if server.Logger != nil { + server.Logger.Warn("订单刷新后台任务结束", "job_id", jobID, "err", err) + } + }, + OnRecoveryError: func(err error) { + if server.Logger != nil { + server.Logger.Warn("扫描订单刷新恢复任务失败", "err", err) + } + }, + }, + ) + if orderRefreshRunnerErr != nil { + panic(orderRefreshRunnerErr) + } + // orderRefreshJobs 是订单刷新任务应用 facade,封装归属、租约和 worker 启动编排。 + orderRefreshJobs, orderRefreshJobsErr := orderapp.NewRefreshJobService( + orderServices.RefreshJobs, + orderServices.Refresh, + orderRefreshRunner, + orderapp.RefreshJobServiceOptions{}, + ) + if orderRefreshJobsErr != nil { + panic(orderRefreshJobsErr) + } // accountProfile 保存账号资料刷新用例的构造结果。 // accountRepository 提供账号登录、资料摘要和删除共用的数据库适配器。 - accountRepository := server.dependencies.NewAccountLoginRepository() + accountRepository := server.accountDependencies.NewAccountLoginRepository() + // platformCredentials 将账号凭证读取限制在消费者定义的只读应用端口。 + platformCredentials, platformCredentialsErr := accountapp.NewPlatformCredentialService(accountRepository) + if platformCredentialsErr != nil { + panic(platformCredentialsErr) + } + // cookieWriterFactory 将明文 Cookie 封装在 adapter 的请求范围实例中,Server 不持有凭证仓储。 + cookieWriterFactory := func(cookies string) accountapp.CookieWriter { + return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, server.Logger) + } + // cookieUpdaterFactory 将既有账号的明文 Cookie 封装在 adapter 的请求范围实例中。 + cookieUpdaterFactory := func(cookies string) accountapp.CookieUpdater { + return adapter.NewAccountCookieWriter(accountRepository, platformCredentials, cookies, server.Logger) + } + // sessionRecovery 统一适配平台 Session 失效分类、诊断日志和账号运行时恢复。 + sessionRecovery := server.sessionRecoveryCallback() // accountProfile 由应用层服务编排平台资料刷新与非敏感摘要持久化。 - accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, server.recoverExpiredMTOPSession, server.Logger)) + accountProfile, profileErr := accountapp.NewProfileService(accountRepository, adapter.NewAccountProfilePort(accountRepository, server.mtopClient, server.updateRunningCookie, sessionRecovery, 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), + adapter.NewLongLoginAdapter(accountRepository, server.longLoginClient, server.updateRunningCookie, server.Logger), ) if longLoginErr != nil { panic(longLoginErr) @@ -124,22 +225,40 @@ func newApplicationServices(server *Server) *applicationServices { settingsRuntime = server.Manager } // accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。 - accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.dependencies.NewAccountSettingsRepository(), settingsRuntime) + accountSettings, accountSettingsErr := accountapp.NewSettingsService(server.accountDependencies.NewAccountSettingsRepository(), settingsRuntime) if accountSettingsErr != nil { panic(accountSettingsErr) } // accountSummaryRepository 保存普通用户与管理员共用的摘要查询适配器。 - accountSummaryRepository := server.dependencies.NewAccountSummaryRepository() + accountSummaryRepository := server.accountDependencies.NewAccountSummaryRepository() // accountSummaries、accountSummariesErr 保存账号摘要应用服务及其装配错误。 accountSummaries, accountSummariesErr := accountapp.NewSummaryService(accountSummaryRepository, accountSummaryRepository) if accountSummariesErr != nil { panic(accountSummariesErr) } // credentialWake 负责将凭证恢复后的任务唤醒写入收口到适配器。 - credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(server.dependencies.NewAutomationCredentialWakeRepository()) + // automationDependencies 提供自动化、默认回复和关键词用例的显式适配器工厂。 + automationDependencies := server.automationDependencies + if automationDependencies == nil { + panic("自动化专用依赖未装配") + } + // credentialWake、credentialWakeErr 保存凭证恢复后的自动化唤醒应用服务及装配错误。 + credentialWake, credentialWakeErr := automationapp.NewCredentialWakeService(automationDependencies.NewAutomationCredentialWakeRepository()) if credentialWakeErr != nil { panic(credentialWakeErr) } + // accountRuntime 将 Manager 与凭证恢复后的自动化唤醒收口到账号应用端口。 + accountRuntime := accountapp.NewRuntimeService(adapter.NewAccountRuntimePort(server.Manager), credentialWake) + // loginSuccess 负责登录成功后的资料刷新和启用账号运行时重启,避免 Server 持有业务编排。 + loginSuccess := accountapp.NewLoginSuccessService(accountRepository, accountProfile, accountRepository, accountRuntime, func(message string, err error) { + if server.Logger != nil { + server.Logger.Warn(message, "err", err) + } + }) + // loginAudit 负责登录方式、账号启用和审计日志写入,生命周期适配器只组合应用端口。 + loginAudit := accountapp.NewLoginAuditService(server.accountDependencies.NewAccountLoginAuditRepository()) + // loginLifecycle 将手动登录与扫码登录的成功后续动作收口到 adapter,不再反向持有 Server。 + loginLifecycle := adapter.NewAccountLoginLifecycle(loginAudit, loginSuccess, server.Logger) // deleteRuntime 是可选的账号运行时端口;显式保持 nil,避免把 nil *Manager 装入非空接口后触发 panic。 var deleteRuntime accountapp.DeleteRuntime if server.Manager != nil { @@ -151,14 +270,16 @@ func newApplicationServices(server *Server) *applicationServices { 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) + itemBatchPublish := server.itemDependencies.NewItemBatchPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) { + if sessionRecovery != nil { + sessionRecovery(ctx, cookieID, err) + } }, readBatchImageFile, downloadImageURL) // itemBatchLocalPublish 将远端发布成功后的本地商品、规则和检查点一次性装配。 itemBatchLocalPublish, itemBatchLocalPublishErr := itemapp.NewBatchLocalPublishService( - server.dependencies.NewItemBatchRepository(), - server.dependencies.NewItemCatalogRepository(), - server.dependencies.NewAutomationRepository(), + server.itemDependencies.NewItemBatchRepository(), + server.itemDependencies.NewItemCatalogRepository(), + automationDependencies.NewAutomationRepository(), ) if itemBatchLocalPublishErr != nil { panic(itemBatchLocalPublishErr) @@ -168,54 +289,72 @@ func newApplicationServices(server *Server) *applicationServices { if batchRunnerErr != nil { panic(batchRunnerErr) } - // itemBatchRecovery 负责恢复扫描的批次状态编排,worker 启动仍由 Server 生命周期边界提供。 + // itemBatchRecovery 负责恢复扫描的批次状态编排;worker 生命周期由协调器拥有。 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) - }, - }, + server.itemDependencies.NewItemBatchRepository(), + itemapp.BatchRecoveryOptions{LeaseDuration: publishBatchLease}, ) if batchRecoveryErr != nil { panic(batchRecoveryErr) } + // itemBatchCoordinator 负责批次 worker 的超时、恢复扫描和停止等待。 + itemBatchCoordinator, batchCoordinatorErr := itemapp.NewBatchWorkerCoordinator(itemBatchRunner, itemBatchRecovery, itemapp.BatchWorkerCoordinatorOptions{ + OnWorkerError: func(batchID string, err error) { + if server.Logger != nil { + server.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", err) + } + }, + OnRecoveryError: func(err error) { + if server.Logger != nil { + server.Logger.Warn("扫描可恢复批量发布任务失败", "err", err) + } + }, + }) + if batchCoordinatorErr != nil { + panic(batchCoordinatorErr) + } // itemBatchPreviewPort 提供批量预检所需的非敏感归属与本地图片校验能力。 - itemBatchPreviewPort := server.dependencies.NewItemBatchPreviewPort() + itemBatchPreviewPort := server.itemDependencies.NewItemBatchPreviewPort() // itemBatchPreview 是批量发布预检应用服务的构造结果。 itemBatchPreview, itemBatchPreviewErr := itemapp.NewBatchPreviewService(itemBatchPreviewPort, itemBatchPreviewPort) if itemBatchPreviewErr != nil { panic(itemBatchPreviewErr) } // itemBatchManagement 是批次管理应用服务的构造结果。 - itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.dependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server}) + itemBatchManagement, itemBatchManagementErr := itemapp.NewBatchManagementService(server.itemDependencies.NewItemBatchRepository(), serverBatchManagementRuntime{server: server, coordinator: itemBatchCoordinator}) if itemBatchManagementErr != nil { panic(itemBatchManagementErr) } // accountLoginCreate 是手动 Cookie 登录应用服务的构造结果。 - accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(server) + accountLoginCreate, accountLoginCreateErr := newAccountLoginCreateApplication(loginLifecycle) if accountLoginCreateErr != nil { panic(accountLoginCreateErr) } // accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。 var accountQRLogin *accountapp.QRLoginService - if server.dependencies != nil { + if server.accountDependencies != nil { // accountQRLoginErr 保存扫码应用服务装配失败原因。 var accountQRLoginErr error - accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.dependencies.NewQRLoginRepository(), serverQRLoginLifecycle{server: server}) + accountQRLogin, accountQRLoginErr = accountapp.NewQRLoginService(server.accountDependencies.NewQRLoginRepository(), loginLifecycle) if accountQRLoginErr != nil { panic(accountQRLoginErr) } } + // qrSessionRegistry 将扫码会话所有权、过期回收和幂等结果放在应用边界内。 + qrSessionRegistry := accountapp.NewQRLoginSessionRegistry() // automationRepository 复用同一个数据库适配器,保持自动化异常与规则查询的基础设施边界一致。 - automationRepository := server.dependencies.NewAutomationRepository() + automationRepository := automationDependencies.NewAutomationRepository() // settingsService 统一装配设置数据库与远端模型目录适配器。 - settingsService := settingsapp.NewService(server.dependencies.NewSettingsRepository(), adapter.NewAIModelClient()) - // adminService 负责管理员用户与仪表盘查询,HTTP 层只做 DTO 映射。 - adminService := adminapp.NewService(server.dependencies.NewAdminRepository()) + settingsService := settingsapp.NewService(server.adminSettingsDependencies.NewSettingsRepository(), adapter.NewAIModelClient()) + // adminRuntime 是管理员删除用户前收束账号运行实例的窄端口;无 Manager 的离线测试保持为空。 + var adminRuntime adminapp.Runtime + if server.Manager != nil { + adminRuntime = server.Manager + } + // adminService 负责管理员用户与仪表盘查询及删除前的账号运行时收束,HTTP 层只做 DTO 映射。 + adminService := adminapp.NewServiceWithRuntime(server.adminSettingsDependencies.NewAdminRepository(), adminRuntime) // itemCatalogRepository 是商品读写用例共用的数据库适配器。 - itemCatalogRepository := server.dependencies.NewItemCatalogRepository() + itemCatalogRepository := server.itemDependencies.NewItemCatalogRepository() // itemCatalog 是商品列表和详情读取用例的应用服务。 itemCatalog, itemCatalogErr := itemapp.NewCatalogService(itemCatalogRepository) if itemCatalogErr != nil { @@ -227,8 +366,10 @@ func newApplicationServices(server *Server) *applicationServices { 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) + itemPublishPort := server.itemDependencies.NewItemPublishPort(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) { + if sessionRecovery != nil { + sessionRecovery(ctx, cookieID, err) + } }) // itemCategoryRecommendation 复用商品发布端口承载类目推荐和响应会话写回。 itemCategoryRecommendation, itemCategoryRecommendationErr := itemapp.NewCategoryRecommendationService(itemPublishPort) @@ -236,69 +377,84 @@ func newApplicationServices(server *Server) *applicationServices { panic(itemCategoryRecommendationErr) } // itemBatchPreviewPersistence 将预检结果持久化到批次仓储,隔离数据库模型转换。 - itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.dependencies.NewItemBatchRepository()) + itemBatchPreviewPersistence, itemBatchPreviewPersistenceErr := itemapp.NewBatchPreviewPersistenceService(server.itemDependencies.NewItemBatchRepository()) if itemBatchPreviewPersistenceErr != nil { panic(itemBatchPreviewPersistenceErr) } // itemSinglePublish 是单商品发布应用服务及其基础设施端口的构造结果。 itemSinglePublish, itemSinglePublishErr := itemapp.NewService( itemPublishPort, - server.dependencies.NewItemPublishRepository(), + server.itemDependencies.NewItemPublishRepository(), ) if itemSinglePublishErr != nil { panic(itemSinglePublishErr) } return &applicationServices{ - orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository}, + platformCredentials: platformCredentials, + orders: &orderHTTPAdapter{services: orderServices}, + orderRefreshJobs: orderRefreshJobs, + orderReconciliationRecovery: orderReconciliationRecovery, itemSinglePublish: itemSinglePublish, - itemBatchRunner: itemBatchRunner, - itemBatchRecovery: itemBatchRecovery, + itemBatchCoordinator: itemBatchCoordinator, 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) + itemSync: itemapp.NewSyncService(server.itemDependencies.NewItemSyncRepository(server.mtopClient, server.Logger, server.updateRunningCookie, func(ctx context.Context, cookieID string, err error) { + if sessionRecovery != nil { + sessionRecovery(ctx, cookieID, err) + } })), itemCatalog: itemCatalog, itemCatalogMutation: itemCatalogMutation, - accountLogin: &accountLoginService{server: server, repository: accountRepository, summaryRepository: accountSummaryRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin}, + accountLogin: &accountLoginService{cookieWriterFactory: cookieWriterFactory, cookieUpdaterFactory: cookieUpdaterFactory, sessionPort: accountRepository, createApplication: accountLoginCreate, qrApplication: accountQRLogin, qrSessions: qrSessionRegistry}, authentication: newAuthenticationApplication(server), - loginAudit: accountapp.NewLoginAuditService(server.dependencies.NewAccountLoginAuditRepository()), + loginAudit: loginAudit, passwordLogin: accountapp.NewPasswordLoginService(), accountDelete: accountDelete, accountProfile: accountProfile, accountLongLogin: accountLongLogin, accountSettings: accountSettings, + accountRuntime: accountRuntime, accountSummaries: accountSummaries, - accountTasks: automationapp.NewService(server.dependencies.NewAccountTaskRepository(), adapter.NewAccountTaskRunner(server.automation)), + accountTasks: automationapp.NewService(automationDependencies.NewAccountTaskRepository(), adapter.NewAccountTaskRunner(server.automation)), credentialWake: credentialWake, chat: newChatSendingApplication(server), - uncertainNotifications: notificationsapp.New(server.dependencies.NewNotificationUncertainRepository()), - notificationChannels: notificationsapp.NewChannelService(server.dependencies.NewNotificationChannelRepository(), server.notifier), - analytics: analyticsapp.NewService(server.dependencies.NewAnalyticsRepository()), + uncertainNotifications: notificationsapp.New(server.miscDependencies.NewNotificationUncertainRepository()), + notificationChannels: notificationsapp.NewChannelService(server.miscDependencies.NewNotificationChannelRepository(), server.notifier), + analytics: analyticsapp.NewService(server.miscDependencies.NewAnalyticsRepository()), automationRules: automationapp.NewRuleService(automationRepository, automationRepository), - cards: cardsapp.NewService(server.dependencies.NewCardsRepository()), + cards: cardsapp.NewService(server.miscDependencies.NewCardsRepository()), publishAutomationRules: automationapp.NewPublishRuleService(automationRepository), automationIssues: automationapp.NewIssueService(automationRepository), - defaultReplies: defaultreplyapp.NewService(server.dependencies.NewDefaultReplyRepository()), - keywords: keywordsapp.NewService(server.dependencies.NewKeywordRepository()), + defaultReplies: defaultreplyapp.NewService(automationDependencies.NewDefaultReplyRepository()), + keywords: keywordsapp.NewService(automationDependencies.NewKeywordRepository()), settings: settingsService, admin: adminService, } } +// accountRuntimeApplication 返回当前 Server 绑定的账号运行时应用服务。 +func (s *Server) accountRuntimeApplication() *accountapp.RuntimeService { + return s.applicationServiceSet().accountRuntime +} + // newAuthenticationApplication 构造用户认证应用服务及其数据库适配器。 func newAuthenticationApplication(server *Server) *accountapp.AuthenticationService { // authentication、authenticationErr 保存认证应用服务及其装配错误。 - authentication, authenticationErr := accountapp.NewAuthenticationService(server.dependencies.NewAuthenticationRepository()) + authentication, authenticationErr := accountapp.NewAuthenticationService(server.accountDependencies.NewAuthenticationRepository()) if authenticationErr != nil { panic(authenticationErr) } return authentication } +// orderRefreshJobsApplication 返回当前 Server 绑定的订单刷新任务应用服务。 +func (s *Server) orderRefreshJobsApplication() *orderapp.RefreshJobService { + return s.applicationServiceSet().orderRefreshJobs +} + // itemCatalogApplication 返回当前 Server 绑定的商品读取应用服务。 func (s *Server) itemCatalogApplication() *itemapp.CatalogService { return s.applicationServiceSet().itemCatalog @@ -329,11 +485,6 @@ 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 @@ -344,16 +495,6 @@ 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 @@ -389,6 +530,14 @@ func (s *Server) accountSettingsApplication() *accountapp.SettingsService { return s.applicationServiceSet().accountSettings } +// platformCredentialApplication 返回当前 Server 绑定的平台凭证只读应用服务。 +func (s *Server) platformCredentialApplication() *accountapp.PlatformCredentialService { + if s == nil || s.applications == nil { + return nil + } + return s.applications.platformCredentials +} + // authenticationApplication 返回当前 Server 绑定的用户认证应用服务。 func (s *Server) authenticationApplication() *accountapp.AuthenticationService { return s.applicationServiceSet().authentication @@ -422,9 +571,9 @@ func (s *Server) applicationServiceSet() *applicationServices { if s.applications != nil { return s.applications } - if s.dependencies == nil { + if s.orderDependencies == nil || s.accountDependencies == nil || s.itemDependencies == nil || s.chatDependencies == nil || s.systemDependencies == nil || s.automationDependencies == nil || s.miscDependencies == nil || s.adminSettingsDependencies == nil { // accountLogin 仅用于零值 Server 的输入校验测试,不触发任何持久化访问。 - return &applicationServices{accountLogin: &accountLoginService{server: s}} + return &applicationServices{accountLogin: &accountLoginService{}} } return newApplicationServices(s) } diff --git a/internal/server/application_services_test.go b/internal/server/application_services_test.go index d518f40..0009987 100644 --- a/internal/server/application_services_test.go +++ b/internal/server/application_services_test.go @@ -12,7 +12,7 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) { } // services 是统一应用服务集合。 services := srv.applicationServiceSet() - 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 { + if services.orders == nil || services.orderRefreshJobs == nil || services.itemBatchCoordinator == 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.uncertainNotifications == nil || services.notificationChannels == nil || services.analytics == nil || services.cards == 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 { @@ -22,3 +22,35 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) { t.Fatal("应用服务访问器未返回统一装配实例") } } + +// TestApplicationLifecycleComponentsExposeWorkerOwnership 验证 Server 只暴露应用 worker 生命周期端口,不再提供启动入口。 +func TestApplicationLifecycleComponentsExposeWorkerOwnership(t *testing.T) { + // srv、cleanup 保存带完整应用服务装配的测试 Server 及其资源清理函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // components 保存交给进程生命周期协调器登记的应用 worker 组件。 + components := srv.ApplicationLifecycleComponents() + if len(components) != 3 { + t.Fatalf("应用生命周期组件数量=%d,期望=3", len(components)) + } + // names 保存组件稳定名称,顺序同时表达启动依赖与关闭逆序。 + names := make([]string, 0, len(components)) + // component 表示当前应用 worker 生命周期组件。 + for _, component := range components { + names = append(names, component.Name) + if component.Component == nil { + t.Fatalf("组件 %q 缺少生命周期实现", component.Name) + } + } + // want 是 cmd 应登记的应用 worker 稳定名称与启动顺序。 + want := []string{"order-refresh-recovery", "publish-batch-workers", "order-reconciliation-recovery"} + if len(names) != len(want) { + t.Fatalf("组件名称数量=%d,期望=%d", len(names), len(want)) + } + // index 表示当前比较的生命周期组件下标。 + for index := range want { + if names[index] != want[index] { + t.Fatalf("组件名称[%d]=%q,期望=%q", index, names[index], want[index]) + } + } +} diff --git a/internal/server/chat_application.go b/internal/server/chat_application.go index 9491b01..4737fcb 100644 --- a/internal/server/chat_application.go +++ b/internal/server/chat_application.go @@ -10,5 +10,8 @@ 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) + if server.chatDependencies == nil { + return adapter.NewChatSendingApplication(server.chat, nil, server.Manager, server.mtopClient) + } + return server.chatDependencies.NewChatSendingApplication(server.chat, server.Manager, server.mtopClient) } diff --git a/internal/server/chat_handlers.go b/internal/server/chat_handlers.go index b605055..4e0d85b 100644 --- a/internal/server/chat_handlers.go +++ b/internal/server/chat_handlers.go @@ -14,7 +14,6 @@ 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" ) @@ -57,30 +56,19 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, "清理无效聊天会话失败") return } - if refresh && s.chat != nil && s.Manager != nil { - if // sender、ok 保存sender、ok,供当前处理流程使用 - sender, ok := s.Manager.GetInstance(accountID); ok { - if // fetcher、ok 保存fetcher、ok,供当前处理流程使用 - fetcher, ok := sender.(interface { - FetchChatConversations(context.Context, int64, int) (map[string]any, string, error) - }); ok { - // fetchCtx、cancel 保存fetchCtx、cancel,供当前处理流程使用 - fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second) - // body、myID、fetchErr 保存body、myID、fetchErr,供当前处理流程使用 - body, myID, fetchErr := fetcher.FetchChatConversations(fetchCtx, cursor, 100) - cancel() - if fetchErr == nil { - // page、saveErr 保存page、saveErr,供当前处理流程使用 - page, saveErr := s.chat.RecordConversationPage(r.Context(), accountID, myID, body) - if saveErr != nil { - writeErr(w, http.StatusInternalServerError, "保存历史联系人失败") - return - } - hasMore, nextCursor = page.HasMore, page.NextCursor - } else { - s.recoverExpiredMTOPSession(r.Context(), accountID, fetchErr) - } - } + if refresh { + // fetchCtx 和 cancel 限制平台联系人刷新请求的最长时间。 + fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + // page 和 fetchErr 保存应用层联系人分页结果及平台/持久化错误。 + page, fetchErr := s.chatApplication().RefreshConversations(fetchCtx, accountID, cursor, 100) + cancel() + if fetchErr == nil { + hasMore, nextCursor = page.HasMore, page.NextCursor + } else if errors.Is(fetchErr, chatapp.ErrRefreshPersist) { + writeErr(w, http.StatusInternalServerError, "保存历史联系人失败") + return + } else if !errors.Is(fetchErr, chatapp.ErrRefreshUnavailable) && !errors.Is(fetchErr, chatapp.ErrOffline) { + s.recoverExpiredSession(r.Context(), accountID, fetchErr) } } // rows、err 保存应用层会话摘要及查询错误。 @@ -97,7 +85,7 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) { resolveCancel() rows = refreshedRows if sessionErr != nil { - s.recoverExpiredMTOPSession(r.Context(), accountID, sessionErr) + s.recoverExpiredSession(r.Context(), accountID, sessionErr) } } writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOsFromApplication(rows), HasMore: hasMore, NextCursor: nextCursor}) @@ -105,7 +93,7 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) { // sendChatImage 负责send聊天图片相关处理。 func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) { - if s.chat == nil || s.Manager == nil { + if !s.chatApplication().ImageUploadAvailable() { writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用") return } @@ -193,37 +181,28 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) { cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64) // limit 保存上限,供当前处理流程使用 limit := parsePositiveInt(r.URL.Query().Get("limit"), 50) - if s.chat != nil && s.Manager != nil { - if // sender、ok 保存sender、ok,供当前处理流程使用 - sender, ok := s.Manager.GetInstance(accountID); ok { - if // fetcher、ok 保存fetcher、ok,供当前处理流程使用 - fetcher, ok := sender.(interface { - FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error) - }); ok { - // fetchCtx、cancel 保存fetchCtx、cancel,供当前处理流程使用 - fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second) - // body、myID、fetchErr 保存body、myID、fetchErr,供当前处理流程使用 - body, myID, fetchErr := fetcher.FetchChatHistory(fetchCtx, chatID, cursor, limit) - cancel() - if fetchErr == nil { - // sessions 保存sessions,供当前处理流程使用 - current, _ := s.chatApplication().FindSession(r.Context(), sess.UserID, accountID, chatID) - // page、saveErr 保存page、saveErr,供当前处理流程使用 - page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, adapter.ChatSessionFromApplication(current), body) - if saveErr != nil { - writeErr(w, http.StatusInternalServerError, "保存聊天历史失败") - return - } - // 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 - } - } + // current 保存刷新前的本地会话摘要,供平台历史写入和响应展示使用。 + current, _ := s.chatApplication().FindSession(r.Context(), sess.UserID, accountID, chatID) + // fetchCtx 和 cancel 限制平台历史刷新请求的最长时间。 + fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + // refreshed 和 fetchErr 保存应用层消息分页结果及平台/持久化错误。 + refreshed, fetchErr := s.chatApplication().RefreshHistory(fetchCtx, accountID, chatID, cursor, limit, current) + cancel() + if fetchErr == nil { + // resolved 和 identityErr 保存身份补全后的会话及平台查询错误。 + resolved, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), refreshed.Session) + if identityErr != nil { + s.recoverExpiredSession(r.Context(), accountID, identityErr) } + writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(refreshed.Messages), HasMore: refreshed.HasMore, NextCursor: refreshed.NextCursor, Session: newChatSessionDTOFromApplication(resolved)}) + return + } + if errors.Is(fetchErr, chatapp.ErrRefreshPersist) { + writeErr(w, http.StatusInternalServerError, "保存聊天历史失败") + return + } + if !errors.Is(fetchErr, chatapp.ErrRefreshUnavailable) && !errors.Is(fetchErr, chatapp.ErrOffline) { + s.recoverExpiredSession(r.Context(), accountID, fetchErr) } // page、err 保存page、err,供当前处理流程使用 page, err := s.chatApplication().ListStoredMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit) @@ -237,7 +216,7 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) { // resolved 和 identityErr 保存身份补全后的会话及平台查询错误。 resolved, identityErr := s.chatApplication().ResolveSessionIdentity(r.Context(), session) if identityErr != nil { - s.recoverExpiredMTOPSession(r.Context(), accountID, identityErr) + s.recoverExpiredSession(r.Context(), accountID, identityErr) } session = resolved } @@ -257,7 +236,7 @@ type sendChatMessageRequest struct { // sendChatMessage 负责send聊天消息相关处理。 func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) { - if s.chat == nil || s.Manager == nil { + if !s.chatApplication().SendingAvailable() { writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用") return } @@ -328,16 +307,16 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) { // chatWebSocket 负责聊天WebSocket相关处理。 func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) { - if s.chat == nil { - writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用") - return - } // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) - // events、unsubscribe、err 保存events、unsubscribe、err,供当前处理流程使用 - events, unsubscribe, err := s.chat.Subscribe(r.Context(), sess.UserID) + // events、unsubscribe、err 保存应用层实时事件、清理函数和订阅错误。 + events, unsubscribe, err := s.chatApplication().Subscribe(r.Context(), sess.UserID) if err != nil { - writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败") + if errors.Is(err, chatapp.ErrSubscriptionUnavailable) { + writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用") + } else { + writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败") + } return } // conn、err 保存conn、err,供当前处理流程使用 diff --git a/internal/server/cookie_handlers.go b/internal/server/cookie_handlers.go index 0fbabd9..ae222bf 100644 --- a/internal/server/cookie_handlers.go +++ b/internal/server/cookie_handlers.go @@ -13,7 +13,6 @@ import ( accountapp "xianyu-go/internal/application/account" automationapp "xianyu-go/internal/application/automation" "xianyu-go/internal/auth" - "xianyu-go/internal/engine" ) // mountCookies 账号 cookie 管理端点。 @@ -102,31 +101,14 @@ func (s *Server) writeLongLoginError(w http.ResponseWriter, err error) { // updateRunningCookie 负责updateRunning登录凭证相关处理。 func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string) { - s.wakeCredentialBlockedAutomation(ctx, cookieID) - // repository 提供运行时更新前的账号启用状态读取。 - repository := s.accountLoginRepositoryForServer() - if s.Manager == nil || repository == nil || !repository.GetStatus(ctx, cookieID) { + // runtimeService 负责唤醒凭证阻塞任务并将 Cookie 同步到账号运行实例。 + runtimeService := s.accountRuntimeApplication() + if runtimeService == nil { return } - if // sender、ok 保存sender、ok,供当前处理流程使用 - sender, ok := s.Manager.GetInstance(cookieID); ok { - sender.UpdateCookie(value) - } -} - -// wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。 -func (s *Server) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) { - if s == nil { - return - } - // service 提供凭证恢复后的自动化任务唤醒能力。 - service := s.credentialWakeApplication() - if service == nil { - return - } - if // err 保存err,供当前处理流程使用 - err := service.WakeCredentialBlocked(ctx, cookieID); err != nil && s.Logger != nil { - s.Logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err) + // runtimeErr 保存账号运行时同步或自动化唤醒错误。 + if runtimeErr := runtimeService.UpdateCookie(ctx, cookieID, value); runtimeErr != nil && s.Logger != nil { + s.Logger.Warn("Cookie 更新后同步账号运行时失败", "cookie_id", cookieID, "err", runtimeErr) } } @@ -223,22 +205,24 @@ func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) writeErr(w, http.StatusInternalServerError, "获取账号失败") return } - runtime := map[string]engine.RuntimeStatus{} // runtime 保存当前账号引擎状态。 - if s.Manager != nil { - runtime = s.Manager.RuntimeStatuses() + // runtime、runtimeErr 保存应用层返回的账号运行状态快照及读取错误。 + runtime, runtimeErr := s.accountRuntimeApplication().RuntimeStatuses(r.Context()) + if runtimeErr != nil { + writeErr(w, http.StatusInternalServerError, "获取账号运行状态失败") + return } - result := make(map[string]engine.RuntimeStatus, len(cookieIDs)) // result 是返回给前端的状态映射。 - for _, cid := range cookieIDs { // cid 是当前账号 ID。 + result := make(map[string]accountapp.RuntimeStatus, len(cookieIDs)) // result 是返回给前端的状态映射。 + for _, cid := range cookieIDs { // cid 是当前账号 ID。 enabled, statusErr := accountSummary.StatusOwned(r.Context(), sess.UserID, cid) if statusErr != nil || !enabled { - result[cid] = engine.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()} + result[cid] = accountapp.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()} continue } if status, ok := runtime[cid]; ok { // status 和 ok 表示已记录的运行状态及存在性。 result[cid] = status continue } - result[cid] = engine.RuntimeStatus{State: engine.RuntimeError, Message: "账号服务未运行", UpdatedAt: time.Now()} + result[cid] = accountapp.RuntimeStatus{State: "error", Message: "账号服务未运行", UpdatedAt: time.Now()} } writeJSON(w, http.StatusOK, result) } diff --git a/internal/server/item_batch_management_application.go b/internal/server/item_batch_management_application.go index 0440fbe..00f94c7 100644 --- a/internal/server/item_batch_management_application.go +++ b/internal/server/item_batch_management_application.go @@ -1,23 +1,31 @@ package server +import ( + "errors" + + itemapp "xianyu-go/internal/application/items" +) + // serverBatchManagementRuntime 将批次管理应用端口接到 Server 的 worker 生命周期边界。 type serverBatchManagementRuntime struct { // server 保存批次 worker 启动与取消所需的 Server 生命周期入口。 server *Server + // coordinator 保存应用层批次 worker 生命周期协调器。 + coordinator *itemapp.BatchWorkerCoordinator } -// StartBatch 启动已由应用服务声明租约的批量 worker。 -func (runtime serverBatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) { - if runtime.server == nil { - return +// StartBatch 启动已由应用服务声明租约的批量 worker,并返回协调器登记失败。 +func (runtime serverBatchManagementRuntime) StartBatch(userID int64, batchID, workerToken string) error { + if runtime.server == nil || runtime.coordinator == nil { + return errors.New("批量 worker 协调器未装配") } - runtime.server.startPublishBatchWorker(runtime.server.lifecycleContext(), userID, batchID, workerToken) + return runtime.coordinator.Start(runtime.server.lifecycleContext(), userID, batchID, workerToken) } // CancelBatch 取消指定批次的后台 worker。 func (runtime serverBatchManagementRuntime) CancelBatch(batchID, workerToken string) { - if runtime.server == nil { + if runtime.coordinator == nil { return } - runtime.server.cancelPublishBatch(batchID, workerToken) + _ = runtime.coordinator.Cancel(batchID, workerToken) } diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go index 2bab3fd..06881d4 100644 --- a/internal/server/item_handlers.go +++ b/internal/server/item_handlers.go @@ -404,31 +404,27 @@ func (s *Server) writeItemSyncError(w http.ResponseWriter, err error) { func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) { // sess 保存sess,供当前处理流程使用 sess := auth.SessionFromContext(r.Context()) - // repository 提供平台请求所需的窄凭证视图,数据库解密和所有权读取均封装在 adapter。 - repository := s.accountLoginRepositoryForServer() - if repository == nil { + // service 提供消费者定义的平台凭证只读端口;本校验不会把 Cookie 明文带入 HTTP 层。 + service := s.platformCredentialApplication() + if service == nil { writeErr(w, http.StatusInternalServerError, "查询账号失败") return "", 0, false } - // detail 和 err 保存账号归属及 Cookie 可用性检查结果;明文仅在当前函数返回给已授权业务适配器。 - detail, err := repository.LoadPlatformDetail(r.Context(), cookieID) + // value、err 保存已完成归属复核的平台 Cookie 及校验错误;明文只交给当前平台调用链。 + value, err := service.LoadOwnedValue(r.Context(), sess.UserID, cookieID) if err != nil { - if errors.Is(err, accountapp.ErrCredentialNotFound) { + if errors.Is(err, accountapp.ErrCredentialNotFound) || errors.Is(err, accountapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "无权限操作该账号") return "", 0, false } + if errors.Is(err, accountapp.ErrCredentialEmpty) { + writeErr(w, http.StatusBadRequest, "账号 cookie 为空") + return "", 0, false + } writeErr(w, http.StatusInternalServerError, "查询账号失败") return "", 0, false } - 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 detail.Value, sess.UserID, true + return value, sess.UserID, true } // listItemsByCookie 负责list商品列表By登录凭证相关处理。 diff --git a/internal/server/item_publish_batch_handlers.go b/internal/server/item_publish_batch_handlers.go index 1614085..30a72ae 100644 --- a/internal/server/item_publish_batch_handlers.go +++ b/internal/server/item_publish_batch_handlers.go @@ -24,9 +24,8 @@ import ( // maxPublishBatchRows 保存max发布批次Rows,供当前处理流程使用 const ( - maxPublishBatchRows = 50 - publishBatchLease = 5 * time.Minute - publishBatchJobTimeout = 2 * time.Hour + maxPublishBatchRows = 50 + publishBatchLease = 5 * time.Minute ) // postPublishError 保存post发布错误,供当前处理流程使用 @@ -457,58 +456,6 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: startedID}) } -// startPublishBatchWorker 负责开始发布批次工作器相关处理。 -func (s *Server) startPublishBatchWorker(parent context.Context, userID int64, batchID, workerToken string) { - // workerDone 保存工作器Done,供当前处理流程使用 - workerDone := s.beginWorker() - // #nosec G118 -- worker 由超时和 Server 根 context 共同约束。 - go func() { - defer workerDone() - // jobCtx、cancel 保存jobCtx、cancel,供当前处理流程使用 - jobCtx, cancel := context.WithTimeout(parent, publishBatchJobTimeout) - s.registerPublishBatchCancel(batchID, workerToken, cancel) - defer cancel() - defer s.unregisterPublishBatchCancel(batchID, workerToken) - // runner 负责批量发布的租约、逐行失败记录和最终状态收口。 - if runErr := s.itemBatchRunnerApplication().Run(jobCtx, userID, batchID, workerToken, false); runErr != nil && s.Logger != nil { - s.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", runErr) - } - }() -} - -// RunPublishBatchRecovery 定期接管租约过期或明确因进程中断失败的批次。 -func (s *Server) RunPublishBatchRecovery(ctx context.Context) { - s.recoverPublishBatchesOnce(ctx) - // ticker 保存ticker,供当前处理流程使用 - ticker := time.NewTicker(time.Minute) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - s.recoverPublishBatchesOnce(ctx) - } - } -} - -// StartPublishBatchRecovery 先登记生命周期,再启动恢复循环,避免关闭流程在 -// goroutine 尚未调度时误判扫描器已经退出。 -// StartPublishBatchRecovery 启动发布批次Recovery。 -func (s *Server) StartPublishBatchRecovery(ctx context.Context) string { - return s.startBackgroundTaskContext("批量发布恢复扫描器", ctx, func() { - s.RunPublishBatchRecovery(ctx) - }) -} - -// recoverPublishBatchesOnce 负责recover发布批次列表Once相关处理。 -func (s *Server) recoverPublishBatchesOnce(ctx context.Context) { - // err 保存恢复扫描应用服务返回的全局查询错误。 - if err := s.itemBatchRecoveryApplication().Recover(ctx); err != nil && s.Logger != nil { - s.Logger.Warn("扫描可恢复批量发布任务失败", "err", err) - } -} - // downloadItemPublishBatchResult 负责download商品发布批次结果相关处理。 func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.Request) { // sess 保存sess,供当前处理流程使用 @@ -599,57 +546,6 @@ func publishBatchFailure(err error, batchStatus string) (string, string) { return message, failureKind } -// registerPublishBatchCancel 负责register发布批次取消相关处理。 -func (s *Server) registerPublishBatchCancel(batchID, workerToken string, cancel context.CancelFunc) { - s.publishMu.Lock() - defer s.publishMu.Unlock() - if s.publishCancels == nil { - s.publishCancels = make(map[string]publishBatchWorker) - } - if // old 保存old,供当前处理流程使用 - old := s.publishCancels[batchID]; old.cancel != nil { - old.cancel() - } - s.publishCancels[batchID] = publishBatchWorker{token: workerToken, cancel: cancel} -} - -// unregisterPublishBatchCancel 负责unregister发布批次取消相关处理。 -func (s *Server) unregisterPublishBatchCancel(batchID, workerToken string) { - s.publishMu.Lock() - defer s.publishMu.Unlock() - if // current 保存current,供当前处理流程使用 - current := s.publishCancels[batchID]; current.token == workerToken { - delete(s.publishCancels, batchID) - } -} - -// cancelPublishBatch 负责取消发布批次相关处理。 -func (s *Server) cancelPublishBatch(batchID, workerToken string) bool { - s.publishMu.Lock() - // worker 保存工作器,供当前处理流程使用 - worker := s.publishCancels[batchID] - s.publishMu.Unlock() - if worker.token != workerToken || worker.cancel == nil { - return false - } - worker.cancel() - return true -} - -// 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("批量发布本地收口端口未装配") - } - 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 根据应用批次统计返回兼容的最终状态。 func finalPublishBatchStatus(batch *itemapp.BatchInfo) string { if batch == nil { @@ -738,23 +634,23 @@ func (s *Server) cookieOwnedByUser(ctx context.Context, userID int64, cookieID s // cookieValueForUser 读取指定用户拥有的单个账号 Cookie 明文。 func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID string) (string, error) { - // repository 提供按账号读取的平台窄凭证视图,解密和数据库访问均由 adapter 负责。 - repository := s.accountLoginRepositoryForServer() - if repository == nil { - return "", errors.New("账号凭证 repository 未初始化") + // service 提供消费者定义的平台凭证读取端口,明文只在当前平台请求边界短暂存在。 + service := s.platformCredentialApplication() + if service == nil { + return "", errors.New("平台凭证读取服务未初始化") } - // detail 和 err 保存账号归属与 Cookie 明文读取结果;明文只在当前发布边界短暂存在。 - detail, err := repository.LoadPlatformDetail(ctx, cookieID) + // value 和 err 保存已通过归属复核的 Cookie 明文及读取错误;value 不进入 HTTP 响应。 + value, err := service.LoadOwnedValue(ctx, userID, cookieID) if err != nil { - if errors.Is(err, accountapp.ErrCredentialNotFound) { + if errors.Is(err, accountapp.ErrCredentialNotFound) || errors.Is(err, accountapp.ErrForbidden) || errors.Is(err, accountapp.ErrCredentialEmpty) { return "", errors.New("账号不存在或 Cookie 为空") } return "", err } - if detail == nil || detail.UserID != userID || strings.TrimSpace(detail.Value) == "" { + if strings.TrimSpace(value) == "" { return "", errors.New("账号不存在或 Cookie 为空") } - return detail.Value, nil + return value, nil } // cardOwnedByUser 判断指定卡券组是否属于用户。 @@ -815,8 +711,6 @@ func firstNonEmpty(values ...string) string { // serverBatchPublisher 将 Server 的商品发布细节适配为应用层批量发布端口。 type serverBatchPublisher struct { - // server 保存平台发布和本地商品结果适配所需的 Server 引用。 - server *Server // remotePort 保存已装配的平台与凭证端口,避免 worker 再进入 Server 远端逻辑。 remotePort itemapp.BatchPublishPort // localService 保存已装配的本地商品、自动化规则和成功检查点收口服务。 @@ -825,7 +719,7 @@ type serverBatchPublisher struct { // PublishRow 调用批量远端端口并收口本地结果,应用层不接触数据库或 MTOP 类型。 func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) error { - if p.server == nil || p.remotePort == nil { + if p.remotePort == nil { return errors.New("批量发布端口未装配") } if p.localService == nil { @@ -844,7 +738,13 @@ func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row if outcome.Result == nil { return errors.New("发布商品接口未返回结果") } - return p.server.completeBatchPublishOutcome(ctx, userID, p.localService, row, workerToken, outcome) + if outcome.ResponseCookieErr != nil { + return &itemapp.PostPublishError{Err: outcome.ResponseCookieErr} + } + if ctx.Err() != nil { + return &itemapp.PostPublishError{Err: ctx.Err()} + } + return p.localService.Complete(ctx, userID, row, workerToken, outcome.Result) } // newItemBatchRunnerApplication 创建批量发布应用层 worker 编排器。 @@ -858,7 +758,7 @@ func newItemBatchRunnerApplication(server *Server, remotePort itemapp.BatchPubli IsSessionExpired: adapter.IsSessionExpiredError, ClassifyFailure: publishBatchFailure, } - return itemapp.NewBatchRunner(server.dependencies.NewItemBatchRepository(), serverBatchPublisher{server: server, remotePort: remotePort, localService: localService}, options) + return itemapp.NewBatchRunner(server.itemDependencies.NewItemBatchRepository(), serverBatchPublisher{remotePort: remotePort, localService: localService}, options) } // publishBatchLocation 保存批量发布请求中的发货地字段,不让平台 DTO 进入 HTTP 层。 diff --git a/internal/server/login_audit.go b/internal/server/login_audit.go index 3d4d15f..a45c4f4 100644 --- a/internal/server/login_audit.go +++ b/internal/server/login_audit.go @@ -1,36 +1,8 @@ package server -import ( - "context" - - accountapp "xianyu-go/internal/application/account" -) +import accountapp "xianyu-go/internal/application/account" const ( // loginMethodPassword 保留 Server 内部调用方使用的账号密码登录方式别名。 loginMethodPassword = accountapp.LoginMethodPassword - // loginMethodQRScan 保留 Server 内部调用方使用的扫码登录方式别名。 - loginMethodQRScan = accountapp.LoginMethodQRScan ) - -// markSuccessfulLogin 将 Server 登录成功事件交给账号应用服务审计,不在 HTTP 层组装数据库模型。 -func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userID int64, method, message string) { - if s == nil { - return - } - // auditService 保存应用层登录审计服务;它拥有归一化、启用和日志写入编排。 - auditService := s.loginAuditApplication() - if auditService == nil { - 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 index 051b282..ce7e47f 100644 --- a/internal/server/login_audit_test.go +++ b/internal/server/login_audit_test.go @@ -3,10 +3,12 @@ package server import ( "context" "testing" + + accountapp "xianyu-go/internal/application/account" ) -// TestMarkSuccessfulLoginUsesApplicationAuditService 验证 Server 仅调用应用审计服务并保持登录成功持久化语义。 -func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) { +// TestLoginAuditApplicationPersistsSuccessfulLogin 验证 Server 通过应用审计服务保持登录成功持久化语义。 +func TestLoginAuditApplicationPersistsSuccessfulLogin(t *testing.T) { // srv、store 和 cleanup 保存带固定管理员账号的 HTTP 测试服务及资源清理函数。 srv, store, cleanup := newTestServer(t) defer cleanup() @@ -15,8 +17,11 @@ func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) { if adminErr != nil { t.Fatal(adminErr) } - // srv.markSuccessfulLogin 执行账号密码登录别名的成功审计。 - srv.markSuccessfulLogin(context.Background(), "acc1", admin.ID, "password_login", "账号登录成功") + // auditErr 保存应用审计服务执行账号密码登录成功记录的结果。 + auditErr := srv.loginAuditApplication().RecordSuccessfulLogin(context.Background(), accountapp.SuccessfulLoginInput{AccountID: "acc1", UserID: admin.ID, Method: "password_login", Message: "账号登录成功"}) + if auditErr != nil { + t.Fatalf("应用审计服务写入失败: %v", auditErr) + } // summary 保存应用服务写入后的账号非敏感摘要。 summary, summaryErr := store.Cookies.GetSummaryOwned(context.Background(), admin.ID, "acc1") if summaryErr != nil || summary.LoginMethod != loginMethodPassword || summary.LastLoginAt == 0 { @@ -29,13 +34,16 @@ func TestMarkSuccessfulLoginUsesApplicationAuditService(t *testing.T) { } } -// TestMarkSuccessfulLoginSkipsEmptyMethod 验证 Server 对缺少登录方式的兼容空操作不创建审计记录。 -func TestMarkSuccessfulLoginSkipsEmptyMethod(t *testing.T) { +// TestLoginAuditApplicationSkipsEmptyMethod 验证应用审计服务对缺少登录方式的兼容空操作不创建审计记录。 +func TestLoginAuditApplicationSkipsEmptyMethod(t *testing.T) { // srv、store 和 cleanup 保存 HTTP 测试服务及资源清理函数。 srv, store, cleanup := newTestServer(t) defer cleanup() - // srv.markSuccessfulLogin 执行缺少方式的兼容调用。 - srv.markSuccessfulLogin(context.Background(), "acc1", 1, "", "不应记录") + // auditErr 保存缺少登录方式时的兼容空操作结果。 + auditErr := srv.loginAuditApplication().RecordSuccessfulLogin(context.Background(), accountapp.SuccessfulLoginInput{AccountID: "acc1", UserID: 1, Message: "不应记录"}) + if auditErr != nil { + t.Fatalf("缺少登录方式不应失败: %v", auditErr) + } // logs 保存兼容调用后的数据库审计记录。 logs, logsErr := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10) if logsErr != nil { diff --git a/internal/server/mtop_cookie_session.go b/internal/server/mtop_cookie_session.go index 1e3d46a..4887d95 100644 --- a/internal/server/mtop_cookie_session.go +++ b/internal/server/mtop_cookie_session.go @@ -22,7 +22,7 @@ func (s *Server) persistMTopCookieSessionLocked( if s == nil { return "", false, true, errors.New("cookie 会话持久化服务未初始化") } - // repository 负责在凭证适配器内保存 Cookie 与加密 metadata;Server 不直接访问 Store。 - repository := s.accountLoginRepositoryForServer() - return adapter.PersistCookieSessionLocked(ctx, repository, detail, session) + // sessionPort 只负责在凭证适配器内保存 Cookie 与加密 metadata;Server 不直接访问 Store。 + sessionPort := s.platformCredentialSessionPort() + return adapter.PersistCookieSessionLocked(ctx, sessionPort, detail, session) } diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go index 420b0f1..bd466a3 100644 --- a/internal/server/order_handlers.go +++ b/internal/server/order_handlers.go @@ -170,24 +170,8 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) { func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) { // orderID 保存订单ID,供当前处理流程使用 orderID := chi.URLParam(r, "order_id") - // req 保存req,供当前处理流程使用 - var req struct { - OrderStatus *string `json:"order_status"` - Status *string `json:"status"` - ItemID *string `json:"item_id"` - BuyerID *string `json:"buyer_id"` - SpecName *string `json:"spec_name"` - SpecValue *string `json:"spec_value"` - Quantity *any `json:"quantity"` - Amount *any `json:"amount"` - ReceiverName *string `json:"receiver_name"` - ReceiverPhone *string `json:"receiver_phone"` - ReceiverAddress *string `json:"receiver_address"` - ReceiverCity *string `json:"receiver_city"` - ChatID *string `json:"chat_id"` - SystemShipped *bool `json:"system_shipped"` - ItemTitle *string `json:"item_title"` - } + // req 保存具名订单更新请求,兼容旧客户端的状态别名和数值字段。 + var req orderUpdateRequestDTO if // err 保存err,供当前处理流程使用 err := decodeJSON(r, &req); err != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") @@ -247,11 +231,8 @@ func normalizeOrderAmount(raw string) (string, bool) { // manualShipOrders 负责manualShip订单列表相关处理。 func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { - // req 保存req,供当前处理流程使用 - var req struct { - OrderIDs []string `json:"order_ids"` - ShipMode string `json:"ship_mode"` - } + // req 保存具名批量发货请求。 + var req manualShipRequestDTO if // err 保存err,供当前处理流程使用 err := decodeJSON(r, &req); err != nil { writeErr(w, http.StatusBadRequest, "请求格式错误") @@ -333,11 +314,3 @@ func isStableOrderStatus(status string) bool { return false } } - -// notifyDelivery 在 Notifier 已注入时发送发货结果通知,未注入则跳过。 -func (s *Server) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) { - if s.notifier == nil { - return - } - s.notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID) -} diff --git a/internal/server/order_handlers_extra_test.go b/internal/server/order_handlers_extra_test.go index ee82236..aa6a5cd 100644 --- a/internal/server/order_handlers_extra_test.go +++ b/internal/server/order_handlers_extra_test.go @@ -112,27 +112,6 @@ func TestCancelOrderRefreshJob(t *testing.T) { } } -// TestOrderRefreshWorkerCancellation 验证内存 worker 控制句柄可以被安全取消并清理。 -func TestOrderRefreshWorkerCancellation(t *testing.T) { - // srv 保存仅用于测试 worker 控制表的 Server。 - srv := &Server{} - // ctx、cancel 保存可观察的 worker Context 及其取消函数。 - ctx, cancel := context.WithCancel(context.Background()) - srv.registerOrderRefreshWorker("job-1", "token-1", cancel) - if !srv.cancelOrderRefreshWorker("job-1") { - t.Fatal("expected active refresh worker to be cancelled") - } - select { - case <-ctx.Done(): - default: - t.Fatal("worker context was not cancelled") - } - srv.unregisterOrderRefreshWorker("job-1", "token-1") - if srv.cancelOrderRefreshWorker("job-1") { - t.Fatal("unregistered refresh worker should not be cancellable") - } -} - // TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。 func TestRefreshOrdersNoBrowser(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 diff --git a/internal/server/order_refresh_job_handlers.go b/internal/server/order_refresh_job_handlers.go index 0f28349..f678142 100644 --- a/internal/server/order_refresh_job_handlers.go +++ b/internal/server/order_refresh_job_handlers.go @@ -1,25 +1,16 @@ package server import ( - "context" "encoding/json" "errors" - "fmt" "net/http" - "time" "github.com/go-chi/chi/v5" - orderapp "xianyu-go/internal/application/orders" + orderapp "xianyu-go/internal/application/orders" "xianyu-go/internal/auth" ) -// orderRefreshJobTimeout 限制单个订单刷新后台任务的最长执行时间。 -const orderRefreshJobTimeout = 30 * time.Minute - -// orderRefreshJobLease 为运行中的订单刷新任务提供可恢复租约。 -const orderRefreshJobLease = orderRefreshJobTimeout + time.Minute - // orderRefreshJobStartResponse 是创建订单刷新任务后的响应 DTO。 type orderRefreshJobStartResponse struct { // Success 表示任务是否成功创建。 @@ -34,9 +25,9 @@ type orderRefreshJobStartResponse struct { type orderRefreshJobStatusResponse struct { // Success 表示查询是否成功。 Success bool `json:"success"` - // JobID 是后台任务标识。 + // JobID 是任务标识。 JobID string `json:"job_id"` - // Status 是 queued/running/succeeded/failed 任务状态。 + // Status 是任务状态。 Status string `json:"status"` // ErrorMessage 是任务失败原因。 ErrorMessage string `json:"error_message,omitempty"` @@ -54,26 +45,6 @@ type orderRefreshJobCancelResponse struct { Status string `json:"status"` } -// orderRefreshWorker 保存可被用户取消的订单刷新 worker 控制句柄。 -type orderRefreshWorker struct { - // token 是当前 worker 的租约令牌。 - token string - // cancel 是取消当前 worker Context 的函数。 - 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) @@ -81,36 +52,26 @@ func (s *Server) mountOrderRefreshJobRoutes(r chi.Router, prefix string) { r.Delete(prefix+"/orders/refresh/{job_id}", s.cancelOrderRefreshJob) } -// startOrderRefreshJob 创建订单刷新任务并立即返回任务标识。 +// startOrderRefreshJob 解析筛选条件并调用应用服务创建订单刷新任务。 func (s *Server) startOrderRefreshJob(w http.ResponseWriter, r *http.Request) { // sess 保存当前认证会话。 sess := auth.SessionFromContext(r.Context()) // cookieID、filterStatus 保存订单刷新筛选条件。 cookieID, filterStatus := r.FormValue("cookie_id"), r.FormValue("status") - if cookieID != "" && !s.orders().orderOwnedByUser(r.Context(), sess.UserID, cookieID) { + // started、err 保存应用服务创建并启动任务的结果。 + started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), s.lifecycleContext(), sess.UserID, cookieID, filterStatus) + if errors.Is(err, orderapp.ErrForbidden) { writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问") return } - // job 保存待持久化的订单刷新任务。 - job := &orderapp.RefreshJob{ - ID: "order-refresh-" + randomHex(16), UserID: sess.UserID, - CookieID: cookieID, FilterStatus: filterStatus, - } - // err 表示创建任务的数据库错误。 - if err := s.orders().services.RefreshJobs.Create(r.Context(), job); err != nil { + if err != nil { + if s.Logger != nil { + s.Logger.Error("创建订单刷新任务失败", "err", err) + } writeErr(w, http.StatusInternalServerError, "创建订单刷新任务失败") return } - // token 保存本次执行者的租约令牌。 - token := randomHex(16) - // claimed、claimErr 保存任务抢占结果及错误。 - claimed, claimErr := s.orders().services.RefreshJobs.Claim(r.Context(), job.ID, token, time.Now().Add(orderRefreshJobLease).Unix()) - if claimErr != nil || !claimed { - writeErr(w, http.StatusInternalServerError, "启动订单刷新任务失败") - return - } - s.startOrderRefreshWorker(job, token) - writeJSON(w, http.StatusAccepted, orderRefreshJobStartResponse{Success: true, JobID: job.ID, Status: "running"}) + writeJSON(w, http.StatusAccepted, orderRefreshJobStartResponse{Success: true, JobID: started.Job.ID, Status: "running"}) } // getOrderRefreshJob 返回当前用户拥有的订单刷新任务状态和结果。 @@ -119,8 +80,8 @@ func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) { sess := auth.SessionFromContext(r.Context()) // jobID 保存路径中的订单刷新任务标识。 jobID := chi.URLParam(r, "job_id") - // job、err 保存任务读取结果及错误。 - job, err := s.orders().services.RefreshJobs.Get(r.Context(), sess.UserID, jobID) + // job、err 保存应用服务读取结果及错误。 + job, err := s.orderRefreshJobsApplication().GetJob(r.Context(), sess.UserID, jobID) if errors.Is(err, orderapp.ErrRefreshJobNotFound) { writeErr(w, http.StatusNotFound, "订单刷新任务不存在") return @@ -132,8 +93,8 @@ func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) { // response 保存任务状态响应 DTO。 response := orderRefreshJobStatusResponse{Success: true, JobID: job.ID, Status: job.Status, ErrorMessage: job.ErrorMessage} if job.ResultJSON != "" && job.ResultJSON != "{}" { - // result 保存成功任务的具名刷新结果。 - var result orderRefreshResponse + // result 保存应用层稳定结果模型,避免 HTTP 层承担持久化结果形状。 + var result orderapp.RefreshJobResult // err 表示任务结果 JSON 解析错误。 if err := json.Unmarshal([]byte(job.ResultJSON), &result); err != nil { if s.Logger != nil { @@ -142,244 +103,58 @@ func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, "读取订单刷新结果失败") return } - response.Result = &result + // mapped 保存转换后的 HTTP 兼容结果 DTO。 + mapped := orderRefreshResponseFromJobResult(result) + response.Result = &mapped } writeJSON(w, http.StatusOK, response) } -// cancelOrderRefreshJob 按当前用户归属取消订单刷新任务并通知运行中的 worker。 +// cancelOrderRefreshJob 按当前用户归属取消任务,并由应用服务通知运行中的 worker。 func (s *Server) cancelOrderRefreshJob(w http.ResponseWriter, r *http.Request) { // sess 保存当前认证会话。 sess := auth.SessionFromContext(r.Context()) // jobID 保存路径中的订单刷新任务标识。 jobID := chi.URLParam(r, "job_id") - // cancelled、err 保存数据库取消结果及错误。 - cancelled, err := s.orders().services.RefreshJobs.Cancel(r.Context(), sess.UserID, jobID) + // result、err 保存应用服务取消结果及错误。 + result, err := s.orderRefreshJobsApplication().CancelForUser(r.Context(), sess.UserID, jobID) + if errors.Is(err, orderapp.ErrRefreshJobNotFound) { + writeErr(w, http.StatusNotFound, "订单刷新任务不存在") + return + } if err != nil { writeErr(w, http.StatusInternalServerError, "取消订单刷新任务失败") return } - if cancelled { - s.cancelOrderRefreshWorker(jobID) - writeJSON(w, http.StatusOK, orderRefreshJobCancelResponse{Success: true, JobID: jobID, Status: "cancelled"}) - return - } - // job、getErr 保存取消未生效时的当前任务状态及查询错误。 - job, getErr := s.orders().services.RefreshJobs.Get(r.Context(), sess.UserID, jobID) - if errors.Is(getErr, orderapp.ErrRefreshJobNotFound) { - writeErr(w, http.StatusNotFound, "订单刷新任务不存在") - return - } - if getErr != nil { - writeErr(w, http.StatusInternalServerError, "读取订单刷新任务失败") - return - } - if job.Status == "cancelled" { + if result.Cancelled || (result.Job != nil && result.Job.Status == "cancelled") { writeJSON(w, http.StatusOK, orderRefreshJobCancelResponse{Success: true, JobID: jobID, Status: "cancelled"}) return } writeErr(w, http.StatusConflict, "订单刷新任务已结束,无法取消") } -// startOrderRefreshWorker 启动受 Server 生命周期管理的订单刷新 worker。 -func (s *Server) startOrderRefreshWorker(job *orderapp.RefreshJob, token string) { - if job == nil { - return +// orderRefreshResponseFromJobResult 将应用层任务结果映射为历史 HTTP 响应 DTO。 +func orderRefreshResponseFromJobResult(result orderapp.RefreshJobResult) orderRefreshResponse { + // results 保存转换后的 HTTP 结果行。 + results := make([]orderRefreshResultDTO, 0, len(result.Results)) + // item 表示当前应用层任务结果行。 + for _, item := range result.Results { + results = append(results, orderRefreshResultDTO{ + Success: item.Success, CookieID: item.CookieID, Discovered: item.Discovered, + Updated: item.Updated, SoftDeleted: item.SoftDeleted, OrderID: item.OrderID, + Stage: item.Stage, Message: item.Message, Error: item.Error, + OldStatus: item.OldStatus, NewStatus: item.NewStatus, + }) } - // parent 保存 Server 生命周期上下文,避免 HTTP 请求结束取消后台任务。 - parent := s.lifecycleContext() - if parent == nil { - 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.startBackgroundTaskResult("订单刷新任务", jobCtx, func() error { - defer cancel() - defer s.unregisterOrderRefreshWorker(job.ID, 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 - }) -} - -// registerOrderRefreshWorker 登记可取消的订单刷新 worker。 -func (s *Server) registerOrderRefreshWorker(jobID, token string, cancel context.CancelFunc) { - s.orderRefreshMu.Lock() - defer s.orderRefreshMu.Unlock() - if s.orderRefreshCancels == nil { - s.orderRefreshCancels = make(map[string]orderRefreshWorker) - } - // previous 保存同一任务的旧 worker 控制句柄。 - previous := s.orderRefreshCancels[jobID] - if previous.cancel != nil && previous.token != token { - previous.cancel() - } - s.orderRefreshCancels[jobID] = orderRefreshWorker{token: token, cancel: cancel} -} - -// unregisterOrderRefreshWorker 在 worker 退出时清理控制句柄。 -func (s *Server) unregisterOrderRefreshWorker(jobID, token string) { - s.orderRefreshMu.Lock() - defer s.orderRefreshMu.Unlock() - // current 保存当前任务登记的 worker 控制句柄。 - current := s.orderRefreshCancels[jobID] - if current.token == token { - delete(s.orderRefreshCancels, jobID) - } -} - -// cancelOrderRefreshWorker 取消内存中的订单刷新 worker,不改变数据库终态。 -func (s *Server) cancelOrderRefreshWorker(jobID string) bool { - s.orderRefreshMu.Lock() - // worker 保存当前任务的取消控制句柄。 - worker := s.orderRefreshCancels[jobID] - s.orderRefreshMu.Unlock() - if worker.cancel == nil { - return false - } - worker.cancel() - return true -} - -// runOrderRefreshJob 执行订单刷新并以租约令牌写入成功或失败终态。 -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 := refresh(ctx, job.UserID, job.CookieID, job.FilterStatus) - if err != nil { - // completeErr 保存失败终态写入错误。 - completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", err.Error()) - if completeErr != nil { - return errors.Join(err, completeErr) - } - return err - } - // resultJSON、marshalErr 保存具名刷新结果 JSON 及序列化错误。 - resultJSON, marshalErr := marshal(result) - if marshalErr != nil { - // completeErr 保存序列化失败终态写入错误。 - completeErr := completeOrderRefreshJob(ctx, complete, job.ID, token, "failed", "{}", marshalErr.Error()) - if completeErr != nil { - return errors.Join(marshalErr, completeErr) - } - return marshalErr - } - // 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 扫描并重新执行租约过期的订单刷新任务。 -func (s *Server) RunOrderRefreshRecovery(ctx context.Context) { - s.recoverOrderRefreshJobsOnce(ctx) - // ticker 保存恢复扫描间隔计时器。 - ticker := time.NewTicker(time.Minute) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - s.recoverOrderRefreshJobsOnce(ctx) - } - } -} - -// StartOrderRefreshRecovery 启动受 Server 生命周期管理的订单刷新恢复扫描器。 -func (s *Server) StartOrderRefreshRecovery(ctx context.Context) string { - return s.startBackgroundTaskContext("订单刷新恢复扫描器", ctx, func() { - s.RunOrderRefreshRecovery(ctx) - }) -} - -// recoverOrderRefreshJobsOnce 将过期任务重新入队并启动新的 worker。 -func (s *Server) recoverOrderRefreshJobsOnce(ctx context.Context) { - // jobs、err 保存可恢复任务及扫描错误。 - jobs, err := s.orders().services.RefreshJobs.Recoverable(ctx, time.Now().Unix(), 20) - if err != nil { - if s.Logger != nil { - s.Logger.Warn("扫描订单刷新恢复任务失败", "err", err) - } - return - } - // job 表示当前待恢复的订单刷新任务。 - for _, job := range jobs { - // requeued、requeueErr 保存重新入队结果及错误。 - requeued, requeueErr := s.orders().services.RefreshJobs.RequeueExpired(ctx, job.ID, time.Now().Unix()) - 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 { - 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) + return orderRefreshResponse{ + PartialFailure: result.PartialFailure, + Message: result.Message, + Summary: orderRefreshSummary{ + Discovered: result.Summary.Discovered, ListUpdated: result.Summary.ListUpdated, + SoftDeleted: result.Summary.SoftDeleted, DetailTotal: result.Summary.DetailTotal, + Total: result.Summary.Total, Updated: result.Summary.Updated, + NoChange: result.Summary.NoChange, Failed: result.Summary.Failed, + }, + Results: results, } } diff --git a/internal/server/order_refresh_job_lifecycle_compat_test.go b/internal/server/order_refresh_job_lifecycle_compat_test.go new file mode 100644 index 0000000..b2ad260 --- /dev/null +++ b/internal/server/order_refresh_job_lifecycle_compat_test.go @@ -0,0 +1,99 @@ +package server + +import ( + "context" + "errors" + + orderapp "xianyu-go/internal/application/orders" +) + +// orderRefreshJobRefresh 是历史生命周期测试使用的 HTTP 结果回调类型。 +type orderRefreshJobRefresh func(context.Context, int64, string, string) (orderRefreshResponse, error) + +// orderRefreshJobMarshal 是历史生命周期测试使用的结果序列化回调类型。 +type orderRefreshJobMarshal func(any) ([]byte, error) + +// orderRefreshJobComplete 是历史生命周期测试使用的任务终态写入回调类型。 +type orderRefreshJobComplete func(context.Context, string, string, string, string, string) (bool, error) + +// errOrderRefreshJobCompletionNotApplied 保留旧测试对应用层租约失配错误的引用。 +var errOrderRefreshJobCompletionNotApplied = orderapp.ErrRefreshJobCompletionNotApplied + +// orderRefreshLifecycleRefresher 将历史 HTTP 结果回调适配到订单应用刷新结果。 +type orderRefreshLifecycleRefresher struct { + // refresh 保存测试注入的刷新业务回调。 + refresh orderRefreshJobRefresh +} + +// Refresh 执行测试回调并把 HTTP 结果转换为应用层刷新结果。 +func (refresher orderRefreshLifecycleRefresher) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderapp.RefreshResult, error) { + // result、err 保存历史刷新回调的结果及错误。 + result, err := refresher.refresh(ctx, userID, cookieID, status) + if err != nil { + return orderapp.RefreshResult{}, err + } + return orderapp.RefreshResult{PartialFailure: result.PartialFailure, Message: result.Message, Summary: orderapp.RefreshSummary{ + Discovered: result.Summary.Discovered, ListUpdated: result.Summary.ListUpdated, + SoftDeleted: result.Summary.SoftDeleted, DetailTotal: result.Summary.DetailTotal, + Total: result.Summary.Total, Updated: result.Summary.Updated, + NoChange: result.Summary.NoChange, Failed: result.Summary.Failed, + }}, nil +} + +// orderRefreshLifecycleRepository 将测试终态回调适配到应用层任务仓储。 +type orderRefreshLifecycleRepository struct { + // complete 保存测试注入的终态写入回调。 + complete orderRefreshJobComplete +} + +// Create 满足订单刷新任务仓储接口;生命周期测试不验证创建流程。 +func (repository orderRefreshLifecycleRepository) Create(context.Context, *orderapp.RefreshJob) error { + return nil +} + +// Get 满足订单刷新任务仓储接口;生命周期测试不读取任务。 +func (repository orderRefreshLifecycleRepository) Get(context.Context, int64, string) (*orderapp.RefreshJob, error) { + return nil, orderapp.ErrRefreshJobNotFound +} + +// Claim 满足订单刷新任务仓储接口;生命周期测试直接执行已声明租约的任务。 +func (repository orderRefreshLifecycleRepository) Claim(context.Context, string, string, int64) (bool, error) { + return true, nil +} + +// Cancel 满足订单刷新任务仓储接口;生命周期测试不验证取消持久化。 +func (repository orderRefreshLifecycleRepository) Cancel(context.Context, int64, string) (bool, error) { + return false, nil +} + +// Complete 调用测试注入的终态写入回调。 +func (repository orderRefreshLifecycleRepository) Complete(ctx context.Context, jobID, token, status, resultJSON, errorMessage string) (bool, error) { + return repository.complete(ctx, jobID, token, status, resultJSON, errorMessage) +} + +// Recoverable 满足订单刷新任务仓储接口;生命周期测试不验证恢复扫描。 +func (repository orderRefreshLifecycleRepository) Recoverable(context.Context, int64, int) ([]orderapp.RefreshJob, error) { + return nil, nil +} + +// RequeueExpired 满足订单刷新任务仓储接口;生命周期测试不验证恢复扫描。 +func (repository orderRefreshLifecycleRepository) RequeueExpired(context.Context, string, int64) (bool, error) { + return false, nil +} + +// runOrderRefreshJobWith 通过应用层 runner 执行历史生命周期测试的可注入任务。 +func runOrderRefreshJobWith(ctx context.Context, job *orderapp.RefreshJob, token string, refresh orderRefreshJobRefresh, marshal orderRefreshJobMarshal, complete orderRefreshJobComplete) error { + if refresh == nil || marshal == nil || complete == nil { + return errors.New("订单刷新测试依赖未初始化") + } + // repository 保存测试终态回调的应用仓储适配器。 + repository := orderRefreshLifecycleRepository{complete: complete} + // runner、err 保存应用层订单刷新运行器及构造错误。 + runner, err := orderapp.NewRefreshJobRunner(repository, orderRefreshLifecycleRefresher{refresh: refresh}, orderapp.RefreshJobRunnerOptions{ + MarshalResult: func(result orderapp.RefreshJobResult) ([]byte, error) { return marshal(result) }, + }) + if err != nil { + return err + } + return runner.RunJob(ctx, job, token) +} diff --git a/internal/server/order_refresh_job_lifecycle_test.go b/internal/server/order_refresh_job_lifecycle_test.go index 16ec19f..e085283 100644 --- a/internal/server/order_refresh_job_lifecycle_test.go +++ b/internal/server/order_refresh_job_lifecycle_test.go @@ -203,12 +203,9 @@ func TestOrderRefreshWorkerUsesCanceledServerLifecycle(t *testing.T) { // srv、store、cleanup 保存测试服务、数据库和清理函数。 srv, store, cleanup := newTestServer(t) defer cleanup() - // lifecycleCtx、cancel 是已取消的 Server 生命周期上下文。 + // lifecycleCtx、cancel 是已取消的应用生命周期上下文。 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 { @@ -229,8 +226,19 @@ func TestOrderRefreshWorkerUsesCanceledServerLifecycle(t *testing.T) { } // job 是传给后台 worker 的应用层任务模型。 job := &orderapp.RefreshJob{ID: dbJob.ID, UserID: dbJob.UserID} - srv.startOrderRefreshWorker(job, token) - srv.WaitForBackground() + // runner、runnerErr 保存直接由应用层拥有的订单刷新 worker。 + runner, runnerErr := orderapp.NewRefreshJobRunner(srv.orders().services.RefreshJobs, srv.orders().services.Refresh, orderapp.RefreshJobRunnerOptions{}) + if runnerErr != nil { + t.Fatalf("构造订单刷新运行器: %v", runnerErr) + } + // startErr 保存应用层 worker 启动错误。 + if startErr := runner.StartJob(lifecycleCtx, job, token); startErr != nil { + t.Fatalf("启动订单刷新 worker: %v", startErr) + } + // closeErr 保存应用层 worker 关闭错误。 + if closeErr := runner.Close(context.Background()); closeErr != nil { + t.Fatalf("关闭订单刷新 worker: %v", closeErr) + } // persisted、err 保存 worker 结束后的任务状态及查询错误。 persisted, err := store.OrderRefreshJobs.Get(context.Background(), admin.ID, dbJob.ID) if err != nil { diff --git a/internal/server/order_service.go b/internal/server/order_service.go index c33142e..e479d60 100644 --- a/internal/server/order_service.go +++ b/internal/server/order_service.go @@ -18,31 +18,20 @@ type serverOrderRuntimeAdapter struct { // newServerOrderRuntime 创建订单运行时 Port 的 Server 适配器。 func newServerOrderRuntime(server *Server, reconciliation orderapp.ReconciliationRecorder) serverOrderRuntimeAdapter { - // hooks 保存 Server 运行时回调,避免适配器反向依赖 Server 包。 + // hooks 保存 adapter 内部构造的账号、自动化、通知和平台回调,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, + // automation、notifier 显式保持 nil 接口语义,避免把 nil 指针转换为非空接口后误报能力已装配。 + var automation adapter.OrderAutomation + if server.automation != nil { + automation = server.automation } + // notifier 只在真实通知器存在时转换为接口,避免 nil 指针伪装成已装配能力。 + var notifier adapter.OrderNotifier + if server.notifier != nil { + notifier = server.notifier + } + hooks = adapter.NewOrderRuntimeHooks(server.mtopClient, server.Manager, automation, notifier, server.updateRunningCookie, server.sessionRecoveryCallback()) } // logger 保存 Server 使用的日志器;适配器会在缺失时使用默认日志器。 var logger = (*slog.Logger)(nil) @@ -54,7 +43,7 @@ func newServerOrderRuntime(server *Server, reconciliation orderapp.Reconciliatio if server == nil { runtime = adapter.NewOrderRuntime(nil, hooks, reconciliation, logger) } else { - runtime = server.dependencies.NewOrderRuntime(hooks, reconciliation, logger) + runtime = server.orderDependencies.NewOrderRuntime(hooks, reconciliation, logger) } return serverOrderRuntimeAdapter{runtime: runtime} } @@ -191,8 +180,6 @@ func (a serverOrderRuntimeAdapter) IsSessionExpired(err error) bool { type orderHTTPAdapter struct { // services 保存应用层统一构造的订单业务服务集合。 services *orderapp.ServiceSet - // repository 保存 HTTP 适配器需要的账号归属查询 Port。 - repository orderapp.Repository } // RefreshSingle 刷新单个订单详情并转换为兼容 HTTP 响应模型。 @@ -232,34 +219,48 @@ func (a *orderHTTPAdapter) Refresh(ctx context.Context, userID int64, cookieID, return orderRefreshResponse{PartialFailure: result.PartialFailure, Message: result.Message, Summary: orderRefreshSummary{Discovered: result.Summary.Discovered, ListUpdated: result.Summary.ListUpdated, SoftDeleted: result.Summary.SoftDeleted, DetailTotal: result.Summary.DetailTotal, Total: result.Summary.Total, Updated: result.Summary.Updated, NoChange: result.Summary.NoChange, Failed: result.Summary.Failed}, Results: refreshResultsFromApplication(result.Results)}, nil } -// refreshResultsFromApplication 将应用层刷新结果转换为兼容动态结果行。 -func refreshResultsFromApplication(items []orderapp.RefreshOrderResult) []map[string]any { - // results 保存兼容客户端使用的结果行。 - results := make([]map[string]any, 0, len(items)) +// intPointer 为结果 DTO 创建整数指针,使零值也能按兼容契约显式返回。 +func intPointer(value int) *int { + return &value +} + +// boolPointer 为结果 DTO 创建布尔指针,使 false 也能按兼容契约显式返回。 +func boolPointer(value bool) *bool { + return &value +} + +// refreshResultsFromApplication 将应用层刷新结果转换为具名结果行。 +func refreshResultsFromApplication(items []orderapp.RefreshOrderResult) []orderRefreshResultDTO { + // results 保存兼容客户端使用的具名结果行,避免响应契约依赖动态 map。 + results := make([]orderRefreshResultDTO, 0, len(items)) // item 是当前应用层刷新结果。 for _, item := range items { // row 保存当前兼容响应行。 - row := map[string]any{"success": item.Success} + row := orderRefreshResultDTO{Success: item.Success} if item.CookieID != "" { - row["cookie_id"], row["discovered"], row["updated"] = item.CookieID, item.Discovered, item.Updated + row.CookieID = item.CookieID + row.Discovered = intPointer(item.Discovered) + row.Updated = intPointer(item.Updated) if item.Success { - row["soft_deleted"] = item.SoftDeleted + // softDeleted 表示本次账号刷新是否标记了失效订单。 + softDeleted := item.SoftDeleted != 0 + row.SoftDeleted = boolPointer(softDeleted) } } if item.OrderID != "" { - row["order_id"] = item.OrderID + row.OrderID = item.OrderID } if item.Stage != "" { - row["stage"] = item.Stage + row.Stage = item.Stage } if item.Message != "" { - row["message"] = item.Message + row.Message = item.Message } if item.Error != "" { - row["error"] = item.Error + row.Error = item.Error } if item.OldStatus != "" || item.NewStatus != "" { - row["old_status"], row["new_status"] = item.OldStatus, item.NewStatus + row.OldStatus, row.NewStatus = item.OldStatus, item.NewStatus } results = append(results, row) } @@ -314,13 +315,6 @@ func (s *Server) orders() *orderHTTPAdapter { return s.applicationServiceSet().orders } -// orderOwnedByUser 判断订单服务使用的账号是否归属于当前用户。 -func (a *orderHTTPAdapter) orderOwnedByUser(ctx context.Context, userID int64, cookieID string) bool { - // owned 和 err 保存账号归属检查结果。 - owned, err := a.repository.ExistsOwned(ctx, userID, cookieID) - return err == nil && owned -} - // orderListQuery 描述订单列表的业务查询条件。 type orderListQuery struct { // UserID 是当前登录用户标识。 @@ -533,8 +527,8 @@ type orderImportResult struct { SuccessCount int // FailedCount 是失败导入数。 FailedCount int - // Results 是逐单结果。 - Results []map[string]any + // Results 是逐单具名结果。 + Results []orderImportResultDTO } // Import 按当前用户账号所有权逐单导入订单,并为订单关联商品补全基础信息。 @@ -570,11 +564,11 @@ func importOrderFromRaw(raw map[string]any) orderapp.ImportOrder { // orderImportResultFromApplication 将应用层导入结果转换为旧 HTTP 响应兼容模型。 func orderImportResultFromApplication(result orderapp.ImportResult) orderImportResult { - // results 保存兼容客户端使用的逐条动态结果。 - results := make([]map[string]any, 0, len(result.Results)) + // results 保存兼容客户端使用的逐条具名结果。 + results := make([]orderImportResultDTO, 0, len(result.Results)) // item 保存当前应用层导入结果行。 for _, item := range result.Results { - results = append(results, map[string]any{"order_id": item.OrderID, "success": item.Success, "message": item.Message}) + results = append(results, orderImportResultDTO{OrderID: item.OrderID, Success: item.Success, Message: item.Message}) } return orderImportResult{Total: result.Total, SuccessCount: result.SuccessCount, FailedCount: result.FailedCount, Results: results} } @@ -595,8 +589,8 @@ type manualShipResult struct { SuccessCount int // FailedCount 是失败发货数。 FailedCount int - // Results 是逐单结果。 - Results []map[string]any + // Results 是逐单具名结果。 + Results []orderMutationResultDTO } // ManualShip 执行状态确认或完整自动化发货,并集中处理逐单失败而不中断批次的规则。 @@ -611,15 +605,15 @@ func (a *orderHTTPAdapter) ManualShip(ctx context.Context, request manualShipReq // manualShipResultFromApplication 将应用层手动发货结果转换为旧 HTTP 响应兼容模型。 func manualShipResultFromApplication(result orderapp.ManualShipResult) manualShipResult { - // results 保存兼容客户端使用的逐条动态结果。 - results := make([]map[string]any, 0, len(result.Results)) + // results 保存兼容客户端使用的逐条具名结果。 + results := make([]orderMutationResultDTO, 0, len(result.Results)) // item 保存当前应用层手动发货结果行。 for _, item := range result.Results { // row 保存兼容客户端使用的单条结果。 - row := map[string]any{"order_id": item.OrderID, "status": item.Status, "success": item.Success, "message": item.Message} + row := orderMutationResultDTO{OrderID: item.OrderID, Status: item.Status, Success: item.Success, Message: item.Message} if item.ReconciliationFieldsPresent { - row["reconciliation_id"] = item.ReconciliationID - row["reconciliation_warning"] = item.ReconciliationWarning + row.ReconciliationID = item.ReconciliationID + row.ReconciliationWarning = item.ReconciliationWarning } results = append(results, row) } diff --git a/internal/server/platform_dependencies_test.go b/internal/server/platform_dependencies_test.go new file mode 100644 index 0000000..cb980cc --- /dev/null +++ b/internal/server/platform_dependencies_test.go @@ -0,0 +1,78 @@ +package server + +import ( + "context" + "testing" + + "xianyu-go/internal/adapter" + "xianyu-go/internal/xianyu/renew" +) + +// serverPlatformQRFake 是 Server 平台访问器测试使用的二维码服务替身。 +type serverPlatformQRFake struct{} + +// GenerateQRCode 返回固定二维码数据,验证 Server 不参与平台协议编排。 +func (serverPlatformQRFake) GenerateQRCode(context.Context) (string, string, error) { + return "session", "https://example.test/qr", nil +} + +// GetSessionStatus 返回固定轮询状态,验证二维码能力可由显式依赖提供。 +func (serverPlatformQRFake) GetSessionStatus(string) map[string]any { + return map[string]any{"status": "waiting"} +} + +// CompleteVerification 返回脱敏验证结果,测试不输出真实凭证。 +func (serverPlatformQRFake) CompleteVerification(context.Context, string) (string, string, error) { + return "masked-cookie", "account", nil +} + +// TestServerPlatformAccessorsUseInjectedDependencies 验证生产访问器读取构造阶段的平台依赖。 +func TestServerPlatformAccessorsUseInjectedDependencies(t *testing.T) { + // mtopClient、longLoginClient 和 qrService 保存本测试注入的客户端能力。 + mtopClient := adapter.NewMTOPClient() + // longLoginClient 保存注入的长登录协议实现。 + longLoginClient := renew.Service{} + // qrService 保存注入的二维码协议实现。 + qrService := serverPlatformQRFake{} + // platformDependencies 保存通过 adapter 边界校验的平台能力集合。 + platformDependencies, err := adapter.NewPlatformDependencies(mtopClient, longLoginClient, qrService) + if err != nil { + t.Fatalf("NewPlatformDependencies: %v", err) + } + // server 保存仅含平台能力的最小 HTTP 服务测试对象。 + server := &Server{platformDependencies: platformDependencies} + if server.mtopClient() != mtopClient { + t.Fatalf("mtopClient 未返回显式注入客户端") + } + if server.longLoginClient() != longLoginClient { + t.Fatalf("longLoginClient 未返回显式注入客户端") + } + if server.qrLoginService() != qrService { + t.Fatalf("qrLoginService 未返回显式注入服务") + } +} + +// TestServerPlatformAccessorsKeepLegacyTestAliases 验证兼容字段仍能替换平台能力以支撑现有测试。 +func TestServerPlatformAccessorsKeepLegacyTestAliases(t *testing.T) { + // platformDependencies 保存生产默认平台能力,legacyMTop 和 legacyQR 保存旧测试替身。 + platformDependencies, err := adapter.NewDefaultPlatformDependencies(nil) + if err != nil { + t.Fatalf("NewDefaultPlatformDependencies: %v", err) + } + // legacyMTop 保存仅用于兼容测试注入的 MTOP 客户端。 + legacyMTop := adapter.NewMTOPClient() + // legacyQR 保存仅用于兼容测试注入的二维码服务。 + legacyQR := serverPlatformQRFake{} + // legacyLongLogin 保存仅用于兼容测试注入的长登录客户端。 + legacyLongLogin := renew.Service{} + // server 保存同时包含新边界和旧测试字段的过渡期对象。 + server := &Server{ + platformDependencies: platformDependencies, + MTop: legacyMTop, + CookieRenew: legacyLongLogin, + QRLogin: legacyQR, + } + if server.mtopClient() != legacyMTop || server.longLoginClient() != legacyLongLogin || server.qrLoginService() != legacyQR { + t.Fatalf("旧测试兼容字段未优先覆盖平台访问器") + } +} diff --git a/internal/server/platform_runtime.go b/internal/server/platform_runtime.go index 10b4275..e44dca2 100644 --- a/internal/server/platform_runtime.go +++ b/internal/server/platform_runtime.go @@ -12,13 +12,13 @@ func (s *Server) loadCookiePlatformDetail(ctx context.Context, cookieID string) if s == nil { return nil, errors.New("平台凭证读取服务未初始化") } - // repository 提供不读取登录密码的平台凭证窄视图;SQL 和解密逻辑由 adapter 负责。 - repository := s.accountLoginRepositoryForServer() - if repository == nil { - return nil, errors.New("平台凭证 repository 未初始化") + // service 提供消费者定义的平台凭证窄视图端口;SQL 和解密逻辑由 adapter 负责。 + service := s.platformCredentialApplication() + if service == nil { + return nil, errors.New("平台凭证读取服务未初始化") } // platformData 是应用 Port 返回的不含登录密码的平台运行视图。 - platformData, err := repository.LoadPlatformDetail(ctx, cookieID) + platformData, err := service.LoadPlatformDetail(ctx, cookieID) if err != nil { return nil, err } diff --git a/internal/server/platform_runtime_boundary_test.go b/internal/server/platform_runtime_boundary_test.go index 70e763d..8c7fbc1 100644 --- a/internal/server/platform_runtime_boundary_test.go +++ b/internal/server/platform_runtime_boundary_test.go @@ -8,6 +8,17 @@ import ( accountapp "xianyu-go/internal/application/account" ) +// serverPlatformCredentialPortFake 返回固定的窄平台凭证视图,验证 Server 不直连数据库仓储。 +type serverPlatformCredentialPortFake struct { + // detail 是当前测试端口返回的平台凭证视图。 + detail *accountapp.CredentialDetail +} + +// LoadPlatformDetail 返回测试平台凭证视图。 +func (f serverPlatformCredentialPortFake) LoadPlatformDetail(context.Context, string) (*accountapp.CredentialDetail, error) { + return f.detail, nil +} + // TestLoadCookiePlatformDetailRequiresCredentialPort 验证平台运行时读取不会在缺少应用 Port 时直接访问 Store。 func TestLoadCookiePlatformDetailRequiresCredentialPort(t *testing.T) { // srv 是仅装配空账号登录服务的测试 Server,模拟凭证适配器缺失场景。 @@ -19,6 +30,22 @@ func TestLoadCookiePlatformDetailRequiresCredentialPort(t *testing.T) { } } +// TestLoadCookiePlatformDetailUsesCredentialApplication 验证平台运行视图通过应用 Port 读取。 +func TestLoadCookiePlatformDetailUsesCredentialApplication(t *testing.T) { + // service 是绑定最小凭证读取端口的平台应用服务。 + service, serviceErr := accountapp.NewPlatformCredentialService(serverPlatformCredentialPortFake{detail: &accountapp.CredentialDetail{ID: "cid", UserID: 9, Value: "sid=masked"}}) + if serviceErr != nil { + t.Fatalf("构造凭证服务失败: %v", serviceErr) + } + // srv 是只装配平台凭证应用服务的测试 Server。 + srv := &Server{applications: &applicationServices{platformCredentials: service}} + // detail、loadErr 保存应用 Port 返回的平台视图及错误。 + detail, loadErr := srv.loadCookiePlatformDetail(context.Background(), "cid") + if loadErr != nil || detail == nil || detail.ID != "cid" || detail.Value == "" { + t.Fatalf("平台凭证视图读取异常: detail=%+v err=%v", detail, loadErr) + } +} + // TestPersistMTopCookieSessionRequiresCredentialPort 验证 MTOP Cookie 会话写回通过凭证 Port 而非直接访问 Store。 func TestPersistMTopCookieSessionRequiresCredentialPort(t *testing.T) { // srv 是仅装配空账号登录服务的测试 Server,模拟写回适配器缺失场景。 @@ -34,3 +61,15 @@ func TestPersistMTopCookieSessionRequiresCredentialPort(t *testing.T) { t.Fatalf("缺少凭证 Port 时应报告写回错误: changed=%v handled=%v err=%v", changed, handled, persistErr) } } + +// TestPlatformCredentialSessionPortIsAvailable 验证平台会话写回通过专用最小端口暴露。 +func TestPlatformCredentialSessionPortIsAvailable(t *testing.T) { + // srv、cleanup 保存完整应用装配的测试 Server 及资源清理函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // sessionPort 保存仅包含 Cookie 写回能力的平台会话端口。 + sessionPort := srv.platformCredentialSessionPort() + if sessionPort == nil { + t.Fatal("完整应用装配应提供平台会话写回端口") + } +} diff --git a/internal/server/publish_batch_run_test.go b/internal/server/publish_batch_run_test.go index 04ee63e..5810867 100644 --- a/internal/server/publish_batch_run_test.go +++ b/internal/server/publish_batch_run_test.go @@ -62,35 +62,6 @@ func TestPublishBatchFailurePreservesUncertainRemoteWarningWhenCanceled(t *testi } } -// TestCancelPublishBatchRequiresMatchingWorkerToken 负责Test取消发布批次RequiresMatching工作器令牌相关处理。 -func TestCancelPublishBatchRequiresMatchingWorkerToken(t *testing.T) { - // srv 保存srv,供当前处理流程使用 - srv := &Server{publishCancels: make(map[string]publishBatchWorker)} - // ctx、cancel 保存ctx、cancel,供当前处理流程使用 - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - srv.registerPublishBatchCancel("batch", "current", cancel) - - if // canceled 保存canceled,供当前处理流程使用 - canceled := srv.cancelPublishBatch("batch", "stale"); canceled { - t.Fatal("stale worker token must not cancel current worker") - } - select { - case <-ctx.Done(): - t.Fatal("current worker was canceled by stale token") - default: - } - if // canceled 保存canceled,供当前处理流程使用 - canceled := srv.cancelPublishBatch("batch", "current"); !canceled { - t.Fatal("matching token should cancel current worker") - } - select { - case <-ctx.Done(): - default: - t.Fatal("matching token did not invoke cancel") - } -} - // buildImageZip 构造含一张图片的 zip 字节流。 func buildImageZip(t *testing.T) []byte { t.Helper() @@ -560,7 +531,7 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test // 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") + err = (serverBatchPublisher{remotePort: port, localService: localService}).PublishRow(ctx, admin.ID, applicationRow, "worker-2") if err != nil { t.Fatalf("resume local persistence: %v", err) } @@ -594,7 +565,10 @@ func TestPublishBatchRecoveryAutomaticallyResumesInterruptedRow(t *testing.T) { }}); err != nil { t.Fatal(err) } - srv.recoverPublishBatchesOnce(ctx) + // err 保存应用层批量恢复扫描的错误。 + if err := srv.applications.itemBatchCoordinator.RunRecovery(ctx); err != nil { + t.Fatalf("批量恢复扫描: %v", err) + } // deadline 保存deadline,供当前处理流程使用 deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { diff --git a/internal/server/qrlogin_handlers.go b/internal/server/qrlogin_handlers.go index 0896fdd..4724c09 100644 --- a/internal/server/qrlogin_handlers.go +++ b/internal/server/qrlogin_handlers.go @@ -9,6 +9,7 @@ import ( "github.com/go-chi/chi/v5" + accountapp "xianyu-go/internal/application/account" "xianyu-go/internal/auth" ) @@ -37,8 +38,14 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) { // generateCtx、cancel 保存generateCtx、cancel,供当前处理流程使用 generateCtx, cancel := context.WithTimeout(r.Context(), qrLoginGenerateTimeout) defer cancel() + // qrService 是通过显式平台依赖边界取得的二维码服务;为空时拒绝执行平台调用。 + qrService := s.qrLoginService() + if qrService == nil { + writeErr(w, http.StatusInternalServerError, "二维码服务未初始化") + return + } // sessionID、qrCodeURL、err 保存会话ID、qrCodeURL、err,供当前处理流程使用 - sessionID, qrCodeURL, err := s.QRLogin.GenerateQRCode(generateCtx) + sessionID, qrCodeURL, err := qrService.GenerateQRCode(generateCtx) if err != nil { // message 保存消息,供当前处理流程使用 message := "生成二维码失败: " + err.Error() @@ -58,9 +65,13 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) { message, "") return } - s.qrMu.Lock() - s.qrOwners[sessionID] = qrLoginOwner{UserID: sess.UserID, CreatedAt: time.Now().UTC()} - s.qrMu.Unlock() + // qrSessions 保存扫码会话所有权;平台二维码服务只负责平台会话本身。 + qrSessions := s.accountLoginApplication().qrSessions + if qrSessions == nil { + writeErr(w, http.StatusInternalServerError, "扫码会话服务未初始化") + return + } + qrSessions.Register(sessionID, sess.UserID, time.Now().UTC()) writeJSON(w, http.StatusOK, qrLoginGenerateResponse{ Success: true, SessionID: sessionID, QRCodeURL: qrCodeURL, // 生成成功响应只暴露会话标识和二维码地址。 @@ -79,8 +90,14 @@ func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) { if !s.requireQRSessionOwner(w, r, sessionID) { return } + // qrService 是已完成平台依赖校验的二维码服务。 + qrService := s.qrLoginService() + if qrService == nil { + writeErr(w, http.StatusInternalServerError, "二维码服务未初始化") + return + } // result 保存结果,供当前处理流程使用 - result := publicQRStatus(s.QRLogin.GetSessionStatus(sessionID)) + result := publicQRStatus(qrService.GetSessionStatus(sessionID)) writeJSON(w, http.StatusOK, result) } @@ -95,8 +112,14 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req if !s.requireQRSessionOwner(w, r, sessionID) { return } + // qrService 是已完成平台依赖校验的二维码服务。 + qrService := s.qrLoginService() + if qrService == nil { + writeErr(w, http.StatusInternalServerError, "二维码服务未初始化") + return + } // result 保存结果,供当前处理流程使用 - result := cloneQRStatus(s.QRLogin.GetSessionStatus(sessionID)) + result := cloneQRStatus(qrService.GetSessionStatus(sessionID)) if qrStatus(result) != "success" { writeJSON(w, http.StatusOK, publicQRStatus(result)) return @@ -136,8 +159,14 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) if !s.requireQRSessionOwner(w, r, sessionID) { return } + // qrService 是已完成平台依赖校验的二维码服务。 + qrService := s.qrLoginService() + if qrService == nil { + writeErr(w, http.StatusInternalServerError, "二维码服务未初始化") + return + } // cookies、unb、err 保存cookies、unb、err,供当前处理流程使用 - cookies, unb, err := s.QRLogin.CompleteVerification(r.Context(), sessionID) + cookies, unb, err := qrService.CompleteVerification(r.Context(), sessionID) if err != nil { s.Logger.Error("验证完成处理失败", "err", err) writeErrCode( @@ -146,10 +175,8 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) err.Error(), "") return } - // req 保存req,供当前处理流程使用 - var req struct { - TargetAccountID string `json:"target_account_id"` - } + // req 保存具名扫码验证完成请求。 + var req qrVerificationRequestDTO if r.Body != nil && r.ContentLength != 0 { if // err 保存err,供当前处理流程使用 err := decodeJSON(r, &req); err != nil { @@ -181,7 +208,7 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) "unb": unb, } if // current 保存current,供当前处理流程使用 - current := s.QRLogin.GetSessionStatus(sessionID); current != nil { + current := qrService.GetSessionStatus(sessionID); current != nil { if // snapshot、ok 保存snapshot、ok,供当前处理流程使用 snapshot, ok := current["cookie_snapshot"]; ok { result["cookie_snapshot"] = snapshot @@ -212,24 +239,20 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s writeErr(w, http.StatusUnauthorized, "未授权访问") return false } - s.qrMu.Lock() - // owner、ok 保存owner、ok,供当前处理流程使用 - owner, ok := s.qrOwners[sessionID] - // expired 保存expired,供当前处理流程使用 - expired := ok && owner.CreatedAt.Before(time.Now().UTC().Add(-30*time.Minute)) - if expired { - delete(s.qrOwners, sessionID) - delete(s.qrPersisted, sessionID) - s.qrPersistLocks.Delete(sessionID) + // qrSessions 负责所有权、过期判断和幂等状态清理,HTTP 层不再持有可变会话表。 + qrSessions := s.accountLoginApplication().qrSessions + if qrSessions == nil { + writeErr(w, http.StatusInternalServerError, "扫码会话服务未初始化") + return false } - s.qrMu.Unlock() - if expired { - if // cleaner、cleanable 保存cleaner、cleanable,供当前处理流程使用 - cleaner, cleanable := s.QRLogin.(interface{ DeleteSession(string) }); cleanable { - cleaner.DeleteSession(sessionID) + // err 保存扫码会话所有权校验结果。 + if err := qrSessions.Authorize(sessionID, sess.UserID); err != nil { + if errors.Is(err, accountapp.ErrQRLoginSessionNotFound) { + // cleaner、cleanable 分别表示平台会话清理器及其接口是否可用。 + if cleaner, cleanable := s.qrLoginService().(interface{ DeleteSession(string) }); cleanable { + cleaner.DeleteSession(sessionID) + } } - } - if !ok || expired || owner.UserID != sess.UserID { writeErr(w, http.StatusNotFound, "扫码会话不存在或已过期") return false } @@ -238,23 +261,15 @@ func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, s // cleanupQRLoginSessions 负责cleanupQR登录Sessions相关处理。 func (s *Server) cleanupQRLoginSessions() { - // cutoff 保存cutoff,供当前处理流程使用 - cutoff := time.Now().UTC().Add(-30 * time.Minute) - // expired 保存expired,供当前处理流程使用 - expired := make([]string, 0) - s.qrMu.Lock() - // id、owner 表示当前遍历过程中的id、owner - for id, owner := range s.qrOwners { - if owner.CreatedAt.Before(cutoff) { - delete(s.qrOwners, id) - delete(s.qrPersisted, id) - s.qrPersistLocks.Delete(id) - expired = append(expired, id) - } + // qrSessions 提供应用层扫码会话过期清理能力。 + qrSessions := s.accountLoginApplication().qrSessions + if qrSessions == nil { + return } - s.qrMu.Unlock() + // expired 保存应用层报告的过期扫码会话标识。 + expired := qrSessions.Cleanup(time.Now().UTC()) if // cleaner、ok 保存cleaner、ok,供当前处理流程使用 - cleaner, ok := s.QRLogin.(interface{ DeleteSession(string) }); ok { + cleaner, ok := s.qrLoginService().(interface{ DeleteSession(string) }); ok { // id 表示当前遍历过程中的标识 for _, id := range expired { cleaner.DeleteSession(id) @@ -277,11 +292,29 @@ func cloneQRStatus(src map[string]any) map[string]any { // 永远不进入前端、浏览器日志或代理响应。 // publicQRStatus 负责publicQR状态相关处理。 func publicQRStatus(src map[string]any) qrLoginStatusResponse { - // dst 保存dst,供当前处理流程使用 - dst := qrLoginStatusResponse(cloneQRStatus(src)) - delete(dst, "cookies") - delete(dst, "cookie_snapshot") - return dst + // status 保存允许传输到浏览器的扫码状态;Cookie 和快照字段刻意不映射。 + status := qrLoginStatusResponse{Status: qrStatus(src)} + // success 表示上游是否报告扫码流程成功;ok 表示字段类型确实为布尔值。 + if success, ok := src["success"].(bool); ok { + status.Success = success + } + // message 保存上游返回的用户提示文本;ok 表示字段类型确实为字符串。 + if message, ok := src["message"].(string); ok { + status.Message = message + } + // sessionID 保存扫码会话标识;ok 表示字段类型确实为字符串。 + if sessionID, ok := src["session_id"].(string); ok { + status.SessionID = sessionID + } + // accountID 保存扫码成功后关联的本地账号标识;ok 表示字段类型确实为字符串。 + if accountID, ok := src["account_id"].(string); ok { + status.AccountID = accountID + } + // isNew 表示是否新建本地账号;ok 表示字段类型确实为布尔值。 + if isNew, ok := src["is_new_account"].(bool); ok { + status.IsNewAccount = isNew + } + return status } // qrStatus 负责qr状态相关处理。 diff --git a/internal/server/qrlogin_keyword_test.go b/internal/server/qrlogin_keyword_test.go index e453d96..a56d466 100644 --- a/internal/server/qrlogin_keyword_test.go +++ b/internal/server/qrlogin_keyword_test.go @@ -195,7 +195,7 @@ func TestQRLoginSessionExpiresWithoutAnotherGenerateRequest(t *testing.T) { srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "waiting"}} // admin 保存admin,供当前处理流程使用 admin, _ := store.Users.GetByUsername(context.Background(), "admin") - srv.qrOwners["expired-session"] = qrLoginOwner{UserID: admin.ID, CreatedAt: time.Now().UTC().Add(-31 * time.Minute)} + srv.accountLoginApplication().qrSessions.Register("expired-session", admin.ID, time.Now().UTC().Add(-31*time.Minute)) // h 保存h,供当前处理流程使用 h := srv.Router() // cookie 保存登录凭证,供当前处理流程使用 @@ -265,9 +265,7 @@ func ownQRSession(t *testing.T, srv *Server, store *db.Store, sessionID string) if err != nil { t.Fatalf("GetByUsername admin: %v", err) } - srv.qrMu.Lock() - srv.qrOwners[sessionID] = qrLoginOwner{UserID: admin.ID, CreatedAt: time.Now().UTC()} - srv.qrMu.Unlock() + srv.accountLoginApplication().qrSessions.Register(sessionID, admin.ID, time.Now().UTC()) } // TestQRLoginStatusPersistsSuccessIdempotently 负责TestQR登录状态PersistsSuccessIdempotently相关处理。 diff --git a/internal/server/run_test.go b/internal/server/run_test.go index dc52565..c2b1640 100644 --- a/internal/server/run_test.go +++ b/internal/server/run_test.go @@ -75,32 +75,6 @@ func TestRun_ServesHealthAndShutdowns(t *testing.T) { } } -// TestPublishWorkerTrackingWaitsForCompletion 负责Test发布工作器TrackingWaitsForCompletion相关处理。 -func TestPublishWorkerTrackingWaitsForCompletion(t *testing.T) { - // srv、cleanup 保存srv、cleanup,供当前处理流程使用 - srv, _, cleanup := newTestServer(t) - defer cleanup() - // doneWorker 保存done工作器,供当前处理流程使用 - doneWorker := srv.beginWorker() - // waited 保存waited,供当前处理流程使用 - waited := make(chan struct{}) - go func() { - srv.waitForWorkers(time.Second) - close(waited) - }() - select { - case <-waited: - t.Fatal("wait returned while worker was still active") - case <-time.After(20 * time.Millisecond): - } - doneWorker() - select { - case <-waited: - case <-time.After(time.Second): - t.Fatal("wait did not return after worker completed") - } -} - // TestPublishRecoveryLifecycleStopsBeforeWorkerWait 负责Test发布RecoveryLifecycleStopsBefore工作器Wait相关处理。 func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) { // srv、cleanup 保存srv、cleanup,供当前处理流程使用 @@ -108,12 +82,15 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) { defer cleanup() // ctx、cancel 保存ctx、cancel,供当前处理流程使用 ctx, cancel := context.WithCancel(context.Background()) - srv.StartPublishBatchRecovery(ctx) + // err 表示测试批量恢复组件启动失败的原因。 + if err := srv.applications.itemBatchCoordinator.StartRecovery(ctx); err != nil { + t.Fatalf("启动批量发布恢复扫描器: %v", err) + } cancel() // done 保存done,供当前处理流程使用 done := make(chan struct{}) go func() { - srv.WaitForBackground() + srv.applications.itemBatchCoordinator.Wait() close(done) }() select { @@ -126,7 +103,7 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) { // TestNewRejectsMissingRequiredDependencies 确保 HTTP 服务构造阶段拒绝缺失核心依赖。 func TestNewRejectsMissingRequiredDependencies(t *testing.T) { // err 是缺少基础设施容器时的构造校验错误。 - if _, err := New(nil, nil, nil, "", ":0", nil, nil, nil); err == nil { + if _, err := New(nil, nil, "", ":0", nil, nil, nil); err == nil { t.Fatal("缺少基础设施容器时应返回构造错误") } // srv 是用于提供合法 Store 的测试服务;cleanup 负责释放测试数据库。 @@ -135,17 +112,83 @@ func TestNewRejectsMissingRequiredDependencies(t *testing.T) { 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(dependencies, authentication, nil, "", ":0", nil, nil, nil); err == nil { + if _, err := New(authentication, nil, "", ":0", nil, nil, nil); err == nil { t.Fatal("缺少 account.Manager 时应返回构造错误") } + // err 是缺少订单专用装配能力时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil); err == nil { + t.Fatal("缺少订单专用依赖时应返回构造错误") + } + // orderDependencies 保存账号依赖缺失测试所需的合法订单装配能力。 + orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store) + if orderDependencyErr != nil { + t.Fatalf("NewOrderDependencies: %v", orderDependencyErr) + } + // err 是缺少账号专用装配能力时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies)); err == nil { + t.Fatal("缺少账号专用依赖时应返回构造错误") + } + // accountDependencies 保存账号与订单依赖均合法时的商品依赖缺失测试输入。 + accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store) + if accountDependencyErr != nil { + t.Fatalf("NewAccountDependencies: %v", accountDependencyErr) + } + // err 是缺少商品专用装配能力时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies)); err == nil { + t.Fatal("缺少商品专用依赖时应返回构造错误") + } + // err 是订单、账号和商品依赖齐全但平台客户端缺失时的构造校验错误。 + itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store) + if itemDependencyErr != nil { + t.Fatalf("NewItemDependencies: %v", itemDependencyErr) + } + // platformDependencies 保存依赖缺失分支测试使用的显式平台能力。 + platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil) + if platformDependencyErr != nil { + t.Fatalf("NewPlatformDependencies: %v", platformDependencyErr) + } + // chatDependencies 保存平台缺失校验所需的聊天专用依赖。 + chatDependencies := adapter.NewChatDependencies(store) + // systemDependencies 保存平台缺失校验所需的系统专用依赖。 + systemDependencies := adapter.NewSystemDependencies(store) + // automationDependencies 保存平台缺失校验所需的自动化专用依赖及构造错误。 + automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store) + if automationDependencyErr != nil { + t.Fatalf("NewAutomationDependencies: %v", automationDependencyErr) + } + // miscDependencies 保存平台缺失校验所需的杂项专用依赖及构造错误。 + miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store) + if miscDependencyErr != nil { + t.Fatalf("NewMiscDependencies: %v", miscDependencyErr) + } + // adminSettingsDependencies 保存平台缺失校验所需的管理员设置依赖。 + adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store) + if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil { + t.Fatal("显式 Server 依赖构造失败") + } + // err 是聊天或系统等显式依赖缺失时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies)); err == nil { + t.Fatal("缺少聊天或系统专用依赖时应返回构造错误") + } + // err 是缺少平台依赖注入时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies)); err == nil { + t.Fatal("缺少平台依赖时应返回构造错误") + } + // err 是缺少自动化专用依赖时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)); err == nil { + t.Fatal("缺少自动化专用依赖时应返回构造错误") + } + // err 是缺少杂项专用依赖时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)); err == nil { + t.Fatal("缺少杂项专用依赖时应返回构造错误") + } + // err 是缺少管理员设置专用依赖时的构造校验错误。 + if _, err := New(authentication, srv.Manager, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithPlatformDependencies(platformDependencies)); err == nil { + t.Fatal("缺少管理员设置专用依赖时应返回构造错误") + } } // TestServerStartStopIsIdempotentAndWaitsForWorkers 验证 Start/Stop 可重复调用且 Stop 等待 worker。 diff --git a/internal/server/server.go b/internal/server/server.go index 1e84023..3a6ac31 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -21,12 +21,14 @@ import ( "xianyu-go/internal/account" "xianyu-go/internal/adapter" + accountapp "xianyu-go/internal/application/account" + lifecycleapp "xianyu-go/internal/application/lifecycle" + orderapp "xianyu-go/internal/application/orders" "xianyu-go/internal/auth" "xianyu-go/internal/automation" "xianyu-go/internal/chat" "xianyu-go/internal/logging" "xianyu-go/internal/notify" - "xianyu-go/internal/reconciliation" appversion "xianyu-go/internal/version" "xianyu-go/internal/webui" ) @@ -42,21 +44,55 @@ type qrLoginPersistence struct { CreatedAt time.Time } -// qrLoginOwner 保存qr登录所有者,供当前处理流程使用 -type qrLoginOwner struct { - UserID int64 - CreatedAt time.Time -} - -// publishBatchWorker 保存发布批次工作器,供当前处理流程使用 -type publishBatchWorker struct { - token string - cancel context.CancelFunc -} - // ServerOption 是 Server 构造阶段应用可选依赖的配置函数。 type ServerOption func(*Server) +// orderDependencyFactory 是订单装配所需的最小能力集合;Server 不持有通用 Store 工厂。 +type orderDependencyFactory interface { + // NewOrderRepository 创建订单读写仓储。 + NewOrderRepository() *adapter.OrderRepository + // NewOrderReconciliationRepository 创建订单补偿记录仓储。 + NewOrderReconciliationRepository() *adapter.OrderReconciliationRepository + // NewOrderRuntime 创建订单平台运行时适配器。 + NewOrderRuntime(adapter.OrderRuntimeHooks, orderapp.ReconciliationRecorder, *slog.Logger) *adapter.OrderRuntime + // NewOrderRefreshJobRepository 创建订单刷新任务仓储。 + NewOrderRefreshJobRepository() orderapp.RefreshJobRepository +} + +// accountDependencyFactory 是账号应用装配所需的最小能力集合;Server 不持有通用 Store 工厂。 +type accountDependencyFactory interface { + // NewAccountLoginRepository 创建账号凭证与资料仓储。 + NewAccountLoginRepository() *adapter.AccountLoginRepository + // NewAccountSettingsRepository 创建账号设置仓储。 + NewAccountSettingsRepository() *adapter.AccountSettingsRepository + // NewAccountSummaryRepository 创建账号摘要仓储。 + NewAccountSummaryRepository() *adapter.AccountSummaryRepository + // NewQRLoginRepository 创建扫码登录凭证端口。 + NewQRLoginRepository() accountapp.QRLoginRepository + // NewAuthenticationRepository 创建用户认证仓储。 + NewAuthenticationRepository() *adapter.AuthenticationRepository + // NewAccountLoginAuditRepository 创建账号登录审计仓储。 + NewAccountLoginAuditRepository() *adapter.AccountLoginAuditRepository +} + +// itemDependencyFactory 是商品应用装配所需的最小能力集合;Server 不持有通用 Store 工厂。 +type itemDependencyFactory interface { + // NewItemBatchRepository 创建批量发布状态仓储。 + NewItemBatchRepository() *adapter.ItemBatchRepository + // NewItemBatchPreviewPort 创建批量预检端口。 + NewItemBatchPreviewPort() *adapter.ItemBatchPreviewPort + // NewItemBatchPublishPort 创建批量远端发布端口。 + NewItemBatchPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error), adapter.ReadPublishImageFile, adapter.DownloadPublishImageURL) *adapter.ItemBatchPublishPort + // NewItemPublishPort 创建单商品发布端口。 + NewItemPublishPort(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemPublishPort + // NewItemPublishRepository 创建单商品发布结果仓储。 + NewItemPublishRepository() *adapter.ItemPublishRepository + // NewItemCatalogRepository 创建商品目录仓储。 + NewItemCatalogRepository() *adapter.ItemCatalogRepository + // NewItemSyncRepository 创建商品同步端口。 + NewItemSyncRepository(func() adapter.MTOPClient, *slog.Logger, func(context.Context, string, string), func(context.Context, string, error)) *adapter.ItemSyncRepository +} + // databaseHealth 定义健康检查需要的最小数据库连通性能力。 type databaseHealth interface { // Ping 在调用方 Context 内探测数据库连接是否可用。 @@ -67,34 +103,44 @@ type databaseHealth interface { // 不再允许外部直接改字段,避免运行时被替换成 nil。 // Server 保存Server,供当前处理流程使用 type Server struct { - // 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 + // orderDependencies 保存订单应用服务专用的显式装配能力,不允许从通用设施容器回退获取。 + orderDependencies orderDependencyFactory + // accountDependencies 保存账号应用服务专用的显式装配能力,不允许从通用设施容器回退获取。 + accountDependencies accountDependencyFactory + // itemDependencies 保存商品应用服务专用的显式装配能力,不允许从通用设施容器回退获取。 + itemDependencies itemDependencyFactory + // chatDependencies 保存聊天应用服务专用的显式装配能力,不允许从通用设施容器回退获取。 + chatDependencies *adapter.ChatDependencies + // systemDependencies 保存健康检查与补偿扫描的显式装配能力。 + systemDependencies *adapter.SystemDependencies + // automationDependencies 保存自动化、默认回复和关键词的显式装配能力。 + automationDependencies *adapter.AutomationDependencies + // miscDependencies 保存通知、分析和卡券的显式装配能力。 + miscDependencies *adapter.MiscDependencies + // adminSettingsDependencies 保存管理员与系统设置的显式装配能力。 + adminSettingsDependencies *adapter.AdminSettingsDependencies + Auth *auth.Service + Manager *account.Manager + automation *automation.Center + notifier *notify.Notifier + chat *chat.Service + // platformDependencies 保存构造阶段校验通过的平台能力;生产调用必须通过下方访问器读取。 + platformDependencies *adapter.PlatformDependencies + // MTop 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。 + MTop adapter.MTOPClient + // CookieRenew 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。 + CookieRenew adapter.LongLoginClient + // QRLogin 是阶段性测试兼容别名;所有生产调用迁移完成后删除,删除前须清点字段写入测试并改用 WithPlatformDependencies。 + QRLogin qrLoginService + Logger *slog.Logger + WebDir string // 前端静态资源目录(含 index.html) + Addr string // applications 保存统一装配的应用服务实例。 applications *applicationServices - // reconciliation 负责恢复外部发货成功但本地订单状态未完成的记录。 - reconciliation *reconciliation.Service - // transactionRepository 提供统一事务执行所需的最小持久化能力。 - transactionRepository *adapter.TransactionRepository + // applicationLifecycle 保存由 cmd 拥有的应用生命周期协调器;Server 只读取其共享 Context。 + applicationLifecycle *lifecycleapp.Coordinator // databaseHealth 提供健康检查所需的数据库探测能力,避免 handler 直接触碰 SQL 连接。 - databaseHealth databaseHealth - publishMu sync.Mutex - publishCancels map[string]publishBatchWorker - orderRefreshMu sync.Mutex - orderRefreshCancels map[string]orderRefreshWorker - workerMu sync.Mutex - workerCount int - workersDone chan struct{} + databaseHealth databaseHealth // backgroundMu 保护 Server 后台任务计数与完成信号,避免关闭等待创建不可取消的等待 goroutine。 backgroundMu sync.Mutex backgroundCount int @@ -102,22 +148,14 @@ type Server struct { // taskRegistryMu 保护后台任务注册表的惰性初始化,避免测试构造的零值 Server 产生数据竞争。 taskRegistryMu sync.Mutex // taskRegistry 保存 Server 自有后台任务的生命周期状态,不持久化业务数据或敏感凭证。 - taskRegistry *taskRegistry - lifecycleMu sync.RWMutex - lifecycleCtx context.Context - lifecycleCancel context.CancelFunc - httpServer *http.Server - httpDone chan struct{} - httpErr error - started bool - stopped bool + taskRegistry *taskRegistry + lifecycleMu sync.RWMutex + httpServer *http.Server + httpDone chan struct{} + httpErr error + started bool + stopped bool - qrMu sync.Mutex - qrPersisted map[string]qrLoginPersistence - qrOwners map[string]qrLoginOwner - // qrPersistLocks 按扫码会话串行化持久化,避免持有全局 qrMu 执行数据库、 - // 资料刷新和账号重启等慢操作。 - qrPersistLocks sync.Map loginLimiter *loginFailureLimiter initializationMu sync.Mutex } @@ -130,13 +168,101 @@ func WithChatService(service *chat.Service) ServerOption { } } -// New 构造并校验 HTTP 服务所需依赖。autoCenter/notifier 由调用方完成创建后注入 -// (创建顺序:adapter → manager → automation → notifier → server)。 -// New 负责New相关处理。 -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 依赖基础设施容器不能为空") +// WithOrderDependencies 注入订单应用服务所需的专用适配器工厂。 +func WithOrderDependencies(dependencies *adapter.OrderDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入订单专用依赖的 HTTP 服务实例。 + if dependencies == nil { + server.orderDependencies = nil + return + } + server.orderDependencies = dependencies } +} + +// WithAccountDependencies 注入账号应用服务所需的专用适配器工厂。 +func WithAccountDependencies(dependencies *adapter.AccountDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入账号专用依赖的 HTTP 服务实例。 + if dependencies == nil { + server.accountDependencies = nil + return + } + server.accountDependencies = dependencies + } +} + +// WithItemDependencies 注入商品应用服务所需的专用适配器工厂。 +func WithItemDependencies(dependencies *adapter.ItemDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入商品专用依赖的 HTTP 服务实例。 + if dependencies == nil { + server.itemDependencies = nil + return + } + server.itemDependencies = dependencies + } +} + +// WithChatDependencies 注入聊天应用服务所需的专用适配器工厂。 +func WithChatDependencies(dependencies *adapter.ChatDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入聊天专用依赖的 HTTP 服务实例。 + server.chatDependencies = dependencies + } +} + +// WithSystemDependencies 注入健康检查与订单补偿扫描所需的专用适配器工厂。 +func WithSystemDependencies(dependencies *adapter.SystemDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入系统专用依赖的 HTTP 服务实例。 + server.systemDependencies = dependencies + } +} + +// WithAutomationDependencies 注入自动化领域所需的专用适配器工厂。 +func WithAutomationDependencies(dependencies *adapter.AutomationDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入自动化专用依赖的 HTTP 服务实例。 + server.automationDependencies = dependencies + } +} + +// WithMiscDependencies 注入通知、分析和卡券领域所需的专用适配器工厂。 +func WithMiscDependencies(dependencies *adapter.MiscDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入杂项领域依赖的 HTTP 服务实例。 + server.miscDependencies = dependencies + } +} + +// WithAdminSettingsDependencies 注入管理员与系统设置所需的专用适配器工厂。 +func WithAdminSettingsDependencies(dependencies *adapter.AdminSettingsDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入管理员设置依赖的 HTTP 服务实例。 + server.adminSettingsDependencies = dependencies + } +} + +// WithPlatformDependencies 注入 MTOP、长登录和二维码服务组成的平台能力边界。 +func WithPlatformDependencies(dependencies *adapter.PlatformDependencies) ServerOption { + return func(server *Server) { + // server 是当前构造流程中待注入平台依赖的 HTTP 服务实例。 + server.platformDependencies = dependencies + } +} + +// WithApplicationLifecycle 注入由进程装配层拥有的应用生命周期协调器。 +func WithApplicationLifecycle(coordinator *lifecycleapp.Coordinator) ServerOption { + return func(server *Server) { + // server 是当前构造流程中需要读取应用生命周期 Context 的 HTTP 服务实例。 + server.applicationLifecycle = coordinator + } +} + +// New 构造并校验 HTTP 服务所需依赖;订单、账号、商品、系统和平台能力必须由显式依赖边界注入。 +// autoCenter/notifier 由调用方完成创建后注入,构造顺序为 adapter → manager → automation → notifier → server。 +func New(authentication *auth.Service, manager *account.Manager, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) { if authentication == nil { return nil, fmt.Errorf("server 依赖认证服务不能为空") } @@ -148,27 +274,16 @@ func New(dependencies *adapter.Dependencies, authentication *auth.Service, manag } // server 是完成依赖装配、等待应用服务初始化后的 HTTP 服务实例。 server := &Server{ - 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), - workersDone: closedSignal(), - lifecycleCtx: context.Background(), - qrPersisted: make(map[string]qrLoginPersistence), - qrOwners: make(map[string]qrLoginOwner), - loginLimiter: newLoginFailureLimiter(), - taskRegistry: newTaskRegistry(), - backgroundDone: closedSignal(), + Auth: authentication, + Manager: manager, + automation: autoCenter, + notifier: notifier, + Logger: logger, + WebDir: webDir, + Addr: addr, + loginLimiter: newLoginFailureLimiter(), + taskRegistry: newTaskRegistry(), + backgroundDone: closedSignal(), } // option 表示当前遍历过程中的option for _, option := range options { @@ -177,35 +292,98 @@ func New(dependencies *adapter.Dependencies, authentication *auth.Service, manag option(server) } } + if server.orderDependencies == nil { + return nil, fmt.Errorf("server 订单专用依赖不能为空") + } + if server.accountDependencies == nil { + return nil, fmt.Errorf("server 账号专用依赖不能为空") + } + if server.itemDependencies == nil { + return nil, fmt.Errorf("server 商品专用依赖不能为空") + } + if server.chatDependencies == nil { + return nil, fmt.Errorf("server 聊天专用依赖不能为空") + } + if server.systemDependencies == nil { + return nil, fmt.Errorf("server 系统专用依赖不能为空") + } + if server.platformDependencies == nil { + return nil, fmt.Errorf("server 平台依赖不能为空") + } + if server.automationDependencies == nil { + return nil, fmt.Errorf("server 自动化依赖不能为空") + } + if server.miscDependencies == nil { + return nil, fmt.Errorf("server 通知、分析和卡券依赖不能为空") + } + if server.adminSettingsDependencies == nil { + return nil, fmt.Errorf("server 管理员与设置依赖不能为空") + } server.applications = newApplicationServices(server) - server.transactionRepository = dependencies.NewTransactionRepository() - server.databaseHealth = dependencies.NewDatabaseHealth() - server.reconciliation = dependencies.NewReconciliationService(logger) + server.databaseHealth = server.systemDependencies.NewDatabaseHealth() return server, nil } -// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。 +// mtopClient 返回构造阶段校验的平台 MTOP 客户端;零值 Server 返回 nil,避免隐式创建依赖。 func (s *Server) mtopClient() adapter.MTOPClient { if s.MTop != nil { return s.MTop } - return adapter.NewMTOPClient() + if s.platformDependencies != nil && s.platformDependencies.MTOPClient() != nil { + return s.platformDependencies.MTOPClient() + } + return nil } -// recoverExpiredMTOPSession 是 HTTP/API 入口的统一 Session 失效出口。 -// 各调用点必须先保存响应 Cookie 并释放账号凭证锁,再进入续期,避免锁反转。 -// recoverExpiredMTOPSession 负责recoverExpiredMTOP会话相关处理。 +// longLoginClient 返回构造阶段注入的长登录客户端;旧公开字段仅用于兼容现有测试替身。 +func (s *Server) longLoginClient() adapter.LongLoginClient { + if s.CookieRenew != nil { + return s.CookieRenew + } + if s.platformDependencies != nil && s.platformDependencies.LongLoginClient() != nil { + return s.platformDependencies.LongLoginClient() + } + return nil +} + +// qrLoginService 返回构造阶段注入的二维码服务;旧公开字段仅用于兼容现有测试替身。 +func (s *Server) qrLoginService() qrLoginService { + if s.QRLogin != nil { + return s.QRLogin + } + if s.platformDependencies != nil && s.platformDependencies.QRLoginService() != nil { + return s.platformDependencies.QRLoginService() + } + return nil +} + +// sessionRecoveryCallback 返回平台会话失效的统一适配回调。 +// 适配器负责错误分类和日志,账号运行时应用端口负责恢复;调用方不得跨凭证锁执行外部 I/O。 +func (s *Server) sessionRecoveryCallback() adapter.SessionRecoveryHandler { + if s == nil { + return nil + } + return adapter.NewSessionRecoveryHandler(s.Logger, func(ctx context.Context, cookieID string) bool { + // runtime 保存账号运行时应用服务;恢复由应用端口编排而非 HTTP 层直接调用 Manager。 + runtime := s.accountRuntimeApplication() + return runtime != nil && runtime.RecoverExpiredCredential(ctx, cookieID) + }) +} + +// recoverExpiredMTOPSession 保留旧测试入口并委托统一 Session 恢复适配回调。 +// 新生产调用应直接注入 sessionRecoveryCallback,避免把 Server 方法传入基础设施适配器。 func (s *Server) recoverExpiredMTOPSession(ctx context.Context, cookieID string, err error) bool { - if !adapter.IsSessionExpiredError(err) { - return false - } - if s.Logger != nil { - s.Logger.Warn("MTOP API 检测到 Session 过期,停止业务请求并开始即时续期", "account", cookieID, "err", err) - } - if s.Manager == nil { - return false - } - return s.Manager.RecoverExpiredCredential(ctx, cookieID) + // recovery 保存统一的错误分类、日志和运行时恢复回调。 + recovery := s.sessionRecoveryCallback() + return recovery != nil && recovery(ctx, cookieID, err) +} + +// recoverExpiredSession 触发已注入的平台会话恢复回调,供 HTTP transport 处理应用层平台错误。 +// 该方法不读取凭证、不调用 Manager,也不在凭证锁内执行外部 I/O。 +func (s *Server) recoverExpiredSession(ctx context.Context, cookieID string, err error) bool { + // recovery 保存统一的错误分类、日志和运行时恢复回调。 + recovery := s.sessionRecoveryCallback() + return recovery != nil && recovery(ctx, cookieID, err) } // Router 构建完整路由树。 @@ -483,12 +661,6 @@ func (s *Server) Start(ctx context.Context) error { WriteTimeout: 2 * time.Minute, IdleTimeout: 2 * time.Minute, } - // lifecycleCtx 是 Server 内部可取消的生命周期上下文。 - // lifecycleCancel 是触发 Server 生命周期收束的取消函数。 - // lifecycleCtx、lifecycleCancel 保存lifecycleCtx、lifecycle取消,供当前处理流程使用 - lifecycleCtx, lifecycleCancel := context.WithCancel(ctx) - s.lifecycleCtx = lifecycleCtx - s.lifecycleCancel = lifecycleCancel s.httpServer = httpServer s.httpDone = make(chan struct{}) s.httpErr = nil @@ -498,10 +670,9 @@ func (s *Server) Start(ctx context.Context) error { httpDone := s.httpDone s.lifecycleMu.Unlock() - // 生命周期上下文取消时触发统一 Stop;该 goroutine 不登记到后台任务组, - // 避免 Stop 等待自身造成死锁。 + // 进程生命周期 Context 取消时触发 HTTP Stop;应用组件关闭由 cmd 统一协调。 go func() { - <-lifecycleCtx.Done() + <-ctx.Done() // stopCtx 是自动关闭 HTTP 服务时使用的有限时长上下文。 // cancel 释放 stopCtx 的定时器资源。 // stopCtx、cancel 保存stopCtx、cancel,供当前处理流程使用 @@ -568,7 +739,7 @@ func (s *Server) Stop(ctx context.Context) error { if httpDone != nil && !waitForSignal(ctx, httpDone) { return ctx.Err() } - if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) { + if !s.waitForBackgroundContext(ctx) { return ctx.Err() } return nil @@ -576,18 +747,11 @@ func (s *Server) Stop(ctx context.Context) error { s.stopped = true // httpServer 是需要执行优雅关闭的标准库 HTTP 服务。 // httpDone 是监听 goroutine 退出的完成信号。 - // lifecycleCancel 是取消 Server 内部生命周期上下文的函数。 // httpServer 保存httpServer,供当前处理流程使用 httpServer := s.httpServer // httpDone 保存httpDone,供当前处理流程使用 httpDone := s.httpDone - // lifecycleCancel 保存lifecycle取消,供当前处理流程使用 - lifecycleCancel := s.lifecycleCancel s.lifecycleMu.Unlock() - - if lifecycleCancel != nil { - lifecycleCancel() - } // shutdownErr 是 HTTP 优雅关闭返回的错误;后台等待错误由 worker 自身记录。 var shutdownErr error if httpServer != nil { @@ -596,7 +760,7 @@ func (s *Server) Stop(ctx context.Context) error { if httpDone != nil && !waitForSignal(ctx, httpDone) { return ctx.Err() } - if !s.waitForBackgroundContext(ctx) || !s.waitForWorkersContext(ctx) { + if !s.waitForBackgroundContext(ctx) { return ctx.Err() } return shutdownErr @@ -611,13 +775,12 @@ func (s *Server) Run(ctx context.Context) error { return s.Wait() } -// WaitForBackground 等待恢复扫描器先退出,再等待其已经登记的批量 worker。 +// WaitForBackground 等待 Server 自有的 HTTP 后台任务退出;应用 worker 由生命周期协调器负责。 func (s *Server) WaitForBackground() { if s == nil { return } _ = s.waitForBackgroundContext(context.Background()) - s.waitForWorkers(10 * time.Second) } // closedSignal 负责closedSignal相关处理。 @@ -630,9 +793,10 @@ func closedSignal() chan struct{} { // lifecycleContext 负责lifecycle上下文相关处理。 func (s *Server) lifecycleContext() context.Context { - s.lifecycleMu.RLock() - defer s.lifecycleMu.RUnlock() - return s.lifecycleCtx + if s == nil || s.applicationLifecycle == nil { + return context.Background() + } + return s.applicationLifecycle.Context() } // startBackgroundTaskContext 登记并启动带显式 Context 的 Server 后台任务。 @@ -698,6 +862,17 @@ func (s *Server) finishBackgroundTask() { } } +// beginWorker 为仍需由 Server 等待的通用后台任务提供兼容测试入口;业务 worker 生命周期由应用协调器拥有。 +func (s *Server) beginWorker() func() { + if s == nil { + return func() {} + } + s.beginBackgroundTask() + return func() { + s.finishBackgroundTask() + } +} + // waitForBackgroundContext 等待已登记后台任务退出;超时只结束当前等待,不创建游离等待 goroutine。 func (s *Server) waitForBackgroundContext(ctx context.Context) bool { if s == nil { @@ -717,16 +892,6 @@ func (s *Server) waitForBackgroundContext(ctx context.Context) bool { return waitForSignal(ctx, done) } -// StartOrderReconciliationRecovery 启动受 Server 生命周期管理的订单补偿扫描器。 -func (s *Server) StartOrderReconciliationRecovery(ctx context.Context) string { - if s == nil || s.reconciliation == nil { - return "" - } - return s.startBackgroundTaskContext("订单状态补偿扫描器", ctx, func() { - s.reconciliation.Run(ctx) - }) -} - // taskRegistryForServer 返回 Server 的后台任务注册表;零值 Server 也会安全惰性初始化。 func (s *Server) taskRegistryForServer() *taskRegistry { if s == nil { @@ -740,58 +905,6 @@ func (s *Server) taskRegistryForServer() *taskRegistry { return s.taskRegistry } -// beginWorker 负责begin工作器相关处理。 -func (s *Server) beginWorker() func() { - s.workerMu.Lock() - if s.workerCount == 0 { - s.workersDone = make(chan struct{}) - } - s.workerCount++ - s.workerMu.Unlock() - return func() { - s.workerMu.Lock() - s.workerCount-- - if s.workerCount == 0 { - close(s.workersDone) - } - s.workerMu.Unlock() - } -} - -// waitForWorkers 负责waitForWorkers相关处理。 -func (s *Server) waitForWorkers(timeout time.Duration) { - if timeout <= 0 { - _ = s.waitForWorkersContext(context.Background()) - return - } - // ctx、cancel 分别表示有限等待上下文和释放定时器的函数。 - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - _ = s.waitForWorkersContext(ctx) -} - -// waitForWorkersContext 等待批量 worker,并将等待限制在调用方的关闭上下文内。 -func (s *Server) waitForWorkersContext(ctx context.Context) bool { - if ctx == nil { - ctx = context.Background() - } - s.workerMu.Lock() - // done 保存done,供当前处理流程使用 - done := s.workersDone - s.workerMu.Unlock() - if done == nil { - // 零值 Server 尚未登记批量 worker,可直接视为已完成。 - return true - } - select { - case <-done: - return true - case <-ctx.Done(): - s.Logger.Warn("等待后台 worker 退出超时") - return false - } -} - // waitForSignal 在关闭上下文取消或目标信号到达时返回,避免无界阻塞。 func waitForSignal(ctx context.Context, signal <-chan struct{}) bool { select { diff --git a/internal/server/server_test.go b/internal/server/server_test.go index d32c3ef..c8b9255 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -38,15 +38,49 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer // mgr 是使用空处理器的测试账号管理器。 mgr := account.NewManager(store, noopHandler{}, nil) // srv 是未启用聊天服务的基础测试 HTTP 服务。 - // dependencies 保存测试 Server 使用的基础设施工厂,避免 Server 直接持有 Store。 - dependencies, dependencyErr := adapter.NewDependencies(store) - if dependencyErr != nil { - t.Fatalf("NewDependencies: %v", dependencyErr) + // orderDependencies 保存订单应用服务专用的测试装配能力,确保 Server 不从通用容器回退读取订单依赖。 + orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store) + if orderDependencyErr != nil { + t.Fatalf("NewOrderDependencies: %v", orderDependencyErr) + } + // accountDependencies 保存测试 Server 的账号专用装配能力,避免回退到通用容器。 + accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store) + if accountDependencyErr != nil { + t.Fatalf("NewAccountDependencies: %v", accountDependencyErr) + } + // itemDependencies 保存测试 Server 的商品专用装配能力,避免回退到通用容器。 + itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store) + if itemDependencyErr != nil { + t.Fatalf("NewItemDependencies: %v", itemDependencyErr) + } + // chatDependencies 保存聊天测试使用的显式适配器工厂。 + chatDependencies := adapter.NewChatDependencies(store) + // systemDependencies 保存健康检查与补偿扫描测试使用的显式适配器工厂。 + systemDependencies := adapter.NewSystemDependencies(store) + // automationDependencies 保存自动化测试使用的显式适配器工厂及构造错误。 + automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store) + if automationDependencyErr != nil { + t.Fatalf("NewAutomationDependencies: %v", automationDependencyErr) + } + // miscDependencies 保存通知、分析和卡券测试使用的显式适配器工厂及构造错误。 + miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store) + if miscDependencyErr != nil { + t.Fatalf("NewMiscDependencies: %v", miscDependencyErr) + } + // adminSettingsDependencies 保存管理员和系统设置测试使用的显式适配器工厂。 + adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store) + if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil { + t.Fatal("显式 Server 依赖构造失败") + } + // platformDependencies 保存测试服务器显式注入的平台客户端集合。 + platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil) + if platformDependencyErr != nil { + t.Fatalf("NewPlatformDependencies: %v", platformDependencyErr) } // authentication 保存测试 HTTP 会话中间件需要的认证服务。 authentication := &auth.Service{Store: store} // srv、err 保存测试 HTTP 服务构造结果及失败原因。 - srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil) + srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)) if err != nil { t.Fatalf("New: %v", err) } @@ -77,6 +111,8 @@ func newTestServerWithChat(t *testing.T) (*Server, *db.Store, func()) { chatService := chat.New(store) // srv.chat 在测试构造阶段一次性注入通信服务,模拟构造 option 的效果。 srv.chat = chatService + // applications.chat 重新绑定测试聊天服务,确保实时订阅适配器与 srv.chat 使用同一事件中心。 + srv.applications.chat = newChatSendingApplication(srv) return srv, store, cleanup } @@ -95,15 +131,49 @@ func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) { // mgr 是未初始化测试使用的空处理器账号管理器。 mgr := account.NewManager(store, noopHandler{}, nil) // srv 是未初始化测试使用的 HTTP 服务实例。 - // dependencies 保存未初始化测试 Server 使用的基础设施工厂。 - dependencies, dependencyErr := adapter.NewDependencies(store) - if dependencyErr != nil { - t.Fatalf("NewDependencies: %v", dependencyErr) + // orderDependencies 保存未初始化测试的订单专用装配能力。 + orderDependencies, orderDependencyErr := adapter.NewOrderDependencies(store) + if orderDependencyErr != nil { + t.Fatalf("NewOrderDependencies: %v", orderDependencyErr) + } + // accountDependencies 保存未初始化测试的账号专用装配能力。 + accountDependencies, accountDependencyErr := adapter.NewAccountDependencies(store) + if accountDependencyErr != nil { + t.Fatalf("NewAccountDependencies: %v", accountDependencyErr) + } + // itemDependencies 保存未初始化测试的商品专用装配能力。 + itemDependencies, itemDependencyErr := adapter.NewItemDependencies(store) + if itemDependencyErr != nil { + t.Fatalf("NewItemDependencies: %v", itemDependencyErr) + } + // chatDependencies 保存未初始化测试使用的聊天适配器工厂。 + chatDependencies := adapter.NewChatDependencies(store) + // systemDependencies 保存未初始化测试使用的系统适配器工厂。 + systemDependencies := adapter.NewSystemDependencies(store) + // automationDependencies 保存未初始化测试使用的自动化适配器工厂及构造错误。 + automationDependencies, automationDependencyErr := adapter.NewAutomationDependencies(store) + if automationDependencyErr != nil { + t.Fatalf("NewAutomationDependencies: %v", automationDependencyErr) + } + // miscDependencies 保存未初始化测试使用的杂项适配器工厂及构造错误。 + miscDependencies, miscDependencyErr := adapter.NewMiscDependencies(store) + if miscDependencyErr != nil { + t.Fatalf("NewMiscDependencies: %v", miscDependencyErr) + } + // adminSettingsDependencies 保存未初始化测试使用的管理员设置适配器工厂。 + adminSettingsDependencies := adapter.NewAdminSettingsDependencies(store) + if chatDependencies == nil || systemDependencies == nil || adminSettingsDependencies == nil { + t.Fatal("显式 Server 依赖构造失败") + } + // platformDependencies 保存未初始化测试服务器显式注入的平台客户端集合。 + platformDependencies, platformDependencyErr := adapter.NewDefaultPlatformDependencies(nil) + if platformDependencyErr != nil { + t.Fatalf("NewPlatformDependencies: %v", platformDependencyErr) } // authentication 保存未初始化数据库上的会话中间件依赖。 authentication := &auth.Service{Store: store} // srv、err 保存未初始化测试服务构造结果及失败原因。 - srv, err := New(dependencies, authentication, mgr, "", ":0", nil, nil, nil) + srv, err := New(authentication, mgr, "", ":0", nil, nil, nil, WithChatDependencies(chatDependencies), WithSystemDependencies(systemDependencies), WithOrderDependencies(orderDependencies), WithAccountDependencies(accountDependencies), WithItemDependencies(itemDependencies), WithAutomationDependencies(automationDependencies), WithMiscDependencies(miscDependencies), WithAdminSettingsDependencies(adminSettingsDependencies), WithPlatformDependencies(platformDependencies)) if err != nil { t.Fatalf("New: %v", err) } diff --git a/internal/server/settings_handlers.go b/internal/server/settings_handlers.go index 3d83e63..5411877 100644 --- a/internal/server/settings_handlers.go +++ b/internal/server/settings_handlers.go @@ -182,7 +182,7 @@ func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) { writeErrRequest(w, r, http.StatusInternalServerError, "查询失败") return } - writeJSON(w, http.StatusOK, settingsResponse(m)) + writeJSON(w, http.StatusOK, newSettingsResponse(m)) } // allSettings 负责all设置相关处理。 @@ -199,7 +199,7 @@ func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, "查询失败") return } - writeJSON(w, http.StatusOK, settingsResponse(m)) + writeJSON(w, http.StatusOK, newSettingsResponse(m)) } // setSetting 负责set设置相关处理。 @@ -447,7 +447,7 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, "查询失败") return } - writeJSON(w, http.StatusOK, settingsResponse(settings)) + writeJSON(w, http.StatusOK, newSettingsResponse(settings)) } // getUserSetting 负责get用户设置相关处理。 diff --git a/internal/server/success_api_contract_test.go b/internal/server/success_api_contract_test.go index b2a5152..95b6a99 100644 --- a/internal/server/success_api_contract_test.go +++ b/internal/server/success_api_contract_test.go @@ -395,7 +395,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { if publicSettingsDecodeErr := json.Unmarshal(publicSettingsRecorder.Body.Bytes(), &publicSettingsValue); publicSettingsDecodeErr != nil { t.Fatalf("decode public settings response: %v", publicSettingsDecodeErr) } - if publicSettingsValue == nil { + if publicSettingsValue.Entries == nil { t.Fatal("public settings response must be an object") } @@ -414,7 +414,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { if allSettingsDecodeErr := json.Unmarshal(allSettingsRecorder.Body.Bytes(), &allSettingsValue); allSettingsDecodeErr != nil { t.Fatalf("decode all settings response: %v", allSettingsDecodeErr) } - if allSettingsValue == nil { + if allSettingsValue.Entries == nil { t.Fatal("all settings response must be an object") } @@ -433,7 +433,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { if userSettingsDecodeErr := json.Unmarshal(userSettingsRecorder.Body.Bytes(), &userSettingsValue); userSettingsDecodeErr != nil { t.Fatalf("decode user settings response: %v", userSettingsDecodeErr) } - if userSettingsValue == nil { + if userSettingsValue.Entries == nil { t.Fatal("user settings response must be an object") } @@ -462,12 +462,18 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) { if qrStatusDecodeErr := json.Unmarshal(qrStatusRecorder.Body.Bytes(), &qrStatusValue); qrStatusDecodeErr != nil { t.Fatalf("decode qr status response: %v", qrStatusDecodeErr) } - if qrStatusValue["status"] != "waiting" || qrStatusValue["custom_field"] != "kept" { + if qrStatusValue.Status != "waiting" || qrStatusValue.SessionID != "contract-qr" { t.Fatalf("qr status response=%+v", qrStatusValue) } // leaked 表示二维码状态响应是否意外包含敏感 Cookie 字段。 - if _, leaked := qrStatusValue["cookies"]; leaked { - t.Fatalf("qr status response leaked cookies: %+v", qrStatusValue) + var rawQR map[string]any + // decodeErr 表示原始二维码响应反序列化失败的原因。 + if decodeErr := json.Unmarshal(qrStatusRecorder.Body.Bytes(), &rawQR); decodeErr != nil { + t.Fatalf("decode raw qr status response: %v", decodeErr) + } + // leaked 表示原始响应是否包含不应暴露的 Cookie 字段。 + if _, leaked := rawQR["cookies"]; leaked { + t.Fatalf("qr status response leaked cookies: %+v", rawQR) } // srv.QRLogin 替换为完成验证场景的测试替身。 diff --git a/internal/server/success_contract.go b/internal/server/success_contract.go index 6468b0c..8675f5e 100644 --- a/internal/server/success_contract.go +++ b/internal/server/success_contract.go @@ -1,6 +1,8 @@ package server import ( + "encoding/json" + cardsapp "xianyu-go/internal/application/cards" chatapp "xianyu-go/internal/application/chat" defaultreplyapp "xianyu-go/internal/application/defaultreply" @@ -572,6 +574,54 @@ type orderDetailResponse struct { Data orderDTO `json:"data"` } +// orderUpdateRequestDTO 是订单更新接口的具名请求 DTO,保留旧客户端的状态字段别名。 +type orderUpdateRequestDTO struct { + // OrderStatus 是订单状态补丁。 + OrderStatus *string `json:"order_status"` + // Status 是旧客户端使用的订单状态别名。 + Status *string `json:"status"` + // ItemID 是商品标识补丁。 + ItemID *string `json:"item_id"` + // BuyerID 是买家标识补丁。 + BuyerID *string `json:"buyer_id"` + // SpecName 是规格名称补丁。 + SpecName *string `json:"spec_name"` + // SpecValue 是规格值补丁。 + SpecValue *string `json:"spec_value"` + // Quantity 是兼容字符串或数字格式的购买数量。 + Quantity *any `json:"quantity"` + // Amount 是兼容字符串或数字格式的订单金额。 + Amount *any `json:"amount"` + // ReceiverName 是收货人补丁。 + ReceiverName *string `json:"receiver_name"` + // ReceiverPhone 是收货电话补丁。 + ReceiverPhone *string `json:"receiver_phone"` + // ReceiverAddress 是收货地址补丁。 + ReceiverAddress *string `json:"receiver_address"` + // ReceiverCity 是收货城市补丁。 + ReceiverCity *string `json:"receiver_city"` + // ChatID 是聊天会话补丁。 + ChatID *string `json:"chat_id"` + // SystemShipped 表示是否由系统完成发货。 + SystemShipped *bool `json:"system_shipped"` + // ItemTitle 是关联商品标题补丁。 + ItemTitle *string `json:"item_title"` +} + +// manualShipRequestDTO 是批量手动发货接口的具名请求 DTO。 +type manualShipRequestDTO struct { + // OrderIDs 是待处理订单标识列表。 + OrderIDs []string `json:"order_ids"` + // ShipMode 是发货模式。 + ShipMode string `json:"ship_mode"` +} + +// qrVerificationRequestDTO 是扫码风控验证完成接口的具名请求 DTO。 +type qrVerificationRequestDTO struct { + // TargetAccountID 是可选的待重新授权本地账号标识。 + TargetAccountID string `json:"target_account_id"` +} + // orderRefreshDetailResponse 是订单刷新后返回的远端详情 DTO。 type orderRefreshDetailResponse struct { // Quantity 是订单购买数量。 @@ -595,7 +645,33 @@ type orderRefreshResponse struct { // Summary 是刷新统计摘要。 Summary orderRefreshSummary `json:"summary"` // Results 是逐账号或逐订单的兼容结果行。 - Results []map[string]any `json:"results"` + Results []orderRefreshResultDTO `json:"results"` +} + +// orderRefreshResultDTO 是订单刷新批次中单条结果的稳定响应 DTO;可选字段只在对应阶段产生时返回。 +type orderRefreshResultDTO struct { + // Success 表示当前账号或订单刷新是否成功。 + Success bool `json:"success"` + // CookieID 是当前结果关联的账号标识。 + CookieID string `json:"cookie_id,omitempty"` + // Discovered 是当前账号发现的新订单数量。 + Discovered *int `json:"discovered,omitempty"` + // Updated 是当前账号更新的订单数量。 + Updated *int `json:"updated,omitempty"` + // SoftDeleted 表示当前账号是否标记了失效订单。 + SoftDeleted *bool `json:"soft_deleted,omitempty"` + // OrderID 是单订单刷新结果关联的平台订单标识。 + OrderID string `json:"order_id,omitempty"` + // Stage 是刷新失败或完成所处的业务阶段。 + Stage string `json:"stage,omitempty"` + // Message 是面向客户端的结果说明。 + Message string `json:"message,omitempty"` + // Error 是当前结果的兼容错误文本。 + Error string `json:"error,omitempty"` + // OldStatus 是刷新前的订单状态。 + OldStatus string `json:"old_status,omitempty"` + // NewStatus 是刷新后的订单状态。 + NewStatus string `json:"new_status,omitempty"` } // orderRefreshSummary 是订单列表刷新统计摘要 DTO。 @@ -639,7 +715,23 @@ type manualShipResponse struct { // FailedCount 是失败发货数量。 FailedCount int `json:"failed_count"` // Results 是逐订单的兼容结果行。 - Results []map[string]any `json:"results"` + Results []orderMutationResultDTO `json:"results"` +} + +// orderMutationResultDTO 是手动发货逐订单结果的稳定响应 DTO。 +type orderMutationResultDTO struct { + // OrderID 是当前结果关联的平台订单标识。 + OrderID string `json:"order_id"` + // Status 是发货后订单状态或失败阶段。 + Status string `json:"status"` + // Success 表示当前订单是否发货成功。 + Success bool `json:"success"` + // Message 是当前订单的处理说明。 + Message string `json:"message"` + // ReconciliationID 是可选的补偿记录标识。 + ReconciliationID string `json:"reconciliation_id,omitempty"` + // ReconciliationWarning 是可选的补偿告警文本。 + ReconciliationWarning string `json:"reconciliation_warning,omitempty"` } // importOrdersResponse 是订单导入接口的具名响应 DTO。 @@ -655,7 +747,17 @@ type importOrdersResponse struct { // FailedCount 是失败导入数量。 FailedCount int `json:"failed_count"` // Results 是逐订单的兼容结果行。 - Results []map[string]any `json:"results"` + Results []orderImportResultDTO `json:"results"` +} + +// orderImportResultDTO 是订单导入逐订单结果的稳定响应 DTO。 +type orderImportResultDTO struct { + // OrderID 是当前结果关联的平台订单标识。 + OrderID string `json:"order_id"` + // Success 表示当前订单是否导入成功。 + Success bool `json:"success"` + // Message 是当前订单的处理说明。 + Message string `json:"message"` } // aiReplySettingsResponse 是账号 AI 回复设置接口的具名响应 DTO。 @@ -1364,11 +1466,69 @@ type qrLoginGenerateResponse struct { Message string `json:"message,omitempty"` } -// settingsResponse 是动态设置查询的具名边界类型,键和值仍由设置仓库定义。 -type settingsResponse map[string]string +// settingsEntryDTO 是单条设置键值的具名 DTO;仅在 HTTP 边界内部用于稳定排序和校验。 +type settingsEntryDTO struct { + // Key 是设置项的稳定键名。 + Key string `json:"key"` + // Value 是设置项的脱敏文本值。 + Value string `json:"value"` +} -// qrLoginStatusResponse 是二维码状态的兼容响应类型,允许上游扩展非敏感字段。 -type qrLoginStatusResponse map[string]any +// settingsResponse 是设置查询的具名响应 DTO;序列化时保持旧客户端的顶层键值对象形状。 +type settingsResponse struct { + // Entries 保存设置键值,避免 DTO 直接暴露动态 map 字段。 + Entries []settingsEntryDTO `json:"-"` +} + +// newSettingsResponse 将应用层动态设置键值转换为具名 HTTP 响应 DTO。 +func newSettingsResponse(values map[string]string) settingsResponse { + // entries 保存待编码的设置项;顺序不影响兼容 JSON 对象,但便于测试和日志稳定。 + entries := make([]settingsEntryDTO, 0, len(values)) + // key 是当前设置名称;value 是对应的非敏感配置值。 + for key, value := range values { + entries = append(entries, settingsEntryDTO{Key: key, Value: value}) + } + return settingsResponse{Entries: entries} +} + +// MarshalJSON 保持设置接口原有的顶层键值对象契约,同时隐藏内部动态字段实现。 +func (response settingsResponse) MarshalJSON() ([]byte, error) { + // values 保存兼容旧客户端的顶层设置对象。 + values := make(map[string]string, len(response.Entries)) + // entry 是当前待恢复为顶层设置字段的具名条目。 + for _, entry := range response.Entries { + values[entry.Key] = entry.Value + } + return json.Marshal(values) +} + +// UnmarshalJSON 将旧客户端顶层设置对象解析为具名条目,供契约测试和边界适配使用。 +func (response *settingsResponse) UnmarshalJSON(data []byte) error { + // values 保存收到的顶层设置对象;设置值均按字符串处理以避免秘密类型扩散。 + var values map[string]string + // err 表示旧版顶层设置对象反序列化失败的原因。 + if err := json.Unmarshal(data, &values); err != nil { + return err + } + *response = newSettingsResponse(values) + return nil +} + +// qrLoginStatusResponse 是二维码状态的稳定响应 DTO,仅暴露非敏感状态和持久化结果。 +type qrLoginStatusResponse struct { + // Success 表示当前扫码状态请求是否正常完成。 + Success bool `json:"success,omitempty"` + // Status 是扫码会话当前状态。 + Status string `json:"status"` + // Message 是可选的平台提示文本。 + Message string `json:"message,omitempty"` + // SessionID 是可选的扫码会话标识。 + SessionID string `json:"session_id,omitempty"` + // AccountID 是扫码成功后创建或更新的本地账号标识。 + AccountID string `json:"account_id,omitempty"` + // IsNewAccount 表示扫码成功后是否新建本地账号。 + IsNewAccount bool `json:"is_new_account,omitempty"` +} // qrLoginVerificationResponse 是二维码风控验证完成的具名响应 DTO。 type qrLoginVerificationResponse struct { diff --git a/internal/server/unit_of_work.go b/internal/server/unit_of_work.go deleted file mode 100644 index 6ba77aa..0000000 --- a/internal/server/unit_of_work.go +++ /dev/null @@ -1,19 +0,0 @@ -package server - -import ( - "context" - "database/sql" - "errors" -) - -// withTransaction 在 Server 应用层统一创建、提交或回滚数据库事务。 -// 调用方只描述事务内的数据库操作,不再直接管理事务生命周期。 -// withTransaction 负责withTransaction相关处理。 -func (s *Server) withTransaction(ctx context.Context, work func(*sql.Tx) error) error { - // repository 是当前 Server 装配的事务执行边界。 - repository := s.transactionRepository - if repository == nil { - return errors.New("事务 repository 未初始化") - } - return repository.WithTransaction(ctx, work) -} diff --git a/internal/server/unit_of_work_test.go b/internal/server/unit_of_work_test.go deleted file mode 100644 index 4cdc8a4..0000000 --- a/internal/server/unit_of_work_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package server - -import ( - "context" - "database/sql" - "errors" - "testing" -) - -// TestWithTransactionCommitAndRollback 验证统一事务入口能够提交成功操作并回滚失败操作。 -func TestWithTransactionCommitAndRollback(t *testing.T) { - // srv 是使用测试数据库的 Server。 - srv, store, cleanup := newTestServer(t) - defer cleanup() - // ctx 是本测试使用的可取消上下文。 - ctx := context.Background() - // createErr 是创建测试表失败时的错误。 - 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 是提交事务执行结果。 - commitErr := srv.withTransaction(ctx, func(tx *sql.Tx) error { - // err 保存err,供当前处理流程使用 - _, err := tx.ExecContext(ctx, `INSERT INTO unit_of_work_probe (id, value) VALUES (1, 'committed')`) - return err - }) - if commitErr != nil { - t.Fatalf("事务提交失败: %v", commitErr) - } - // rollbackErr 是故意触发回滚事务的错误。 - rollbackErr := errors.New("故意回滚") - if // err 保存err,供当前处理流程使用 - err := srv.withTransaction(ctx, func(tx *sql.Tx) error { - // err 保存err,供当前处理流程使用 - _, err := tx.ExecContext(ctx, `INSERT INTO unit_of_work_probe (id, value) VALUES (2, 'rolled back')`) - if err != nil { - return err - } - return rollbackErr - }); !errors.Is(err, rollbackErr) { - t.Fatalf("事务回滚错误不匹配: %v", err) - } - // count 是事务提交后测试表中的记录数。 - var count int - if // err 保存err,供当前处理流程使用 - err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM unit_of_work_probe`).Scan(&count); err != nil { - t.Fatalf("查询事务测试结果失败: %v", err) - } - if count != 1 { - t.Fatalf("事务回滚后记录数应为 1,got %d", count) - } -} diff --git a/internal/webui/static/assets/AccountList-Bpj-f-W3.js b/internal/webui/static/assets/AccountList-Bpj-f-W3.js deleted file mode 100644 index bf7c235..0000000 --- a/internal/webui/static/assets/AccountList-Bpj-f-W3.js +++ /dev/null @@ -1,3 +0,0 @@ -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/AccountList-fhDk6BDY.js b/internal/webui/static/assets/AccountList-fhDk6BDY.js new file mode 100644 index 0000000..2e9a992 --- /dev/null +++ b/internal/webui/static/assets/AccountList-fhDk6BDY.js @@ -0,0 +1,3 @@ +import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,p as ae,a as ce,d as Pe}from"./index-CFzx5gQT.js";import{c as Le,o as ke}from"./contract-COFcZjyb.js";import{X as de,n as ze,L as J,o as Ge,p as Ie,q as Te,r as $e,s as te,t as De,K as We,u as Ve,v as Je,e as Ke,w as ue,f as He,U as Ee,x as Xe,k as _e,Q as ve,R as Ye,y as Ze,z as Fe,F as Ne,H as es}from"./icons-vendor-CvzvbbIV.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Le(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Pe(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Pe(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={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 ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Le(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),vs=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",Ns=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.signal)&&a(R)}).catch(R=>{Y(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Y(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[s.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var v;if(!Ae(i,b))return;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Se(s.id,r,{signal:j.signal});if(!Y(p.current,S,j.signal))return;a(R),t(R)}catch(R){Y(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Y(p.current,S,j.signal)&&d(!1)}},[s.id,r,t,b,i]),M=n.useCallback(async S=>{var R;if(!Ae(i,b)||!s.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),A(null),g(null);try{await Se(s.id,r,{signal:v.signal});const w=await vs(s.id,S,{signal:v.signal}),q=await Ce(s.id,{signal:v.signal});if(!Y(p.current,j,v.signal))return;A(w.summary),a(q),t(q)}catch(w){Y(p.current,j,v.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Y(p.current,j,v.signal)&&m("")}},[s.enabled,s.id,r,t,b,i]),T=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:l,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:T}},qe=({checked:s,onChange:t,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":s,onClick:t,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${s?"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 ${s?"translate-x-6":""}`})}),ks=({account:s,onClose:t,onSaved:r})=>{const{form:a,loading:l,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=Ns({account:s,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:s.nickname||s.remark||s.id})]}),e.jsx("button",{type:"button",onClick:t,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[l&&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(ze,{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(qe,{checked:a.auto_rate_enabled,onChange:(()=>f(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=>f(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:i!==""||!s.enabled,onClick:(()=>void u("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:[i==="auto_rate"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Ge,{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(Ie,{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(qe,{checked:a.auto_polish_enabled,onChange:(()=>f(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=>f(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:i!==""||!s.enabled,onClick:(()=>void u("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:[i==="auto_polish"?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{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||""]}),d&&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:d}),m&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void A()),children:"重试"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex w-full gap-3",children:[e.jsx("button",{type:"button",onClick:t,disabled:c||i!=="",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:c||i!==""||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:[c?e.jsx(J,{className:"h-4 w-4 animate-spin"}):e.jsx($e,{className:"h-4 w-4"}),"保存"]})]})})]})})},Qe=({src:s,alt:t,className:r=""})=>e.jsx("img",{src:s,alt:t,className:`block aspect-square h-auto w-full object-contain ${r}`.trim()}),Cs=({account:s,editForm:t,setEditForm:r,saving:a,onClose:l,onSave:c,onRestartPause:i,longLogin:d,onToggleLongLogin:b,passwordLoginView:m,onPasswordLogin:f,onCancelPasswordLogin:h,notifChannels:u,selectedChannelIds:A,bindingsLoaded:k,bindingsLoading:g,bindingsLoadError:p,onRetryBindings:L,onToggleChannel:U,onSettingsDirty:M})=>{const T=(C,W)=>{r(ee=>({...ee,[C]:W}))},S=()=>void l(),j=()=>void c(),v=C=>T("remark",C.target.value),R=C=>T("cookie",C.target.value),w=()=>T("auto_confirm",!t.auto_confirm),q=C=>T("pause_duration",parseInt(C.target.value,10)||0),D=()=>void i(),H=()=>void b(),K=C=>T("username",C.target.value),G=C=>r(W=>({...W,login_password:C.target.value,clear_password:!1})),V=()=>T("showLoginPassword",!t.showLoginPassword),O=C=>r(W=>({...W,clear_password:C.target.checked,login_password:C.target.checked?"":W.login_password})),I=()=>T("show_browser",!t.show_browser),z=()=>void h(),E=()=>void f(),Q=()=>void L(),F=C=>{k&&(U(C),M())},re=C=>{const W=A.includes(Number(C.id)),ee=()=>F(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:ee,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(te,{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 ie.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:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:S,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(de,{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:s.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:t.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:t.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长度: ",t.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(te,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:w,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.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 ${t.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(De,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:t.pause_duration,onChange:q,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:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),t.pause_duration>0&&!s.paused&&t.pause_duration===(s.pause_duration||0)&&e.jsx("button",{type:"button",disabled:a,onClick:D,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(We,{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:"状态直接读取并修改闲鱼官方长登录设置"}),d.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:d.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:d.loading||d.saving||!d.canOpen,onClick:H,className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${d.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 ${d.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:t.username,onChange:K,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:t.showLoginPassword?"text":"password",value:t.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:t.showLoginPassword?e.jsx(Ve,{className:"w-5 h-5"}):e.jsx(Je,{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:t.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 ${t.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 ${t.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:E,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(Qe,{src:m.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(u.length>0||g||p)&&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(Ke,{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(J,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),p&&!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:p}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:Q,children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:u.map(re)})]})]}),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:j,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(J,{className:"w-4 h-4 animate-spin"}):e.jsx(te,{className:"w-4 h-4"}),a?"保存中...":"保存"]})]})})]})}),document.body)},Ss=({account:s,settings:t,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...t,...u}),d=()=>i({ai_enabled:!t.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.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(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:l,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{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(ue,{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:d,className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${t.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 ${t.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:t.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:t.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:t.max_bargain_rounds,onChange:f,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:t.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(He,{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:l,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 c()),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(J,{className:"w-4 h-4 animate-spin"}):e.jsx($e,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Rs=(s,t)=>{if(!s||!t)return!1;const r=Date.parse(s),a=Date.parse(t);return Number.isFinite(r)&&Number.isFinite(a)&&as.map(r=>{const a=t[r.id];return!a||Rs(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}}),qs=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.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"}}},Ps=Oe.memo(function({account:t,refreshing:r,deleting:a,onRefreshProfile:l,onReauthorize:c,onEdit:i,onAI:d,onTasks:b,onToggle:m,onDelete:f}){const h=qs(t),u=t.runtime_state==="auth_expired"||t.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:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.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(Ee,{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:t.runtime_state==="online"&&e.jsx(te,{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:t.nickname||t.remark||`账号 ${t.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}),t.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(ue,{className:"w-3 h-3"})," AI"]}),t.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(Xe,{className:"h-3 w-3"})," 自动评价"]}),t.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(Ie,{className:"h-3 w-3"})," 每日擦亮"]}),t.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(te,{className:"h-3 w-3"})," 自动确认发货"]}),t.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:t.profile_error,children:[e.jsx(_e,{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:t.remark||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",t.id]})]}),t.runtime_message&&t.runtime_state!=="online"&&t.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${u?"text-red-700":"text-amber-700"}`,children:[e.jsx(_e,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:t.runtime_message}),u&&e.jsxs("button",{type:"button",onClick:(()=>c(t)),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(ve,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),t.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(De,{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:(()=>l(t)),disabled:r,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(Ye,{className:`w-5 h-5 ${r?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>c(t)),className:`p-3 rounded-xl transition-colors ${u?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(ve,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>i(t)),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Ze,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>d(t)),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(ue,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>b(t)),className:"p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600",title:"自动评价与每日擦亮",children:e.jsx(Te,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>m(t.id,t.enabled)),className:`p-3 rounded-xl transition-colors ${t.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:t.enabled?"停用账号":"启用账号",children:e.jsx(Fe,{className:"w-5 h-5"})}),e.jsx("button",{onClick:(()=>f(t)),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?"删除中…":`删除账号 ${t.nickname||t.remark||t.id}`,children:a?e.jsx(J,{className:"w-5 h-5 animate-spin"}):e.jsx(Ne,{className:"w-5 h-5"})})]})]})]})]})})}),Ls=({account:s,deleting:t,error:r,onClose:a,onConfirm:l})=>ie.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(Ne,{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:t,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(de,{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:s.nickname||s.remark||"未命名账号"}),s.remark&&s.nickname&&e.jsxs("div",{className:"mt-1 text-sm text-gray-500",children:["备注:",s.remark]}),e.jsxs("div",{className:"mt-1.5 break-all font-mono text-[11px] text-gray-400",children:["ID: ",s.id]})]}),t&&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(J,{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(_e,{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:t,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 l()),disabled:t,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:t?e.jsxs(e.Fragment,{children:[e.jsx(J,{className:"h-4 w-4 animate-spin"}),"处理中"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"h-4 w-4"}),"确认删除"]})})]})]})}),document.body),Is=({faceQrUrl:s,verificationScreenshot:t})=>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(es,{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:s?e.jsx("img",{src:s,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):t?e.jsx("img",{src:t,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(J,{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:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),Ts=({target:s,status:t,codeUrl:r,errorMessage:a,faceQrUrl:l,verificationScreenshot:c,onClose:i})=>ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:i,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(de,{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:s?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:s?`请用闲鱼APP扫码,为「${s.nickname||s.remark||s.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 ${t==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[t==="loading"&&e.jsx(J,{className:"w-10 h-10 text-brand animate-spin"}),t==="waiting"&&e.jsx(Qe,{src:r,alt:"闲鱼登录二维码",className:"p-2"}),t==="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(te,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),t==="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||"请关闭窗口后重新发起扫码登录。"})]}),t==="verification"&&e.jsx(Is,{faceQrUrl:l,verificationScreenshot:c})]}),t!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),$s=(s,t)=>s.map(r=>{var a,l,c,i,d;return{...r,ai_enabled:((a=t[r.id])==null?void 0:a.ai_enabled)??!1,max_discount_percent:((l=t[r.id])==null?void 0:l.max_discount_percent)??10,max_discount_amount:((c=t[r.id])==null?void 0:c.max_discount_amount)??100,max_bargain_rounds:((i=t[r.id])==null?void 0:i.max_bargain_rounds)??3,custom_prompts:((d=t[r.id])==null?void 0:d.custom_prompts)??""}}),Ds=()=>{const[s,t]=n.useState([]),[r,a]=n.useState(!0),l=n.useRef(0),c=n.useRef(null),i=n.useCallback(async()=>{var m;const d=++l.current;(m=c.current)==null||m.abort();const b=new AbortController;c.current=b,a(!0);try{const f={signal:b.signal},[h,u]=await Promise.allSettled([ts(f),ps(f)]);if(d!==l.current)return;if(h.status==="rejected")throw h.reason;const A=u.status==="fulfilled"?u.value:{};u.status==="rejected"&&console.error("加载 AI 设置失败:",u.reason),t($s(h.value,A))}catch(f){d===l.current&&!b.signal.aborted&&console.error("加载账号失败:",f)}finally{d===l.current&&a(!1)}},[]);return n.useEffect(()=>{let d=!1,b=null;const m=new AbortController,f=async()=>{try{const u=await as({signal:m.signal,timeoutMs:1e4});d||t(A=>As(A,u))}catch(u){d||console.error("加载账号运行状态失败:",u)}finally{d||(b=window.setTimeout(()=>void f(),2e3))}};return i().finally(()=>{d||f()}),()=>{var u;d=!0,m.abort(),l.current+=1,(u=c.current)==null||u.abort(),b!==null&&window.clearTimeout(b)}},[i]),{accounts:s,setAccounts:t,loading:r,loadAccounts:i}},Es=new Set(["expired","cancelled","error","not_found"]),Qs=()=>{let s=0;return{next:()=>(s+=1,s),cancel:()=>{s+=1},isCurrent:(t=>t===s)}},Us=(s={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let t=null,r=null,a=-1,l=0;const c=()=>{l+=1,r==null||r.abort(),r=null,t!==null&&(s.clearInterval(t),t=null)};return{start:(d,b,m,f=2e3)=>{c();const h=l;r=new AbortController;const u=r.signal;t=s.setInterval(()=>{a===h||h!==l||(a=h,(async()=>{var A,k;try{const g=await b(d,u);if(g.status==="success"){c(),await m.onSuccess(g);return}if(g.status==="scanned"){(A=m.onScanned)==null||A.call(m,g);return}if(g.status==="verification_required"){(k=m.onVerificationRequired)==null||k.call(m,g);return}g.status&&Es.has(g.status)&&(c(),m.onTerminalError(g))}catch(g){if(u.aborted||h!==l)return;c(),m.onPollError(g)}finally{a===h&&(a=-1)}})())},f)},stop:c,isActive:(()=>t!==null)}},Ms=({onLoginSuccess:s})=>{const[t,r]=n.useState(!1),[a,l]=n.useState(""),[c,i]=n.useState("pending"),[d,b]=n.useState(""),[m,f]=n.useState(""),[h,u]=n.useState(""),[A,k]=n.useState(null),g=n.useRef(null),p=n.useRef(null),L=n.useRef(null),U=n.useRef(null);g.current===null&&(g.current=Us()),p.current===null&&(p.current=Qs());const M=()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},T=()=>{var w;(w=g.current)==null||w.stop()},S=()=>{var w,q;(w=L.current)==null||w.abort(),(q=p.current)==null||q.cancel(),T(),M(),r(!1)},j=()=>{M(),U.current=window.setTimeout(()=>{U.current=null,r(!1),s()},1e3)};n.useEffect(()=>()=>{var q,D;T(),(q=p.current)==null||q.cancel(),(D=L.current)==null||D.abort(),M()},[]);const v=async(w,q)=>{const D=await ls(w,q==null?void 0:q.id);if(!D.success||!D.account_id)throw new Error(D.message||"保存扫码授权失败");return D.account_id};return{showQRModal:t,qrCodeUrl:a,qrStatus:c,qrErrorMessage:d,verificationScreenshot:m,faceQrUrl:h,qrReauthTarget:A,startQRLogin:async w=>{var K,G,V,O;T(),(K=L.current)==null||K.abort();const q=new AbortController;L.current=q;const D=p.current.next();M();const H=w||null;k(H),r(!0),i("loading"),b(""),l(""),f(""),u("");try{const I=await rs({signal:q.signal});if(!((G=p.current)!=null&&G.isCurrent(D)))return;if(!I.success||!I.qr_code_url||!I.session_id)throw new Error(I.message||"闲鱼未返回可用的登录二维码");const z=I.session_id;l(I.qr_code_url),i("waiting"),(V=g.current)==null||V.start(z,ns,{onSuccess:(async()=>{try{await v(z,H)}catch(E){console.error("保存扫码授权失败",E),i("error");return}i("success"),j()}),onScanned:(()=>{i("waiting")}),onTerminalError:(()=>{i("error")}),onPollError:(E=>{console.error("轮询扫码状态失败",E),i("error")}),onVerificationRequired:(E=>{i("verification"),E.face_qr_url&&u(E.face_qr_url),E.verification_screenshot&&f(E.verification_screenshot)})})}catch(I){if(!((O=p.current)!=null&&O.isCurrent(D))||q.signal.aborted)return;b(I instanceof Error?I.message:"二维码获取失败,请稍后重试"),i("error")}finally{L.current===q&&(L.current=null)}},closeQRModal:S}},Bs=(s,t)=>s!==(t.pause_duration||0),Os=(s,t)=>{const r=t.username!==(s.username||""),a=t.show_browser!==(s.show_browser||!1),l=t.login_password!=="",c=t.clear_password===!0;if(!r&&!a&&!l&&!c)return null;const i={username:t.username,show_browser:t.show_browser};return c?i.clear_password=!0:l&&(i.login_password=t.login_password),i},Z=(s,t,r,a)=>s===t&&r===a,zs=s=>s.status==="success"?{sessionId:"",status:"success",message:s.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}:s.status==="processing"||s.status==="verification_required"?{sessionId:"",status:s.status,message:s.message||(s.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:s.qr_code_url||""}:{sessionId:"",status:"failed",message:s.error||s.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""},Gs=(s,t)=>s&&t,Ws=({editingAccount:s,setEditingAccount:t,setActiveModal:r,editForm:a,setEditForm:l,loadAccounts:c})=>{const[i,d]=n.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[b,m]=n.useState([]),[f,h]=n.useState([]),[u,A]=n.useState(!1),[k,g]=n.useState(!1),[p,L]=n.useState(!1),[U,M]=n.useState(""),[T,S]=n.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[j,v]=n.useState(!1),[R,w]=n.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),q=n.useRef(0),D=n.useRef(null),H=n.useRef(0),K=n.useRef(null),G=n.useRef(0),V=n.useRef(null),O=n.useRef(0),I=n.useRef(""),z=n.useRef(null),E=n.useRef(null),Q=n.useCallback(()=>{E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),F=n.useCallback(async o=>{var B;const x=++q.current;(B=D.current)==null||B.abort();const N=new AbortController;D.current=N,g(!0),A(!1),L(!1),M("");const[$,_]=await Promise.allSettled([ws({signal:N.signal}),_s(o,{signal:N.signal})]);Z(x,q.current,o,o)&&($.status==="fulfilled"?m($.value.data||[]):(m([]),M("通知渠道列表加载失败,请重试")),_.status==="fulfilled"?(h(_.value||[]),A(!0)):(h([]),M("通知绑定加载失败;本次保存不会修改现有绑定")),g(!1))},[]),re=n.useCallback(o=>{h(x=>x.includes(o)?x.filter(N=>N!==o):[...x,o]),L(!0)},[]),C=n.useCallback(async o=>{var _,B;const x=++H.current;(_=K.current)==null||_.abort();const N=new AbortController;K.current=N,O.current+=1,I.current=o.id,(B=z.current)==null||B.abort(),Q(),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),t(o),l({remark:o.remark||"",cookie:"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),r("edit"),d({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,$]=await Promise.allSettled([F(o.id),us(o.id,{signal:N.signal})]);x===H.current&&($.status==="fulfilled"?d({loading:!1,saving:!1,canOpen:$.value.can_open_long_login,enabled:$.value.enabled,error:""}):d({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"}))},[Q,F,r,l,t]),W=n.useCallback(async()=>{if(!s||i.loading||i.saving||!i.canOpen)return;const o=!i.enabled;d(x=>({...x,saving:!0,error:""}));try{const x=await xs(s.id,o);d({loading:!1,saving:!1,canOpen:x.can_open_long_login,enabled:x.enabled,error:""})}catch(x){d(N=>({...N,saving:!1,error:x instanceof Error?x.message:"保存登录信息设置失败"}))}},[s,i]),ee=n.useCallback(async o=>{var $;const x=++G.current;($=V.current)==null||$.abort();const N=new AbortController;V.current=N,t(o),r("ai-settings"),v(!0);try{const _=await fs(o.id,{signal:N.signal});if(!Z(x,G.current,o.id,o.id))return;S({ai_enabled:_.ai_enabled??!1,max_discount_percent:_.max_discount_percent??10,max_discount_amount:_.max_discount_amount??100,max_bargain_rounds:_.max_bargain_rounds??3,custom_prompts:_.custom_prompts??""})}catch(_){Z(x,G.current,o.id,o.id)&&console.error("加载 AI 设置失败:",_)}finally{Z(x,G.current,o.id,o.id)&&v(!1)}},[r,t]),xe=n.useCallback(async()=>{if(!(!s||j)){v(!0);try{await ys(s.id,T),r(null),await c()}catch(o){console.error("更新 AI 设置失败:",o)}finally{v(!1)}}},[T,s,c,j,r]),me=n.useCallback(async()=>{if(!(!s||j)){v(!0);try{const o={};a.remark!==(s.remark||"")&&(o.remark=a.remark),a.cookie&&(o.cookie=a.cookie),a.auto_confirm!==s.auto_confirm&&(o.auto_confirm=a.auto_confirm),Bs(a.pause_duration,s)&&(o.pause_duration=a.pause_duration);const x=Os(s,a);x&&Object.assign(o,x),Gs(u,p)&&(o.channel_ids=f),Object.keys(o).length>0&&await ds(s.id,o),r(null),await c()}catch(o){console.error("更新账号失败:",o)}finally{v(!1)}}},[p,u,a,s,c,f,j,r]),be=n.useCallback(async()=>{if(!(!s||a.pause_duration<=0||j)){v(!0);try{const o=await cs(s.id,a.pause_duration);t(x=>x&&{...x,pause_duration:a.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await c()}catch(o){console.error("重新暂停失败:",o)}finally{v(!1)}}},[a.pause_duration,s,c,j,t]),ne=n.useCallback(async(o,x,N)=>{var _;(_=z.current)==null||_.abort();const $=new AbortController;z.current=$;try{const B=await bs(o,$.signal);if(!Z(x,O.current,N,I.current))return;const oe={...zs(B),sessionId:o};if(B.status==="success"){Q(),w(oe),l(fe=>({...fe,login_password:"",showLoginPassword:!1})),await c();return}if(B.status==="processing"||B.status==="verification_required"){w(oe),Q(),E.current=window.setTimeout(()=>void ne(o,x,N),1500);return}Q(),w(oe)}catch(B){if(!Z(x,O.current,N,I.current))return;Q(),w({sessionId:o,status:"failed",message:B instanceof Error?B.message:"查询密码登录状态失败",qrCodeUrl:""})}},[Q,c,l]),he=n.useCallback(async()=>{var $;if(!s)return;const o=a.username.trim();if(!o||!a.login_password)return;Q(),($=z.current)==null||$.abort();const x=++O.current;I.current=s.id;const N=new AbortController;z.current=N,w({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const _=await ms({account_id:s.id,account:o,password:a.login_password,show_browser:a.show_browser},{signal:N.signal});if(!Z(x,O.current,s.id,I.current))return;if(!_.success||!_.session_id)throw new Error(_.message||"无法启动密码登录");w({sessionId:_.session_id,status:"processing",message:_.message||"登录处理中",qrCodeUrl:""}),await ne(_.session_id,x,s.id)}catch(_){if(!Z(x,O.current,s.id,I.current))return;w({sessionId:"",status:"failed",message:_ instanceof Error?_.message:"启动密码登录失败",qrCodeUrl:""})}},[Q,a.login_password,a.show_browser,a.username,s,ne]),le=n.useCallback(async()=>{var x;const o=R.sessionId;O.current+=1,I.current="",(x=z.current)==null||x.abort(),Q(),o&&await hs(o).catch(()=>{}),w({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},[Q,R.sessionId]),ge=n.useCallback(async()=>{var o,x,N;(o=D.current)==null||o.abort(),H.current+=1,(x=K.current)==null||x.abort(),(N=V.current)==null||N.abort(),(R.status==="processing"||R.status==="verification_required")&&await le(),r(null)},[le,R.status,r]),pe=n.useCallback(()=>{var o;G.current+=1,(o=V.current)==null||o.abort(),r(null)},[r]);return n.useEffect(()=>(()=>{var o,x,N,$;(o=D.current)==null||o.abort(),(x=K.current)==null||x.abort(),(N=V.current)==null||N.abort(),($=z.current)==null||$.abort(),Q()}),[Q]),{longLogin:i,notifChannels:b,selectedChannelIds:f,bindingsLoaded:u,bindingsLoading:k,bindingsDirty:p,bindingsLoadError:U,aiSettings:T,saving:j,passwordLoginView:R,setAiSettings:S,setBindingsDirty:L,setEditForm:l,openEditModal:C,closeEditModal:ge,openAIModal:ee,closeAIModal:pe,loadNotificationBindings:F,toggleNotificationChannel:re,handleLongLoginToggle:W,handleSaveAISettings:xe,handleSaveEdit:me,handleRestartPause:be,handlePasswordLogin:he,handleCancelPasswordLogin:le}},Xs=()=>{const{accounts:s,setAccounts:t,loading:r,loadAccounts:a}=Ds(),[l,c]=n.useState(""),[i,d]=n.useState(""),[b,m]=n.useState(""),[f,h]=n.useState(null),[u,A]=n.useState(""),[k,g]=n.useState(null),[p,L]=n.useState(null),[U,M]=n.useState(null),[T,S]=n.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),j=Ws({editingAccount:p,setEditingAccount:L,setActiveModal:g,editForm:T,setEditForm:S,loadAccounts:a}),{longLogin:v,notifChannels:R,selectedChannelIds:w,bindingsLoaded:q,bindingsLoading:D,bindingsLoadError:H,aiSettings:K,saving:G,passwordLoginView:V,setAiSettings:O,setBindingsDirty:I,openEditModal:z,closeEditModal:E,openAIModal:Q,closeAIModal:F,loadNotificationBindings:re,toggleNotificationChannel:C,handleLongLoginToggle:W,handleSaveAISettings:ee,handleSaveEdit:xe,handleRestartPause:me,handlePasswordLogin:be,handleCancelPasswordLogin:ne}=j,he=Ms({onLoginSuccess:a}),{showQRModal:le,qrCodeUrl:ge,qrStatus:pe,qrErrorMessage:o,verificationScreenshot:x,faceQrUrl:N,qrReauthTarget:$,startQRLogin:_,closeQRModal:B}=he,oe=async(y,P)=>{await os(y,!P),a()},fe=y=>{b||(A(""),h(y))},Ue=()=>{b||(A(""),h(null))},Me=async()=>{const y=f;if(!(!y||b)){m(y.id),A("");try{await is(y.id),t(P=>P.filter(se=>se.id!==y.id)),h(null)}catch(P){console.error("删除账号失败:",P),A((P==null?void 0:P.message)||"删除账号失败,请稍后重试")}finally{m("")}}},Be=async y=>{d(y.id);try{const P=await gs(y.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{d("")}};if(r)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(J,{className:"w-8 h-8 text-brand animate-spin"})});const ye=s.filter(y=>{const P=l.trim().toLowerCase();return P?[y.id,y.nickname,y.remark,y.username,y.runtime_message].some(se=>(se||"").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:l,onChange:(y=>c(y.target.value)),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:(()=>_()),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(ve,{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:["当前显示 ",ye.length," / ",s.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[ye.map(y=>e.jsx(Ps,{account:y,refreshing:i===y.id,deleting:b===y.id,onRefreshProfile:Be,onReauthorize:_,onEdit:z,onAI:Q,onTasks:M,onToggle:oe,onDelete:fe},y.id)),s.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(Ee,{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:"请点击右上角扫码添加您的闲鱼账号"})]}),s.length>0&&ye.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&&ie.createPortal(e.jsx(ks,{account:U,onClose:(()=>M(null)),onSaved:(y=>{t(P=>P.map(se=>se.id===U.id?{...se,auto_rate_enabled:y.auto_rate_enabled,rate_content:y.rate_content,auto_polish_enabled:y.auto_polish_enabled,polish_time:y.polish_time,last_rate_scan_at:y.last_rate_scan_at,last_polish_date:y.last_polish_date,last_polish_at:y.last_polish_at}:se))})}),document.body),f&&e.jsx(Ls,{account:f,deleting:b===f.id,error:u,onClose:Ue,onConfirm:Me}),le&&e.jsx(Ts,{target:$,status:pe,codeUrl:ge,errorMessage:o,faceQrUrl:N,verificationScreenshot:x,onClose:B}),k==="edit"&&p&&e.jsx(Cs,{account:p,editForm:T,setEditForm:S,saving:G,onClose:E,onSave:xe,onRestartPause:me,longLogin:v,onToggleLongLogin:W,passwordLoginView:V,onPasswordLogin:be,onCancelPasswordLogin:ne,notifChannels:R,selectedChannelIds:w,bindingsLoaded:q,bindingsLoading:D,bindingsLoadError:H,onRetryBindings:(()=>re(p.id)),onToggleChannel:C,onSettingsDirty:(()=>I(!0))}),k==="ai-settings"&&p&&e.jsx(Ss,{account:p,settings:K,saving:G,onChange:O,onClose:F,onSave:ee})]})};export{Xs as default}; diff --git a/internal/webui/static/assets/CardList-D-c7QNTB.js b/internal/webui/static/assets/CardList-D-c7QNTB.js new file mode 100644 index 0000000..e4fc7fe --- /dev/null +++ b/internal/webui/static/assets/CardList-D-c7QNTB.js @@ -0,0 +1,17 @@ +import{b as z,j as e,r as i}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Z,J as D,Y as ee,L as U,N as V,C as H,_ as te,$ as W,a0 as X,a1 as ae,I as se,a2 as le,V as ne,F as re,P as oe,r as ie}from"./icons-vendor-CvzvbbIV.js";import{g as ce,p as de,d as xe,a as Y,b as pe}from"./index-CFzx5gQT.js";import{c as me}from"./contract-COFcZjyb.js";const he=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.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:f,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:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Z,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(D,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.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:n,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(ee,{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(D,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.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:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.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(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.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:a.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:l.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:a.appendContent,onChange:m,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:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.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:a.appendError}),e.jsx("button",{type:"button",onClick:c,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.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:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(D,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:r,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||l.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(V,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ue=({type:l})=>{switch(l){case"text":return e.jsx(X,{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(te,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(H,{className:"w-5 h-5 text-gray-500"})}},be=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ge=async l=>{const n=await ce("/api/v1/cards",void 0,l);return me(n,["cards","data","items"]).map(be)},ye=async l=>Y("/api/v1/cards",K(l)),J=async(l,n)=>de(`/api/v1/cards/${l}`,K(n)),fe=async l=>xe(`/api/v1/cards/${l}`),je=async(l,n)=>{const a=new FormData;return a.append("file",l),pe("/api/v1/cards/batch",a,n)},Ne=async(l,n,a)=>Y(`/api/v1/cards/${l}/append-data`,{content:n},a),ve=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(` +`).map(n=>n.trim()).filter(Boolean),we=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,Ce=()=>{const[l,n]=i.useState([]),[a,u]=i.useState(!0),m=i.useRef(0),_=i.useRef(null),f=i.useCallback(async()=>{var A;const j=++m.current;(A=_.current)==null||A.abort();const d=new AbortController;_.current=d,u(!0);try{const c=await ge({signal:d.signal});if(j!==m.current)return;n(c)}catch(c){j===m.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",c)}finally{j===m.current&&u(!1)}},[]);return i.useEffect(()=>(f(),()=>{var d;m.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},_e=l=>{const n=l.dataCards,a=l.loadCards,[u,m]=i.useState(!1),[_,f]=i.useState("create"),[j,d]=i.useState(null),[A,c]=i.useState(null),[y,N]=i.useState(!1),[b,r]=i.useState(""),[x,s]=i.useState(""),[h,E]=i.useState(null),[M,R]=i.useState(""),v=i.useRef(0),T=i.useRef(null),P=i.useRef("");i.useEffect(()=>(()=>{var p;v.current+=1,(p=T.current)==null||p.abort()}),[]);const $=i.useMemo(()=>Q(x),[x]),o=i.useCallback(()=>{var p;f("create"),d(null),c(null),r((p=n[0])!=null&&p.id?String(n[0].id):""),s(""),E(null),R(""),m(!0)},[n]),t=i.useCallback(()=>{var p;v.current+=1,(p=T.current)==null||p.abort(),N(!1),m(!1)},[]),g=i.useCallback(async()=>{var w;if(!j||y)return;const p=++v.current;(w=T.current)==null||w.abort();const B=new AbortController;T.current=B,N(!0),c(null);try{const I=await je(j,{signal:B.signal});if(!F(p,v.current,"",""))return;c(I),I.created>0&&await a()}catch(I){if(!F(p,v.current,"",""))return;c({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(p,v.current,"","")&&N(!1)}},[y,j,a]),k=i.useCallback(async()=>{var I;if(!we(b,x,y))return;const p=b,B=++v.current;P.current=p,(I=T.current)==null||I.abort();const w=new AbortController;T.current=w,N(!0),E(null),R("");try{const O=await Ne(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:O.added}),s(""),await a()}catch(O){if(!F(B,v.current,p,b))return;R((O==null?void 0:O.message)||"追加失败")}finally{F(B,v.current,p,b)&&N(!1)}},[x,b,y,a]),S=i.useCallback(async()=>{await g()},[g]),C=i.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:m,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:h,appendError:M,appendPreview:$,openBatchModal:o,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:""}),L=(l,n)=>l instanceof Error?l.message:n,ke=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>ve(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(L(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await fe(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(L(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(o.text_content=c.content.trim()),c.type==="data"&&(o.data_content=c.content.trim()),c.type==="image"&&(o.image_url=c.content.trim()),c.type==="api"&&(o.api_config={url:c.content.trim(),method:c.api_method,timeout:c.api_timeout,headers:c.api_headers.trim()||void 0,params:c.api_params.trim()||void 0}),await ye(o),_(!1),y(q()),await n()}catch(o){console.error("添加卡密失败:",o),alert(L(o,"添加失败,请重试"))}},[c,n]),T=i.useCallback(async o=>{try{await J(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),P=i.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),$=i.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 +VIP-MONTH-002 +VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(p=>p.map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")).join(` +`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:s,filteredCards:h,typeFilter:N,setTypeFilter:b,nameSearch:r,setNameSearch:x,showEditModal:a,setShowEditModal:u,showAddModal:m,setShowAddModal:_,selectedCard:f,editForm:d,setEditForm:A,addForm:c,setAddForm:y,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}},Ie=()=>{const{cards:l,loadCards:n}=Ce(),a=ke({cards:l,loadCards:n}),{dataCards:u,filteredCards:m,typeFilter:_,setTypeFilter:f,nameSearch:j,setNameSearch:d,showEditModal:A,setShowEditModal:c,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:r,setEditForm:x,addForm:s,setAddForm:h,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}=a,o=_e({dataCards:u,loadCards:n});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.jsxs("button",{onClick:o.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(D,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>N(!0)),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(V,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ae,{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:_,onChange:(t=>f(t.target.value)),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:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(se,{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:"搜索卡密名称...",value:j,onChange:(t=>d(t.target.value)),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:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",m.length," / ",l.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed 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:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:m.map(t=>{let g="";return t.type==="data"&&t.data_content?g=`库存: ${t.data_content.split(` +`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?g=t.text_content:t.type==="api"&&t.api_config?g=t.api_config.url:t.type==="image"&&t.image_url&&(g="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ue,{type:t.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:t.name,children:t.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>P(t.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:t.id}),e.jsx(le,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${t.type==="text"?"bg-blue-50 text-blue-600":t.type==="data"?"bg-purple-50 text-purple-600":t.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:t.type==="text"?"文本":t.type==="data"?"批量":t.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:g,children:g})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:t.description||"-",children:t.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>T(t)),"aria-label":`切换卡密 ${t.name} 状态`,className:`w-12 h-8 rounded-full relative transition-colors ${t.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${t.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>E(t)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(ne,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>R(t.id)),"aria-label":`删除卡密 ${t.name}`,className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(re,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),m.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(oe,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:l.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),A&&b&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:r.name||"",onChange:(t=>x({...r,name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:r.type||"text",onChange:(t=>x({...r,type:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(b==null?void 0:b.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),r.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:r.api_url||"",onChange:(t=>x({...r,api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),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.jsxs("select",{value:r.api_method||"GET",onChange:(t=>x({...r,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),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:r.api_timeout||10,onChange:(t=>x({...r,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:r.api_headers||"",onChange:(t=>x({...r,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:r.api_params||"",onChange:(t=>x({...r,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),r.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:r.text_content||"",onChange:(t=>x({...r,text_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),r.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:r.data_content||"",onChange:(t=>x({...r,data_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: +卡号1:密码1 +卡号2:密码2 +或者 +兑换码1 +兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:r.data_content?r.data_content.split(` +`).filter(t=>t.trim()).length:0})," 条"]})]})]}),r.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:r.image_url||"",onChange:(t=>x({...r,image_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),r.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:r.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(t=>{t.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:r.delay_seconds||0,onChange:(t=>x({...r,delay_seconds:parseInt(t.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:r.description||"",onChange:(t=>x({...r,description:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>x({...r,enabled:!r.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${r.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 ${r.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!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:M,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ie,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",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:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>N(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:s.name,onChange:(t=>h({...s,name:t.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(H,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(X,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(W,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:s.type==="data"?"库存内容(一行一个)":s.type==="text"?"固定回复内容":s.type==="image"?"图片 URL":"API 地址"}),s.type==="api"?e.jsx("input",{type:"url",value:s.content,onChange:(t=>h({...s,content:t.target.value})),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):s.type==="image"?e.jsx("input",{type:"url",value:s.content,onChange:(t=>h({...s,content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:s.content,onChange:(t=>h({...s,content:t.target.value})),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${s.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:s.type==="data"?`CODE-123456 +CODE-789012 +...`:"请输入每次发货时发送的固定文字"}),s.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:s.content.split(` +`).filter(t=>t.trim()).length})," 条"]})]}),s.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 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-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:s.api_method,onChange:(t=>h({...s,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:s.api_timeout,onChange:(t=>h({...s,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),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:"请求头(JSON)"}),e.jsx("textarea",{value:s.api_headers,onChange:(t=>h({...s,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:s.api_params,onChange:(t=>h({...s,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] 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",{value:s.description,onChange:(t=>h({...s,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:s.delay_seconds,onChange:(t=>h({...s,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!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:v,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(V,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(he,{dataCards:u,downloadCardTemplate:$,...o})]})};export{Ie as default}; diff --git a/internal/webui/static/assets/CardList-D5uSws-z.js b/internal/webui/static/assets/CardList-D5uSws-z.js deleted file mode 100644 index 5cc8e42..0000000 --- a/internal/webui/static/assets/CardList-D5uSws-z.js +++ /dev/null @@ -1,17 +0,0 @@ -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 -VIP-MONTH-002 -VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(h=>h.map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")).join(` -`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:a,filteredCards:m,typeFilter:N,setTypeFilter:b,nameSearch:l,setNameSearch:x,showEditModal:s,setShowEditModal:u,showAddModal:p,setShowAddModal:_,selectedCard:j,editForm:i,setEditForm:A,addForm:o,setAddForm:y,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:w,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:L}},ve=()=>{const{cards:c,loadCards:d}=be(),s=ye({cards:c,loadCards:d}),{dataCards:u,filteredCards:p,typeFilter:_,setTypeFilter:j,nameSearch:f,setNameSearch:i,showEditModal:A,setShowEditModal:o,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:l,setEditForm:x,addForm:a,setAddForm:m,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:w,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:L}=s,n=ge({dataCards:u,loadCards:d});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.jsxs("button",{onClick:n.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx($,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>N(!0)),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(V,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ee,{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:_,onChange:(t=>j(t.target.value)),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:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(te,{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:"搜索卡密名称...",value:f,onChange:(t=>i(t.target.value)),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:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",p.length," / ",c.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed 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:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:p.map(t=>{let g="";return t.type==="data"&&t.data_content?g=`库存: ${t.data_content.split(` -`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?g=t.text_content:t.type==="api"&&t.api_config?g=t.api_config.url:t.type==="image"&&t.image_url&&(g="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(me,{type:t.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:t.name,children:t.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>P(t.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:t.id}),e.jsx(ae,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${t.type==="text"?"bg-blue-50 text-blue-600":t.type==="data"?"bg-purple-50 text-purple-600":t.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:t.type==="text"?"文本":t.type==="data"?"批量":t.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:g,children:g})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:t.description||"-",children:t.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>T(t)),"aria-label":`切换卡密 ${t.name} 状态`,className:`w-12 h-8 rounded-full relative transition-colors ${t.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${t.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>E(t)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(se,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>R(t.id)),"aria-label":`删除卡密 ${t.name}`,className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(le,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),p.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ne,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:c.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),A&&b&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>o(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:l.name||"",onChange:(t=>x({...l,name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:l.type||"text",onChange:(t=>x({...l,type:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(b==null?void 0:b.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),l.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:l.api_url||"",onChange:(t=>x({...l,api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),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.jsxs("select",{value:l.api_method||"GET",onChange:(t=>x({...l,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),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:l.api_timeout||10,onChange:(t=>x({...l,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:l.api_headers||"",onChange:(t=>x({...l,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:l.api_params||"",onChange:(t=>x({...l,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),l.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:l.text_content||"",onChange:(t=>x({...l,text_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),l.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:l.data_content||"",onChange:(t=>x({...l,data_content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: -卡号1:密码1 -卡号2:密码2 -或者 -兑换码1 -兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:l.data_content?l.data_content.split(` -`).filter(t=>t.trim()).length:0})," 条"]})]})]}),l.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:l.image_url||"",onChange:(t=>x({...l,image_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),l.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:l.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(t=>{t.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:l.delay_seconds||0,onChange:(t=>x({...l,delay_seconds:parseInt(t.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:l.description||"",onChange:(t=>x({...l,description:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>x({...l,enabled:!l.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${l.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 ${l.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>o(!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:M,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(re,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",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:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>N(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:a.name,onChange:(t=>m({...a,name:t.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>m({...a,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${a.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(H,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>m({...a,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${a.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(K,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>m({...a,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${a.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(W,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:a.type==="data"?"库存内容(一行一个)":a.type==="text"?"固定回复内容":a.type==="image"?"图片 URL":"API 地址"}),a.type==="api"?e.jsx("input",{type:"url",value:a.content,onChange:(t=>m({...a,content:t.target.value})),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):a.type==="image"?e.jsx("input",{type:"url",value:a.content,onChange:(t=>m({...a,content:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:a.content,onChange:(t=>m({...a,content:t.target.value})),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${a.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:a.type==="data"?`CODE-123456 -CODE-789012 -...`:"请输入每次发货时发送的固定文字"}),a.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:a.content.split(` -`).filter(t=>t.trim()).length})," 条"]})]}),a.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 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-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:a.api_method,onChange:(t=>m({...a,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:a.api_timeout,onChange:(t=>m({...a,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),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:"请求头(JSON)"}),e.jsx("textarea",{value:a.api_headers,onChange:(t=>m({...a,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:a.api_params,onChange:(t=>m({...a,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] 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",{value:a.description,onChange:(t=>m({...a,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:a.delay_seconds,onChange:(t=>m({...a,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!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:w,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(V,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(pe,{dataCards:u,downloadCardTemplate:L,...n})]})};export{ve as default}; diff --git a/internal/webui/static/assets/Chat-BLyP9Pyt.js b/internal/webui/static/assets/Chat-BLyP9Pyt.js deleted file mode 100644 index 059b0b9..0000000 --- a/internal/webui/static/assets/Chat-BLyP9Pyt.js +++ /dev/null @@ -1 +0,0 @@ -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/Chat-By_xPFNH.js b/internal/webui/static/assets/Chat-By_xPFNH.js new file mode 100644 index 0000000..724b3a6 --- /dev/null +++ b/internal/webui/static/assets/Chat-By_xPFNH.js @@ -0,0 +1 @@ +import{j as e,c as $0,r as i}from"./react-vendor-C_od1ZSF.js";import{g as b0,a as F0,b as ee}from"./index-CFzx5gQT.js";import{o as J0}from"./contract-COFcZjyb.js";import{L as r0,ak as te,al as se,M as L0,I as ae,R as ie,ad as I0,k as ne,am as re,s as ce,an as le,ao as oe,ah as pe}from"./icons-vendor-CvzvbbIV.js";const B0=[["尊嘟假嘟","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"]],me=l=>l,ge=new Map(B0.map(([l,m])=>[l,m])),de=l=>l.split(/(\[[^\]]+\])/g).map((m,s)=>{const n=m.startsWith("[")?ge.get(m.slice(1,-1)):void 0;return n?e.jsx("img",{src:n,alt:m,title:m,className:"mx-0.5 inline-block h-7 w-7 align-middle"},s):e.jsx($0.Fragment,{children:m},s)}),xe=async l=>b0("/api/v1/accounts/details",void 0,l),U0=async l=>b0("/api/v1/accounts/runtime-status",void 0,l),M0=async(l,m,s,n=!1)=>{const d=await b0("/api/v1/chat/sessions",{account_id:l,cursor:m,refresh:n?1:void 0},n?{timeoutMs:6e4,...s}:s),j=J0(d,["data","result"])||{};return{sessions:j.sessions||[],has_more:j.has_more===!0,next_cursor:j.next_cursor}},A0=async(l,m,s,n,d)=>{const j=await b0("/api/v1/chat/messages",{account_id:l,chat_id:m,cursor:s,before_id:n},d),_=J0(j,["data","result"])||{};return{messages:_.messages||[],has_more:_.has_more===!0,next_cursor:_.next_cursor,session:_.session}},_e=async(l,m)=>F0("/api/v1/chat/messages",l,m),ue=async(l,m)=>{const s=new FormData;return Object.entries(l).forEach(([n,d])=>s.append(n,d)),ee("/api/v1/chat/images",s,{timeoutMs:12e4,...m})},H0=async(l,m,s)=>F0("/api/v1/chat/read",{account_id:l,chat_id:m},s),he=(l,m,s)=>{const n=m.trim().toLowerCase();return l.filter(d=>s&&d.unread_count<=0?!1:n?[d.buyer_name,d.buyer_id,d.item_title,d.last_message].some(j=>(j||"").toLowerCase().includes(n)):!0)},be=(l,m)=>{const s=new Set(l.map(n=>n.message_key));return[...m.filter(n=>!s.has(n.message_key)),...l]},q0=(l,m)=>{const s=l.findIndex(n=>n.message_key===m.message_key);return s<0?[...l,m]:l.map((n,d)=>d===s?m:n)},N=(l,m,s)=>l===m&&!s.aborted,Z=l=>l instanceof Error&&l.message==="请求已取消",fe=l=>{if(!l)return"";const m=new Date(l<1e10?l*1e3:l),s=new Date;return m.toDateString()===s.toDateString()?m.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}):m.toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})},je=l=>new Date(l<1e10?l*1e3:l).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),we=()=>{const[l,m]=i.useState([]),[s,n]=i.useState(""),[d,j]=i.useState({}),[_,z]=i.useState(""),[D,S]=i.useState([]),[V,f0]=i.useState(""),[M,j0]=i.useState(!1),[q,c0]=i.useState(""),[w0,T]=i.useState(!0),[A,I]=i.useState(!1),[W,G]=i.useState(!1),[X,l0]=i.useState(!1),[o0,p0]=i.useState(),[Y,H]=i.useState({}),[K,$]=i.useState({}),[e0,m0]=i.useState(!1),[g0,N0]=i.useState(!1),[y,F]=i.useState(!1),[C0,C]=i.useState(""),[y0,J]=i.useState("connecting"),[B,t0]=i.useState(null),[a,f]=i.useState(null),v=i.useRef(""),s0=i.useRef(""),d0=i.useRef(null),O0=i.useRef({accountID:"",chatID:""}),v0=i.useRef(!0),Q=i.useRef(!1),k0=i.useRef(null),T0=i.useRef(new Set),S0=i.useRef(0),R0=i.useRef(null),L=i.useRef(0),E0=i.useRef(null),U=i.useRef(0),a0=i.useRef(null),i0=i.useRef(0),x0=i.useRef(null),R=i.useRef(0),P=i.useRef(null);i.useEffect(()=>{v.current=s},[s]),i.useEffect(()=>{s0.current=_},[_]);const n0=i.useCallback(async t=>{var c;const o=++S0.current;(c=R0.current)==null||c.abort();const p=new AbortController;R0.current=p;try{const r=await M0(t,void 0,{signal:p.signal},!0);return N(S0.current,o,p.signal)?(j(g=>({...g,[t]:r.sessions})),H(g=>({...g,[t]:r.next_cursor})),$(g=>({...g,[t]:r.has_more})),r.sessions):[]}catch(r){return N(S0.current,o,p.signal)&&!Z(r)&&C(r instanceof Error?r.message:"同步会话失败"),[]}},[]);i.useEffect(()=>{const t=new AbortController;return(async()=>{var p;T(!0);try{const[c,r]=await Promise.all([xe({signal:t.signal}),U0({signal:t.signal})]),x=c.map(u=>{var O,D0;return{...u,runtime_state:((O=r[u.id])==null?void 0:O.state)||(u.enabled?"connecting":"disabled"),runtime_connected:((D0=r[u.id])==null?void 0:D0.connected)===!0}}).filter(u=>u.enabled),w=await Promise.all(x.map(async u=>[u.id,await M0(u.id,void 0,{signal:t.signal})]));if(t.signal.aborted)return;m(x),j(Object.fromEntries(w.map(([u,O])=>[u,O.sessions]))),H(Object.fromEntries(w.map(([u,O])=>[u,O.next_cursor]))),$(Object.fromEntries(w.map(([u,O])=>[u,O.has_more])));const h=window.localStorage.getItem("ydisks.chat.account.v1")||"",k=x.some(u=>u.id===h)?h:((p=x[0])==null?void 0:p.id)||"";n(k)}catch(c){t.signal.aborted||C(c instanceof Error?c.message:"加载聊天数据失败")}finally{t.signal.aborted||T(!1)}})(),(()=>t.abort())},[]),i.useEffect(()=>{let t=!1,o=0,p=null;const c=async()=>{p=new AbortController;try{const r=await U0({signal:p.signal,timeoutMs:1e4});t||m(g=>g.map(x=>{var w,h;return{...x,runtime_state:((w=r[x.id])==null?void 0:w.state)||x.runtime_state,runtime_connected:((h=r[x.id])==null?void 0:h.connected)??x.runtime_connected}}))}catch{}finally{t||(o=window.setTimeout(c,3e3))}};return o=window.setTimeout(c,3e3),(()=>{t=!0,window.clearTimeout(o),p==null||p.abort()})},[]),i.useEffect(()=>{if(!s)return;window.localStorage.setItem("ydisks.chat.account.v1",s);const t=d[s]||[];z(o=>{var p;return t.some(c=>c.chat_id===o)?o:((p=t[0])==null?void 0:p.chat_id)||""})},[s,d]),i.useEffect(()=>{!s||T0.current.has(s)||(T0.current.add(s),n0(s))},[s,n0]),i.useEffect(()=>{var p,c;if(!s||!_){L.current+=1,U.current+=1,(p=a0.current)==null||p.abort(),Q.current=!1,S([]);return}const t=++L.current;(c=E0.current)==null||c.abort();const o=new AbortController;return E0.current=o,I(!0),Promise.all([A0(s,_,void 0,void 0,{signal:o.signal}),H0(s,_,{signal:o.signal})]).then(([r])=>{N(L.current,t,o.signal)&&(S(r.messages),l0(r.has_more),p0(r.next_cursor),r.session&&j(g=>({...g,[s]:(g[s]||[]).map(x=>{var w;return x.chat_id===((w=r.session)==null?void 0:w.chat_id)?r.session:x})})),j(g=>({...g,[s]:(g[s]||[]).map(x=>x.chat_id===_?{...x,unread_count:0}:x)})))}).catch(r=>{N(L.current,t,o.signal)&&!Z(r)&&C(r instanceof Error?r.message:"加载消息失败")}).finally(()=>{N(L.current,t,o.signal)&&I(!1)}),(()=>o.abort())},[s,_]),i.useEffect(()=>{var t;(t=x0.current)==null||t.abort(),i0.current+=1},[s]),i.useEffect(()=>{var t;(t=P.current)==null||t.abort(),R.current+=1},[s,_]),i.useEffect(()=>{var t;U.current+=1,(t=a0.current)==null||t.abort(),Q.current=!1},[s,_]),i.useEffect(()=>(()=>{var t,o,p,c,r;(t=R0.current)==null||t.abort(),(o=E0.current)==null||o.abort(),U.current+=1,(p=a0.current)==null||p.abort(),(c=x0.current)==null||c.abort(),(r=P.current)==null||r.abort()}),[]);const Q0=i.useCallback(async()=>{var g,x;if(!s||!_||W||!X)return;const t=d0.current,o=(t==null?void 0:t.scrollHeight)||0,p=L.current,c=++U.current;(g=a0.current)==null||g.abort();const r=new AbortController;a0.current=r,Q.current=!0,G(!0),C("");try{const w=(x=D[0])==null?void 0:x.id,h=await A0(s,_,o0,w,{signal:r.signal});if(!N(L.current,p,r.signal)||c!==U.current)return;S(k=>be(k,h.messages)),l0(h.has_more),p0(h.next_cursor),requestAnimationFrame(()=>{c===U.current&&!r.signal.aborted&&t&&(t.scrollTop+=t.scrollHeight-o)})}catch(w){Q.current=!1,Z(w)||C(w instanceof Error?w.message:"加载历史消息失败")}finally{c===U.current&&G(!1)}},[s,_,X,o0,D,W]);i.useEffect(()=>{let t=!1,o=0,p=0,c=null;const r=()=>{if(t)return;J("connecting");const g=window.location.protocol==="https:"?"wss:":"ws:";c=new WebSocket(`${g}//${window.location.host}/api/v1/chat/ws`),c.onopen=()=>{p=0,J("online")},c.onmessage=x=>{try{const h=JSON.parse(x.data).message;if(!h)return;const k=h.account_id;j(u=>{const O=u[k]||[];return O.some(E=>E.chat_id===h.chat_id)?{...u,[k]:O.map(E=>E.chat_id===h.chat_id?{...E,last_message:h.content,last_message_at:h.sent_at,unread_count:h.direction==="incoming"&&(v.current!==k||s0.current!==h.chat_id)?E.unread_count+1:E.unread_count}:E).sort((E,K0)=>K0.last_message_at-E.last_message_at)}:(n0(k),u)}),v.current===k&&s0.current===h.chat_id&&(S(u=>q0(u,h)),h.direction==="incoming"&&H0(k,h.chat_id))}catch{}},c.onclose=()=>{if(t)return;J("offline");const x=Math.min(15e3,1e3*2**Math.min(p++,4));o=window.setTimeout(r,x)},c.onerror=()=>c==null?void 0:c.close()};return r(),(()=>{t=!0,window.clearTimeout(o),c==null||c.close()})},[n0]);const P0=i.useCallback(()=>{const t=d0.current;if(!t)return;const o=t.scrollHeight-t.scrollTop-t.clientHeight;v0.current=o<=48},[]);i.useLayoutEffect(()=>{const t=O0.current.accountID!==s||O0.current.chatID!==_;O0.current={accountID:s,chatID:_},t&&(v0.current=!0);const o=d0.current;if(o){if(Q.current){Q.current=!1;return}(A||v0.current)&&(o.scrollTop=o.scrollHeight)}},[s,_,D,A]);const Z0=l.find(t=>t.id===s),_0=d[s]||[],b=_0.find(t=>t.chat_id===_),z0=i.useMemo(()=>he(_0,V,M),[_0,V,M]),V0=i.useCallback(t=>(d[t]||[]).reduce((o,p)=>o+p.unread_count,0),[d]),W0=i.useCallback(async()=>{var c;if(!s||e0||!K[s])return;const t=++i0.current;(c=x0.current)==null||c.abort();const o=new AbortController;x0.current=o;const p=s;m0(!0),C("");try{const r=await M0(p,Y[p],{signal:o.signal},!0);if(!N(i0.current,t,o.signal))return;j(g=>({...g,[p]:r.sessions})),H(g=>({...g,[p]:r.next_cursor})),$(g=>({...g,[p]:r.has_more}))}catch(r){N(i0.current,t,o.signal)&&!Z(r)&&C(r instanceof Error?r.message:"加载历史联系人失败")}finally{N(i0.current,t,o.signal)&&m0(!1)}},[s,Y,e0,K]),u0=i.useCallback(async(t,o)=>{var r;if(!b||!s||y)return;const p=++R.current;(r=P.current)==null||r.abort();const c=new AbortController;P.current=c,F(!0),C("");try{const g=await _e({account_id:s,chat_id:b.chat_id,buyer_id:b.buyer_id,buyer_name:b.buyer_name,item_id:b.item_id,item_title:b.item_title,text:t},{signal:c.signal});if(!N(R.current,p,c.signal))return;c0(""),t0(null),S(x=>q0(x,g.message))}catch(g){N(R.current,p,c.signal)&&(o&&t0(t),Z(g)||C(g instanceof Error?g.message:"消息发送失败"))}finally{N(R.current,p,c.signal)&&F(!1)}},[s,b,y]),h0=i.useCallback(async(t,o)=>{var r;if(!b||!s||y)return;const p=++R.current;(r=P.current)==null||r.abort();const c=new AbortController;P.current=c,F(!0),C("");try{const g=await ue({account_id:s,chat_id:b.chat_id,buyer_id:b.buyer_id,buyer_name:b.buyer_name,buyer_avatar_url:b.buyer_avatar_url,item_id:b.item_id,item_title:b.item_title,image:t},{signal:c.signal});if(!N(R.current,p,c.signal))return;f(null),S(x=>q0(x,g.message))}catch(g){N(R.current,p,c.signal)&&(o&&f(t),Z(g)||C(g instanceof Error?g.message:"图片发送失败"))}finally{N(R.current,p,c.signal)&&(F(!1),k0.current&&(k0.current.value=""))}},[s,b,y]),G0=i.useCallback(async()=>{const t=q.trim();!t||!b||!s||y||await u0(t,!0)},[s,q,b,u0,y]),X0=i.useCallback(async t=>{!t||!b||!s||y||await h0(t,!0)},[s,b,h0,y]),Y0=i.useCallback(async()=>{B?await u0(B,!1):a&&await h0(a,!1)},[a,B,h0,u0]);return{accounts:l,activeAccountID:s,activeSessions:_0,selectedSession:b,activeAccount:Z0,messages:D,search:V,unreadOnly:M,draft:q,loading:w0,messagesLoading:A,olderLoading:W,hasOlder:X,contactsLoading:e0,hasMoreContacts:K[s]===!0,emojiOpen:g0,sending:y,error:C0,liveState:y0,activeChatID:_,filteredSessions:z0,scrollRef:d0,imageInputRef:k0,setActiveAccountID:n,setActiveChatID:z,setSearch:f0,setUnreadOnly:j0,setDraft:c0,setEmojiOpen:N0,reloadSessions:n0,loadMoreContacts:W0,loadOlderMessages:Q0,handleMessageScroll:P0,handleSend:G0,handleImage:X0,retrySend:Y0,retryAvailable:!!(B||a),unreadForAccount:V0,emojiURL:me,xianyuEmojis:B0,renderXianyuText:de,formatClock:fe,messageTime:je}},ve=()=>{const{accounts:l,activeAccountID:m,activeChatID:s,activeAccount:n,selectedSession:d,filteredSessions:j,messages:_,search:z,unreadOnly:D,draft:S,loading:V,messagesLoading:f0,olderLoading:M,hasOlder:j0,contactsLoading:q,hasMoreContacts:c0,emojiOpen:w0,sending:T,error:A,liveState:I,scrollRef:W,imageInputRef:G,setActiveAccountID:X,setActiveChatID:l0,setSearch:o0,setUnreadOnly:p0,setDraft:Y,setEmojiOpen:H,reloadSessions:K,loadMoreContacts:$,loadOlderMessages:e0,handleMessageScroll:m0,handleSend:g0,handleImage:N0,retrySend:y,retryAvailable:F,unreadForAccount:C0,emojiURL:C,xianyuEmojis:y0,renderXianyuText:J,formatClock:B,messageTime:t0}=we();return V?e.jsx("div",{className:"flex h-[calc(100vh-4rem)] items-center justify-center",children:e.jsx(r0,{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 ${I==="online"?"bg-emerald-50 text-emerald-700":I==="connecting"?"bg-amber-50 text-amber-700":"bg-red-50 text-red-700"}`,children:[I==="online"?e.jsx(te,{className:"h-3.5 w-3.5"}):e.jsx(se,{className:"h-3.5 w-3.5"}),I==="online"?"实时同步中":I==="connecting"?"正在连接":"连接已断开"]})]}),e.jsx("div",{className:"flex gap-1 overflow-x-auto pb-0",role:"tablist","aria-label":"聊天账号",children:l.map(a=>{const f=a.id===m,v=C0(a.id),s0=a.runtime_state==="online";return e.jsxs("button",{type:"button",role:"tab","aria-selected":f,onClick:(()=>X(a.id)),className:`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${f?"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 ${s0?"bg-emerald-500":"bg-slate-300"}`}),e.jsx("span",{className:"max-w-36 truncate",children:a.nickname||a.remark||a.id}),v>0&&e.jsx("span",{className:"min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white",children:v>99?"99+":v})]},a.id)})})]}),l.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(ae,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:z,onChange:(a=>o0(a.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:(()=>p0(a=>!a)),className:`rounded-lg px-2.5 py-1.5 text-xs font-bold ${D?"bg-sky-100 text-sky-700":"text-slate-500 hover:bg-slate-100"}`,children:D?"只看未读":"全部会话"}),e.jsx("button",{type:"button",title:"刷新会话",onClick:(()=>void K(m)),className:"rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(ie,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[j.map(a=>e.jsxs("button",{type:"button",onClick:(()=>l0(a.chat_id)),className:`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${a.chat_id===s?"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:a.buyer_avatar_url?e.jsx("img",{src:a.buyer_avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx(I0,{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:a.buyer_name||`用户 ${a.buyer_id}`}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-slate-400",children:B(a.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:a.last_message||"暂无消息"}),a.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:a.unread_count})]}),a.item_title&&e.jsxs("div",{className:"mt-1.5 truncate text-[10px] font-medium text-sky-700",children:["商品 · ",a.item_title]})]})]},a.chat_id)),j.length===0&&e.jsx("div",{className:"px-6 py-16 text-center text-sm text-slate-400",children:"当前账号暂无匹配会话"}),c0&&!z&&!D&&e.jsx("div",{className:"flex justify-center p-4",children:e.jsxs("button",{type:"button",onClick:(()=>void $()),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(r0,{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:d?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:d.buyer_name||d.buyer_id}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-slate-500",children:["用户 ID:",d.buyer_id]})]}),e.jsx("span",{className:`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${(n==null?void 0:n.runtime_state)==="online"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:(n==null?void 0:n.runtime_state)==="online"?"账号在线":"账号离线"})]}),e.jsx("div",{ref:W,onScroll:m0,className:"min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5",children:f0?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(r0,{className:"h-6 w-6 animate-spin text-sky-500"})}):e.jsxs(e.Fragment,{children:[j0&&e.jsx("div",{className:"flex justify-center pb-1",children:e.jsxs("button",{type:"button",onClick:(()=>void e0()),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(r0,{className:"h-3.5 w-3.5 animate-spin"}),M?"正在加载":"加载更早消息"]})}),_.map(a=>{const f=a.direction==="outgoing";return a.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:[J(a.content),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400",children:t0(a.sent_at)})]})},a.message_key):e.jsxs("div",{className:`flex items-end gap-2.5 ${f?"justify-end":"justify-start"}`,children:[!f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white",children:d.buyer_avatar_url?e.jsx("img",{src:d.buyer_avatar_url,alt:d.buyer_name||"用户",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"m-2 h-5 w-5 text-slate-500"})}),e.jsxs("div",{className:`max-w-[72%] ${f?"items-end":"items-start"} flex flex-col`,children:[e.jsx("div",{className:"mb-1 px-1 text-[10px] font-semibold text-slate-400",children:f?(n==null?void 0:n.nickname)||(n==null?void 0:n.remark)||"我":d.buyer_name||a.sender_name||d.buyer_id}),a.message_type==="image"?e.jsx("a",{href:a.content,target:"_blank",rel:"noreferrer",className:`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${f?"rounded-br-md border-sky-200":"rounded-bl-md border-slate-200"}`,children:e.jsx("img",{src:a.content,alt:"聊天图片",className:"max-h-80 max-w-full rounded-xl object-contain"})}):a.message_type==="video"?e.jsx("video",{src:a.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 ${f?"rounded-br-md bg-sky-500 text-white":"rounded-bl-md border border-slate-200 bg-white text-slate-800"}`,children:J(a.content)}),e.jsxs("div",{className:"mt-1 flex items-center gap-1 text-[10px] text-slate-400",children:[t0(a.sent_at),f&&(a.status==="failed"?e.jsx(ne,{className:"h-3 w-3 text-red-500"}):a.status==="sent"?e.jsx(re,{className:"h-3 w-3 text-sky-500"}):e.jsx(ce,{className:"h-3 w-3"}))]})]}),f&&e.jsx("div",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white",children:n!=null&&n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"我",className:"h-full w-full object-cover"}):e.jsx(I0,{className:"m-2 h-5 w-5 text-sky-600"})})]},a.message_key)})]})}),A&&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:A}),F&&e.jsx("button",{type:"button",className:"font-bold underline",onClick:(()=>void y()),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:(()=>H(a=>!a)),disabled:T||(n==null?void 0:n.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(le,{className:"h-5 w-5"})}),w0&&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:y0.map(([a,f])=>e.jsx("button",{type:"button",title:`[${a}]`,onClick:(()=>{Y(v=>v+`[${a}]`),H(!1)}),className:"flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100",children:e.jsx("img",{src:C(f),alt:`[${a}]`,className:"h-8 w-8 object-contain"})},a))})]})]}),e.jsx("input",{ref:G,type:"file",accept:"image/*",className:"hidden",onChange:(a=>{var f;return void N0((f=a.target.files)==null?void 0:f[0])})}),e.jsx("button",{type:"button",onClick:(()=>{var a;return(a=G.current)==null?void 0:a.click()}),disabled:T||(n==null?void 0:n.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(oe,{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:S,onChange:(a=>Y(a.target.value)),rows:2,maxLength:2e3,onKeyDown:(a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),g0())}),disabled:(n==null?void 0:n.runtime_state)!=="online",placeholder:(n==null?void 0:n.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 g0()),disabled:!S.trim()||T||(n==null?void 0:n.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(r0,{className:"h-4 w-4 animate-spin"}):e.jsx(pe,{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{ve as default}; diff --git a/internal/webui/static/assets/Dashboard-RK26q9J7.js b/internal/webui/static/assets/Dashboard-RK26q9J7.js new file mode 100644 index 0000000..699812e --- /dev/null +++ b/internal/webui/static/assets/Dashboard-RK26q9J7.js @@ -0,0 +1 @@ +import{r as c,j as e}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{g as q}from"./index-CFzx5gQT.js";import{c as de,o as ge}from"./contract-COFcZjyb.js";import{j as xe,k as he,l as te,D as pe,c as be,P as fe,m as se,E as ye,T as je}from"./icons-vendor-CvzvbbIV.js";import{R as E,B as ve,X as ae,Y as re,T as F,a as Ne,C as U,A as we,b as _e,c as ke,P as ne,d as le,L as De}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},Ce=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},$e=t=>{var a;return((a=t.daily_stats)==null?void 0:a.map(s=>({name:s.date.slice(5),amount:s.amount,orders:s.order_count,avgAmount:s.order_count>0?(s.amount/s.order_count).toFixed(2):0})))||[]},Re=(t,a)=>(t.item_stats||[]).map(s=>{const l=a[s.item_id]||s.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:s.order_count}}).sort((s,l)=>l.sales-s.sales).slice(0,10),Le=(t,a,s)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,6).map((n,o)=>({...n,color:s[o%s.length]}))},Ae=(t,a,s)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,5).map((n,o)=>({...n,color:s[o%s.length],percentage:n.percentage.toFixed(1)}))},Oe=(t,a)=>{if(!t||!a)return null;const s=t.revenue_stats.total_amount,l=a.revenue_stats.total_amount;if(l===0)return s>0?"+100%":"0%";const n=(s-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},Te=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",ze=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Pe=async t=>q("/api/v1/analytics/dashboard",void 0,t),We=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return de(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Ee=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=ge(s,["data","result"])||{},o=de(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.status||b.order_status),order_status:oe(b.order_status),quantity:Number(b.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Fe=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,b]=c.useState(null),[_,I]=c.useState(null),[K,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,T]=c.useState(0),R=c.useRef(0),S=c.useRef(0),L=c.useMemo(()=>({range:a,customStartDate:s,customEndDate:l}),[l,s,a]),D=c.useCallback(()=>T(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([Pe({signal:h.signal}),We(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Ce(g)}),v(p=>({...p,overview:"success"})))}).catch(m=>{!P(S.current,u,h.signal)||ce(m)||v(g=>({...g,overview:"error",error:G(m,"概览加载失败")}))}),(()=>h.abort())},[d]),c.useEffect(()=>{let u;try{u=ue(a,new Date,s,l)}catch(p){v(w=>({...w,range:"error",error:G(p,"日期范围无效")}));return}const h=Se(u),m=++R.current,g=new AbortController;return v(p=>({...p,range:"loading",error:""})),Promise.all([ie({start_date:u.startDate,end_date:u.endDate},{signal:g.signal}),ie({start_date:h.startDate,end_date:h.endDate},{signal:g.signal}),Ee({start_date:u.startDate,end_date:u.endDate},{signal:g.signal})]).then(([p,w,Y])=>{P(R.current,m,g.signal)&&(I({analytics:p,previousAnalytics:w,validOrders:Y,dateRange:u}),v($=>({...$,range:"success"})))}).catch(p=>{!P(R.current,m,g.signal)||ce(p)||v(w=>({...w,range:"error",error:G(p,"经营数据加载失败")}))}),(()=>g.abort())},[n,a,d]);const C=c.useMemo(()=>o&&_?{...o,..._}:null,[o,_]),k=(o==null?void 0:o.itemNames)||{},x=(_==null?void 0:_.analytics)||null,z=c.useMemo(()=>x?$e(x):[],[x]),N=c.useMemo(()=>x?Re(x,k):[],[x,k]),f=c.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))"],[]),A=c.useMemo(()=>x?Le(x,k,f):[],[x,f,k]),B=c.useMemo(()=>x?Ae(x,k,f):[],[x,f,k]),V=c.useMemo(()=>ze(N),[N]);return{data:C,status:K,chartData:z,productSalesData:N,sourceData:A,categoryData:B,maxProductSales:V,trendPercent:Oe(x,(C==null?void 0:C.previousAnalytics)||null),selectedRangeLabel:Te(L),refresh:D}},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Me=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>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:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(xe,{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:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ve,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{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:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(Ne,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(we,{data:t,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(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_e,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{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(ke,{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=(t,a)=>`rgb(var(--color-${t}))`,qe=({status:t})=>{const a={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"},s={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 ${a[t]||a.cancelled}`,children:s[t]||t})},W=({title:t,value:a,icon:s,colorClass:l,trend:n})=>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 ${l} 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 ${l} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(s,{className:`w-6 h-6 ${l.replace("bg-","text-")}`})}),n&&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(je,{className:"w-3 h-3"})," ",n]})]}),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:a}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:t})]})]}),Xe=()=>{const[t,a]=c.useState("7days"),[s,l]=c.useState(""),[n,o]=c.useState(""),[b,_]=c.useState(""),[I,K]=c.useState(0),v=Fe({range:t,customStartDate:s,customEndDate:n,customRangeVersion:I}),{data:d,status:T,chartData:R,productSalesData:S,sourceData:L,categoryData:D,maxProductSales:C,trendPercent:k,selectedRangeLabel:x,refresh:z}=v,N=(d==null?void 0:d.stats)||null,f=(d==null?void 0:d.analytics)||null;d!=null&&d.previousAnalytics;const A=(d==null?void 0:d.validOrders.orders)||[],B=(d==null?void 0:d.validOrders.total)||0,V=(d==null?void 0:d.validOrders.truncated)||!1,u=T.range==="loading",h=T.error,m=[j("brand"),j("brand-highlight"),j("success-500"),j("warning-500"),j("accent-500")],g=r=>`¥${Number(r||0).toLocaleString("zh-CN",{maximumFractionDigits:2})}`;if(h&&(!N||!f))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(he,{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:z,children:"重新加载"})]});if(!N||!f)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(te,{className:"w-8 h-8 animate-spin text-brand"})});const p=f.revenue_stats.total_orders||0,w=f.revenue_stats.total_amount||0,Y=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];let $;try{$=ue(t,new Date,s,n)}catch{$={startDate:s,endDate:n}}const O=b.trim().toLowerCase(),J=A.filter(r=>{var y,Q,Z,ee;return((y=r.order_id)==null?void 0:y.toLowerCase().includes(O))||((Q=r.item_id)==null?void 0:Q.toLowerCase().includes(O))||((Z=r.item_title)==null?void 0:Z.toLowerCase().includes(O))||((ee=r.buyer_id)==null?void 0:ee.toLowerCase().includes(O))});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:z,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:[Y.map(r=>e.jsx("button",{onClick:(()=>a(r.key)),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${t===r.key?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:r.label},r.key)),t==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:s,onChange:(r=>l(r.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:n,onChange:(r=>o(r.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:(()=>K(r=>r+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:`¥${f.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:pe,colorClass:"bg-blue-400",trend:k||void 0}),e.jsx(W,{title:"活跃账号 / 总数",value:`${N.active_cookies} / ${N.total_cookies}`,icon:be,colorClass:"bg-blue-500"}),e.jsx(W,{title:"订单数",value:f.revenue_stats.total_orders.toLocaleString(),icon:xe,colorClass:"bg-blue-500"}),e.jsx(W,{title:"库存卡密余量",value:N.available_card_stock,icon:fe,colorClass:"bg-purple-500"})]}),e.jsx(Me,{chartData:R,selectedRangeLabel:x,totalAmount:w}),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:S.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:S.map((r,y)=>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 ${y<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:y+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:r.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[r.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,r.sales/C*100)}%`}})})]},`${r.name}-${y}`))})})]}),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":`商品下单占比,共 ${p} 单`,children:L.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(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:L,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:L.map((r,y)=>e.jsx(U,{fill:r.color},`cell-${y}`))}),e.jsx(F,{formatter:(r=>`${Number(r||0)} 单`),wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"10px",boxShadow:"var(--shadow-md)"}}),e.jsx(De,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:(r=>e.jsx("span",{style:{color:j("neutral-500"),fontWeight:500},children:r}))})]})}),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:p}),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:"参与统计的订单"}),V&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",A.length," / ",B," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:b,onChange:(r=>_(r.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:u?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(te,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):J.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(se,{className:"w-7 h-7 text-gray-300"})}),O?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:["当前共有 ",A.length," 单参与统计,但没有订单号、商品、买家匹配“",b,"”。"]})]}):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:["日期范围:",$.startDate," 至 ",$.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",f.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:J.map(r=>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(se,{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:r.item_title||r.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:r.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",r.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:r.buyer_id}),r.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:me(r.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",r.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(qe,{status:r.status||r.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=${r.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(ye,{className:"w-4 h-4"})})})]},r.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)"}),D.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":`商品金额分析,总金额 ${g(w)}`,children:[e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(ne,{accessibilityLayer:!1,children:[e.jsx(le,{data:D,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:D.map((r,y)=>e.jsx(U,{fill:r.color||m[y%m.length]},`cell-${y}`))}),e.jsx(F,{wrapperStyle:{zIndex:30,outline:"none"},contentStyle:{backgroundColor:j("white"),border:`1px solid ${j("neutral-200")}`,borderRadius:"6px",boxShadow:"var(--shadow-md)"},formatter:(r=>`¥${Number(r||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:g(w)}),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:D.map(r=>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:r.color||m[D.indexOf(r)%m.length]}}),e.jsx("span",{className:"text-gray-600 font-medium truncate",title:r.name,children:r.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:["¥",r.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[r.percentage,"%"]})]})]},r.name))})]})]})]})]})};export{qe as StatusBadge,Xe as default}; diff --git a/internal/webui/static/assets/Dashboard-sUNU2Eg5.js b/internal/webui/static/assets/Dashboard-sUNU2Eg5.js deleted file mode 100644 index 904640d..0000000 --- a/internal/webui/static/assets/Dashboard-sUNU2Eg5.js +++ /dev/null @@ -1 +0,0 @@ -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-kyCurZV6.js b/internal/webui/static/assets/ItemList-FcKS3Z5e.js similarity index 51% rename from internal/webui/static/assets/ItemList-kyCurZV6.js rename to internal/webui/static/assets/ItemList-FcKS3Z5e.js index b094ce2..cbbbf6b 100644 --- a/internal/webui/static/assets/ItemList-kyCurZV6.js +++ b/internal/webui/static/assets/ItemList-FcKS3Z5e.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-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}; +import{r as l,j as e,b as ge}from"./react-vendor-C_od1ZSF.js";import{g as de,a as te,b as Ge,d as Ve,p as ot}from"./index-CFzx5gQT.js";import{c as We}from"./contract-COFcZjyb.js";import{a3 as xt,U as Ee,R as we,N as Re,a4 as _e,a5 as be,V as mt,F as ht,B as ut,a6 as $e,a7 as pt,a8 as gt,A as bt,d as yt,X as re,r as ft,a9 as De,I as qe}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",jt="c9b68d4ce9a2a97f22a4a439404488ca";let ce=null;const Nt=()=>jt,vt=()=>window.AMap?Promise.resolve(window.AMap):ce||(ce=new Promise((s,a)=>{const x=document.getElementById(Ue),o=x||document.createElement("script"),d=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(P)},g=()=>{window.AMap?(d(),s(window.AMap)):(d(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},P=window.setTimeout(()=>{d(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=g,o.id=Ue,o.async=!0,o.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Nt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,o.onerror=()=>{d(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},x||document.head.appendChild(o)}).catch(s=>{throw ce=null,s}),ce),ye=s=>Number.isFinite(s)&&s!==0,wt=s=>{var d,g;const a=Number((d=s.location)==null?void 0:d.lng),x=Number((g=s.location)==null?void 0:g.lat),o={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:x,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!o.division_id||!o.province||!o.city||!o.poi_id||!o.poi_name||!ye(a)||!ye(x)||a<-180||a>180||x<-90||x>90?null:o},_t=async(s,a)=>{if(!ye(s)||!ye(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const x=await vt();return new Promise((o,d)=>{new x.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(P,f)=>{var w;if(P!=="complete"){if(P==="no_data"){o([]);return}d(new Error("高德地图附近地址查询失败,请稍后重试"));return}const L=(((w=f==null?void 0:f.poiList)==null?void 0:w.pois)||[]).map(wt).filter(T=>T!==null);o(L)})})},kt=async s=>de("/api/v1/accounts/details",void 0,s),ze=async()=>de("/api/v1/automation-rules"),ke=s=>s===!0||s===1||s==="1",Oe=async(s,a)=>{const x=await de("/api/v1/items",void 0,a);return We(x,["items","data","results"]).map(d=>({...d,id:d.id||`${d.cookie_id}-${d.item_id}`,is_multi_spec:ke(d.is_multi_spec),is_multi_qty_ship:ke(d.is_multi_qty_ship??d.multi_quantity_delivery),multi_quantity_delivery:ke(d.multi_quantity_delivery??d.is_multi_qty_ship)}))},Ct=async s=>te("/api/v1/items/get-all-from-account",{cookie_id:s}),It=async(s,a)=>Ve(`/api/v1/items/${s}/${a}`),St=async(s,a)=>te(`/api/v1/items/${s}`,a),Pt=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const x of s.images)a.append("images",x);return Ge("/api/v1/items/publish",a)},Bt=async(s,a)=>te("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:a}),Ft=async s=>{const a=new FormData;return a.set("file",s.file),s.imagesZip&&a.set("images_zip",s.imagesZip),s.defaultCookieId&&a.set("default_cookie_id",s.defaultCookieId),a.set("fallback_category_id",s.fallbackCategory.catId),a.set("fallback_category_name",s.fallbackCategory.catName),a.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),a.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&a.set("location",JSON.stringify(s.location)),Ge("/api/v1/items/publish-batches/preview",a)},Lt=async s=>te("/api/v1/items/publish-batches",{preview_id:s}),ee=async s=>de(`/api/v1/items/publish-batches/${s}`),Ye=async(s=20)=>{const a=await de("/api/v1/items/publish-batches",{limit:s});return We(a,["batches","data","items"])},At=async s=>Ve(`/api/v1/items/publish-batches/${s}`),Mt=async s=>te(`/api/v1/items/publish-batches/${s}/cancel`,{}),Et=async s=>te(`/api/v1/items/publish-batches/${s}/retry-failed`,{}),Rt=async(s,a,x)=>ot(`/api/v1/items/${s}/${a}`,x),$t=s=>s.find(a=>a.status==="running"||a.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Dt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),qt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Ut=(s,a)=>s===a,Te=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||"-"}},Ke=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"}},zt=s=>{const[a,x]=l.useState(!1),[o,d]=l.useState("upload"),[g,P]=l.useState(null),[f,L]=l.useState(null),[w,T]=l.useState(""),[K,J]=l.useState(!1),[R,G]=l.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[y,N]=l.useState(null),[c,_]=l.useState(null),[I,$]=l.useState(null),[V,D]=l.useState([]),[q,B]=l.useState(null),[U,p]=l.useState(!1),k=l.useRef(!1),m=l.useRef(0),A=l.useCallback(async()=>{d("upload"),N(null),_(null),P(null),L(null),T(""),G({catId:"",catName:"",channelCatId:"",tbCatId:""}),D([]),B(null),x(!0),p(!0);try{const r=await Ye(20),h=$t(r);if(h!=null&&h.id){const S=await ee(h.id);$(S),_(S),d(["running","canceling"].includes(S.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{p(!1)}},[]),u=l.useCallback(async()=>{const r=w.trim();if(!s.selectedAccount){alert("请先选择默认发布账号");return}if(!r){alert("请输入类目关键词");return}J(!0);try{const S=(await Bt(s.selectedAccount,r)).category;G({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{J(!1)}},[w,s.selectedAccount]),M=l.useCallback(async()=>{if(I!=null&&I.id){p(!0),x(!0);try{const r=await ee(I.id);_(r),d(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{p(!1)}}},[I==null?void 0:I.id]),se=l.useCallback(async()=>{if(!g){alert("请先上传商品表格");return}if(!s.selectedAccount){alert("请先选择默认发布账号");return}p(!0);try{const r=await Ft({file:g,imagesZip:f,defaultCookieId:s.selectedAccount,fallbackCategory:R,location:q||void 0});N(r),_(null),d("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{p(!1)}},[R,g,f,q,s.selectedAccount]),W=l.useCallback(async()=>{if(y!=null&&y.preview_id){if(!Dt(y)){alert("没有可发布的商品行");return}p(!0);try{const r=await Lt(y.preview_id),h=await ee(r.batch_id||y.preview_id);_(h),$(h),d(h.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{p(!1)}}},[y]),Y=l.useCallback(async()=>{if(c!=null&&c.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){p(!0);try{const r=await Mt(c.id),h=await ee(c.id);_(h),d((r==null?void 0:r.status)==="canceling"||h.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{p(!1)}}},[c==null?void 0:c.id]),H=l.useCallback(async()=>{const r=y==null?void 0:y.preview_id;if(r&&o==="preview")try{await At(r)}catch(h){console.error("清理批量铺货预检失败:",h)}N(null),d("upload")},[o,y==null?void 0:y.preview_id]),Q=l.useCallback(async()=>{await H(),x(!1)},[H]),ae=l.useCallback(async()=>{if(!(!(c!=null&&c.id)||!qt(c))){p(!0);try{await Et(c.id),_(await ee(c.id)),d("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{p(!1)}}},[c]);return l.useEffect(()=>{if(!a||!(c!=null&&c.id)||!Ie(c.status))return;const r=++m.current,h=async()=>{if(!k.current){k.current=!0;try{const z=await ee(c.id);if(!Ut(r,m.current))return;_(z),$(z),Ie(z.status)||(d("done"),await Promise.all([s.loadItems(),s.loadShippingRules()]))}catch(z){console.error("刷新批量铺货进度失败:",z)}finally{k.current=!1}}},S=window.setInterval(()=>void h(),3e3);return(()=>{window.clearInterval(S),m.current+=1})},[c==null?void 0:c.id,c==null?void 0:c.status,s.loadItems,s.loadShippingRules,a]),{showBatchModal:a,setShowBatchModal:x,batchLoading:U,batchPhase:o,setBatchPhase:d,batchFile:g,setBatchFile:P,batchImagesZip:f,setBatchImagesZip:L,batchCategoryKeyword:w,setBatchCategoryKeyword:T,batchCategoryLoading:K,batchFallbackCategory:R,setBatchFallbackCategory:G,batchPreview:y,setBatchPreview:N,batchDetail:c,setBatchDetail:_,recentBatch:I,setRecentBatch:$,batchLocations:V,batchLocation:q,setBatchLocations:D,setBatchLocation:B,openBatchModal:A,handleRecommendBatchCategory:u,openRecentBatchResult:M,handlePreviewBatch:se,handleStartBatch:W,handleCancelBatch:Y,abandonBatchPreview:H,closeBatchModal:Q,handleRetryBatchFailed:ae}},Je=()=>({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),Ze=(s="")=>({cookie_id:s,title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),Ce=(s,a)=>{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:a},Ot=({selectedAccount:s,setSelectedAccount:a,setItems:x,loadItems:o,loadShippingRules:d,onConfigureDelivery:g,setBatchLocations:P,setBatchLocation:f})=>{const[L,w]=l.useState(!1),[T,K]=l.useState(!1),[J,R]=l.useState(!1),[G,y]=l.useState(!1),[N,c]=l.useState(!1),[_,I]=l.useState(!1),[$,V]=l.useState([]),[D,q]=l.useState(null),[B,U]=l.useState(null),[p,k]=l.useState({}),[m,A]=l.useState(Je),[u,M]=l.useState(Ze),[se,W]=l.useState([]);l.useEffect(()=>{if(!N||u.images.length===0){W([]);return}const i=u.images.map((j,C)=>({key:j.name+C,url:URL.createObjectURL(j)}));return W(i),(()=>i.forEach(j=>URL.revokeObjectURL(j.url)))},[u.images,N]);const Y=l.useCallback(async()=>{if(!s)return alert("请先选择账号");w(!0);try{const i=await Ct(s);await o(),alert((i==null?void 0:i.message)||"商品同步完成")}catch(i){console.error("同步商品失败:",i),alert(Ce(i,"同步失败,请重试"))}finally{w(!1)}},[o,s]),H=l.useCallback(i=>{U(i),k({...i}),R(!0)},[]),Q=l.useCallback(async()=>{if(B)try{await Rt(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 o(),await d(),R(!1),U(null)}catch(i){console.error("更新商品失败:",i),alert("更新失败,请重试")}},[p,o,d,B]),ae=l.useCallback(async i=>{if(confirm(`确认删除商品"${i.item_title}"吗?`))try{await It(i.cookie_id,i.item_id),x(j=>j.filter(C=>!(C.cookie_id===i.cookie_id&&C.item_id===i.item_id)))}catch(j){console.error("删除商品失败:",j),alert("删除失败,请重试")}},[x]),oe=l.useCallback(async()=>{try{if(!m.cookie_id||!m.item_id){alert("请选择账号并填写商品ID");return}await St(m.cookie_id,{item_id:m.item_id,item_title:m.item_title,item_price:m.item_price,item_detail:m.item_image?JSON.stringify({item_image:m.item_image}):""}),await o(),y(!1),A(Je())}catch(i){console.error("添加商品失败:",i),alert("添加失败,请重试")}},[m,o]),r=l.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("请填写一口价邮费");K(!0);try{const i=await Pt({...u,location:D||void 0});if(await o(),c(!1),M(Ze(s||"")),V([]),q(null),i!=null&&i.item_id){const j={id:i.item_id,cookie_id:u.cookie_id,item_id:i.item_id,item_title:i.item_title||u.title,item_price:i.item_price||u.price,item_image:i.item_image};g(j),alert("商品发布成功,ID: "+i.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(i){console.error("发布商品失败:",i);const j=i==null?void 0:i.payload;if((j==null?void 0:j.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert(Ce(i,"发布失败,请重试"))}finally{K(!1)}},[o,g,u,D,s]),h=l.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(je=>je.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(` +`),F=new Blob(["\uFEFF"+C],{type:"text/csv;charset=utf-8"}),xe=URL.createObjectURL(F),X=document.createElement("a");X.href=xe,X.download="批量铺货模板.csv",document.body.appendChild(X),X.click(),X.remove(),URL.revokeObjectURL(xe)},[]),S=l.useCallback(()=>{A(i=>({...i,cookie_id:s||i.cookie_id})),y(!0)},[s]),z=l.useCallback(()=>{M(i=>({...i,cookie_id:s||i.cookie_id})),c(!0)},[s]),fe=l.useCallback(async i=>{if(!(i?s:u.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");I(!0),navigator.geolocation.getCurrentPosition(async C=>{try{const F=await _t(C.coords.longitude,C.coords.latitude);if(!F.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");i?(P(F),f(F[0])):(V(F),q(F[0]))}catch(F){alert(Ce(F,"获取发货地失败"))}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:a,loading:L,publishing:T,showEditModal:J,setShowEditModal:R,showAddModal:G,setShowAddModal:y,showPublishModal:N,setShowPublishModal:c,locationLoading:_,publishLocations:$,setPublishLocations:V,publishLocation:D,setPublishLocation:q,selectedItem:B,editForm:p,setEditForm:k,addForm:m,setAddForm:A,publishForm:u,setPublishForm:M,publishImagePreviews:se,handleSync:Y,handleEdit:H,handleSaveEdit:Q,handleDelete:ae,handleAddItem:oe,handlePublishItem:r,downloadPublishTemplate:h,openAddModal:S,openPublishModal:z,locateForPublish:fe}},Tt=({phase:s})=>{const a=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:a.map(([x,o])=>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:o},x))})},Kt=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},Wt=({onConfigureDelivery:s})=>{const[a,x]=l.useState([]),[o,d]=l.useState([]),[g,P]=l.useState([]),[f,L]=l.useState(""),[w,T]=l.useState(""),K=l.useCallback(async()=>{const t=await Oe();x(t)},[]),J=l.useCallback(async()=>{d(await ze())},[]),R=zt({selectedAccount:f,loadItems:K,loadShippingRules:J}),{showBatchModal:G,setShowBatchModal:y,batchLoading:N,batchPhase:c,batchFile:_,setBatchFile:I,batchImagesZip:$,setBatchImagesZip:V,batchCategoryKeyword:D,setBatchCategoryKeyword:q,batchCategoryLoading:B,batchFallbackCategory:U,setBatchFallbackCategory:p,batchPreview:k,batchDetail:m,recentBatch:A,setRecentBatch:u,batchLocations:M,batchLocation:se,setBatchLocations:W,setBatchLocation:Y,openBatchModal:H,handleRecommendBatchCategory:Q,openRecentBatchResult:ae,handlePreviewBatch:oe,handleStartBatch:r,handleCancelBatch:h,abandonBatchPreview:S,closeBatchModal:z,handleRetryBatchFailed:fe}=R,i=Ot({selectedAccount:f,setSelectedAccount:L,setItems:x,loadItems:K,loadShippingRules:J,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Y}),{loading:j,publishing:C,showEditModal:F,setShowEditModal:xe,showAddModal:X,setShowAddModal:je,showPublishModal:Ne,setShowPublishModal:He,locationLoading:me,publishLocations:he,setPublishLocations:Xe,publishLocation:Qe,setPublishLocation:Se,selectedItem:Pe,editForm:Z,setEditForm:ue,addForm:E,setAddForm:le,publishForm:b,setPublishForm:O,publishImagePreviews:Be,handleSync:et,handleEdit:tt,handleSaveEdit:st,handleDelete:at,handleAddItem:lt,handlePublishItem:it,downloadPublishTemplate:nt,openAddModal:rt,openPublishModal:ct,locateForPublish:Fe}=i;l.useEffect(()=>{Promise.all([kt(),Oe(),ze(),Ye(20)]).then(([t,n,v,ne])=>{P(t),x(n),d(v);const pe=ne.find(ve=>["running","canceling"].includes(ve.status))||ne.find(ve=>ve.status!=="preview");u(pe||null)}).catch(t=>console.error("加载商品配置失败:",t))},[]);const dt=t=>o.filter(n=>n.cookie_id===t.cookie_id&&n.item_id===t.item_id).length>0?o.filter(n=>n.cookie_id===t.cookie_id&&n.item_id===t.item_id):o.filter(n=>n.cookie_id===t.cookie_id&&!n.item_id),Le=l.useMemo(()=>new Map(g.map(t=>[t.id,t])),[g]),Ae=l.useMemo(()=>w?a.filter(t=>t.cookie_id===w):a,[w,a]),ie=t=>{const n=Le.get(t),v=(n==null?void 0:n.remark)||(n==null?void 0:n.nickname);return v?`${v} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Me=t=>{const n=Le.get(t);return(n==null?void 0:n.remark)||(n==null?void 0:n.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(xt,{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=>T(t.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(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(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",{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=>L(t.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(t.id)},t.id))]})]})]}),e.jsxs("button",{onClick:et,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(we,{className:`w-4 h-4 ${j?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:rt,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:ct,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(_e,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void H()),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(be,{className:"w-4 h-4"}),A&&["running","canceling"].includes(A.status)?"继续批量任务":"批量铺货"]}),A&&!["running","canceling"].includes(A.status)&&e.jsx("button",{onClick:(()=>void ae()),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:[Ae.map(t=>{const n=dt(t),v=n.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:(()=>tt(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(mt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:(()=>at(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(ht,{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(ut,{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:Kt(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:Me(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:Me(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($e,{className:"w-3 h-3"}):e.jsx(pt,{className:"w-3 h-3"}),v?`${n.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(gt,{className:"w-3.5 h-3.5"}),v?"查看发货规则":"关联发货规则"]}),e.jsx(bt,{className:"w-3.5 h-3.5"})]})})]},`${t.cookie_id}-${t.item_id}`)}),Ae.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(yt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),w?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),F&&Pe&&ge.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: ",Pe.item_id]})]}),e.jsx("button",{onClick:(()=>xe(!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:Z.item_title||"",onChange:(t=>ue({...Z,item_title:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:Z.item_price||"",onChange:(t=>ue({...Z,item_price:t.target.value}))}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:Z.item_category||"",onChange:(t=>ue({...Z,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:Z.item_description||"",onChange:(t=>ue({...Z,item_description:t.target.value}))})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:st,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ft,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),X&&ge.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:(()=>je(!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:E.cookie_id,onChange:(t=>le({...E,cookie_id:t.target.value})),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(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:E.item_id,onChange:(t=>le({...E,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:E.item_price,onChange:(t=>le({...E,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:E.item_title,onChange:(t=>le({...E,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:E.item_image,onChange:(t=>le({...E,item_image:t.target.value}))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:lt,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),Ne&&ge.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:(()=>He(!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=>{O({...b,cookie_id:t.target.value}),Xe([]),Se(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(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=>O({...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=>O({...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=>O({...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=>O({...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=>O({...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=>O({...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=>O({...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:me||!b.cookie_id,onClick:(()=>void Fe(!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(De,{className:"h-4 w-4"}),me?"定位中...":"获取当前位置"]})]}),he.length>0&&e.jsx("select",{className:"w-full ios-input rounded-xl bg-white px-4 py-3",value:String(Math.max(0,he.indexOf(Qe))),onChange:(t=>Se(he[Number(t.target.value)]||null)),children:he.map((t,n)=>e.jsx("option",{value:String(n),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${n}`))})]}),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(be,{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=>O({...b,images:Array.from(t.target.files||[]).slice(0,9)}))})]}),Be.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:Be.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:it,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(_e,{className:"w-4 h-4"}),C?"正在发布...":"发布到闲鱼"]})})]})}),document.body),G&&ge.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 z()),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(Tt,{phase:c}),c==="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:nt,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=>{L(t.target.value),W([]),Y(null)}),children:[e.jsx("option",{value:"",children:"选择账号"}),g.map(t=>e.jsx("option",{value:t.id,children:ie(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(qe,{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=>q(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(qe,{className:"h-4 w-4"}),B?"匹配中...":"获取类目"]})]}),U.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($e,{className:"h-4 w-4 shrink-0 text-emerald-600"}),e.jsx("span",{className:"truncate",children:U.catName})]}),e.jsxs("div",{className:"mt-1 font-mono text-xs text-gray-500",children:["类目 ",U.catId," · 频道 ",U.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:me||!f,onClick:(()=>void Fe(!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(De,{className:"h-4 w-4"}),me?"定位中...":"获取当前位置"]})]}),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(se))),onChange:(t=>Y(M[Number(t.target.value)]||null)),children:M.map((t,n)=>e.jsx("option",{value:String(n),children:[t.province,t.city,t.area,t.poi_name].filter(Boolean).join(" ")},`${t.division_id}-${t.poi_id}-${n}`))})]}),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(be,{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 n;return I(((n=t.target.files)==null?void 0:n[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(be,{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 n;return V(((n=t.target.files)==null?void 0:n[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,n,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 ${n==="每个商品都要填"?"text-red-600":n==="可以留空"?"text-gray-500":"text-amber-700"}`,children:n}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:v})]},t))})]})})]})]}),c==="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 n,v,ne,pe;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:((n=t.category)==null?void 0:n.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:[((ne=t.images)==null?void 0:ne.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((pe=t.errors)==null?void 0:pe.join(";"))||"-"})]},t.row_no)})})]})})]}),(c==="running"||c==="done")&&m&&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 ${Ke(m.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:Te(m.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:m.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:m.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:m.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:m.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:m.rows.map(t=>{var n,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 ${Ke(t.status)}`,children:Te(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:((n=t.category)==null?void 0:n.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:[c==="upload"&&e.jsxs("button",{disabled:N||!_||!f,onClick:oe,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(we,{className:`w-4 h-4 ${N?"animate-spin":""}`}),N?"正在预检...":"开始预检"]}),c==="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(_e,{className:"w-4 h-4"}),N?"启动中...":`确认发布 ${k.valid} 个商品`]})]}),(c==="running"||c==="done")&&m&&e.jsxs("div",{className:"flex gap-3 w-full",children:[m.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:"取消任务"}):m.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/${m.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:"下载结果"}),m.retryable>0&&!["running","canceling"].includes(m.status)&&e.jsxs("button",{disabled:N,onClick:fe,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(we,{className:`w-4 h-4 ${N?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(m.status)&&e.jsx("button",{onClick:(()=>{y(!1),K(),J()}),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{Wt as default}; diff --git a/internal/webui/static/assets/Notifications-BJQ8JgFo.js b/internal/webui/static/assets/Notifications-BJQ8JgFo.js new file mode 100644 index 0000000..2c200e2 --- /dev/null +++ b/internal/webui/static/assets/Notifications-BJQ8JgFo.js @@ -0,0 +1 @@ +import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,x as K,e as W,L as I,y as ve,F as ke,s as Q,X as te,u as ae,v as ne,r as we,R as Se,N as Ce}from"./icons-vendor-CvzvbbIV.js";import{g as re,p as le,a as oe,d as Te}from"./index-CFzx5gQT.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(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},ie=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?G(s.use_custom_smtp,!1):a}},ce=(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=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(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},B={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:K,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:K,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:K,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:Ne,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 是互斥模式,不会再混用两套配置中的部分字段。"}}},pe=[{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:"后台任务或系统级异常"}],Y=()=>({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Pe=s=>!s||s.length===0?"全部事件":s.map(t=>{var a;return((a=pe.find(n=>n.value===t))==null?void 0:a.label)||t}).join("、"),Ee=(s,t)=>{const a=s.type==="email"?ie({...s.config||{}}):null,n=a?a.use_custom_smtp===!0?ce(a,t):a:{...s.config||{}};return{name:s.name,type:s.type,enabled:s.enabled,config:n,event_types:s.event_types||[]}},Me=s=>{const a=B[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=de(s.config);if(n.use_custom_smtp){const k=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([h])=>!String(n[h]||"").trim());if(k)return`请填写 ${k[1]}`}}return""},qe=s=>({name:s.name.trim(),type:s.type,config:s.type==="email"?de(s.config):s.config,event_types:s.event_types,enabled:s.enabled}),g=(s,t)=>s===t,O=(s,t)=>s instanceof Error&&s.message?s.message:t,Ae=({channels:s,testingId:t,onEdit:a,onDelete:n,onToggleEnabled:b,onTest:k})=>{const h=l=>s.find(o=>o.id===l.currentTarget.dataset.channelId)||null,_=l=>{const o=h(l);o&&b(o)},S=l=>{const o=h(l);o&&k(o)},E=l=>{const o=h(l);o&&a(o)},j=l=>{const o=h(l);o&&n(o)},M=l=>{const o=B[l.type]||B.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:l.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}),!l.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 w;return(w=l.config)==null?void 0:w[x.key]}).filter(Boolean).map((x,w)=>e.jsx("span",{className:"mr-3",children:String(x).length>40?`${String(x).slice(0,40)}…`:String(x)},w))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Pe(l.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{"data-channel-id":l.id,onClick:_,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${l.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:l.enabled?"启用中":"已停用"}),e.jsxs("button",{"data-channel-id":l.id,onClick:S,disabled:t===l.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===l.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":l.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(ve,{className:"w-4 h-4"})}),e.jsx("button",{"data-channel-id":l.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(ke,{className:"w-4 h-4"})})]})]},l.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)})},Le=({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:pe.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(Q,{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)})})]})},Re=({showModal:s,editing:t,form:a,setForm:n,smtp:b,showChannelSmtpPassword:k,setShowChannelSmtpPassword:h,saving:_,onClose:S,onSave:E})=>{const j=B[a.type],M=r=>n(p=>({...p,name:r.target.value})),l=r=>{const p=r.currentTarget.dataset.type;p&&n(N=>({...N,type:p,config:{}}))},o=r=>{const p=r.currentTarget.dataset.field;p&&n(N=>({...N,config:{...N.config,[p]:r.target.value}}))},P=()=>n(r=>({...r,config:r.config.use_custom_smtp===!0?{...r.config,use_custom_smtp:!1}:ce(r.config,b)})),x=r=>n(p=>({...p,config:{...p.config,smtp_use_tls:r.target.checked,smtp_use_ssl:r.target.checked?!1:p.config.smtp_use_ssl}})),w=r=>n(p=>({...p,config:{...p.config,smtp_use_ssl:r.target.checked,smtp_use_tls:r.target.checked?!1:p.config.smtp_use_tls}})),U=r=>n(p=>({...p,event_types:p.event_types.includes(r)?p.event_types.filter(N=>N!==r):[...p.event_types,r]})),F=()=>n(r=>({...r,enabled:!r.enabled})),J=()=>h(r=>!r),X=(r,p)=>e.jsx("li",{children:r},p);return s?_e.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:S,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(B).map(r=>{const p=B[r],N=p.icon,q=a.type===r;return e.jsxs("button",{"data-type":r,type:"button",onClick:l,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(N,{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:p.label})]},r)})})]}),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(X)}),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(r=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[r.label,r.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{"data-field":r.key,type:r.type==="password"?"password":r.type==="number"?"number":"text",value:String(a.config[r.key]||""),onChange:o,placeholder:r.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),r.help&&e.jsx("p",{className:"text-xs text-gray-500",children:r.help})]},r.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:k?"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:J,className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:k?e.jsx(ae,{className:"w-4 h-4"}):e.jsx(ne,{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:w}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsx(Le,{selectedEvents:a.event_types,onToggleEvent:U}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:F,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:S,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:_,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[_?e.jsx(I,{className:"w-4 h-4 animate-spin"}):e.jsx(Q,{className:"w-4 h-4"}),_?"保存中...":"保存"]})]})]})}),document.body):null},Be=({smtp:s,setSmtp:t,smtpSaving:a,showPassword:n,setShowPassword:b,onSave:k})=>{const h=l=>{const o=l.currentTarget.dataset.field;o&&t(P=>({...P,[o]:l.target.value}))},_=l=>{t(o=>({...o,smtp_port:parseInt(l.target.value,10)||587}))},S=l=>{t(o=>({...o,smtp_use_tls:l.target.checked,smtp_use_ssl:l.target.checked?!1:o.smtp_use_ssl}))},E=l=>{t(o=>({...o,smtp_use_ssl:l.target.checked,smtp_use_tls:l.target.checked?!1:o.smtp_use_tls}))},j=l=>{t(o=>({...o,smtp_password:l.target.value}))},M=()=>b(l=>!l);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:h,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:_,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:h,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(ne,{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:h,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:h,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:S}),"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:k,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(we,{className:"w-4 h-4"}),a?"保存中...":"保存 SMTP 配置"]})]})},$e=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},me=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Oe=s=>{let t={};try{const n=typeof s.config=="string"?JSON.parse(s.config):s.config;n&&typeof n=="object"&&!Array.isArray(n)&&(t=n)}catch{}const a=s.type==="ding_talk"?"dingtalk":s.type==="lark"?"feishu":s.type;return{id:String(s.id),name:s.name,type:a,config:t,event_types:$e(s.event_types),enabled:s.enabled,created_at:s.created_at,updated_at:s.updated_at}},Fe=async s=>{const t=await re("/api/v1/notifications/channels",void 0,s);return{success:!0,data:(Array.isArray(t)?t:t.data||t.channels||[]).map(Oe)}},De=async(s,t)=>oe("/api/v1/notifications/channels",{...s,config:JSON.stringify(s.config),event_types:me(s.event_types)},t),Z=async(s,t,a)=>{const n={...t};return"config"in t&&(n.config=JSON.stringify(t.config)),"event_types"in t&&(n.event_types=me(t.event_types)),le(`/api/v1/notifications/channels/${s}`,n,a)},We=async(s,t)=>Te(`/api/v1/notifications/channels/${s}`,void 0,t),Ie=async(s,t)=>oe(`/api/v1/notifications/channels/${s}/test`,{},t),Ue=s=>{const t={...s};if("renewal_log_retention_days"in t){const a=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(a)?a:10}return t},Je=async s=>{const t=await re("/api/v1/settings/system",void 0,s);return Ue(t.data||t.settings||t)},Xe=async(s,t)=>le("/api/v1/settings/system",s,t),ze=s=>{const[t,a]=d.useState([]),[n,b]=d.useState(!0),[k,h]=d.useState(!1),[_,S]=d.useState(null),[E,j]=d.useState(!1),[M,l]=d.useState(""),[o,P]=d.useState(null),[x,w]=d.useState({}),[U,F]=d.useState(!1),[J,X]=d.useState(!1),[r,p]=d.useState(!1),[N,q]=d.useState(Y),$=d.useRef(0),z=d.useRef(null),C=d.useRef(0),L=d.useRef(null),y=d.useRef(0),T=d.useRef(null),R=d.useRef(null),f=d.useCallback((i,c)=>{P({type:i,text:c}),R.current!==null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{R.current=null,P(null)},3e3)},[]),A=d.useCallback(async()=>{var m;const i=++$.current;(m=z.current)==null||m.abort();const c=new AbortController;z.current=c,b(!0);try{const u=await Fe({signal:c.signal});if(!g(i,$.current))return;a(u.data||[])}catch(u){g(i,$.current)&&!c.signal.aborted&&console.error("加载通知渠道失败",u)}finally{g(i,$.current)&&b(!1)}},[]),V=d.useCallback(async()=>{var m;const i=++C.current;(m=L.current)==null||m.abort();const c=new AbortController;L.current=c;try{const u=await Je({signal:c.signal});g(i,C.current)&&w(u||{})}catch(u){g(i,C.current)&&!c.signal.aborted&&console.error("加载 SMTP 配置失败",u)}},[]);d.useEffect(()=>{var i;return A(),s?V():(C.current+=1,(i=L.current)==null||i.abort(),w({})),(()=>{var c,m;$.current+=1,(c=z.current)==null||c.abort(),C.current+=1,(m=L.current)==null||m.abort()})},[s,A,V]),d.useEffect(()=>(()=>{R.current!==null&&window.clearTimeout(R.current)}),[]);const ue=d.useCallback(()=>{S(null),q(Y()),p(!1),h(!0)},[]),xe=d.useCallback(i=>{S(i),q(Ee(i,x)),p(!1),h(!0)},[x]),ge=d.useCallback(()=>{var i;y.current+=1,(i=T.current)==null||i.abort(),j(!1),h(!1)},[]),he=d.useCallback(async()=>{var u;const i=Me(N);if(i){f("error",i);return}const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m,j(!0);try{const v=qe(N);if(_?await Z(_.id,v,{signal:m.signal}):await De(v,{signal:m.signal}),!g(c,y.current)||(h(!1),await A(),!g(c,y.current)))return;f("success",_?"已更新":"已创建")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"保存失败"))}finally{g(c,y.current)&&j(!1)}},[_,N,A,f]),be=d.useCallback(async i=>{var u;if(!confirm(`确认删除渠道「${i.name}」吗?已绑定该渠道的账号会自动解绑。`))return;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await We(i.id,{signal:m.signal}),!g(c,y.current)||(await A(),!g(c,y.current)))return;f("success","已删除")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"删除失败"))}},[A,f]),ye=d.useCallback(async i=>{var u;const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{if(await Z(i.id,{enabled:!i.enabled},{signal:m.signal}),!g(c,y.current))return;a(v=>v.map(D=>D.id===i.id?{...D,enabled:!D.enabled}:D))}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"切换失败"))}},[f]),fe=d.useCallback(async i=>{var u;l(i.id);const c=++y.current;(u=T.current)==null||u.abort();const m=new AbortController;T.current=m;try{await Ie(i.id,{signal:m.signal}),g(c,y.current)&&f("success","测试通知已发送,请检查对应渠道")}catch(v){g(c,y.current)&&!m.signal.aborted&&f("error",O(v,"发送失败"))}finally{g(c,y.current)&&l("")}},[f]),je=d.useCallback(async()=>{var m;const i=++C.current;(m=L.current)==null||m.abort();const c=new AbortController;L.current=c,F(!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 Xe(u,{signal:c.signal}),g(i,C.current)&&f("success","SMTP 配置已保存")}catch(u){g(i,C.current)&&!c.signal.aborted&&f("error",O(u,"保存失败"))}finally{g(i,C.current)&&F(!1)}},[f,x]);return{channels:t,loading:n,showModal:k,editing:_,saving:E,testingId:M,toast:o,smtp:x,smtpSaving:U,showSmtpPassword:J,showChannelSmtpPassword:r,form:N,setForm:q,setSmtp:w,setShowSmtpPassword:X,setShowChannelSmtpPassword:p,loadChannels:A,openCreate:ue,openEdit:xe,closeModal:ge,showToast:f,handleSave:he,handleDelete:be,handleToggleEnabled:ye,handleTest:fe,handleSaveSmtp:je}},He=({isAdmin:s=!1})=>{const t=ze(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(Se,{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(Ce,{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(Ae,{channels:t.channels,testingId:t.testingId,onEdit:t.openEdit,onDelete:t.handleDelete,onToggleEnabled:t.handleToggleEnabled,onTest:t.handleTest}),s&&e.jsx(Be,{smtp:t.smtp,setSmtp:t.setSmtp,smtpSaving:t.smtpSaving,showPassword:t.showSmtpPassword,setShowPassword:t.setShowSmtpPassword,onSave:t.handleSaveSmtp}),e.jsx(Re,{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(Q,{className:"w-4 h-4"}):e.jsx(te,{className:"w-4 h-4"}),t.toast.text]})]})};export{He as default}; diff --git a/internal/webui/static/assets/Notifications-CyWpiVXa.js b/internal/webui/static/assets/Notifications-CyWpiVXa.js deleted file mode 100644 index 059f7e7..0000000 --- a/internal/webui/static/assets/Notifications-CyWpiVXa.js +++ /dev/null @@ -1 +0,0 @@ -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-Bb5NffV_.js b/internal/webui/static/assets/OrderList-Bb5NffV_.js deleted file mode 100644 index 07560f2..0000000 --- a/internal/webui/static/assets/OrderList-Bb5NffV_.js +++ /dev/null @@ -1 +0,0 @@ -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/OrderList-CSGFKOqw.js b/internal/webui/static/assets/OrderList-CSGFKOqw.js new file mode 100644 index 0000000..4ca91b8 --- /dev/null +++ b/internal/webui/static/assets/OrderList-CSGFKOqw.js @@ -0,0 +1 @@ +import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Y,m as Z,E as ce,v as oe,V as de,F as xe,h as me,g as ue,r as he}from"./icons-vendor-CvzvbbIV.js";import{g as X,b as ae,a as K,p as ge,d as pe}from"./index-CFzx5gQT.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import{f as ee}from"./dateTime-DDi7rqpW.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.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:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.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(te,{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:c,onChange:_,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:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{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:u,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.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:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{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:t,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(ne,{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:g,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:Ne(s.importResult).map((m,u)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:m.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:m.message||"导入失败"})]},`${m.order_id}-${u}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:c,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:h,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},Ie=async s=>X("/api/v1/accounts/details",void 0,s),Oe=async(s,t)=>X("/api/v1/items",void 0,t),Fe=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Me=async(s,t,c=1,h=20,g,m)=>{const u={page:c,page_size:h};s&&(u.cookie_id=s),t&&t!=="all"&&(u.status=t),g!=null&&g.trim()&&(u.search=g.trim());const p=await X("/api/v1/orders",u,m),b=be(p,["data","result"])||{},y=(Array.isArray(b.orders)?b.orders:ye(b.data,["data","orders","items"])).map(r=>({...r,id:r.id||r.order_id,status:Fe(r.status||r.order_status),quantity:Number(r.quantity||1)}));return{success:!0,data:y,total:b.total||y.length,page:b.page||c,page_size:b.page_size||h,total_pages:b.total_pages||1}},De=async(s,t)=>ge(`/api/v1/orders/${s}`,t),Re=async s=>pe(`/api/v1/orders/${s}`),$e=async(s,t,c)=>{const h=new FormData;s&&h.append("cookie_id",s),t&&h.append("status",t);const g=await ae("/api/v1/orders/refresh",h,c),m=180;let u=0;try{for(;u{const r=()=>{globalThis.clearTimeout(i),y(new Error("请求已取消"))},i=globalThis.setTimeout(()=>{var C;(C=c==null?void 0:c.signal)==null||C.removeEventListener("abort",r),_()},b);c!=null&&c.signal&&(c.signal.aborted?r():c.signal.addEventListener("abort",r,{once:!0}))}),u+=1}}finally{}throw new Error("订单刷新任务等待超时")},Ae=async s=>K(`/api/v1/orders/${s}/refresh`),Le=async(s,t)=>K("/api/v1/orders/manual-ship",{order_ids:s,ship_mode:t}),Pe=async(s,t)=>s instanceof FormData?ae("/api/v1/orders/import",s,t):K("/api/v1/orders/import",s,t),Te=(s={pageSize:20})=>{const[t,c]=a.useState([]),[h,g]=a.useState([]),[m,u]=a.useState([]),[p,b]=a.useState("all"),[_,y]=a.useState(""),[r,i]=a.useState(""),[C,$]=a.useState(""),[O,S]=a.useState(1),[w,A]=a.useState(1),[F,o]=a.useState(!1),N=a.useRef(0),f=a.useRef(null),M=a.useRef(null),D=a.useCallback(async()=>{var j;const d=++N.current;(j=f.current)==null||j.abort();const x=new AbortController;f.current=x,o(!0);try{const E=await Me(_||void 0,p,O,s.pageSize,C,{signal:x.signal});if(!T(d,N.current))return;c(E.data),A(E.total_pages)}catch(E){T(d,N.current)&&!x.signal.aborted&&console.error("加载订单失败:",E)}finally{T(d,N.current)&&o(!1)}},[_,C,p,s.pageSize,O]);a.useEffect(()=>{const d=window.setTimeout(()=>{S(1),$(r.trim())},300);return(()=>window.clearTimeout(d))},[r]),a.useEffect(()=>(D(),(()=>{var d;N.current+=1,(d=f.current)==null||d.abort()})),[D]),a.useEffect(()=>{var x;const d=new AbortController;return(x=M.current)==null||x.abort(),M.current=d,Promise.all([Ie({signal:d.signal}),Oe(void 0,{signal:d.signal})]).then(([j,E])=>{d.signal.aborted||(u(j),g(E))}).catch(j=>{d.signal.aborted||console.error("加载订单辅助数据失败:",j)}),(()=>d.abort())},[]);const k=a.useMemo(()=>new Map(m.map(d=>[d.id,d])),[m]),P=a.useMemo(()=>{const d={};return h.forEach(x=>{x.item_id&&(d[`${x.cookie_id}:${x.item_id}`]=x.item_title||x.item_id)}),d},[h]),U=a.useCallback(d=>{const x=k.get(d),j=(x==null?void 0:x.remark)||(x==null?void 0:x.nickname);return j?`${j} · ${d.slice(0,6)}`:`账号 ${d.slice(0,8)}`},[k]),V=a.useCallback(d=>{const x=k.get(d);return(x==null?void 0:x.remark)||(x==null?void 0:x.nickname)||"未命名账号"},[k]),q=a.useCallback((d,x,j)=>{if(j!=null&&j.trim())return j;const E=P[`${d}:${x}`];if(E)return E;const I=h.find(z=>{if(!j||!z.item_title)return!1;const B=j.toLowerCase(),L=z.item_title.toLowerCase();return L.includes(B)||B.includes(L)});return(I==null?void 0:I.item_title)||"未知商品"},[P,h]);return{orders:t,items:h,accounts:m,filter:p,setFilter:b,accountFilter:_,setAccountFilter:y,searchText:r,setSearchText:i,page:O,setPage:S,totalPages:w,loading:F,loadOrders:D,accountName:U,accountNickname:V,getItemNameById:q}},qe=s=>{const[t,c]=a.useState(!1),[h,g]=a.useState(null),[m,u]=a.useState(null),[p,b]=a.useState(!1),[_,y]=a.useState(""),r=a.useRef(0),i=a.useRef(null);a.useEffect(()=>(()=>{var w;r.current+=1,(w=i.current)==null||w.abort()}),[]);const C=a.useCallback(()=>{g(null),u(null),y(""),c(!0)},[]),$=a.useCallback(()=>{var w;r.current+=1,(w=i.current)==null||w.abort(),b(!1),c(!1),g(null),u(null),y("")},[]),O=a.useCallback(async()=>{var N;if(!_e(h,p))return;const w=h;if(!w)return;const A=ke(w);if(A){y(A);return}const F=++r.current;(N=i.current)==null||N.abort();const o=new AbortController;i.current=o,b(!0),u(null),y("");try{const f=new FormData;f.append("file",w);const M=je(await Pe(f,{signal:o.signal}));if(!T(F,r.current))return;u(M),g(null),await s(),M.failed_count===0&&T(F,r.current)&&(alert(`订单导入成功,共 ${M.success_count} 条`),c(!1),u(null))}catch(f){T(F,r.current)&&!o.signal.aborted&&y(Ce(f,"导入失败,请检查文件格式"))}finally{T(F,r.current)&&b(!1)}},[h,p,s]),S=a.useCallback(async()=>{await O()},[O]);return{showImportModal:t,importFile:h,setImportFile:g,importResult:m,importing:p,importError:_,openImportModal:C,closeImportModal:$,handleImportOrders:O,handleRetryImport:S}},Q=(s,t)=>s instanceof Error?s.message:t,ze=({orders:s,page:t,accountFilter:c,filter:h,setPage:g,loadOrders:m})=>{const[u,p]=a.useState(!1),[b,_]=a.useState(null),[y,r]=a.useState(!1),[i,C]=a.useState(null),[$,O]=a.useState(!1),[S,w]=a.useState(""),[A,F]=a.useState(!1),[o,N]=a.useState(null),[f,M]=a.useState(null),[D,k]=a.useState(null),P=a.useCallback(async()=>{try{const n=await $e(c||void 0,h);await m(),n.message&&alert(n.message)}catch(n){console.error("同步订单失败:",n),alert(Q(n,"同步失败,请重试"))}},[c,h,m]),U=a.useCallback(n=>{w(n),N(null),O(!0)},[]),V=a.useCallback(async n=>{var v;F(!0),N(null);try{const R=(v=(await Le([S],n)).results)==null?void 0:v[0];R!=null&&R.success?(N({success:!0,message:R.message}),m()):N({success:!1,message:(R==null?void 0:R.message)||"发货失败"})}catch(G){N({success:!1,message:Q(G,"请求失败")})}finally{F(!1)}},[m,S]),q=a.useCallback(n=>{_(n),p(!0)},[]),d=a.useCallback(n=>{C({...n}),r(!0)},[]),x=a.useCallback(n=>{C(v=>v&&{...v,...n})},[]),j=a.useCallback(async()=>{if(i!=null&&i.order_id)try{const n={};i.status!==void 0&&(n.order_status=i.status),i.buyer_id!==void 0&&(n.buyer_id=i.buyer_id),i.amount!==void 0&&(n.amount=i.amount),i.receiver_name!==void 0&&(n.receiver_name=i.receiver_name),i.receiver_phone!==void 0&&(n.receiver_phone=i.receiver_phone),i.receiver_address!==void 0&&(n.receiver_address=i.receiver_address),i.item_id!==void 0&&(n.item_id=i.item_id),i.quantity!==void 0&&(n.quantity=i.quantity),i.item_title!==void 0&&(n.item_title=i.item_title),await De(i.order_id,n),r(!1),C(null),await m()}catch(n){console.error("更新订单失败:",n),alert("更新失败,请重试")}},[i,m]),E=a.useCallback(async n=>{M(n);try{const v=await Ae(n);v.success?await m():alert(v.message||"同步失败")}catch(v){console.error("同步订单失败:",v),alert(Q(v,"同步失败,请重试"))}finally{M(null)}},[m]),I=a.useCallback(async n=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){k(n);try{await Re(n),s.length===1&&t>1?g(v=>v-1):await m()}catch(v){console.error("删除订单失败:",v),alert(Q(v,"删除失败,请重试")),await m()}finally{k(null)}}},[m,s.length,t,g]),z=a.useCallback(()=>p(!1),[]),B=a.useCallback(()=>r(!1),[]),L=a.useCallback(()=>{O(!1),N(null)},[]);return{showDetailModal:u,selectedOrder:b,showEditModal:y,editingOrder:i,showShipModal:$,shipOrderId:S,shipLoading:A,shipResult:o,syncingOrderId:f,deletingOrderId:D,handleSync:P,handleShip:U,executeShip:V,handleViewDetail:q,handleEdit:d,handleSaveEdit:j,updateEditingOrder:x,handleSyncSingle:E,handleDelete:I,closeDetailModal:z,closeEditModal:B,closeShipModal:L}},se=({status:s})=>{const t={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"},c={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:c[s]||s})},Je=()=>{const s=Te(),t=qe(s.loadOrders),{orders:c,accounts:h,filter:g,setFilter:m,accountFilter:u,setAccountFilter:p,searchText:b,setSearchText:_,page:y,setPage:r,totalPages:i,loading:C,loadOrders:$,accountName:O,accountNickname:S,getItemNameById:w}=s,A=ze({orders:c,page:y,accountFilter:u,filter:g,setPage:r,loadOrders:$}),{showDetailModal:F,selectedOrder:o,showEditModal:N,editingOrder:f,showShipModal:M,shipLoading:D,shipResult:k,syncingOrderId:P,deletingOrderId:U,handleSync:V,handleShip:q,executeShip:d,handleViewDetail:x,handleEdit:j,handleSaveEdit:E,updateEditingOrder:I,handleSyncSingle:z,handleDelete:B,closeDetailModal:L,closeEditModal:n,closeShipModal:v}=A,G=l=>{m(l),r(1),_("")},R=l=>{p(l),r(1)},le=l=>{_(l),r(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(H,{className:`w-5 h-5 ${C?"animate-spin":""}`})}),e.jsxs("button",{onClick:t.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(ie,{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(Y,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx(Se,{filter:g,onFilterChange:G,accountFilter:u,onAccountFilterChange:R,accounts:h,accountName:O,searchText:b,onSearchChange:le}),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:c.map(l=>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:l.item_image?e.jsx("img",{src:l.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(Z,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:w(l.cookie_id,l.item_id,l.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:S(l.cookie_id),children:[e.jsx(te,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:S(l.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",l.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",l.quantity," • ",ee(l.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:l.buyer_id}),l.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:l.receiver_name})]}),l.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:l.receiver_phone})]}),l.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:l.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:l.amount?`¥${l.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(se,{status:l.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[l.status==="pending_ship"&&e.jsx("button",{onClick:(()=>q(l.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=${l.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(ce,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>x(l)),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(oe,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>j(l)),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>z(l.order_id)),disabled:P===l.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(H,{className:`w-4 h-4 ${P===l.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:(()=>B(l.order_id)),disabled:U===l.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(xe,{className:"w-4 h-4"})})]})]},l.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:["第 ",y," 页 / 共 ",i," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:y<=1,onClick:(()=>r(l=>l-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(me,{className:"w-5 h-5"})}),e.jsx("button",{disabled:y>=i,onClick:(()=>r(l=>l+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(ue,{className:"w-5 h-5"})})]})]})]}),F&&o&&J.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(W,{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:o.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:S(o.cookie_id),children:S(o.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(se,{status:o.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:o.amount?`¥${o.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:o.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:ee(o.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:[o.item_image&&e.jsx("img",{src:o.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:w(o.cookie_id,o.item_id,o.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",o.item_id]}),o.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",o.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:o.buyer_id})]}),o.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:o.receiver_name})]}),o.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:o.receiver_phone})]}),o.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:o.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:"关闭"}),o.status==="pending_ship"&&e.jsx("button",{onClick:(()=>{L(),q(o.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(Ee,{...t}),M&&J.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:v,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{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:(()=>d("status_only")),disabled:D,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(Y,{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:(()=>d("full_delivery")),disabled:D,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(Z,{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:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),D&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(H,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),k&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${k.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[k.success?"✓ ":"✗ ",k.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:v,className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:k!=null&&k.success?"完成":"取消"})})]})}),document.body),N&&f&&J.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:n,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{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:f.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:f.status,onChange:(l=>I({status:l.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:f.buyer_id,onChange:(l=>I({buyer_id:l.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:f.amount,onChange:(l=>I({amount:l.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:f.receiver_name||"",onChange:(l=>I({receiver_name:l.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:f.receiver_phone||"",onChange:(l=>I({receiver_phone:l.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:f.receiver_address||"",onChange:(l=>I({receiver_address:l.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:f.item_title||"",onChange:(l=>I({item_title:l.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:n,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:E,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(he,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})};export{Je as default}; diff --git a/internal/webui/static/assets/Rules-D79nNK3r.js b/internal/webui/static/assets/Rules-D79nNK3r.js new file mode 100644 index 0000000..82120e5 --- /dev/null +++ b/internal/webui/static/assets/Rules-D79nNK3r.js @@ -0,0 +1 @@ +import{j as e,r as o,b as De}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,x as wt,w as et,I as kt,a1 as Ct,X as ke,V as ze,F as Ce,h as St,g as Rt,a6 as At,ag as $t,r as tt,ah as Mt}from"./icons-vendor-CvzvbbIV.js";import{g as Z,p as Ge,a as fe,d as Ke}from"./index-CFzx5gQT.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>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(Je,{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:[t.map(r=>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:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>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:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ft=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Dt=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ue(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/v1/automation-rules",{page:r,page_size:y,cookie_id:t||void 0,trigger_type:a||void 0,enabled:i,search:(u==null?void 0:u.trim())||void 0}),C=Ae(A,["data","result"])||{},m=ct(Ue(A,["data","rules","items"]));return{success:!0,data:m,total:Number(C.total??m.length),page:Number(C.page??r),page_size:Number(C.page_size??y),total_pages:Number(C.total_pages??(m.length?1:0)),trigger_counts:Object.fromEntries(Object.entries(C.trigger_counts||{}).map(([I,T])=>[I,Number(T)]))}},zt=(t,a)=>{if(t!=="order_paid")return a.map((r,y)=>({...r,sort_order:r.sort_order||y+1}));const i=a.filter(r=>r.action_type==="send_card").map((r,y)=>({...r,sort_order:y+1})),u=a.filter(r=>r.action_type!=="send_card"&&r.action_type!=="confirm_shipment");return[...i,...u.map((r,y)=>({...r,sort_order:i.length+y+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:i.length+u.length+1}]},st=async t=>{const a=t.trigger_type||"order_paid",u=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[a]||"自动化规则",t.item_title||t.item_id||t.cookie_id||""].filter(Boolean).join(" - "),r=(t.actions||[]).filter(m=>m.action_type!=="send_card"&&m.action_type!=="confirm_shipment"),y=t.variants&&t.variants.length>0?[...t.variants.map((m,I)=>({action_type:"send_card",card_id:m.card_id,delivery_count:m.delivery_count||1,enabled:m.enabled!==!1,sort_order:I+1,delay_seconds:m.delay_seconds||0,config_json:JSON.stringify({spec_name:m.spec_name||"",spec_value:m.spec_value||"",delay_override:m.delay_override===!0})})),...r]:t.actions&&t.actions.length>0?t.actions:[{action_type:"send_card",card_id:t.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],A=zt(a,y),C={cookie_id:t.cookie_id||"",item_id:t.item_id||"",name:(t.name||"").trim()||u||"自动化规则",trigger_type:a,enabled:t.enabled??!0,priority:t.priority||100,config_json:t.config_json||"{}",actions:A.map((m,I)=>({action_type:m.action_type,card_id:m.card_id||0,delivery_count:m.delivery_count||1,message_template:m.message_template||"",delay_seconds:m.delay_seconds||0,config_json:m.config_json||"{}",enabled:m.enabled!==!1,sort_order:m.sort_order||I+1}))};return t.id?Ge(`/api/v1/automation-rules/${t.id}`,C):fe("/api/v1/automation-rules",C)},Et=async t=>Ke(`/api/v1/automation-rules/${t}`),Ot=async()=>{const t=await Z("/api/v1/automation-issues"),a=Ae(t,["data","result"])||{};return{runs:Array.isArray(a==null?void 0:a.runs)?a.runs:[],pending_tasks:Array.isArray(a==null?void 0:a.pending_tasks)?a.pending_tasks:[]}},qt=async(t,a)=>fe(`/api/v1/automation-runs/${t}/resolve`,{resolution:a}),Vt=async(t,a)=>fe(`/api/v1/automation-pending-tasks/${t}/resolve`,{resolution:a}),Bt=t=>({id:String((t==null?void 0:t.id)||""),keyword:(t==null?void 0:t.keyword)||"",reply:(t==null?void 0:t.reply)||"",item_id:(t==null?void 0:t.item_id)||"",type:(t==null?void 0:t.type)==="image"?"image":"text",image_url:(t==null?void 0:t.image_url)||""}),Jt=async t=>{const a=await Z(`/api/v1/reply-rules/${t}/typed`);return Ue(a,["data","items","rules"]).map(Bt)},Gt=async t=>t?(await Jt(t)).map(i=>({id:i.id,keyword:i.keyword||"",reply_content:i.reply||"",match_type:"fuzzy",enabled:!0,item_id:i.item_id||"",type:i.type==="image"?"image":"text",image_url:i.image_url||""})):[],Kt=async(t,a)=>{const i=t.type||"text",u={keyword:t.keyword||"",reply:i==="text"&&t.reply_content||"",item_id:t.item_id||"",type:i,image_url:i==="image"&&t.image_url||""};return t.id?Ge(`/api/v1/reply-rules/${a}/typed/${t.id}`,u):fe(`/api/v1/reply-rules/${a}/items`,u)},Ut=async(t,a)=>Ke(`/api/v1/reply-rules/${a}/typed/${t}`),at=async()=>{const t=await Z("/api/v1/default-replies");return Ae(t,["data","replies","items"])||{}},Wt=async t=>{const a=await Z(`/api/v1/default-replies/${t}`),i=Ae(a,["data","result"])||{};return{cookie_id:t,enabled:i.enabled||!1,reply_content:i.reply_content||"",reply_once:i.reply_once||!1,reply_image_url:i.reply_image_url||""}},Zt=async(t,a)=>Ge(`/api/v1/default-replies/${t}`,{enabled:a.enabled??!1,reply_content:a.reply_content||"",reply_once:a.reply_once??!1,reply_image_url:a.reply_image_url||""}),Xt=async t=>Ke(`/api/v1/default-replies/${t}`),Qt=async t=>fe(`/api/v1/default-replies/${t}/clear-records`,{}),Oe=()=>({submitting:!1,result:"idle"}),qe=t=>t.submitting?t:{submitting:!0,result:"idle"},Ve=(t,a)=>({submitting:!1,result:a?"success":"failure"}),rt=t=>t+1,Be=(t,a,i,u)=>t===a&&i===u,Yt=t=>{const[a,i]=o.useState([]),[u,r]=o.useState({runs:[],pending_tasks:[]}),[y,A]=o.useState([]),[C,m]=o.useState({}),[I,T]=o.useState([]),[J,w]=o.useState([]),[G,F]=o.useState([]),[v,X]=o.useState(!1),q=o.useRef(0),re=o.useRef(0),[Q,K]=o.useState(0),[le,Y]=o.useState(0),[V,H]=o.useState({}),U=o.useCallback(async()=>{const P=Promise.all([Ft(),ot(),dt(),at()]),[_,j,D,ee]=await P;T(_),w(j),F(D),m(ee),t.setSelectedAccountId(ne=>{var E;return ne||((E=_[0])==null?void 0:E.id)||""})},[t.setSelectedAccountId]),n=o.useCallback(async()=>{var ee;const P=rt(q.current);q.current=P;const _=Ot().catch(ne=>(console.warn("加载自动化异常列表失败,不阻断规则展示",ne),null)),j=await Tt({cookieId:t.selectedAccountId||void 0,triggerType:t.automationTriggerFilter,enabled:t.automationStatusFilter==="all"?void 0:t.automationStatusFilter==="enabled",search:t.debouncedAutomationSearch,page:t.automationPage,pageSize:t.automationPageSize});if(!Be(P,q.current,t.selectedAccountId,t.selectedAccountId))return;i(j.data),K(j.total),Y(j.total_pages),H(j.trigger_counts||{}),j.page!==t.automationPage&&((ee=t.onAutomationPageChange)==null||ee.call(t,j.page));const D=await _;Be(P,q.current,t.selectedAccountId,t.selectedAccountId)&&D&&r(D)},[t.automationPage,t.automationPageSize,t.automationStatusFilter,t.automationTriggerFilter,t.debouncedAutomationSearch,t.onAutomationPageChange,t.selectedAccountId]),$=o.useCallback(async()=>{const P=rt(re.current);re.current=P;const _=t.selectedAccountId;if(A([]),!_)return;const j=await Gt(_);Be(P,re.current,_,t.selectedAccountId)&&A(j)},[t.selectedAccountId]),R=o.useCallback(async()=>{m(await at())},[]),z=o.useCallback(async()=>{X(!0);try{t.activeTab==="automation"?await n():t.activeTab==="reply"?await $():await R()}finally{X(!1)}},[n,R,$,t.activeTab]);return{automationRules:a,automationIssues:u,replyRules:y,defaultReplies:C,accounts:I,cards:J,items:G,automationTotal:Q,automationTotalPages:le,automationTriggerCounts:V,loading:v,setLoading:X,setAutomationRules:i,setCards:w,setItems:F,loadReferenceData:U,loadAutomationRules:n,loadReplyRules:$,loadDefaultReplies:R,refresh:z}},ae={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Nt},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:vt},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:it}},Se=["order_paid","buyer_reviewed","review_missing_timeout"],Ht="亲,商品使用满意的话,麻烦给个评价,谢谢~",he=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),mt=t=>{if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}},ce=(t,a={})=>{const i=mt(t);return JSON.stringify({after_shipped_hours:Number(i.after_shipped_hours||72),repeat_interval_hours:Number(i.repeat_interval_hours||24),max_attempts:Number(i.max_attempts||1),...a})},ye=(t,a)=>{var u;const i=((u=ae[t])==null?void 0:u.label)||"自动化规则";return a?`${i} - ${a}`:i},lt=t=>{const a=(t||"").trim();return a?Object.values(ae).some(i=>a===i.label||a.startsWith(`${i.label} -`)):!0},_e=(t,a=0)=>{if(t==="review_missing_timeout")return[{action_type:"send_text",message_template:Ht,enabled:!0,sort_order:1}];const i={action_type:"send_card",card_id:a,delivery_count:1,enabled:!0,sort_order:1};return t==="order_paid"?[i,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[i]},es=t=>{var i,u;if(t.trigger_type==="review_missing_timeout")return((u=(i=t.actions)==null?void 0:i.find(r=>r.action_type==="send_text"))==null?void 0:u.message_template)||"发送求评价文案";const a=(t.actions||[]).filter(r=>r.action_type==="send_card");return a.length?a.map(r=>r.card_name||`卡密 ${r.card_id}`).join(" / "):"未配置卡密库存"},nt=(t,a=!1)=>{const i={blue:a?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:a?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:a?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return i[t]||i.blue},ts=t=>t?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Re=t=>(t==null?void 0:t.nickname)||(t==null?void 0:t.remark)||(t==null?void 0:t.id)||"未知账号",ss=t=>t===!0||t===1||t==="1",as=({selectedAccountId:t,setSelectedAccountId:a,setActiveTab:i,items:u,setAutomationRules:r,setCards:y,setItems:A,setLoading:C,loadAutomationRules:m,loadReferenceData:I,loadReplyRules:T,loadDefaultReplies:J,initialDeliveryTarget:w,onDeliveryTargetHandled:G})=>{var xe;const[F,v]=o.useState(!1),[X,q]=o.useState(!1),[re,Q]=o.useState(!1),[K,le]=o.useState(Oe),[Y,V]=o.useState(Oe),[H,U]=o.useState(Oe),[n,$]=o.useState(null),[R,z]=o.useState(null),[M,P]=o.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),_=o.useMemo(()=>n!=null&&n.cookie_id&&n.item_id?u.find(l=>l.cookie_id===n.cookie_id&&l.item_id===n.item_id):void 0,[n==null?void 0:n.cookie_id,n==null?void 0:n.item_id,u]),j=ss(_==null?void 0:_.is_multi_spec),D=(n==null?void 0:n.trigger_type)||"order_paid",ee=ae[D],ne=mt(n==null?void 0:n.config_json),E=(xe=n==null?void 0:n.variants)!=null&&xe.length?n.variants:[he()],W=o.useCallback((l="order_paid",d=t,b="")=>{const p=u.find(N=>N.cookie_id===d&&N.item_id===b),h=(p==null?void 0:p.item_title)||b;return{name:ye(l,h),trigger_type:l,cookie_id:d,item_id:b,item_title:(p==null?void 0:p.item_title)||"",item_keyword:h,card_group_id:0,priority:100,enabled:!0,config_json:l==="review_missing_timeout"?ce():"{}",actions:_e(l),variants:l==="review_missing_timeout"?[]:[he()]}},[u,t]),ue=o.useCallback(l=>{var b,p;const d=l.trigger_type||"order_paid";$({...l,trigger_type:d,config_json:d==="review_missing_timeout"?ce(l.config_json):l.config_json||"{}",actions:(b=l.actions)!=null&&b.length?l.actions.map(h=>({...h})):_e(d,l.card_group_id),variants:(p=l.variants)!=null&&p.length?l.variants.map(h=>({...h})):d==="review_missing_timeout"?[]:[he()]}),v(!0)},[]);o.useEffect(()=>{if(!w)return;let l=!1;return(async()=>{i("automation"),a(w.cookieId),C(!0);try{const[b,p,h]=await Promise.all([Dt(),dt(),ot().catch(f=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",f),[]))]);if(l)return;r(b),A(p),y(h);const N=b.find(f=>f.cookie_id===w.cookieId&&f.item_id===w.itemId&&f.trigger_type==="order_paid");if(N)ue(N);else{const f=p.find(B=>B.cookie_id===w.cookieId&&B.item_id===w.itemId);$({...W("order_paid",w.cookieId,w.itemId),item_title:(f==null?void 0:f.item_title)||"",item_keyword:(f==null?void 0:f.item_title)||w.itemId,name:ye("order_paid",(f==null?void 0:f.item_title)||w.itemId)}),v(!0)}}catch(b){console.error("打开商品自动化规则失败",b),alert("无法加载该商品的自动化规则")}finally{l||(C(!1),G==null||G())}})(),(()=>{l=!0})},[W,w,G,ue,i,r,y,A,C,a]);const $e=o.useCallback((l="order_paid")=>{if(!t){alert("请先选择账号");return}$(W(l)),v(!0)},[W,t]),je=o.useCallback(l=>{var p,h,N,f,B;if(!n)return;const d=((h=(p=n.variants)==null?void 0:p.find(se=>se.card_id))==null?void 0:h.card_id)||((f=(N=n.actions)==null?void 0:N.find(se=>se.action_type==="send_card"))==null?void 0:f.card_id)||n.card_group_id||0,b=(_==null?void 0:_.item_title)||n.item_title||n.item_id||"";$({...n,trigger_type:l,name:lt(n.name)?ye(l,b):n.name,card_group_id:d,config_json:l==="review_missing_timeout"?ce(n.config_json):"{}",actions:_e(l,d),variants:l==="review_missing_timeout"?[]:(B=n.variants)!=null&&B.length?n.variants:[{...he(),card_id:d}]})},[n,_]),Me=o.useCallback(l=>{if(!n)return;const d=u.find(p=>p.cookie_id===(n.cookie_id||t)&&p.item_id===l),b=(d==null?void 0:d.item_title)||l;$({...n,item_id:l,item_title:(d==null?void 0:d.item_title)||"",item_keyword:b,name:lt(n.name)?ye(D,b):n.name})},[D,n,u,t]),pe=o.useCallback((l,d)=>{var p;if(!n)return;const b=E.map((h,N)=>N===l?{...h,...d}:h);$({...n,variants:b,card_group_id:((p=b[0])==null?void 0:p.card_id)||0})},[E,n]),Pe=o.useCallback(()=>{if(!n)return;const l=E[E.length-1];$({...n,variants:[...E,{...he(),spec_name:j&&(l==null?void 0:l.spec_name)||"",spec_value:j&&(l==null?void 0:l.spec_value)||""}]})},[E,n,j]),ve=o.useCallback(async()=>{var h,N,f,B,se;if(!n||K.submitting)return;const l=n.trigger_type||"order_paid";if(!n.cookie_id)return alert("请选择账号");const d=(h=n.variants)!=null&&h.length?n.variants:[];if(l!=="review_missing_timeout"){if(!d.length||d.some(k=>!k.card_id))return alert(l==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");if(j&&d.some(k=>!k.spec_name.trim()||!k.spec_value.trim()))return alert("多规格商品必须填写每一行的规格名称和规格值")}if(l==="review_missing_timeout"&&!(((f=(N=n.actions)==null?void 0:N.find(Le=>Le.action_type==="send_text"))==null?void 0:f.message_template)||"").trim())return alert("请填写求评价文案");const b=l==="review_missing_timeout"?[]:d.map(k=>({...k,spec_name:j?k.spec_name.trim():"",spec_value:j?k.spec_value.trim():"",delivery_count:Math.max(1,Number(k.delivery_count)||1),enabled:k.enabled!==!1}));le(qe(K));let p=!1;try{await st({...n,trigger_type:l,name:(n.name||"").trim()||ye(l,(_==null?void 0:_.item_title)||n.item_id||""),config_json:l==="review_missing_timeout"?ce(n.config_json):n.config_json||"{}",actions:(B=n.actions)!=null&&B.length?n.actions:_e(l,((se=b[0])==null?void 0:se.card_id)||n.card_group_id||0),variants:b}),v(!1),await Promise.all([m(),I()]),alert("保存成功"),p=!0}catch(k){console.error("保存自动化规则失败:",k),alert("保存失败:"+k.message)}finally{le(k=>Ve(k,p))}},[K,n,j,m,I,_]),g=o.useCallback(async l=>{if(confirm("确定删除该自动化规则吗?"))try{await Et(l),await m(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[m]),O=o.useCallback(async l=>{try{await st({...l,enabled:!l.enabled}),await m()}catch(d){alert("操作失败:"+d.message)}},[m]),S=o.useCallback(async(l,d)=>{if(confirm(d==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":d==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await qt(l,d),await m()}catch(p){alert("处理失败:"+p.message)}},[m]),te=o.useCallback(async(l,d)=>{if(confirm(d==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Vt(l,d),await m()}catch(b){alert("处理失败:"+b.message)}},[m]),L=o.useCallback(()=>{if(!t)return alert("请先选择账号");z({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),q(!0)},[t]),ie=o.useCallback(async()=>{var b,p,h;if(!R||!t||Y.submitting)return;const l=R.type==="image"?!!((b=R.image_url)!=null&&b.trim()):!!((p=R.reply_content)!=null&&p.trim());if(!((h=R.keyword)!=null&&h.trim())||!l)return alert("请填写关键词和回复内容");V(qe(Y));let d=!1;try{await Kt({...R,match_type:"fuzzy",enabled:!0},t),q(!1),await T(),alert("保存成功"),d=!0}catch(N){alert("保存失败:"+N.message)}finally{V(N=>Ve(N,d))}},[R,T,Y,t]),ge=o.useCallback(async l=>{if(!(!t||!confirm("确定删除该回复规则吗?")))try{await Ut(l,t),await T(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[T,t]),oe=o.useCallback(async(l=t)=>{if(!l)return alert("请先选择账号");try{const d=await Wt(l);P({cookie_id:l,enabled:d.enabled,reply_content:d.reply_content,reply_once:d.reply_once,reply_image_url:d.reply_image_url||""})}catch{P({cookie_id:l,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}Q(!0)},[t]),me=o.useCallback(async()=>{if(H.submitting)return;if(!M.cookie_id)return alert("请先选择账号");if(M.enabled&&!M.reply_content.trim()&&!M.reply_image_url.trim())return alert("启用默认回复时,请填写回复内容或图片 URL");U(qe(H));let l=!1;try{await Zt(M.cookie_id,{enabled:M.enabled,reply_content:M.reply_content,reply_once:M.reply_once,reply_image_url:M.reply_image_url}),Q(!1),await J(),alert("保存成功"),l=!0}catch(d){alert("保存失败:"+d.message)}finally{U(d=>Ve(d,l))}},[M,H,J]),Ne=o.useCallback(async l=>{if(confirm("确定删除该账号默认回复吗?"))try{await Xt(l),await J(),alert("删除成功")}catch(d){alert("删除失败:"+d.message)}},[J]),be=o.useCallback(async l=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await Qt(l),alert("清空成功")}catch(d){alert("清空失败:"+d.message)}},[]);return{showAutomationModal:F,setShowAutomationModal:v,showReplyModal:X,setShowReplyModal:q,showDefaultModal:re,setShowDefaultModal:Q,automationSubmitState:K,replySubmitState:Y,defaultReplySubmitState:H,editingAutomationRule:n,setEditingAutomationRule:$,editingReplyRule:R,setEditingReplyRule:z,defaultForm:M,setDefaultForm:P,selectedRuleItem:_,isMultiSpecRule:j,currentTrigger:D,currentMeta:ee,reviewConfig:ne,displayVariants:E,buildAutomationDraft:W,openAutomationRule:ue,openNewAutomationRule:$e,handleTriggerChange:je,handleAutomationItemChange:Me,updateVariant:pe,appendDeliveryContent:Pe,handleSaveAutomationRule:ve,handleDeleteAutomation:g,handleToggleAutomation:O,handleResolveRunIssue:S,handleResolveDeferredIssue:te,handleAddReplyRule:L,handleSaveReplyRule:ie,handleDeleteReply:ge,openDefaultReplyModal:oe,handleSaveDefaultReply:me,handleDeleteDefaultReply:Ne,handleClearDefaultReplyRecords:be}},os=({initialDeliveryTarget:t,onDeliveryTargetHandled:a})=>{var Xe,Qe;const[i,u]=o.useState("automation"),[r,y]=o.useState(""),[A,C]=o.useState(""),[m,I]=o.useState(""),[T,J]=o.useState(""),[w,G]=o.useState("all"),[F,v]=o.useState(1),[X,q]=o.useState(10),re=Yt({activeTab:i,selectedAccountId:r,automationTriggerFilter:T,automationStatusFilter:w,debouncedAutomationSearch:m,automationPage:F,automationPageSize:X,setSelectedAccountId:y,onAutomationPageChange:v}),{automationRules:Q,automationIssues:K,replyRules:le,defaultReplies:Y,accounts:V,cards:H,items:U,loading:n,setLoading:$,automationTotal:R,automationTotalPages:z,automationTriggerCounts:M,setAutomationRules:P,setCards:_,setItems:j,loadReferenceData:D,loadAutomationRules:ee,loadReplyRules:ne,loadDefaultReplies:E,refresh:W}=re,ue=as({selectedAccountId:r,setSelectedAccountId:y,setActiveTab:u,items:U,setAutomationRules:P,setCards:_,setItems:j,setLoading:$,loadAutomationRules:ee,loadReferenceData:D,loadReplyRules:ne,loadDefaultReplies:E,initialDeliveryTarget:t,onDeliveryTargetHandled:a}),{showAutomationModal:$e,setShowAutomationModal:je,showReplyModal:Me,setShowReplyModal:pe,showDefaultModal:Pe,setShowDefaultModal:ve,editingAutomationRule:g,setEditingAutomationRule:O,editingReplyRule:S,setEditingReplyRule:te,defaultForm:L,setDefaultForm:ie,selectedRuleItem:ge,isMultiSpecRule:oe,currentTrigger:me,currentMeta:Ne,reviewConfig:be,displayVariants:xe,openAutomationRule:l,openNewAutomationRule:d,handleTriggerChange:b,handleAutomationItemChange:p,updateVariant:h,appendDeliveryContent:N,handleSaveAutomationRule:f,handleDeleteAutomation:B,handleToggleAutomation:se,handleResolveRunIssue:k,handleResolveDeferredIssue:Le,handleAddReplyRule:xt,handleSaveReplyRule:ut,handleDeleteReply:pt,openDefaultReplyModal:We,handleSaveDefaultReply:gt,handleDeleteDefaultReply:bt,handleClearDefaultReplyRecords:ht}=ue;o.useEffect(()=>{const s=window.setTimeout(()=>{v(1),I(A.trim())},300);return(()=>window.clearTimeout(s))},[A]),o.useEffect(()=>{D().catch(s=>console.error("加载规则参考数据失败",s))},[D]),o.useEffect(()=>{W().catch(s=>console.error("刷新规则页面失败",s))},[W]);const Ie=o.useMemo(()=>Q.filter(s=>!r||s.cookie_id===r),[Q,r]),we=o.useMemo(()=>Pt(K,r),[K,r]),Ze=o.useMemo(()=>V.filter(s=>!r||s.id===r),[V,r]),yt=o.useMemo(()=>{if(z<=1)return[];const s=Math.max(1,Math.min(F-2,z-4)),c=Math.min(z,s+4);return Array.from({length:c-s+1},(x,de)=>s+de)},[F,z]),Fe=!!(A.trim()||T||w!=="all"),_t=()=>{C(""),I(""),J(""),G("all"),v(1)},ft=o.useMemo(()=>{const s=(g==null?void 0:g.cookie_id)||r;return U.filter(c=>c.cookie_id===s)},[g==null?void 0:g.cookie_id,U,r]),jt=i==="automation"?"新建自动化":i==="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:r,onChange:(s=>{y(s.target.value),v(1)}),className:"ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]}),e.jsxs("button",{onClick:W,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(Te,{className:`w-4 h-4 ${n?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:i==="automation"?(()=>d("order_paid")):i==="reply"?xt:(()=>void We()),disabled:!r,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(Ye,{className:"w-4 h-4"}),jt]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:He},{id:"reply",label:"关键词回复",icon:wt},{id:"default",label:"账号默认回复",icon:et}].map(s=>{const c=s.icon;return e.jsxs("button",{onClick:(()=>u(s.id)),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${i===s.id?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(c,{className:"w-4 h-4"}),s.label]},s.id)})}),i==="automation"&&(we.runs.length>0||we.pending_tasks.length>0)&&e.jsx(It,{runs:we.runs,pendingTasks:we.pending_tasks,onResolveRun:((s,c)=>void k(s,c)),onResolveDeferredTask:((s,c)=>void Le(s,c))}),i==="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:Se.map(s=>{const c=ae[s],x=c.icon;return e.jsx("button",{type:"button",onClick:(()=>d(s)),className:`w-full text-left rounded-2xl border p-4 transition-colors ${nt(c.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(x,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:c.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:c.description})]})]})},s)})})]}),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:["共 ",R," 条"]})]}),e.jsx("div",{className:"space-y-3",children:Se.map(s=>{const c=ae[s],x=c.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(x,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:c.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:M[s]||0})]},s)})})]})]}),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(kt,{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:A,onChange:(s=>{C(s.target.value),v(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(Ct,{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:(s=>{J(s.target.value),v(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:"全部自动化类型"}),Se.map(s=>e.jsx("option",{value:s,children:ae[s].shortLabel},s))]})]}),e.jsxs("select",{"aria-label":"按启用状态筛选",value:w,onChange:(s=>{G(s.target.value),v(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:"已禁用"})]}),Fe&&e.jsx("button",{type:"button",onClick:_t,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(ke,{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:["找到 ",R," 条规则"]}),n&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Te,{className:"h-3.5 w-3.5 animate-spin"}),"正在更新"]})]})]}),n&&Ie.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(Te,{className:"mr-2 h-4 w-4 animate-spin"}),"正在加载规则"]}):Ie.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(He,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:Fe?"没有匹配的自动化规则":"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:Fe?"调整或清除筛选条件后再试。":"从左侧选择一个模板开始配置。"})]}):Ie.map(s=>{const c=ae[s.trigger_type],x=c.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 ${nt(c.accent,!0)}`,children:e.jsx(x,{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:s.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${ts(s.enabled)}`,children:s.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:c.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:s.item_title||s.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:es(s)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:(()=>l(s)),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(ze,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:(()=>se(s)),className:`px-4 py-2 rounded-xl text-sm font-bold ${s.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:s.enabled?"禁用":"启用"}),e.jsx("button",{onClick:(()=>B(s.id)),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ce,{className:"w-4 h-4"})})]})]})},s.id)}),R>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:["第 ",F," / ",Math.max(z,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:X,onChange:(s=>{q(Number(s.target.value)),v(1)}),className:"ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm",children:[10,20,50].map(s=>e.jsxs("option",{value:s,children:[s," 条/页"]},s))})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button",disabled:F<=1||n,onClick:(()=>v(s=>Math.max(1,s-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(St,{className:"h-4 w-4"})}),yt.map(s=>e.jsx("button",{type:"button",disabled:n,onClick:(()=>v(s)),className:`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${s===F?"bg-brand text-white":"bg-gray-50 text-gray-600 hover:bg-gray-100"} disabled:cursor-not-allowed disabled:opacity-60`,"aria-label":`第 ${s} 页`,"aria-current":s===F?"page":void 0,children:s},s)),e.jsx("button",{type:"button",disabled:F>=z||n,onClick:(()=>v(s=>Math.min(z,s+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(Rt,{className:"h-4 w-4"})})]})]})]})]}),i==="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(Je,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[le.map(s=>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:["“",s.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:s.type==="image"&&s.image_url?s.image_url:s.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:(()=>{te({...s}),pe(!0)}),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>pt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]},s.id)),le.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),i==="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(Je,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[Ze.map(s=>{const c=Y[s.id],x=!!(c!=null&&c.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 ${x?"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 ${x?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(et,{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:Re(s)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${x?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:x?"已启用":"未启用"}),(c==null?void 0:c.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:x?c.reply_content||c.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 We(s.id)),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(ze,{className:"w-4 h-4"})}),x&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:(()=>void ht(s.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 bt(s.id)),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ce,{className:"w-5 h-5"})})]})]})]},s.id)}),Ze.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),$e&&g&&De.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:g.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:Ne.description})]}),e.jsx("button",{onClick:(()=>je(!1)),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(ke,{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:Se.map(s=>{const c=ae[s],x=c.icon,de=me===s;return e.jsx("button",{type:"button",onClick:(()=>b(s)),className:`w-full rounded-2xl p-4 text-left border transition-all ${de?"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(x,{className:`w-5 h-5 mt-0.5 ${de?"text-brand":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:c.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${de?"text-gray-500":"text-gray-400"}`,children:c.description})]})]})},s)})}),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:Ne.flow.map((s,c)=>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:c+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:s})]},s))})]})]}),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(At,{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:g.name||"",onChange:(s=>O({...g,name:s.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:g.cookie_id||"",onChange:(s=>O({...g,cookie_id:s.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:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:g.item_id||"",onChange:(s=>p(s.target.value)),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ft.map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.item_id}`))]})]})]}),ge&&me!=="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:ge.item_title||ge.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${oe?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:oe?"多规格商品":"普通商品"}),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:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),me!=="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($t,{className:"w-5 h-5 text-brand"}),e.jsx("h4",{className:"font-black text-gray-900",children:me==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:oe?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:N,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(Ye,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:xe.map((s,c)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${oe?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[oe&&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:s.spec_name,onChange:(x=>h(c,{spec_name:x.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:s.spec_value,onChange:(x=>h(c,{spec_value:x.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:s.card_id||"",onChange:(x=>h(c,{card_id:Number(x.target.value)})),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),H.filter(x=>x.enabled&&x.type!=="api").map(x=>e.jsx("option",{value:x.id,children:x.name},x.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:s.delivery_count,onChange:(x=>h(c,{delivery_count:Math.max(1,Number(x.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:s.delay_override===!0,onChange:(x=>h(c,{delay_override:x.target.checked})),className:"accent-brand"}),"覆盖卡密默认延时"]}),s.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:s.delay_seconds||0,onChange:(x=>h(c,{delay_seconds:Math.max(0,Number(x.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:s.delay_override?`本动作延时 ${s.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:xe.length===1,onClick:(()=>O({...g,variants:xe.filter((x,de)=>de!==c)})),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(Ce,{className:"w-4 h-4"})})]},s.id||c))})]}):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(it,{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(be.after_shipped_hours||72),onChange:(s=>O({...g,config_json:ce(g.config_json,{after_shipped_hours:Math.max(1,Number(s.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(be.repeat_interval_hours||24),onChange:(s=>O({...g,config_json:ce(g.config_json,{repeat_interval_hours:Math.max(1,Number(s.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(be.max_attempts||1),onChange:(s=>O({...g,config_json:ce(g.config_json,{max_attempts:Math.max(1,Number(s.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:((Qe=(Xe=g.actions)==null?void 0:Xe.find(s=>s.action_type==="send_text"))==null?void 0:Qe.message_template)||"",onChange:(s=>{var c;return O({...g,actions:((c=g.actions)!=null&&c.length?g.actions:_e("review_missing_timeout")).map(x=>x.action_type==="send_text"?{...x,message_template:s.target.value}:x)})}),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:g.priority||100,onChange:(s=>O({...g,priority:Number(s.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:g.enabled!==!1,onChange:(s=>O({...g,enabled:s.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:(()=>je(!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:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Me&&S&&De.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:S.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:(()=>pe(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{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:S.item_id||"",onChange:(s=>te({...S,item_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),U.filter(s=>!r||s.cookie_id===r).map(s=>e.jsx("option",{value:s.item_id,children:s.item_title||s.item_id},`${s.cookie_id}-${s.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:S.type||"text",onChange:(s=>{const c=s.target.value;te({...S,type:c,reply_content:c==="text"?S.reply_content:"",image_url:c==="image"?S.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:S.keyword||"",onChange:(s=>te({...S,keyword:s.target.value})),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),S.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:S.image_url||"",onChange:(s=>te({...S,image_url:s.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:S.reply_content||"",onChange:(s=>te({...S,reply_content:s.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:(()=>pe(!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:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Pe&&De.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:(()=>ve(!1)),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(ke,{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:L.cookie_id,onChange:(s=>ie({...L,cookie_id:s.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),V.map(s=>e.jsx("option",{value:s.id,children:Re(s)},s.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:(()=>ie({...L,enabled:!L.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${L.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 ${L.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:L.reply_content,onChange:(s=>ie({...L,reply_content:s.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:L.reply_image_url,onChange:(s=>ie({...L,reply_image_url:s.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:L.reply_once,onChange:(s=>ie({...L,reply_once:s.target.checked})),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:(()=>ve(!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:gt,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})};export{os as default}; diff --git a/internal/webui/static/assets/Rules-MPWRzM5C.js b/internal/webui/static/assets/Rules-MPWRzM5C.js deleted file mode 100644 index 0377a12..0000000 --- a/internal/webui/static/assets/Rules-MPWRzM5C.js +++ /dev/null @@ -1 +0,0 @@ -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-5xhSVKHU.js b/internal/webui/static/assets/Settings-5xhSVKHU.js deleted file mode 100644 index 39e19ec..0000000 --- a/internal/webui/static/assets/Settings-5xhSVKHU.js +++ /dev/null @@ -1 +0,0 @@ -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/Settings-fa7In0jk.js b/internal/webui/static/assets/Settings-fa7In0jk.js new file mode 100644 index 0000000..06da5dc --- /dev/null +++ b/internal/webui/static/assets/Settings-fa7In0jk.js @@ -0,0 +1 @@ +import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-CFzx5gQT.js";import{f as ue,R as se,aa as pe,p as me,u as R,v as O,ab as he,s as ge,S as te,ac as ae,ad as ye,r as fe}from"./icons-vendor-CvzvbbIV.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=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"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=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?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[U,q]=r.useState(!1),[z,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(g){if(!f(m.current,i,l.signal)||D(g))return;y(T("error",K(g,"登录凭据更新失败")))}finally{f(m.current,i,l.signal)&&_(!1)}},[E,t]);return{settings:s,loading:o,loadError:h,saving:S,saveError:P,aiModels:C,modelsLoading:j,modelError:M,modelDropdownOpen:$,showApiKey:U,showCaptchaSecret:z,showCurrentPassword:b,showNewPassword:G,credentialsSaving:Y,credentialsMessage:L,credentials:t,requestStatus:ce,modelPickerRef:Z,loadSettings:H,loadAIModels:((n,c)=>void B(n,c)),handleSave:ie,handleCredentialsSave:de,setSettings:a,setModelDropdownOpen:v,setShowApiKey:q,setShowCaptchaSecret:u,setShowCurrentPassword:F,setShowNewPassword:V,setCredentials:X,setCredentialsMessage:y}},Re=()=>{const{settings:s,loading:a,loadError:o,saving:d,saveError:h,aiModels:p,modelsLoading:S,modelError:A,modelDropdownOpen:P,showApiKey:k,showCaptchaSecret:C,showCurrentPassword:w,showNewPassword:j,credentialsSaving:I,credentialsMessage:M,credentials:x,modelPickerRef:$,loadSettings:v,loadAIModels:U,handleSave:q,handleCredentialsSave:z,setSettings:u,setModelDropdownOpen:b,setShowApiKey:F,setShowCaptchaSecret:G,setShowCurrentPassword:V,setShowNewPassword:Y,setCredentials:_}=Me();if(!s)return e.jsxs("div",{className:"p-8 text-center text-gray-400 space-y-3",children:[o||(a?"加载配置中...":"暂无配置"),!a&&o&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:v,children:"重新加载"})})]});const L=s.ai_model||"",y=p;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(ue,{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:v,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"}),"刷新"]})]}),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:(()=>{}),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(pe,{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=>u({...s,log_level:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:be.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=>u({...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=>u({...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(me,{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||ne,onChange:(t=>u({...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:k?"text":"password",value:s.ai_api_key||"",onChange:(t=>u({...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(!k)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:k?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{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:L,onFocus:(()=>p.length>0&&b(!0)),onChange:(t=>{u({...s,ai_model:t.target.value}),p.length>0&&b(!0)}),onKeyDown:(t=>{t.key==="Escape"&&b(!1),t.key==="ArrowDown"&&p.length>0&&b(!0)}),className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:(()=>p.length>0&&b(t=>!t)),disabled:p.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(he,{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:y.length>0?y.map(t=>e.jsxs("button",{type:"button",onClick:(()=>{u({...s,ai_model:t}),b(!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===L&&e.jsx(ge,{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:S,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 ${S?"animate-spin":""}`}),"读取模型"]})]}),A?e.jsx("p",{className:"text-xs text-red-500",children:A}):e.jsx("p",{className:"text-xs text-gray-500",children:p.length>0?`已从当前 API 地址读取到 ${p.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=>u({...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:C?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:(t=>u({...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(!C)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:C?"隐藏秘钥":"显示秘钥",children:C?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{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=>u({...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(ye,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:x.new_username,onChange:(t=>_({...x,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:w?"text":"password",value:x.current_password,onChange:(t=>_({...x,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:(()=>V(!w)),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:w?"隐藏密码":"显示密码",children:w?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{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:j?"text":"password",value:x.new_password,onChange:(t=>_({...x,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:(()=>Y(!j)),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:j?"隐藏密码":"显示密码",children:j?e.jsx(R,{className:"w-4 h-4"}):e.jsx(O,{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:j?"text":"password",value:x.confirm_password,onChange:(t=>_({...x,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:I||!x.new_username||!x.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"}),I?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:q,disabled:d,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"}),d?"保存中...":"保存所有配置"]})})]})};export{Re as default}; diff --git a/internal/webui/static/assets/contract-COFcZjyb.js b/internal/webui/static/assets/contract-COFcZjyb.js new file mode 100644 index 0000000..35184fc --- /dev/null +++ b/internal/webui/static/assets/contract-COFcZjyb.js @@ -0,0 +1 @@ +const a=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),i=(t,s=["data","items","results"])=>{let r=t,e=0;for(;e<2;e+=1){if(Array.isArray(r))return r;if(!a(r))return[];for(const n of s){const c=r[n];if(Array.isArray(c))return c;if(c===null)return[]}const o=r.data;if(a(o)){r=o;continue}return[]}return[]},d=(t,s=["data","result"])=>{let r=t,e=0;for(;e<2;e+=1){if(!a(r))return;for(const o of s){const n=r[o];if(a(n))return n}return r}};export{i as c,d as o}; diff --git a/internal/webui/static/assets/icons-vendor-ThcsWkZG.js b/internal/webui/static/assets/icons-vendor-CvzvbbIV.js similarity index 99% rename from internal/webui/static/assets/icons-vendor-ThcsWkZG.js rename to internal/webui/static/assets/icons-vendor-CvzvbbIV.js index 35b8a1b..cf6f615 100644 --- a/internal/webui/static/assets/icons-vendor-ThcsWkZG.js +++ b/internal/webui/static/assets/icons-vendor-CvzvbbIV.js @@ -413,4 +413,4 @@ import{r as h}from"./react-vendor-C_od1ZSF.js";/** * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const F1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],_0=e("zap",F1);export{N2 as $,Z1 as A,Q1 as B,i2 as C,r2 as D,l2 as E,o0 as F,u2 as G,h0 as H,K2 as I,d0 as J,f2 as K,z2 as L,P2 as M,W2 as N,s0 as O,D2 as P,I2 as Q,O2 as R,X2 as S,y0 as T,i0 as U,c0 as V,q2 as W,M0 as X,x2 as Y,_0 as Z,n2 as _,K1 as a,v2 as a0,e0 as a1,k2 as a2,m2 as a3,B2 as a4,d2 as a5,o2 as a6,y2 as a7,b2 as a8,j2 as a9,p2 as aa,e2 as ab,A2 as ac,n0 as ad,h2 as ae,g2 as af,w2 as ag,G2 as ah,L2 as ai,p0 as aj,l0 as ak,r0 as al,X1 as am,a0 as an,$2 as ao,Q2 as b,t2 as c,a2 as d,V2 as e,C2 as f,H2 as g,J2 as h,k0 as i,Y2 as j,c2 as k,O1 as l,E2 as m,U2 as n,T2 as o,t0 as p,J1 as q,Z2 as r,Y1 as s,s2 as t,M2 as u,_2 as v,G1 as w,S2 as x,R2 as y,F2 as z}; + */const F1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],_0=e("zap",F1);export{N2 as $,Z1 as A,Q1 as B,i2 as C,r2 as D,l2 as E,o0 as F,u2 as G,h0 as H,K2 as I,d0 as J,f2 as K,C2 as L,P2 as M,W2 as N,s0 as O,D2 as P,I2 as Q,O2 as R,J2 as S,y0 as T,k0 as U,c0 as V,q2 as W,M0 as X,x2 as Y,_0 as Z,n2 as _,H2 as a,v2 as a0,e0 as a1,k2 as a2,m2 as a3,B2 as a4,d2 as a5,o2 as a6,y2 as a7,b2 as a8,j2 as a9,p2 as aa,e2 as ab,A2 as ac,n0 as ad,h2 as ae,g2 as af,w2 as ag,G2 as ah,L2 as ai,p0 as aj,l0 as ak,r0 as al,X1 as am,a0 as an,$2 as ao,z2 as b,i0 as c,X2 as d,K1 as e,Q2 as f,t2 as g,a2 as h,V2 as i,Y2 as j,c2 as k,O1 as l,E2 as m,U2 as n,T2 as o,t0 as p,J1 as q,Z2 as r,Y1 as s,s2 as t,M2 as u,_2 as v,G1 as w,S2 as x,R2 as y,F2 as z}; diff --git a/internal/webui/static/assets/index-1VXvcBKv.css b/internal/webui/static/assets/index-1VXvcBKv.css deleted file mode 100644 index 0fcbe39..0000000 --- a/internal/webui/static/assets/index-1VXvcBKv.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-1{top:-.25rem;right:-.25rem;bottom:-.25rem;left:-.25rem}.inset-0{top:0;right:0;bottom:0;left:0}.inset-y-0{top:0;bottom:0}.-right-6{right:-1.5rem}.-top-6{top:-1.5rem}.bottom-10{bottom:2.5rem}.bottom-11{bottom:2.75rem}.bottom-8{bottom:2rem}.bottom-\[-10\%\]{bottom:-10%}.left-0{left:0}.left-1{left:.25rem}.left-1\.5{left:.375rem}.left-1\/2{left:50%}.left-3{left:.75rem}.left-4{left:1rem}.left-5{left:1.25rem}.left-\[-10\%\]{left:-10%}.right-0{right:0}.right-10{right:2.5rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-\[-10\%\]{right:-10%}.top-0{top:0}.top-1{top:.25rem}.top-1\.5{top:.375rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-\[-10\%\]{top:-10%}.top-\[calc\(100\%\+6px\)\]{top:calc(100% + 6px)}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-\[10000\]{z-index:10000}.order-1{order:1}.col-span-2{grid-column:span 2 / span 2}.col-span-full{grid-column:1 / -1}.m-2{margin:.5rem}.mx-0\.5{margin-left:.125rem;margin-right:.125rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-10{margin-bottom:2.5rem}.mb-2{margin-bottom:.5rem}.mb-2\.5{margin-bottom:.625rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-auto{margin-left:auto}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.mt-auto{margin-top:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.line-clamp-3{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-80{height:20rem}.h-9{height:2.25rem}.h-\[18px\]{height:18px}.h-\[19px\]{height:19px}.h-\[280px\]{height:280px}.h-\[300px\]{height:300px}.h-\[350px\]{height:350px}.h-\[48px\]{height:48px}.h-\[60\%\]{height:60%}.h-\[calc\(100vh-4rem\)\]{height:calc(100vh - 4rem)}.h-auto{height:auto}.h-full{height:100%}.h-screen{height:100vh}.max-h-32{max-height:8rem}.max-h-44{max-height:11rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-72{max-height:18rem}.max-h-80{max-height:20rem}.max-h-\[380px\]{max-height:380px}.max-h-\[400px\]{max-height:400px}.max-h-\[420px\]{max-height:420px}.max-h-\[min\(64vh\,28rem\)\]{max-height:min(64vh,28rem)}.min-h-0{min-height:0px}.min-h-12{min-height:3rem}.min-h-36{min-height:9rem}.min-h-56{min-height:14rem}.min-h-\[120px\]{min-height:120px}.min-h-\[150px\]{min-height:150px}.min-h-\[400px\]{min-height:400px}.min-h-\[42px\]{min-height:42px}.min-h-\[46px\]{min-height:46px}.min-h-\[560px\]{min-height:560px}.min-h-screen{min-height:100vh}.w-1\.5{width:.375rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-28{width:7rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[18px\]{width:18px}.w-\[19\%\]{width:19%}.w-\[19px\]{width:19px}.w-\[23\%\]{width:23%}.w-\[27\%\]{width:27%}.w-\[360px\]{width:360px}.w-\[60\%\]{width:60%}.w-\[7\%\]{width:7%}.w-\[8\%\]{width:8%}.w-\[9\%\]{width:9%}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-5{min-width:1.25rem}.min-w-9{min-width:2.25rem}.min-w-\[150px\]{min-width:150px}.min-w-\[200px\]{min-width:200px}.min-w-\[210px\]{min-width:210px}.min-w-\[260px\]{min-width:260px}.min-w-\[760px\]{min-width:760px}.max-w-36{max-width:9rem}.max-w-6xl{max-width:72rem}.max-w-\[12rem\]{max-width:12rem}.max-w-\[15rem\]{max-width:15rem}.max-w-\[240px\]{max-width:240px}.max-w-\[260px\]{max-width:260px}.max-w-\[280px\]{max-width:280px}.max-w-\[340px\]{max-width:340px}.max-w-\[72\%\]{max-width:72%}.max-w-\[80px\]{max-width:80px}.max-w-\[82\%\]{max-width:82%}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.table-fixed{table-layout:fixed}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-6{--tw-translate-x: 1.5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-7{--tw-translate-x: 1.75rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-8{grid-template-columns:repeat(8,minmax(0,1fr))}.grid-cols-\[320px_minmax\(0\,1fr\)\]{grid-template-columns:320px minmax(0,1fr)}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-50>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(var(--color-neutral-50) / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-center{align-self:center}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.overscroll-contain{overscroll-behavior:contain}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:6px}.rounded-2xl,.rounded-3xl{border-radius:10px}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:7px}.rounded-md{border-radius:6px}.rounded-xl{border-radius:8px}.rounded-bl-md{border-bottom-left-radius:6px}.rounded-br-md{border-bottom-right-radius:6px}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-y{border-top-width:1px;border-bottom-width:1px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(var(--color-warning-200) / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-100) / var(--tw-border-opacity, 1))}.border-emerald-100{--tw-border-opacity: 1;border-color:rgb(var(--color-success-100) / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(var(--color-neutral-100) / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(var(--color-neutral-200) / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(var(--color-neutral-300) / var(--tw-border-opacity, 1))}.border-gray-50{--tw-border-opacity: 1;border-color:rgb(var(--color-neutral-50) / var(--tw-border-opacity, 1))}.border-purple-100{--tw-border-opacity: 1;border-color:rgb(var(--color-accent-100) / var(--tw-border-opacity, 1))}.border-red-100{--tw-border-opacity: 1;border-color:rgb(var(--color-danger-100) / var(--tw-border-opacity, 1))}.border-sky-100{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-100) / var(--tw-border-opacity, 1))}.border-sky-200{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-200) / var(--tw-border-opacity, 1))}.border-sky-500{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-500) / var(--tw-border-opacity, 1))}.border-slate-100{--tw-border-opacity: 1;border-color:rgb(var(--color-slate-100) / var(--tw-border-opacity, 1))}.border-slate-200{--tw-border-opacity: 1;border-color:rgb(var(--color-slate-200) / var(--tw-border-opacity, 1))}.border-slate-200\/80{border-color:rgb(var(--color-slate-200) / .8)}.border-transparent{border-color:var(--color-transparent)}.border-white{--tw-border-opacity: 1;border-color:rgb(var(--color-white) / var(--tw-border-opacity, 1))}.border-white\/10{border-color:rgb(var(--color-white) / .1)}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-warning-100) / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-warning-50) / var(--tw-bg-opacity, 1))}.bg-amber-50\/70{background-color:rgb(var(--color-warning-50) / .7)}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-warning-500) / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(var(--color-black) / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:rgb(var(--color-black) / .5)}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-100) / var(--tw-bg-opacity, 1))}.bg-blue-200\/30{background-color:rgb(var(--color-brand-200) / .3)}.bg-blue-200\/40{background-color:rgb(var(--color-brand-200) / .4)}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-400) / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-50) / var(--tw-bg-opacity, 1))}.bg-blue-50\/50{background-color:rgb(var(--color-brand-50) / .5)}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-500) / var(--tw-bg-opacity, 1))}.bg-blue-500\/20{background-color:rgb(var(--color-brand-500) / .2)}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-600) / var(--tw-bg-opacity, 1))}.bg-brand{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand) / var(--tw-bg-opacity, 1))}.bg-canvas{--tw-bg-opacity: 1;background-color:rgb(var(--color-canvas) / var(--tw-bg-opacity, 1))}.bg-danger-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-danger-500) / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-50) / var(--tw-bg-opacity, 1))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-500) / var(--tw-bg-opacity, 1))}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-600) / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-100) / var(--tw-bg-opacity, 1))}.bg-gray-100\/50{background-color:rgb(var(--color-neutral-100) / .5)}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-200) / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-300) / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-50) / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-900) / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-100) / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-50) / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-500) / var(--tw-bg-opacity, 1))}.bg-pink-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-accent-50) / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-accent-100) / var(--tw-bg-opacity, 1))}.bg-purple-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-accent-50) / var(--tw-bg-opacity, 1))}.bg-purple-50\/50{background-color:rgb(var(--color-accent-50) / .5)}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-accent-500) / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(var(--color-accent-600) / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-danger-100) / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-danger-50) / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-danger-500) / var(--tw-bg-opacity, 1))}.bg-sky-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-100) / var(--tw-bg-opacity, 1))}.bg-sky-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-50) / var(--tw-bg-opacity, 1))}.bg-sky-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-500) / var(--tw-bg-opacity, 1))}.bg-slate-100{--tw-bg-opacity: 1;background-color:rgb(var(--color-slate-100) / var(--tw-bg-opacity, 1))}.bg-slate-200{--tw-bg-opacity: 1;background-color:rgb(var(--color-slate-200) / var(--tw-bg-opacity, 1))}.bg-slate-300{--tw-bg-opacity: 1;background-color:rgb(var(--color-slate-300) / var(--tw-bg-opacity, 1))}.bg-slate-50{--tw-bg-opacity: 1;background-color:rgb(var(--color-slate-50) / var(--tw-bg-opacity, 1))}.bg-slate-50\/40{background-color:rgb(var(--color-slate-50) / .4)}.bg-slate-50\/70{background-color:rgb(var(--color-slate-50) / .7)}.bg-slate-900{--tw-bg-opacity: 1;background-color:rgb(var(--color-slate-900) / var(--tw-bg-opacity, 1))}.bg-success-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-500) / var(--tw-bg-opacity, 1))}.bg-surface{--tw-bg-opacity: 1;background-color:rgb(var(--color-surface) / var(--tw-bg-opacity, 1))}.bg-surface-muted{--tw-bg-opacity: 1;background-color:rgb(var(--color-surface-muted) / var(--tw-bg-opacity, 1))}.bg-surface-subtle{--tw-bg-opacity: 1;background-color:rgb(var(--color-surface-subtle) / var(--tw-bg-opacity, 1))}.bg-transparent{background-color:var(--color-transparent)}.bg-white{--tw-bg-opacity: 1;background-color:rgb(var(--color-white) / var(--tw-bg-opacity, 1))}.bg-white\/5{background-color:rgb(var(--color-white) / .05)}.bg-white\/80{background-color:rgb(var(--color-white) / .8)}.bg-white\/90{background-color:rgb(var(--color-white) / .9)}.bg-white\/95{background-color:rgb(var(--color-white) / .95)}.bg-opacity-10{--tw-bg-opacity: .1}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-16{padding:4rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-3\.5{padding-left:.875rem;padding-right:.875rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-0{padding-bottom:0}.pb-1{padding-bottom:.25rem}.pb-24{padding-bottom:6rem}.pb-9{padding-bottom:2.25rem}.pl-10{padding-left:2.5rem}.pl-11{padding-left:2.75rem}.pl-14{padding-left:3.5rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-9{padding-left:2.25rem}.pr-10{padding-right:2.5rem}.pr-11{padding-right:2.75rem}.pr-12{padding-right:3rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-9{padding-right:2.25rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[13px\]{font-size:13px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-4{line-height:1rem}.leading-5{line-height:1.25rem}.leading-6{line-height:1.5rem}.leading-none{line-height:1}.leading-relaxed{line-height:1.625}.leading-tight{line-height:1.25}.tracking-\[0\.18em\]{letter-spacing:.18em}.tracking-\[0\.22em\]{letter-spacing:.22em}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-amber-600{--tw-text-opacity: 1;color:rgb(var(--color-warning-600) / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(var(--color-warning-700) / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(var(--color-warning-800) / var(--tw-text-opacity, 1))}.text-amber-900{--tw-text-opacity: 1;color:rgb(var(--color-warning-900) / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(var(--color-brand-600) / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(var(--color-brand-700) / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(var(--color-brand-800) / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(var(--color-brand-900) / var(--tw-text-opacity, 1))}.text-blue-950{--tw-text-opacity: 1;color:rgb(var(--color-brand-950) / var(--tw-text-opacity, 1))}.text-brand{--tw-text-opacity: 1;color:rgb(var(--color-brand) / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(var(--color-success-600) / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(var(--color-success-700) / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(var(--color-neutral-100) / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(var(--color-neutral-300) / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(var(--color-neutral-400) / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(var(--color-neutral-500) / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(var(--color-neutral-600) / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(var(--color-neutral-700) / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(var(--color-neutral-800) / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(var(--color-neutral-900) / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(var(--color-success-700) / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(var(--color-success-800) / var(--tw-text-opacity, 1))}.text-pink-600,.text-purple-600{--tw-text-opacity: 1;color:rgb(var(--color-accent-600) / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(var(--color-accent-700) / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(var(--color-danger-500) / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(var(--color-danger-600) / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(var(--color-danger-700) / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(var(--color-danger-800) / var(--tw-text-opacity, 1))}.text-sky-500{--tw-text-opacity: 1;color:rgb(var(--color-brand-500) / var(--tw-text-opacity, 1))}.text-sky-600{--tw-text-opacity: 1;color:rgb(var(--color-brand-600) / var(--tw-text-opacity, 1))}.text-sky-700{--tw-text-opacity: 1;color:rgb(var(--color-brand-700) / var(--tw-text-opacity, 1))}.text-sky-800{--tw-text-opacity: 1;color:rgb(var(--color-brand-800) / var(--tw-text-opacity, 1))}.text-sky-900{--tw-text-opacity: 1;color:rgb(var(--color-brand-900) / var(--tw-text-opacity, 1))}.text-slate-300{--tw-text-opacity: 1;color:rgb(var(--color-slate-300) / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(var(--color-slate-400) / var(--tw-text-opacity, 1))}.text-slate-500{--tw-text-opacity: 1;color:rgb(var(--color-slate-500) / var(--tw-text-opacity, 1))}.text-slate-600{--tw-text-opacity: 1;color:rgb(var(--color-slate-600) / var(--tw-text-opacity, 1))}.text-slate-700{--tw-text-opacity: 1;color:rgb(var(--color-slate-700) / var(--tw-text-opacity, 1))}.text-slate-800{--tw-text-opacity: 1;color:rgb(var(--color-slate-800) / var(--tw-text-opacity, 1))}.text-slate-900{--tw-text-opacity: 1;color:rgb(var(--color-slate-900) / var(--tw-text-opacity, 1))}.text-slate-950{--tw-text-opacity: 1;color:rgb(var(--color-slate-950) / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(var(--color-white) / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.accent-brand{accent-color:rgb(var(--color-brand) / 1)}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-25{opacity:.25}.opacity-30{opacity:.3}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: var(--shadow-2xl);--tw-shadow-colored: var(--shadow-2xl);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-brand-active{--tw-shadow: var(--shadow-brand-active);--tw-shadow-colored: var(--shadow-brand-active);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-chat{--tw-shadow: var(--shadow-chat);--tw-shadow-colored: var(--shadow-chat);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-chat-active{--tw-shadow: var(--shadow-chat-active);--tw-shadow-colored: var(--shadow-chat-active);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-chat-input{--tw-shadow: var(--shadow-chat-input);--tw-shadow-colored: var(--shadow-chat-input);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: var(--shadow-lg);--tw-shadow-colored: var(--shadow-lg);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: var(--shadow-md);--tw-shadow-colored: var(--shadow-md);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-panel{--tw-shadow: var(--shadow-panel);--tw-shadow-colored: var(--shadow-panel);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sidebar{--tw-shadow: var(--shadow-sidebar);--tw-shadow-colored: var(--shadow-sidebar);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: var(--shadow-sm);--tw-shadow-colored: var(--shadow-sm);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: var(--shadow-xl);--tw-shadow-colored: var(--shadow-xl);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-blue-100{--tw-shadow-color: rgb(var(--color-brand-100) / 1);--tw-shadow: var(--tw-shadow-colored)}.shadow-blue-200{--tw-shadow-color: rgb(var(--color-brand-200) / 1);--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-100{--tw-shadow-color: rgb(var(--color-success-100) / 1);--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200{--tw-shadow-color: rgb(var(--color-neutral-200) / 1);--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200\/70{--tw-shadow-color: rgb(var(--color-neutral-200) / .7);--tw-shadow: var(--tw-shadow-colored)}.shadow-sky-100{--tw-shadow-color: rgb(var(--color-brand-100) / 1);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-white{--tw-ring-opacity: 1;--tw-ring-color: rgb(var(--color-white) / var(--tw-ring-opacity, 1))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-2xl{--tw-blur: blur(40px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-\[120px\]{--tw-blur: blur(120px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-3xl{--tw-backdrop-blur: blur(64px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-xl{--tw-backdrop-blur: blur(24px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[width\]{transition-property:width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}:root{--color-transparent: transparent;--color-black: 0 0 0;--color-white: 255 255 255;--color-brand: 0 148 247;--color-brand-highlight: 0 113 227;--color-brand-light: 40 126 254;--color-ink: 29 29 31;--color-muted: 134 134 139;--color-line: 210 210 215;--color-canvas: 244 245 247;--color-surface: 255 255 255;--color-surface-subtle: 247 248 250;--color-surface-muted: 250 250 250;--color-neutral-50: 249 250 251;--color-neutral-100: 243 244 246;--color-neutral-200: 229 231 235;--color-neutral-300: 209 213 219;--color-neutral-400: 156 163 175;--color-neutral-500: 107 114 128;--color-neutral-600: 75 85 99;--color-neutral-700: 55 65 81;--color-neutral-800: 31 41 55;--color-neutral-900: 17 24 39;--color-neutral-950: 3 7 18;--color-slate-50: 248 250 252;--color-slate-100: 241 245 249;--color-slate-200: 226 232 240;--color-slate-300: 203 213 225;--color-slate-400: 148 163 184;--color-slate-500: 100 116 139;--color-slate-600: 71 85 105;--color-slate-700: 51 65 85;--color-slate-800: 30 41 59;--color-slate-900: 15 23 42;--color-slate-950: 2 6 23;--color-brand-50: 239 248 255;--color-brand-100: 223 241 255;--color-brand-200: 191 229 255;--color-brand-300: 143 210 255;--color-brand-400: 83 184 251;--color-brand-500: 0 148 247;--color-brand-600: 0 148 247;--color-brand-700: 0 113 227;--color-brand-800: 0 91 181;--color-brand-900: 0 75 147;--color-brand-950: 0 53 107;--color-success-50: 236 253 245;--color-success-100: 209 250 229;--color-success-200: 167 243 208;--color-success-300: 110 231 183;--color-success-400: 52 211 153;--color-success-500: 16 185 129;--color-success-600: 5 150 105;--color-success-700: 4 120 87;--color-success-800: 6 95 70;--color-success-900: 6 78 59;--color-success-950: 2 44 34;--color-warning-50: 255 251 235;--color-warning-100: 254 243 199;--color-warning-200: 253 230 138;--color-warning-300: 252 211 77;--color-warning-400: 251 191 36;--color-warning-500: 245 158 11;--color-warning-600: 217 119 6;--color-warning-700: 180 83 9;--color-warning-800: 146 64 14;--color-warning-900: 120 53 15;--color-warning-950: 69 26 3;--color-danger-50: 254 242 242;--color-danger-100: 254 226 226;--color-danger-200: 254 202 202;--color-danger-300: 252 165 165;--color-danger-400: 248 113 113;--color-danger-500: 239 68 68;--color-danger-600: 220 38 38;--color-danger-700: 185 28 28;--color-danger-800: 153 27 27;--color-danger-900: 127 29 29;--color-danger-950: 69 10 10;--color-info-50: 239 246 255;--color-info-100: 219 234 254;--color-info-200: 191 219 254;--color-info-300: 147 197 253;--color-info-400: 96 165 250;--color-info-500: 59 130 246;--color-info-600: 37 99 235;--color-info-700: 29 78 216;--color-info-800: 30 64 175;--color-info-900: 30 58 138;--color-info-950: 23 37 84;--color-accent-50: 250 245 255;--color-accent-100: 243 232 255;--color-accent-200: 233 213 255;--color-accent-300: 216 180 254;--color-accent-400: 192 132 252;--color-accent-500: 168 85 247;--color-accent-600: 147 51 234;--color-accent-700: 126 34 206;--color-accent-800: 107 33 168;--color-accent-900: 88 28 135;--color-accent-950: 59 7 100;--shadow-none: 0 0 0 var(--color-transparent);--shadow-default: 0 1px 3px 0 rgb(var(--color-black) / .1), 0 1px 2px -1px rgb(var(--color-black) / .1);--shadow-sm: 0 1px 2px 0 rgb(var(--color-black) / .05);--shadow-md: 0 4px 6px -1px rgb(var(--color-black) / .1), 0 2px 4px -2px rgb(var(--color-black) / .1);--shadow-lg: 0 10px 15px -3px rgb(var(--color-black) / .1), 0 4px 6px -4px rgb(var(--color-black) / .1);--shadow-xl: 0 20px 25px -5px rgb(var(--color-black) / .1), 0 8px 10px -6px rgb(var(--color-black) / .1);--shadow-2xl: 0 25px 50px -12px rgb(var(--color-black) / .25);--shadow-inner: inset 0 2px 4px 0 rgb(var(--color-black) / .05);--shadow-card: 0 8px 24px rgb(var(--color-black) / .04);--shadow-panel: 0 20px 60px -15px rgb(var(--color-black) / .05);--shadow-modal: 0 25px 50px -12px rgb(var(--color-black) / .25);--shadow-sidebar: 4px 0 24px rgb(var(--color-slate-900) / .035);--shadow-chat: 0 16px 45px rgb(var(--color-slate-900) / .06);--shadow-chat-input: 0 -8px 24px rgb(var(--color-slate-900) / .04);--shadow-chat-active: inset 3px 0 0 rgb(var(--color-brand));--shadow-brand-soft: 0 2px 8px rgb(var(--color-brand) / .2);--shadow-brand-active: 0 8px 18px rgb(var(--color-brand) / .2);--shadow-brand-strong: 0 8px 20px rgb(var(--color-brand) / .3)}*,:before,:after{--tw-ring-offset-color: rgb(var(--color-white));--tw-ring-color: rgb(var(--color-brand-400) / .5);--tw-ring-offset-shadow: 0 0 0 var(--color-transparent);--tw-ring-shadow: 0 0 0 var(--color-transparent);--tw-shadow: 0 0 0 var(--color-transparent);--tw-shadow-colored: 0 0 0 var(--color-transparent)}.squircle{-webkit-mask-image:url(/static/assets/squircle-rb6SKa34.svg);mask-image:url(/static/assets/squircle-rb6SKa34.svg);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;border-radius:0}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{height:100%;width:100%}body{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:rgb(var(--color-canvas));color:rgb(var(--color-ink));-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ios-card{background:rgb(var(--color-surface));border-radius:8px;border:1px solid rgb(var(--color-black) / .02);box-shadow:var(--shadow-card);transition:transform .2s ease,box-shadow .2s ease}.ios-card:hover{box-shadow:0 12px 32px rgb(var(--color-black) / .06)}.dashboard-pie-chart .recharts-surface:focus,.dashboard-pie-chart .recharts-pie:focus,.dashboard-pie-chart .recharts-pie-sector:focus,.dashboard-pie-chart .recharts-sector:focus{outline:none}.dashboard-revenue-chart .recharts-surface:focus,.dashboard-revenue-chart .recharts-bar-rectangle:focus,.dashboard-revenue-chart .recharts-rectangle:focus,.dashboard-revenue-chart .recharts-curve:focus,.dashboard-revenue-chart .recharts-dot:focus,.dashboard-revenue-chart [class*=recharts-zIndex-layer_]:focus{outline:none!important}.dashboard-revenue-chart .recharts-bar-rectangle,.dashboard-revenue-chart .recharts-rectangle{stroke:none!important}.ios-input{background:rgb(var(--color-surface-subtle));border:1px solid var(--color-transparent);transition:all .3s cubic-bezier(.25,.8,.25,1);color:rgb(var(--color-ink));font-weight:500}.ios-input:focus{background:rgb(var(--color-surface));border-color:rgb(var(--color-brand));box-shadow:0 0 0 4px rgb(var(--color-brand) / .3);outline:none}.ios-input::-moz-placeholder{color:rgb(var(--color-neutral-400));font-weight:400}.ios-input::placeholder{color:rgb(var(--color-neutral-400));font-weight:400}.ios-btn-primary{background:rgb(var(--color-brand));color:rgb(var(--color-white));font-weight:700;border:none;transition:all .2s cubic-bezier(.25,.8,.25,1);cursor:pointer}.ios-btn-primary:hover:not(:disabled){background:rgb(var(--color-brand-highlight));transform:translateY(-1px);box-shadow:var(--shadow-brand-strong)}.ios-btn-primary:active:not(:disabled){transform:translateY(1px);box-shadow:var(--shadow-brand-soft)}.ios-btn-primary:disabled{background:rgb(var(--color-neutral-100));color:rgb(var(--color-neutral-400));box-shadow:none;transform:none;cursor:not-allowed}.ios-btn-secondary{background:rgb(var(--color-surface-subtle));color:rgb(var(--color-ink));font-weight:600;border:1px solid var(--color-transparent);transition:all .2s ease;cursor:pointer}.ios-btn-secondary:hover{background:rgb(var(--color-neutral-200));border-color:rgb(var(--color-neutral-300))}.ios-btn-danger{background:rgb(var(--color-danger-100));color:rgb(var(--color-danger-600));font-weight:600;border:1px solid var(--color-transparent);transition:all .2s ease;cursor:pointer}.ios-btn-danger:hover{background:rgb(var(--color-danger-200));border-color:rgb(var(--color-danger-300))}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:var(--color-transparent)}::-webkit-scrollbar-thumb{background:rgb(var(--color-black) / .1);border-radius:10px}::-webkit-scrollbar-thumb:hover{background:rgb(var(--color-black) / .2)}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .5s cubic-bezier(.16,1,.3,1) forwards}@keyframes slideUp{0%{opacity:0;transform:translateY(30px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}.animate-slide-up{animation:slideUp .3s cubic-bezier(.16,1,.3,1) forwards}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}::-moz-selection{background:rgb(var(--color-brand));color:rgb(var(--color-white))}::selection{background:rgb(var(--color-brand));color:rgb(var(--color-white))}.text-brand{color:rgb(var(--color-brand))}.bg-brand{background-color:rgb(var(--color-brand))}.border-brand{border-color:rgb(var(--color-brand))}.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:9999px;font-size:12px;font-weight:600}.status-badge-success{background-color:rgb(var(--color-success-100));color:rgb(var(--color-success-800))}.status-badge-warning{background-color:rgb(var(--color-warning-100));color:rgb(var(--color-warning-800))}.status-badge-error{background-color:rgb(var(--color-danger-100));color:rgb(var(--color-danger-800))}.status-badge-info{background-color:rgb(var(--color-info-100));color:rgb(var(--color-info-800))}.loading-skeleton{background:linear-gradient(90deg,rgb(var(--color-neutral-100)),rgb(var(--color-neutral-200)),rgb(var(--color-neutral-100)));background-size:200% 100%;animation:loading 1.5s ease-in-out infinite}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;align-items:center;justify-content:center;background-color:rgb(var(--color-black) / .4);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto;display:flex;flex-direction:column;background-color:rgb(var(--color-white));border-radius:10px;box-shadow:var(--shadow-modal);overflow:hidden}.modal-header{flex-shrink:0;padding:2rem 2rem 1.5rem;border-bottom:1px solid rgb(var(--color-neutral-100));background-color:rgb(var(--color-white));z-index:10}.modal-body{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:2rem}.modal-footer{flex-shrink:0;padding:1.5rem 2rem 2rem;border-top:1px solid rgb(var(--color-neutral-100));background-color:rgb(var(--color-white));z-index:10}.modal-container-lg{max-width:64rem}.modal-overlay-centered{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;justify-content:center;background-color:rgb(var(--color-black) / .4);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-overlay-centered .modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto 0;display:flex;flex-direction:column;background-color:rgb(var(--color-white));border-radius:10px;box-shadow:var(--shadow-modal);overflow:hidden}@media(max-width:768px){.ios-card{border-radius:6px}.ios-input{font-size:16px}.modal-container{max-width:calc(100% - 2rem);max-height:90vh;border-radius:8px}.modal-header,.modal-body,.modal-footer{padding-left:1.5rem;padding-right:1.5rem}}.placeholder\:text-slate-400::-moz-placeholder{--tw-text-opacity: 1;color:rgb(var(--color-slate-400) / var(--tw-text-opacity, 1))}.placeholder\:text-slate-400::placeholder{--tw-text-opacity: 1;color:rgb(var(--color-slate-400) / var(--tw-text-opacity, 1))}.focus-within\:border-sky-400:focus-within{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-400) / var(--tw-border-opacity, 1))}.focus-within\:ring-2:focus-within{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-within\:ring-sky-100:focus-within{--tw-ring-opacity: 1;--tw-ring-color: rgb(var(--color-brand-100) / var(--tw-ring-opacity, 1))}.hover\:translate-y-\[-4px\]:hover{--tw-translate-y: -4px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-300) / var(--tw-border-opacity, 1))}.hover\:border-brand:hover{--tw-border-opacity: 1;border-color:rgb(var(--color-brand) / var(--tw-border-opacity, 1))}.hover\:border-emerald-300:hover{--tw-border-opacity: 1;border-color:rgb(var(--color-success-300) / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(var(--color-neutral-400) / var(--tw-border-opacity, 1))}.hover\:border-sky-200:hover{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-200) / var(--tw-border-opacity, 1))}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-warning-100) / var(--tw-bg-opacity, 1))}.hover\:bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-black) / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-50) / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-700) / var(--tw-bg-opacity, 1))}.hover\:bg-brand:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand) / var(--tw-bg-opacity, 1))}.hover\:bg-brand-highlight:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-highlight) / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-100:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-100) / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-50) / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50\/50:hover{background-color:rgb(var(--color-success-50) / .5)}.hover\:bg-emerald-600:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-600) / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-700) / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-100) / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-200) / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-50) / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-neutral-800) / var(--tw-bg-opacity, 1))}.hover\:bg-green-50:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-50) / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-danger-100) / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-danger-50) / var(--tw-bg-opacity, 1))}.hover\:bg-sky-50:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-50) / var(--tw-bg-opacity, 1))}.hover\:bg-sky-600:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-600) / var(--tw-bg-opacity, 1))}.hover\:bg-slate-100:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-slate-100) / var(--tw-bg-opacity, 1))}.hover\:bg-warning-50\/50:hover{background-color:rgb(var(--color-warning-50) / .5)}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-white) / var(--tw-bg-opacity, 1))}.hover\:bg-white\/10:hover{background-color:rgb(var(--color-white) / .1)}.hover\:bg-white\/80:hover{background-color:rgb(var(--color-white) / .8)}.hover\:text-black:hover{--tw-text-opacity: 1;color:rgb(var(--color-black) / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(var(--color-brand-600) / var(--tw-text-opacity, 1))}.hover\:text-brand:hover{--tw-text-opacity: 1;color:rgb(var(--color-brand) / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(var(--color-neutral-600) / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(var(--color-neutral-900) / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(var(--color-success-600) / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(var(--color-danger-500) / var(--tw-text-opacity, 1))}.hover\:text-red-600:hover{--tw-text-opacity: 1;color:rgb(var(--color-danger-600) / var(--tw-text-opacity, 1))}.hover\:text-sky-600:hover{--tw-text-opacity: 1;color:rgb(var(--color-brand-600) / var(--tw-text-opacity, 1))}.hover\:text-slate-700:hover{--tw-text-opacity: 1;color:rgb(var(--color-slate-700) / var(--tw-text-opacity, 1))}.hover\:text-slate-900:hover{--tw-text-opacity: 1;color:rgb(var(--color-slate-900) / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(var(--color-white) / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-lg:hover{--tw-shadow: var(--shadow-lg);--tw-shadow-colored: var(--shadow-lg);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-400:focus{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-400) / var(--tw-border-opacity, 1))}.focus\:border-sky-400:focus{--tw-border-opacity: 1;border-color:rgb(var(--color-brand-400) / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-brand:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(var(--color-brand) / var(--tw-ring-opacity, 1))}.focus\:ring-sky-100:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(var(--color-brand-100) / var(--tw-ring-opacity, 1))}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-slate-300:disabled{--tw-bg-opacity: 1;background-color:rgb(var(--color-slate-300) / var(--tw-bg-opacity, 1))}.disabled\:opacity-25:disabled{opacity:.25}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.disabled\:opacity-70:disabled{opacity:.7}.disabled\:shadow-none:disabled{--tw-shadow: var(--shadow-none);--tw-shadow-colored: var(--shadow-none);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group:focus-within .group-focus-within\:text-black{--tw-text-opacity: 1;color:rgb(var(--color-black) / var(--tw-text-opacity, 1))}.group:hover .group-hover\:translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-125{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:bg-white{--tw-bg-opacity: 1;background-color:rgb(var(--color-white) / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-slate-700{--tw-text-opacity: 1;color:rgb(var(--color-slate-700) / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media(min-width:640px){.sm\:w-48{width:12rem}.sm\:w-64{width:16rem}.sm\:w-72{width:18rem}.sm\:max-w-sm{max-width:24rem}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.sm\:grid-cols-\[1fr_180px\]{grid-template-columns:1fr 180px}.sm\:flex-row{flex-direction:row}.sm\:flex-wrap{flex-wrap:wrap}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:col-span-3{grid-column:span 3 / span 3}.md\:col-span-full{grid-column:1 / -1}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:grid-cols-\[1\.4fr_110px_40px\]{grid-template-columns:1.4fr 110px 40px}.md\:grid-cols-\[180px_1fr\]{grid-template-columns:180px 1fr}.md\:grid-cols-\[1fr_1fr_1\.4fr_110px_40px\]{grid-template-columns:1fr 1fr 1.4fr 110px 40px}.md\:flex-row{flex-direction:row}.md\:items-end{align-items:flex-end}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:border-l{border-left-width:1px}.md\:border-t-0{border-top-width:0px}.md\:p-12{padding:3rem}.md\:pl-6{padding-left:1.5rem}.md\:pt-0{padding-top:0}}@media(min-width:1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[320px_1fr\]{grid-template-columns:320px 1fr}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}}@media(min-width:1280px){.xl\:w-36{width:9rem}.xl\:w-52{width:13rem}.xl\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.xl\:grid-cols-\[minmax\(270px\,0\.72fr\)_minmax\(0\,1\.28fr\)\]{grid-template-columns:minmax(270px,.72fr) minmax(0,1.28fr)}.xl\:flex-row{flex-direction:row}.xl\:items-end{align-items:flex-end}.xl\:items-center{align-items:center}.xl\:justify-between{justify-content:space-between}}@media(min-width:1536px){.\32xl\:grid-cols-\[360px_1fr\]{grid-template-columns:360px 1fr}} diff --git a/internal/webui/static/assets/index-CFzx5gQT.js b/internal/webui/static/assets/index-CFzx5gQT.js new file mode 100644 index 0000000..33ab584 --- /dev/null +++ b/internal/webui/static/assets/index-CFzx5gQT.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-RK26q9J7.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-BxxJOyEX.js","assets/vendor-D-Edl3pr.js","assets/AccountList-fhDk6BDY.js","assets/OrderList-CSGFKOqw.js","assets/CardList-D-c7QNTB.js","assets/ItemList-FcKS3Z5e.js","assets/Settings-fa7In0jk.js","assets/Rules-D79nNK3r.js","assets/Notifications-BJQ8JgFo.js","assets/Chat-By_xPFNH.js"])))=>i.map(i=>d[i]); +import{c as S,j as e,r as c,d as H}from"./react-vendor-C_od1ZSF.js";import{L as T,a as P,S as J,U as Y,A as K,b as Q,c as W,M as X,C as ee,B as te,d as se,Z as ne,e as re,f as ae,G as k,g as oe,h as ie,i as le}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))d(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&d(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function d(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ce extends S.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:e.jsxs("section",{className:"max-w-md text-center",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),e.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const de=3e4,ue=10*6e4;let N=!1;const I=()=>{N||typeof window>"u"||(N=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{N=!1}))},he=t=>{if(!t)return"";const n=new URLSearchParams;for(const[d,r]of Object.entries(t))r!=null&&n.set(d,String(r));const s=n.toString();return s?`?${s}`:""},L=async(t,n,s={})=>{var o;const d=he(s.params),r=`${n}${d}`,i=$(s.signal,s.timeoutMs??de);let a;try{a=await fetch(r,{method:t,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(m){throw i.signal.aborted?new Error((o=s.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):m}finally{i.cleanup()}const h=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&I();const m=h?await a.json().catch(()=>{}):await a.text().catch(()=>{}),f=z(m,a.status);throw new Error(f)}return h?await a.json():await a.text()},D=async(t,n,s)=>L("GET",t,{params:n,...s}),_=async(t,n,s)=>L("POST",t,{body:n,...s}),Ve=async(t,n,s)=>L("PUT",t,{body:n,...s}),Ue=async(t,n,s)=>L("DELETE",t,{params:n,...s}),Ge=async(t,n,s={})=>{var h;const d=$(s.signal,s.timeoutMs??ue);let r;try{r=await fetch(t,{method:"POST",credentials:"include",signal:d.signal,body:n})}catch(o){throw d.signal.aborted?new Error((h=s.signal)!=null&&h.aborted?"请求已取消":"上传超时,请稍后重试"):o}finally{d.cleanup()}const l=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){r.status===401&&I();const o=z(l,r.status),m=new Error(o);throw m.payload=l,m}return l},$=(t,n)=>{const s=new AbortController,d=()=>s.abort(t==null?void 0:t.reason);t!=null&&t.aborted?d():t==null||t.addEventListener("abort",d,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),t==null||t.removeEventListener("abort",d)}}},me=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.code=="string"&&typeof n.message=="string"},z=(t,n)=>typeof t=="string"?t:me(t)?t.message:`请求失败: ${n}`,fe=async t=>_("/api/v1/session/login",t,{skipAuthLogout:!0}),xe=async t=>_("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),pe=async t=>D("/api/v1/session",void 0,t),ge=async()=>_("/api/v1/session/logout",{}),M=c.createContext(void 0),be=({children:t})=>{const[n,s]=c.useState(!1),[d,r]=c.useState(!1),[i,a]=c.useState(!0),[l,h]=c.useState(!1),o=()=>{s(!1),r(!1)};c.useEffect(()=>{const b=new AbortController;let g=!0;pe({signal:b.signal}).then(p=>{if(g){if((p==null?void 0:p.initialized)===!1){h(!0),o();return}h(!1),p!=null&&p.authenticated?(s(!0),r(p.is_admin===!0)):o()}}).catch(p=>{!g||p instanceof DOMException&&p.name==="AbortError"||(h(!1),o())}).finally(()=>{g&&a(!1)});const u=()=>o();return window.addEventListener("auth:logout",u),(()=>{g=!1,b.abort(),window.removeEventListener("auth:logout",u)})},[]);const m=async b=>{const g=await fe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},f=async b=>{const g=await xe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},x=async()=>{try{await ge()}finally{o()}};return e.jsx(M.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:d,needsInit:l,signIn:m,initialize:f,signOut:x},children:t})},B=()=>{const t=c.useContext(M);if(!t)throw new Error("useSession 必须在 SessionProvider 内使用");return t},q="ydisks.sidebar.v1",ye=()=>{try{return window.localStorage.getItem(q)==="collapsed"}catch{return!1}},ve=t=>{try{window.localStorage.setItem(q,t?"collapsed":"expanded")}catch{}},we=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.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"})})}),F=({sizeClass:t="w-12 h-12",logoClassName:n="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.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)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(we,{className:n})})]})]}),je=()=>{const{checkingAuth:t,needsInit:n,signIn:s,initialize:d}=B(),[r,i]=c.useState(""),[a,l]=c.useState(""),[h,o]=c.useState(""),[m,f]=c.useState(""),[x,b]=c.useState(!1),[g,u]=c.useState(""),p=async y=>{y.preventDefault(),b(!0),u("");try{const v=await s({username:r,password:a});v.success||u(v.message||"登录失败")}catch(v){u(v instanceof Error&&v.message||"登录失败")}finally{b(!1)}},j=async y=>{if(y.preventDefault(),u(""),h.length<8){u("密码至少需要 8 个字符");return}if(h!==m){u("两次输入的密码不一致");return}b(!0);try{const v=await d(h);if(!v.success){u(v.message||"初始化失败,请重试");return}o(""),f("")}catch(v){u(v instanceof Error&&v.message||"初始化失败,请重试")}finally{b(!1)}};if(t)return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-surface","aria-label":"正在校验会话",children:e.jsx(T,{className:"h-8 w-8 animate-spin text-brand"})});const G=n?"首次设置管理员密码":"欢迎回来",Z=n?"设置完成后会自动进入系统,管理员账号为 admin。":"Ydisks闲鱼助手 · 自动发货与管家系统";return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-4 font-sans",children:e.jsxs("section",{className:"w-full max-w-lg rounded-xl border border-white bg-white/80 p-8 shadow-panel backdrop-blur-3xl md:p-12",children:[e.jsxs("header",{className:"mb-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:e.jsx(F,{sizeClass:"h-24 w-24"})}),e.jsx("h1",{className:"text-3xl font-extrabold text-gray-900",children:G}),e.jsx("p",{className:"mt-2 font-medium text-gray-600",children:Z})]}),n?e.jsxs("form",{className:"space-y-5",onSubmit:j,children:[e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"设置管理员密码"}),e.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>o(y.target.value)),placeholder:"设置管理员密码(至少 8 个字符)",type:"password",value:h})]}),e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"确认管理员密码"}),e.jsx(J,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>f(y.target.value)),placeholder:"再次输入密码",type:"password",value:m})]}),e.jsx(A,{submitting:x,text:"设置密码并进入系统"})]}):e.jsxs("form",{className:"space-y-5",onSubmit:p,children:[e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"管理员账号"}),e.jsx(Y,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{autoFocus:!0,className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>i(y.target.value)),placeholder:"管理员账号",type:"text",value:r})]}),e.jsxs("label",{className:"relative block",children:[e.jsx("span",{className:"sr-only",children:"管理员密码"}),e.jsx(P,{className:"absolute left-5 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"}),e.jsx("input",{className:"ios-input h-14 w-full rounded-xl py-4 pl-14 pr-6",onChange:(y=>l(y.target.value)),placeholder:"密码",type:"password",value:a})]}),e.jsx(A,{submitting:x,text:"立即登录"})]}),g?e.jsx("p",{className:"mt-5 rounded-xl bg-red-50 p-3 text-center text-sm font-medium text-red-600",children:g}):null]})})},A=({submitting:t,text:n})=>e.jsx("button",{className:"ios-btn-primary flex h-14 w-full items-center justify-center gap-2 rounded-xl text-lg disabled:opacity-70",disabled:t,type:"submit",children:t?e.jsx(T,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:n}),e.jsx(K,{className:"h-5 w-5"})]})}),Le="modulepreload",Ne=function(t){return"/static/"+t},O={},w=function(n,s,d){let r=Promise.resolve();if(s&&s.length>0){let a=function(o){return Promise.all(o.map(m=>Promise.resolve(m).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),h=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));r=a(s.map(o=>{if(o=Ne(o),o in O)return;O[o]=!0;const m=o.endsWith(".css"),f=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${f}`))return;const x=document.createElement("link");if(x.rel=m?"stylesheet":Le,m||(x.as="script"),x.crossOrigin="",x.href=o,h&&x.setAttribute("nonce",h),document.head.appendChild(x),m)return new Promise((b,g)=>{x.addEventListener("load",b),x.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${o}`)))})}))}function i(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return r.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return n().catch(i)})},Ce=({activeTab:t,isAdmin:n=!1,collapsed:s,onToggleCollapsed:d,onNavigate:r,onLogout:i,buildInfo:a})=>{const l=[{id:"dashboard",icon:Q,label:"仪表盘"},{id:"accounts",icon:W,label:"账号管理"},{id:"chat",icon:X,label:"在线聊天"},{id:"cards",icon:ee,label:"卡密库存"},{id:"items",icon:te,label:"商品列表"},{id:"orders",icon:se,label:"订单管理"},{id:"rules",icon:ne,label:"自动化规则"},{id:"notifications",icon:re,label:"通知设置"},...n?[{id:"settings",icon:ae,label:"系统与AI"}]:[]],h=/^\d+\.\d+\.\d+$/.test(a.version)?`v${a.version}`:a.version;return e.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:[e.jsxs("div",{className:`flex h-20 items-center border-b border-slate-100 ${s?"justify-center px-2":"gap-3 px-5"}`,children:[e.jsx(F,{sizeClass:"h-10 w-10"}),!s&&e.jsxs("div",{className:"min-w-0 leading-tight",children:[e.jsx("div",{className:"truncate text-base font-black tracking-tight text-slate-950",children:"Ydisks 闲鱼助手"}),e.jsx("div",{className:"mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600",children:"Operations"})]})]}),e.jsx("nav",{className:`flex-1 space-y-1.5 overflow-y-auto pt-5 ${s?"px-2":"px-3"}`,"aria-label":"主导航",children:l.map(o=>{const m=o.icon,f=t===o.id;return e.jsx(S.Fragment,{children:e.jsxs("button",{type:"button",title:s?o.label:void 0,"aria-label":o.label,"aria-current":f?"page":void 0,onClick:(()=>r(o.id)),className:`group relative flex h-11 w-full items-center rounded-xl transition-colors ${s?"justify-center":"gap-3 px-3.5"} ${f?"bg-brand text-white shadow-brand-active":"text-slate-500 hover:bg-slate-100 hover:text-slate-900"}`,children:[e.jsx(m,{className:`h-[19px] w-[19px] shrink-0 ${f?"text-white":"text-slate-400 group-hover:text-slate-700"}`}),!s&&e.jsx("span",{className:"truncate text-sm font-bold",children:o.label}),f&&!s&&e.jsx("span",{className:"ml-auto h-1.5 w-1.5 rounded-full bg-white/90"})]})},o.id)})}),e.jsxs("div",{children:[e.jsx("div",{title:s?`版本 ${a.version} · ${a.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?e.jsx(k,{className:"h-[18px] w-[18px] text-slate-400","aria-label":`版本 ${a.version}`}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-extrabold uppercase tracking-[0.18em] text-slate-400",children:[e.jsx(k,{className:"h-3.5 w-3.5"}),"运行版本"]}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-2",children:[e.jsx("span",{className:"truncate font-mono text-xs font-bold text-slate-700",children:h}),e.jsx("span",{className:"truncate font-mono text-[10px] text-slate-400",children:a.commit})]})]})}),e.jsxs("div",{className:`space-y-2 p-2 ${s?"":"p-3"}`,children:[e.jsxs("button",{type:"button",onClick:d,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?e.jsx(oe,{className:"h-5 w-5"}):e.jsx(ie,{className:"h-5 w-5"}),!s&&e.jsx("span",{className:"text-sm font-bold",children:"收起侧边栏"})]}),e.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:[e.jsx(le,{className:"h-5 w-5"}),!s&&e.jsx("span",{className:"text-sm font-bold",children:"退出登录"})]})]})]})]})},Ee=async t=>D("/health",void 0,t),C=c.lazy(()=>w(()=>import("./Dashboard-RK26q9J7.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),Se=c.lazy(()=>w(()=>import("./AccountList-fhDk6BDY.js"),__vite__mapDeps([7,1,3,4]))),_e=c.lazy(()=>w(()=>import("./OrderList-CSGFKOqw.js"),__vite__mapDeps([8,1,4,3,2]))),Pe=c.lazy(()=>w(()=>import("./CardList-D-c7QNTB.js"),__vite__mapDeps([9,1,4,3]))),ke=c.lazy(()=>w(()=>import("./ItemList-FcKS3Z5e.js"),__vite__mapDeps([10,1,3,4]))),Ae=c.lazy(()=>w(()=>import("./Settings-fa7In0jk.js"),__vite__mapDeps([11,1,4]))),Oe=c.lazy(()=>w(()=>import("./Rules-D79nNK3r.js"),__vite__mapDeps([12,1,4,3]))),Re=c.lazy(()=>w(()=>import("./Notifications-BJQ8JgFo.js"),__vite__mapDeps([13,1,4]))),Te=c.lazy(()=>w(()=>import("./Chat-By_xPFNH.js"),__vite__mapDeps([14,1,3,4]))),Ie=()=>e.jsx("div",{className:"flex min-h-[24rem] items-center justify-center",role:"status","aria-label":"正在加载页面",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-brand/20 border-t-brand"})}),De=({activeTab:t,isAdmin:n,deliveryRuleTarget:s,onConfigureDelivery:d,onDeliveryTargetHandled:r})=>{const i=l=>{d({cookieId:l.cookie_id,itemId:l.item_id,requestId:Date.now()})},a=()=>{switch(t){case"dashboard":return e.jsx(C,{});case"accounts":return e.jsx(Se,{});case"chat":return e.jsx(Te,{});case"orders":return e.jsx(_e,{});case"cards":return e.jsx(Pe,{});case"items":return e.jsx(ke,{onConfigureDelivery:i});case"rules":return e.jsx(Oe,{initialDeliveryTarget:s,onDeliveryTargetHandled:r});case"notifications":return e.jsx(Re,{isAdmin:n});case"settings":return n?e.jsx(Ae,{}):e.jsx(C,{});default:return e.jsx(C,{})}};return e.jsx(c.Suspense,{fallback:e.jsx(Ie,{}),children:a()})},$e=({activeTab:t,isAdmin:n,collapsed:s,deliveryRuleTarget:d,onToggleCollapsed:r,onNavigate:i,onLogout:a,onConfigureDelivery:l,onDeliveryTargetHandled:h})=>{const[o,m]=c.useState({version:"dev",commit:"unknown"});return c.useEffect(()=>{const f=new AbortController;return Ee({signal:f.signal}).then(x=>m({version:String(x.version||"dev"),commit:String(x.commit||"unknown")})).catch(x=>{x instanceof DOMException&&x.name}),(()=>f.abort())},[]),e.jsxs("div",{className:"flex min-h-screen bg-canvas text-ink",children:[e.jsx(Ce,{activeTab:t,isAdmin:n,collapsed:s,onToggleCollapsed:r,onNavigate:i,onLogout:a,buildInfo:o}),e.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"} ${t==="chat"?"p-4 md:p-6":"p-8 md:p-12"}`,children:[e.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]"}),e.jsx("div",{className:`${t==="chat"?"mx-auto max-w-[1680px]":"mx-auto max-w-[1400px] pb-10"}`,children:e.jsx(De,{activeTab:t,isAdmin:n,deliveryRuleTarget:d,onConfigureDelivery:l,onDeliveryTargetHandled:h})})]})]})},V={"/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"},E=Object.fromEntries(Object.entries(V).map(([t,n])=>[n,t])),R=()=>V[window.location.pathname]??"dashboard",ze=()=>{const{isLoggedIn:t,isAdmin:n,signOut:s}=B(),[d,r]=c.useState(R),[i,a]=c.useState(),[l,h]=c.useState(ye);c.useEffect(()=>{const u=()=>r(R());return window.addEventListener("popstate",u),(()=>window.removeEventListener("popstate",u))},[]),c.useEffect(()=>{t&&!n&&d==="settings"&&(window.history.replaceState({},"",E.dashboard),r("dashboard"))},[d,n,t]);const o=u=>{const p=u==="settings"&&!n?"dashboard":u,j=E[p];j!==window.location.pathname&&window.history.pushState({},"",j),r(p)},m=u=>{const p=Object.prototype.hasOwnProperty.call(E,u)?u:"dashboard";o(p)},f=async()=>{try{await s()}catch(u){console.error("退出登录失败",u)}},x=()=>{h(u=>{const p=!u;return ve(p),p})},b=u=>{a(u),o("rules")},g=()=>a(void 0);return t?e.jsx($e,{activeTab:d,isAdmin:n,collapsed:l,deliveryRuleTarget:i,onToggleCollapsed:x,onNavigate:m,onLogout:f,onConfigureDelivery:b,onDeliveryTargetHandled:g}):e.jsx(je,{})},Me=()=>e.jsx(ce,{children:e.jsx(be,{children:e.jsx(ze,{})})}),U=document.getElementById("root");if(!U)throw new Error("Could not find root element to mount to");const Be=H.createRoot(U);Be.render(e.jsx(S.StrictMode,{children:e.jsx(Me,{})}));export{_ as a,Ge as b,Ue as d,D as g,Ve as p}; diff --git a/internal/webui/static/assets/index-CYPNW7Ux.js b/internal/webui/static/assets/index-CYPNW7Ux.js deleted file mode 100644 index 2063c4c..0000000 --- a/internal/webui/static/assets/index-CYPNW7Ux.js +++ /dev/null @@ -1,2 +0,0 @@ -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-ZQ7msDu9.css b/internal/webui/static/assets/index-ZQ7msDu9.css new file mode 100644 index 0000000..d1b8f6c --- /dev/null +++ b/internal/webui/static/assets/index-ZQ7msDu9.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.collapse{visibility:collapse}.static{position:static}.relative{position:relative}.mx-0\.5{margin-left:.125rem;margin-right:.125rem}.inline-block{display:inline-block}.inline{display:inline}.contents{display:contents}.h-7{height:1.75rem}.h-screen{height:100vh}.min-h-0{min-height:0px}.w-16{width:4rem}.w-64{width:16rem}.w-7{width:1.75rem}.min-w-0{min-width:0px}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.grid-cols-\[320px_minmax\(0\,1fr\)\]{grid-template-columns:320px minmax(0,1fr)}.flex-col{flex-direction:column}.justify-center{justify-content:center}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-x-hidden{overflow-x:hidden}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-600) / var(--tw-bg-opacity, 1))}.bg-brand{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand) / var(--tw-bg-opacity, 1))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-500) / var(--tw-bg-opacity, 1))}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-600) / var(--tw-bg-opacity, 1))}.bg-sky-500{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-500) / var(--tw-bg-opacity, 1))}.py-1{padding-top:.25rem;padding-bottom:.25rem}.align-middle{vertical-align:middle}.text-white{--tw-text-opacity: 1;color:rgb(var(--color-white) / var(--tw-text-opacity, 1))}.shadow-brand-active{--tw-shadow: var(--shadow-brand-active);--tw-shadow-colored: var(--shadow-brand-active);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}:root{--color-transparent: transparent;--color-black: 0 0 0;--color-white: 255 255 255;--color-brand: 0 148 247;--color-brand-highlight: 0 113 227;--color-brand-light: 40 126 254;--color-ink: 29 29 31;--color-muted: 134 134 139;--color-line: 210 210 215;--color-canvas: 244 245 247;--color-surface: 255 255 255;--color-surface-subtle: 247 248 250;--color-surface-muted: 250 250 250;--color-neutral-50: 249 250 251;--color-neutral-100: 243 244 246;--color-neutral-200: 229 231 235;--color-neutral-300: 209 213 219;--color-neutral-400: 156 163 175;--color-neutral-500: 107 114 128;--color-neutral-600: 75 85 99;--color-neutral-700: 55 65 81;--color-neutral-800: 31 41 55;--color-neutral-900: 17 24 39;--color-neutral-950: 3 7 18;--color-slate-50: 248 250 252;--color-slate-100: 241 245 249;--color-slate-200: 226 232 240;--color-slate-300: 203 213 225;--color-slate-400: 148 163 184;--color-slate-500: 100 116 139;--color-slate-600: 71 85 105;--color-slate-700: 51 65 85;--color-slate-800: 30 41 59;--color-slate-900: 15 23 42;--color-slate-950: 2 6 23;--color-brand-50: 239 248 255;--color-brand-100: 223 241 255;--color-brand-200: 191 229 255;--color-brand-300: 143 210 255;--color-brand-400: 83 184 251;--color-brand-500: 0 148 247;--color-brand-600: 0 148 247;--color-brand-700: 0 113 227;--color-brand-800: 0 91 181;--color-brand-900: 0 75 147;--color-brand-950: 0 53 107;--color-success-50: 236 253 245;--color-success-100: 209 250 229;--color-success-200: 167 243 208;--color-success-300: 110 231 183;--color-success-400: 52 211 153;--color-success-500: 16 185 129;--color-success-600: 5 150 105;--color-success-700: 4 120 87;--color-success-800: 6 95 70;--color-success-900: 6 78 59;--color-success-950: 2 44 34;--color-warning-50: 255 251 235;--color-warning-100: 254 243 199;--color-warning-200: 253 230 138;--color-warning-300: 252 211 77;--color-warning-400: 251 191 36;--color-warning-500: 245 158 11;--color-warning-600: 217 119 6;--color-warning-700: 180 83 9;--color-warning-800: 146 64 14;--color-warning-900: 120 53 15;--color-warning-950: 69 26 3;--color-danger-50: 254 242 242;--color-danger-100: 254 226 226;--color-danger-200: 254 202 202;--color-danger-300: 252 165 165;--color-danger-400: 248 113 113;--color-danger-500: 239 68 68;--color-danger-600: 220 38 38;--color-danger-700: 185 28 28;--color-danger-800: 153 27 27;--color-danger-900: 127 29 29;--color-danger-950: 69 10 10;--color-info-50: 239 246 255;--color-info-100: 219 234 254;--color-info-200: 191 219 254;--color-info-300: 147 197 253;--color-info-400: 96 165 250;--color-info-500: 59 130 246;--color-info-600: 37 99 235;--color-info-700: 29 78 216;--color-info-800: 30 64 175;--color-info-900: 30 58 138;--color-info-950: 23 37 84;--color-accent-50: 250 245 255;--color-accent-100: 243 232 255;--color-accent-200: 233 213 255;--color-accent-300: 216 180 254;--color-accent-400: 192 132 252;--color-accent-500: 168 85 247;--color-accent-600: 147 51 234;--color-accent-700: 126 34 206;--color-accent-800: 107 33 168;--color-accent-900: 88 28 135;--color-accent-950: 59 7 100;--shadow-none: 0 0 0 var(--color-transparent);--shadow-default: 0 1px 3px 0 rgb(var(--color-black) / .1), 0 1px 2px -1px rgb(var(--color-black) / .1);--shadow-sm: 0 1px 2px 0 rgb(var(--color-black) / .05);--shadow-md: 0 4px 6px -1px rgb(var(--color-black) / .1), 0 2px 4px -2px rgb(var(--color-black) / .1);--shadow-lg: 0 10px 15px -3px rgb(var(--color-black) / .1), 0 4px 6px -4px rgb(var(--color-black) / .1);--shadow-xl: 0 20px 25px -5px rgb(var(--color-black) / .1), 0 8px 10px -6px rgb(var(--color-black) / .1);--shadow-2xl: 0 25px 50px -12px rgb(var(--color-black) / .25);--shadow-inner: inset 0 2px 4px 0 rgb(var(--color-black) / .05);--shadow-card: 0 8px 24px rgb(var(--color-black) / .04);--shadow-panel: 0 20px 60px -15px rgb(var(--color-black) / .05);--shadow-modal: 0 25px 50px -12px rgb(var(--color-black) / .25);--shadow-sidebar: 4px 0 24px rgb(var(--color-slate-900) / .035);--shadow-chat: 0 16px 45px rgb(var(--color-slate-900) / .06);--shadow-chat-input: 0 -8px 24px rgb(var(--color-slate-900) / .04);--shadow-chat-active: inset 3px 0 0 rgb(var(--color-brand));--shadow-brand-soft: 0 2px 8px rgb(var(--color-brand) / .2);--shadow-brand-active: 0 8px 18px rgb(var(--color-brand) / .2);--shadow-brand-strong: 0 8px 20px rgb(var(--color-brand) / .3)}*,:before,:after{--tw-ring-offset-color: rgb(var(--color-white));--tw-ring-color: rgb(var(--color-brand-400) / .5);--tw-ring-offset-shadow: 0 0 0 var(--color-transparent);--tw-ring-shadow: 0 0 0 var(--color-transparent);--tw-shadow: 0 0 0 var(--color-transparent);--tw-shadow-colored: 0 0 0 var(--color-transparent)}.squircle{-webkit-mask-image:url(/static/assets/squircle-rb6SKa34.svg);mask-image:url(/static/assets/squircle-rb6SKa34.svg);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;border-radius:0}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{height:100%;width:100%}body{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:rgb(var(--color-canvas));color:rgb(var(--color-ink));-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ios-card{background:rgb(var(--color-surface));border-radius:8px;border:1px solid rgb(var(--color-black) / .02);box-shadow:var(--shadow-card);transition:transform .2s ease,box-shadow .2s ease}.ios-card:hover{box-shadow:0 12px 32px rgb(var(--color-black) / .06)}.dashboard-pie-chart .recharts-surface:focus,.dashboard-pie-chart .recharts-pie:focus,.dashboard-pie-chart .recharts-pie-sector:focus,.dashboard-pie-chart .recharts-sector:focus{outline:none}.dashboard-revenue-chart .recharts-surface:focus,.dashboard-revenue-chart .recharts-bar-rectangle:focus,.dashboard-revenue-chart .recharts-rectangle:focus,.dashboard-revenue-chart .recharts-curve:focus,.dashboard-revenue-chart .recharts-dot:focus,.dashboard-revenue-chart [class*=recharts-zIndex-layer_]:focus{outline:none!important}.dashboard-revenue-chart .recharts-bar-rectangle,.dashboard-revenue-chart .recharts-rectangle{stroke:none!important}.ios-input{background:rgb(var(--color-surface-subtle));border:1px solid var(--color-transparent);transition:all .3s cubic-bezier(.25,.8,.25,1);color:rgb(var(--color-ink));font-weight:500}.ios-input:focus{background:rgb(var(--color-surface));border-color:rgb(var(--color-brand));box-shadow:0 0 0 4px rgb(var(--color-brand) / .3);outline:none}.ios-input::-moz-placeholder{color:rgb(var(--color-neutral-400));font-weight:400}.ios-input::placeholder{color:rgb(var(--color-neutral-400));font-weight:400}.ios-btn-primary{background:rgb(var(--color-brand));color:rgb(var(--color-white));font-weight:700;border:none;transition:all .2s cubic-bezier(.25,.8,.25,1);cursor:pointer}.ios-btn-primary:hover:not(:disabled){background:rgb(var(--color-brand-highlight));transform:translateY(-1px);box-shadow:var(--shadow-brand-strong)}.ios-btn-primary:active:not(:disabled){transform:translateY(1px);box-shadow:var(--shadow-brand-soft)}.ios-btn-primary:disabled{background:rgb(var(--color-neutral-100));color:rgb(var(--color-neutral-400));box-shadow:none;transform:none;cursor:not-allowed}.ios-btn-secondary{background:rgb(var(--color-surface-subtle));color:rgb(var(--color-ink));font-weight:600;border:1px solid var(--color-transparent);transition:all .2s ease;cursor:pointer}.ios-btn-secondary:hover{background:rgb(var(--color-neutral-200));border-color:rgb(var(--color-neutral-300))}.ios-btn-danger{background:rgb(var(--color-danger-100));color:rgb(var(--color-danger-600));font-weight:600;border:1px solid var(--color-transparent);transition:all .2s ease;cursor:pointer}.ios-btn-danger:hover{background:rgb(var(--color-danger-200));border-color:rgb(var(--color-danger-300))}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:var(--color-transparent)}::-webkit-scrollbar-thumb{background:rgb(var(--color-black) / .1);border-radius:10px}::-webkit-scrollbar-thumb:hover{background:rgb(var(--color-black) / .2)}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .5s cubic-bezier(.16,1,.3,1) forwards}@keyframes slideUp{0%{opacity:0;transform:translateY(30px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}.animate-slide-up{animation:slideUp .3s cubic-bezier(.16,1,.3,1) forwards}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}::-moz-selection{background:rgb(var(--color-brand));color:rgb(var(--color-white))}::selection{background:rgb(var(--color-brand));color:rgb(var(--color-white))}.text-brand{color:rgb(var(--color-brand))}.bg-brand{background-color:rgb(var(--color-brand))}.border-brand{border-color:rgb(var(--color-brand))}.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:9999px;font-size:12px;font-weight:600}.status-badge-success{background-color:rgb(var(--color-success-100));color:rgb(var(--color-success-800))}.status-badge-warning{background-color:rgb(var(--color-warning-100));color:rgb(var(--color-warning-800))}.status-badge-error{background-color:rgb(var(--color-danger-100));color:rgb(var(--color-danger-800))}.status-badge-info{background-color:rgb(var(--color-info-100));color:rgb(var(--color-info-800))}.loading-skeleton{background:linear-gradient(90deg,rgb(var(--color-neutral-100)),rgb(var(--color-neutral-200)),rgb(var(--color-neutral-100)));background-size:200% 100%;animation:loading 1.5s ease-in-out infinite}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;align-items:center;justify-content:center;background-color:rgb(var(--color-black) / .4);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto;display:flex;flex-direction:column;background-color:rgb(var(--color-white));border-radius:10px;box-shadow:var(--shadow-modal);overflow:hidden}.modal-header{flex-shrink:0;padding:2rem 2rem 1.5rem;border-bottom:1px solid rgb(var(--color-neutral-100));background-color:rgb(var(--color-white));z-index:10}.modal-body{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:2rem}.modal-footer{flex-shrink:0;padding:1.5rem 2rem 2rem;border-top:1px solid rgb(var(--color-neutral-100));background-color:rgb(var(--color-white));z-index:10}.modal-container-lg{max-width:64rem}.modal-overlay-centered{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;justify-content:center;background-color:rgb(var(--color-black) / .4);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-overlay-centered .modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto 0;display:flex;flex-direction:column;background-color:rgb(var(--color-white));border-radius:10px;box-shadow:var(--shadow-modal);overflow:hidden}@media(max-width:768px){.ios-card{border-radius:6px}.ios-input{font-size:16px}.modal-container{max-width:calc(100% - 2rem);max-height:90vh;border-radius:8px}.modal-header,.modal-body,.modal-footer{padding-left:1.5rem;padding-right:1.5rem}}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-700) / var(--tw-bg-opacity, 1))}.hover\:bg-brand-highlight:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-brand-highlight) / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-600:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-600) / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(var(--color-success-700) / var(--tw-bg-opacity, 1))}@media(min-width:1280px){.xl\:grid-cols-\[minmax\(270px\,0\.72fr\)_minmax\(0\,1\.28fr\)\]{grid-template-columns:minmax(270px,.72fr) minmax(0,1.28fr)}}@media(min-width:1536px){.\32xl\:grid-cols-\[360px_1fr\]{grid-template-columns:360px 1fr}} diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html index ec3f1fd..6a04b2c 100644 --- a/internal/webui/static/index.html +++ b/internal/webui/static/index.html @@ -6,10 +6,10 @@ Ydisks闲鱼助手 - 自动发货与管家系统 - + - - + +
diff --git a/tools/architecturecheck/frontend_api_contract_test.go b/tools/architecturecheck/frontend_api_contract_test.go new file mode 100644 index 0000000..40655e5 --- /dev/null +++ b/tools/architecturecheck/frontend_api_contract_test.go @@ -0,0 +1,161 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +// TestFrontendProductionRequestsUseVersionedAPI 清点 React 生产源码,确保业务请求不再调用旧路径。 +func TestFrontendProductionRequestsUseVersionedAPI(t *testing.T) { + // root 是当前仓库根目录,测试从任意 Go 包工作目录向上解析它。 + root := repositoryRootForContractTest(t) + // frontendRoot 是需要审计的前端源码目录。 + frontendRoot := filepath.Join(root, "frontend") + // legacyFragments 是旧 HTTP 入口在字符串字面量中的稳定前缀集合。 + legacyFragments := []string{ + "'/login", `"/login`, "`/login", + "'/verify", `"/verify`, "`/verify", + "'/logout", `"/logout`, "`/logout", + "'/change-password", `"/change-password`, "`/change-password", + "'/account/credentials", `"/account/credentials`, "`/account/credentials", + "'/cookies", `"/cookies`, "`/cookies", + "'/items", `"/items`, "`/items", + "'/automation-rules", `"/automation-rules`, "`/automation-rules", + "'/automation-issues", `"/automation-issues`, "`/automation-issues", + "'/automation-runs", `"/automation-runs`, "`/automation-runs", + "'/automation-pending-tasks", `"/automation-pending-tasks`, "`/automation-pending-tasks", + "'/api/orders", `"/api/orders`, "`/api/orders", + "'/system-settings", `"/system-settings`, "`/system-settings", + "'/user-settings", `"/user-settings`, "`/user-settings", + "'/ai-reply-settings", `"/ai-reply-settings`, "`/ai-reply-settings", + "'/ai-models", `"/ai-models`, "`/ai-models", + "'/cards", `"/cards`, "`/cards", + "'/notification-channels", `"/notification-channels`, "`/notification-channels", + "'/message-notifications", `"/message-notifications`, "`/message-notifications", + "'/api/chat", `"/api/chat`, "`/api/chat", + "'/keywords", `"/keywords`, "`/keywords", + "'/keywords-with-item-id", `"/keywords-with-item-id`, "`/keywords-with-item-id", + "'/keywords-with-type", `"/keywords-with-type`, "`/keywords-with-type", + "'/item-reply", `"/item-reply`, "`/item-reply", + "'/itemReplays", `"/itemReplays`, "`/itemReplays", + "'/default-replies", `"/default-replies`, "`/default-replies", + "'/api/default-reply", `"/api/default-reply`, "`/api/default-reply", + "'/api/account-tasks", `"/api/account-tasks`, "`/api/account-tasks", + "'/admin/", `"/admin/`, "`/admin/", + "'/change-admin-password", `"/change-admin-password`, "`/change-admin-password", + "'/dashboard/stats", `"/dashboard/stats`, "`/dashboard/stats", + "'/analytics/", `"/analytics/`, "`/analytics/", + "'/qr-login", `"/qr-login`, "`/qr-login", + "'/password-login", `"/password-login`, "`/password-login", + } + // findings 保存命中的文件、行号和旧路径片段。 + var findings []string + // walkErr 表示遍历前端生产源码时遇到的文件系统错误。 + walkErr := filepath.WalkDir(frontendRoot, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + if entry.Name() == "node_modules" || entry.Name() == "coverage" || entry.Name() == "dist" { + return filepath.SkipDir + } + return nil + } + if !isFrontendProductionSource(path) { + return nil + } + // file 是当前待扫描的前端生产源码文件;openErr 表示打开失败原因。 + file, openErr := os.Open(path) + if openErr != nil { + return openErr + } + defer file.Close() + // lineNumber 是当前源码行的 1-based 行号。 + lineNumber := 0 + // scanner 按行读取当前前端源码,供旧路径静态清点使用。 + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lineNumber++ + // line 是当前源码文本,用于检查是否包含历史 API 路径。 + line := scanner.Text() + // fragment 是当前待检查的历史 API 路径片段。 + for _, fragment := range legacyFragments { + if strings.Contains(line, fragment) { + findings = append(findings, fmt.Sprintf("%s:%d 命中 %s", filepath.ToSlash(path), lineNumber, fragment)) + } + } + } + return scanner.Err() + }) + if walkErr != nil { + t.Fatal(walkErr) + } + if len(findings) != 0 { + t.Fatalf("前端生产源码存在旧 API 调用:\n%s", strings.Join(findings, "\n")) + } +} + +// TestCompatibilityMatrixDocumentsSunsetConditions 验证兼容清单保留调用方证据和删除条件。 +func TestCompatibilityMatrixDocumentsSunsetConditions(t *testing.T) { + // root 是当前仓库根目录,供读取架构契约文档使用。 + root := repositoryRootForContractTest(t) + // matrixPath 是 API 兼容边界清单的绝对路径。 + matrixPath := filepath.Join(root, "docs", "architecture", "api-compatibility-matrix.md") + // raw 是兼容清单原文,测试只检查治理字段是否仍被记录。 + raw, err := os.ReadFile(matrixPath) + if err != nil { + t.Fatal(err) + } + // requiredPhrases 是阶段三调用方审计必须保留的证据和删除条件短语。 + requiredPhrases := []string{ + "阶段 3 调用方审计", + "TestFrontendProductionRequestsUseVersionedAPI", + "外部调用方", + "Sunset", + "连续两个发布周期", + "回滚", + } + for _, phrase := range requiredPhrases { // phrase 是当前待核对的治理短语。 + if !strings.Contains(string(raw), phrase) { + t.Errorf("兼容清单缺少治理短语 %q", phrase) + } + } +} + +// isFrontendProductionSource 判断文件是否属于需要审计的前端生产源码。 +func isFrontendProductionSource(path string) bool { + // ext 是当前文件扩展名,用于排除非 TypeScript 源码。 + ext := filepath.Ext(path) + if ext != ".ts" && ext != ".tsx" { + return false + } + // base 是当前文件名,用于排除测试与规格文件。 + base := filepath.Base(path) + return !strings.Contains(base, ".test.") && !strings.Contains(base, ".spec.") +} + +// repositoryRootForContractTest 从当前测试目录向上寻找包含 go.mod 的仓库根目录。 +func repositoryRootForContractTest(t *testing.T) string { + t.Helper() + // current 是当前测试进程的工作目录绝对路径。 + current, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + for { + // statErr 表示当前目录是否存在模块声明文件。 + if _, statErr := os.Stat(filepath.Join(current, "go.mod")); statErr == nil { + return current + } + // parent 是向上搜索仓库根目录时的父目录。 + parent := filepath.Dir(current) + if parent == current { + t.Fatal("无法定位仓库根目录") + } + current = parent + } +} diff --git a/tools/architecturecheck/main.go b/tools/architecturecheck/main.go index 1b4b64f..eb9a449 100644 --- a/tools/architecturecheck/main.go +++ b/tools/architecturecheck/main.go @@ -132,6 +132,7 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e } } violations = append(violations, checkApplicationTypeLeaks(relativePath, syntax, fset)...) + violations = append(violations, checkHTTPResponseContracts(relativePath, syntax, fset)...) if strings.HasPrefix(filepath.ToSlash(relativePath), "internal/server/") && !strings.HasSuffix(relativePath, "_repository.go") { // sourceLine 是裸 BeginTx 调用首次出现的源码行号。 sourceLine := firstLineContaining(string(source), ".DB.BeginTx(") @@ -146,6 +147,121 @@ func checkGoFile(root, relativePath string, fset *token.FileSet) ([]violation, e return violations, nil } +// checkHTTPResponseContracts 检查 Server 对外响应是否使用具名 DTO,并阻止动态 map 绕过契约边界。 +func checkHTTPResponseContracts(relativePath string, syntax *ast.File, fset *token.FileSet) []violation { + // normalizedPath 是统一使用斜杠的仓库相对路径。 + normalizedPath := filepath.ToSlash(relativePath) + if !strings.HasPrefix(normalizedPath, "internal/server/") || strings.HasSuffix(normalizedPath, "_test.go") { + return nil + } + // violations 保存当前 Server 文件发现的 HTTP 契约问题。 + var violations []violation + ast.Inspect(syntax, func(node ast.Node) bool { + // typedNode 是当前遍历到的 AST 节点,用于识别 HTTP 契约声明或调用。 + switch typedNode := node.(type) { + case *ast.TypeSpec: + if !isHTTPContractTypeName(typedNode.Name.Name) { + return true + } + if (typedNode.Name.Name == "settingsResponse" || containsDynamicMapType(typedNode.Type)) && + !isControlledDynamicResponseType(typedNode.Name.Name) { + violations = append(violations, violation{ + file: normalizedPath, + line: fset.Position(typedNode.Pos()).Line, + message: fmt.Sprintf("HTTP 契约类型 %s 禁止使用动态 map,请定义具名 DTO 字段", typedNode.Name.Name), + }) + } + case *ast.CallExpr: + if !isWriteJSONCall(typedNode) || len(typedNode.Args) < 3 { + return true + } + // responseArg 是 writeJSON 的响应值参数,必须是具名 DTO 或受控类型。 + responseArg := typedNode.Args[2] + if isDynamicMapLiteral(responseArg) { + violations = append(violations, violation{ + file: normalizedPath, + line: fset.Position(responseArg.Pos()).Line, + message: "HTTP 响应禁止直接写入动态 map,请使用具名 DTO", + }) + } + } + return true + }) + return violations +} + +// isControlledDynamicResponseType 判断已登记的动态键兼容响应,避免本阶段改变旧客户端 JSON 形状。 +func isControlledDynamicResponseType(name string) bool { + // 这些类型的键来自账号 ID、触发类型或设置名称;只有完成外部调用方审计后才允许在后续阶段删除。 + switch name { + case "settingsResponse", "notificationBindingListResponse", "automationRulePageResponse": + return true + default: + return false + } +} + +// isHTTPContractTypeName 判断类型名称是否属于 Server 的 HTTP 响应契约。 +func isHTTPContractTypeName(name string) bool { + // lowerName 统一大小写,兼容 Response、DTO、Envelope 和 Result 的命名习惯。 + lowerName := strings.ToLower(name) + return strings.HasSuffix(lowerName, "response") || strings.HasSuffix(lowerName, "dto") || + strings.HasSuffix(lowerName, "envelope") || strings.HasSuffix(lowerName, "result") +} + +// containsDynamicMapType 递归识别以 any/interface{} 为值的动态 map,保留已有键值兼容契约。 +func containsDynamicMapType(expr ast.Expr) bool { + // typedExpr 是当前递归检查的 AST 类型表达式。 + switch typedExpr := expr.(type) { + case *ast.MapType: + return isAnyType(typedExpr.Value) + case *ast.ArrayType: + return containsDynamicMapType(typedExpr.Elt) + case *ast.StarExpr: + return containsDynamicMapType(typedExpr.X) + case *ast.StructType: + // field 是当前结构体字段,需继续检查其元素类型。 + for _, field := range typedExpr.Fields.List { + if containsDynamicMapType(field.Type) { + return true + } + } + } + return false +} + +// isAnyType 判断表达式是否为 Go 的 any 或空接口,用于识别无稳定字段边界的响应 map。 +func isAnyType(expr ast.Expr) bool { + // ident 是表达式的标识符形式;ok 表示断言成功。 + if ident, ok := expr.(*ast.Ident); ok { + return ident.Name == "any" || ident.Name == "interface{}" + } + // interfaceType 是表达式的接口类型形式;ok 表示断言成功。 + if interfaceType, ok := expr.(*ast.InterfaceType); ok { + return interfaceType.Methods != nil && len(interfaceType.Methods.List) == 0 + } + return false +} + +// isWriteJSONCall 判断调用是否为 Server 的统一 JSON 响应写入函数。 +func isWriteJSONCall(call *ast.CallExpr) bool { + // functionName 是调用目标的简单函数名。 + functionName, ok := call.Fun.(*ast.Ident) + return ok && functionName.Name == "writeJSON" +} + +// isDynamicMapLiteral 判断表达式是否直接构造 map 响应,避免匿名契约逃逸静态检查。 +func isDynamicMapLiteral(expr ast.Expr) bool { + // composite 是表达式的复合字面量;ok 表示断言成功。 + composite, ok := expr.(*ast.CompositeLit) + if !ok { + return false + } + // isMap 表示复合字面量是否直接构造动态 map。 + _, isMap := composite.Type.(*ast.MapType) + return isMap +} + // checkApplicationTypeLeaks 检查应用 Port 是否泄露数据库、事务或 Server 类型。 func checkApplicationTypeLeaks(relativePath string, syntax *ast.File, fset *token.FileSet) []violation { if !strings.HasPrefix(filepath.ToSlash(relativePath), "internal/application/") { @@ -210,7 +326,7 @@ func isForbiddenServerLowLevelImport(filePath, importedPath string) bool { if !strings.HasPrefix(filePath, "internal/server/") || strings.HasSuffix(filePath, "_test.go") { return false } - if importedPath != "internal/db" && !strings.HasPrefix(importedPath, "internal/db/") && + if importedPath != "database/sql" && importedPath != "internal/db" && !strings.HasPrefix(importedPath, "internal/db/") && importedPath != "internal/xianyu" && !strings.HasPrefix(importedPath, "internal/xianyu/") && importedPath != "internal/browser" && !strings.HasPrefix(importedPath, "internal/browser/") { return false diff --git a/tools/architecturecheck/main_test.go b/tools/architecturecheck/main_test.go index e8273f8..db42011 100644 --- a/tools/architecturecheck/main_test.go +++ b/tools/architecturecheck/main_test.go @@ -6,6 +6,81 @@ import ( "testing" ) +// TestHTTPResponseContractBoundary 验证 HTTP 契约扫描会拒绝动态 map 和直接 map 响应。 +func TestHTTPResponseContractBoundary(t *testing.T) { + // fset 是模拟 Server 源码的文件位置集合。 + fset := token.NewFileSet() + // syntax、err 是同时包含 map 响应类型和直接 map 写入的模拟 Server 文件。 + syntax, err := parser.ParseFile(fset, "response.go", []byte(`package server +type badResponse struct { Rows []map[string]any } +func handler(w any) { writeJSON(w, 200, map[string]any{"ok": true}) } +`), parser.ParseComments) + if err != nil { + t.Fatal(err) + } + // violations 是动态响应契约的扫描结果。 + violations := checkHTTPResponseContracts("internal/server/response.go", syntax, fset) + if len(violations) != 2 { + t.Fatalf("violations=%+v", violations) + } + // cleanSyntax 是只使用具名字段的模拟 Server 文件。 + cleanSyntax, err := parser.ParseFile(fset, "clean.go", []byte(`package server +type goodResponse struct { Rows []goodRow } +type goodRow struct { ID string } +func handler(w any) { writeJSON(w, 200, goodResponse{}) } +`), parser.ParseComments) + if err != nil { + t.Fatal(err) + } + // cleanViolations 是合规响应契约的扫描结果。 + cleanViolations := checkHTTPResponseContracts("internal/server/clean.go", cleanSyntax, fset) + if len(cleanViolations) != 0 { + t.Fatalf("clean violations=%+v", cleanViolations) + } +} + +// TestControlledDynamicResponseTypes 验证已登记的兼容动态键不会被阶段三门禁误判。 +func TestControlledDynamicResponseTypes(t *testing.T) { + // fset 是兼容响应模拟源码的文件位置集合。 + fset := token.NewFileSet() + // syntax、err 是包含既有动态键响应的模拟 Server 文件。 + syntax, err := parser.ParseFile(fset, "compat.go", []byte(`package server +type settingsResponse map[string]string +type notificationBindingListResponse map[string][]bindingRow +type automationRulePageResponse struct { TriggerCounts map[string]int } +type bindingRow struct { ID string } +`), parser.ParseComments) + if err != nil { + t.Fatal(err) + } + // violations 是兼容响应扫描结果;现有键形状必须继续保留。 + violations := checkHTTPResponseContracts("internal/server/compat.go", syntax, fset) + if len(violations) != 0 { + t.Fatalf("controlled response violations=%+v", violations) + } +} + +// TestHTTPResponseContractScope 验证架构扫描不会误伤测试代码和非 Server 包。 +func TestHTTPResponseContractScope(t *testing.T) { + // fset 是模拟源代码的文件位置集合。 + fset := token.NewFileSet() + // syntax、err 是包含动态 map 的模拟文件。 + syntax, err := parser.ParseFile(fset, "response_test.go", []byte(`package server +type testResponse map[string]any +`), parser.ParseComments) + if err != nil { + t.Fatal(err) + } + // got 是测试文件被扫描出的架构违规列表。 + if got := checkHTTPResponseContracts("internal/server/response_test.go", syntax, fset); len(got) != 0 { + t.Fatalf("test-file violations=%+v", got) + } + // got 是非 Server 文件被扫描出的架构违规列表。 + if got := checkHTTPResponseContracts("internal/application/response.go", syntax, fset); len(got) != 0 { + t.Fatalf("non-server violations=%+v", got) + } +} + // TestNormalizeImportPath 验证架构检查器能够识别当前模块的内部包路径。 func TestNormalizeImportPath(t *testing.T) { if got /* got 是规范化后的导入路径。 */ := normalizeImportPath("xianyu-go/internal/db"); got != "internal/db" { @@ -40,6 +115,9 @@ func TestServerLowLevelBoundary(t *testing.T) { if !isForbiddenServerLowLevelImport("internal/server/new_service.go", "internal/db") { t.Fatal("新增 Server 低层依赖必须被门禁拒绝") } + if !isForbiddenServerLowLevelImport("internal/server/unit_of_work.go", "database/sql") { + t.Fatal("Server 不得暴露 database/sql 事务类型") + } if isForbiddenServerLowLevelImport("internal/server/new_service_test.go", "internal/db") { t.Fatal("测试文件不应被生产依赖门禁阻断") }