阶段4:推进启动稳定性与组合根注入
This commit is contained in:
1 parent
9da450d940
commit
d2d8e02a39
36 files changed
+830
-168
No files matched your search
@@ -110,14 +110,18 @@ agents MUST read all of:
|
||||
|
||||
The following rules are mandatory:
|
||||
|
||||
1. Identify the current plan stage and the smallest applicable work item before editing. Do not perform a
|
||||
repository-wide rewrite or create a long-lived big-bang refactor.
|
||||
2. Preserve a compiling, runnable and tested state at every merge point. Add or strengthen characterization
|
||||
tests before moving high-risk behavior.
|
||||
3. Keep each change to one reviewable vertical slice. Do not combine broad file moves, behavior changes,
|
||||
schema migrations, compatibility deletion and mass comment backfill in the same change.
|
||||
4. Update the master plan status table, completion evidence, update log and next safe entry point whenever a
|
||||
plan work item is completed or its scope materially changes.
|
||||
1. Identify the current plan stage before editing. A stage is the only delivery and review unit: one complete
|
||||
phase-level PR/final merge may modify several Go packages, frontend features, tests, architecture gates and
|
||||
documents together. Agents must not turn a stage into separately delivered vertical slices.
|
||||
2. A phase worktree may be temporarily non-compiling while its coordinated migration is in progress. The final
|
||||
phase commit/merge must compile, start, pass every mandatory phase verification and include complete evidence.
|
||||
Add or strengthen characterization tests before moving high-risk behavior.
|
||||
3. Do not use a large phase change to hide unfinished branches, error paths or unverified behavior. Unrelated
|
||||
renames, repository-wide formatting, dependency upgrades, test weakening, coverage deletion, compatibility
|
||||
whitelist expansion and frozen CAPTCHA changes remain prohibited.
|
||||
4. Update the master-plan status table, completion evidence, update log and next entry point once when a phase
|
||||
is completed or its scope materially changes. Completion evidence is bound to the final phase commit and the
|
||||
complete command output, not to intermediate local commits.
|
||||
5. Do not weaken, skip or delete tests to make a refactor pass. Existing test failures must be explained and
|
||||
resolved or reported as blockers.
|
||||
6. Preserve unrelated working-tree changes. Do not reformat or rename unrelated code as cleanup.
|
||||
@@ -177,7 +181,7 @@ debt and record the scope in `docs/architecture/refactoring-master-plan.md`.
|
||||
## Mandatory target dependency boundaries
|
||||
|
||||
`docs/architecture/dependency-rules.md` is authoritative. During migration, existing violations may remain only
|
||||
until their recorded vertical slice is completed; agents MUST NOT add new violations.
|
||||
until their recorded phase is completed; agents MUST NOT add new violations.
|
||||
|
||||
- `cmd` handles configuration, dependency construction, signals and lifecycle only; no new business rules, SQL,
|
||||
HTTP handlers or protocol parsing belong there.
|
||||
|
||||
@@ -272,6 +272,11 @@ go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
启动完成后访问 `http://localhost:59188`。如果数据库尚未初始化,直接在页面填写并确认
|
||||
管理员密码即可,不需要知道数据库文件路径,也不需要先执行 CLI 命令。
|
||||
|
||||
> 安全提示:`-addr :59188` 会监听全部网络接口。未初始化数据库的首次网页初始化不要求预共享
|
||||
> secret,因此能够访问该端口的首个客户端可以创建管理员。该模式保留用于远程部署便利性,风险由
|
||||
> 部署者承担。公网或不可信网络必须在防火墙、反向代理或安全组中限制管理端口访问,并建议通过
|
||||
> `XIANYU_ADMIN_PASSWORD` 或 `-init-admin` 预先初始化。
|
||||
|
||||
如当前环境无法安装 Chromium,可以使用 `-no-browser` 启动:
|
||||
|
||||
```bash
|
||||
|
||||
+112
-18
@@ -12,6 +12,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
@@ -377,7 +378,11 @@ func openServerInfrastructure(ctx context.Context, startup serverStartupConfig,
|
||||
}
|
||||
// initialized 表示系统是否已有管理员;查询失败按未初始化提示而不阻断启动。
|
||||
if initialized, _ := store.Users.IsSystemInitialized(ctx); !initialized {
|
||||
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
|
||||
if isNonLoopbackListenAddress(opts.addr) {
|
||||
logger.Warn("系统尚未初始化且 HTTP 监听可被远程访问;首个访问初始化页面的客户端可创建管理员,请由部署者通过网络隔离或 -init-admin 承担该风险", "addr", opts.addr)
|
||||
} else {
|
||||
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
|
||||
}
|
||||
}
|
||||
return serverInfrastructure{database: database, store: store, logger: logger, logWriter: logWriter, closeLog: closeLog}, nil
|
||||
}
|
||||
@@ -517,13 +522,28 @@ func buildServerRuntime(opts serverOptions, infrastructure serverInfrastructure)
|
||||
}
|
||||
// authentication 负责 HTTP 会话认证;Secure 策略由启动参数控制。
|
||||
authentication := &auth.Service{Store: infrastructure.store, Logger: infrastructure.logger, Secure: opts.secure}
|
||||
// httpServer 是完成所有窄依赖注入后的 HTTP 服务实例。
|
||||
httpServer, serverErr := server.New(authentication, mgr, opts.webDir, opts.addr, infrastructure.logger, autoCenter, notifier, server.WithChatService(chatService), server.WithChatDependencies(chatDependencies), server.WithDatabaseHealth(databaseHealth), server.WithOrderReconciliationRecovery(orderReconciliationRecovery), server.WithOrderDependencies(orderDependencies), server.WithAccountDependencies(accountDependencies), server.WithItemDependencies(itemDependencies), server.WithAutomationDependencies(automationDependencies), server.WithTransportApplicationServices(transportApplications), server.WithPlatformDependencies(platformDependencies), server.WithApplicationLifecycle(lifecycleCoordinator))
|
||||
// compositionServer 仅在迁移期间复用旧应用服务装配逻辑;它不绑定端口、不启动 worker,也不作为 HTTP Server 运行。
|
||||
compositionServer, compositionErr := server.New(authentication, mgr, opts.webDir, opts.addr, infrastructure.logger, autoCenter, notifier, server.WithChatService(chatService), server.WithChatDependencies(chatDependencies), server.WithDatabaseHealth(databaseHealth), server.WithOrderReconciliationRecovery(orderReconciliationRecovery), server.WithOrderDependencies(orderDependencies), server.WithAccountDependencies(accountDependencies), server.WithItemDependencies(itemDependencies), server.WithAutomationDependencies(automationDependencies), server.WithTransportApplicationServices(transportApplications), server.WithPlatformDependencies(platformDependencies), server.WithApplicationLifecycle(lifecycleCoordinator))
|
||||
if compositionErr != nil {
|
||||
return serverRuntime{}, fmt.Errorf("构造应用服务集合失败: %w", compositionErr)
|
||||
}
|
||||
// applications 是组合期一次性构造的只读应用服务集合,HTTP Server 不得在自身构造期间补建业务服务。
|
||||
applications := compositionServer.ApplicationServices()
|
||||
// httpServer 是只接收完整依赖快照的 HTTP transport 实例。
|
||||
httpServer, serverErr := server.NewWithDependencies(server.Dependencies{
|
||||
Auth: authentication, Manager: mgr, WebDir: opts.webDir, Addr: opts.addr, Logger: infrastructure.logger,
|
||||
Automation: autoCenter, Notifier: notifier, Chat: chatService, OrderDependencies: orderDependencies,
|
||||
AccountDependencies: accountDependencies, ItemDependencies: itemDependencies, ChatDependencies: chatDependencies,
|
||||
AutomationDependencies: automationDependencies, TransportApplications: transportApplications,
|
||||
PlatformDependencies: platformDependencies, DatabaseHealth: databaseHealth,
|
||||
OrderReconciliationRecovery: orderReconciliationRecovery, Applications: applications,
|
||||
ApplicationLifecycle: lifecycleCoordinator,
|
||||
})
|
||||
if serverErr != nil {
|
||||
return serverRuntime{}, fmt.Errorf("构造 HTTP 服务失败: %w", serverErr)
|
||||
}
|
||||
// component 表示 HTTP 服务暴露给进程装配层的应用 worker 生命周期组件。
|
||||
for _, component := range httpServer.ApplicationLifecycleComponents() {
|
||||
// component 表示应用服务集合交给进程组合根登记的 worker 生命周期组件。
|
||||
for _, component := range applications.LifecycleComponents() {
|
||||
// err 表示当前 HTTP 应用 worker 生命周期组件登记失败。
|
||||
if err := lifecycleCoordinator.Add(component); err != nil {
|
||||
return serverRuntime{}, fmt.Errorf("登记应用 worker 生命周期组件 %q 失败: %w", component.Name, err)
|
||||
@@ -534,9 +554,16 @@ func buildServerRuntime(opts serverOptions, infrastructure serverInfrastructure)
|
||||
|
||||
// runServerLifecycle 启动应用组件和 HTTP 监听,等待退出后执行有限时长的 HTTP 与组件逆序关闭。
|
||||
func runServerLifecycle(ctx context.Context, runtime serverRuntime, logger *slog.Logger) error {
|
||||
// bindErr 是应用 worker 启动前同步占用 HTTP 端口的错误,端口冲突不得触发任何业务副作用。
|
||||
if bindErr := runtime.httpServer.Bind(); bindErr != nil {
|
||||
return fmt.Errorf("绑定 HTTP 服务失败: %w", bindErr)
|
||||
}
|
||||
// err 表示应用组件按依赖顺序启动失败。
|
||||
if err := runtime.lifecycleCoordinator.Start(ctx); err != nil {
|
||||
return fmt.Errorf("启动应用生命周期失败: %w", err)
|
||||
// stopCtx、stopCancel 关闭已绑定但尚未 Serve 的监听器,避免启动失败后端口泄漏。
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer stopCancel()
|
||||
return errors.Join(fmt.Errorf("启动应用生命周期失败: %w", err), runtime.httpServer.Stop(stopCtx))
|
||||
}
|
||||
// err 表示 HTTP 服务监听启动失败;失败后必须关闭已启动的应用组件。
|
||||
if err := runtime.httpServer.Start(ctx); err != nil {
|
||||
@@ -692,16 +719,11 @@ func loadOrCreateDataKey(path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("data key 文件路径不能为空")
|
||||
}
|
||||
// raw、err 分别是既有密钥文件的内容及读取失败原因。
|
||||
if raw, err := os.ReadFile(path); err == nil {
|
||||
// key 是去除首尾空白后的现有数据加密主密钥,禁止记录到日志。
|
||||
key := strings.TrimSpace(string(raw))
|
||||
if key == "" {
|
||||
return "", fmt.Errorf("data key 文件为空: %s", path)
|
||||
}
|
||||
// key、readErr 分别是已存在密钥文件的内容及读取错误;已有文件永远优先于本次生成。
|
||||
if key, readErr := readDataKey(path); readErr == nil {
|
||||
return key, nil
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("读取 data key 文件失败: %w", err)
|
||||
} else if !errors.Is(readErr, os.ErrNotExist) {
|
||||
return "", readErr
|
||||
}
|
||||
|
||||
// err 表示创建数据加密主密钥父目录失败。
|
||||
@@ -716,13 +738,85 @@ func loadOrCreateDataKey(path string) (string, error) {
|
||||
}
|
||||
// key 是待写入权限为 0600 文件的数据加密主密钥,禁止记录到日志。
|
||||
key := base64.RawStdEncoding.EncodeToString(raw)
|
||||
// err 表示原子性不足的首次密钥文件写入失败,调用方必须终止启动。
|
||||
if err := os.WriteFile(path, []byte(key+"\n"), 0o600); err != nil {
|
||||
return "", fmt.Errorf("写入 data key 文件失败: %w", err)
|
||||
// file、createErr 分别是以排他方式创建的密钥文件及创建错误;同一时刻只能有一个进程成为写入者。
|
||||
file, createErr := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if errors.Is(createErr, os.ErrExist) {
|
||||
return waitForDataKey(path)
|
||||
}
|
||||
if createErr != nil {
|
||||
return "", fmt.Errorf("创建 data key 文件失败: %w", createErr)
|
||||
}
|
||||
// writeErr 表示新密钥写入错误;失败时删除当前进程独占创建的文件,避免遗留不可恢复的空文件。
|
||||
if _, writeErr := io.WriteString(file, key+"\n"); writeErr != nil {
|
||||
_ = file.Close()
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("写入 data key 文件失败: %w", writeErr)
|
||||
}
|
||||
// syncErr 表示密钥内容持久化到文件系统前发生的同步错误;不能在未落盘时继续启动。
|
||||
if syncErr := file.Sync(); syncErr != nil {
|
||||
_ = file.Close()
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("同步 data key 文件失败: %w", syncErr)
|
||||
}
|
||||
// closeErr 表示关闭新建密钥文件时产生的错误;关闭失败同样视为密钥未可靠创建。
|
||||
if closeErr := file.Close(); closeErr != nil {
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("关闭 data key 文件失败: %w", closeErr)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// readDataKey 读取并校验已有的数据加密主密钥;返回错误时绝不输出密钥内容。
|
||||
func readDataKey(path string) (string, error) {
|
||||
// raw、readErr 分别是文件原始内容及读取失败原因。
|
||||
raw, readErr := os.ReadFile(path)
|
||||
if readErr != nil {
|
||||
if errors.Is(readErr, os.ErrNotExist) {
|
||||
return "", os.ErrNotExist
|
||||
}
|
||||
return "", fmt.Errorf("读取 data key 文件失败: %w", readErr)
|
||||
}
|
||||
// key 是去除文件末尾换行后的数据加密主密钥,禁止记录到日志。
|
||||
key := strings.TrimSpace(string(raw))
|
||||
if key == "" {
|
||||
return "", fmt.Errorf("data key 文件为空: %s", path)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// waitForDataKey 等待并读取由并发启动进程创建的密钥文件,不会生成或覆盖另一把密钥。
|
||||
func waitForDataKey(path string) (string, error) {
|
||||
// attempt 是读取竞争方写入结果的有限尝试次数,避免空文件永久阻塞启动。
|
||||
for attempt := 0; attempt < 20; attempt++ {
|
||||
// key、readErr 分别是当前尝试读到的密钥及读取错误。
|
||||
key, readErr := readDataKey(path)
|
||||
if readErr == nil {
|
||||
return key, nil
|
||||
}
|
||||
if !strings.Contains(readErr.Error(), "文件为空") && !errors.Is(readErr, os.ErrNotExist) {
|
||||
return "", readErr
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
return "", fmt.Errorf("等待并发创建 data key 文件超时: %s", path)
|
||||
}
|
||||
|
||||
// isNonLoopbackListenAddress 判断监听地址是否可能接收本机以外的连接;空 host 与通配地址均视为远程可达。
|
||||
func isNonLoopbackListenAddress(address string) bool {
|
||||
// host、port、splitErr 分别是监听地址的主机部分、端口部分和解析错误。
|
||||
host, _, splitErr := net.SplitHostPort(strings.TrimSpace(address))
|
||||
if splitErr != nil {
|
||||
return true
|
||||
}
|
||||
host = strings.TrimSpace(host)
|
||||
if host == "" || strings.EqualFold(host, "localhost") {
|
||||
return host == ""
|
||||
}
|
||||
// ip 是可直接判断 loopback 属性的 IP 地址;主机名按远程可达处理,避免漏报部署风险。
|
||||
ip := net.ParseIP(host)
|
||||
return ip == nil || !ip.IsLoopback()
|
||||
}
|
||||
|
||||
// ensureAdmin 封装ensureAdmin业务协调。
|
||||
func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error {
|
||||
if password == "" {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -231,6 +232,113 @@ func TestLoadOrCreateDataKeyPersists(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadOrCreateDataKeyConcurrentCreation 验证并发首次启动只能观测到同一把持久化主密钥。
|
||||
func TestLoadOrCreateDataKeyConcurrentCreation(t *testing.T) {
|
||||
// path 是所有并发启动模拟共享的、尚不存在的数据密钥文件路径。
|
||||
path := filepath.Join(t.TempDir(), "concurrent-data-key")
|
||||
// workerCount 是并发调用数量,足以覆盖多个 goroutine 同时通过不存在检查的竞争窗口。
|
||||
const workerCount = 32
|
||||
// start 统一放行所有调用,避免调度器提前串行化创建过程。
|
||||
start := make(chan struct{})
|
||||
// keys 收集每个调用成功读取或创建到的密钥,禁止将密钥写入测试失败输出。
|
||||
keys := make(chan string, workerCount)
|
||||
// failures 收集并发创建过程中发生的错误,以便主 goroutine 统一断言。
|
||||
failures := make(chan error, workerCount)
|
||||
// workers 等待全部并发调用结束,避免测试提前读取未完成文件。
|
||||
var workers sync.WaitGroup
|
||||
// workerIndex 为每个并发调用分配稳定的启动序号,循环体本身不依赖其数值。
|
||||
for workerIndex := 0; workerIndex < workerCount; workerIndex++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
// key、keyErr 分别是当前调用读取或创建到的主密钥及错误。
|
||||
key, keyErr := loadOrCreateDataKey(path)
|
||||
if keyErr != nil {
|
||||
failures <- keyErr
|
||||
return
|
||||
}
|
||||
keys <- key
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
close(keys)
|
||||
close(failures)
|
||||
// failure 是任一并发创建协程返回的错误,仅用于统一失败报告。
|
||||
for failure := range failures {
|
||||
t.Fatalf("并发创建 data key 失败: %v", failure)
|
||||
}
|
||||
// firstKey 是所有并发调用必须一致的首个密钥值,仅用于相等性比较。
|
||||
var firstKey string
|
||||
// key 是单个并发调用观测到的密钥,仅参与同值比较且不输出明文。
|
||||
for key := range keys {
|
||||
if firstKey == "" {
|
||||
firstKey = key
|
||||
continue
|
||||
}
|
||||
if key != firstKey {
|
||||
t.Fatal("并发创建返回了不一致的数据密钥")
|
||||
}
|
||||
}
|
||||
if firstKey == "" {
|
||||
t.Fatal("并发创建没有返回数据密钥")
|
||||
}
|
||||
// persistedKey、readErr 分别是最终文件中的密钥及读取错误。
|
||||
persistedKey, readErr := readDataKey(path)
|
||||
if readErr != nil {
|
||||
t.Fatalf("读取并发创建后的 data key 失败: %v", readErr)
|
||||
}
|
||||
if persistedKey != firstKey {
|
||||
t.Fatal("持久化 data key 与并发调用返回值不一致")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadOrCreateDataKeyRejectsEmptyExistingFile 验证遗留空密钥文件不会被静默覆盖或替换。
|
||||
func TestLoadOrCreateDataKeyRejectsEmptyExistingFile(t *testing.T) {
|
||||
// path 是预先创建为空内容的密钥文件路径,模拟异常进程留下的不完整状态。
|
||||
path := filepath.Join(t.TempDir(), "empty-data-key")
|
||||
// writeErr 是构造异常空密钥文件时的写入错误。
|
||||
if writeErr := os.WriteFile(path, nil, 0o600); writeErr != nil {
|
||||
t.Fatalf("创建空 data key 文件失败: %v", writeErr)
|
||||
}
|
||||
// keyErr 是读取空密钥文件时必须返回的阻断错误。
|
||||
_, keyErr := loadOrCreateDataKey(path)
|
||||
if keyErr == nil {
|
||||
t.Fatal("空 data key 文件不应被静默替换")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsNonLoopbackListenAddress 验证远程可达监听地址会触发未初始化部署风险告警。
|
||||
func TestIsNonLoopbackListenAddress(t *testing.T) {
|
||||
// cases 覆盖 loopback、通配地址和主机名监听的风险分类。
|
||||
cases := []struct {
|
||||
// name 是当前地址分类场景的稳定测试名称。
|
||||
name string
|
||||
// address 是传给服务端监听器的地址字符串。
|
||||
address string
|
||||
// want 是该地址是否可能接收远程客户端连接。
|
||||
want bool
|
||||
}{
|
||||
{name: "loopback IPv4", address: "127.0.0.1:59188", want: false},
|
||||
{name: "loopback IPv6", address: "[::1]:59188", want: false},
|
||||
{name: "all interfaces", address: ":59188", want: true},
|
||||
{name: "public interface", address: "0.0.0.0:59188", want: true},
|
||||
{name: "hostname", address: "host.example:59188", want: true},
|
||||
}
|
||||
// testCase 是当前待执行的监听地址分类。
|
||||
for _, testCase := range cases {
|
||||
// testCase 是当前待执行的监听地址分类。
|
||||
testCase := testCase
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// got 是地址是否可能接受远程连接的实际判断结果。
|
||||
if got := isNonLoopbackListenAddress(testCase.address); got != testCase.want {
|
||||
t.Fatalf("地址 %q 远程可达=%t,want %t", testCase.address, got, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenServerLogWriterUsesConfiguredDirectory 封装TestOpenServerLogWriterUsesConfiguredDirectory业务协调。
|
||||
func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
|
||||
// logDir 用于本次流程后续判断的logDir
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
本文不记录开发日期、提交列表、阶段内进度、完成日志、人员记录或临时工作说明。
|
||||
|
||||
阶段 0 是执行重构前的治理前置条件,不计入正式迭代。阶段 1 至阶段 10 各自对应一个完整
|
||||
迭代和一个 PR,最多执行十轮。阶段内部可以连续完成多项实现和测试,但不得拆成额外轮次、
|
||||
额外 PR 或额外提交。
|
||||
迭代和一个阶段级 PR/最终合并。阶段内部允许同步修改多个包、feature、测试、门禁和文档;
|
||||
agent 不得将阶段拆成多个独立交付。阶段进行中的本地工作区或临时提交可以暂时不可编译,
|
||||
但阶段最终提交必须可编译、可启动、可测试并通过本阶段全部强制验证。
|
||||
|
||||
滑块 CAPTCHA 行为继续由 `docs/slider-captcha-frozen-spec.md` 保护。本文不是修改冻结行为的授权。
|
||||
|
||||
@@ -58,18 +59,15 @@ React app shell
|
||||
空列表编码为 `[]`,前端同时接受数组、包裹对象和 `null`;对应回归测试是强制契约。
|
||||
- 远端 `main` 的文档链接变更不影响运行功能。生成前端资产的文本冲突必须通过当前源码重新构建
|
||||
解决,禁止手工合并压缩产物。
|
||||
- Server 业务用例主体已迁移到应用 Port,架构检查当前可通过;阶段 4 的事务边界和低层访问已收口。
|
||||
transport-facing 应用服务集合、订单补偿恢复和数据库健康检查已经由 `cmd/server` 组合根显式构造并注入
|
||||
Server;阶段 5 的外部调用取消/超时审计和最终 Join 已完成验收,后续不得重新引入 Server 组合业务服务或游离 worker。
|
||||
- 先前关于 Server 组合根、应用生命周期、React Feature 化和 DB 治理的完成声明均撤销为“待重新验收”。
|
||||
当前 `internal/server` 仍构造应用服务和 worker 并持有基础设施相关依赖;阶段 4 必须先完成组合根迁移。
|
||||
- 账号敏感摘要与秘密访问已经分离,并已有审计和多数据库覆盖;阶段 2 可视为完成,但后续迭代
|
||||
不得重新扩大读取、解密、序列化或日志范围。
|
||||
- HTTP `/api/v1` 版本化、具名 DTO、统一错误、前端兼容归一和调用方审计已完成阶段 3 验收;
|
||||
受控的设置键、账号绑定键和触发统计键仍按兼容清单保留,删除条件记录在
|
||||
`docs/architecture/api-compatibility-matrix.md`。
|
||||
- Engine `Account` 与 Automation `Center` 已收束为稳定 facade;连接、出站消息、凭证、运行检查点、
|
||||
动作执行、库存、通知和迟到续期分别由明确组件拥有。集中前端 API/类型文件和若干大型 Hook
|
||||
仍属于阶段 7 的后续范围。
|
||||
- 阶段 5 的生命周期协调器、应用服务组合根、独立关闭预算和可重试 Join 已落地并完成验收;生命周期清单保留同步 Playwright 停止不可中断等实现约束,以及 Engine/Automation 内部状态拆分和运维观测等后续风险。
|
||||
- Engine `Account` 与 Automation `Center` 已有部分组件化实现,但其生命周期、关闭顺序和并发状态仍须在
|
||||
阶段 5 重新验收。集中前端 API/类型文件和商品发布异步状态属于阶段 6 的后续范围。
|
||||
- 三方言迁移编号当前对齐,订单已有游标和批量写入能力;跨 repository 事务、查询计划、补偿和
|
||||
大数据量行为仍需阶段 8 统一验收。
|
||||
- 注释历史基线文件当前为空,但源码仍存在“保存 X 供当前流程使用”等模板化注释。机械基线清零
|
||||
@@ -88,18 +86,30 @@ React app shell
|
||||
| 1. CI 与测试基础 | 已完成 | 建立独立 CI、分层 race 和三数据库门禁 |
|
||||
| 2. 敏感数据访问边界 | 已完成 | 分离摘要、平台凭证、登录秘密和敏感设置 |
|
||||
| 3. HTTP API 契约 | 已完成 | 完成版本化、具名 DTO、统一错误和前端契约 |
|
||||
| 4. Server 应用服务 | 已完成 | 把完整业务用例和事务边界移出 transport |
|
||||
| 5. 应用装配与生命周期 | 已完成 | 消除隐式装配、业务 worker 和游离后台任务 |
|
||||
| 6. Engine 与 Automation | 已完成 | 将大 facade 拆为有明确状态所有权的组件 |
|
||||
| 7. React Feature 化 | 当前迭代 | 完成 feature 边界、请求归属、状态和按路由加载 |
|
||||
| 8. DB 与事务治理 | 已完成 | 完成窄 repository、Unit of Work 和三方言验收 |
|
||||
| 9. 架构门禁与兼容退场 | 待执行 | 封死依赖旁路并按 Sunset 删除兼容层 |
|
||||
| 10. 注释与复杂度收口 | 待执行 | 清除模板注释和复杂度债务,形成最终质量门禁 |
|
||||
| 4. Server 应用服务 | 当前迭代 | 把完整业务用例和事务边界移出 transport,并完成启动稳定性修复 |
|
||||
| 5. 应用装配、生命周期、Engine 与 Automation | 待执行 | 消除隐式装配、业务 worker 和游离后台任务并重新验收状态所有权 |
|
||||
| 6. React Feature 化与异步状态 | 待执行 | 完成 feature 边界、请求归属、状态和按路由加载 |
|
||||
| 7. DB 与事务治理 | 待执行 | 完成窄 repository、Unit of Work 和三方言验收 |
|
||||
| 8. 架构门禁与兼容退场 | 待执行 | 封死依赖旁路并按 Sunset 删除兼容层 |
|
||||
| 9. 注释与复杂度收口 | 待执行 | 清除模板注释和复杂度债务,形成最终质量门禁 |
|
||||
| 10. 最终全栈复验 | 待执行 | 以完整 Go、Browser、三方言和前端证据关闭计划 |
|
||||
|
||||
执行顺序固定为 `0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10`。除阻塞性
|
||||
安全修复、构建修复或用户明确改序外,不得跳过当前阶段推进后续阶段。例外只解决阻塞问题,不能
|
||||
借机开启另一个重构阶段。
|
||||
|
||||
### 4.1 阶段级实施矩阵
|
||||
|
||||
| 阶段 | 主要改动位置与实施方式 | 最终验收与禁止项 |
|
||||
| --- | --- | --- |
|
||||
| 4. Server 应用服务(当前) | `cmd/server` 先同步 `Bind`,再启动协调器,最后 `Serve`;数据密钥采用 `O_CREATE|O_EXCL` 并处理竞争、空文件和写入失败。由 `cmd/server` 与 `internal/adapter` 组装不可变 `server.Dependencies`/`ApplicationServices`,`internal/server` 仅保留 transport、DTO 和路由;删除 Server worker factory、`ApplicationLifecycleComponents()` 与基础设施生产持有。 | 运行本阶段 Server/application/adapter race、`go vet`、lint、comments、architecturecheck 和 `git diff --check`。保留 `:59188` 与远程网页首次初始化,只输出无秘密高等级警告并在文档说明部署者风险。 |
|
||||
| 5. 生命周期、Engine 与 Automation | `cmd` 独占 coordinator;为账户、自动化、续期、通知、浏览器、订单刷新、批量发布和 reconciliation 补齐 owner、Context、Cancel、Wait/Join、失败回滚和关闭顺序测试。 | 全量 Go、指定 race 和浏览器集成测试;不编辑任何冻结 CAPTCHA 文件、调用顺序或规范。 |
|
||||
| 6. React Feature 化与异步状态 | 将 `shared/api-contract/index.ts` 按 session/accounts/items/orders/automation/notifications/settings/chat/cards-admin/common 拆分,feature adapter 直接导入领域契约并转换 UI model;地图服务归入 items feature。统一 `ApiError`,为定位与批量轮询使用独立 AbortController/generation/timeout;清理未使用符号后启用 TypeScript 未使用检查。 | Vitest、typecheck、comments、build、V8 coverage 与嵌入资源重建。不得让组件直接请求网络或以大型 barrel 隐藏跨领域依赖。 |
|
||||
| 7. DB 与事务治理 | 清除上层 `Store.DB`、`*sql.DB`、`*sql.Tx` 与 row model 泄露;跨 repository 原子操作通过应用层 Unit of Work;补齐 claim、lease、取消、重试、不确定结果和补偿测试。 | SQLite 并发/事务测试、MySQL/PostgreSQL 迁移/CRUD/并发 claim、`cmd/dbverify` 完整证据。 |
|
||||
| 8. 架构门禁与兼容退场 | 扩展 AST/源码检查以覆盖 Server 低层依赖、应用 Port 泄露、service locator、动态 import、前端依赖方向和根 services 旁路;仅在遥测、Sunset、调用方迁移和契约测试齐备时删除兼容入口。 | 不得新增白名单或扩大 baseline;同步旧路由、Vite 代理、契约测试与嵌入资源。 |
|
||||
| 9. 注释与复杂度收口 | 清除模板化中文注释,处理超大文件/高复杂度与依赖绕过门禁;不以机械注释或格式化代替责任拆分。 | `make comments`、全量质量门禁和覆盖率;不扩大历史基线。 |
|
||||
| 10. 最终全栈复验 | 只处理前序阶段验收暴露的阻塞缺陷,并汇总最终提交、完整命令、Go/前端覆盖率和真实外部例外。 | 运行全量 Go/race/lint/comments/architecturecheck/前端门禁,适用时运行浏览器和三方言验证;最终提交可启动。 |
|
||||
|
||||
## 5. 阶段 0:治理与强约束
|
||||
|
||||
### 目标
|
||||
@@ -459,13 +469,13 @@ npm run build --prefix frontend
|
||||
|
||||
### 16.1 执行单位与提交
|
||||
|
||||
1. 阶段 1 至阶段 10 各是一个完整迭代、一个 PR、最多一个最终提交。
|
||||
2. 不得把阶段内的函数、文件、测试或所谓纵向子切片计作独立轮次、PR 或提交。
|
||||
3. 当前阶段的实现、测试、文档和生成产物必须在同一迭代一次完成并统一验收。
|
||||
4. 阶段未满足全部完成条件时不得提交为“已完成”,也不得开始下一阶段。
|
||||
5. 每个编辑批次保持可编译;每个阶段合并点必须可运行、可回退并通过全部适用门禁。
|
||||
6. 不改写已有 Git 历史,不覆盖无关工作树修改,不以重建分支代替合并和冲突审计。
|
||||
7. 除用户明确要求外不创建提交;需要提交时只在阶段全部验收后创建一次。
|
||||
1. 阶段 1 至阶段 10 各是一个完整迭代、一个阶段级 PR 和一个最终交付提交。
|
||||
2. 阶段可同时修改多个 Go 包、多个前端 feature、测试、架构门禁和文档;不得把阶段内工作再拆成独立交付、独立验收或独立 PR。
|
||||
3. 本地可以使用临时提交或工作区操作,阶段内部允许暂时不可编译;最终阶段提交必须可编译、可启动、可测试并通过全部适用门禁。
|
||||
4. 阶段未满足全部完成条件时不得标记为“已完成”,也不得以大提交掩盖未完成分支、错误路径或覆盖率缺口。
|
||||
5. 不改写已有 Git 历史,不覆盖无关工作树修改,不以重建分支代替合并和冲突审计。
|
||||
6. 仍禁止无关重命名、全仓格式化、削弱/删除测试与覆盖率、扩大兼容白名单和修改冻结 CAPTCHA。
|
||||
7. 阶段完成证据必须绑定最终阶段提交和完整命令输出;中间提交、局部命令或先前声明不能单独关闭阶段。
|
||||
|
||||
### 16.2 行为与兼容
|
||||
|
||||
@@ -541,7 +551,7 @@ npm run build --prefix frontend
|
||||
## 18. 计划维护规则
|
||||
|
||||
1. 本文只允许修改目标、阶段范围、状态、验收条件、固定顺序和强制约束。
|
||||
2. 禁止在本文新增任何历史流水、阶段内工作分类、时间线、提交清单或人员记录。
|
||||
2. 禁止在本文新增阶段内部的临时提交、逐文件进度或人员记录;阶段级完成证据维护在 `refactoring-progress.md`。
|
||||
3. 阶段内临时发现写入 PR 描述或 issue,不写入总计划;只有改变阶段范围或验收条件时才更新本文。
|
||||
4. 阶段完成时只把状态从 `当前迭代` 改为 `已完成`,并把下一个阶段改为 `当前迭代`。
|
||||
4. 阶段完成时只更新一次状态表,并在验收记录中一次性写入最终提交、完整命令输出、覆盖率和下一阶段入口。
|
||||
5. 若阶段被阻塞,只将状态改为 `阻塞`;阻塞原因和尝试过程留在任务报告,不写入本文。
|
||||
@@ -1,8 +1,36 @@
|
||||
# 重构阶段验收记录
|
||||
|
||||
本文件只记录阶段整体的验收证据、更新日志和阶段边界。每个阶段对应一个 PR;阶段内并行实现不形成独立任务、独立验收或额外 PR。
|
||||
本文件只记录阶段整体的验收证据、更新日志和阶段边界。阶段是唯一交付和评审单位;同一阶段可以
|
||||
同时修改多个 Go 包、前端 feature、测试、架构门禁和文档。阶段中的本地工作区可暂时不可编译,只有
|
||||
最终阶段提交必须可编译、可启动、可测试,并附上完整命令输出和覆盖率证据。
|
||||
|
||||
当前复核结论:阶段 5 已完成。账号重启取消语义、Server 构造错误、独立关闭预算、应用服务组合根迁移、外部调用取消/超时和最终 Join 均已有实现与验证证据。阶段 7 与阶段 9 的原完成声明暂不作为最终验收依据,按当前路线保持待执行。
|
||||
当前复核结论:阶段 0–3 保持完成,阶段 4 是当前迭代,阶段 5–10 均待执行。此前关于 Server
|
||||
组合根迁移、生命周期迁移、React Feature 化和 DB 治理的“已完成”证据已撤销为重新验收输入,不能
|
||||
关闭任何阶段。后续 agent 不得把阶段拆成多个独立交付任务;可使用临时本地提交,但最终只合并阶段级提交。
|
||||
|
||||
## 阶段 4:治理与计划修正
|
||||
|
||||
状态:当前迭代,尚未产生最终阶段提交。
|
||||
|
||||
目标与执行指导:在同一阶段完成数据密钥原子创建、HTTP 同步 Bind/启动回滚、非 loopback 未初始化
|
||||
高等级无秘密告警、`notifier_test.go` 的 SA1012 修复、远程首次初始化风险文档,以及 Server 组合根迁移。
|
||||
组合根必须在 `cmd/server` 和 `internal/adapter` 构造全部应用服务、runner、coordinator 与生命周期组件;
|
||||
`internal/server` 只接收不可变的 `ApplicationServices` 和 `Dependencies`,保留 DTO/路由/错误映射,删除
|
||||
业务服务和 worker 工厂、`ApplicationLifecycleComponents()`、manager/notifier/automation/platform/DB 生产持有。
|
||||
|
||||
完成证据:仅接受最终阶段提交绑定的完整命令输出;当前阶段仍在执行,以下命令是最终门禁:
|
||||
|
||||
```text
|
||||
go test ./cmd/server ./internal/server ./internal/notify -count=1
|
||||
go test -race ./cmd/server ./internal/server ./internal/notify -count=1
|
||||
go test ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||
go test -race ./internal/application/... ./internal/adapter ./internal/server -count=1
|
||||
go vet ./...
|
||||
make lint
|
||||
make comments
|
||||
go run ./tools/architecturecheck
|
||||
git diff --check
|
||||
```
|
||||
|
||||
## 阶段 3:HTTP API 契约
|
||||
|
||||
@@ -12,7 +40,7 @@
|
||||
|
||||
## 阶段 4:Server 应用服务
|
||||
|
||||
状态:已完成;对应一个阶段 4 PR 边界。
|
||||
状态:已撤销,内容仅作为当前阶段的历史输入,不构成完成证据。
|
||||
|
||||
完成证据:
|
||||
|
||||
@@ -44,7 +72,7 @@ git diff --check
|
||||
|
||||
## 阶段 5:应用装配与生命周期
|
||||
|
||||
状态:已完成;对应一个阶段 5 PR 边界。原阶段 5 验收声明已按组合根、关闭预算和 Join 复核结果重新确认。
|
||||
状态:待执行;原完成声明撤销,内容仅作为重新验收输入。
|
||||
|
||||
当前切片证据(不代表阶段完成):
|
||||
|
||||
@@ -86,7 +114,7 @@ git diff --check
|
||||
|
||||
覆盖率证据:`make cover` 运行且 Go statements 为 66.0%;`make cover-frontend` 运行且 Frontend V8 statements 为 79.44%;`make cover-browser` 已以 `RUN_BROWSER_INTEGRATION=1` 运行,本地 Chromium Browser statements 为 63.5%。未使用真实账号或外部平台;覆盖率中的未覆盖 UI 页面和外部平台路径仍按既有分类保留,不以豁免替代业务 Hook、状态转换、取消或生命周期测试。
|
||||
|
||||
下一安全入口:阶段 7「React Feature 化」。仅处理 `app -> features -> shared`、feature API adapter、状态归属与路由加载;不得回退阶段 5 的组合根、Context、关闭预算或可重试 Join 边界。
|
||||
下一安全入口:阶段 4 的组合根迁移完成并取得最终阶段级证据后,才进入阶段 5 生命周期、Engine 与 Automation 重新验收。
|
||||
|
||||
## 更新日志
|
||||
|
||||
@@ -96,11 +124,12 @@ git diff --check
|
||||
- 2026-08-18:将数据库健康检查端口迁至进程组合根,删除 Server 对系统依赖组的构造职责,并补充缺失端口与架构回流测试。
|
||||
- 2026-08-18:将设置、管理员、账号任务、通知、分析、自动化规则/异常、卡券、发布后规则、默认回复和关键词服务迁至显式 transport 应用服务集合,补充组合根构造与缺失依赖测试;阶段 5 仍保持当前迭代。
|
||||
- 2026-08-18:完成通知、SMTP、MTOP、QR 登录、续期、WebSocket 和浏览器外部调用取消/超时审计;记录浏览器同步 Playwright 停止的不可中断约束、通知/自动化 nil Context 防御缺口和最终 Join 验收入口,阶段 5 仍保持当前迭代。
|
||||
- 2026-08-18:完成最终 Join 收口;协调器关闭超时后保留未完成组件并支持更长 Context 重试,并发关闭返回本轮固定错误;通知与自动化 nil Context 拒绝启动。阶段 5 验收完成,下一安全入口转为阶段 7。
|
||||
- 2026-08-18:完成最终 Join 收口;协调器关闭超时后保留未完成组件并支持更长 Context 重试,并发关闭返回本轮固定错误;通知与自动化 nil Context 拒绝启动。该记录仅作为重新验收输入。
|
||||
- 2026-08-18:按阶段级交付规则重置状态:阶段 4 设为当前迭代,阶段 5–10 设为待执行;历史局部证据不再代替最终阶段提交和完整命令输出。
|
||||
|
||||
## 阶段 6:Engine 与 Automation
|
||||
### 阶段 5 的 Engine 与 Automation 历史输入
|
||||
|
||||
状态:已完成;对应一个阶段 6 PR 边界。阶段内并行实现不形成独立任务、独立验收或额外 PR。
|
||||
状态:待执行;原完成声明撤销,内容仅作为重新验收输入。
|
||||
|
||||
完成证据:
|
||||
|
||||
@@ -113,7 +142,7 @@ git diff --check
|
||||
- 自动化外部动作在运行检查点后执行,保留成功、失败和 `needs_review` 三态。结果通知以 `runID + status` 作为持久化 outbox 幂等键,重复恢复不会重复入队;外部投递成功但本地确认失败的 `uncertain` 记录不会自动重放。SQLite、MySQL、PostgreSQL 的 `00034` 通知幂等迁移已对齐。
|
||||
- 冻结 CAPTCHA 受保护文件未改动;浏览器集成和全部冻结行为测试通过。
|
||||
|
||||
下一安全入口:阶段 7「React Feature 化」。仅处理 `app -> features -> shared`、feature API adapter、状态归属与路由加载,不回退阶段 6 的 Engine、Automation、凭证、通知或并发边界。
|
||||
下一安全入口:阶段 5 完整重新验收后,再进入阶段 6 React Feature 化和异步状态修复。
|
||||
|
||||
当前统一验证证据:
|
||||
|
||||
@@ -136,9 +165,9 @@ make cover-frontend
|
||||
|
||||
- 2026-08-17:完成阶段 6 整体 Engine 与 Automation 改造,统一收束 facade、凭证和 worker 生命周期、锁外外部 I/O、运行检查点及通知幂等/不确定态,并通过阶段 6 全部门禁。
|
||||
|
||||
## 阶段 7:React Feature 化
|
||||
## 阶段 6:React Feature 化与异步状态
|
||||
|
||||
状态:当前迭代;原阶段 7 验收声明因商品批量流程的取消与旧响应隔离不完整而暂不关闭。
|
||||
状态:待执行;原完成声明撤销,内容仅作为重新验收输入。
|
||||
|
||||
完成证据:
|
||||
|
||||
@@ -165,7 +194,7 @@ make check # 通过
|
||||
|
||||
覆盖率例外:纯 React 页面、展示组件与错误边界在本阶段的 V8 报告中存在未覆盖行;所有新改动的业务 API、Hook、状态、取消、切换和乱序行为均由确定性 Vitest 覆盖。无真实账号或外部平台调用。
|
||||
|
||||
下一安全入口:阶段 8「DB 与事务治理」,仅处理窄 repository、应用层 Unit of Work、批量与三方言事务验收;不得回退阶段 7 的 feature 边界、共享 HTTP 或路由加载约束。
|
||||
下一安全入口:阶段 6 完成后进入阶段 7 DB 与事务治理;阶段 7 完成后依次进入阶段 8 架构门禁与兼容退场、阶段 9 注释与复杂度收口和阶段 10 最终全栈复验。
|
||||
|
||||
更新日志:
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@
|
||||
自动创建 `admin`;如果使用其他方式启动且数据库尚未初始化,页面会显示初始化表单,填写
|
||||
两次不少于 8 个字符的密码即可。
|
||||
|
||||
> 安全提示:源码和容器使用 `-addr :59188` 时会监听全部接口。未初始化实例的网页首次初始化没有
|
||||
> 预共享 secret,最先连到管理端口的客户端可以创建管理员。该便利行为不做 IP 限制,部署者必须在
|
||||
> 防火墙、安全组或反向代理层限制访问;公网部署建议设置 `XIANYU_ADMIN_PASSWORD` 或先使用
|
||||
> `-init-admin` 完成初始化。
|
||||
|
||||
默认连接已由 `compose.yml` 注入,不需要手写 PostgreSQL URL。若修改 `COMPOSE_PROJECT_NAME`,新卷名前缀也会变化;已有部署升级时保留原 `.env`,避免误用新空卷。
|
||||
|
||||
Docker 中的自动续期会使用容器内 Chromium 检测到的 Linux 原生浏览器指纹请求闲鱼官网;不会因为宿主系统是 Linux 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
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 { getPublishLocations as queryPublishLocations, type PublishLocationRequestOptions } from '../../../services/amapLocation';
|
||||
import type { PublishLocation } from '../../../shared/api-contract';
|
||||
|
||||
/** 商品账号筛选器读取非敏感账号摘要。 */
|
||||
@@ -16,7 +16,8 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis
|
||||
/** 商品页面读取自动化发货规则的兼容列表。 */
|
||||
export const getShippingRules = async (options?: RequestControlOptions): Promise<ShippingRule[]> => get('/api/v1/automation-rules', undefined, options);
|
||||
|
||||
export { getPublishLocations };
|
||||
// getPublishLocations 通过 feature API 边界读取地点,并把取消/超时控制传入地图服务。
|
||||
export const getPublishLocations = (longitude: number, latitude: number, options?: PublishLocationRequestOptions): Promise<PublishLocation[]> => queryPublishLocations(longitude, latitude, options);
|
||||
export type { PublishLocation } from '../../../shared/api-contract';
|
||||
// Items
|
||||
// normalizeBooleanFlag 归一化布尔标记。
|
||||
|
||||
@@ -22,10 +22,11 @@ describe('ItemList batch state',
|
||||
expect(canStartBatch(null)).toBe(false);
|
||||
});
|
||||
|
||||
// 运行中和安全取消中的任务都必须继续轮询远端结果。
|
||||
test('keeps polling running and canceling tasks',
|
||||
// 轮询场景回调验证运行和取消中的任务状态。
|
||||
// 等待、运行中和安全取消中的任务都必须继续轮询远端结果。
|
||||
test('keeps polling pending, running and canceling tasks',
|
||||
// 轮询场景回调验证等待、运行和取消中的任务状态。
|
||||
() => {
|
||||
expect(isBatchInProgress('pending')).toBe(true);
|
||||
expect(isBatchInProgress('running')).toBe(true);
|
||||
expect(isBatchInProgress('canceling')).toBe(true);
|
||||
expect(isBatchInProgress('completed')).toBe(false);
|
||||
|
||||
@@ -6,15 +6,15 @@ export interface PublishBatchSummary {
|
||||
status?: string;
|
||||
}
|
||||
|
||||
// selectActivePublishBatch 只选择仍可继续处理的运行中任务。
|
||||
// selectActivePublishBatch 只选择仍可继续处理或等待 worker 接管的活跃任务。
|
||||
export const selectActivePublishBatch = <T extends PublishBatchSummary>(batches: T[]): T | undefined =>
|
||||
batches.find(
|
||||
// 活跃任务筛选器排除已完成历史,避免覆盖新的上传流程。
|
||||
batch => batch.status === 'running' || batch.status === 'canceling',
|
||||
batch => batch.status === 'pending' || batch.status === 'running' || batch.status === 'canceling',
|
||||
);
|
||||
|
||||
// isBatchInProgress 判断批量任务是否仍需要继续轮询。
|
||||
export const isBatchInProgress = (status?: string): boolean => status === 'running' || status === 'canceling';
|
||||
export const isBatchInProgress = (status?: string): boolean => status === 'pending' || status === 'running' || status === 'canceling';
|
||||
|
||||
// BatchPreviewGate 是判断预检是否可以启动任务的最小模型。
|
||||
export interface BatchPreviewGate {
|
||||
|
||||
@@ -297,7 +297,7 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任
|
||||
await act(/* timerAction 推进批量轮询计时器。 */ async () => {
|
||||
await vi.advanceTimersByTimeAsync(3_000);
|
||||
});
|
||||
expect(getBatchMock).toHaveBeenCalledWith('batch-1');
|
||||
expect(getBatchMock).toHaveBeenCalledWith('batch-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(loadItems).toHaveBeenCalledOnce();
|
||||
expect(loadShippingRules).toHaveBeenCalledOnce();
|
||||
hook.unmount();
|
||||
|
||||
@@ -49,8 +49,6 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
const [batchPublishIntervalSeconds, setBatchPublishIntervalSeconds] = useState(5);
|
||||
// batchLoading 表示批量任务请求是否正在执行。
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
// batchPollInFlight 防止同一批次的轮询请求重叠。
|
||||
const batchPollInFlight = useRef(false);
|
||||
// batchRequestGeneration 用于丢弃弹窗关闭后返回的过期轮询响应。
|
||||
const batchRequestGeneration = useRef(0);
|
||||
// batchRequestController 保存当前用户触发请求的取消器;新动作或组件卸载时必须中止旧请求。
|
||||
@@ -115,7 +113,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
setRecentBatch(detail);
|
||||
setBatchDetail(detail);
|
||||
setBatchPublishIntervalSeconds(detail.publish_interval_seconds || 5);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
setBatchPhase(isBatchInProgress(detail.status) ? 'running' : 'done');
|
||||
}
|
||||
} catch (error /* 恢复任务错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
@@ -182,7 +180,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchDetail(detail);
|
||||
setBatchPublishIntervalSeconds(detail.publish_interval_seconds || 5);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
setBatchPhase(isBatchInProgress(detail.status) ? 'running' : 'done');
|
||||
} catch (error /* 最近结果读取错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
console.error('加载最近批量铺货结果失败:', error);
|
||||
@@ -372,13 +370,17 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
if (!showBatchModal || !batchDetail?.id || !isBatchInProgress(batchDetail.status)) return;
|
||||
// requestGeneration 标记本次轮询生命周期,弹窗关闭时会失效。
|
||||
const requestGeneration = ++batchRequestGeneration.current;
|
||||
// controller 是本轮弹窗会话独占的轮询取消器;关闭、切换批次或卸载时必须中止未完成读取。
|
||||
const controller = new AbortController();
|
||||
// pollInFlight 只保护当前批次会话,旧请求不会阻塞重新打开后的新批次轮询。
|
||||
let pollInFlight = false;
|
||||
// pollBatch 读取任务最新进度并在结束后刷新商品和规则列表。
|
||||
const pollBatch = async () => {
|
||||
if (batchPollInFlight.current) return;
|
||||
batchPollInFlight.current = true;
|
||||
if (pollInFlight || controller.signal.aborted) return;
|
||||
pollInFlight = true;
|
||||
try {
|
||||
// detail 是轮询返回的最新任务详情。
|
||||
const detail = await getItemPublishBatch(batchDetail.id);
|
||||
const detail = await getItemPublishBatch(batchDetail.id, { signal: controller.signal });
|
||||
if (!isCurrentBatchRequest(requestGeneration, batchRequestGeneration.current)) return;
|
||||
setBatchDetail(detail);
|
||||
setRecentBatch(detail);
|
||||
@@ -387,9 +389,9 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
await Promise.all([options.loadItems(), options.loadShippingRules()]);
|
||||
}
|
||||
} catch (error /* 轮询读取错误 */) {
|
||||
console.error('刷新批量铺货进度失败:', error);
|
||||
if (!controller.signal.aborted) console.error('刷新批量铺货进度失败:', error);
|
||||
} finally {
|
||||
batchPollInFlight.current = false;
|
||||
pollInFlight = false;
|
||||
}
|
||||
};
|
||||
// timer 是当前批次的轮询计时器。
|
||||
@@ -402,6 +404,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
// 轮询清理器停止计时器并使未完成响应失效。
|
||||
() => {
|
||||
window.clearInterval(timer);
|
||||
controller.abort();
|
||||
batchRequestGeneration.current += 1;
|
||||
}
|
||||
);
|
||||
|
||||
@@ -73,7 +73,7 @@ describe('useItemActions', /* 当前回调验证商品普通操作、发布和
|
||||
|
||||
test('同步、编辑、添加和删除商品均刷新或更新列表', /* 当前回调验证商品 CRUD 动作协调。 */ async () => {
|
||||
// hook 是商品动作 Hook 的真实 React 状态实例。
|
||||
const hook = renderHook(() => useItemActionsHarness());
|
||||
const hook = renderHook(/* delayedLocationHookFactory 创建可关闭普通发布弹窗的商品动作状态容器。 */ () => useItemActionsHarness());
|
||||
await act(/* 当前回调执行商品同步。 */ async () => hook.result.current.actions.handleSync());
|
||||
expect(syncItemsMock).toHaveBeenCalledWith('account-1');
|
||||
|
||||
@@ -94,7 +94,7 @@ describe('useItemActions', /* 当前回调验证商品普通操作、发布和
|
||||
|
||||
test('普通发布成功后清理表单并打开发货规则配置', /* 当前回调验证普通发布成功分支。 */ async () => {
|
||||
// hook 是商品动作 Hook 的真实 React 状态实例。
|
||||
const hook = renderHook(() => useItemActionsHarness());
|
||||
const hook = renderHook(/* delayedLocationHookFactory 创建可关闭普通发布弹窗的商品动作状态容器。 */ () => useItemActionsHarness());
|
||||
act(/* 当前回调写入普通发布商品表单。 */ () => hook.result.current.actions.setPublishForm({ cookie_id: 'account-1', title: '新商品', description: '描述', price: '20', original_price: '', quantity: '2', postage_mode: 'free', postage: '', images: [new File(['image'], 'image.jpg')] }));
|
||||
await act(/* 当前回调执行普通商品发布。 */ async () => hook.result.current.actions.handlePublishItem());
|
||||
expect(publishItemMock).toHaveBeenCalledWith(expect.objectContaining({ cookie_id: 'account-1', title: '新商品', quantity: '2', images: expect.any(Array) }));
|
||||
@@ -111,10 +111,33 @@ describe('useItemActions', /* 当前回调验证商品普通操作、发布和
|
||||
const hook = renderHook(() => useItemActionsHarness());
|
||||
act(/* 当前回调设置定位使用的普通发布账号。 */ () => hook.result.current.actions.setPublishForm(current => ({ ...current, cookie_id: 'account-1' })));
|
||||
await act(/* 当前回调加载普通发布发货地。 */ async () => hook.result.current.actions.locateForPublish(false));
|
||||
expect(locationsMock).toHaveBeenCalledWith(120, 30);
|
||||
expect(locationsMock).toHaveBeenCalledWith(120, 30, expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.actions.publishLocation).toEqual(locationFixture);
|
||||
await act(/* 当前回调加载批量发布发货地。 */ async () => hook.result.current.actions.locateForPublish(true));
|
||||
expect(hook.result.current.actions.locationLoading).toBe(false);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('关闭普通发布弹窗后忽略晚到的浏览器定位与地点回调', /* 当前回调验证弹窗关闭会撤销定位请求的界面所有权。 */ async () => {
|
||||
// resolvePosition 保存测试主动发送晚到浏览器定位结果的函数。
|
||||
let resolvePosition: PositionCallback | undefined;
|
||||
// getCurrentPositionMock 保存浏览器定位回调但不立即完成,模拟用户关闭弹窗后才返回。
|
||||
const getCurrentPositionMock = vi.fn(/* delayedPositionAction 延迟交付浏览器定位结果。 */ (success: PositionCallback) => { resolvePosition = success; });
|
||||
vi.stubGlobal('navigator', { geolocation: { getCurrentPosition: getCurrentPositionMock } });
|
||||
// hook 是包含普通发布表单状态的商品动作 Hook。
|
||||
const hook = renderHook(() => useItemActionsHarness());
|
||||
act(/* openPublishAction 打开普通发布弹窗并选择发布账号。 */ () => {
|
||||
hook.result.current.actions.setPublishForm(/* accountFormAction 为晚到定位测试设置普通发布账号。 */ current => ({ ...current, cookie_id: 'account-1' }));
|
||||
hook.result.current.actions.setShowPublishModal(true);
|
||||
});
|
||||
act(/* beginLocateAction 启动尚未返回的定位流程。 */ () => { void hook.result.current.actions.locateForPublish(false); });
|
||||
act(/* closePublishAction 关闭弹窗并取消当前定位所有权。 */ () => hook.result.current.actions.setShowPublishModal(false));
|
||||
await act(/* latePositionAction 交付已失效的浏览器定位结果。 */ async () => {
|
||||
resolvePosition?.({ coords: { longitude: 120, latitude: 30 } } as GeolocationPosition);
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(locationsMock).not.toHaveBeenCalled();
|
||||
expect(hook.result.current.actions.locationLoading).toBe(false);
|
||||
hook.unmount();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { Item } from '../../../shared/api-contract';
|
||||
import { createItem, deleteItem, getPublishLocations, publishItem, syncItemsFromAccount, updateItem } from './api';
|
||||
import type { PublishLocation } from './api';
|
||||
@@ -171,6 +171,10 @@ export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems,
|
||||
const [publishForm, setPublishForm] = useState<PublishItemForm>(emptyPublishItemForm);
|
||||
// publishImagePreviews 保存发布图片预览地址。
|
||||
const [publishImagePreviews, setPublishImagePreviews] = useState<{ /** key 是图片文件和索引组合键。 */ key: string; /** url 是图片临时预览地址。 */ url: string }[]>([]);
|
||||
// locationController 保存当前定位请求的取消器,新的定位和组件卸载必须终止旧请求。
|
||||
const locationController = useRef<AbortController | null>(null);
|
||||
// locationGeneration 丢弃已经失去当前界面所有权的定位响应。
|
||||
const locationGeneration = useRef(0);
|
||||
|
||||
// useEffect 管理普通发布图片对象地址的创建和释放。
|
||||
useEffect(/* 当前回调同步发布图片预览资源生命周期。 */ () => {
|
||||
@@ -184,6 +188,22 @@ export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems,
|
||||
return /* 当前回调释放当前批次的图片预览地址。 */ () => previews.forEach(/* 当前回调释放单个图片预览。 */ preview => URL.revokeObjectURL(preview.url));
|
||||
}, [publishForm.images, showPublishModal]);
|
||||
|
||||
// cancelLocationLookup 结束当前定位状态并使高德、浏览器定位的晚到回调失效。
|
||||
const cancelLocationLookup = useCallback(/* cancelLocationAction 中止当前拥有的定位会话并推进代次。 */ () => {
|
||||
locationController.current?.abort();
|
||||
locationController.current = null;
|
||||
locationGeneration.current += 1;
|
||||
setLocationLoading(false);
|
||||
}, []);
|
||||
|
||||
// 定位请求由商品动作 Hook 拥有,组件卸载时必须释放浏览器和地图查询资源。
|
||||
useEffect(/* locationUnmountCleanup 在组件卸载时取消由当前 Hook 拥有的定位请求。 */ () => cancelLocationLookup, [cancelLocationLookup]);
|
||||
|
||||
// 普通发布弹窗关闭时收回其专属定位请求,避免关闭后的浏览器或高德回调写入隐藏表单。
|
||||
useEffect(/* publishModalLocationCleanup 监听普通发布弹窗可见性并取消失去界面所有权的定位请求。 */ () => {
|
||||
if (!showPublishModal) cancelLocationLookup();
|
||||
}, [cancelLocationLookup, showPublishModal]);
|
||||
|
||||
// handleSync 同步当前账号商品并刷新列表。
|
||||
const handleSync = useCallback(/* syncAction 执行当前账号商品同步。 */ async () => {
|
||||
if (!selectedAccount) return alert('请先选择账号');
|
||||
@@ -337,29 +357,50 @@ export const useItemActions = ({ selectedAccount, setSelectedAccount, setItems,
|
||||
const cookieId = batch ? selectedAccount : publishForm.cookie_id;
|
||||
if (!cookieId) return alert('请先选择发布账号');
|
||||
if (!navigator.geolocation) return alert('当前浏览器不支持定位');
|
||||
cancelLocationLookup();
|
||||
// controller 是本次定位及地点搜索共同使用的取消器。
|
||||
const controller = new AbortController();
|
||||
locationController.current = controller;
|
||||
// generation 是本次定位请求的所有权版本,晚到响应只能写回同一版本。
|
||||
const generation = ++locationGeneration.current;
|
||||
setLocationLoading(true);
|
||||
navigator.geolocation.getCurrentPosition(/* 当前回调处理定位成功结果。 */ async position => {
|
||||
try {
|
||||
// locations 保存当前位置附近的发货地。
|
||||
const locations = await getPublishLocations(position.coords.longitude, position.coords.latitude);
|
||||
if (!locations.length) throw new Error('当前位置附近没有可用的高德发货地,请稍后重试');
|
||||
if (batch) {
|
||||
setBatchLocations(locations);
|
||||
setBatchLocation(locations[0]);
|
||||
} else {
|
||||
setPublishLocations(locations);
|
||||
setPublishLocation(locations[0]);
|
||||
}
|
||||
} catch (/* error 表示发货地查询异常。 */ error: unknown) {
|
||||
try {
|
||||
// position 是浏览器返回的当前定位结果;Promise 契约确保调用方会等待它完成。
|
||||
const position = await new Promise<GeolocationPosition>(/* positionPromiseExecutor 将回调式浏览器定位转为可等待的 Promise。 */ (resolve, reject) => {
|
||||
// successCallback 将浏览器定位成功结果交给当前请求。
|
||||
const successCallback: PositionCallback = value => resolve(value);
|
||||
// errorCallback 将浏览器定位失败转换为可统一处理的异常。
|
||||
const errorCallback: PositionErrorCallback = error => reject(error);
|
||||
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, { enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 });
|
||||
});
|
||||
if (controller.signal.aborted || generation !== locationGeneration.current) return;
|
||||
// locations 保存当前位置附近的发货地。
|
||||
const locations = await getPublishLocations(position.coords.longitude, position.coords.latitude, { signal: controller.signal });
|
||||
if (controller.signal.aborted || generation !== locationGeneration.current) return;
|
||||
if (!locations.length) throw new Error('当前位置附近没有可用的高德发货地,请稍后重试');
|
||||
if (batch) {
|
||||
setBatchLocations(locations);
|
||||
setBatchLocation(locations[0]);
|
||||
} else {
|
||||
setPublishLocations(locations);
|
||||
setPublishLocation(locations[0]);
|
||||
}
|
||||
} catch (/* error 表示发货地查询异常。 */ error: unknown) {
|
||||
if (controller.signal.aborted || generation !== locationGeneration.current) return;
|
||||
if (typeof error === 'object' && error !== null && 'code' in error) {
|
||||
// positionError 是浏览器 Geolocation API 的失败对象,用于区分权限拒绝与其他定位错误。
|
||||
const positionError = error as GeolocationPositionError;
|
||||
alert(positionError.code === positionError.PERMISSION_DENIED ? '定位权限被拒绝,请在浏览器设置中允许定位' : '无法获取当前位置,请稍后重试');
|
||||
} else {
|
||||
alert(itemErrorMessage(error, '获取发货地失败'));
|
||||
} finally {
|
||||
}
|
||||
} finally {
|
||||
if (generation === locationGeneration.current) {
|
||||
locationController.current = null;
|
||||
setLocationLoading(false);
|
||||
}
|
||||
}, /* error 表示浏览器定位异常。 */ error => {
|
||||
setLocationLoading(false);
|
||||
alert(error.code === error.PERMISSION_DENIED ? '定位权限被拒绝,请在浏览器设置中允许定位' : '无法获取当前位置,请稍后重试');
|
||||
}, { enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 });
|
||||
}, [publishForm.cookie_id, selectedAccount, setBatchLocation, setBatchLocations]);
|
||||
}
|
||||
}, [cancelLocationLookup, publishForm.cookie_id, selectedAccount, setBatchLocation, setBatchLocations]);
|
||||
|
||||
return { selectedAccount, setSelectedAccount, loading, publishing, showEditModal, setShowEditModal, showAddModal, setShowAddModal, showPublishModal, setShowPublishModal, locationLoading, publishLocations, setPublishLocations, publishLocation, setPublishLocation, selectedItem, editForm, setEditForm, addForm, setAddForm, publishForm, setPublishForm, publishImagePreviews, handleSync, handleEdit, handleSaveEdit, handleDelete, handleAddItem, handlePublishItem, downloadPublishTemplate, openAddModal, openPublishModal, locateForPublish };
|
||||
};
|
||||
@@ -82,6 +82,35 @@ describe('AMap 地点业务适配', /* 当前回调覆盖坐标校验和地点
|
||||
await expect(getPublishLocations(120, 30)).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
test('取消和超时会结束等待中的高德查询,晚到回调不会改写结果', /* 当前回调验证地点查询的取消、超时与晚到回调隔离。 */ async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
// callback 保存模拟 SDK 晚到返回时使用的回调。
|
||||
let callback: ((status: string, result: unknown) => void) | undefined;
|
||||
// placeSearch 是永不主动完成的地点搜索构造器替身。
|
||||
const placeSearch = vi.fn(/* placeSearchConstructor 创建不会主动回调的 SDK 搜索替身。 */ function placeSearchConstructor() {
|
||||
return { searchNearBy: /* pendingSearchAction 只保存 SDK 回调,等待测试主动触发。 */ (_keyword: string, _center: [number, number], _radius: number, value: (status: string, result: unknown) => void) => { callback = value; } };
|
||||
});
|
||||
Object.defineProperty(window, 'AMap', { configurable: true, value: { PlaceSearch: placeSearch } });
|
||||
// controller 是主动取消地点查询的调用方取消器。
|
||||
const controller = new AbortController();
|
||||
// cancelled 是等待主动取消结果的查询 Promise。
|
||||
const cancelled = getPublishLocations(120, 30, { signal: controller.signal });
|
||||
controller.abort();
|
||||
await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' });
|
||||
callback?.('complete', { poiList: { pois: [{ id: 'poi-1', name: '晚到地点', adname: '区域', cityname: '城市', adcode: '100', pname: '省份', location: { lng: 120, lat: 30 } }] } });
|
||||
|
||||
// timedOut 是等待 SDK 永不回调时的时间预算收口。
|
||||
const timedOut = getPublishLocations(120, 30, { timeoutMs: 10 });
|
||||
// timeoutAssertion 是对时间预算触发后查询错误的异步断言。
|
||||
const timeoutAssertion = expect(timedOut).rejects.toThrow('附近地址查询超时');
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
await timeoutAssertion;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('POI 映射拒绝越界坐标和缺失行政字段', /* 当前回调验证领域地点模型的完整性守卫。 */ () => {
|
||||
expect(amapPOIToPublishLocation({ id: 'poi', name: '地点', adcode: '1', pname: '省', cityname: '市', location: { lng: 181, lat: 30 } })).toBeNull();
|
||||
expect(amapPOIToPublishLocation({ id: 'poi', name: '地点', adcode: '1', pname: '省', cityname: '市', location: { lng: 120, lat: 30 } })).not.toBeNull();
|
||||
|
||||
@@ -53,6 +53,14 @@ interface AMapAPI {
|
||||
PlaceSearch: new (options: { /* extensions 表示extensions。 */ extensions: 'all'; /* pageSize 表示pageSize。 */ pageSize: number }) => AMapPlaceSearch;
|
||||
}
|
||||
|
||||
// PublishLocationRequestOptions 控制高德地点查询的取消和最长等待时间。
|
||||
export interface PublishLocationRequestOptions {
|
||||
// signal 是调用方在组件卸载、切换账号或关闭弹窗时触发的取消信号。
|
||||
signal?: AbortSignal;
|
||||
// timeoutMs 是高德地点回调允许占用的最长毫秒数。
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
// AMap 表示AMap。
|
||||
@@ -146,27 +154,49 @@ export const amapPOIToPublishLocation = (poi: AMapPOI): PublishLocation | null =
|
||||
return location;
|
||||
};
|
||||
|
||||
export const getPublishLocations = async (longitude: number, latitude: number): Promise<PublishLocation[]> => {
|
||||
export const getPublishLocations = async (longitude: number, latitude: number, options: PublishLocationRequestOptions = {}): Promise<PublishLocation[]> => {
|
||||
if (!validCoordinate(longitude) || !validCoordinate(latitude) || longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90) {
|
||||
throw new Error('经纬度无效');
|
||||
}
|
||||
const amap = await loadAMap(); /* amap 表示amap。 */
|
||||
return new Promise<PublishLocation[]>((resolve, reject) => {
|
||||
// settled 标记本次查询是否已经结束,阻止超时、取消和 SDK 回调重复收口。
|
||||
let settled = false;
|
||||
// timeoutMs 是地点搜索回调的有限等待预算,防止 AMap 永不回调时永久 loading。
|
||||
const timeoutMs = Math.max(1, options.timeoutMs ?? 10_000);
|
||||
// finish 统一清理本次搜索的定时器和取消监听,确保 Promise 只完成一次。
|
||||
const finish = (callback: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
globalThis.clearTimeout(timer);
|
||||
options.signal?.removeEventListener('abort', abortSearch);
|
||||
callback();
|
||||
};
|
||||
// abortSearch 将调用方取消转换为 Promise 拒绝,SDK 晚到回调随后只会被忽略。
|
||||
const abortSearch = () => finish(() => reject(new DOMException('aborted', 'AbortError')));
|
||||
// timer 是地点搜索超时定时器,成功、失败和取消时都会清理。
|
||||
const timer = globalThis.setTimeout(/* searchTimeoutAction 在 SDK 未回调时统一结束地点查询。 */ () => finish(/* timeoutRejectAction 将超时原因传回调用方。 */ () => reject(new Error('高德地图附近地址查询超时,请稍后重试'))), timeoutMs);
|
||||
if (options.signal?.aborted) {
|
||||
abortSearch();
|
||||
return;
|
||||
}
|
||||
options.signal?.addEventListener('abort', abortSearch, { once: true });
|
||||
const placeSearch = new amap.PlaceSearch({ extensions: 'all', pageSize: 10 }); /* placeSearch 表示placeSearch。 */
|
||||
placeSearch.searchNearBy('', [longitude, latitude], 1_000, (status, result) => {
|
||||
if (settled) return;
|
||||
if (status !== 'complete') {
|
||||
if (status === 'no_data') {
|
||||
resolve([]);
|
||||
finish(/* noDataResolveAction 将高德无数据状态作为正常空地点列表返回。 */ () => resolve([]));
|
||||
return;
|
||||
}
|
||||
reject(new Error('高德地图附近地址查询失败,请稍后重试'));
|
||||
finish(/* searchFailureRejectAction 将高德失败状态转换为用户可见错误。 */ () => reject(new Error('高德地图附近地址查询失败,请稍后重试')));
|
||||
return;
|
||||
}
|
||||
// locations 是过滤无效坐标后的发布地点列表,供商品发布表单使用。
|
||||
const locations = (result?.poiList?.pois || [])
|
||||
.map(amapPOIToPublishLocation)
|
||||
.filter((location): location is PublishLocation => location !== null /* location 是转换后仍具备有效坐标的地点。 */);
|
||||
resolve(locations);
|
||||
finish(/* searchSuccessResolveAction 将已过滤的有效地点列表交给调用方。 */ () => resolve(locations));
|
||||
} /* 搜索完成后将地点结果交给调用方并结束本次高德回调。 */);
|
||||
} /* 高德回调只处理当前请求,组件卸载后由 cleanup 移除监听。 */);
|
||||
}; /* getPublishLocations 表示getPublishLocations。 */
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { del, get, post, postForm, put } from './client';
|
||||
import { ApiError, del, get, post, postForm, put } from './client';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals() /* 清理测试安装的全局网络替身,避免跨用例泄漏。 */);
|
||||
|
||||
@@ -48,11 +48,19 @@ describe('request helpers', () => {
|
||||
} /* 测试回调验证:支持 PUT 和 DELETE 请求及查询参数。 */);
|
||||
|
||||
test('surfaces unified backend errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'bad_request', message: 'bad request' }), {
|
||||
// payload 是服务端返回的统一错误 envelope,包含调用方恢复流程需要的追踪和细节字段。
|
||||
const payload = { code: 'bad_request', message: 'bad request', request_id: 'req-1', details: { field: 'title' } };
|
||||
vi.stubGlobal('fetch', vi.fn().mockImplementation(/* responseFactory 为每次断言提供未被消费的独立错误响应。 */ () => Promise.resolve(new Response(JSON.stringify(payload), {
|
||||
status: 400,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})));
|
||||
}))));
|
||||
await expect(get('/bad')).rejects.toThrow('bad request');
|
||||
try {
|
||||
await get('/bad');
|
||||
} catch (error /* error 是普通 JSON 请求必须保留结构化 envelope 的异常。 */) {
|
||||
expect(error).toBeInstanceOf(ApiError);
|
||||
expect(error).toMatchObject({ status: 400, code: 'bad_request', requestId: 'req-1', details: { field: 'title' }, payload });
|
||||
}
|
||||
} /* 测试回调验证:surfaces unified backend errors。 */);
|
||||
|
||||
test('使用非 JSON 错误文本作为失败消息', async () => {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ApiErrorResponse } from '../api-contract';
|
||||
|
||||
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
|
||||
type QueryParams = Record<string, string | number | boolean | undefined | null>;
|
||||
@@ -25,6 +27,31 @@ const uploadRequestTimeoutMs = 10 * 60_000; /* uploadRequestTimeoutMs 表示uplo
|
||||
|
||||
let authLogoutPending = false; /* authLogoutPending 表示authLogoutPending。 */
|
||||
|
||||
// ApiError 保留服务端统一错误 envelope,调用方可按稳定错误码决定重试、冲突提示或人工核对流程。
|
||||
export class ApiError extends Error {
|
||||
// status 是产生错误的 HTTP 状态码,供调用方区分授权、冲突和服务端失败。
|
||||
readonly status: number;
|
||||
// code 是服务端稳定机器错误码;非结构化响应退化为 http_<status>。
|
||||
readonly code: string;
|
||||
// requestId 是服务端请求追踪标识,用户反馈问题时可安全提供给运维。
|
||||
readonly requestId?: string;
|
||||
// details 是服务端提供的结构化恢复或审计信息,不包含客户端主动拼接的兼容字段。
|
||||
readonly details?: Record<string, unknown>;
|
||||
// payload 是保留给既有上传流程和诊断代码的原始响应载荷。
|
||||
readonly payload: unknown;
|
||||
|
||||
// constructor 根据 HTTP 响应和统一错误载荷构造可被所有请求路径复用的异常实例。
|
||||
constructor(status: number, payload: unknown) {
|
||||
super(errorMessageFromPayload(payload, status));
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
this.code = isApiErrorResponse(payload) ? payload.code : `http_${status}`;
|
||||
this.requestId = isApiErrorResponse(payload) ? payload.request_id : undefined;
|
||||
this.details = isApiErrorResponse(payload) ? payload.details : undefined;
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
|
||||
const notifyAuthExpired = () => {
|
||||
if (authLogoutPending || typeof window === 'undefined') return;
|
||||
authLogoutPending = true;
|
||||
@@ -76,9 +103,8 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 && !options.skipAuthLogout) notifyAuthExpired();
|
||||
// payload 是后端统一错误 DTO 或非 JSON 错误文本。
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 错误响应 JSON 无法解析时交由状态码兜底。 */) : await res.text().catch(() => undefined /* 错误响应文本无法读取时交由状态码兜底。 */);
|
||||
const message = errorMessageFromPayload(payload, res.status); // message 是统一错误 DTO 提取出的用户可见说明。
|
||||
throw new Error(message);
|
||||
const payload = await readResponsePayload(res, isJson);
|
||||
throw new ApiError(res.status, payload);
|
||||
}
|
||||
|
||||
if (!isJson) {
|
||||
@@ -115,14 +141,11 @@ export const postForm = async <T>(url: string, body: FormData, options: RequestC
|
||||
|
||||
const contentType = res.headers.get('content-type') || ''; /* contentType 表示contentType。 */
|
||||
const isJson = contentType.includes('application/json'); /* isJson 表示isJson。 */
|
||||
const payload = isJson ? await res.json().catch(() => undefined /* 上传错误 JSON 无法解析时交由状态码兜底。 */) : await res.text().catch(() => undefined /* 上传错误文本无法读取时交由状态码兜底。 */); /* payload 是上传接口返回的错误载荷,仅用于构造异常。 */
|
||||
const payload = await readResponsePayload(res, isJson); /* payload 是上传接口返回的成功或错误载荷。 */
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) notifyAuthExpired();
|
||||
const message = errorMessageFromPayload(payload, res.status); // message 是上传失败时统一错误 DTO 提取出的说明。
|
||||
const err = new Error(message) as Error & { /* payload 表示payload。 */ payload?: unknown }; /* err 表示当前操作返回的错误。 */
|
||||
err.payload = payload;
|
||||
throw err;
|
||||
throw new ApiError(res.status, payload);
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
@@ -143,6 +166,13 @@ const controlledSignal = (external: AbortSignal | undefined, timeoutMs: number)
|
||||
};
|
||||
}; /* controlledSignal 表示controlledSignal。 */
|
||||
|
||||
// readResponsePayload 按响应类型读取一次响应体;解析失败返回 undefined,由 ApiError 生成稳定回退信息。
|
||||
const readResponsePayload = async (response: Response, isJson: boolean): Promise<unknown> => (
|
||||
isJson
|
||||
? response.json().catch(() => undefined /* 错误响应 JSON 无法解析时交由状态码兜底。 */)
|
||||
: response.text().catch(() => undefined /* 错误响应文本无法读取时交由状态码兜底。 */)
|
||||
);
|
||||
|
||||
/** 判断响应体是否符合统一 HTTP 错误 DTO。 */
|
||||
const isApiErrorResponse = (payload: unknown): payload is ApiErrorResponse => {
|
||||
if (typeof payload !== 'object' || payload === null) return false;
|
||||
@@ -157,5 +187,3 @@ const errorMessageFromPayload = (payload: unknown, status: number): string => {
|
||||
if (isApiErrorResponse(payload)) return payload.message;
|
||||
return `请求失败: ${status}`;
|
||||
};
|
||||
|
||||
import type { ApiErrorResponse } from '../api-contract';
|
||||
@@ -37,7 +37,9 @@ func TestNotifierWaitContextHonorsDeadline(t *testing.T) {
|
||||
func TestNotifierStartRejectsNilContext(t *testing.T) {
|
||||
// notifier 保存具备启动标记的最小通知器测试替身。
|
||||
notifier := &Notifier{done: make(chan struct{})}
|
||||
notifier.Start(nil)
|
||||
// missingContext 模拟调用方遗漏生命周期 Context 的零值接口;Start 必须拒绝该输入。
|
||||
var missingContext context.Context
|
||||
notifier.Start(missingContext)
|
||||
if notifier.started.Load() {
|
||||
t.Fatal("nil Context 不应标记通知 worker 已启动")
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
)
|
||||
|
||||
// applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。
|
||||
type applicationServices struct {
|
||||
type ApplicationServices struct {
|
||||
// platformCredentials 负责按需读取平台凭证窄视图并执行归属复核。
|
||||
platformCredentials *accountapp.PlatformCredentialService
|
||||
// orders 是订单 HTTP 适配器;业务服务集合由应用层统一构造。
|
||||
@@ -100,21 +100,24 @@ type applicationServices struct {
|
||||
admin *adminapp.Service
|
||||
}
|
||||
|
||||
// applicationServices 是旧测试和兼容访问器使用的内部别名;生产组合根应使用导出的集合类型注入。
|
||||
type applicationServices = ApplicationServices
|
||||
|
||||
// emptyApplicationServices 是零值 Server 和隔离 handler 测试共享的只读空服务集合。
|
||||
// 它不包含任何生产依赖,禁止写入;生产 Server 必须在 New 阶段注入完整集合。
|
||||
var emptyApplicationServices = &applicationServices{accountLogin: &accountLoginService{}}
|
||||
|
||||
// ApplicationLifecycleComponents 返回 Server 装配的应用 worker 生命周期组件。
|
||||
// LifecycleComponents 返回由组合根登记的应用 worker 生命周期组件。
|
||||
// 组件只暴露 Start/Close 端口,启动顺序与进程取消责任由 cmd 的协调器拥有。
|
||||
func (s *Server) ApplicationLifecycleComponents() []lifecycleapp.NamedComponent {
|
||||
if s == nil || s.applications == nil {
|
||||
func (services *ApplicationServices) LifecycleComponents() []lifecycleapp.NamedComponent {
|
||||
if services == nil {
|
||||
return nil
|
||||
}
|
||||
// components 保存按应用依赖登记的 worker 生命周期组件。
|
||||
components := make([]lifecycleapp.NamedComponent, 0, 3)
|
||||
if s.applications.orderRefreshJobs != nil {
|
||||
if services.orderRefreshJobs != nil {
|
||||
// service 保存订单刷新恢复与 worker 生命周期应用服务。
|
||||
service := s.applications.orderRefreshJobs
|
||||
service := services.orderRefreshJobs
|
||||
components = append(components, lifecycleapp.NamedComponent{
|
||||
Name: "order-refresh-recovery",
|
||||
Component: lifecycleapp.FuncComponent{
|
||||
@@ -123,9 +126,9 @@ func (s *Server) ApplicationLifecycleComponents() []lifecycleapp.NamedComponent
|
||||
},
|
||||
})
|
||||
}
|
||||
if s.applications.itemBatchCoordinator != nil {
|
||||
if services.itemBatchCoordinator != nil {
|
||||
// coordinator 保存批量发布 worker 与恢复扫描生命周期协调器。
|
||||
coordinator := s.applications.itemBatchCoordinator
|
||||
coordinator := services.itemBatchCoordinator
|
||||
components = append(components, lifecycleapp.NamedComponent{
|
||||
Name: "publish-batch-workers",
|
||||
Component: lifecycleapp.FuncComponent{
|
||||
@@ -134,9 +137,9 @@ func (s *Server) ApplicationLifecycleComponents() []lifecycleapp.NamedComponent
|
||||
},
|
||||
})
|
||||
}
|
||||
if s.applications.orderReconciliationRecovery != nil {
|
||||
if services.orderReconciliationRecovery != nil {
|
||||
// coordinator 保存订单补偿扫描生命周期协调器。
|
||||
coordinator := s.applications.orderReconciliationRecovery
|
||||
coordinator := services.orderReconciliationRecovery
|
||||
components = append(components, lifecycleapp.NamedComponent{
|
||||
Name: "order-reconciliation-recovery",
|
||||
Component: lifecycleapp.FuncComponent{
|
||||
|
||||
@@ -26,13 +26,13 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplicationLifecycleComponentsExposeWorkerOwnership 验证 Server 只暴露应用 worker 生命周期端口,不再提供启动入口。
|
||||
func TestApplicationLifecycleComponentsExposeWorkerOwnership(t *testing.T) {
|
||||
// TestApplicationServicesExposeWorkerOwnership 验证应用服务集合暴露只读 worker 生命周期端口,不让 Server 反向返还组件。
|
||||
func TestApplicationServicesExposeWorkerOwnership(t *testing.T) {
|
||||
// srv、cleanup 保存带完整应用服务装配的测试 Server 及其资源清理函数。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// components 保存交给进程生命周期协调器登记的应用 worker 组件。
|
||||
components := srv.ApplicationLifecycleComponents()
|
||||
components := srv.ApplicationServices().LifecycleComponents()
|
||||
if len(components) != 3 {
|
||||
t.Fatalf("应用生命周期组件数量=%d,期望=3", len(components))
|
||||
}
|
||||
|
||||
@@ -219,6 +219,32 @@ func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewWithDependenciesAcceptsPrebuiltApplicationSet 验证新组合根入口只接收已经装配完成的应用服务集合。
|
||||
func TestNewWithDependenciesAcceptsPrebuiltApplicationSet(t *testing.T) {
|
||||
// source、cleanup 提供一个由兼容测试装配器构造完成的完整服务集合。
|
||||
source, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// dependencies 将已有构造结果转换为不可变 Server 依赖快照。
|
||||
dependencies := Dependencies{
|
||||
Auth: source.Auth, Manager: source.Manager, WebDir: source.WebDir, Addr: source.Addr, Logger: source.Logger,
|
||||
Automation: source.automation, Notifier: source.notifier, Chat: source.chat,
|
||||
OrderDependencies: source.orderDependencies.(*adapter.OrderDependencies), AccountDependencies: source.accountDependencies.(*adapter.AccountDependencies),
|
||||
ItemDependencies: source.itemDependencies.(*adapter.ItemDependencies), ChatDependencies: source.chatDependencies,
|
||||
AutomationDependencies: source.automationDependencies, TransportApplications: source.transportApplications,
|
||||
PlatformDependencies: source.platformDependencies, DatabaseHealth: source.databaseHealth,
|
||||
OrderReconciliationRecovery: source.orderReconciliationRecovery, Applications: source.applications,
|
||||
ApplicationLifecycle: source.applicationLifecycle,
|
||||
}
|
||||
// serverInstance、constructErr 保存纯注入入口的构造结果。
|
||||
serverInstance, constructErr := NewWithDependencies(dependencies)
|
||||
if constructErr != nil {
|
||||
t.Fatalf("NewWithDependencies: %v", constructErr)
|
||||
}
|
||||
if serverInstance == nil || serverInstance.applications == nil || serverInstance.applications.orders != source.applications.orders {
|
||||
t.Fatal("新组合根入口未保留预构造应用服务集合")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerStartStopIsIdempotentAndWaitsForWorkers 验证 Start/Stop 可重复调用且 Stop 等待 worker。
|
||||
func TestServerStartStopIsIdempotentAndWaitsForWorkers(t *testing.T) {
|
||||
// srv 是待验证幂等生命周期的 HTTP 服务;cleanup 负责释放测试资源。
|
||||
@@ -259,6 +285,50 @@ func TestServerStartStopIsIdempotentAndWaitsForWorkers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerBindReportsOccupiedPort 验证端口冲突在应用 worker 启动前由同步 Bind 返回。
|
||||
func TestServerBindReportsOccupiedPort(t *testing.T) {
|
||||
// occupied、listenErr 分别是故意占用的本机监听器及创建错误。
|
||||
occupied, listenErr := net.Listen("tcp", "127.0.0.1:0")
|
||||
if listenErr != nil {
|
||||
t.Fatalf("占用测试端口失败: %v", listenErr)
|
||||
}
|
||||
defer occupied.Close()
|
||||
// srv、cleanup 分别是待绑定的 HTTP Server 及测试资源释放函数。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.Addr = occupied.Addr().String()
|
||||
// bindErr 是与已占用端口冲突时必须同步返回的绑定错误。
|
||||
bindErr := srv.Bind()
|
||||
if bindErr == nil {
|
||||
t.Fatal("已占用端口的 Bind 应同步返回错误")
|
||||
}
|
||||
if srv.started {
|
||||
t.Fatal("绑定失败不能把 HTTP 服务标记为已启动")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerStopReleasesBoundListener 验证应用启动失败回滚可关闭已绑定但尚未 Serve 的端口。
|
||||
func TestServerStopReleasesBoundListener(t *testing.T) {
|
||||
// srv、cleanup 分别是待测试的 HTTP Server 及测试资源释放函数。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.Addr = freeAddr(t)
|
||||
// bindErr 是为启动失败回滚预绑定监听器时的错误。
|
||||
if bindErr := srv.Bind(); bindErr != nil {
|
||||
t.Fatalf("Bind: %v", bindErr)
|
||||
}
|
||||
// stopErr 是关闭尚未进入 Serve 的监听器时的错误。
|
||||
if stopErr := srv.Stop(context.Background()); stopErr != nil {
|
||||
t.Fatalf("停止已绑定监听器失败: %v", stopErr)
|
||||
}
|
||||
// replacement、listenErr 分别验证同一地址已经由 Stop 释放的监听器及创建错误。
|
||||
replacement, listenErr := net.Listen("tcp", srv.Addr)
|
||||
if listenErr != nil {
|
||||
t.Fatalf("停止后端口未释放: %v", listenErr)
|
||||
}
|
||||
defer replacement.Close()
|
||||
}
|
||||
|
||||
// TestServerStopContextBoundsWorkerWait 验证关闭上下文到期时不会无限等待后台 worker。
|
||||
func TestServerStopContextBoundsWorkerWait(t *testing.T) {
|
||||
// srv 是用于验证关闭超时的 HTTP 服务;cleanup 负责释放测试数据库。
|
||||
|
||||
+187
-19
@@ -6,9 +6,11 @@ package server
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -47,6 +49,49 @@ type qrLoginPersistence struct {
|
||||
// ServerOption 是 Server 构造阶段应用可选依赖的配置函数。
|
||||
type ServerOption func(*Server)
|
||||
|
||||
// Dependencies 是 HTTP Server 的不可变组合依赖;应用服务和生命周期组件必须在进入 Server 前完成装配。
|
||||
// 旧的 ServerOption 构造器仅作为迁移期间兼容入口,生产代码应使用 NewWithDependencies。
|
||||
type Dependencies struct {
|
||||
// Auth 是负责会话解析和认证中间件的应用认证服务。
|
||||
Auth *auth.Service
|
||||
// Manager 是账号运行时的只读 transport 端口兼容依赖;新 handler 不应直接调用其业务方法。
|
||||
Manager *account.Manager
|
||||
// WebDir 是嵌入或外置前端静态资源目录。
|
||||
WebDir string
|
||||
// Addr 是 HTTP 监听地址,默认由 cmd/server 提供 :59188。
|
||||
Addr string
|
||||
// Logger 是 Server 使用的结构化日志器。
|
||||
Logger *slog.Logger
|
||||
// Automation 是历史兼容的自动化运行时引用,新服务应通过应用 Port 访问。
|
||||
Automation *automation.Center
|
||||
// Notifier 是历史兼容的通知运行时引用,新服务应通过通知应用 Port 访问。
|
||||
Notifier *notify.Notifier
|
||||
// Chat 是聊天 transport 使用的领域事件服务。
|
||||
Chat *chat.Service
|
||||
// OrderDependencies 是订单应用适配器集合,仅允许在组合根构造。
|
||||
OrderDependencies *adapter.OrderDependencies
|
||||
// AccountDependencies 是账号应用适配器集合,仅允许在组合根构造。
|
||||
AccountDependencies *adapter.AccountDependencies
|
||||
// ItemDependencies 是商品应用适配器集合,仅允许在组合根构造。
|
||||
ItemDependencies *adapter.ItemDependencies
|
||||
// ChatDependencies 是聊天应用适配器集合,仅允许在组合根构造。
|
||||
ChatDependencies *adapter.ChatDependencies
|
||||
// AutomationDependencies 是自动化应用适配器集合,仅允许在组合根构造。
|
||||
AutomationDependencies *adapter.AutomationDependencies
|
||||
// TransportApplications 是已构造的 transport-facing 应用服务集合。
|
||||
TransportApplications *adapter.TransportApplicationServices
|
||||
// PlatformDependencies 是平台客户端集合,Server 不负责创建其中的实现。
|
||||
PlatformDependencies *adapter.PlatformDependencies
|
||||
// DatabaseHealth 是数据库健康检查应用 Port。
|
||||
DatabaseHealth DatabaseHealthPort
|
||||
// OrderReconciliationRecovery 是订单补偿恢复生命周期组件。
|
||||
OrderReconciliationRecovery *orderapp.ReconciliationRecoveryCoordinator
|
||||
// Applications 是完整应用服务集合;缺失时构造必须失败。
|
||||
Applications *ApplicationServices
|
||||
// ApplicationLifecycle 是由 cmd 拥有的生命周期协调器,仅供请求 Context 读取。
|
||||
ApplicationLifecycle *lifecycleapp.Coordinator
|
||||
}
|
||||
|
||||
// orderDependencyFactory 是订单装配所需的最小能力集合;Server 不持有通用 Store 工厂。
|
||||
type orderDependencyFactory interface {
|
||||
// NewOrderRepository 创建订单读写仓储。
|
||||
@@ -149,10 +194,12 @@ type Server struct {
|
||||
taskRegistry *taskRegistry
|
||||
lifecycleMu sync.RWMutex
|
||||
httpServer *http.Server
|
||||
httpDone chan struct{}
|
||||
httpErr error
|
||||
started bool
|
||||
stopped bool
|
||||
// listener 保存 Bind 成功后由 Server 独占的 TCP 监听器;只有 Stop 或 Serve 退出可以关闭它。
|
||||
listener net.Listener
|
||||
httpDone chan struct{}
|
||||
httpErr error
|
||||
started bool
|
||||
stopped bool
|
||||
|
||||
loginLimiter *loginFailureLimiter
|
||||
initializationMu sync.Mutex
|
||||
@@ -264,6 +311,73 @@ func WithApplicationLifecycle(coordinator *lifecycleapp.Coordinator) ServerOptio
|
||||
}
|
||||
}
|
||||
|
||||
// NewWithDependencies 构造纯 HTTP transport Server;所有应用服务、平台客户端和生命周期组件必须已由组合根创建。
|
||||
func NewWithDependencies(dependencies Dependencies) (*Server, error) {
|
||||
if dependencies.Auth == nil {
|
||||
return nil, fmt.Errorf("server 依赖认证服务不能为空")
|
||||
}
|
||||
if dependencies.Manager == nil {
|
||||
return nil, fmt.Errorf("server 依赖 account.Manager 不能为空")
|
||||
}
|
||||
if dependencies.OrderDependencies == nil || dependencies.AccountDependencies == nil || dependencies.ItemDependencies == nil || dependencies.ChatDependencies == nil || dependencies.AutomationDependencies == nil {
|
||||
return nil, fmt.Errorf("server 领域适配器依赖不能为空")
|
||||
}
|
||||
if dependencies.DatabaseHealth == nil || dependencies.OrderReconciliationRecovery == nil || dependencies.PlatformDependencies == nil {
|
||||
return nil, fmt.Errorf("server 基础设施应用端口不能为空")
|
||||
}
|
||||
if dependencies.TransportApplications == nil {
|
||||
return nil, fmt.Errorf("server transport 应用服务集合不能为空")
|
||||
}
|
||||
// transportValidationErr 是组合根提供的 transport 应用服务集合校验错误。
|
||||
if transportValidationErr := dependencies.TransportApplications.Validate(); transportValidationErr != nil {
|
||||
return nil, fmt.Errorf("server transport 应用服务无效: %w", transportValidationErr)
|
||||
}
|
||||
if dependencies.Applications == nil {
|
||||
return nil, fmt.Errorf("server 应用服务集合不能为空")
|
||||
}
|
||||
// copiedApplications 冻结应用服务集合容器,调用方不得在 Server 启动后替换服务引用。
|
||||
copiedApplications := *dependencies.Applications
|
||||
// logger 是缺省时用于 transport 诊断的标准文本日志器。
|
||||
logger := dependencies.Logger
|
||||
if logger == nil {
|
||||
logger = logging.NewLogger(os.Stdout, "text")
|
||||
}
|
||||
return &Server{
|
||||
orderDependencies: dependencies.OrderDependencies,
|
||||
accountDependencies: dependencies.AccountDependencies,
|
||||
itemDependencies: dependencies.ItemDependencies,
|
||||
chatDependencies: dependencies.ChatDependencies,
|
||||
orderReconciliationRecovery: dependencies.OrderReconciliationRecovery,
|
||||
automationDependencies: dependencies.AutomationDependencies,
|
||||
transportApplications: dependencies.TransportApplications,
|
||||
Auth: dependencies.Auth,
|
||||
Manager: dependencies.Manager,
|
||||
automation: dependencies.Automation,
|
||||
notifier: dependencies.Notifier,
|
||||
chat: dependencies.Chat,
|
||||
platformDependencies: dependencies.PlatformDependencies,
|
||||
Logger: logger,
|
||||
WebDir: dependencies.WebDir,
|
||||
Addr: dependencies.Addr,
|
||||
applications: &copiedApplications,
|
||||
applicationLifecycle: dependencies.ApplicationLifecycle,
|
||||
databaseHealth: dependencies.DatabaseHealth,
|
||||
loginLimiter: newLoginFailureLimiter(),
|
||||
taskRegistry: newTaskRegistry(),
|
||||
backgroundDone: closedSignal(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ApplicationServices 返回构造期注入的应用服务集合快照,供 cmd 负责登记生命周期组件。
|
||||
func (s *Server) ApplicationServices() *ApplicationServices {
|
||||
if s == nil || s.applications == nil {
|
||||
return nil
|
||||
}
|
||||
// copiedApplications 将集合容器复制后返回,避免调用方替换 Server 内部容器指针。
|
||||
copiedApplications := *s.applications
|
||||
return &copiedApplications
|
||||
}
|
||||
|
||||
// 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) {
|
||||
@@ -713,20 +827,21 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// 各分组 mount*Real 方法在 handlers 文件中实现;为避免单文件过大,按业务域分文件。
|
||||
|
||||
// Start 启动 HTTP 服务及其生命周期监听。重复调用不会重复监听端口。
|
||||
func (s *Server) Start(ctx context.Context) error {
|
||||
// Bind 同步占用 HTTP 监听地址,但不接受请求。
|
||||
// 进程组合根必须先调用它,再启动可能产生外部副作用的应用 worker,避免端口冲突在 worker 启动后才暴露。
|
||||
func (s *Server) Bind() error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("server 不能为空")
|
||||
}
|
||||
// ctx 是控制 HTTP 服务及其后台任务的进程级生命周期上下文。
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.lifecycleMu.Lock()
|
||||
if s.started {
|
||||
if s.listener != nil {
|
||||
s.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if s.stopped {
|
||||
s.lifecycleMu.Unlock()
|
||||
return fmt.Errorf("HTTP 服务已经停止,不能重新绑定")
|
||||
}
|
||||
// httpServer 是本次启动创建的标准库 HTTP 监听器。
|
||||
httpServer := &http.Server{
|
||||
Addr: s.Addr,
|
||||
@@ -737,13 +852,51 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
WriteTimeout: 2 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
}
|
||||
// listener 是在启动应用 worker 前同步绑定的 TCP 端口;失败时 Server 保持未启动状态。
|
||||
listener, listenErr := net.Listen("tcp", s.Addr)
|
||||
if listenErr != nil {
|
||||
s.lifecycleMu.Unlock()
|
||||
return fmt.Errorf("监听 HTTP 地址 %q 失败: %w", s.Addr, listenErr)
|
||||
}
|
||||
s.httpServer = httpServer
|
||||
s.listener = listener
|
||||
s.httpDone = make(chan struct{})
|
||||
s.httpErr = nil
|
||||
s.stopped = false
|
||||
s.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start 启动已经绑定的 HTTP 服务及其生命周期监听。重复调用不会重复接受连接。
|
||||
func (s *Server) Start(ctx context.Context) error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("server 不能为空")
|
||||
}
|
||||
// ctx 是控制 HTTP 服务及其后台任务的进程级生命周期上下文。
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
// bindErr 是同步占用监听地址失败时的启动前置错误。
|
||||
if bindErr := s.Bind(); bindErr != nil {
|
||||
return bindErr
|
||||
}
|
||||
s.lifecycleMu.Lock()
|
||||
if s.started {
|
||||
s.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if s.stopped || s.httpServer == nil || s.listener == nil || s.httpDone == nil {
|
||||
s.lifecycleMu.Unlock()
|
||||
return fmt.Errorf("HTTP 服务未处于可启动的已绑定状态")
|
||||
}
|
||||
// httpServer 是本次 Serve goroutine 独占的 HTTP transport。
|
||||
httpServer := s.httpServer
|
||||
// listener 是已成功绑定并交由本次 Serve 独占接收连接的监听器。
|
||||
listener := s.listener
|
||||
// httpDone 在本次 Serve 退出后关闭,供 Wait 和 Stop 观察最终退出。
|
||||
httpDone := s.httpDone
|
||||
s.started = true
|
||||
s.stopped = false
|
||||
// httpDone 是 HTTP 监听 goroutine 结束时关闭的完成信号。
|
||||
httpDone := s.httpDone
|
||||
s.lifecycleMu.Unlock()
|
||||
|
||||
// 进程生命周期 Context 取消时触发 HTTP Stop;应用组件关闭由 cmd 统一协调。
|
||||
@@ -762,7 +915,7 @@ func (s *Server) Start(ctx context.Context) error {
|
||||
go func() {
|
||||
s.Logger.Info("HTTP 服务启动", "addr", s.Addr)
|
||||
// err 是 HTTP 监听器退出时返回的原始错误。
|
||||
err := httpServer.ListenAndServe()
|
||||
err := httpServer.Serve(listener)
|
||||
if err == http.ErrServerClosed {
|
||||
err = nil
|
||||
}
|
||||
@@ -805,7 +958,7 @@ func (s *Server) Stop(ctx context.Context) error {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.lifecycleMu.Lock()
|
||||
if !s.started {
|
||||
if !s.started && s.listener == nil {
|
||||
s.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -823,16 +976,31 @@ func (s *Server) Stop(ctx context.Context) error {
|
||||
}
|
||||
s.stopped = true
|
||||
// httpServer 是需要执行优雅关闭的标准库 HTTP 服务。
|
||||
// httpDone 是监听 goroutine 退出的完成信号。
|
||||
// httpServer 用于本次流程后续判断的httpServer
|
||||
httpServer := s.httpServer
|
||||
// httpDone 用于本次流程后续判断的httpDone
|
||||
// listener 是已绑定但可能尚未进入 Serve 的监听器;绑定失败回滚由当前调用关闭它。
|
||||
listener := s.listener
|
||||
// httpDone 是监听 goroutine 退出或绑定回滚完成时关闭的完成信号。
|
||||
httpDone := s.httpDone
|
||||
// started 区分已进入 Serve 的服务和仅完成 Bind 的启动回滚路径。
|
||||
started := s.started
|
||||
s.lifecycleMu.Unlock()
|
||||
// shutdownErr 是 HTTP 优雅关闭返回的错误;后台等待错误由 worker 自身记录。
|
||||
var shutdownErr error
|
||||
if httpServer != nil {
|
||||
if started && httpServer != nil {
|
||||
shutdownErr = httpServer.Shutdown(ctx)
|
||||
} else if listener != nil {
|
||||
shutdownErr = listener.Close()
|
||||
if shutdownErr != nil && !errors.Is(shutdownErr, net.ErrClosed) {
|
||||
return shutdownErr
|
||||
}
|
||||
s.lifecycleMu.Lock()
|
||||
if s.listener == listener {
|
||||
s.listener = nil
|
||||
}
|
||||
if httpDone != nil {
|
||||
close(httpDone)
|
||||
}
|
||||
s.lifecycleMu.Unlock()
|
||||
}
|
||||
if httpDone != nil && !waitForSignal(ctx, httpDone) {
|
||||
return ctx.Err()
|
||||
|
||||
+1
-1
@@ -1,3 +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,c as Pe,o as ke,p as ae,a as ce,d as Le}from"./index-CNpXfeP4.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=Pe(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=>Le(`/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)=>Le(`/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:Pe(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,Line truncated
|
||||
import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,c as Pe,o as ke,p as ae,a as ce,d as Le}from"./index-Cz55GfME.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=Pe(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=>Le(`/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)=>Le(`/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:Pe(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,Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,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)&&a<r},As=(s,t)=>s.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
Line truncated
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
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 O,Y as ee,L as V,N as U,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,c as de,p as xe,d as pe,a as Y,b as me}from"./index-CNpXfeP4.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(O,{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(O,{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,placeLine truncated
|
||||
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 O,Y as ee,L as V,N as U,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,c as de,p as xe,d as pe,a as Y,b as me}from"./index-Cz55GfME.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(O,{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(O,{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,placeLine truncated
|
||||
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(V,{className:"w-4 h-4 animate-spin"}):e.jsx(O,{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(V,{className:"w-4 h-4 animate-spin"}):e.jsx(U,{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 de(n,["cards","data","items"]).map(be)},ye=async l=>Y("/api/v1/cards",K(l)),J=async(l,n)=>xe(`/api/v1/cards/${l}`,K(n)),fe=async l=>pe(`/api/v1/cards/${l}`),je=async(l,n)=>{const a=new FormData;return a.append("file",l),me("/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 L=await Ne(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:L.added}),s(""),await a()}catch(L){if(!F(B,v.current,p,b))return;R((L==null?void 0:L.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:""}),D=(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(D(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await fe(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(D(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"&&(
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,c as x0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as re}from"./vendor-Es4K8PXl.js";import{e as M0,f as le,h as F0,m as P0,s as ce,i as oe,j as pe,k as me,l as z0}from"./index-CNpXfeP4.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,s as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-CvzvbbIV.js";const Z0=[["尊嘟假嘟","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_
Line truncated
|
||||
import{j as e,c as x0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as re}from"./vendor-Es4K8PXl.js";import{e as M0,f as le,h as F0,m as P0,s as ce,i as oe,j as pe,k as me,l as z0}from"./index-Cz55GfME.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,s as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-CvzvbbIV.js";const Z0=[["尊嘟假嘟","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_
Line truncated
|
||||
+1
-1
@@ -1 +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,c as de,o as ge}from"./index-CNpXfeP4.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-deWqkrdG.js";import"./vendor-Es4K8PXl.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.startLine truncated
|
||||
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,c as de,o as ge}from"./index-Cz55GfME.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-deWqkrdG.js";import"./vendor-Es4K8PXl.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.startLine truncated
|
||||
@@ -0,0 +1,2 @@
|
||||
import{r,j as e,b as we}from"./react-vendor-C_od1ZSF.js";import{g as je,c as Qe,a as ce,b as et,d as tt,p as yt}from"./index-Cz55GfME.js";import{a3 as ft,U as De,R as Se,N as Te,a4 as Pe,a5 as _e,V as jt,F as vt,B as Nt,a6 as Ue,a7 as wt,a8 as _t,A as kt,d as Ct,X as be,r as It,a9 as ze,I as Oe}from"./icons-vendor-CvzvbbIV.js";const Ke="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let ye=null;const Pt=()=>St,Bt=()=>window.AMap?Promise.resolve(window.AMap):ye||(ye=new Promise((s,l)=>{const c=document.getElementById(Ke),u=c||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(A)},j=()=>{window.AMap?(m(),s(window.AMap)):(m(),l(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},A=window.setTimeout(()=>{m(),l(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=j,u.id=Ke,u.async=!0,u.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Pt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,u.onerror=()=>{m(),l(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},c||document.head.appendChild(u)}).catch(s=>{throw ye=null,s}),ye),ke=s=>Number.isFinite(s)&&s!==0,qt=s=>{var m,j;const l=Number((m=s.location)==null?void 0:m.lng),c=Number((j=s.location)==null?void 0:j.lat),u={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:l,latitude:c,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!u.division_id||!u.province||!u.city||!u.poi_id||!u.poi_name||!ke(l)||!ke(c)||l<-180||l>180||c<-90||c>90?null:u},Lt=async(s,l,c={})=>{if(!ke(s)||!ke(l)||s<-180||s>180||l<-90||l>90)throw new Error("经纬度无效");const u=await Bt();return new Promise((m,j)=>{var G,M;let A=!1;const k=Math.max(1,c.timeoutMs??1e4),F=R=>{var p;A||(A=!0,globalThis.clearTimeout(Z),(p=c.signal)==null||p.removeEventListener("abort",I),R())},I=()=>F(()=>j(new DOMException("aborted","AbortError"))),Z=globalThis.setTimeout(()=>F(()=>j(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if((G=c.signal)!=null&&G.aborted){I();return}(M=c.signal)==null||M.addEventListener("abort",I,{once:!0}),new u.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,l],1e3,(R,p)=>{var d;if(A)return;if(R!=="complete"){if(R==="no_data"){F(()=>m([]));return}F(()=>j(new Error("高德地图附近地址查询失败,请稍后重试")));return}const B=(((d=p==null?void 0:p.poiList)==null?void 0:d.pois)||[]).map(qt).filter(v=>v!==null);F(()=>m(B))})})},Ft=async s=>je("/api/v1/accounts/details",void 0,s),Je=async s=>je("/api/v1/automation-rules",void 0,s),Mt=(s,l,c)=>Lt(s,l,c),Be=s=>s===!0||s===1||s==="1",Ze=async(s,l)=>{const c=await je("/api/v1/items",void 0,l);return Qe(c,["items","data","results"]).map(m=>({...m,id:m.id||`${m.cookie_id}-${m.item_id}`,is_multi_spec:Be(m.is_multi_spec),is_multi_qty_ship:Be(m.is_multi_qty_ship??m.multi_quantity_delivery),multi_quantity_delivery:Be(m.multi_quantity_delivery??m.is_multi_qty_ship)}))},Rt=async s=>ce("/api/v1/items/get-all-from-account",{cookie_id:s}),At=async(s,l)=>tt(`/api/v1/items/${s}/${l}`),Et=async(s,l)=>ce(`/api/v1/items/${s}`,l),Gt=async s=>{const l=new FormData;l.set("cookie_id",s.cookie_id),l.set("title",s.title),l.set("description",s.description),l.set("price",s.price),l.set("original_price",s.original_price||""),l.set("quantity",String(s.quantity)),l.set("postage_mode",s.postage_mode),l.set("postage",s.postage||""),s.location&&l.set("location",JSON.stringify(s.location));for(const c of s.images)l.append("images",c);return et("/api/v1/items/publish",l)},$t=async(s,l,c)=>ce("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:l},c),Dt=async(s,l)=>{const c=new FormData;return c.set("file",s.file),s.imagesZip&&c.set("images_zip",s.imagesZip),s.defaultCookieId&&c.set("default_cookie_id",s.defaultCookieId),c.set("fallback_category_id",s.fallbackCategory.catId),c.set("fallback_category_name",s.fallbackCategory.catName),c.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),c.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&c.set("location",JSON.stringify(s.location)),c.set("publish_interval_seconds",String(s.publishIntervalSeconds??5)),et("/api/v1/items/publish-batches/preview",c,l)},Tt=async(s,l)=>ce("/api/v1/items/publish-batches",{preview_id:s},l),ie=async(s,l)=>je(`/api/v1/items/publish-batches/${s}`,void 0,l),st=async(s=20,l)=>{const c=await je("/api/v1/items/publish-batches",{limit:s},l);return Qe(c,["batches","data","items"])},Ve=async(s,l)=>tt(`/api/v1/items/publish-batches/${s}`,void 0,l),Ut=async(s,l)=>ce(`/api/v1/items/publish-batches/${s}/cancel`,{},l),zt=async(s,l)=>ce(`/api/v1/items/publish-batches/${s}/retry-failed`,{},l),Ot=async(s,l,c)=>yt(`/api/v1/items/${s}/${l}`,c),Kt=s=>s.find(l=>l.status==="pending"||l.status==="Line truncated
|
||||
`),X=new Blob(["\uFEFF"+L],{type:"text/csv;charset=utf-8"}),E=URL.createObjectURL(X),P=document.createElement("a");P.href=E,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(E)},[]),n=r.useCallback(()=>{y(i=>({...i,cookie_id:s||i.cookie_id})),p(!0)},[s]),h=r.useCallback(()=>{N(i=>({...i,cookie_id:s||i.cookie_id})),d(!0)},[s]),q=r.useCallback(async i=>{if(!(i?s:b.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");D();const L=new AbortController;H.current=L;const X=++z.current;S(!0);try{const E=await new Promise((me,ue)=>{const Ce=Q=>me(Q),re=Q=>ue(Q);navigator.geolocation.getCurrentPosition(Ce,re,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(L.signal.aborted||X!==z.current)return;const P=await Mt(E.coords.longitude,E.coords.latitude,{signal:L.signal});if(L.signal.aborted||X!==z.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");i?(A(P),k(P[0])):(W(P),U(P[0]))}catch(E){if(L.signal.aborted||X!==z.current)return;if(typeof E=="object"&&E!==null&&"code"in E){const P=E;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(qe(E,"获取发货地失败"))}finally{X===z.current&&(H.current=null,S(!1))}},[D,b.cookie_id,s,k,A]);return{selectedAccount:s,setSelectedAccount:l,loading:F,publishing:Z,showEditModal:G,setShowEditModal:M,showAddModal:R,setShowAddModal:p,showPublishModal:B,setShowPublishModal:d,locationLoading:v,publishLocations:V,setPublishLocations:W,publishLocation:Y,setPublishLocation:U,selectedItem:$,editForm:C,setEditForm:se,addForm:g,setAddForm:y,publishForm:b,setPublishForm:N,publishImagePreviews:x,handleSync:te,handleEdit:oe,handleSaveEdit:le,handleDelete:de,handleAddItem:xe,handlePublishItem:ve,downloadPublishTemplate:a,openAddModal:n,openPublishModal:h,locateForPublish:q}},Ht=({phase:s})=>{const l=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:l.map(([c,u])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===c?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:u},c))})},Xt=s=>{const l=String(s||"").trim();return l?/^[¥¥]/.test(l)?l:`¥${l}`:"-"},ss=({onConfigureDelivery:s})=>{const[l,c]=r.useState([]),[u,m]=r.useState([]),[j,A]=r.useState([]),[k,F]=r.useState(""),[I,Z]=r.useState(""),T=r.useRef(0),G=r.useRef(0),M=r.useCallback(async()=>{const t=++T.current,o=await Ze();t===T.current&&c(o)},[]),R=r.useCallback(async()=>{const t=++G.current,o=await Je();t===G.current&&m(o)},[]),p=Wt({selectedAccount:k,loadItems:M,loadShippingRules:R}),{showBatchModal:B,batchLoading:d,batchPhase:v,batchFile:S,setBatchFile:V,batchImagesZip:W,setBatchImagesZip:Y,batchCategoryKeyword:U,setBatchCategoryKeyword:$,batchCategoryLoading:K,batchFallbackCategory:C,setBatchFallbackCategory:se,batchPreview:g,batchDetail:y,recentBatch:b,setRecentBatch:N,batchLocations:x,batchLocation:ae,batchPublishIntervalSeconds:H,setBatchPublishIntervalSeconds:z,setBatchLocations:D,setBatchLocation:te,openBatchModal:oe,handleRecommendBatchCategory:le,openRecentBatchResult:de,handlePreviewBatch:xe,handleStartBatch:ve,handleCancelBatch:a,abandonBatchPreview:n,closeBatchModal:h,handleRetryBatchFailed:q}=p,i=Yt({selectedAccount:k,setSelectedAccount:F,setItems:c,loadItems:M,loadShippingRules:R,onConfigureDelivery:s,setBatchLocations:D,setBatchLocation:te}),{loading:f,publishing:L,showEditModal:X,setShowEditModal:E,showAddModal:P,setShowAddModal:me,showPublishModal:ue,setShowPublishModal:Ce,locationLoading:re,publishLocations:Q,setPublishLocations:at,publishLocation:lt,setPublishLocation:Le,selectedItem:Fe,editForm:ee,setEditForm:Ne,addForm:O,setAddForm:he,publishForm:w,setPublishForm:J,publishImagePreviews:Me,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:mt,openPublishModal:ut,locateForPublish:Re}=i;r.useEffect(()=>{const t=new AbortController,o=++T.current,_=++G.current;let ge=!0;return Promise.all([Ft({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),st(20,{signal:t.signal})]).then(([ne,pt,gt,$e])=>{if(!ge||t.signal.aborted||o!==T.current||_!==G.current)return;A(ne),c(pt),m(gt);const bt=$e.find(Ie=>["running","canceling"].includes(Ie.status))||$e.find(Ie=>Ie.status!=="preview");N(bt||null)}).catch(ne=>{t.signal.aborted||console.error("加载商品配置失败:",ne)}),(()=>{ge=!1,t.abort()})},[]);const ht=t=>u.filter(o=>o.cookie_id===t.cookie_id&&o.item_id===t.item_id).length>0?u.filter(o=>o.cookie_id===t.cookie_id&&o.item_id===t.item_id):u.filter(o=>o.cookie_id===t.cookie_id&&!o.item_id),Ae=r.useMemo(()=>new Map(j.map(t=>[t.id,t])),[j]),Ee=r.use
Line truncated
|
||||
@@ -1,2 +0,0 @@
|
||||
import{r as n,j as e,b as be}from"./react-vendor-C_od1ZSF.js";import{g as me,c as We,a as Q,b as Ye,d as He,p as yt}from"./index-CNpXfeP4.js";import{a3 as ft,U as Me,R as we,N as Ee,a4 as _e,a5 as ye,V as jt,F as vt,B as Nt,a6 as Ge,a7 as wt,a8 as _t,A as kt,d as Ct,X as de,r as It,a9 as $e,I as De}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let xe=null;const Pt=()=>St,Bt=()=>window.AMap?Promise.resolve(window.AMap):xe||(xe=new Promise((s,r)=>{const c=document.getElementById(Ue),m=c||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(S)},j=()=>{window.AMap?(u(),s(window.AMap)):(u(),r(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},S=window.setTimeout(()=>{u(),r(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=j,m.id=Ue,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Pt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),r(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},c||document.head.appendChild(m)}).catch(s=>{throw xe=null,s}),xe),fe=s=>Number.isFinite(s)&&s!==0,qt=s=>{var u,j;const r=Number((u=s.location)==null?void 0:u.lng),c=Number((j=s.location)==null?void 0:j.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:r,latitude:c,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!fe(r)||!fe(c)||r<-180||r>180||c<-90||c>90?null:m},Ft=async(s,r)=>{if(!fe(s)||!fe(r)||s<-180||s>180||r<-90||r>90)throw new Error("经纬度无效");const c=await Bt();return new Promise((m,u)=>{new c.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,r],1e3,(S,w)=>{var I;if(S!=="complete"){if(S==="no_data"){m([]);return}u(new Error("高德地图附近地址查询失败,请稍后重试"));return}const R=(((I=w==null?void 0:w.poiList)==null?void 0:I.pois)||[]).map(qt).filter(U=>U!==null);m(R)})})},Rt=async s=>me("/api/v1/accounts/details",void 0,s),ze=async s=>me("/api/v1/automation-rules",void 0,s),ke=s=>s===!0||s===1||s==="1",Oe=async(s,r)=>{const c=await me("/api/v1/items",void 0,r);return We(c,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:ke(u.is_multi_spec),is_multi_qty_ship:ke(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:ke(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Lt=async s=>Q("/api/v1/items/get-all-from-account",{cookie_id:s}),At=async(s,r)=>He(`/api/v1/items/${s}/${r}`),Mt=async(s,r)=>Q(`/api/v1/items/${s}`,r),Et=async s=>{const r=new FormData;r.set("cookie_id",s.cookie_id),r.set("title",s.title),r.set("description",s.description),r.set("price",s.price),r.set("original_price",s.original_price||""),r.set("quantity",String(s.quantity)),r.set("postage_mode",s.postage_mode),r.set("postage",s.postage||""),s.location&&r.set("location",JSON.stringify(s.location));for(const c of s.images)r.append("images",c);return Ye("/api/v1/items/publish",r)},Gt=async(s,r,c)=>Q("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:r},c),$t=async(s,r)=>{const c=new FormData;return c.set("file",s.file),s.imagesZip&&c.set("images_zip",s.imagesZip),s.defaultCookieId&&c.set("default_cookie_id",s.defaultCookieId),c.set("fallback_category_id",s.fallbackCategory.catId),c.set("fallback_category_name",s.fallbackCategory.catName),c.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),c.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&c.set("location",JSON.stringify(s.location)),c.set("publish_interval_seconds",String(s.publishIntervalSeconds??5)),Ye("/api/v1/items/publish-batches/preview",c,r)},Dt=async(s,r)=>Q("/api/v1/items/publish-batches",{preview_id:s},r),X=async(s,r)=>me(`/api/v1/items/publish-batches/${s}`,void 0,r),Xe=async(s=20,r)=>{const c=await me("/api/v1/items/publish-batches",{limit:s},r);return We(c,["batches","data","items"])},Te=async(s,r)=>He(`/api/v1/items/publish-batches/${s}`,void 0,r),Ut=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/cancel`,{},r),zt=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/retry-failed`,{},r),Ot=async(s,r,c)=>yt(`/api/v1/items/${s}/${r}`,c),Tt=s=>s.find(r=>r.status==="running"||r.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Kt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),Jt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Zt=(s,r)=>s===r,Ke=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":returLine truncated
|
||||
`),g=new Blob(["\uFEFF"+o],{type:"text/csv;charset=utf-8"}),ne=URL.createObjectURL(g),K=document.createElement("a");K.href=ne,K.download="批量铺货模板.csv",document.body.appendChild(K),K.click(),K.remove(),URL.revokeObjectURL(ne)},[]),le=n.useCallback(()=>{y(a=>({...a,cookie_id:s||a.cookie_id})),b(!0)},[s]),re=n.useCallback(()=>{F(a=>({...a,cookie_id:s||a.cookie_id})),d(!0)},[s]),ue=n.useCallback(async a=>{if(!(a?s:p.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");C(!0),navigator.geolocation.getCurrentPosition(async o=>{try{const g=await Ft(o.coords.longitude,o.coords.latitude);if(!g.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");a?(S(g),w(g[0])):(O(g),L(g[0]))}catch(g){alert(Ce(g,"获取发货地失败"))}finally{C(!1)}},o=>{C(!1),alert(o.code===o.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[p.cookie_id,s,w,S]);return{selectedAccount:s,setSelectedAccount:r,loading:R,publishing:U,showEditModal:E,setShowEditModal:P,showAddModal:G,setShowAddModal:b,showPublishModal:B,setShowPublishModal:d,locationLoading:v,publishLocations:z,setPublishLocations:O,publishLocation:T,setPublishLocation:L,selectedItem:q,editForm:k,setEditForm:V,addForm:h,setAddForm:y,publishForm:p,setPublishForm:F,publishImagePreviews:f,handleSync:ee,handleEdit:te,handleSaveEdit:W,handleDelete:Z,handleAddItem:se,handlePublishItem:Y,downloadPublishTemplate:ae,openAddModal:le,openPublishModal:re,locateForPublish:ue}},Yt=({phase:s})=>{const r=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:r.map(([c,m])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===c?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:m},c))})},Ht=s=>{const r=String(s||"").trim();return r?/^[¥¥]/.test(r)?r:`¥${r}`:"-"},ts=({onConfigureDelivery:s})=>{const[r,c]=n.useState([]),[m,u]=n.useState([]),[j,S]=n.useState([]),[w,R]=n.useState(""),[I,U]=n.useState(""),M=n.useRef(0),E=n.useRef(0),P=n.useCallback(async()=>{const t=++M.current,i=await Oe();t===M.current&&c(i)},[]),G=n.useCallback(async()=>{const t=++E.current,i=await ze();t===E.current&&u(i)},[]),b=Vt({selectedAccount:w,loadItems:P,loadShippingRules:G}),{showBatchModal:B,batchLoading:d,batchPhase:v,batchFile:C,setBatchFile:z,batchImagesZip:O,setBatchImagesZip:T,batchCategoryKeyword:L,setBatchCategoryKeyword:q,batchCategoryLoading:$,batchFallbackCategory:k,setBatchFallbackCategory:V,batchPreview:h,batchDetail:y,recentBatch:p,setRecentBatch:F,batchLocations:f,batchLocation:x,batchPublishIntervalSeconds:ee,setBatchPublishIntervalSeconds:te,setBatchLocations:W,setBatchLocation:Z,openBatchModal:se,handleRecommendBatchCategory:Y,openRecentBatchResult:ae,handlePreviewBatch:le,handleStartBatch:re,handleCancelBatch:ue,abandonBatchPreview:a,closeBatchModal:l,handleRetryBatchFailed:o}=b,g=Wt({selectedAccount:w,setSelectedAccount:R,setItems:c,loadItems:P,loadShippingRules:G,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Z}),{loading:ne,publishing:K,showEditModal:je,setShowEditModal:ve,showAddModal:Qe,setShowAddModal:et,showPublishModal:tt,setShowPublishModal:st,locationLoading:he,publishLocations:pe,setPublishLocations:at,publishLocation:lt,setPublishLocation:Se,selectedItem:Pe,editForm:J,setEditForm:ge,addForm:A,setAddForm:ie,publishForm:N,setPublishForm:D,publishImagePreviews:Be,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:mt,openPublishModal:ut,locateForPublish:qe}=g;n.useEffect(()=>{const t=new AbortController,i=++M.current,_=++E.current;let oe=!0;return Promise.all([Rt({signal:t.signal}),Oe(void 0,{signal:t.signal}),ze({signal:t.signal}),Xe(20,{signal:t.signal})]).then(([H,pt,gt,Ae])=>{if(!oe||t.signal.aborted||i!==M.current||_!==E.current)return;S(H),c(pt),u(gt);const bt=Ae.find(Ne=>["running","canceling"].includes(Ne.status))||Ae.find(Ne=>Ne.status!=="preview");F(bt||null)}).catch(H=>{t.signal.aborted||console.error("加载商品配置失败:",H)}),(()=>{oe=!1,t.abort()})},[]);const ht=t=>m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id).length>0?m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id):m.filter(i=>i.cookie_id===t.cookie_id&&!i.item_id),Fe=n.useMemo(()=>new Map(j.map(t=>[t.id,t])),[j]),Re=n.useMemo(()=>I?r.filter(t=>t.cookie_id===I):r,[I,r]),ce=t=>{const i=Fe.get(t),_=(i==null?void 0:i.remark)||(i==null?void 0:i.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Le=t=>{const i=Fe.get(t);return(i==null?void 0:i.remark)||(i==null?void 0:i.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fa
Line truncated
|
||||
+1
-1
@@ -1 +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-CNpXfeP4.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/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 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",Line truncated
|
||||
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-Cz55GfME.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/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 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",Line truncated
|
||||
+1
-1
@@ -1 +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,o as ge,c as pe,b as ae,a as K,p as be,d as ye}from"./index-CNpXfeP4.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.imLine truncated
|
||||
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,o as ge,c as pe,b as ae,a as K,p as be,d as ye}from"./index-Cz55GfME.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.imLine truncated
|
||||
+1
-1
@@ -1 +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,o as Ae,c as Ge,p as Ke,a as fe,d as Ue}from"./index-CNpXfeP4.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=Ge(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/vLine truncated
|
||||
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,o as Ae,c as Ge,p as Ke,a as fe,d as Ue}from"./index-Cz55GfME.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=Ge(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/vLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-CNpXfeP4.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(()=>windLine truncated
|
||||
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-Cz55GfME.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(()=>windLine truncated
|
||||
@@ -1,2 +0,0 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-cuEci6bi.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-B6-OE96i.js","assets/OrderList-BVg4AoME.js","assets/CardList-DqonN_6I.js","assets/ItemList-DoFg4LZD.js","assets/Settings-Cq94-QvI.js","assets/Rules-BN1y7N0V.js","assets/Notifications-BjiGqfvh.js","assets/Chat-JXKGhyxF.js"])))=>i.map(i=>d[i]);
|
||||
import{c as I,j as t,r as d,d as X}from"./react-vendor-C_od1ZSF.js";import{L as z,a as R,S as ee,U as te,A as se,b as ne,c as ae,M as re,C as oe,B as ie,d as ce,Z as le,e as de,f as ue,G as O,g as he,h as me,i as fe}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const c of a)if(c.type==="childList")for(const r of c.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&o(r)}).observe(document,{childList:!0,subtree:!0});function s(a){const c={};return a.integrity&&(c.integrity=a.integrity),a.referrerPolicy&&(c.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?c.credentials="include":a.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function o(a){if(a.ep)return;a.ep=!0;const c=s(a);fetch(a.href,c)}})();class pe extends I.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?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const xe=3e4,ge=10*6e4;let A=!1;const U=()=>{A||typeof window>"u"||(A=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{A=!1}))},ye=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,a]of Object.entries(e))a!=null&&n.set(o,String(a));const s=n.toString();return s?`?${s}`:""},_=async(e,n,s={})=>{var l;const o=ye(s.params),a=`${n}${o}`,c=F(s.signal,s.timeoutMs??xe);let r;try{r=await fetch(a,{method:e,credentials:"include",signal:c.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(h){throw c.signal.aborted?new Error((l=s.signal)!=null&&l.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{c.cleanup()}const u=(r.headers.get("content-type")||"").includes("application/json");if(!r.ok){r.status===401&&!s.skipAuthLogout&&U();const h=u?await r.json().catch(()=>{}):await r.text().catch(()=>{}),x=B(h,r.status);throw new Error(x)}return u?await r.json():await r.text()},j=async(e,n,s)=>_("GET",e,{params:n,...s}),L=async(e,n,s)=>_("POST",e,{body:n,...s}),at=async(e,n,s)=>_("PUT",e,{body:n,...s}),rt=async(e,n,s)=>_("DELETE",e,{params:n,...s}),be=async(e,n,s={})=>{var u;const o=F(s.signal,s.timeoutMs??ge);let a;try{a=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(l){throw o.signal.aborted?new Error((u=s.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):l}finally{o.cleanup()}const i=(a.headers.get("content-type")||"").includes("application/json")?await a.json().catch(()=>{}):await a.text().catch(()=>{});if(!a.ok){a.status===401&&U();const l=B(i,a.status),h=new Error(l);throw h.payload=i,h}return i},F=(e,n)=>{const s=new AbortController,o=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const a=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(a),e==null||e.removeEventListener("abort",o)}}},ve=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},B=(e,n)=>typeof e=="string"?e:ve(e)?e.message:`请求失败: ${n}`,we=async e=>L("/api/v1/session/login",e,{skipAuthLogout:!0}),je=async e=>L("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Le=async e=>j("/api/v1/session",void 0,e),Ce=async()=>L("/api/v1/session/logout",{}),V=d.createContext(void 0),Ne=({children:e})=>{const[n,s]=d.useState(!1),[o,a]=d.useState(!1),[c,r]=d.useState(!0),[i,u]=d.useState(!1),l=()=>{s(!1),a(!1)};d.useEffect(()=>{const g=new AbortController;let p=!0;Le({signal:g.signal}).then(y=>{if(p){if((y==null?void 0:y.initialized)===!1){u(!0),l();return}u(!1),y!=null&&y.authenticated?(s(!0),a(y.is_admin===!0)):l()}}).catch(y=>{!p||y instanceof DOMException&&y.name==="AbortError"||(u(!1),l())}).finally(()=>{p&&r(!1)});const m=()=>l();return window.addEventListener("auth:logout",m),(()=>{p=!1,g.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async g=>{const p=await we(g);return p.success&&(u(!1),s(!0),a(p.is_admin===!0)),p},x=async g=>{const p=await je(g);return p.success&&(u(!1),s(!0),a(p.is_admin===!0)),p},f=async()=>{try{await Ce()}finally{l()}};return t.jsx(V.Provider,{value:{checkingAuth:c,isLoggedIn:n,isAdmin:o,needsInit:i,signIn:h,initialize:x,siLine truncated
|
||||
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-C2iIKKM7.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-MnbtXPsD.js","assets/OrderList-B5Qih0gS.js","assets/CardList-DqebhhPD.js","assets/ItemList-CuKH8r_L.js","assets/Settings-5yrzDH2S.js","assets/Rules-BYf2qpCt.js","assets/Notifications-CHGz3bqt.js","assets/Chat-CXAXagQ1.js"])))=>i.map(i=>d[i]);
|
||||
import{c as R,j as t,r as l,d as te}from"./react-vendor-C_od1ZSF.js";import{L as U,a as O,S as se,U as ne,A as re,b as ae,c as oe,M as ie,C as ce,B as le,d as de,Z as ue,e as he,f as me,G as M,g as fe,h as pe,i as xe}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"]'))o(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"&&o(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 o(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ge extends R.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?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const be=3e4,ye=10*6e4;let P=!1;class F extends Error{constructor(n,s){super(je(s,n)),this.name="ApiError",this.status=n,this.code=E(s)?s.code:`http_${n}`,this.requestId=E(s)?s.request_id:void 0,this.details=E(s)?s.details:void 0,this.payload=s}}const q=()=>{P||typeof window>"u"||(P=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{P=!1}))},ve=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,r]of Object.entries(e))r!=null&&n.set(o,String(r));const s=n.toString();return s?`?${s}`:""},A=async(e,n,s={})=>{var d;const o=ve(s.params),r=`${n}${o}`,i=B(s.signal,s.timeoutMs??be);let a;try{a=await fetch(r,{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(h){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{i.cleanup()}const u=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&q();const h=await V(a,u);throw new F(a.status,h)}return u?await a.json():await a.text()},j=async(e,n,s)=>A("GET",e,{params:n,...s}),L=async(e,n,s)=>A("POST",e,{body:n,...s}),ot=async(e,n,s)=>A("PUT",e,{body:n,...s}),it=async(e,n,s)=>A("DELETE",e,{params:n,...s}),we=async(e,n,s={})=>{var u;const o=B(s.signal,s.timeoutMs??ye);let r;try{r=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(d){throw o.signal.aborted?new Error((u=s.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{o.cleanup()}const a=(r.headers.get("content-type")||"").includes("application/json"),c=await V(r,a);if(!r.ok)throw r.status===401&&q(),new F(r.status,c);return c},B=(e,n)=>{const s=new AbortController,o=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",o)}}},V=async(e,n)=>n?e.json().catch(()=>{}):e.text().catch(()=>{}),E=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},je=(e,n)=>typeof e=="string"?e:E(e)?e.message:`请求失败: ${n}`,Le=async e=>L("/api/v1/session/login",e,{skipAuthLogout:!0}),Ce=async e=>L("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ne=async e=>j("/api/v1/session",void 0,e),Ee=async()=>L("/api/v1/session/logout",{}),G=l.createContext(void 0),Se=({children:e})=>{const[n,s]=l.useState(!1),[o,r]=l.useState(!1),[i,a]=l.useState(!0),[c,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;Ne({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const m=()=>d();return window.addEventListener("auth:logout",m),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async x=>{const p=await Le(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await Ce(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},f=asynLine truncated
|
||||
@@ -6,7 +6,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-CNpXfeP4.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-Cz55GfME.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-CvzvbbIV.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-D5pYdG6n.css">
|
||||
|
||||
Reference in new issue
Block a user