commit 074554a6de5581c21ceed6ee5b3e5320b1b0e12f Author: Christ Date: Sun Jun 28 11:54:39 2026 +0800 Initial xianyu-go repository diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b686b2c --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Build outputs +/server +/xianyu-server +/xianyu-init-admin +/init-admin +*.exe +*.test +*.out + +# Runtime data +/data/ +*.db +*.db-shm +*.db-wal +*.sqlite +*.sqlite3 + +# Uploads / temporary files +/uploads/ +/tmp/ +*.log + +# OS / editor +.DS_Store +.idea/ +.vscode/ + diff --git a/README.md b/README.md new file mode 100644 index 0000000..f8dc515 --- /dev/null +++ b/README.md @@ -0,0 +1,111 @@ +# 闲鱼管家 Go 后端 + +这是闲鱼自动回复/自动发货系统的 Go 重写后端。 + +## 运行方式 + +### 1) 本地开发运行 + +先构建前端静态文件: + +```bash +cd /Users/christ/Workspace/git/xianyu/xianyu-super-butler/frontend +npm install +npm run build +``` + +启动后端: + +```bash +cd /Users/christ/Workspace/git/xianyu/xianyu-go +go run ./cmd/server \ + -db data/xianyu_data.db \ + -addr :8080 \ + -web /Users/christ/Workspace/git/xianyu/xianyu-super-butler/static +``` + +浏览器打开: + +```text +http://localhost:8080 +``` + +### 2) 首次初始化管理员 + +系统第一次启动前先初始化管理员: + +```bash +cd /Users/christ/Workspace/git/xianyu/xianyu-go +go run ./cmd/server -init-admin -db data/xianyu_data.db +``` + +也可以指定密码: + +```bash +go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '你的密码' +``` + +### 3) 编译后运行 + +```bash +cd /Users/christ/Workspace/git/xianyu/xianyu-go +go build -o xianyu-server ./cmd/server +go build -o xianyu-init-admin ./cmd/init-admin +``` + +运行: + +```bash +./xianyu-server -db data/xianyu_data.db -addr :8080 -web /Users/christ/Workspace/git/xianyu/xianyu-super-butler/static +``` + +### 4) Docker 部署 + +批量铺货会用到上传目录,建议挂载持久化数据: + +```bash +docker run -v ./data:/app/data ... +``` + +并设置: + +```bash +XIANYU_UPLOAD_DIR=/app/data/uploads +``` + +## 常用参数 + +| 参数 | 说明 | +| --- | --- | +| `-db` | SQLite 数据库路径,默认 `data/xianyu_data.db` | +| `-addr` | HTTP 监听地址,默认 `:8080` | +| `-web` | 前端静态资源目录(包含 `index.html`) | +| `-init-admin` | 初始化/重置管理员后退出 | +| `-admin-email` | 初始化管理员邮箱 | +| `-admin-password` | 初始化管理员密码 | +| `-no-browser` | 禁用内置浏览器自动化 | +| `-secure` | HTTPS 模式(Cookie 加 Secure) | +| `-v` | 输出调试日志 | + +## 构建检查 + +```bash +go test ./... +``` + +前端: + +```bash +cd /Users/christ/Workspace/git/xianyu/xianyu-super-butler/frontend +npm run build +``` + +## 目录说明 + +- `cmd/server`:主服务入口 +- `cmd/init-admin`:管理员初始化 CLI +- `internal/db`:SQLite 和迁移 +- `internal/server`:HTTP API +- `internal/engine`:账号运行时 +- `internal/xianyu`:协议和 mtop 调用 +- `internal/webui`:内置静态前端资源 diff --git a/cmd/init-admin/main.go b/cmd/init-admin/main.go new file mode 100644 index 0000000..7c7b0ba --- /dev/null +++ b/cmd/init-admin/main.go @@ -0,0 +1,119 @@ +// init-admin 交互式初始化管理员账号,移植自 Python init_admin.py。 +// 沿用 Fork 安全基线:不创建默认口令,密码不回显、二次确认,bcrypt 哈希。 +// +// 用法:go run ./cmd/init-admin -db data/xianyu_data.db +package main + +import ( + "bufio" + "context" + "flag" + "fmt" + "os" + "strings" + + "golang.org/x/term" + + "xianyu-go/internal/db" +) + +func main() { + dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径") + flag.Parse() + + ctx := context.Background() + database, err := db.Open(ctx, *dbPath) + if err != nil { + fatalf("打开数据库失败: %v", err) + } + defer database.Close() + store := db.NewStore(database) + users := store.Users + + reader := bufio.NewReader(os.Stdin) + + existing, err := users.GetAdmin(ctx) + if err != nil && !isNotFound(err) { + fatalf("查询 admin 失败: %v", err) + } + + if existing != nil { + fmt.Printf("管理员用户 %s 已存在\n", existing.Username) + fmt.Print("是否重置管理员密码?(y/N): ") + ans, _ := reader.ReadString('\n') + if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") { + fmt.Println("跳过初始化") + return + } + pw := promptPasswordTwice(reader) + ok, err := users.UpdatePassword(ctx, existing.Username, pw) + if err != nil || !ok { + fatalf("重置 admin 密码失败: %v", err) + } + if err := users.SetAdmin(ctx, existing.Username); err != nil { + fatalf("设置管理员标记失败: %v", err) + } + fmt.Printf("重置完成:已更新 %s 的密码\n", existing.Username) + return + } + + fmt.Println("=== 初始化管理员账号(CLI)===") + fmt.Print("请输入管理员邮箱: ") + email, _ := reader.ReadString('\n') + email = strings.TrimSpace(email) + if email == "" { + fatalf("邮箱不能为空") + } + pw := promptPasswordTwice(reader) + + ok, err := users.Create(ctx, "admin", email, pw) + if err != nil || !ok { + fatalf("创建 admin 用户失败:用户名或邮箱可能已存在 (%v)", err) + } + if err := users.SetAdmin(ctx, "admin"); err != nil { + fatalf("设置管理员标记失败: %v", err) + } + fmt.Println("初始化完成:已创建 admin 用户") +} + +// promptPasswordTwice 两次输入密码(不回显)并校验一致性。 +func promptPasswordTwice(reader *bufio.Reader) string { + for { + p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ") + if p1 == "" { + fmt.Println("密码不能为空") + continue + } + p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ") + if p1 != p2 { + fmt.Println("两次输入不一致,请重试") + continue + } + return p1 + } +} + +// readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道), +// 共用同一 bufio.Reader 避免缓冲吞掉后续输入。 +func readPasswordNoEcho(reader *bufio.Reader, prompt string) string { + fmt.Print(prompt) + if term.IsTerminal(int(os.Stdin.Fd())) { + b, err := term.ReadPassword(int(os.Stdin.Fd())) + fmt.Println() + if err != nil { + fatalf("读取密码失败: %v", err) + } + return strings.TrimSpace(string(b)) + } + // 非 TTY 回退:共用传入的 reader。 + s, _ := reader.ReadString('\n') + fmt.Println() + return strings.TrimSpace(s) +} + +func isNotFound(err error) bool { return err == db.ErrNotFound } + +func fatalf(format string, a ...any) { + fmt.Fprintf(os.Stderr, format+"\n", a...) + os.Exit(1) +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..836996a --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,237 @@ +// cmd/server 是闲鱼管家 Go 主进程入口。 +// 启动:DB 迁移 → 加载账号引擎 → HTTP API 服务。 +// +// 用法: +// +// go run ./cmd/server -db data/xianyu_data.db -addr :8080 [-web ./static] [-secure] [-no-browser] +// go run ./cmd/server -db data/xianyu_data.db -init-admin -admin-password '...' +// +// 首次使用可直接用本二进制初始化管理员,不再需要单独 init-admin。 +// +// 浏览器自动化(扫码风控验证、滑块、密码登录、搜索、订单抓取)内置 playwright-go, +// 首次使用时自动下载 Chromium,无需手动启动 sidecar。加 -no-browser 可禁用。 +package main + +import ( + "context" + "flag" + "fmt" + "log/slog" + "os" + "os/signal" + "strings" + "sync" + "syscall" + "time" + + "xianyu-go/internal/account" + "xianyu-go/internal/browser" + "xianyu-go/internal/db" + "xianyu-go/internal/engine" + "xianyu-go/internal/server" +) + +func main() { + dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径") + addr := flag.String("addr", ":8080", "HTTP 监听地址") + webDir := flag.String("web", "", "前端静态资源目录(含 index.html)") + secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)") + noBrowser := flag.Bool("no-browser", false, "禁用内置浏览器自动化(扫码风控验证/滑块/搜索/订单抓取将不可用)") + verbose := flag.Bool("v", false, "调试日志") + initAdmin := flag.Bool("init-admin", false, "初始化或重置 admin 管理员后退出") + adminEmail := flag.String("admin-email", "admin@example.com", "初始化 admin 的邮箱") + adminPassword := flag.String("admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量") + flag.Parse() + + level := slog.LevelInfo + if *verbose { + level = slog.LevelDebug + } + logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level})) + + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + + // 1) DB。 + database, err := db.Open(ctx, *dbPath) + if err != nil { + logger.Error("打开数据库失败", "err", err) + os.Exit(1) + } + defer database.Close() + store := db.NewStore(database) + + if *initAdmin { + if err := ensureAdmin(ctx, store, *adminEmail, *adminPassword); err != nil { + logger.Error("初始化管理员失败", "err", err) + os.Exit(1) + } + logger.Info("管理员初始化完成", "username", "admin") + return + } + + // 检查系统是否已初始化。 + if init, _ := store.Users.IsSystemInitialized(ctx); !init { + logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员") + } + + // 2) 内置浏览器管理器(playwright-go,首运行自动下载 Chromium)。 + var bm *browser.Manager + if !*noBrowser { + bm = browser.NewManager(logger) + } + mgr := account.NewManager(store, &handlerAdapter{store: store, browser: bm, logger: logger}, logger) + if err := mgr.StartAll(ctx); err != nil { + logger.Error("启动账号引擎失败", "err", err) + } + + // 3) HTTP 服务。 + srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger) + if err := srv.Run(ctx); err != nil { + logger.Error("HTTP 服务退出", "err", err) + os.Exit(1) + } +} + +// handlerAdapter 实现 engine.Handler,把系统消息/密码登录刷新接到浏览器。 +// 聊天消息的发货/回复由 Account 内部 DeliveryService/ReplyService 处理。 +type handlerAdapter struct { + store *db.Store + browser *browser.Manager + logger *slog.Logger + + mu sync.Mutex + lastLoginByCID map[string]time.Time + orderFetchMu sync.Mutex + lastOrderFetch time.Time +} + +func (h *handlerAdapter) HandleChatMessage(ctx context.Context, m engine.ChatMessage) error { + return nil +} + +func (h *handlerAdapter) HandleSystemMessage(ctx context.Context, m engine.SystemMessage) error { + h.logger.Info("系统消息", "account", m.AccountID, "reminder", m.RedReminder) + return nil +} + +// Fetch 实现 engine.OrderDetailFetcher。只在本地订单缺少规格时启动浏览器, +// 并将所有账号的详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。 +func (h *handlerAdapter) Fetch(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*engine.OrderDetail, error) { + if order, err := h.store.Orders.Get(ctx, orderID); err == nil && order != nil && order.Amount != "" && order.Quantity != "" && + (!h.store.Items.IsMultiSpec(ctx, cookieID, itemID) || (order.SpecName != "" && order.SpecValue != "")) { + return &engine.OrderDetail{Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue, Amount: order.Amount, OrderStatus: order.OrderStatus}, nil + } + if h.browser == nil { + return nil, fmt.Errorf("订单缺少规格信息且浏览器自动化未启用") + } + + h.orderFetchMu.Lock() + defer h.orderFetchMu.Unlock() + // 等锁期间其他流程可能已经补齐订单,再检查一次。 + if order, err := h.store.Orders.Get(ctx, orderID); err == nil && order != nil && order.Amount != "" && order.Quantity != "" && + (!h.store.Items.IsMultiSpec(ctx, cookieID, itemID) || (order.SpecName != "" && order.SpecValue != "")) { + return &engine.OrderDetail{Quantity: order.Quantity, SpecName: order.SpecName, SpecValue: order.SpecValue, Amount: order.Amount, OrderStatus: order.OrderStatus}, nil + } + if remain := 3*time.Second - time.Since(h.lastOrderFetch); !h.lastOrderFetch.IsZero() && remain > 0 { + timer := time.NewTimer(remain) + defer timer.Stop() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-timer.C: + } + } + h.lastOrderFetch = time.Now() + detail, err := h.browser.FetchOrderDetail(ctx, orderID, cookieID, cookieStr, h.store.Items.IsMultiSpec(ctx, cookieID, itemID)) + if err != nil { + return nil, err + } + if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr { + _ = h.store.Cookies.Save(ctx, cookieID, detail.UpdatedCookies, 0) + } + return &engine.OrderDetail{ + Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue, + Amount: detail.Amount, OrderStatus: detail.OrderStatus, + }, nil +} + +// OnPasswordLoginRefresh 连续失败时调用浏览器密码登录刷新 cookie。 +func (h *handlerAdapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool { + if h.browser == nil { + h.logger.Warn("密码登录刷新失败:浏览器自动化已禁用") + return false + } + h.mu.Lock() + if h.lastLoginByCID == nil { + h.lastLoginByCID = make(map[string]time.Time) + } + last := h.lastLoginByCID[cookieID] + if !last.IsZero() && time.Since(last) < engine.PasswordLoginMinGap { + remain := engine.PasswordLoginMinGap - time.Since(last) + h.mu.Unlock() + h.logger.Warn("密码登录刷新冷却中", "account", cookieID, "remain", remain.Round(time.Second)) + return false + } + h.mu.Unlock() + + d, err := h.store.Cookies.GetDetails(ctx, cookieID) + if err != nil { + h.logger.Warn("密码登录刷新失败:读取账号详情失败", "account", cookieID, "err", err) + return false + } + if strings.TrimSpace(d.Username) == "" || strings.TrimSpace(d.Password) == "" { + h.logger.Warn("密码登录刷新失败:账号未配置登录用户名或密码", "account", cookieID) + return false + } + h.mu.Lock() + h.lastLoginByCID[cookieID] = time.Now() + h.mu.Unlock() + cookies, err := h.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", !d.ShowBrowser) + if err != nil { + h.logger.Warn("密码登录刷新失败", "account", cookieID, "err", err) + return false + } + cookieStr := browser.MarshalCookies(cookies) + if strings.TrimSpace(cookieStr) == "" { + h.logger.Warn("密码登录刷新失败:浏览器未返回 cookie", "account", cookieID) + return false + } + if err := h.store.Cookies.Save(ctx, cookieID, cookieStr, d.UserID); err != nil { + h.logger.Warn("密码登录刷新失败:保存 cookie 失败", "account", cookieID, "err", err) + return false + } + h.logger.Info("密码登录刷新 cookie 成功", "account", cookieID) + return true +} + +func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error { + if password == "" { + password = os.Getenv("XIANYU_ADMIN_PASSWORD") + } + if password == "" { + return fmt.Errorf("admin 密码不能为空,请传 -admin-password 或设置 XIANYU_ADMIN_PASSWORD") + } + existing, err := store.Users.GetAdmin(ctx) + if err != nil && err != db.ErrNotFound { + return err + } + if existing != nil { + ok, err := store.Users.UpdatePassword(ctx, existing.Username, password) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("admin 用户存在但密码未更新") + } + return store.Users.SetAdmin(ctx, existing.Username) + } + ok, err := store.Users.Create(ctx, "admin", email, password) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("创建 admin 用户失败:用户名或邮箱可能已存在") + } + return store.Users.SetAdmin(ctx, "admin") +} diff --git a/cmd/spike/main.go b/cmd/spike/main.go new file mode 100644 index 0000000..46bcbe9 --- /dev/null +++ b/cmd/spike/main.go @@ -0,0 +1,122 @@ +//go:build debug || tools + +// spike 是 Phase 0 协议可行性验证程序(go/no-go 闸门)。 +// +// 串起单账号完整链路: +// +// cookie → mtop token API(签名)→ accessToken → WS 连接 → /reg 注册 → 心跳 → 收消息 → ACK → 解密 +// +// 用法: +// +// export XIANYU_COOKIE='unb=...; _m_h5_tk=...; cookie2=...; ...' +// go run -tags debug ./cmd/spike +// +// 或从文件读取(避免 cookie 出现在进程列表): +// +// go run -tags debug ./cmd/spike -cookie-file /path/to/cookie.txt +// +// 真机验证成功(能收到并解密一条闲鱼消息)即视为 Phase 0 通过。 +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log/slog" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "xianyu-go/internal/logsafe" + "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/protocol" + "xianyu-go/internal/xianyu/ws" +) + +func main() { + cookieFile := flag.String("cookie-file", "", "从文件读取 cookie(首行)") + verbose := flag.Bool("v", false, "调试日志") + flag.Parse() + + logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})) + if *verbose { + logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})) + } + + cookieStr := strings.TrimSpace(os.Getenv("XIANYU_COOKIE")) + if *cookieFile != "" { + b, err := os.ReadFile(*cookieFile) + if err != nil { + logger.Error("读取 cookie 文件失败", "err", err) + os.Exit(1) + } + cookieStr = strings.TrimSpace(strings.SplitN(string(b), "\n", 2)[0]) + } + if cookieStr == "" { + fmt.Fprintln(os.Stderr, "缺少 cookie:请设置 XIANYU_COOKIE 环境变量或用 -cookie-file 指定") + os.Exit(2) + } + + // 基本校验:必须有 unb 和 _m_h5_tk。 + c := protocol.TransCookies(cookieStr) + if c["unb"] == "" || c["_m_h5_tk"] == "" { + fmt.Fprintln(os.Stderr, "cookie 缺少 unb 或 _m_h5_tk 字段") + os.Exit(2) + } + logger.Info("cookie 已加载", "account_hash", logsafe.ID(c["unb"]), "fields", len(c)) + + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + + // 1) mtop token API → accessToken。 + mc := &mtop.Client{} + logger.Info("步骤 1/3:刷新 token") + res, err := mc.RefreshToken(cookieStr) + if err != nil { + logger.Error("刷新 token 失败", "err", err) + os.Exit(1) + } + logger.Info("token 刷新成功", "accessToken_len", len(res.AccessToken)) + + // 2) WS 连接 + 注册。 + deviceID := protocol.GenerateDeviceID(c["unb"]) + cfg := ws.Config{ + CookieStr: res.UpdatedCookies, + DeviceID: deviceID, + AccessToken: res.AccessToken, + } + logger.Info("步骤 2/3:连接 WebSocket", "device_id", deviceID) + conn, err := ws.Dial(ctx, cfg, logger) + if err != nil { + logger.Error("WS 连接/注册失败", "err", err) + os.Exit(1) + } + defer conn.Close() + + // 3) 心跳 + 收消息。 + logger.Info("步骤 3/3:心跳与消息接收(等待闲鱼消息…)") + go func() { + if err := conn.HeartbeatLoop(ctx, 15*time.Second); err != nil { + logger.Error("心跳循环退出", "err", err) + cancel() + } + }() + + gotMessage := false + err = conn.ReceiveLoop(ctx, func(decrypted map[string]any) { + gotMessage = true + b, _ := json.MarshalIndent(decrypted, "", " ") + fmt.Println("\n========== 收到并解密一条消息 ==========") + fmt.Println(string(b)) + fmt.Println("========================================") + logger.Info("✅ 成功收到并解密消息,Phase 0 闸门通过") + cancel() + }) + if !gotMessage { + logger.Error("未收到消息即退出", "err", err) + os.Exit(1) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..7c4d02f --- /dev/null +++ b/go.mod @@ -0,0 +1,34 @@ +module xianyu-go + +go 1.26.1 + +require ( + github.com/coder/websocket v1.8.15 + github.com/go-chi/chi/v5 v5.3.0 + github.com/playwright-community/playwright-go v0.5700.1 + github.com/pressly/goose/v3 v3.27.1 + github.com/sashabaranov/go-openai v1.41.2 + github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e + golang.org/x/crypto v0.50.0 + golang.org/x/term v0.44.0 + modernc.org/sqlite v1.53.0 +) + +require ( + github.com/deckarep/golang-set/v2 v2.8.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-jose/go-jose/v3 v3.0.4 // indirect + github.com/go-stack/stack v1.8.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.21 // indirect + github.com/mfridman/interpolate v0.0.2 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/sethvargo/go-retry v0.3.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.46.0 // indirect + modernc.org/libc v1.73.4 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..c6d8d57 --- /dev/null +++ b/go.sum @@ -0,0 +1,130 @@ +github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= +github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/deckarep/golang-set/v2 v2.8.0 h1:swm0rlPCmdWn9mESxKOjWk8hXSqoxOp+ZlfuyaAdFlQ= +github.com/deckarep/golang-set/v2 v2.8.0/go.mod h1:VAky9rY/yGXJOLEDv3OMci+7wtDpOF4IN+y82NBOac4= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM= +github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY= +github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= +github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= +github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs= +github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= +github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/playwright-community/playwright-go v0.5700.1 h1:PNFb1byWqrTT720rEO0JL88C6Ju0EmUnR5deFLvtP/U= +github.com/playwright-community/playwright-go v0.5700.1/go.mod h1:MlSn1dZrx8rszbCxY6x3qK89ZesJUYVx21B2JnkoNF0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pressly/goose/v3 v3.27.1 h1:6uEvcprBybDmW4hcz3gYujhARhye+GoWKhEWyzD5sh4= +github.com/pressly/goose/v3 v3.27.1/go.mod h1:maruOxsPnIG2yHHyo8UqKWXYKFcH7Q76csUV7+7KYoM= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM= +github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg= +github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE= +github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= +golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= +golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= +golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= +golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c= +modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws= +modernc.org/ccgo/v4 v4.34.4/go.mod h1:qdKqE8FNIYyysougB1RX9MxCzp5oJOcQXSobANJ4TuE= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc= +modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA= +modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M= +modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/account/manager.go b/internal/account/manager.go new file mode 100644 index 0000000..d816c76 --- /dev/null +++ b/internal/account/manager.go @@ -0,0 +1,213 @@ +// Package account 实现多账号生命周期管理(supervisor): +// 从 DB 加载启用的闲鱼账号,为每个账号起一个 engine.Account goroutine, +// 支持动态启停、状态查询、跨层 GetInstance(供 HTTP 手动发货等操作调用)。 +// +// 对应 Python cookie_manager.CookieManager + XianyuLive._instances。 +package account + +import ( + "context" + "fmt" + "log/slog" + "sync" + "time" + + "xianyu-go/internal/db" + "xianyu-go/internal/engine" +) + +// Manager 管理所有账号运行时。 +type Manager struct { + store *db.Store + handler engine.Handler + logger *slog.Logger + + mu sync.Mutex + accounts map[string]*managedAccount + runCtx context.Context +} + +type managedAccount struct { + cookieID string + acc *engine.Account + cancel context.CancelFunc + done chan struct{} // Run 返回后关闭 + err error +} + +// NewManager 构造管理器。 +func NewManager(store *db.Store, handler engine.Handler, logger *slog.Logger) *Manager { + if logger == nil { + logger = slog.Default() + } + return &Manager{ + store: store, + handler: handler, + logger: logger, + accounts: make(map[string]*managedAccount), + } +} + +// StartAll 从 DB 加载所有启用的账号并启动。 +// 已禁用的账号不启动;启动失败的账号记录错误但不影响其他账号。 +func (m *Manager) StartAll(ctx context.Context) error { + m.mu.Lock() + m.runCtx = ctx + m.mu.Unlock() + // 管理员视角取全部 cookie(userID=0)。 + all, err := m.store.Cookies.AllForUser(ctx, 0) + if err != nil { + return fmt.Errorf("加载账号失败: %w", err) + } + for cookieID, cookieValue := range all { + if !m.store.Cookies.GetStatus(ctx, cookieID) { + m.logger.Info("账号已禁用,跳过启动", "account", cookieID) + continue + } + if err := m.Start(ctx, cookieID, cookieValue); err != nil { + m.logger.Error("启动账号失败", "account", cookieID, "err", err) + } + } + return nil +} + +// Start 启动单个账号(若已在运行则跳过)。 +func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error { + m.mu.Lock() + if m.runCtx != nil { + ctx = m.runCtx + } + if ma, ok := m.accounts[cookieID]; ok { + m.mu.Unlock() + // 已存在:如果已退出则清理后重启,否则跳过。 + select { + case <-ma.done: + m.mu.Lock() + delete(m.accounts, cookieID) + m.mu.Unlock() + default: + m.logger.Info("账号已在运行,跳过", "account", cookieID) + return nil + } + } + m.mu.Unlock() + + acc := engine.New(engine.Config{ + CookieID: cookieID, + CookieStr: cookieValue, + Store: m.store, + Handler: m.handler, + Logger: m.logger, + }) + accCtx, cancel := context.WithCancel(ctx) + ma := &managedAccount{ + cookieID: cookieID, + acc: acc, + cancel: cancel, + done: make(chan struct{}), + } + + m.mu.Lock() + m.accounts[cookieID] = ma + m.mu.Unlock() + + m.logger.Info("启动账号", "account", cookieID) + go func() { + defer close(ma.done) + ma.err = acc.Run(accCtx) + m.logger.Info("账号运行结束", "account", cookieID, "err", ma.err) + }() + return nil +} + +// Stop 停止单个账号。 +func (m *Manager) Stop(cookieID string) { + m.mu.Lock() + ma, ok := m.accounts[cookieID] + m.mu.Unlock() + if !ok { + return + } + ma.acc.Stop() + ma.cancel() + <-ma.done + m.mu.Lock() + delete(m.accounts, cookieID) + m.mu.Unlock() + m.logger.Info("账号已停止", "account", cookieID) +} + +// StopAll 停止所有账号。 +func (m *Manager) StopAll() { + m.mu.Lock() + ids := make([]string, 0, len(m.accounts)) + for id := range m.accounts { + ids = append(ids, id) + } + m.mu.Unlock() + for _, id := range ids { + m.Stop(id) + } +} + +// GetInstance 跨层获取账号运行时(供 HTTP 手动发货等操作)。 +func (m *Manager) GetInstance(cookieID string) (*engine.Account, bool) { + m.mu.Lock() + defer m.mu.Unlock() + ma, ok := m.accounts[cookieID] + if !ok { + return nil, false + } + return ma.acc, true +} + +// RunningAccounts 返回当前运行的账号 ID 列表(用于状态展示)。 +func (m *Manager) RunningAccounts() []string { + m.mu.Lock() + defer m.mu.Unlock() + ids := make([]string, 0, len(m.accounts)) + for id, ma := range m.accounts { + select { + case <-ma.done: + continue + default: + ids = append(ids, id) + } + } + return ids +} + +// RuntimeStatuses 返回所有已启动账号的实时状态快照。 +func (m *Manager) RuntimeStatuses() map[string]engine.RuntimeStatus { + m.mu.Lock() + defer m.mu.Unlock() + statuses := make(map[string]engine.RuntimeStatus, len(m.accounts)) + for id, ma := range m.accounts { + status := ma.acc.RuntimeStatus() + select { + case <-ma.done: + if status.State != engine.RuntimeAuthExpired && status.State != engine.RuntimeVerificationRequired { + status.State = engine.RuntimeError + status.Connected = false + status.Message = "账号服务已退出" + if ma.err != nil && ma.err != context.Canceled { + status.Message = ma.err.Error() + } + status.UpdatedAt = time.Now() + } + default: + } + statuses[id] = status + } + return statuses +} + +// Restart 重启账号(停后用最新 DB cookie 重启)。 +func (m *Manager) Restart(ctx context.Context, cookieID string) error { + m.Stop(cookieID) + d, err := m.store.Cookies.GetDetails(ctx, cookieID) + if err != nil { + return fmt.Errorf("读取账号详情失败: %w", err) + } + return m.Start(ctx, cookieID, d.Value) +} diff --git a/internal/account/manager_test.go b/internal/account/manager_test.go new file mode 100644 index 0000000..e770575 --- /dev/null +++ b/internal/account/manager_test.go @@ -0,0 +1,75 @@ +package account + +import ( + "context" + "path/filepath" + "testing" + "time" + + "xianyu-go/internal/db" + "xianyu-go/internal/engine" +) + +type noopHandler struct{} + +func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil } +func (noopHandler) HandleSystemMessage(context.Context, engine.SystemMessage) error { return nil } +func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false } + +// TestManager_StartStopAll 验证从 DB 加载账号、启停、GetInstance、RunningAccounts。 +// 用无效 cookie 让账号快速进入重连等待(不会真正连上),验证管理逻辑而非网络。 +func TestManager_StartStopAll(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "test.db") + d, err := db.Open(context.Background(), dbPath) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer d.Close() + store := db.NewStore(d) + store.Users.Create(context.Background(), "admin", "a@e.com", "pw") + admin, _ := store.Users.GetByUsername(context.Background(), "admin") + + // 两个启用 + 一个禁用的账号。 + store.Cookies.Save(context.Background(), "acc1", "unb=1; _m_h5_tk=t1_1;", admin.ID) + store.Cookies.SetStatus(context.Background(), "acc1", true) + store.Cookies.Save(context.Background(), "acc2", "unb=2; _m_h5_tk=t2_1;", admin.ID) + store.Cookies.SetStatus(context.Background(), "acc2", true) + store.Cookies.Save(context.Background(), "acc3", "unb=3; _m_h5_tk=t3_1;", admin.ID) + store.Cookies.SetStatus(context.Background(), "acc3", false) + + mgr := NewManager(store, noopHandler{}, nil) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if err := mgr.StartAll(ctx); err != nil { + t.Fatalf("StartAll: %v", err) + } + + // acc1/acc2 应在运行,acc3 不应。 + running := map[string]bool{} + for _, id := range mgr.RunningAccounts() { + running[id] = true + } + if !running["acc1"] || !running["acc2"] { + t.Fatalf("acc1/acc2 应运行,got %v", running) + } + if running["acc3"] { + t.Fatal("acc3 已禁用不应启动") + } + + // GetInstance 可取到。 + if acc, ok := mgr.GetInstance("acc1"); !ok || acc == nil { + t.Fatal("GetInstance(acc1) 失败") + } + if _, ok := mgr.GetInstance("acc3"); ok { + t.Fatal("acc3 不应有实例") + } + + // StopAll 应能干净停止。 + mgr.StopAll() + // 给 goroutine 退出时间。 + time.Sleep(100 * time.Millisecond) + if len(mgr.RunningAccounts()) != 0 { + t.Fatalf("StopAll 后应无运行账号,got %v", mgr.RunningAccounts()) + } +} diff --git a/internal/auth/auth.go b/internal/auth/auth.go new file mode 100644 index 0000000..a155315 --- /dev/null +++ b/internal/auth/auth.go @@ -0,0 +1,163 @@ +// Package auth 实现 HttpOnly Cookie 会话认证,沿用 Fork 版安全基线: +// - 无默认口令(管理员必须经 init-admin CLI 初始化) +// - 会话存 DB(sessions 表),HttpOnly + SameSite=Lax Cookie 传递 +// - bcrypt 哈希,兼容老库无盐 SHA-26(首次登录静默升级) +// +// 中间件基于 net/http,兼容 chi。 +package auth + +import ( + "context" + "errors" + "log/slog" + "net/http" + + "xianyu-go/internal/db" +) + +// CookieName 会话 Cookie 名(与 Python 端 SESSION_COOKIE_NAME 一致)。 +const CookieName = "session" + +// CookieMaxAge 会话有效期(24 小时)。 +const CookieMaxAge = 24 * 60 * 60 + +// ctxKey 上下文键类型,避免冲突。 +type ctxKey int + +const ( + ctxKeyUser ctxKey = iota +) + +// Service 认证服务。 +type Service struct { + Store *db.Store + Logger *slog.Logger + Secure bool // HTTPS 下应为 true,Cookie 加 Secure 标记 +} + +// LoginResult 登录结果。 +type LoginResult struct { + Success bool + User *db.User + Message string +} + +// Login 用户名密码登录。成功时返回会话 ID(由调用方写入 Cookie)。 +func (s *Service) Login(ctx context.Context, username, password string) (string, *db.User, error) { + user, ok, err := s.Store.Users.VerifyAndUpgrade(ctx, username, password) + if err != nil { + return "", nil, err + } + if !ok { + return "", nil, nil // 密码错误或用户不存在/未激活 + } + sid, err := s.Store.Sessions.Create(ctx, user) + if err != nil { + return "", nil, err + } + return sid, user, nil +} + +// CreateSessionForUser 为已加载的 user 创建会话,返回 session ID。 +func (s *Service) CreateSessionForUser(user *db.User) string { + sid, err := s.Store.Sessions.Create(context.Background(), user) + if err != nil { + s.Logger.Error("创建会话失败", "err", err) + return "" + } + return sid +} + +// Logout 删除会话并返回清 Cookie 所需操作。 +func (s *Service) Logout(ctx context.Context, sessionID string) { + if sessionID != "" { + _ = s.Store.Sessions.Delete(ctx, sessionID) + } +} + +// SetSessionCookie 把会话 ID 写入响应 Cookie(HttpOnly + SameSite=Lax)。 +func (s *Service) SetSessionCookie(w http.ResponseWriter, sessionID string) { + http.SetCookie(w, &http.Cookie{ + Name: CookieName, + Value: sessionID, + Path: "/", + MaxAge: CookieMaxAge, + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.Secure, + }) +} + +// ClearSessionCookie 清除会话 Cookie。 +func (s *Service) ClearSessionCookie(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: CookieName, + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.Secure, + }) +} + +// SessionFromRequest 从请求 Cookie 取会话。无效返回 nil。 +func (s *Service) SessionFromRequest(ctx context.Context, r *http.Request) (*db.Session, error) { + c, err := r.Cookie(CookieName) + if err != nil || c.Value == "" { + return nil, nil + } + sess, err := s.Store.Sessions.Get(ctx, c.Value) + if err != nil { + if errors.Is(err, db.ErrNotFound) { + return nil, nil + } + return nil, err + } + return sess, nil +} + +// Middleware 解析会话并把 *db.Session 放入请求上下文。不强制登录(公开路由也可用)。 +func (s *Service) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sess, err := s.SessionFromRequest(r.Context(), r) + if err != nil { + s.Logger.Warn("读取会话失败", "err", err) + } + ctx := WithSession(r.Context(), sess) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +// RequireAuth 要求已登录,否则 401。 +func RequireAuth(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if SessionFromContext(r.Context()) == nil { + http.Error(w, `{"detail":"未授权访问"}`, http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +} + +// RequireAdmin 要求管理员,否则 403(须在 RequireAuth 之后)。 +func RequireAdmin(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sess := SessionFromContext(r.Context()) + if sess == nil || !sess.IsAdmin { + http.Error(w, `{"detail":"需要管理员权限"}`, http.StatusForbidden) + return + } + next.ServeHTTP(w, r) + }) +} + +// WithSession / SessionFromContext 上下文存取。 +func WithSession(ctx context.Context, sess *db.Session) context.Context { + return context.WithValue(ctx, ctxKeyUser, sess) +} + +func SessionFromContext(ctx context.Context) *db.Session { + v, _ := ctx.Value(ctxKeyUser).(*db.Session) + return v +} diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go new file mode 100644 index 0000000..740a8d1 --- /dev/null +++ b/internal/auth/auth_test.go @@ -0,0 +1,115 @@ +package auth + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "xianyu-go/internal/db" +) + +func newAuth(t *testing.T) (*Service, func()) { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "test.db") + d, err := db.Open(context.Background(), dbPath) + if err != nil { + t.Fatalf("Open: %v", err) + } + store := db.NewStore(d) + // 初始化 admin。 + if ok, _ := store.Users.Create(context.Background(), "admin", "a@e.com", "pw"); !ok { + t.Fatal("create admin") + } + store.Users.SetAdmin(context.Background(), "admin") + svc := &Service{Store: store, Logger: testLogger()} + return svc, func() { d.Close() } +} + +func testLogger() *slog.Logger { return slog.Default() } + +func TestLoginAndMiddleware(t *testing.T) { + svc, cleanup := newAuth(t) + defer cleanup() + ctx := context.Background() + + // 登录。 + sid, user, err := svc.Login(ctx, "admin", "pw") + if err != nil || user == nil || sid == "" { + t.Fatalf("Login: err=%v user=%v sid=%q", err, user, sid) + } + // 错误密码。 + _, noUser, _ := svc.Login(ctx, "admin", "wrong") + if noUser != nil { + t.Fatal("错误密码不应登录成功") + } + + // 中间件解析会话。 + chain := svc.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sess := SessionFromContext(r.Context()) + if sess == nil || !sess.IsAdmin { + t.Errorf("中间件应解析出管理员会话,got=%v", sess) + } + w.WriteHeader(200) + })) + + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.AddCookie(&http.Cookie{Name: CookieName, Value: sid}) + rec := httptest.NewRecorder() + chain.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("status=%d", rec.Code) + } +} + +func TestRequireAuthAndAdmin(t *testing.T) { + svc, cleanup := newAuth(t) + defer cleanup() + ctx := context.Background() + sid, _, _ := svc.Login(ctx, "admin", "pw") + + protected := svc.Middleware(RequireAuth(RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + })))) + + // 无 cookie → 401。 + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + protected.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("未登录应 401,got %d", rec.Code) + } + + // 有 admin cookie → 200。 + req2 := httptest.NewRequest(http.MethodGet, "/", nil) + req2.AddCookie(&http.Cookie{Name: CookieName, Value: sid}) + rec2 := httptest.NewRecorder() + protected.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("管理员应 200,got %d", rec2.Code) + } +} + +func TestSetAndClearCookie(t *testing.T) { + svc, cleanup := newAuth(t) + defer cleanup() + + rec := httptest.NewRecorder() + svc.SetSessionCookie(rec, "sid123") + c := rec.Result().Cookies() + if len(c) != 1 || c[0].Name != CookieName || c[0].Value != "sid123" || !c[0].HttpOnly { + t.Fatalf("SetSessionCookie 异常: %+v", c) + } + if c[0].SameSite != http.SameSiteLaxMode { + t.Fatalf("SameSite 应为 Lax,got %v", c[0].SameSite) + } + + rec2 := httptest.NewRecorder() + svc.ClearSessionCookie(rec2) + cc := rec2.Result().Cookies() + if len(cc) != 1 || cc[0].MaxAge != -1 { + t.Fatalf("ClearSessionCookie 应 MaxAge=-1: %+v", cc) + } +} diff --git a/internal/browser/cookies.go b/internal/browser/cookies.go new file mode 100644 index 0000000..f446759 --- /dev/null +++ b/internal/browser/cookies.go @@ -0,0 +1,108 @@ +package browser + +import ( + "math/rand" + "strconv" + "strings" + "time" + + "github.com/playwright-community/playwright-go" +) + +// parseCookieStr 把 "k=v; k2=v2" 解析为 map。 +func parseCookieStr(s string) map[string]string { + m := make(map[string]string) + for _, part := range strings.Split(s, ";") { + part = strings.TrimSpace(part) + if eq := strings.Index(part, "="); eq >= 0 { + m[part[:eq]] = part[eq+1:] + } + } + return m +} + +// cookieMarshal 把 map 拼成 "k=v; k2=v2"。 +func cookieMarshal(m map[string]string) string { + parts := make([]string, 0, len(m)) + for k, v := range m { + parts = append(parts, k+"="+v) + } + return strings.Join(parts, "; ") +} + +// MarshalCookies 把 cookie map 拼成标准 Cookie 头字符串。 +func MarshalCookies(m map[string]string) string { + return cookieMarshal(m) +} + +// parseCookieStrToPlaywright 把 cookie 字符串转成 playwright OptionalCookie(domain .goofish.com)。 +func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie { + var cookies []playwright.OptionalCookie + for _, part := range strings.Split(s, ";") { + part = strings.TrimSpace(part) + if eq := strings.Index(part, "="); eq >= 0 { + name := part[:eq] + value := part[eq+1:] + if name == "" { + continue + } + cookies = append(cookies, playwright.OptionalCookie{ + Name: name, + Value: value, + Domain: playwright.String(goofishDot), + Path: playwright.String("/"), + }) + } + } + return cookies +} + +// cookiesToMap 把 playwright Cookie 切片转成 map。 +func cookiesToMap(cs []playwright.Cookie) map[string]string { + m := make(map[string]string, len(cs)) + for _, c := range cs { + m[c.Name] = c.Value + } + return m +} + +// cookiesToStr 把 playwright Cookie 切片拼成字符串。 +func cookiesToStr(cs []playwright.Cookie) string { + m := cookiesToMap(cs) + return cookieMarshal(m) +} + +// rng 用于浏览器流程的随机化(轨迹、stealth 参数)。全局,进程级足够。 +var rng = rand.New(rand.NewSource(time.Now().UnixNano())) + +// stealthScript 生成隐身 JS(移植自 xianyu_slider_stealth._get_stealth_script)。 +// 原 Python 用 f-string 插入随机值;这里用占位符 + Go 运行时替换。 +func stealthScript() string { + pluginCount := rng.Intn(6) + 3 // 3-8 + hwCores := []int{2, 4, 6, 8}[rng.Intn(4)] + mem := []int{4, 8, 16}[rng.Intn(3)] + effType := []string{"3g", "4g", "5g"}[rng.Intn(3)] + rtt := rng.Intn(81) + 20 // 20-100 + downlink := float64(rng.Intn(901)+100) / 100.0 // 1.00-10.00 + maxTouch := []int{0, 1, 5, 10}[rng.Intn(4)] + battCharging := []string{"true", "false"}[rng.Intn(2)] + battLevel := float64(rng.Intn(66)+30) / 100.0 // 0.30-0.95 + + repl := strings.NewReplacer( + "{{PLUGIN_COUNT}}", strconv.Itoa(pluginCount), + "{{LOCALE}}", defaultLang, + "{{VW}}", strconv.Itoa(defaultW), + "{{VH}}", strconv.Itoa(defaultH), + "{{HW_CORES}}", strconv.Itoa(hwCores), + "{{MEM}}", strconv.Itoa(mem), + "{{TZ}}", defaultTZ, + "{{EFF_TYPE}}", effType, + "{{RTT}}", strconv.Itoa(rtt), + "{{DOWNLINK}}", strconv.FormatFloat(downlink, 'f', 2, 64), + "{{MAX_TOUCH}}", strconv.Itoa(maxTouch), + "{{BATT_CHARGE}}", battCharging, + "{{BATT_LEVEL}}", strconv.FormatFloat(battLevel, 'f', 2, 64), + "{{UA}}", defaultUA, + ) + return repl.Replace(stealthTemplate) +} diff --git a/internal/browser/cookies_test.go b/internal/browser/cookies_test.go new file mode 100644 index 0000000..e80141e --- /dev/null +++ b/internal/browser/cookies_test.go @@ -0,0 +1,89 @@ +package browser + +import ( + "strings" + "testing" +) + +func TestParseCookieStrRoundTrip(t *testing.T) { + in := "unb=999; _m_h5_tk=abc_1; cookie2=xyz" + m := parseCookieStr(in) + if m["unb"] != "999" || m["_m_h5_tk"] != "abc_1" || m["cookie2"] != "xyz" { + t.Fatalf("解析异常: %+v", m) + } + out := cookieMarshal(m) + // 顺序不保证,逐项检查。 + for _, kv := range []string{"unb=999", "_m_h5_tk=abc_1", "cookie2=xyz"} { + if !strings.Contains(out, kv) { + t.Fatalf("marshal 缺少 %q: %q", kv, out) + } + } +} + +func TestParseCookieStrToPlaywright(t *testing.T) { + cookies := parseCookieStrToPlaywright("a=1; b=2") + if len(cookies) != 2 { + t.Fatalf("应解析 2 个 cookie,got %d", len(cookies)) + } + for _, c := range cookies { + if c.Domain == nil || *c.Domain != goofishDot { + t.Fatalf("domain 应为 %s: %+v", goofishDot, c.Domain) + } + if c.Path == nil || *c.Path != "/" { + t.Fatalf("path 应为 /: %+v", c.Path) + } + } +} + +func TestParseCookieStrEmpty(t *testing.T) { + if got := parseCookieStr(""); len(got) != 0 { + t.Fatalf("空串应返回空 map, got %+v", got) + } + if got := parseCookieStrToPlaywright(",,, ;"); len(got) != 0 { + t.Fatalf("无效串应返回空, got %+v", got) + } +} + +func TestCookiesToMapAndStr(t *testing.T) { + // 用 cookiesToMap/cookiesToStr 覆盖(构造 Cookie 不导出字段,借 parse 间接)。 + m := map[string]string{"unb": "1", "cna": "xx"} + s := cookieMarshal(m) + m2 := parseCookieStr(s) + if m2["unb"] != "1" || m2["cna"] != "xx" { + t.Fatalf("往返异常: %+v", m2) + } +} + +func TestStealthScriptReplaced(t *testing.T) { + s := stealthScript() + if strings.Contains(s, "{{") { + t.Fatalf("stealth 脚本仍有未替换占位符: %q", s[:min(200, len(s))]) + } + for _, key := range []string{"webdriver", "chrome", "RTCPeerConnection", "toDataURL"} { + if !strings.Contains(s, key) { + t.Fatalf("stealth 脚本缺少关键段 %q", key) + } + } +} + +func TestStealthScriptUnique(t *testing.T) { + // 多次生成应有时不同(随机参数)。 + a := stealthScript() + differ := false + for i := 0; i < 10; i++ { + if stealthScript() != a { + differ = true + break + } + } + if !differ { + t.Fatal("stealth 脚本多次生成应出现随机差异") + } +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/internal/browser/lifecycle.go b/internal/browser/lifecycle.go new file mode 100644 index 0000000..65c2da6 --- /dev/null +++ b/internal/browser/lifecycle.go @@ -0,0 +1,314 @@ +// Package browser 用 playwright-go 在进程内驱动 Chromium,替换原 Python sidecar。 +// 首次使用时自动下载 Chromium(playwright.Install),无需手动启动任何外部服务。 +// +// 移植自原项目: +// - utils/browser_pool.py → Manager 上下文池 +// - utils/xianyu_slider_stealth.py → stealth.go + slider.go +// - utils/item_search.py → search.go +// - utils/order_fetcher_optimized.py → orders.go +// - XianyuAutoAsync.refresh_cookies_from_qr_login → qrrefresh.go +package browser + +import ( + "context" + "errors" + "fmt" + "log/slog" + "sync" + "time" + + "github.com/playwright-community/playwright-go" + + "xianyu-go/internal/xianyu" +) + +// 默认 UA / 视口,与 Python 端一致。 +const ( + defaultUA = xianyu.BrowserUA + defaultW = 1920 + defaultH = 1080 + defaultLang = "zh-CN" + defaultTZ = "Asia/Shanghai" + goofishDot = ".goofish.com" + goofishIMURL = "https://www.goofish.com/im" +) + +// chromiumLaunchArgs 统一 Chromium 启动参数(取自 browser_pool._create_browser)。 +func chromiumLaunchArgs() []string { + return []string{ + "--no-sandbox", + "--disable-setuid-sandbox", + "--disable-dev-shm-usage", + "--disable-gpu", + "--disable-extensions", + "--disable-blink-features=AutomationControlled", + "--disable-background-timer-throttling", + "--disable-backgrounding-occluded-windows", + "--disable-renderer-backgrounding", + "--disable-features=TranslateUI", + "--disable-ipc-flooding-protection", + "--disable-default-apps", + "--disable-sync", + "--disable-translate", + "--hide-scrollbars", + "--mute-audio", + "--no-default-browser-check", + "--no-pings", + "--lang=zh-CN", + } +} + +// Manager 管理浏览器生命周期与按账号复用的上下文池。 +type Manager struct { + pw *playwright.Playwright + logger *slog.Logger + + once sync.Once + initErr error + installed bool + + mu sync.Mutex + pool map[string]*poolEntry + maxSize int + idleTTL time.Duration + + // 允许测试注入自定义 playwright / 安装函数。 + installFn func() error + runFn func() (*playwright.Playwright, error) +} + +type poolEntry struct { + cookieID string + browser playwright.Browser + context playwright.BrowserContext + lastUsed time.Time + userData string // 持久化目录(密码登录用),空表示非持久化 + persistent bool +} + +// NewManager 构造。logger 为 nil 用默认。 +func NewManager(logger *slog.Logger) *Manager { + if logger == nil { + logger = slog.Default() + } + return &Manager{ + logger: logger, + pool: make(map[string]*poolEntry), + maxSize: 3, + idleTTL: 5 * time.Minute, + installFn: func() error { + return playwright.Install(&playwright.RunOptions{ + Browsers: []string{"chromium"}, + Verbose: false, + }) + }, + runFn: func() (*playwright.Playwright, error) { + return playwright.Run() + }, + } +} + +// init 懒加载 playwright(首次调用时下载 driver + chromium)。 +func (m *Manager) init() error { + m.once.Do(func() { + if err := m.installFn(); err != nil { + m.initErr = fmt.Errorf("安装 playwright/chromium 失败(缺系统依赖时需手动执行 playwright install --with-deps): %w", err) + return + } + pw, err := m.runFn() + if err != nil { + m.initErr = fmt.Errorf("启动 playwright 失败: %w", err) + return + } + m.pw = pw + m.installed = true + m.logger.Info("playwright chromium 就绪") + }) + return m.initErr +} + +// Close 释放所有浏览器与 playwright。 +func (m *Manager) Close() error { + m.mu.Lock() + entries := make([]*poolEntry, 0, len(m.pool)) + for _, e := range m.pool { + entries = append(entries, e) + } + m.pool = make(map[string]*poolEntry) + m.mu.Unlock() + + for _, e := range entries { + closeEntry(e, m.logger) + } + if m.pw != nil { + return m.pw.Stop() + } + return nil +} + +// ping 暴露给 health 检查:playwright 是否就绪。 +func (m *Manager) ping(ctx context.Context) error { + if err := m.init(); err != nil { + return err + } + return nil +} + +// newPage 从池中取(或创建)一个 context,返回新 page + 释放函数。 +// 每次请求新建 page,避免并发导航冲突(与 browser_pool.get_browser 一致)。 +func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headless bool) (playwright.Page, func(), error) { + if err := m.init(); err != nil { + return nil, nil, err + } + entry, err := m.acquireEntry(cookieID, cookieStr, headless) + if err != nil { + return nil, nil, err + } + page, err := entry.context.NewPage() + if err != nil { + // context 损坏,丢弃重建一次。 + m.evict(cookieID) + entry, err = m.acquireEntry(cookieID, cookieStr, headless) + if err != nil { + return nil, nil, err + } + page, err = entry.context.NewPage() + if err != nil { + return nil, nil, fmt.Errorf("新建 page 失败: %w", err) + } + } + release := func() { + _ = page.Close() + m.touch(cookieID) + } + return page, release, nil +} + +func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) { + m.mu.Lock() + if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() { + e.lastUsed = time.Now() + m.mu.Unlock() + return e, nil + } + m.mu.Unlock() + + // 池满,淘汰最久未用。 + m.evictIfNeeded() + return m.createEntry(cookieID, cookieStr, headless) +} + +func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) { + browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(headless), + Args: chromiumLaunchArgs(), + }) + if err != nil { + return nil, fmt.Errorf("启动 chromium 失败: %w", err) + } + context, err := browser.NewContext(playwright.BrowserNewContextOptions{ + UserAgent: playwright.String(defaultUA), + Viewport: &playwright.Size{Width: defaultW, Height: defaultH}, + Locale: playwright.String(defaultLang), + TimezoneId: playwright.String(defaultTZ), + }) + if err != nil { + _ = browser.Close() + return nil, fmt.Errorf("创建 context 失败: %w", err) + } + if err := context.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil { + m.logger.Warn("注入 stealth 脚本失败", "err", err) + } + if cookieStr != "" { + if err := addCookieStr(context, cookieStr); err != nil { + m.logger.Warn("注入 cookie 失败", "err", err) + } + } + entry := &poolEntry{ + cookieID: cookieID, + browser: browser, + context: context, + lastUsed: time.Now(), + } + m.mu.Lock() + m.pool[cookieID] = entry + m.mu.Unlock() + return entry, nil +} + +func (m *Manager) touch(cookieID string) { + m.mu.Lock() + if e, ok := m.pool[cookieID]; ok { + e.lastUsed = time.Now() + } + m.mu.Unlock() +} + +func (m *Manager) evict(cookieID string) { + m.mu.Lock() + e, ok := m.pool[cookieID] + delete(m.pool, cookieID) + m.mu.Unlock() + if ok { + closeEntry(e, m.logger) + } +} + +func (m *Manager) evictIfNeeded() { + m.mu.Lock() + if len(m.pool) < m.maxSize { + m.mu.Unlock() + return + } + var oldest *poolEntry + var oldestID string + for id, e := range m.pool { + if oldest == nil || e.lastUsed.Before(oldest.lastUsed) { + oldest = e + oldestID = id + } + } + delete(m.pool, oldestID) + m.mu.Unlock() + if oldest != nil { + closeEntry(oldest, m.logger) + } +} + +// CleanupIdle 清理超过 idleTTL 未用的浏览器。 +func (m *Manager) CleanupIdle() { + now := time.Now() + m.mu.Lock() + var toClose []*poolEntry + for id, e := range m.pool { + if now.Sub(e.lastUsed) > m.idleTTL { + toClose = append(toClose, e) + delete(m.pool, id) + } + } + m.mu.Unlock() + for _, e := range toClose { + closeEntry(e, m.logger) + } +} + +func closeEntry(e *poolEntry, logger *slog.Logger) { + if e == nil { + return + } + if e.context != nil { + _ = e.context.Close() + } + if e.browser != nil { + _ = e.browser.Close() + } +} + +// addCookieStr 把 "k=v; k2=v2" 注入 context(domain .goofish.com)。 +func addCookieStr(ctx playwright.BrowserContext, cookieStr string) error { + cookies := parseCookieStrToPlaywright(cookieStr) + if len(cookies) == 0 { + return errors.New("cookie 为空或格式错误") + } + return ctx.AddCookies(cookies) +} diff --git a/internal/browser/orders.go b/internal/browser/orders.go new file mode 100644 index 0000000..f71823e --- /dev/null +++ b/internal/browser/orders.go @@ -0,0 +1,277 @@ +package browser + +import ( + "context" + "fmt" + "net/url" + "regexp" + "strings" + "sync" + "time" + + "github.com/playwright-community/playwright-go" + + "xianyu-go/internal/xianyu/mtop" +) + +const mtopOrderDetailURL = "mtop.idle.web.trade.order.detail" + +// OrderDetail 订单详情(对齐 engine.OrderDetail)。 +type OrderDetail struct { + OrderID string `json:"order_id"` + Quantity string `json:"quantity"` + SpecName string `json:"spec_name"` + SpecValue string `json:"spec_value"` + OrderStatus string `json:"order_status"` + Amount string `json:"amount"` + UpdatedCookies string `json:"-"` +} + +// orderStatusMap 移植自 order_fetcher_optimized._parse_api_response。纯映射,可单测。 +var orderStatusMap = map[int]string{ + 1: "processing", 2: "pending_ship", 3: "shipped", + 4: "completed", 7: "refunding", 8: "cancelled", + 9: "refunding", 10: "cancelled", 11: "completed", 12: "cancelled", +} + +// FetchOrderDetail 用浏览器抓取单个订单详情。 +// 移植自 utils/order_fetcher_optimized.py fetch_order_complete。 +func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cookieValue string, requireSpec ...bool) (*OrderDetail, error) { + needsSpec := len(requireSpec) > 0 && requireSpec[0] + // 优先调用稳定的 MTop 详情接口;页面自动化只作为规格字段的兼容兜底。 + if direct, directErr := (&mtop.Client{}).FetchOrderDetail(ctx, cookieValue, orderID); directErr == nil && direct != nil && direct.Amount != "" && + (!needsSpec || (direct.SpecName != "" && direct.SpecValue != "")) { + return &OrderDetail{ + OrderID: orderID, Quantity: direct.Quantity, SpecName: direct.SpecName, SpecValue: direct.SpecValue, + OrderStatus: direct.OrderStatus, Amount: direct.Amount, UpdatedCookies: direct.UpdatedCookies, + }, nil + } else if directErr != nil { + m.logger.Warn("MTop 订单详情获取失败,回退浏览器", "order_id", orderID, "err", directErr) + } + if err := m.init(); err != nil { + return nil, err + } + page, release, err := m.newPage(ctx, cookieID, cookieValue, true) + if err != nil { + return nil, err + } + defer release() + + var mu sync.Mutex + var apiBody map[string]any + var observedAPIs []string + + // 路由拦截:fetch mtop 订单详情 API 响应体。 + _ = page.Route("**/*", func(route playwright.Route) { + requestURL := route.Request().URL() + if parsed, parseErr := url.Parse(requestURL); parseErr == nil && strings.Contains(parsed.Host, "goofish.com") { + apiName := parsed.Query().Get("api") + if apiName == "" && strings.Contains(parsed.Path, "/h5/") { + parts := strings.Split(parsed.Path, "/") + if len(parts) > 2 { + apiName = parts[2] + } + } + if apiName != "" { + mu.Lock() + if len(observedAPIs) < 30 { + observedAPIs = append(observedAPIs, apiName) + } + mu.Unlock() + } + } + if strings.Contains(requestURL, mtopOrderDetailURL) { + resp, err := route.Fetch() + if err == nil { + var body map[string]any + if err := resp.JSON(&body); err == nil { + mu.Lock() + apiBody = body + mu.Unlock() + } + } + } + _ = route.Continue() + }) + + url := fmt.Sprintf("https://www.goofish.com/order-detail?orderId=%s&role=seller", orderID) + if _, err := page.Goto(url, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateNetworkidle, + Timeout: playwright.Float(30000), + }); err != nil { + m.logger.Warn("访问订单详情页超时", "err", err) + } + time.Sleep(2 * time.Second) + _, _ = page.Evaluate("() => window.scrollTo(0, document.body.scrollHeight)") + time.Sleep(500 * time.Millisecond) + _, _ = page.Evaluate("() => window.scrollTo(0, 0)") + time.Sleep(1 * time.Second) + + mu.Lock() + body := apiBody + mu.Unlock() + + od := &OrderDetail{OrderID: orderID} + + if body != nil { + if d, ok := body["data"].(map[string]any); ok { + parseAPIResponse(od, d) + } + } + + // DOM 补充(金额 / SKU)。 + parseDOMContent(page, od) + if od.Amount == "" { + title, _ := page.Title() + m.logger.Warn("订单详情未解析到实付金额", "order_id", orderID, "page_title", title, "page_url", page.URL(), "api_captured", body != nil, "observed_apis", observedAPIs) + } + return od, nil +} + +func parseAPIResponse(od *OrderDetail, data map[string]any) { + // 订单状态。 + if ut, ok := data["utArgs"].(map[string]any); ok { + if code, ok := ut["orderStatus"].(float64); ok { + if s, ok := orderStatusMap[int(code)]; ok { + od.OrderStatus = s + } + } + } + // 组件中找金额和规格。 + comps, _ := data["components"].([]any) + for _, c := range comps { + cm, ok := c.(map[string]any) + if !ok { + continue + } + if cm["render"] == "orderInfoVO" { + // 当前接口把 priceInfo 放在 component.data 下;兼容旧结构的顶层字段。 + componentData, _ := cm["data"].(map[string]any) + priceInfo, _ := componentData["priceInfo"].(map[string]any) + if priceInfo == nil { + priceInfo, _ = cm["priceInfo"].(map[string]any) + } + if priceInfo != nil { + amount, _ := priceInfo["amount"].(map[string]any) + if v, ok := amount["value"].(string); ok { + od.Amount = v + } + } + } + } +} + +var amountRE = regexp.MustCompile(`[\d.]+`) +var currencyAmountRE = regexp.MustCompile(`[¥¥]\s*([0-9]+(?:\.[0-9]{1,2})?)`) +var plainAmountRE = regexp.MustCompile(`^\s*([0-9]+(?:\.[0-9]{1,2})?)\s*$`) +var orderTimeRE = regexp.MustCompile(`\d{4}[-/]\d{2}[-/]\d{2}\s+\d{2}:\d{2}(?::\d{2})?`) + +func parseDOMContent(page playwright.Page, od *OrderDetail) { + // 金额。 + if od.Amount == "" { + if el, err := page.QuerySelector(`.boldNum--JgEOXfA3`); err == nil && el != nil { + if t, err := el.TextContent(); err == nil { + od.Amount = strings.TrimSpace(t) + } + } + } + if od.Amount == "" { + if raw, err := page.Evaluate(`() => document.body?.innerText || ''`); err == nil { + if pageText, ok := raw.(string); ok { + od.Amount = extractPaidAmountFromText(pageText) + } + } + } + + // SKU(规格+数量)。移植自 _parse_dom_content。 + if skuEls, err := page.QuerySelectorAll(`.sku--u_ddZval`); err == nil && len(skuEls) >= 1 { + t, _ := skuEls[0].TextContent() + parts := strings.SplitN(t, ":", 2) + if len(parts) == 2 { + od.SpecName = strings.TrimSpace(parts[0]) + od.SpecValue = strings.TrimSpace(parts[1]) + } + if len(skuEls) >= 2 { + q, _ := skuEls[1].TextContent() + od.Quantity = strings.TrimPrefix(strings.TrimSpace(q), "x") + } + } + if od.Quantity == "" { + od.Quantity = "1" + } +} + +func extractPaidAmountFromText(pageText string) string { + labels := []string{"实付款", "实付金额", "订单金额", "合计"} + rawLines := strings.Split(pageText, "\n") + lines := make([]string, 0, len(rawLines)) + for _, line := range rawLines { + if trimmed := strings.TrimSpace(line); trimmed != "" { + lines = append(lines, trimmed) + } + } + for i, line := range lines { + matchedLabel := false + for _, label := range labels { + if strings.Contains(line, label) { + matchedLabel = true + break + } + } + if !matchedLabel { + continue + } + end := i + 3 + if end > len(lines) { + end = len(lines) + } + for _, candidate := range lines[i:end] { + if match := currencyAmountRE.FindStringSubmatch(candidate); len(match) == 2 { + return match[1] + } + if candidate != line { + if match := plainAmountRE.FindStringSubmatch(candidate); len(match) == 2 { + return match[1] + } + } + } + } + return "" +} + +// BatchRefreshOrders 并发抓取多个订单详情(semaphore=5)。 +func (m *Manager) BatchRefreshOrders(ctx context.Context, orderIDs []string, cookieID, cookieValue string) (map[string]any, error) { + sem := make(chan struct{}, 5) + type result struct { + id string + od *OrderDetail + err error + } + results := make([]result, len(orderIDs)) + var wg sync.WaitGroup + for i, id := range orderIDs { + wg.Add(1) + go func(idx int, oid string) { + defer wg.Done() + sem <- struct{}{} + defer func() { <-sem }() + od, err := m.FetchOrderDetail(ctx, oid, cookieID, cookieValue) + results[idx] = result{id: oid, od: od, err: err} + }(i, id) + } + wg.Wait() + + orders := make([]map[string]any, 0, len(orderIDs)) + for _, r := range results { + if r.err != nil { + orders = append(orders, map[string]any{"order_id": r.id, "success": false, "error": r.err.Error()}) + continue + } + orders = append(orders, map[string]any{ + "order_id": r.od.OrderID, "success": true, + "quantity": r.od.Quantity, "spec_name": r.od.SpecName, "spec_value": r.od.SpecValue, + "order_status": r.od.OrderStatus, "amount": r.od.Amount, + }) + } + return map[string]any{"orders": orders}, nil +} diff --git a/internal/browser/orders_test.go b/internal/browser/orders_test.go new file mode 100644 index 0000000..99a6a8e --- /dev/null +++ b/internal/browser/orders_test.go @@ -0,0 +1,80 @@ +package browser + +import ( + "testing" +) + +func TestOrderStatusMap(t *testing.T) { + cases := []struct { + code int + expect string + }{ + {1, "processing"}, {2, "pending_ship"}, {3, "shipped"}, + {4, "completed"}, {7, "refunding"}, {8, "cancelled"}, + {9, "refunding"}, {10, "cancelled"}, {11, "completed"}, {12, "cancelled"}, + } + for _, c := range cases { + if s, ok := orderStatusMap[c.code]; !ok || s != c.expect { + t.Errorf("orderStatusMap[%d] = %q, want %q", c.code, s, c.expect) + } + } +} + +func TestParseWantCount(t *testing.T) { + cases := map[string]int{ + "3": 3, + "1.5万": 15000, + "2万": 20000, + "100": 100, + } + for in, want := range cases { + if got := parseWantCount(in); got != want { + t.Errorf("parseWantCount(%q) = %d, want %d", in, got, want) + } + } +} + +func TestParseAPIResponseStatusCode(t *testing.T) { + od := &OrderDetail{} + data := map[string]any{ + "utArgs": map[string]any{"orderStatus": float64(2)}, + } + parseAPIResponse(od, data) + if od.OrderStatus != "pending_ship" { + t.Errorf("got %q, want pending_ship", od.OrderStatus) + } +} + +func TestParseAPIResponseAmountFromComponentData(t *testing.T) { + od := &OrderDetail{} + data := map[string]any{ + "components": []any{ + map[string]any{ + "render": "orderInfoVO", + "data": map[string]any{ + "priceInfo": map[string]any{ + "amount": map[string]any{"value": "0.88"}, + }, + }, + }, + }, + } + parseAPIResponse(od, data) + if od.Amount != "0.88" { + t.Fatalf("Amount=%q want 0.88", od.Amount) + } +} + +func TestExtractPaidAmountFromText(t *testing.T) { + cases := map[string]string{ + "商品标价\n¥99.00\n实付款 ¥0.88\n交易成功": "0.88", + "订单信息\n实付金额\n¥12.50\n订单编号": "12.50", + "合计\n6.00\n其他信息": "6.00", + "商品价格\n¥19.90\n没有付款标签": "", + } + for input, want := range cases { + if got := extractPaidAmountFromText(input); got != want { + t.Errorf("extractPaidAmountFromText(%q)=%q want %q", input, got, want) + } + } +} diff --git a/internal/browser/passwordlogin.go b/internal/browser/passwordlogin.go new file mode 100644 index 0000000..c921c39 --- /dev/null +++ b/internal/browser/passwordlogin.go @@ -0,0 +1,180 @@ +package browser + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "time" + + "github.com/playwright-community/playwright-go" +) + +// loginFormSelectors 登录表单选择器,主页面和 iframe 中都要找。 +var loginIDSelectors = []string{ + "#fm-login-id", `input[name="fm-login-id"]`, + `input[placeholder*="手机号"]`, `input[placeholder*="邮箱"]`, + ".fm-login-id", +} +var loginPwdSelectors = []string{ + "#fm-login-password", `input[type="password"]`, +} +var loginBtnSelectors = []string{ + "button.password-login", `button[type="submit"]`, +} +var loginSuccessSelectors = []string{ + ".rc-virtual-list-holder-inner", // IM 页面侧边栏有子元素则已登录 +} + +// PasswordLogin 用账号密码通过浏览器登录闲鱼,返回完整 cookie map。 +// 移植自 xianyu_slider_stealth.login_with_password_playwright。 +// userDataDir:空字符串用临时目录,非空则持久化(跨次复用 session)。 +func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) { + if err := m.init(); err != nil { + return nil, err + } + + if userDataDir == "" { + userDataDir = filepath.Join("browser_data", "user_"+sanitize(cookieID)) + } + + bctx, err := m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{ + Headless: playwright.Bool(headless), + Args: chromiumLaunchArgs(), + UserAgent: playwright.String(defaultUA), + Viewport: &playwright.Size{Width: 1980, Height: 1024}, + Locale: playwright.String(defaultLang), + TimezoneId: playwright.String(defaultTZ), + }) + if err != nil { + return nil, fmt.Errorf("启动持久化浏览器失败: %w", err) + } + defer func() { _ = bctx.Close() }() + + if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil { + m.logger.Warn("注入 stealth 脚本失败", "err", err) + } + + page, err := bctx.NewPage() + if err != nil { + return nil, fmt.Errorf("新建 page 失败: %w", err) + } + + if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateNetworkidle, + Timeout: playwright.Float(60000), + }); err != nil { + m.logger.Warn("访问 goofish.com/im 超时", "err", err) + } + + // 检查是否已经登录。 + if checkLoginSuccess(page) { + m.logger.Info("密码登录:已有有效 session,无需重新登录", "cookieID", cookieID) + return extractPageCookies(page) + } + + // 在主页和所有 iframe 中找登录表单。 + idEl, pwdEl, submitEl := findLoginForm(page) + if idEl == nil { + return nil, fmt.Errorf("未找到登录表单,可能页面结构已变更") + } + + if err := idEl.Click(); err == nil { + _ = page.Fill(getCSSSelector(idEl, loginIDSelectors), account) + } + if err := pwdEl.Click(); err == nil { + _ = page.Fill(getCSSSelector(pwdEl, loginPwdSelectors), password) + } + // 同意协议复选框(若存在)。 + if cb, err := page.QuerySelector("#fm-agreement-checkbox"); err == nil && cb != nil { + if checked, _ := cb.GetAttribute("checked"); checked == "" { + _ = cb.Click() + } + } + if submitEl != nil { + _ = submitEl.Click() + } + time.Sleep(3 * time.Second) + + // 登录后可能出现滑块。 + content, _ := page.Content() + if strings.Contains(content, "nc-container") || strings.Contains(content, "scratch-captcha") { + scratch := isScratchCaptcha(content) + m.logger.Info("密码登录后出现滑块,自动处理") + if err := solveSlider(page, scratch, m.logger); err != nil { + m.logger.Warn("密码登录滑块处理失败", "err", err) + } + time.Sleep(2 * time.Second) + } + + if !checkLoginSuccess(page) { + // 采集错误信息。 + errMsg := "" + if el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil { + errMsg, _ = el.TextContent() + } + if errMsg == "" { + c, _ := page.Content() + for _, kw := range []string{"账密错误", "账号密码错误", "用户名或密码错误", "密码错误"} { + if strings.Contains(c, kw) { + errMsg = kw + break + } + } + } + if errMsg == "" { + errMsg = "登录失败" + } + return nil, fmt.Errorf("密码登录失败: %s", errMsg) + } + + m.logger.Info("密码登录成功", "cookieID", cookieID) + return extractPageCookies(page) +} + +func checkLoginSuccess(page playwright.Page) bool { + for _, sel := range loginSuccessSelectors { + el, err := page.QuerySelector(sel) + if err != nil || el == nil { + continue + } + // 子元素数 > 0 则已登录。 + count, err := page.Evaluate(`(sel) => { + const el = document.querySelector(sel); + return el ? el.children.length : 0; + }`, sel) + if err == nil { + if n, ok := count.(float64); ok && n > 0 { + return true + } + } + } + return false +} + +func findLoginForm(page playwright.Page) (idEl, pwdEl, submitEl playwright.ElementHandle) { + frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...) + for _, f := range frames { + id := queryFirst(f, loginIDSelectors) + if id == nil { + continue + } + pwd := queryFirst(f, loginPwdSelectors) + submit := queryFirst(f, loginBtnSelectors) + return id, pwd, submit + } + return nil, nil, nil +} + +// getCSSSelector 返回元素对应的第一个匹配选择器(用于 page.Fill)。 +func getCSSSelector(el playwright.ElementHandle, selectors []string) string { + if el == nil { + return selectors[0] + } + return selectors[0] // page.Fill 用首选器即可,元素已 Click +} + +func sanitize(s string) string { + r := strings.NewReplacer("/", "_", "\\", "_", ":", "_", " ", "_") + return r.Replace(s) +} diff --git a/internal/browser/qrrefresh.go b/internal/browser/qrrefresh.go new file mode 100644 index 0000000..11a6d15 --- /dev/null +++ b/internal/browser/qrrefresh.go @@ -0,0 +1,198 @@ +package browser + +import ( + "context" + "encoding/base64" + "fmt" + "strings" + "time" + + "github.com/playwright-community/playwright-go" + + "xianyu-go/internal/logsafe" +) + +// QRCookieRefresh 用扫码临时 cookie + 风控验证 URL,通过浏览器换取真实 cookie(含 unb)。 +// verificationURL 为空时跳过验证步骤(无风控场景)。 +func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error) { + if tmpCookies == "" { + return "", "", fmt.Errorf("扫码临时 cookie 为空") + } + if err := m.init(); err != nil { + return "", "", err + } + + m.logger.Info("开始用临时 cookie 换取真实 cookie", "tmp_cookie_count", len(parseCookieStr(tmpCookies))) + + // QR 刷新不复用账号池:一次性上下文,注入临时 cookie,访问后提取。 + browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{ + Headless: playwright.Bool(true), + Args: chromiumLaunchArgs(), + }) + if err != nil { + return "", "", fmt.Errorf("启动 chromium 失败: %w", err) + } + defer func() { _ = browser.Close() }() + + bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{ + UserAgent: playwright.String(defaultUA), + Viewport: &playwright.Size{Width: 400, Height: 400}, + Locale: playwright.String(defaultLang), + TimezoneId: playwright.String(defaultTZ), + }) + if err != nil { + return "", "", fmt.Errorf("创建 context 失败: %w", err) + } + defer func() { _ = bctx.Close() }() + + if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil { + m.logger.Warn("注入 stealth 脚本失败", "err", err) + } + if err := addCookieStr(bctx, tmpCookies); err != nil { + return "", "", fmt.Errorf("注入临时 cookie 失败: %w", err) + } + + page, err := bctx.NewPage() + if err != nil { + return "", "", fmt.Errorf("新建 page 失败: %w", err) + } + + if verificationURL != "" { + // 关键:Chromium 打开验证页面并持有该 session。 + // 用户在手机完成验证后,mini_login_check.htm 会自动 redirect 到 ivCheckLogin.htm。 + // Chromium 跟随这个 redirect,服务端会在此 session 里写入认证态。 + m.logger.Info("Chromium 打开验证等待页", "verification_url", logsafe.URL(verificationURL)) + if _, err := page.Goto(verificationURL, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateDomcontentloaded, + Timeout: playwright.Float(15000), + }); err != nil { + m.logger.Warn("打开验证页面异常", "err", err) + } + + // 等待用户完成手机验证,页面会 redirect 到 ivCheckLogin.htm(最多3分钟)。 + // 每2秒截图一次并通过 onScreenshot 回调发给前端,用户可直接看到验证页面。 + m.logger.Info("等待验证完成(监测页面 redirect + 截图推送)...") + deadline := time.Now().Add(3 * time.Minute) + for time.Now().Before(deadline) { + u := page.URL() + if strings.Contains(u, "ivCheckLogin") { + m.logger.Info("验证通过,页面已跳转", "url", logsafe.URL(u)) + break + } + // 截图并回调给前端。 + if onScreenshot != nil { + if img, err2 := page.Screenshot(); err2 == nil { + onScreenshot("data:image/png;base64," + base64.StdEncoding.EncodeToString(img)) + } + } + sleep(2 * time.Second) + } + if !strings.Contains(page.URL(), "ivCheckLogin") { + return "", "", fmt.Errorf("等待验证超时(3分钟),请重新扫码") + } + sleep(2 * time.Second) + } + + // 访问 /im 触发 unb 写入。 + if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateNetworkidle, + Timeout: playwright.Float(20000), + }); err != nil { + m.logger.Warn("访问 goofish.com/im 异常", "err", err) + } + m.logger.Info("goto /im 完成", "current_url", logsafe.URL(page.URL())) + + // reload 后再等网络空闲,确保 unb 写入。 + if _, err := page.Reload(playwright.PageReloadOptions{ + WaitUntil: playwright.WaitUntilStateNetworkidle, + Timeout: playwright.Float(15000), + }); err != nil { + m.logger.Warn("reload 异常", "err", err) + } + m.logger.Info("reload 完成", "current_url", logsafe.URL(page.URL())) + + // 轮询直到 unb 出现或超时(最长15秒)。 + var all []playwright.Cookie + deadline := time.Now().Add(15 * time.Second) + for time.Now().Before(deadline) { + var err2 error + all, err2 = bctx.Cookies() + if err2 == nil { + if m2 := cookiesToMap(all); m2["unb"] != "" { + m.logger.Info("轮询拿到 unb") + break + } + } + sleep(500 * time.Millisecond) + } + + if len(all) == 0 { + all, err = bctx.Cookies() + if err != nil { + return "", "", fmt.Errorf("提取 cookie 失败: %w", err) + } + } + cookieMap := cookiesToMap(all) + cookieStr := cookieMarshal(cookieMap) + unb = cookieMap["unb"] + + // 关键字段日志,便于排查。 + for _, k := range []string{"unb", "_m_h5_tk", "_m_h5_tk_enc", "cookie2", "t", "sgcookie", "cna"} { + if v, ok := cookieMap[k]; ok { + m.logger.Info("cookie字段", "name", k, "len", len(v)) + } else { + m.logger.Info("cookie字段缺失", "name", k) + } + } + m.logger.Info("提取 cookie 完成", "count", len(all), "has_unb", unb != "") + + if cookieStr == "" || unb == "" { + return "", "", fmt.Errorf("浏览器提取后仍未获取到 unb,可能验证未完成或临时 cookie 已失效") + } + return cookieStr, unb, nil +} + +// gotoWithFallback 访问 URL,超时降级(domcontentloaded→load→无等待)。 +func gotoWithFallback(page playwright.Page, url string) error { + to := func(ms float64) *float64 { return &ms } + if _, err := page.Goto(url, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateDomcontentloaded, + Timeout: to(15000), + }); err == nil { + return nil + } + if _, err := page.Goto(url, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateLoad, + Timeout: to(20000), + }); err == nil { + return nil + } + _, err := page.Goto(url, playwright.PageGotoOptions{Timeout: to(25000)}) + return err +} + +func reloadWithFallback(page playwright.Page) error { + to := func(ms float64) *float64 { return &ms } + if _, err := page.Reload(playwright.PageReloadOptions{ + WaitUntil: playwright.WaitUntilStateDomcontentloaded, + Timeout: to(12000), + }); err == nil { + return nil + } + _, err := page.Reload(playwright.PageReloadOptions{ + WaitUntil: playwright.WaitUntilStateLoad, + Timeout: to(15000), + }) + return err +} + +// sleep 可被测试替换。 +var sleep = time.Sleep + +func cookieNames(m map[string]string) []string { + names := make([]string, 0, len(m)) + for k := range m { + names = append(names, k) + } + return names +} diff --git a/internal/browser/search.go b/internal/browser/search.go new file mode 100644 index 0000000..132d61a --- /dev/null +++ b/internal/browser/search.go @@ -0,0 +1,216 @@ +package browser + +import ( + "context" + "encoding/json" + "fmt" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "github.com/playwright-community/playwright-go" +) + +const mtopSearchURL = "h5api.m.goofish.com/h5/mtop.taobao.idlemtopsearch.pc.search" + +// SearchItem 商品搜索结果。 +type SearchItem struct { + Title string `json:"title"` + Price string `json:"price"` + WantCount int `json:"want_count"` + Area string `json:"area"` + UserNick string `json:"user_nick"` + ItemURL string `json:"item_url"` + PicURL string `json:"pic_url"` + ItemID string `json:"item_id"` +} + +// SearchItems 搜索闲鱼商品,返回解析结果。 +// 移植自 utils/item_search.py search_items。 +func (m *Manager) SearchItems(ctx context.Context, keyword, cookieID, cookieValue string, page, pageSize int) (map[string]any, error) { + if err := m.init(); err != nil { + return nil, err + } + + pw, release, err := m.newPage(ctx, cookieID, cookieValue, true) + if err != nil { + return nil, err + } + defer release() + + var mu sync.Mutex + var responses []map[string]any + + pw.OnResponse(func(resp playwright.Response) { + if !strings.Contains(resp.URL(), mtopSearchURL) { + return + } + if resp.Status() != 200 { + return + } + var body map[string]any + if err := resp.JSON(&body); err == nil { + mu.Lock() + responses = append(responses, body) + mu.Unlock() + } + }) + + // 访问首页、注入 cookie、刷新。 + if _, err := pw.Goto("https://www.goofish.com", playwright.PageGotoOptions{Timeout: playwright.Float(30000)}); err != nil { + return nil, fmt.Errorf("访问 goofish.com 失败: %w", err) + } + if cookieValue != "" { + _ = addCookieStr(pw.Context(), cookieValue) + _, _ = pw.Reload() + time.Sleep(2 * time.Second) + } + + // 填搜索框并提交。 + _, _ = pw.WaitForSelector(`input[class*="search-input"]`, playwright.PageWaitForSelectorOptions{Timeout: playwright.Float(10000)}) + _ = pw.Fill(`input[class*="search-input"]`, keyword) + _ = pw.Click(`button[type="submit"]`) + + // 等待 mtop 响应。 + deadline := time.Now().Add(15 * time.Second) + for time.Now().Before(deadline) { + mu.Lock() + got := len(responses) + mu.Unlock() + if got > 0 { + break + } + time.Sleep(500 * time.Millisecond) + } + + // 可能出现滑块。 + content, _ := pw.Content() + if strings.Contains(content, "nc-container") || strings.Contains(content, "scratch-captcha") { + if err := solveSlider(pw, isScratchCaptcha(content), m.logger); err != nil { + m.logger.Warn("搜索滑块处理失败", "err", err) + } + // 重试搜索。 + _ = pw.Fill(`input[class*="search-input"]`, keyword) + _ = pw.Click(`button[type="submit"]`) + time.Sleep(3 * time.Second) + } + + mu.Lock() + defer mu.Unlock() + if len(responses) == 0 { + return map[string]any{"items": []any{}, "total": 0, "is_real_data": false}, nil + } + + items := parseSearchResponse(responses[0]) + return map[string]any{"items": items, "total": len(items), "is_real_data": true, "source": "browser"}, nil +} + +// parseSearchResponse 解析 mtop 搜索响应(移植自 _parse_real_item)。 +func parseSearchResponse(body map[string]any) []SearchItem { + data, _ := body["data"].(map[string]any) + list, _ := data["resultList"].([]any) + var items []SearchItem + for _, raw := range list { + item := parseSearchItem(raw) + if item != nil { + items = append(items, *item) + } + } + return items +} + +var wantRE = regexp.MustCompile(`(\d+(?:\.\d+)?(?:万)?)\s*人想要`) + +func parseSearchItem(raw any) *SearchItem { + r, ok := raw.(map[string]any) + if !ok { + return nil + } + d, _ := r["data"].(map[string]any) + if d == nil { + return nil + } + itemM, _ := d["item"].(map[string]any) + if itemM == nil { + return nil + } + main, _ := itemM["main"].(map[string]any) + if main == nil { + return nil + } + exContent, _ := main["exContent"].(map[string]any) + clickParam, _ := main["clickParam"].(map[string]any) + args, _ := clickParam["args"].(map[string]any) + + title, _ := exContent["title"].(string) + area, _ := exContent["area"].(string) + userNick, _ := exContent["userNickName"].(string) + picURL, _ := exContent["picUrl"].(string) + targetURL, _ := exContent["targetUrl"].(string) + itemID, _ := args["content"].(string) + + // 价格:取 priceList 中的文字拼接。 + price := "" + if pl, ok := exContent["priceList"].([]any); ok { + var parts []string + for _, p := range pl { + if pm, ok := p.(map[string]any); ok { + if t, ok := pm["text"].(string); ok { + parts = append(parts, t) + } + } + } + price = strings.Join(parts, "") + price = strings.TrimPrefix(price, "当前价") + } + + // 想要数。 + wantCount := 0 + if tags, ok := exContent["fishTags"].([]any); ok { + for _, t := range tags { + if s, ok := t.(string); ok { + if m := wantRE.FindStringSubmatch(s); len(m) > 1 { + wantCount = parseWantCount(m[1]) + } + } + } + } + + itemURL := strings.ReplaceAll(targetURL, "fleamarket://", "https://www.goofish.com/") + + return &SearchItem{ + Title: title, + Price: price, + WantCount: wantCount, + Area: area, + UserNick: userNick, + PicURL: picURL, + ItemURL: itemURL, + ItemID: itemID, + } +} + +func parseWantCount(s string) int { + if strings.HasSuffix(s, "万") { + f, err := strconv.ParseFloat(strings.TrimSuffix(s, "万"), 64) + if err == nil { + return int(f * 10000) + } + } + n, _ := strconv.Atoi(s) + return n +} + +// marshalSearchItems 供 HTTP handler 序列化。 +func marshalSearchItems(items []SearchItem) []map[string]any { + result := make([]map[string]any, 0, len(items)) + for _, it := range items { + b, _ := json.Marshal(it) + var m map[string]any + _ = json.Unmarshal(b, &m) + result = append(result, m) + } + return result +} diff --git a/internal/browser/slider.go b/internal/browser/slider.go new file mode 100644 index 0000000..998d151 --- /dev/null +++ b/internal/browser/slider.go @@ -0,0 +1,245 @@ +package browser + +import ( + "context" + "fmt" + "math" + "strings" + "time" + + "github.com/playwright-community/playwright-go" +) + +// sliderSelectors 按优先级排列的滑块相关选择器(移植自 xianyu_slider_stealth.py)。 +var sliderButtonSelectors = []string{ + "#nc_1_n1z", ".nc_iconfont", ".btn_slide", + "#scratch-captcha-btn", ".scratch-captcha-slider .button", +} +var sliderTrackSelectors = []string{ + "#nc_1_n1t", ".nc_scale", ".nc_1_n1t", +} +var sliderContainerSelectors = []string{ + "#nc_1_n1z", "#baxia-dialog-content", ".nc-container", ".nc_wrapper", + "#nocaptcha", ".scratch-captcha-container", +} +var sliderRetrySelectors = []string{ + ".nc-lang-cnt", "#nc_1_n1z", +} + +// trajectoryPoint 轨迹中的单个采样点。 +type trajectoryPoint struct { + x float64 + y float64 + delay time.Duration +} + +// generateTrajectory 生成仿人类滑动轨迹(移植自 _generate_physics_trajectory)。 +// 过冲 100-110%,15-25 步,progress^1.5 加速曲线。纯数学,可单测。 +func generateTrajectory(distance float64) []trajectoryPoint { + overshoot := distance * (1.0 + 0.1*float64(rng.Intn(11))/10.0) // 100-110% + steps := 15 + rng.Intn(11) // 15-25 + baseDelay := 3.0 + float64(rng.Intn(6)) // 3-8 ms + + pts := make([]trajectoryPoint, steps) + for i := 0; i < steps; i++ { + progress := float64(i+1) / float64(steps) + x := overshoot * math.Pow(progress, 1.5) + y := float64(rng.Intn(3)) // 0-2 px + d := time.Duration((baseDelay*(0.9+0.2*float64(rng.Intn(11))/10.0))*float64(time.Millisecond)) + pts[i] = trajectoryPoint{x: x, y: y, delay: d} + } + return pts +} + +// isScratchCaptcha 判断是否为刮刮乐验证码(只滑 25-35%)。 +func isScratchCaptcha(content string) bool { + return strings.Contains(content, "scratch-captcha") || + strings.Contains(content, "scratch-captcha-btn") || + strings.Contains(content, "scratch-captcha-slider") +} + +// SliderVerify 访问风控验证 URL,自动过滑块,返回更新后的 cookie map(含 x5sec)。 +// 移植自 xianyu_slider_stealth.py run() + solve_slider()。 +func (m *Manager) SliderVerify(ctx context.Context, url, cookieID string, headless bool) (map[string]string, error) { + if err := m.init(); err != nil { + return nil, err + } + page, release, err := m.newPage(ctx, cookieID, "", headless) + if err != nil { + return nil, err + } + defer release() + + if _, err := page.Goto(url, playwright.PageGotoOptions{ + WaitUntil: playwright.WaitUntilStateDomcontentloaded, + Timeout: playwright.Float(30000), + }); err != nil { + return nil, fmt.Errorf("访问验证 URL 失败: %w", err) + } + time.Sleep(300 + time.Duration(rng.Intn(500))*time.Millisecond) + + content, _ := page.Content() + if !strings.Contains(content, "验证") && !strings.Contains(content, "captcha") && !strings.Contains(content, "slider") { + // 页面不含验证码,直接提取 cookie。 + m.logger.Info("页面无验证码,直接提取 cookie") + return extractPageCookies(page) + } + + scratch := isScratchCaptcha(content) + if err := solveSlider(page, scratch, m.logger); err != nil { + return nil, fmt.Errorf("滑块验证失败: %w", err) + } + + time.Sleep(1 * time.Second) + return extractPageCookies(page) +} + +// solveSlider 在 page 上求解滑块,最多重试 3 次。 +func solveSlider(page playwright.Page, scratch bool, logger interface { + Info(string, ...any) + Warn(string, ...any) + Error(string, ...any) +}) error { + for attempt := 0; attempt < 3; attempt++ { + btn, track, _, err := findSliderElements(page) + if err != nil { + logger.Warn("未找到滑块元素", "attempt", attempt, "err", err) + time.Sleep(500 * time.Millisecond) + continue + } + + dist, err := calculateSlideDistance(btn, track, scratch) + if err != nil { + logger.Warn("计算滑块距离失败", "err", err) + dist = 200 // 降级默认值 + } + + if err := simulateSlide(page, btn, dist); err != nil { + logger.Warn("模拟滑动失败", "err", err) + continue + } + time.Sleep(800 * time.Millisecond) + + if checkSliderSuccess(page) { + logger.Info("滑块验证成功", "attempt", attempt) + return nil + } + // 失败后尝试点重试按钮。 + clickRetry(page) + time.Sleep(500 * time.Millisecond) + } + return fmt.Errorf("滑块验证 3 次均失败") +} + +// findSliderElements 在 page 和所有 iframe 中找到按钮与轨道元素。 +func findSliderElements(page playwright.Page) (btn, track playwright.ElementHandle, frame playwright.Frame, err error) { + frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...) + for _, f := range frames { + b := queryFirst(f, sliderButtonSelectors) + if b == nil { + continue + } + t := queryFirst(f, sliderTrackSelectors) + return b, t, f, nil + } + return nil, nil, nil, fmt.Errorf("未找到滑块元素") +} + +func queryFirst(f playwright.Frame, selectors []string) playwright.ElementHandle { + for _, sel := range selectors { + el, err := f.QuerySelector(sel) + if err == nil && el != nil { + return el + } + } + return nil +} + +// calculateSlideDistance 计算需要滑动的像素距离。 +func calculateSlideDistance(btn, track playwright.ElementHandle, scratch bool) (float64, error) { + var dist float64 + if track != nil { + tb, err := track.BoundingBox() + if err == nil && tb != nil { + bb, err2 := btn.BoundingBox() + if err2 == nil && bb != nil { + dist = tb.Width - bb.Width + float64(rng.Intn(2)) - 0.5 + } + } + } + if dist <= 0 { + dist = 220 + float64(rng.Intn(40)) + } + if scratch { + dist *= 0.25 + float64(rng.Intn(11))*0.01 // 25-35% + } + return dist, nil +} + +// simulateSlide 模拟人类滑动(移植自 simulate_slide)。 +func simulateSlide(page playwright.Page, btn playwright.ElementHandle, distance float64) error { + bb, err := btn.BoundingBox() + if err != nil || bb == nil { + return fmt.Errorf("无法获取按钮位置") + } + startX := bb.X + bb.Width/2 + startY := bb.Y + bb.Height/2 + mouse := page.Mouse() + + // 移到按钮旁边再到中心,模拟自然接近。 + _ = mouse.Move(startX-float64(10+rng.Intn(20)), startY+float64(rng.Intn(31)-15), + playwright.MouseMoveOptions{Steps: playwright.Int(3 + rng.Intn(3))}) + time.Sleep(100*time.Millisecond + time.Duration(rng.Intn(200))*time.Millisecond) + _ = mouse.Move(startX, startY, playwright.MouseMoveOptions{Steps: playwright.Int(2)}) + time.Sleep(100*time.Millisecond + time.Duration(rng.Intn(200))*time.Millisecond) + + if err := mouse.Down(); err != nil { + return err + } + + pts := generateTrajectory(distance) + for _, pt := range pts { + _ = mouse.Move(startX+pt.x, startY+pt.y, playwright.MouseMoveOptions{Steps: playwright.Int(1)}) + time.Sleep(pt.delay) + } + + return mouse.Up() +} + +// checkSliderSuccess 检查验证是否成功(nc-container 消失或 frame 断开)。 +func checkSliderSuccess(page playwright.Page) bool { + frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...) + for _, f := range frames { + el, err := f.QuerySelector(".nc-container") + if err != nil || el == nil { + continue + } + vis, err := el.IsVisible() + if err != nil || !vis { + return true + } + } + return true // 找不到容器也视为成功 +} + +func clickRetry(page playwright.Page) { + frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...) + for _, f := range frames { + for _, sel := range sliderRetrySelectors { + el, err := f.QuerySelector(sel) + if err == nil && el != nil { + _ = el.Click() + return + } + } + } +} + +// extractPageCookies 从 page 的 context 提取所有 cookie 返回 map。 +func extractPageCookies(page playwright.Page) (map[string]string, error) { + all, err := page.Context().Cookies() + if err != nil { + return nil, err + } + return cookiesToMap(all), nil +} diff --git a/internal/browser/slider_test.go b/internal/browser/slider_test.go new file mode 100644 index 0000000..b5916e1 --- /dev/null +++ b/internal/browser/slider_test.go @@ -0,0 +1,58 @@ +package browser + +import ( + "math" + "testing" +) + +func TestGenerateTrajectoryShape(t *testing.T) { + pts := generateTrajectory(200) + if len(pts) < 15 || len(pts) > 25 { + t.Fatalf("steps 应在 15-25,got %d", len(pts)) + } + // 最终 x 应在 distance*1.0 ~ distance*1.1 附近(最后一点在过冲范围内)。 + last := pts[len(pts)-1] + if last.x < 190 || last.x > 240 { + t.Fatalf("末端 x 应约等于 distance*1.05,got %.1f", last.x) + } + // x 应单调不减(加速曲线)。 + for i := 1; i < len(pts); i++ { + if pts[i].x < pts[i-1].x-1 { + t.Fatalf("轨迹 x 不单调: pts[%d]=%.1f < pts[%d]=%.1f", i, pts[i].x, i-1, pts[i-1].x) + } + } +} + +func TestGenerateTrajectoryDelay(t *testing.T) { + pts := generateTrajectory(150) + for i, pt := range pts { + if pt.delay < 2*1e6 || pt.delay > 15*1e6 { // 2ms-15ms in nanoseconds + t.Fatalf("delay[%d]=%v 超出合理范围", i, pt.delay) + } + } +} + +func TestIsScratchCaptcha(t *testing.T) { + if !isScratchCaptcha("
") { + t.Fatal("应识别 scratch-captcha-btn") + } + if !isScratchCaptcha("scratch-captcha-slider") { + t.Fatal("应识别 scratch-captcha-slider") + } + if isScratchCaptcha("
") { + t.Fatal("普通滑块不应识别为刮刮乐") + } +} + +func TestTrajectoryPhysics(t *testing.T) { + // progress^1.5 曲线:中间步进应比线性大。 + pts := generateTrajectory(100) + // 前半段增量应小于后半段增量(加速)。 + half := len(pts) / 2 + frontIncrement := pts[half-1].x - pts[0].x + backIncrement := pts[len(pts)-1].x - pts[half].x + // 允许误差:不严格要求加速,但增量应合理。 + if math.IsNaN(frontIncrement) || math.IsNaN(backIncrement) { + t.Fatal("轨迹 x 为 NaN") + } +} diff --git a/internal/browser/stealth.go b/internal/browser/stealth.go new file mode 100644 index 0000000..2a11946 --- /dev/null +++ b/internal/browser/stealth.go @@ -0,0 +1,299 @@ +package browser + +// stealthTemplate 是从 utils/xianyu_slider_stealth.py _get_stealth_script 原样移植的 +// 浏览器侧反检测 JS。Python 用 f-string 插入随机值,这里用 {{占位符}},由 +// stealthScript() 在 Go 侧生成随机值后替换。JS 本身未改动。 +const stealthTemplate = ` + // 隐藏webdriver属性 + Object.defineProperty(navigator, 'webdriver', { + get: () => undefined, + }); + + // 隐藏自动化相关属性 + delete navigator.__proto__.webdriver; + delete window.navigator.webdriver; + delete window.navigator.__proto__.webdriver; + + // 模拟真实浏览器环境 + window.chrome = { + runtime: {}, + loadTimes: function() {}, + csi: function() {}, + app: {} + }; + + // 覆盖plugins - 随机化 + const pluginCount = {{PLUGIN_COUNT}}; + Object.defineProperty(navigator, 'plugins', { + get: () => Array.from({length: pluginCount}, (_, i) => ({ + name: 'Plugin' + i, + description: 'Plugin ' + i + })), + }); + + // 覆盖languages + Object.defineProperty(navigator, 'languages', { + get: () => ['{{LOCALE}}', 'zh', 'en'], + }); + + // 模拟真实的屏幕信息 + Object.defineProperty(screen, 'availWidth', { get: () => {{VW}} }); + Object.defineProperty(screen, 'availHeight', { get: () => {{VH}} - 40 }); + Object.defineProperty(screen, 'width', { get: () => {{VW}} }); + Object.defineProperty(screen, 'height', { get: () => {{VH}} }); + + // 隐藏自动化检测 - 随机化硬件信息 + Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => {{HW_CORES}} }); + Object.defineProperty(navigator, 'deviceMemory', { get: () => {{MEM}} }); + + // 模拟真实的时区 + Object.defineProperty(Intl.DateTimeFormat.prototype, 'resolvedOptions', { + value: function() { + return { timeZone: '{{TZ}}' }; + } + }); + + // 隐藏自动化痕迹 + delete window.cdc_adoQpoasnfa76pfcZLmcfl_Array; + delete window.cdc_adoQpoasnfa76pfcZLmcfl_Promise; + delete window.cdc_adoQpoasnfa76pfcZLmcfl_Symbol; + + // 模拟有头模式的特征 + Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 0 }); + Object.defineProperty(navigator, 'platform', { get: () => 'Win32' }); + Object.defineProperty(navigator, 'vendor', { get: () => 'Google Inc.' }); + Object.defineProperty(navigator, 'vendorSub', { get: () => '' }); + Object.defineProperty(navigator, 'productSub', { get: () => '20030107' }); + + // 模拟真实的连接信息 + Object.defineProperty(navigator, 'connection', { + get: () => ({ + effectiveType: "{{EFF_TYPE}}", + rtt: {{RTT}}, + downlink: {{DOWNLINK}} + }) + }); + + // 隐藏无头模式特征 + Object.defineProperty(navigator, 'headless', { get: () => undefined }); + Object.defineProperty(window, 'outerHeight', { get: () => {{VH}} }); + Object.defineProperty(window, 'outerWidth', { get: () => {{VW}} }); + + // 模拟真实的媒体设备 + Object.defineProperty(navigator, 'mediaDevices', { + get: () => ({ + enumerateDevices: () => Promise.resolve([]) + }), + }); + + // 隐藏自动化检测特征 + Object.defineProperty(navigator, '__webdriver_script_fn', { get: () => undefined }); + Object.defineProperty(navigator, '__webdriver_evaluate', { get: () => undefined }); + Object.defineProperty(navigator, '__webdriver_unwrapped', { get: () => undefined }); + Object.defineProperty(navigator, '__fxdriver_evaluate', { get: () => undefined }); + Object.defineProperty(navigator, '__driver_evaluate', { get: () => undefined }); + Object.defineProperty(navigator, '__webdriver_script_func', { get: () => undefined }); + + // 隐藏Playwright特定的对象 + delete window.playwright; + delete window.__playwright; + delete window.__pw_manual; + delete window.__pw_original; + + // 模拟真实的用户代理 + Object.defineProperty(navigator, 'userAgent', { + get: () => '{{UA}}' + }); + + // 隐藏自动化相关的全局变量 + delete window.webdriver; + delete window.__webdriver_script_fn; + delete window.__webdriver_evaluate; + delete window.__webdriver_unwrapped; + delete window.__fxdriver_evaluate; + delete window.__driver_evaluate; + delete window.__webdriver_script_func; + delete window._selenium; + delete window._phantom; + delete window.callPhantom; + delete window.phantom; + delete window.Buffer; + delete window.emit; + delete window.spawn; + + // Canvas指纹随机化 + const originalToDataURL = HTMLCanvasElement.prototype.toDataURL; + HTMLCanvasElement.prototype.toDataURL = function() { + const context = this.getContext('2d'); + if (context) { + const imageData = context.getImageData(0, 0, this.width, this.height); + const data = imageData.data; + for (let i = 0; i < data.length; i += 4) { + if (Math.random() < 0.001) { + data[i] = Math.floor(Math.random() * 256); + } + } + context.putImageData(imageData, 0, 0); + } + return originalToDataURL.apply(this, arguments); + }; + + // 音频指纹随机化 + const originalGetChannelData = AudioBuffer.prototype.getChannelData; + AudioBuffer.prototype.getChannelData = function(channel) { + const data = originalGetChannelData.call(this, channel); + for (let i = 0; i < data.length; i += 1000) { + if (Math.random() < 0.01) { + data[i] += Math.random() * 0.0001; + } + } + return data; + }; + + // WebGL指纹随机化 + const originalGetParameter = WebGLRenderingContext.prototype.getParameter; + WebGLRenderingContext.prototype.getParameter = function(parameter) { + if (parameter === 37445) { // UNMASKED_VENDOR_WEBGL + return 'Intel Inc.'; + } + if (parameter === 37446) { // UNMASKED_RENDERER_WEBGL + return 'Intel Iris OpenGL Engine'; + } + return originalGetParameter.call(this, parameter); + }; + + // 模拟真实的鼠标事件 + const originalAddEventListener = EventTarget.prototype.addEventListener; + EventTarget.prototype.addEventListener = function(type, listener, options) { + if (type === 'mousedown' || type === 'mouseup' || type === 'mousemove') { + const originalListener = listener; + listener = function(event) { + setTimeout(() => originalListener.call(this, event), Math.random() * 10); + }; + } + return originalAddEventListener.call(this, type, listener, options); + }; + + // 随机化字体检测 + Object.defineProperty(document, 'fonts', { + get: () => ({ + ready: Promise.resolve(), + check: () => true, + load: () => Promise.resolve([]) + }) + }); + + // 增强鼠标移动轨迹记录 + let mouseMovements = []; + let lastMouseTime = Date.now(); + document.addEventListener('mousemove', function(e) { + const now = Date.now(); + const timeDiff = now - lastMouseTime; + mouseMovements.push({ + x: e.clientX, + y: e.clientY, + time: now, + timeDiff: timeDiff + }); + lastMouseTime = now; + if (mouseMovements.length > 100) { + mouseMovements.shift(); + } + }, true); + + // 模拟真实的电池API + if (navigator.getBattery) { + const originalGetBattery = navigator.getBattery; + navigator.getBattery = async function() { + const battery = await originalGetBattery.call(navigator); + Object.defineProperty(battery, 'charging', { get: () => {{BATT_CHARGE}} }); + Object.defineProperty(battery, 'level', { get: () => {{BATT_LEVEL}} }); + return battery; + }; + } + + // 伪装鼠标移动加速度(反检测关键) + let velocityProfile = []; + window.addEventListener('mousemove', function(e) { + const now = performance.now(); + velocityProfile.push({ x: e.clientX, y: e.clientY, t: now }); + if (velocityProfile.length > 50) velocityProfile.shift(); + }, true); + + // 伪装Permission API + const originalQuery = Permissions.prototype.query; + Permissions.prototype.query = function(parameters) { + if (parameters.name === 'notifications') { + return Promise.resolve({ state: 'denied' }); + } + return originalQuery.apply(this, arguments); + }; + + // 伪装Performance API + const originalNow = Performance.prototype.now; + Performance.prototype.now = function() { + return originalNow.call(this) + Math.random() * 0.1; + }; + + // 伪装RTCPeerConnection(WebRTC指纹) + if (window.RTCPeerConnection) { + const originalRTC = window.RTCPeerConnection; + window.RTCPeerConnection = function(...args) { + const pc = new originalRTC(...args); + const originalCreateOffer = pc.createOffer; + pc.createOffer = function(...args) { + return originalCreateOffer.apply(this, args).then(offer => { + offer.sdp = offer.sdp.replace(/a=fingerprint:.*\r\n/g, + 'a=fingerprint:sha-256 ' + Array.from({length:64}, ()=>Math.floor(Math.random()*16).toString(16)).join('') + '\r\n'); + return offer; + }); + }; + return pc; + }; + } + + // 🔑 关键优化:隐藏CDP运行时特征 + Object.defineProperty(navigator, 'webdriver', { + get: () => undefined + }); + + // 🔑 隐藏自动化控制特征 + window.navigator.chrome = { + runtime: {}, + loadTimes: function() {}, + csi: function() {}, + app: {} + }; + + // 🔑 隐藏Playwright特征 + delete window.__playwright; + delete window.__pw_manual; + delete window.__PW_inspect; + + // 🔑 伪装chrome对象(防止检测headless) + if (!window.chrome) { + window.chrome = {}; + } + window.chrome.runtime = { + id: undefined, + sendMessage: function() {}, + connect: function() {} + }; + + // 🔑 伪装Permissions API + const originalQuery2 = window.navigator.permissions.query; + window.navigator.permissions.query = (parameters) => ( + parameters.name === 'notifications' ? + Promise.resolve({ state: Notification.permission }) : + originalQuery2(parameters) + ); + + // 🔑 覆盖Function.prototype.toString以隐藏代理 + const oldToString = Function.prototype.toString; + Function.prototype.toString = function() { + if (this === navigator.permissions.query) { + return 'function query() { [native code] }'; + } + return oldToString.call(this); + }; +` diff --git a/internal/db/ai_reply.go b/internal/db/ai_reply.go new file mode 100644 index 0000000..29d4677 --- /dev/null +++ b/internal/db/ai_reply.go @@ -0,0 +1,52 @@ +package db + +import ( + "context" + "database/sql" + "errors" +) + +// AIReplySettings 对应 ai_reply_settings 表。 +type AIReplySettings struct { + CookieID string `json:"cookie_id"` + AIEnabled bool `json:"ai_enabled"` + ModelName string `json:"model_name"` + APIKey string `json:"api_key"` + BaseURL string `json:"base_url"` + MaxDiscountPercent int `json:"max_discount_percent"` + MaxDiscountAmount int `json:"max_discount_amount"` + MaxBargainRounds int `json:"max_bargain_rounds"` + CustomPrompts string `json:"custom_prompts"` +} + +// AIReply 操作。 +type AIReply struct{ DB *sql.DB } + +// Get 取某账号 AI 回复配置。 +func (a *AIReply) Get(ctx context.Context, cookieID string) (*AIReplySettings, error) { + var s AIReplySettings + var enabled int + var apiKey, customPrompts sql.NullString + err := a.DB.QueryRowContext(ctx, + `SELECT cookie_id, ai_enabled, COALESCE(model_name, ''), COALESCE(api_key, ''), COALESCE(base_url, ''), + max_discount_percent, max_discount_amount, max_bargain_rounds, custom_prompts + FROM ai_reply_settings WHERE cookie_id=?`, cookieID).Scan( + &s.CookieID, &enabled, &s.ModelName, &apiKey, &s.BaseURL, + &s.MaxDiscountPercent, &s.MaxDiscountAmount, &s.MaxBargainRounds, &customPrompts) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + s.AIEnabled = enabled != 0 + s.APIKey = apiKey.String + s.CustomPrompts = customPrompts.String + if s.ModelName == "" { + s.ModelName = "qwen-plus" + } + if s.BaseURL == "" { + s.BaseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1" + } + return &s, nil +} diff --git a/internal/db/cookies.go b/internal/db/cookies.go new file mode 100644 index 0000000..32daf25 --- /dev/null +++ b/internal/db/cookies.go @@ -0,0 +1,173 @@ +package db + +import ( + "context" + "database/sql" + "errors" + "fmt" +) + +// Cookies 闲鱼账号(cookie)相关操作。 +type Cookies struct { + DB *sql.DB +} + +// Save 保存/更新 cookie。user_id 为 0 时:复用现有记录的 user_id,若无则报错 +// (对应 Python 端"系统未初始化不应兜底为 1"的安全修正)。 +func (c *Cookies) Save(ctx context.Context, cookieID, cookieValue string, userID int64) error { + if userID == 0 { + var existing int64 + err := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&existing) + if err == nil { + userID = existing + } else if errors.Is(err, sql.ErrNoRows) { + return errors.New("系统未初始化:admin 用户不存在,请先执行 init-admin 初始化管理员") + } else { + return fmt.Errorf("查询 cookie user_id: %w", err) + } + } + _, err := c.DB.ExecContext(ctx, + `INSERT INTO cookies (id, value, user_id, updated_at) + VALUES (?, ?, ?, CURRENT_TIMESTAMP) + ON CONFLICT(id) DO UPDATE SET + value=excluded.value, + user_id=excluded.user_id, + updated_at=CURRENT_TIMESTAMP`, + cookieID, cookieValue, userID) + return err +} + +// Delete 删除 cookie 及其关联关键字(级联由外键处理,keywords 显式删以兼容未开外键的库)。 +func (c *Cookies) Delete(ctx context.Context, cookieID string) error { + tx, err := c.DB.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `DELETE FROM keywords WHERE cookie_id=?`, cookieID); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM cookies WHERE id=?`, cookieID); err != nil { + return err + } + return tx.Commit() +} + +// GetValue 取 cookie 明文值。不存在返回 ErrNotFound。 +func (c *Cookies) GetValue(ctx context.Context, cookieID string) (string, error) { + var v string + err := c.DB.QueryRowContext(ctx, `SELECT value FROM cookies WHERE id=?`, cookieID).Scan(&v) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return "", ErrNotFound + } + return "", err + } + return v, nil +} + +// AllForUser 取某用户的所有 cookie(id→value)。userID 为 0 时取全部(管理员视图)。 +func (c *Cookies) AllForUser(ctx context.Context, userID int64) (map[string]string, error) { + var rows *sql.Rows + var err error + if userID == 0 { + rows, err = c.DB.QueryContext(ctx, `SELECT id, value FROM cookies`) + } else { + rows, err = c.DB.QueryContext(ctx, `SELECT id, value FROM cookies WHERE user_id=?`, userID) + } + if err != nil { + return nil, err + } + defer rows.Close() + m := make(map[string]string) + for rows.Next() { + var id, v string + if err := rows.Scan(&id, &v); err != nil { + return nil, err + } + m[id] = v + } + return m, rows.Err() +} + +// GetDetails 取账号完整详情。不存在返回 ErrNotFound。 +func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetail, error) { + var d CookieDetail + var autoConfirm, showBrowser int + var pauseDuration sql.NullInt64 + err := c.DB.QueryRowContext(ctx, + `SELECT id, value, user_id, auto_confirm, remark, pause_duration, username, password, + show_browser, COALESCE(nickname,''), COALESCE(avatar_url,''), created_at + FROM cookies WHERE id=?`, cookieID).Scan( + &d.ID, &d.Value, &d.UserID, &autoConfirm, &d.Remark, &pauseDuration, + &d.Username, &d.Password, &showBrowser, &d.Nickname, &d.AvatarURL, &d.CreatedAt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + d.AutoConfirm = autoConfirm != 0 + d.ShowBrowser = showBrowser != 0 + d.PauseDuration = 10 + if pauseDuration.Valid { + // 0 是有效值(表示不暂停),与 Python 端一致。 + d.PauseDuration = int(pauseDuration.Int64) + } + return &d, nil +} + +// UpdateProfile 保存账号展示资料。 +func (c *Cookies) UpdateProfile(ctx context.Context, cookieID, nickname, avatarURL string) error { + _, err := c.DB.ExecContext(ctx, + `UPDATE cookies + SET nickname=?, avatar_url=?, updated_at=CURRENT_TIMESTAMP + WHERE id=?`, + nickname, avatarURL, cookieID) + return err +} + +// GetPauseDuration 取自动回复暂停时长(分钟)。未找到或 NULL 返回 10。 +func (c *Cookies) GetPauseDuration(ctx context.Context, cookieID string) int { + var pd sql.NullInt64 + err := c.DB.QueryRowContext(ctx, `SELECT pause_duration FROM cookies WHERE id=?`, cookieID).Scan(&pd) + if err != nil || !pd.Valid { + return 10 + } + return int(pd.Int64) // 0 有效 +} + +// GetAutoConfirm 读取账号是否自动将订单确认成已发货状态。 +func (c *Cookies) GetAutoConfirm(ctx context.Context, cookieID string) (bool, error) { + var enabled int + err := c.DB.QueryRowContext(ctx, `SELECT auto_confirm FROM cookies WHERE id=?`, cookieID).Scan(&enabled) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return false, ErrNotFound + } + return false, err + } + return enabled != 0, nil +} + +// SetStatus 启用/禁用账号(cookie_status 表)。 +func (c *Cookies) SetStatus(ctx context.Context, cookieID string, enabled bool) error { + v := 0 + if enabled { + v = 1 + } + _, err := c.DB.ExecContext(ctx, + `INSERT OR REPLACE INTO cookie_status (cookie_id, enabled, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP)`, + cookieID, v) + return err +} + +// GetStatus 取启用状态,默认 true(出错或无记录时)。 +func (c *Cookies) GetStatus(ctx context.Context, cookieID string) bool { + var enabled int + err := c.DB.QueryRowContext(ctx, `SELECT enabled FROM cookie_status WHERE cookie_id=?`, cookieID).Scan(&enabled) + if err != nil { + return true + } + return enabled != 0 +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..4d16b93 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,58 @@ +// Package db 提供 SQLite 连接管理与迁移。 +// 使用 modernc.org/sqlite(纯 Go,免 CGO,跨平台编译友好),WAL 模式 + busy_timeout。 +// 迁移用 goose 嵌入式执行,schema 从 Python db_manager.py 收敛而来——把历史上 12+ 处 +// 运行时 ALTER TABLE 补齐到 CREATE TABLE,并修复 schema 不一致 +// (orders.system_shipped、delivery_rules.user_id 等列在原 CREATE 中缺失却被引用)。 +package db + +import ( + "context" + "database/sql" + "embed" + "fmt" + "time" + + "github.com/pressly/goose/v3" + _ "modernc.org/sqlite" +) + +//go:embed migrations/*.sql +var migrationsFS embed.FS + +// Open 打开/创建数据库并执行迁移。dbPath 形如 "data/xianyu_data.db"。 +func Open(ctx context.Context, dbPath string) (*sql.DB, error) { + // _pragma 通过 DSN 设置;foreign_keys=ON 让 ON DELETE CASCADE 生效。 + dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)", dbPath) + db, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, fmt.Errorf("打开数据库: %w", err) + } + + // SQLite 写串行,连接池主要供读并发;设单写多读的合理上限。 + db.SetMaxOpenConns(8) + db.SetMaxIdleConns(4) + db.SetConnMaxLifetime(time.Hour) + + if err := db.PingContext(ctx); err != nil { + db.Close() + return nil, fmt.Errorf("ping 数据库: %w", err) + } + + if err := Migrate(ctx, db); err != nil { + db.Close() + return nil, err + } + return db, nil +} + +// Migrate 执行嵌入式 goose 迁移。 +func Migrate(ctx context.Context, db *sql.DB) error { + if err := goose.SetDialect("sqlite3"); err != nil { + return fmt.Errorf("设置 goose dialect: %w", err) + } + goose.SetBaseFS(migrationsFS) + if err := goose.Up(db, "migrations"); err != nil { + return fmt.Errorf("执行迁移: %w", err) + } + return nil +} diff --git a/internal/db/delivery.go b/internal/db/delivery.go new file mode 100644 index 0000000..fc1f4ad --- /dev/null +++ b/internal/db/delivery.go @@ -0,0 +1,318 @@ +package db + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" +) + +// ItemInfo 对应 item_info 表。 +type ItemInfo struct { + ID int64 + CookieID string + ItemID string + ItemTitle string + ItemDescription string + ItemCategory string + ItemPrice string + ItemDetail string + IsMultiSpec bool + MultiQuantityDelivery bool +} + +// Card 对应 cards 表(发货用字段)。 +type Card struct { + ID int64 + Name string + Type string // api/text/data/image + APIConfig string // JSON + TextContent string + DataContent string + ImageURL string + Description string + Enabled bool + DelaySeconds int + IsMultiSpec bool + SpecName string + SpecValue string + UserID int64 +} + +// DeliveryRule 对应 delivery_rules JOIN cards 的发货匹配结果。 +type DeliveryRule struct { + ID int64 + Keyword string + CardID int64 + DeliveryCount int + Enabled bool + Description string + DeliveryTimes int + CardName string + CardType string + APIConfig string + TextContent string + DataContent string + ImageURL string + CardDescription string + CardDelaySeconds int + IsMultiSpec bool + SpecName string + SpecValue string +} + +// Items 商品信息操作。 +type Items struct{ DB *sql.DB } + +// Get 取某账号下某商品信息。不存在返回 ErrNotFound。 +func (i *Items) Get(ctx context.Context, cookieID, itemID string) (*ItemInfo, error) { + var it ItemInfo + var isMulti, multiQty int + var title, desc, cat, price, detail sql.NullString + err := i.DB.QueryRowContext(ctx, + `SELECT id, cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, + is_multi_spec, multi_quantity_delivery + FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan( + &it.ID, &it.CookieID, &it.ItemID, &title, &desc, &cat, + &price, &detail, &isMulti, &multiQty) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + it.ItemTitle = title.String + it.ItemDescription = desc.String + it.ItemCategory = cat.String + it.ItemPrice = price.String + it.ItemDetail = detail.String + it.IsMultiSpec = isMulti != 0 + it.MultiQuantityDelivery = multiQty != 0 + return &it, nil +} + +// IsMultiSpec 是否多规格商品。 +func (i *Items) IsMultiSpec(ctx context.Context, cookieID, itemID string) bool { + var v int + err := i.DB.QueryRowContext(ctx, `SELECT is_multi_spec FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v) + if err != nil { + return false + } + return v != 0 +} + +// MultiQuantityDelivery 是否开启多数量发货。 +func (i *Items) MultiQuantityDelivery(ctx context.Context, cookieID, itemID string) bool { + var v int + err := i.DB.QueryRowContext(ctx, `SELECT multi_quantity_delivery FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v) + if err != nil { + return false + } + return v != 0 +} + +// Cards 卡券操作。 +type Cards struct{ DB *sql.DB } + +// ConsumeBatchData 消费一条批量数据卡券(data 类型),返回内容。 +// 对应 Python consume_batch_data:取 data_content 第一行,删除已消费行,发完置空。 +func (c *Cards) ConsumeBatchData(ctx context.Context, cardID int64) (string, error) { + tx, err := c.DB.BeginTx(ctx, nil) + if err != nil { + return "", err + } + defer tx.Rollback() + + var dataContent sql.NullString + err = tx.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&dataContent) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return "", ErrNotFound + } + return "", err + } + if !dataContent.Valid || dataContent.String == "" { + return "", errors.New("卡券批量数据为空") + } + + // 按行分割,取第一行非空作为发货内容,其余回写。 + lines := splitLines(dataContent.String) + if len(lines) == 0 { + return "", errors.New("卡券批量数据无有效行") + } + content := lines[0] + remaining := "" + if len(lines) > 1 { + remaining = joinLines(lines[1:]) + } + if _, err := tx.ExecContext(ctx, `UPDATE cards SET data_content=? WHERE id=?`, remaining, cardID); err != nil { + return "", err + } + if err := tx.Commit(); err != nil { + return "", err + } + return content, nil +} + +// IncrementDeliveryTimes 发货次数 +1。 +func (c *Cards) IncrementDeliveryTimes(ctx context.Context, ruleID int64) error { + _, err := c.DB.ExecContext(ctx, + `UPDATE delivery_rules SET delivery_times=delivery_times+1, updated_at=CURRENT_TIMESTAMP WHERE id=?`, ruleID) + return err +} + +// DeliveryRules 发货规则匹配。 +type DeliveryRules struct{ DB *sql.DB } + +// MatchByKeyword 非多规格双向模糊匹配(? LIKE %keyword% OR keyword LIKE %?%)。 +// 按关键字长度降序(商品包含关键字时按全长,否则半长)+ id 升序。 +// 移植自 get_delivery_rules_by_keyword。 +func (d *DeliveryRules) MatchByKeyword(ctx context.Context, searchText string) ([]DeliveryRule, error) { + q := ` +SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, dr.description, dr.delivery_times, + c.name, c.type, c.api_config, c.text_content, c.data_content, c.image_url, c.description, + c.delay_seconds, c.is_multi_spec, c.spec_name, c.spec_value +FROM delivery_rules dr +LEFT JOIN cards c ON dr.card_id = c.id +WHERE dr.enabled=1 AND c.enabled=1 + AND (? LIKE '%' || dr.keyword || '%' OR dr.keyword LIKE '%' || ? || '%') +ORDER BY + CASE WHEN ? LIKE '%' || dr.keyword || '%' THEN LENGTH(dr.keyword) ELSE LENGTH(dr.keyword)/2 END DESC, + dr.id ASC` + return d.scanRules(ctx, q, searchText, searchText, searchText) +} + +// MatchByKeywordAndSpec 多规格匹配:双向模糊 + spec_name/spec_value 精确匹配。 +// 移植自 get_delivery_rules_by_keyword_and_spec。 +func (d *DeliveryRules) MatchByKeywordAndSpec(ctx context.Context, searchText, specName, specValue string) ([]DeliveryRule, error) { + q := ` +SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, dr.description, dr.delivery_times, + c.name, c.type, c.api_config, c.text_content, c.data_content, c.image_url, c.description, + c.delay_seconds, c.is_multi_spec, c.spec_name, c.spec_value +FROM delivery_rules dr +LEFT JOIN cards c ON dr.card_id = c.id +WHERE dr.enabled=1 AND c.enabled=1 + AND (? LIKE '%' || dr.keyword || '%' OR dr.keyword LIKE '%' || ? || '%') + AND c.is_multi_spec=1 AND c.spec_name=? AND c.spec_value=? +ORDER BY + CASE WHEN ? LIKE '%' || dr.keyword || '%' THEN LENGTH(dr.keyword) ELSE LENGTH(dr.keyword)/2 END DESC, + dr.delivery_times ASC` + return d.scanRules(ctx, q, searchText, searchText, specName, specValue, searchText) +} + +// MatchForOrder 按账号、真实商品 ID 和订单规格匹配卡券。 +// 新规则优先精确 item_id;旧规则(item_id 为空)保留关键词回退。 +func (d *DeliveryRules) MatchForOrder(ctx context.Context, cookieID, itemID, searchText, specName, specValue string) ([]DeliveryRule, error) { + q := ` +SELECT dr.id, dr.keyword, v.card_id, v.delivery_count, dr.enabled, dr.description, dr.delivery_times, + c.name, c.type, c.api_config, c.text_content, c.data_content, c.image_url, c.description, + c.delay_seconds, + CASE WHEN v.spec_name <> '' OR v.spec_value <> '' THEN 1 ELSE 0 END, + v.spec_name, v.spec_value +FROM delivery_rules dr +JOIN delivery_rule_variants v ON v.rule_id = dr.id +JOIN cards c ON c.id = v.card_id +WHERE dr.enabled=1 AND v.enabled=1 AND c.enabled=1 + AND (dr.cookie_id='' OR dr.cookie_id=?) + AND ((dr.item_id<>'' AND dr.item_id=?) OR + (dr.item_id='' AND (? LIKE '%' || dr.keyword || '%' OR dr.keyword LIKE '%' || ? || '%'))) + AND v.spec_name=? AND v.spec_value=? +ORDER BY + CASE WHEN dr.item_id=? THEN 1 ELSE 0 END DESC, + CASE WHEN ? LIKE '%' || dr.keyword || '%' THEN LENGTH(dr.keyword) ELSE LENGTH(dr.keyword)/2 END DESC, + dr.delivery_times ASC` + return d.scanRules(ctx, q, cookieID, itemID, searchText, searchText, specName, specValue, itemID, searchText) +} + +func (d *DeliveryRules) scanRules(ctx context.Context, query string, args ...any) ([]DeliveryRule, error) { + rows, err := d.DB.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var rules []DeliveryRule + for rows.Next() { + var r DeliveryRule + var enabled, isMultiSpec int + var apiConfig, textContent, dataContent, imageURL, specName, specValue, desc, cardDesc sql.NullString + var delaySeconds sql.NullInt64 + if err := rows.Scan( + &r.ID, &r.Keyword, &r.CardID, &r.DeliveryCount, &enabled, &desc, &r.DeliveryTimes, + &r.CardName, &r.CardType, &apiConfig, &textContent, &dataContent, &imageURL, &cardDesc, + &delaySeconds, &isMultiSpec, &specName, &specValue); err != nil { + return nil, err + } + r.Enabled = enabled != 0 + r.Description = desc.String + r.APIConfig = apiConfig.String + r.TextContent = textContent.String + r.DataContent = dataContent.String + r.ImageURL = imageURL.String + r.CardDescription = cardDesc.String + if delaySeconds.Valid { + r.CardDelaySeconds = int(delaySeconds.Int64) + } + r.IsMultiSpec = isMultiSpec != 0 + r.SpecName = specName.String + r.SpecValue = specValue.String + rules = append(rules, r) + } + return rules, rows.Err() +} + +// APIConfig 解析卡券的 api_config JSON。 +func (r *DeliveryRule) APIConfigMap() map[string]any { + if r.APIConfig == "" { + return nil + } + var m map[string]any + if err := json.Unmarshal([]byte(r.APIConfig), &m); err != nil { + return nil + } + return m +} + +// splitLines / joinLines 复刻 Python str.splitlines / "\n".join。 +func splitLines(s string) []string { + var out []string + cur := []rune{} + for _, r := range s { + switch r { + case '\n': + out = append(out, string(cur)) + cur = cur[:0] + case '\r': + out = append(out, string(cur)) + cur = cur[:0] + // 跳过 \r,处理 \r\n + default: + cur = append(cur, r) + } + } + if len(cur) > 0 { + out = append(out, string(cur)) + } + // 过滤空行(Python consume_batch_data 行为)。 + res := out[:0] + for _, l := range out { + if l != "" { + res = append(res, l) + } + } + return res +} + +func joinLines(lines []string) string { + if len(lines) == 0 { + return "" + } + out := lines[0] + for _, l := range lines[1:] { + out += "\n" + l + } + return out +} + +// 防止 fmt 未用(保留供未来错误格式化)。 +var _ = fmt.Sprintf diff --git a/internal/db/extras.go b/internal/db/extras.go new file mode 100644 index 0000000..1673301 --- /dev/null +++ b/internal/db/extras.go @@ -0,0 +1,376 @@ +package db + +import ( + "context" + "database/sql" + "fmt" +) + +// ---- 关键字 CRUD ---- + +// KeywordRow keywords 表完整行(含自增 id,用于按索引删除)。 +type KeywordRow struct { + ID int64 + CookieID string + Keyword string + Reply string + ItemID string + Type string + ImageURL string +} + +// AllRows 取某账号所有关键字(含 id)。 +func (k *Keywords) AllRows(ctx context.Context, cookieID string) ([]KeywordRow, error) { + rows, err := k.DB.QueryContext(ctx, + `SELECT rowid, keyword, reply, COALESCE(item_id,''), COALESCE(type,'text'), COALESCE(image_url,'') + FROM keywords WHERE cookie_id=? ORDER BY rowid`, cookieID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []KeywordRow + for rows.Next() { + var r KeywordRow + if err := rows.Scan(&r.ID, &r.Keyword, &r.Reply, &r.ItemID, &r.Type, &r.ImageURL); err != nil { + return nil, err + } + r.CookieID = cookieID + out = append(out, r) + } + return out, rows.Err() +} + +// Add 添加关键字。 +func (k *Keywords) Add(ctx context.Context, cookieID, keyword, reply, itemID, kwType, imageURL string) (int64, error) { + if kwType == "" { + kwType = "text" + } + res, err := k.DB.ExecContext(ctx, + `INSERT INTO keywords (cookie_id, keyword, reply, item_id, type, image_url) VALUES (?,?,?,?,?,?)`, + cookieID, keyword, reply, nullable(itemID), kwType, nullable(imageURL)) + if err != nil { + return 0, err + } + return res.LastInsertId() +} + +// DeleteByIndex 按索引(0-based,按 rowid 顺序)删除某账号的一个关键字。 +func (k *Keywords) DeleteByIndex(ctx context.Context, cookieID string, index int) error { + rows, err := k.DB.QueryContext(ctx, + `SELECT rowid FROM keywords WHERE cookie_id=? ORDER BY rowid`, cookieID) + if err != nil { + return err + } + defer rows.Close() + var ids []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return err + } + ids = append(ids, id) + } + if index < 0 || index >= len(ids) { + return ErrNotFound + } + _, err = k.DB.ExecContext(ctx, `DELETE FROM keywords WHERE rowid=?`, ids[index]) + return err +} + +// ---- 指定商品回复 (item_replay) CRUD ---- + +// ItemReplies 已在 reply.go 定义 Get。补 Set/Delete。 + +// Set 设置指定商品回复。 +func (i *ItemReplies) Set(ctx context.Context, cookieID, itemID, content string) error { + _, err := i.DB.ExecContext(ctx, + `INSERT OR REPLACE INTO item_replay (item_id, cookie_id, reply_content, updated_at) + VALUES (?,?,?,CURRENT_TIMESTAMP)`, itemID, cookieID, content) + return err +} + +// Delete 删除指定商品回复。 +func (i *ItemReplies) Delete(ctx context.Context, cookieID, itemID string) error { + _, err := i.DB.ExecContext(ctx, + `DELETE FROM item_replay WHERE cookie_id=? AND item_id=?`, cookieID, itemID) + return err +} + +// AllForUser 取某账号所有指定商品回复。 +func (i *ItemReplies) AllForUser(ctx context.Context, cookieID string) ([]ItemReply, error) { + rows, err := i.DB.QueryContext(ctx, + `SELECT item_id, cookie_id, reply_content FROM item_replay WHERE cookie_id=?`, cookieID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []ItemReply + for rows.Next() { + var r ItemReply + if err := rows.Scan(&r.ItemID, &r.CookieID, &r.ReplyContent); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + +// ---- 通知渠道 CRUD ---- + +// NotificationChannelRow 通知渠道完整行(含 id)。 +type NotificationChannelRow struct { + ID int64 + Name string + Type string + Config string + Enabled bool + UserID int64 +} + +// AllChannelsForUser 取某用户全部通知渠道。 +func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([]NotificationChannelRow, error) { + rows, err := n.DB.QueryContext(ctx, + `SELECT id, name, type, config, enabled, COALESCE(user_id,1) FROM notification_channels + WHERE user_id=? ORDER BY id DESC`, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []NotificationChannelRow + for rows.Next() { + var c NotificationChannelRow + var enabled int + if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config, &enabled, &c.UserID); err != nil { + return nil, err + } + c.Enabled = enabled != 0 + out = append(out, c) + } + return out, rows.Err() +} + +// CreateChannel 创建通知渠道。 +func (n *Notifications) CreateChannel(ctx context.Context, c *NotificationChannelRow) (int64, error) { + res, err := n.DB.ExecContext(ctx, + `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES (?,?,?,?,?)`, + c.Name, c.Type, c.Config, boolToInt(c.Enabled), c.UserID) + if err != nil { + return 0, err + } + return res.LastInsertId() +} + +// UpdateChannel 更新通知渠道。 +func (n *Notifications) UpdateChannel(ctx context.Context, c *NotificationChannelRow) error { + _, err := n.DB.ExecContext(ctx, + `UPDATE notification_channels SET name=?, type=?, config=?, enabled=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`, + c.Name, c.Type, c.Config, boolToInt(c.Enabled), c.ID) + return err +} + +// DeleteChannel 删除通知渠道。 +func (n *Notifications) DeleteChannel(ctx context.Context, id int64) error { + _, err := n.DB.ExecContext(ctx, `DELETE FROM notification_channels WHERE id=?`, id) + return err +} + +// AccountBindings 取某账号已绑定的通知渠道 ID 列表。 +func (n *Notifications) AccountBindings(ctx context.Context, cookieID string) ([]int64, error) { + rows, err := n.DB.QueryContext(ctx, + `SELECT channel_id FROM message_notifications WHERE cookie_id=? AND enabled=1`, cookieID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + return out, rows.Err() +} + +// SetBindings 设置某账号的通知渠道绑定(覆盖式)。 +func (n *Notifications) SetBindings(ctx context.Context, cookieID string, channelIDs []int64) error { + tx, err := n.DB.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `DELETE FROM message_notifications WHERE cookie_id=?`, cookieID); err != nil { + return err + } + for _, cid := range channelIDs { + if _, err := tx.ExecContext(ctx, + `INSERT OR IGNORE INTO message_notifications (cookie_id, channel_id, enabled) VALUES (?,?,1)`, + cookieID, cid); err != nil { + return err + } + } + return tx.Commit() +} + +// ---- 系统设置 ---- + +// SystemSettings 系统设置操作。 +type SystemSettings struct{ DB *sql.DB } + +// Get 取单项设置。 +func (s *SystemSettings) Get(ctx context.Context, key string) (string, error) { + var v string + err := s.DB.QueryRowContext(ctx, `SELECT value FROM system_settings WHERE key=?`, key).Scan(&v) + if err != nil { + if err == sql.ErrNoRows { + return "", nil + } + return "", err + } + return v, nil +} + +// All 取全部设置(key→value)。 +func (s *SystemSettings) All(ctx context.Context) (map[string]string, error) { + rows, err := s.DB.QueryContext(ctx, `SELECT key, value FROM system_settings`) + if err != nil { + return nil, err + } + defer rows.Close() + m := make(map[string]string) + for rows.Next() { + var k, v string + if err := rows.Scan(&k, &v); err != nil { + return nil, err + } + m[k] = v + } + return m, rows.Err() +} + +// Set 设置单项。 +func (s *SystemSettings) Set(ctx context.Context, key, value string) error { + _, err := s.DB.ExecContext(ctx, + `INSERT OR REPLACE INTO system_settings (key, value, updated_at) VALUES (?,?,CURRENT_TIMESTAMP)`, + key, value) + return err +} + +// PublicKeys 公开设置键白名单(前端登录页等无需登录可读)。 +var PublicSystemKeys = map[string]bool{ + "theme_color": true, "registration_enabled": true, + "show_default_login_info": true, "login_captcha_enabled": true, +} + +// Public 取公开设置子集。 +func (s *SystemSettings) Public(ctx context.Context) (map[string]string, error) { + all, err := s.All(ctx) + if err != nil { + return nil, err + } + out := make(map[string]string) + for k := range PublicSystemKeys { + if v, ok := all[k]; ok { + out[k] = v + } + } + return out, nil +} + +// ---- 物品 (item_info) CRUD ---- + +// ItemInfoRow item_info 完整行。 +type ItemInfoRow struct { + ID int64 + CookieID string + ItemID string + ItemTitle string + ItemDescription string + ItemCategory string + ItemPrice string + ItemDetail string + IsMultiSpec bool + MultiQuantityDelivery bool +} + +// AllForCookie 取某账号全部商品。 +func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRow, error) { + rows, err := i.DB.QueryContext(ctx, + `SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''), + COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''), + is_multi_spec, COALESCE(multi_quantity_delivery,0) + FROM item_info WHERE cookie_id=? ORDER BY id DESC`, cookieID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []ItemInfoRow + for rows.Next() { + var r ItemInfoRow + var isMulti, multiQty int + if err := rows.Scan(&r.ID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.ItemDescription, + &r.ItemCategory, &r.ItemPrice, &r.ItemDetail, &isMulti, &multiQty); err != nil { + return nil, err + } + r.IsMultiSpec = isMulti != 0 + r.MultiQuantityDelivery = multiQty != 0 + out = append(out, r) + } + return out, rows.Err() +} + +// Upsert 插入或更新商品信息。 +func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error { + _, err := i.DB.ExecContext(ctx, + `INSERT OR REPLACE INTO item_info (cookie_id, item_id, item_title, item_description, + item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery, updated_at) + VALUES (?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`, + r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription), + nullable(r.ItemCategory), nullable(r.ItemPrice), nullable(r.ItemDetail), + boolToInt(r.IsMultiSpec), boolToInt(r.MultiQuantityDelivery)) + return err +} + +// UpsertBasic 插入或补全商品基础信息,不覆盖已有的多规格/多数量发货设置。 +func (i *Items) UpsertBasic(ctx context.Context, r *ItemInfoRow) error { + _, err := i.DB.ExecContext(ctx, + `INSERT INTO item_info (cookie_id, item_id, item_title, item_description, + item_category, item_price, item_detail, updated_at) + VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP) + ON CONFLICT(cookie_id, item_id) DO UPDATE SET + item_title=CASE WHEN excluded.item_title IS NOT NULL AND excluded.item_title != '' THEN excluded.item_title ELSE item_info.item_title END, + item_description=CASE WHEN excluded.item_description IS NOT NULL AND excluded.item_description != '' THEN excluded.item_description ELSE item_info.item_description END, + item_category=CASE WHEN excluded.item_category IS NOT NULL AND excluded.item_category != '' THEN excluded.item_category ELSE item_info.item_category END, + item_price=CASE WHEN excluded.item_price IS NOT NULL AND excluded.item_price != '' THEN excluded.item_price ELSE item_info.item_price END, + item_detail=CASE WHEN excluded.item_detail IS NOT NULL AND excluded.item_detail != '' THEN excluded.item_detail ELSE item_info.item_detail END, + updated_at=CURRENT_TIMESTAMP`, + r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription), + nullable(r.ItemCategory), nullable(r.ItemPrice), nullable(r.ItemDetail)) + return err +} + +// Delete 删除商品。 +func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error { + _, err := i.DB.ExecContext(ctx, `DELETE FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID) + return err +} + +// SetMultiSpec 设置多规格开关。 +func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bool) error { + _, err := i.DB.ExecContext(ctx, + `UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`, + boolToInt(on), cookieID, itemID) + return err +} + +// SetMultiQuantity 设置多数量发货开关。 +func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, on bool) error { + _, err := i.DB.ExecContext(ctx, + `UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`, + boolToInt(on), cookieID, itemID) + return err +} + +// 防止 fmt 未用。 +var _ = fmt.Sprintf diff --git a/internal/db/item_publish_batches.go b/internal/db/item_publish_batches.go new file mode 100644 index 0000000..7e4f0e3 --- /dev/null +++ b/internal/db/item_publish_batches.go @@ -0,0 +1,234 @@ +package db + +import ( + "context" + "database/sql" + "errors" +) + +type ItemPublishBatches struct{ DB *sql.DB } + +type ItemPublishBatch struct { + ID string + UserID int64 + DefaultCookieID string + Filename string + UploadDir string + Status string + TotalCount int + SuccessCount int + FailedCount int + CreatedAt string + UpdatedAt string +} + +type ItemPublishBatchRow struct { + ID int64 + BatchID string + RowNo int + CookieID string + Title string + Description string + Price string + OriginalPrice string + Quantity int + PostageMode string + Postage string + ImagesJSON string + AutoCreateDeliveryRule bool + CardGroupID int64 + DeliveryCount int + Status string + ItemID string + ItemURL string + ErrorMessage string + RawJSON string + CreatedAt string + UpdatedAt string +} + +func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch, rows []ItemPublishBatchRow) error { + tx, err := b.DB.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, + `INSERT INTO item_publish_batches + (id,user_id,default_cookie_id,filename,upload_dir,status,total_count,success_count,failed_count) + VALUES (?,?,?,?,?,?,?,?,?)`, + batch.ID, batch.UserID, batch.DefaultCookieID, batch.Filename, batch.UploadDir, + batch.Status, len(rows), 0, 0); err != nil { + return err + } + for _, row := range rows { + if row.Quantity <= 0 { + row.Quantity = 1 + } + if row.PostageMode == "" { + row.PostageMode = "free" + } + if row.DeliveryCount <= 0 { + row.DeliveryCount = 1 + } + if row.Status == "" { + row.Status = "pending" + } + if row.ImagesJSON == "" { + row.ImagesJSON = "[]" + } + if row.RawJSON == "" { + row.RawJSON = "{}" + } + if _, err := tx.ExecContext(ctx, + `INSERT INTO item_publish_batch_rows + (batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage, + images_json,auto_create_delivery_rule,card_group_id,delivery_count,status,error_message,raw_json) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, + batch.ID, row.RowNo, row.CookieID, row.Title, row.Description, row.Price, row.OriginalPrice, + row.Quantity, row.PostageMode, row.Postage, row.ImagesJSON, boolToInt(row.AutoCreateDeliveryRule), + row.CardGroupID, row.DeliveryCount, row.Status, row.ErrorMessage, row.RawJSON); err != nil { + return err + } + } + return tx.Commit() +} + +func (b *ItemPublishBatches) Get(ctx context.Context, userID int64, id string) (*ItemPublishBatch, error) { + var out ItemPublishBatch + err := b.DB.QueryRowContext(ctx, + `SELECT id,user_id,default_cookie_id,filename,upload_dir,status,total_count,success_count,failed_count, + COALESCE(created_at,''),COALESCE(updated_at,'') + FROM item_publish_batches WHERE id=? AND user_id=?`, id, userID).Scan( + &out.ID, &out.UserID, &out.DefaultCookieID, &out.Filename, &out.UploadDir, &out.Status, + &out.TotalCount, &out.SuccessCount, &out.FailedCount, &out.CreatedAt, &out.UpdatedAt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + return &out, nil +} + +func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPublishBatchRow, error) { + rows, err := b.DB.QueryContext(ctx, + `SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage, + images_json,auto_create_delivery_rule,card_group_id,delivery_count,status,item_id,item_url,error_message, + raw_json,COALESCE(created_at,''),COALESCE(updated_at,'') + FROM item_publish_batch_rows WHERE batch_id=? ORDER BY row_no`, batchID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []ItemPublishBatchRow{} + for rows.Next() { + var r ItemPublishBatchRow + var auto int + if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price, + &r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &auto, &r.CardGroupID, + &r.DeliveryCount, &r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt, + &r.UpdatedAt); err != nil { + return nil, err + } + r.AutoCreateDeliveryRule = auto != 0 + out = append(out, r) + } + return out, rows.Err() +} + +func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]ItemPublishBatchRow, error) { + statuses := "('pending')" + if failedOnly { + statuses = "('failed')" + } + rows, err := b.DB.QueryContext(ctx, + `SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage, + images_json,auto_create_delivery_rule,card_group_id,delivery_count,status,item_id,item_url,error_message, + raw_json,COALESCE(created_at,''),COALESCE(updated_at,'') + FROM item_publish_batch_rows WHERE batch_id=? AND status IN `+statuses+` ORDER BY row_no`, batchID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []ItemPublishBatchRow{} + for rows.Next() { + var r ItemPublishBatchRow + var auto int + if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price, + &r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &auto, &r.CardGroupID, + &r.DeliveryCount, &r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.RawJSON, &r.CreatedAt, + &r.UpdatedAt); err != nil { + return nil, err + } + r.AutoCreateDeliveryRule = auto != 0 + out = append(out, r) + } + return out, rows.Err() +} + +func (b *ItemPublishBatches) SetBatchStatus(ctx context.Context, batchID, status string) error { + _, err := b.DB.ExecContext(ctx, + `UPDATE item_publish_batches SET status=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, status, batchID) + return err +} + +func (b *ItemPublishBatches) BatchStatus(ctx context.Context, batchID string) (string, error) { + var status string + err := b.DB.QueryRowContext(ctx, `SELECT status FROM item_publish_batches WHERE id=?`, batchID).Scan(&status) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return "", ErrNotFound + } + return "", err + } + return status, nil +} + +func (b *ItemPublishBatches) MarkRowRunning(ctx context.Context, rowID int64) error { + _, err := b.DB.ExecContext(ctx, + `UPDATE item_publish_batch_rows SET status='running',error_message='',updated_at=CURRENT_TIMESTAMP WHERE id=?`, rowID) + return err +} + +func (b *ItemPublishBatches) MarkRowSuccess(ctx context.Context, rowID int64, itemID, itemURL, rawJSON string) error { + if rawJSON == "" { + rawJSON = "{}" + } + _, err := b.DB.ExecContext(ctx, + `UPDATE item_publish_batch_rows + SET status='success',item_id=?,item_url=?,error_message='',raw_json=?,updated_at=CURRENT_TIMESTAMP + WHERE id=?`, itemID, itemURL, rawJSON, rowID) + return err +} + +func (b *ItemPublishBatches) MarkRowFailed(ctx context.Context, rowID int64, message string) error { + _, err := b.DB.ExecContext(ctx, + `UPDATE item_publish_batch_rows SET status='failed',error_message=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, + message, rowID) + return err +} + +func (b *ItemPublishBatches) ResetFailed(ctx context.Context, batchID string) error { + _, err := b.DB.ExecContext(ctx, + `UPDATE item_publish_batch_rows + SET status='pending',error_message='',updated_at=CURRENT_TIMESTAMP + WHERE batch_id=? AND status='failed'`, batchID) + return err +} + +func (b *ItemPublishBatches) Recount(ctx context.Context, batchID string) error { + var total, success, failed int + if err := b.DB.QueryRowContext(ctx, + `SELECT COUNT(*), + COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END),0), + COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END),0) + FROM item_publish_batch_rows WHERE batch_id=?`, batchID).Scan(&total, &success, &failed); err != nil { + return err + } + _, err := b.DB.ExecContext(ctx, + `UPDATE item_publish_batches + SET total_count=?,success_count=?,failed_count=?,updated_at=CURRENT_TIMESTAMP + WHERE id=?`, total, success, failed, batchID) + return err +} diff --git a/internal/db/migrate_test.go b/internal/db/migrate_test.go new file mode 100644 index 0000000..d2f2009 --- /dev/null +++ b/internal/db/migrate_test.go @@ -0,0 +1,85 @@ +package db + +import ( + "context" + "database/sql" + "path/filepath" + "testing" +) + +// TestMigrate_AppliesCleanSchema 在临时库上跑迁移,验证全量 schema 干净落地、 +// 关键不一致列(orders.system_shipped / delivery_rules.user_id)存在、默认设置就位。 +func TestMigrate_AppliesCleanSchema(t *testing.T) { + tmp := t.TempDir() + dbPath := filepath.Join(tmp, "test.db") + + ctx := context.Background() + db, err := Open(ctx, dbPath) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer db.Close() + + checks := []struct { + table string + col string + }{ + {"orders", "system_shipped"}, + {"orders", "receiver_city"}, + {"orders", "version"}, + {"delivery_rules", "user_id"}, + {"cards", "image_url"}, + {"cards", "delay_seconds"}, + {"keywords", "item_id"}, + {"item_info", "multi_quantity_delivery"}, + {"default_replies", "reply_once"}, + {"users", "is_admin"}, + {"sessions", "session_id"}, + {"notification_channels", "user_id"}, + } + for _, c := range checks { + if !columnExists(t, db, c.table, c.col) { + t.Errorf("列缺失: %s.%s(应为收敛后的最终 schema)", c.table, c.col) + } + } + + // 默认系统设置应就位(qq_reply_secret_key 应为空,遵循无默认口令安全基线)。 + var val string + err = db.QueryRow(`SELECT value FROM system_settings WHERE key='theme_color'`).Scan(&val) + if err != nil || val != "blue" { + t.Errorf("默认设置 theme_color 异常: val=%q err=%v", val, err) + } + err = db.QueryRow(`SELECT value FROM system_settings WHERE key='qq_reply_secret_key'`).Scan(&val) + if err != nil || val != "" { + t.Errorf("qq_reply_secret_key 应为空(无默认值安全基线): val=%q err=%v", val, err) + } + + // 二次 Open 应幂等(迁移不重复执行、不报错)。 + if err := db.Close(); err != nil { + t.Fatalf("close: %v", err) + } + db2, err := Open(ctx, dbPath) + if err != nil { + t.Fatalf("二次 Open 幂等失败: %v", err) + } + db2.Close() +} + +func columnExists(t *testing.T, db *sql.DB, table, col string) bool { + t.Helper() + rows, err := db.Query(`SELECT name FROM pragma_table_info(?)`, table) + if err != nil { + t.Fatalf("pragma_table_info(%s): %v", table, err) + } + defer rows.Close() + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + t.Fatalf("scan: %v", err) + } + if name == col { + return true + } + } + return false +} diff --git a/internal/db/migrations/00001_init.sql b/internal/db/migrations/00001_init.sql new file mode 100644 index 0000000..add7c99 --- /dev/null +++ b/internal/db/migrations/00001_init.sql @@ -0,0 +1,358 @@ +-- +goose Up +-- +goose StatementBegin +-- 闲鱼管家全量 schema(从 Python db_manager.py 收敛)。 +-- 把历史上 12+ 处运行时 ALTER TABLE 补齐到 CREATE,并修复 schema 不一致: +-- - orders.system_shipped:原 CREATE 缺失却被 insert_or_update_order 引用 → 补齐 +-- - orders.receiver_city:原为运行时补齐 → 补齐 +-- - delivery_rules.user_id:原 CREATE 缺失却被 create_delivery_rule 引用 → 补齐 +-- - cards.user_id / delay_seconds / image_url:历史 ALTER → 补齐 +-- - keywords.item_id / type / image_url:历史 ALTER → 补齐 +-- - item_info.multi_quantity_delivery:历史 ALTER → 补齐 +-- - default_replies.reply_once / reply_image_url:历史 ALTER → 补齐 +-- - users.is_admin:历史 ALTER → 补齐 +-- 注:老库导入对齐在 Phase 6 单独脚本处理;本迁移面向全新库。 + +-- 认证与会话 +CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE NOT NULL, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + is_active BOOLEAN DEFAULT TRUE, + is_admin BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS sessions ( + session_id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL, + username TEXT NOT NULL, + is_admin INTEGER DEFAULT 0, + expires_at INTEGER NOT NULL, + created_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id); + +CREATE TABLE IF NOT EXISTS email_verifications ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT NOT NULL, + code TEXT NOT NULL, + expires_at TIMESTAMP NOT NULL, + used BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS captcha_codes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + code TEXT NOT NULL, + expires_at TIMESTAMP NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- 账号(闲鱼 cookie) +CREATE TABLE IF NOT EXISTS cookies ( + id TEXT PRIMARY KEY, + value TEXT NOT NULL, + user_id INTEGER NOT NULL, + auto_confirm INTEGER DEFAULT 1, + remark TEXT DEFAULT '', + pause_duration INTEGER DEFAULT 10, + username TEXT DEFAULT '', + password TEXT DEFAULT '', + show_browser INTEGER DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); +CREATE INDEX IF NOT EXISTS idx_cookies_user_id ON cookies(user_id); + +CREATE TABLE IF NOT EXISTS cookie_status ( + cookie_id TEXT PRIMARY KEY, + enabled BOOLEAN DEFAULT TRUE, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); + +-- 关键字回复 +CREATE TABLE IF NOT EXISTS keywords ( + cookie_id TEXT, + keyword TEXT, + reply TEXT, + item_id TEXT, + type TEXT DEFAULT 'text', + image_url TEXT, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); +CREATE INDEX IF NOT EXISTS idx_keywords_cookie_id ON keywords(cookie_id); + +-- AI 回复 +CREATE TABLE IF NOT EXISTS ai_reply_settings ( + cookie_id TEXT PRIMARY KEY, + ai_enabled BOOLEAN DEFAULT FALSE, + model_name TEXT DEFAULT 'qwen-plus', + api_key TEXT, + base_url TEXT DEFAULT 'https://dashscope.aliyuncs.com/compatible-mode/v1', + max_discount_percent INTEGER DEFAULT 10, + max_discount_amount INTEGER DEFAULT 100, + max_bargain_rounds INTEGER DEFAULT 3, + custom_prompts TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS ai_conversations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cookie_id TEXT NOT NULL, + chat_id TEXT NOT NULL, + user_id TEXT NOT NULL, + item_id TEXT NOT NULL, + role TEXT NOT NULL, + content TEXT NOT NULL, + intent TEXT, + bargain_count INTEGER DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies (id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS ai_item_cache ( + item_id TEXT PRIMARY KEY, + data TEXT NOT NULL, + price REAL, + description TEXT, + last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- 卡券与发货规则 +CREATE TABLE IF NOT EXISTS cards ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL CHECK (type IN ('api', 'text', 'data', 'image')), + api_config TEXT, + text_content TEXT, + data_content TEXT, + image_url TEXT, + description TEXT, + enabled BOOLEAN DEFAULT TRUE, + delay_seconds INTEGER DEFAULT 0, + is_multi_spec BOOLEAN DEFAULT FALSE, + spec_name TEXT, + spec_value TEXT, + user_id INTEGER NOT NULL DEFAULT 1, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users (id) +); +CREATE INDEX IF NOT EXISTS idx_cards_user_id ON cards(user_id); + +CREATE TABLE IF NOT EXISTS delivery_rules ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + keyword TEXT NOT NULL, + card_id INTEGER NOT NULL, + delivery_count INTEGER DEFAULT 1, + enabled BOOLEAN DEFAULT TRUE, + description TEXT, + delivery_times INTEGER DEFAULT 0, + user_id INTEGER NOT NULL DEFAULT 1, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) +); +CREATE INDEX IF NOT EXISTS idx_delivery_rules_user_id ON delivery_rules(user_id); +CREATE INDEX IF NOT EXISTS idx_delivery_rules_card_id ON delivery_rules(card_id); + +-- 订单 +CREATE TABLE IF NOT EXISTS orders ( + order_id TEXT PRIMARY KEY, + item_id TEXT, + buyer_id TEXT, + spec_name TEXT, + spec_value TEXT, + quantity TEXT, + amount TEXT, + order_status TEXT DEFAULT 'unknown', + cookie_id TEXT, + is_bargain INTEGER DEFAULT 0, + receiver_name TEXT DEFAULT '', + receiver_phone TEXT DEFAULT '', + receiver_address TEXT DEFAULT '', + receiver_city TEXT DEFAULT '', + version INTEGER DEFAULT 1, + chat_id TEXT DEFAULT '', + system_shipped INTEGER DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); +CREATE INDEX IF NOT EXISTS idx_orders_cookie_id ON orders(cookie_id); + +-- 商品信息 +CREATE TABLE IF NOT EXISTS item_info ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cookie_id TEXT NOT NULL, + item_id TEXT NOT NULL, + item_title TEXT, + item_description TEXT, + item_category TEXT, + item_price TEXT, + item_detail TEXT, + is_multi_spec BOOLEAN DEFAULT FALSE, + multi_quantity_delivery BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE, + UNIQUE(cookie_id, item_id) +); + +-- 默认回复 +CREATE TABLE IF NOT EXISTS default_replies ( + cookie_id TEXT PRIMARY KEY, + enabled BOOLEAN DEFAULT FALSE, + reply_content TEXT, + reply_image_url TEXT, + reply_once BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); + +-- WS 原始消息记录 +CREATE TABLE IF NOT EXISTS ws_messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cookie_id TEXT NOT NULL, + direction TEXT NOT NULL DEFAULT 'in', + raw_text TEXT NOT NULL DEFAULT '', + parsed_json TEXT NOT NULL DEFAULT '', + message_kind TEXT NOT NULL DEFAULT '', + parse_status TEXT NOT NULL DEFAULT 'raw', + error TEXT NOT NULL DEFAULT '', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); +CREATE INDEX IF NOT EXISTS idx_ws_messages_cookie_id_created_at ON ws_messages(cookie_id, created_at DESC); + +-- 指定商品回复 +CREATE TABLE IF NOT EXISTS item_replay ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + item_id TEXT NOT NULL, + cookie_id TEXT NOT NULL, + reply_content TEXT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_item_replay_cookie_item ON item_replay(cookie_id, item_id); + +-- 默认回复记录(防重复) +CREATE TABLE IF NOT EXISTS default_reply_records ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cookie_id TEXT NOT NULL, + chat_id TEXT NOT NULL, + replied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(cookie_id, chat_id), + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); + +-- 通知 +CREATE TABLE IF NOT EXISTS notification_channels ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL CHECK (type IN ('qq','ding_talk','dingtalk','feishu','lark','bark','email','webhook','wechat','telegram')), + config TEXT NOT NULL, + enabled BOOLEAN DEFAULT TRUE, + user_id INTEGER NOT NULL DEFAULT 1, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) +); + +CREATE TABLE IF NOT EXISTS message_notifications ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cookie_id TEXT NOT NULL, + channel_id INTEGER NOT NULL, + enabled BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE, + FOREIGN KEY (channel_id) REFERENCES notification_channels(id) ON DELETE CASCADE, + UNIQUE(cookie_id, channel_id) +); + +-- 系统设置 +CREATE TABLE IF NOT EXISTS system_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + description TEXT, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- 用户设置 +CREATE TABLE IF NOT EXISTS user_settings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + key TEXT NOT NULL, + value TEXT NOT NULL, + description TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + UNIQUE(user_id, key) +); + +-- 风控日志 +CREATE TABLE IF NOT EXISTS risk_control_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cookie_id TEXT NOT NULL, + event_type TEXT NOT NULL DEFAULT 'slider_captcha', + event_description TEXT, + processing_result TEXT, + processing_status TEXT DEFAULT 'processing', + error_message TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); + +-- 默认系统设置(不含管理员口令——由 init-admin CLI 初始化) +INSERT OR IGNORE INTO system_settings (key, value, description) VALUES + ('theme_color', 'blue', '主题颜色'), + ('registration_enabled', 'true', '是否开启用户注册'), + ('show_default_login_info', 'true', '是否显示默认登录信息'), + ('login_captcha_enabled', 'true', '登录滑动验证码开关'), + ('smtp_server', '', 'SMTP服务器地址'), + ('smtp_port', '587', 'SMTP端口'), + ('smtp_user', '', 'SMTP登录用户名(发件邮箱)'), + ('smtp_password', '', 'SMTP登录密码/授权码'), + ('smtp_from', '', '发件人显示名(留空则使用用户名)'), + ('smtp_use_tls', 'true', '是否启用TLS'), + ('smtp_use_ssl', 'false', '是否启用SSL'), + ('qq_reply_secret_key', '', 'QQ回复消息API秘钥(必须显式配置,无默认值)'), + ('item_sync_enabled', 'true', '是否启用定时自动同步商品'), + ('item_sync_interval', '600', '商品同步间隔时间(秒)'), + ('item_sync_max_pages', '5', '每次最多同步的页数'); +-- +goose StatementEnd + +-- +goose Down +DROP TABLE IF EXISTS risk_control_logs; +DROP TABLE IF EXISTS user_settings; +DROP TABLE IF EXISTS system_settings; +DROP TABLE IF EXISTS message_notifications; +DROP TABLE IF EXISTS notification_channels; +DROP TABLE IF EXISTS default_reply_records; +DROP TABLE IF EXISTS item_replay; +DROP TABLE IF EXISTS default_replies; +DROP TABLE IF EXISTS item_info; +DROP TABLE IF EXISTS orders; +DROP TABLE IF EXISTS delivery_rules; +DROP TABLE IF EXISTS cards; +DROP TABLE IF EXISTS ai_item_cache; +DROP TABLE IF EXISTS ai_conversations; +DROP TABLE IF EXISTS ai_reply_settings; +DROP TABLE IF EXISTS keywords; +DROP TABLE IF EXISTS cookie_status; +DROP TABLE IF EXISTS cookies; +DROP TABLE IF EXISTS captcha_codes; +DROP TABLE IF EXISTS email_verifications; +DROP TABLE IF EXISTS sessions; +DROP TABLE IF EXISTS users; diff --git a/internal/db/migrations/00002_cookie_profile.sql b/internal/db/migrations/00002_cookie_profile.sql new file mode 100644 index 0000000..3a0e9b7 --- /dev/null +++ b/internal/db/migrations/00002_cookie_profile.sql @@ -0,0 +1,15 @@ +-- +goose Up +-- +goose StatementBegin +ALTER TABLE cookies ADD COLUMN nickname TEXT DEFAULT ''; +ALTER TABLE cookies ADD COLUMN avatar_url TEXT DEFAULT ''; +ALTER TABLE cookies ADD COLUMN updated_at TIMESTAMP; +UPDATE cookies +SET updated_at = COALESCE(updated_at, created_at, CURRENT_TIMESTAMP); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +ALTER TABLE cookies DROP COLUMN updated_at; +ALTER TABLE cookies DROP COLUMN avatar_url; +ALTER TABLE cookies DROP COLUMN nickname; +-- +goose StatementEnd diff --git a/internal/db/migrations/00003_global_ai_settings.sql b/internal/db/migrations/00003_global_ai_settings.sql new file mode 100644 index 0000000..1041a7a --- /dev/null +++ b/internal/db/migrations/00003_global_ai_settings.sql @@ -0,0 +1,8 @@ +-- +goose Up +INSERT OR IGNORE INTO system_settings (key, value, description) VALUES + ('ai_api_url', 'https://dashscope.aliyuncs.com/compatible-mode/v1', 'AI OpenAI兼容API地址'), + ('ai_api_key', '', 'AI API Key'), + ('ai_model', 'qwen-plus', 'AI模型名称'); + +-- +goose Down +DELETE FROM system_settings WHERE key IN ('ai_api_url', 'ai_api_key', 'ai_model'); diff --git a/internal/db/migrations/00004_delivery_rule_variants.sql b/internal/db/migrations/00004_delivery_rule_variants.sql new file mode 100644 index 0000000..153e528 --- /dev/null +++ b/internal/db/migrations/00004_delivery_rule_variants.sql @@ -0,0 +1,44 @@ +-- +goose Up +-- +goose StatementBegin +ALTER TABLE delivery_rules ADD COLUMN cookie_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE delivery_rules ADD COLUMN item_id TEXT NOT NULL DEFAULT ''; + +CREATE TABLE delivery_rule_variants ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + rule_id INTEGER NOT NULL, + spec_name TEXT NOT NULL DEFAULT '', + spec_value TEXT NOT NULL DEFAULT '', + card_id INTEGER NOT NULL, + delivery_count INTEGER NOT NULL DEFAULT 1, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (rule_id) REFERENCES delivery_rules(id) ON DELETE CASCADE, + FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE RESTRICT, + UNIQUE(rule_id, spec_name, spec_value) +); + +CREATE INDEX idx_delivery_rules_cookie_item ON delivery_rules(cookie_id, item_id); +CREATE INDEX idx_delivery_rule_variants_rule ON delivery_rule_variants(rule_id); +CREATE INDEX idx_delivery_rule_variants_card ON delivery_rule_variants(card_id); + +-- 旧规则迁移为一条默认或指定规格映射。cards 上的规格字段仅保留兼容读取。 +INSERT INTO delivery_rule_variants + (rule_id, spec_name, spec_value, card_id, delivery_count, enabled) +SELECT dr.id, + CASE WHEN COALESCE(c.is_multi_spec, 0) = 1 THEN COALESCE(c.spec_name, '') ELSE '' END, + CASE WHEN COALESCE(c.is_multi_spec, 0) = 1 THEN COALESCE(c.spec_value, '') ELSE '' END, + dr.card_id, + CASE WHEN dr.delivery_count > 0 THEN dr.delivery_count ELSE 1 END, + dr.enabled +FROM delivery_rules dr +JOIN cards c ON c.id = dr.card_id; +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE delivery_rule_variants; +DROP INDEX IF EXISTS idx_delivery_rules_cookie_item; +ALTER TABLE delivery_rules DROP COLUMN item_id; +ALTER TABLE delivery_rules DROP COLUMN cookie_id; +-- +goose StatementEnd diff --git a/internal/db/migrations/00005_ws_messages.sql b/internal/db/migrations/00005_ws_messages.sql new file mode 100644 index 0000000..11bb822 --- /dev/null +++ b/internal/db/migrations/00005_ws_messages.sql @@ -0,0 +1,22 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS ws_messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cookie_id TEXT NOT NULL, + direction TEXT NOT NULL DEFAULT 'in', + raw_text TEXT NOT NULL DEFAULT '', + parsed_json TEXT NOT NULL DEFAULT '', + message_kind TEXT NOT NULL DEFAULT '', + parse_status TEXT NOT NULL DEFAULT 'raw', + error TEXT NOT NULL DEFAULT '', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE +); +CREATE INDEX IF NOT EXISTS idx_ws_messages_cookie_id_created_at ON ws_messages(cookie_id, created_at DESC); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP INDEX IF EXISTS idx_ws_messages_cookie_id_created_at; +DROP TABLE IF EXISTS ws_messages; +-- +goose StatementEnd diff --git a/internal/db/migrations/00006_item_publish_batches.sql b/internal/db/migrations/00006_item_publish_batches.sql new file mode 100644 index 0000000..35784dc --- /dev/null +++ b/internal/db/migrations/00006_item_publish_batches.sql @@ -0,0 +1,53 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS item_publish_batches ( + id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL, + default_cookie_id TEXT NOT NULL DEFAULT '', + filename TEXT NOT NULL DEFAULT '', + upload_dir TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', + total_count INTEGER NOT NULL DEFAULT 0, + success_count INTEGER NOT NULL DEFAULT 0, + failed_count INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS item_publish_batch_rows ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + batch_id TEXT NOT NULL, + row_no INTEGER NOT NULL, + cookie_id TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + description TEXT NOT NULL DEFAULT '', + price TEXT NOT NULL DEFAULT '', + original_price TEXT NOT NULL DEFAULT '', + quantity INTEGER NOT NULL DEFAULT 1, + postage_mode TEXT NOT NULL DEFAULT 'free', + postage TEXT NOT NULL DEFAULT '', + images_json TEXT NOT NULL DEFAULT '[]', + auto_create_delivery_rule INTEGER NOT NULL DEFAULT 0, + card_group_id INTEGER NOT NULL DEFAULT 0, + delivery_count INTEGER NOT NULL DEFAULT 1, + status TEXT NOT NULL DEFAULT 'pending', + item_id TEXT NOT NULL DEFAULT '', + item_url TEXT NOT NULL DEFAULT '', + error_message TEXT NOT NULL DEFAULT '', + raw_json TEXT NOT NULL DEFAULT '{}', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (batch_id) REFERENCES item_publish_batches(id) ON DELETE CASCADE +); + +CREATE INDEX IF NOT EXISTS idx_item_publish_batches_user ON item_publish_batches(user_id, created_at); +CREATE INDEX IF NOT EXISTS idx_item_publish_batch_rows_batch ON item_publish_batch_rows(batch_id, row_no); +CREATE INDEX IF NOT EXISTS idx_item_publish_batch_rows_status ON item_publish_batch_rows(batch_id, status); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS item_publish_batch_rows; +DROP TABLE IF EXISTS item_publish_batches; +-- +goose StatementEnd diff --git a/internal/db/models.go b/internal/db/models.go new file mode 100644 index 0000000..57f8d8f --- /dev/null +++ b/internal/db/models.go @@ -0,0 +1,39 @@ +package db + +// User 对应 users 表。 +type User struct { + ID int64 + Username string + Email string + PasswordHash string + IsActive bool + IsAdmin bool + CreatedAt string + UpdatedAt string +} + +// Session 对应 sessions 表(HttpOnly Cookie 会话)。 +type Session struct { + SessionID string + UserID int64 + Username string + IsAdmin bool + ExpiresAt int64 + CreatedAt int64 +} + +// CookieDetail 对应 cookies 表的完整行(get_cookie_details)。 +type CookieDetail struct { + ID string + Value string + UserID int64 + AutoConfirm bool + Remark string + PauseDuration int + Username string + Password string + ShowBrowser bool + Nickname string + AvatarURL string + CreatedAt string +} diff --git a/internal/db/notifications.go b/internal/db/notifications.go new file mode 100644 index 0000000..0c03b23 --- /dev/null +++ b/internal/db/notifications.go @@ -0,0 +1,41 @@ +package db + +import ( + "context" + "database/sql" +) + +// NotificationChannel 通知渠道(含配置 JSON)。 +type NotificationChannel struct { + ID int64 + Name string + Type string + Config string // JSON +} + +// Notifications 通知绑定操作。 +type Notifications struct{ DB *sql.DB } + +// AccountChannels 取某账号已启用的通知渠道(message_notifications JOIN notification_channels)。 +// 移植自 get_account_notifications。 +func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([]NotificationChannel, error) { + rows, err := n.DB.QueryContext(ctx, + `SELECT nc.id, nc.name, nc.type, nc.config + FROM message_notifications mn + JOIN notification_channels nc ON mn.channel_id = nc.id + WHERE mn.cookie_id=? AND mn.enabled=1 AND nc.enabled=1 + ORDER BY mn.id`, cookieID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []NotificationChannel + for rows.Next() { + var c NotificationChannel + if err := rows.Scan(&c.ID, &c.Name, &c.Type, &c.Config); err != nil { + return nil, err + } + out = append(out, c) + } + return out, rows.Err() +} diff --git a/internal/db/orders.go b/internal/db/orders.go new file mode 100644 index 0000000..d31690d --- /dev/null +++ b/internal/db/orders.go @@ -0,0 +1,193 @@ +package db + +import ( + "context" + "database/sql" + "errors" +) + +// Order 对应 orders 表。 +type Order struct { + OrderID string + ItemID string + BuyerID string + SpecName string + SpecValue string + Quantity string + Amount string + OrderStatus string + CookieID string + IsBargain int + ReceiverName string + ReceiverPhone string + ReceiverAddr string + ReceiverCity string + Version int + ChatID string + SystemShipped bool + CreatedAt string + UpdatedAt string +} + +// Orders 订单操作。 +type Orders struct{ DB *sql.DB } + +// Upsert 插入或更新订单。仅更新提供的非零字段,使用 version 乐观锁。 +// 对应 Python insert_or_update_order 的核心行为。 +func (o *Orders) Upsert(ctx context.Context, orderID string, opts OrderUpsertOpts) error { + if orderID == "" { + return errors.New("order_id 不能为空") + } + // 先尝试 INSERT OR IGNORE 占位。 + _, err := o.DB.ExecContext(ctx, + `INSERT OR IGNORE INTO orders (order_id, item_id, buyer_id, cookie_id, order_status, version) + VALUES (?, ?, ?, ?, 'unknown', 1)`, + orderID, opts.ItemID, opts.BuyerID, opts.CookieID) + if err != nil { + return err + } + + // 动态构造 UPDATE。 + set := []string{} + args := []any{} + if opts.SystemShipped != nil { + set = append(set, "system_shipped=?") + args = append(args, boolToInt(*opts.SystemShipped)) + } + if opts.ChatID != "" { + set = append(set, "chat_id=?") + args = append(args, opts.ChatID) + } + if opts.ItemID != "" { + set = append(set, "item_id=?") + args = append(args, opts.ItemID) + } + if opts.BuyerID != "" { + set = append(set, "buyer_id=?") + args = append(args, opts.BuyerID) + } + if opts.CookieID != "" { + set = append(set, "cookie_id=?") + args = append(args, opts.CookieID) + } + if opts.OrderStatus != "" { + set = append(set, "order_status=?") + args = append(args, opts.OrderStatus) + } + if opts.SpecName != "" { + set = append(set, "spec_name=?") + args = append(args, opts.SpecName) + } + if opts.SpecValue != "" { + set = append(set, "spec_value=?") + args = append(args, opts.SpecValue) + } + if opts.Quantity != "" { + set = append(set, "quantity=?") + args = append(args, opts.Quantity) + } + if opts.Amount != "" { + set = append(set, "amount=?") + args = append(args, opts.Amount) + } + if opts.ReceiverName != "" { + set = append(set, "receiver_name=?") + args = append(args, opts.ReceiverName) + } + if opts.ReceiverPhone != "" { + set = append(set, "receiver_phone=?") + args = append(args, opts.ReceiverPhone) + } + if opts.ReceiverAddr != "" { + set = append(set, "receiver_address=?") + args = append(args, opts.ReceiverAddr) + } + if opts.ReceiverCity != "" { + set = append(set, "receiver_city=?") + args = append(args, opts.ReceiverCity) + } + if len(set) == 0 { + return nil // 无字段可更新 + } + set = append(set, "updated_at=CURRENT_TIMESTAMP") + args = append(args, orderID) + q := `UPDATE orders SET ` + joinSet(set) + ` WHERE order_id=?` + _, err = o.DB.ExecContext(ctx, q, args...) + return err +} + +// OrderUpsertOpts Upsert 的可选字段。 +type OrderUpsertOpts struct { + ItemID string + BuyerID string + CookieID string + OrderStatus string + SpecName string + SpecValue string + Quantity string + Amount string + ReceiverName string + ReceiverPhone string + ReceiverAddr string + ReceiverCity string + ChatID string + SystemShipped *bool +} + +// Get 按 order_id 查询。 +func (o *Orders) Get(ctx context.Context, orderID string) (*Order, error) { + var ord Order + var isBargain, version, sysShipped int + var itemID, buyerID, specName, specValue, qty, amount, status, cookieID, receiverName, receiverPhone, receiverAddr, receiverCity, chatID, createdAt, updatedAt sql.NullString + err := o.DB.QueryRowContext(ctx, + `SELECT order_id, item_id, buyer_id, spec_name, spec_value, quantity, amount, + order_status, cookie_id, is_bargain, receiver_name, receiver_phone, receiver_address, + receiver_city, version, chat_id, system_shipped, created_at, updated_at + FROM orders WHERE order_id=?`, orderID).Scan( + &ord.OrderID, &itemID, &buyerID, &specName, &specValue, &qty, &amount, + &status, &cookieID, &isBargain, &receiverName, &receiverPhone, &receiverAddr, + &receiverCity, &version, &chatID, &sysShipped, &createdAt, &updatedAt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + ord.ItemID = itemID.String + ord.BuyerID = buyerID.String + ord.SpecName = specName.String + ord.SpecValue = specValue.String + ord.Quantity = qty.String + ord.Amount = amount.String + ord.OrderStatus = status.String + ord.CookieID = cookieID.String + ord.IsBargain = isBargain + ord.ReceiverName = receiverName.String + ord.ReceiverPhone = receiverPhone.String + ord.ReceiverAddr = receiverAddr.String + ord.ReceiverCity = receiverCity.String + ord.Version = version + ord.ChatID = chatID.String + ord.SystemShipped = sysShipped != 0 + ord.CreatedAt = createdAt.String + ord.UpdatedAt = updatedAt.String + return &ord, nil +} + +func boolToInt(b bool) int { + if b { + return 1 + } + return 0 +} + +func joinSet(parts []string) string { + out := "" + for i, p := range parts { + if i > 0 { + out += ", " + } + out += p + } + return out +} diff --git a/internal/db/orders_ext.go b/internal/db/orders_ext.go new file mode 100644 index 0000000..ffa113e --- /dev/null +++ b/internal/db/orders_ext.go @@ -0,0 +1,234 @@ +package db + +import ( + "context" + "database/sql" + "fmt" + "strings" +) + +// OrderRow 订单列表展示行(含 item_title)。 +type OrderRow struct { + OrderID string + ItemID string + ItemTitle string + BuyerID string + SpecName string + SpecValue string + Quantity string + Amount string + OrderStatus string + CookieID string + IsBargain int + SystemShipped bool + ReceiverName string + ReceiverPhone string + ReceiverAddr string + ReceiverCity string + CreatedAt string + UpdatedAt string +} + +// OrdersByCookie 取某账号的订单(limit 上限)。移植自 get_orders_by_cookie。 +func (o *Orders) ByCookie(ctx context.Context, cookieID string, limit int) ([]OrderRow, error) { + if limit <= 0 { + limit = 1000 + } + rows, err := o.DB.QueryContext(ctx, + `SELECT order_id, item_id, buyer_id, spec_name, spec_value, quantity, amount, + order_status, is_bargain, system_shipped, receiver_name, receiver_phone, + receiver_address, receiver_city, created_at, updated_at + FROM orders WHERE cookie_id=? ORDER BY created_at DESC LIMIT ?`, cookieID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []OrderRow + for rows.Next() { + var r OrderRow + var itemID, buyerID, specName, specValue, qty, amount, receiverName, receiverPhone, receiverAddr, receiverCity sql.NullString + var isBargain, sysShipped int + if err := rows.Scan(&r.OrderID, &itemID, &buyerID, &specName, &specValue, &qty, &amount, + &r.OrderStatus, &isBargain, &sysShipped, &receiverName, &receiverPhone, &receiverAddr, + &receiverCity, &r.CreatedAt, &r.UpdatedAt); err != nil { + return nil, err + } + r.ItemID = itemID.String + r.BuyerID = buyerID.String + r.SpecName = specName.String + r.SpecValue = specValue.String + r.Quantity = qty.String + r.Amount = amount.String + r.IsBargain = isBargain + r.SystemShipped = sysShipped != 0 + r.ReceiverName = receiverName.String + r.ReceiverPhone = receiverPhone.String + r.ReceiverAddr = receiverAddr.String + r.ReceiverCity = receiverCity.String + r.CookieID = cookieID + out = append(out, r) + } + return out, rows.Err() +} + +// OrderStatusMap 数字状态码 → 文本(移植自 Python order_status_handler)。 +var OrderStatusMap = map[string]string{ + "1": "processing", "2": "pending_ship", "3": "shipped", "4": "completed", + "5": "refunding", "6": "cancelled", "7": "refunding", "8": "cancelled", + "9": "refunding", "10": "cancelled", "11": "completed", "12": "cancelled", +} + +// NormalizeOrderStatus 数字码归一为文本。 +func NormalizeOrderStatus(s string) string { + if t, ok := OrderStatusMap[s]; ok { + return t + } + if s == "" { + return "unknown" + } + return s +} + +// AllItemTitles 取全部 item_id → item_title 映射(订单列表用)。 +func (i *Items) AllTitles(ctx context.Context) (map[string]string, error) { + rows, err := i.DB.QueryContext(ctx, `SELECT item_id, item_title FROM item_info`) + if err != nil { + return nil, err + } + defer rows.Close() + m := make(map[string]string) + for rows.Next() { + var id, title sql.NullString + if err := rows.Scan(&id, &title); err != nil { + return nil, err + } + m[id.String] = title.String + } + return m, rows.Err() +} + +// 卡券 CRUD 辅助。 + +// CardFull 卡券完整信息(CRUD 用)。 +type CardFull struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + APIConfig string `json:"api_config"` + TextContent string `json:"text_content"` + DataContent string `json:"data_content"` + ImageURL string `json:"image_url"` + Description string `json:"description"` + Enabled bool `json:"enabled"` + DelaySeconds int `json:"delay_seconds"` + IsMultiSpec bool `json:"is_multi_spec"` + SpecName string `json:"spec_name"` + SpecValue string `json:"spec_value"` + UserID int64 `json:"user_id"` +} + +// GetCard 取单个卡券。 +func (c *Cards) Get(ctx context.Context, cardID int64) (*CardFull, error) { + var cf CardFull + var enabled, isMultiSpec int + var apiCfg, textContent, dataContent, imageURL, specName, specValue, desc sql.NullString + err := c.DB.QueryRowContext(ctx, + `SELECT id, name, type, api_config, text_content, data_content, image_url, description, + enabled, delay_seconds, is_multi_spec, spec_name, spec_value, user_id + FROM cards WHERE id=?`, cardID).Scan( + &cf.ID, &cf.Name, &cf.Type, &apiCfg, &textContent, &dataContent, &imageURL, &desc, + &enabled, &cf.DelaySeconds, &isMultiSpec, &specName, &specValue, &cf.UserID) + if err != nil { + if err == sql.ErrNoRows { + return nil, ErrNotFound + } + return nil, err + } + cf.APIConfig = apiCfg.String + cf.TextContent = textContent.String + cf.DataContent = dataContent.String + cf.ImageURL = imageURL.String + cf.Description = desc.String + cf.Enabled = enabled != 0 + cf.IsMultiSpec = isMultiSpec != 0 + cf.SpecName = specName.String + cf.SpecValue = specValue.String + return &cf, nil +} + +// AllCardsForUser 取某用户全部卡券。 +func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error) { + rows, err := c.DB.QueryContext(ctx, + `SELECT id, name, type, api_config, text_content, data_content, image_url, description, + enabled, delay_seconds, is_multi_spec, spec_name, spec_value, user_id + FROM cards WHERE user_id=? ORDER BY id DESC`, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []CardFull + for rows.Next() { + var cf CardFull + var enabled, isMultiSpec int + var apiCfg, textContent, dataContent, imageURL, specName, specValue, desc sql.NullString + if err := rows.Scan(&cf.ID, &cf.Name, &cf.Type, &apiCfg, &textContent, &dataContent, &imageURL, &desc, + &enabled, &cf.DelaySeconds, &isMultiSpec, &specName, &specValue, &cf.UserID); err != nil { + return nil, err + } + cf.APIConfig = apiCfg.String + cf.TextContent = textContent.String + cf.DataContent = dataContent.String + cf.ImageURL = imageURL.String + cf.Description = desc.String + cf.Enabled = enabled != 0 + cf.IsMultiSpec = isMultiSpec != 0 + cf.SpecName = specName.String + cf.SpecValue = specValue.String + out = append(out, cf) + } + return out, rows.Err() +} + +// CreateCard 创建卡券,返回新 ID。 +func (c *Cards) Create(ctx context.Context, cf *CardFull) (int64, error) { + res, err := c.DB.ExecContext(ctx, + `INSERT INTO cards (name, type, api_config, text_content, data_content, image_url, description, + enabled, delay_seconds, is_multi_spec, spec_name, spec_value, user_id) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`, + cf.Name, cf.Type, nullable(cf.APIConfig), nullable(cf.TextContent), nullable(cf.DataContent), + nullable(cf.ImageURL), nullable(cf.Description), boolToInt(cf.Enabled), cf.DelaySeconds, + boolToInt(cf.IsMultiSpec), nullable(cf.SpecName), nullable(cf.SpecValue), cf.UserID) + if err != nil { + return 0, err + } + return res.LastInsertId() +} + +// UpdateCard 更新卡券。 +func (c *Cards) Update(ctx context.Context, cf *CardFull) error { + _, err := c.DB.ExecContext(ctx, + `UPDATE cards SET name=?, type=?, api_config=?, text_content=?, data_content=?, image_url=?, + description=?, enabled=?, delay_seconds=?, is_multi_spec=?, spec_name=?, spec_value=?, updated_at=CURRENT_TIMESTAMP + WHERE id=?`, + cf.Name, cf.Type, nullable(cf.APIConfig), nullable(cf.TextContent), nullable(cf.DataContent), + nullable(cf.ImageURL), nullable(cf.Description), boolToInt(cf.Enabled), cf.DelaySeconds, + boolToInt(cf.IsMultiSpec), nullable(cf.SpecName), nullable(cf.SpecValue), cf.ID) + return err +} + +// DeleteCard 删除卡券。 +func (c *Cards) Delete(ctx context.Context, cardID int64) error { + _, err := c.DB.ExecContext(ctx, `DELETE FROM cards WHERE id=?`, cardID) + return err +} + +func nullable(s string) any { + if s == "" { + return nil + } + return s +} + +// 占位防未用 fmt(未来扩展)。 +var _ = fmt.Sprintf +var _ = strings.TrimSpace diff --git a/internal/db/password.go b/internal/db/password.go new file mode 100644 index 0000000..d7ed1b4 --- /dev/null +++ b/internal/db/password.go @@ -0,0 +1,54 @@ +package db + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "strings" + + "golang.org/x/crypto/bcrypt" +) + +// ErrPasswordMismatch 密码不匹配。 +var ErrPasswordMismatch = errors.New("密码错误") + +// HashPassword 用 bcrypt 哈希明文密码(新用户/改密码用)。 +func HashPassword(plain string) (string, error) { + b, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost) + if err != nil { + return "", err + } + return string(b), nil +} + +// legacySHA256 复刻 Python 端 hashlib.sha256(password).hexdigest(),用于兼容老库。 +func legacySHA256(plain string) string { + sum := sha256.Sum256([]byte(plain)) + return hex.EncodeToString(sum[:]) +} + +// isLegacyHash 判断是否为老的无盐 SHA-256 哈希(64 位十六进制)。 +// bcrypt 哈希以 $2 开头,据此区分。 +func isLegacyHash(h string) bool { + return len(h) == 64 && !strings.HasPrefix(h, "$2") +} + +// VerifyPassword 校验明文与存储哈希。 +// - bcrypt 哈希:bcrypt.CompareHashAndPassword +// - 老 SHA-256 哈希:逐字节对比(兼容老库) +// 返回 (matched, needsUpgrade)。needsUpgrade=true 表示命中老哈希、应升级到 bcrypt。 +func VerifyPassword(stored, plain string) (matched bool, needsUpgrade bool, err error) { + if isLegacyHash(stored) { + if stored == legacySHA256(plain) { + return true, true, nil + } + return false, false, ErrPasswordMismatch + } + if err := bcrypt.CompareHashAndPassword([]byte(stored), []byte(plain)); err != nil { + if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { + return false, false, ErrPasswordMismatch + } + return false, false, err + } + return true, false, nil +} diff --git a/internal/db/reply.go b/internal/db/reply.go new file mode 100644 index 0000000..009f16f --- /dev/null +++ b/internal/db/reply.go @@ -0,0 +1,115 @@ +package db + +import ( + "context" + "database/sql" + "errors" +) + +// Keyword 对应 keywords 表。 +type Keyword struct { + Keyword string + Reply string + ItemID string + Type string // text/image + ImageURL string +} + +// DefaultReply 对应 default_replies 表。 +type DefaultReply struct { + Enabled bool + ReplyContent string + ReplyImageURL string + ReplyOnce bool +} + +// ItemReply 对应 item_replay 表(指定商品回复)。 +type ItemReply struct { + ItemID string + CookieID string + ReplyContent string +} + +// Keywords 关键字操作。 +type Keywords struct{ DB *sql.DB } + +// AllWithType 取某账号所有关键字(含类型/图片)。 +func (k *Keywords) AllWithType(ctx context.Context, cookieID string) ([]Keyword, error) { + rows, err := k.DB.QueryContext(ctx, + `SELECT keyword, reply, COALESCE(item_id,''), COALESCE(type,'text'), COALESCE(image_url,'') + FROM keywords WHERE cookie_id=?`, cookieID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Keyword + for rows.Next() { + var kw Keyword + if err := rows.Scan(&kw.Keyword, &kw.Reply, &kw.ItemID, &kw.Type, &kw.ImageURL); err != nil { + return nil, err + } + out = append(out, kw) + } + return out, rows.Err() +} + +// DefaultReplies 默认回复操作。 +type DefaultReplies struct{ DB *sql.DB } + +// Get 取某账号默认回复设置。不存在返回 ErrNotFound。 +func (d *DefaultReplies) Get(ctx context.Context, cookieID string) (*DefaultReply, error) { + var dr DefaultReply + var enabled, replyOnce int + var content, imageURL sql.NullString + err := d.DB.QueryRowContext(ctx, + `SELECT enabled, reply_content, reply_image_url, reply_once FROM default_replies WHERE cookie_id=?`, + cookieID).Scan(&enabled, &content, &imageURL, &replyOnce) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + dr.Enabled = enabled != 0 + dr.ReplyContent = content.String + dr.ReplyImageURL = imageURL.String + dr.ReplyOnce = replyOnce != 0 + return &dr, nil +} + +// HasRecord 是否已对该 chat_id 回复过(reply_once 用)。 +func (d *DefaultReplies) HasRecord(ctx context.Context, cookieID, chatID string) bool { + var n int + err := d.DB.QueryRowContext(ctx, + `SELECT 1 FROM default_reply_records WHERE cookie_id=? AND chat_id=? LIMIT 1`, + cookieID, chatID).Scan(&n) + return err == nil +} + +// AddRecord 记录已回复(reply_once 防重复)。 +func (d *DefaultReplies) AddRecord(ctx context.Context, cookieID, chatID string) error { + _, err := d.DB.ExecContext(ctx, + `INSERT OR IGNORE INTO default_reply_records (cookie_id, chat_id) VALUES (?, ?)`, + cookieID, chatID) + return err +} + +// ItemReplies 指定商品回复操作。 +type ItemReplies struct{ DB *sql.DB } + +// Get 取某账号某商品的指定回复。 +func (i *ItemReplies) Get(ctx context.Context, cookieID, itemID string) (*ItemReply, error) { + var ir ItemReply + var content sql.NullString + err := i.DB.QueryRowContext(ctx, + `SELECT item_id, cookie_id, reply_content FROM item_replay WHERE cookie_id=? AND item_id=?`, + cookieID, itemID).Scan(&ir.ItemID, &ir.CookieID, &content) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + ir.ReplyContent = content.String + return &ir, nil +} diff --git a/internal/db/repository_test.go b/internal/db/repository_test.go new file mode 100644 index 0000000..3a6852f --- /dev/null +++ b/internal/db/repository_test.go @@ -0,0 +1,157 @@ +package db + +import ( + "context" + "path/filepath" + "testing" +) + +func newTestDB(t *testing.T) (*Store, func()) { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "test.db") + db, err := Open(context.Background(), dbPath) + if err != nil { + t.Fatalf("Open: %v", err) + } + s := NewStore(db) + return s, func() { db.Close() } +} + +// TestPassword_LegacySHA256Compat 老 SHA-26 哈希能校验、且标记需升级。 +func TestPassword_LegacySHA256Compat(t *testing.T) { + legacy := legacySHA256("hunter2") + matched, needsUpgrade, err := VerifyPassword(legacy, "hunter2") + if err != nil || !matched || !needsUpgrade { + t.Fatalf("老哈希校验失败: matched=%v needsUpgrade=%v err=%v", matched, needsUpgrade, err) + } + matched2, _, _ := VerifyPassword(legacy, "wrong") + if matched2 { + t.Fatal("错误密码不应通过") + } +} + +// TestPassword_Bcrypt 新 bcrypt 哈希正常工作且不标记升级。 +func TestPassword_Bcrypt(t *testing.T) { + h, err := HashPassword("s3cret") + if err != nil { + t.Fatal(err) + } + matched, needsUpgrade, err := VerifyPassword(h, "s3cret") + if err != nil || !matched || needsUpgrade { + t.Fatalf("bcrypt 校验: matched=%v needsUpgrade=%v err=%v", matched, needsUpgrade, err) + } +} + +// TestUserLifecycle 创建→验证→升级→改密 全链路。 +func TestUserLifecycle(t *testing.T) { + s, cleanup := newTestDB(t) + defer cleanup() + ctx := context.Background() + + // 系统未初始化。 + if init, _ := s.Users.IsSystemInitialized(ctx); init { + t.Fatal("新库不应已初始化") + } + + ok, err := s.Users.Create(ctx, "admin", "admin@example.com", "pw123") + if err != nil || !ok { + t.Fatalf("Create: ok=%v err=%v", ok, err) + } + if err := s.Users.SetAdmin(ctx, "admin"); err != nil { + t.Fatalf("SetAdmin: %v", err) + } + if init, _ := s.Users.IsSystemInitialized(ctx); !init { + t.Fatal("创建 admin 后应已初始化") + } + + // 重复创建应失败。 + ok2, _ := s.Users.Create(ctx, "admin", "other@example.com", "x") + if ok2 { + t.Fatal("重复用户名应创建失败") + } + + // 验证密码 + bcrypt 升级路径(新用户直接 bcrypt,无需升级)。 + user, ok, err := s.Users.VerifyAndUpgrade(ctx, "admin", "pw123") + if err != nil || !ok || user == nil { + t.Fatalf("VerifyAndUpgrade: ok=%v err=%v", ok, err) + } + if !user.IsAdmin { + t.Fatal("应为管理员") + } + + // 改密后旧密码失效。 + if _, _ = s.Users.UpdatePassword(ctx, "admin", "newpw"); true { + } + _, okOld, _ := s.Users.VerifyAndUpgrade(ctx, "admin", "pw123") + if okOld { + t.Fatal("旧密码应失效") + } + _, okNew, _ := s.Users.VerifyAndUpgrade(ctx, "admin", "newpw") + if !okNew { + t.Fatal("新密码应可用") + } +} + +// TestSessionRoundTrip 创建→读取→删除。 +func TestSessionRoundTrip(t *testing.T) { + s, cleanup := newTestDB(t) + defer cleanup() + ctx := context.Background() + + s.Users.Create(ctx, "u1", "u1@e.com", "pw") + user, _, _ := s.Users.VerifyAndUpgrade(ctx, "u1", "pw") + + sid, err := s.Sessions.Create(ctx, user) + if err != nil { + t.Fatalf("Create session: %v", err) + } + got, err := s.Sessions.Get(ctx, sid) + if err != nil || got == nil || got.UserID != user.ID { + t.Fatalf("Get session: got=%+v err=%v", got, err) + } + if err := s.Sessions.Delete(ctx, sid); err != nil { + t.Fatalf("Delete: %v", err) + } + if _, err := s.Sessions.Get(ctx, sid); err != ErrNotFound { + t.Fatalf("删除后应 ErrNotFound,got err=%v", err) + } +} + +// TestCookieSaveRequiresInit 未初始化时 Save 应报错(不兜底 user_id=1)。 +func TestCookieSaveRequiresInit(t *testing.T) { + s, cleanup := newTestDB(t) + defer cleanup() + ctx := context.Background() + + err := s.Cookies.Save(ctx, "cid", "cookievalue", 0) + if err == nil { + t.Fatal("系统未初始化时 Save cookie 应报错") + } + + // 初始化 admin 后,用其 user_id 保存。 + s.Users.Create(ctx, "admin", "a@e.com", "pw") + admin, _ := s.Users.GetByUsername(ctx, "admin") + if err := s.Cookies.Save(ctx, "cid", "cookievalue", admin.ID); err != nil { + t.Fatalf("Save: %v", err) + } + d, err := s.Cookies.GetDetails(ctx, "cid") + if err != nil || d.Value != "cookievalue" || d.PauseDuration != 10 { + t.Fatalf("GetDetails: %+v err=%v", d, err) + } + all, _ := s.Cookies.AllForUser(ctx, admin.ID) + if all["cid"] != "cookievalue" { + t.Fatalf("AllForUser: %v", all) + } + if pd := s.Cookies.GetPauseDuration(ctx, "cid"); pd != 10 { + t.Fatalf("GetPauseDuration=%d want 10", pd) + } + if enabled, err := s.Cookies.GetAutoConfirm(ctx, "cid"); err != nil || !enabled { + t.Fatalf("GetAutoConfirm=%v want true, err=%v", enabled, err) + } + if _, err := s.DB.ExecContext(ctx, `UPDATE cookies SET auto_confirm=0 WHERE id=?`, "cid"); err != nil { + t.Fatalf("关闭 auto_confirm: %v", err) + } + if enabled, err := s.Cookies.GetAutoConfirm(ctx, "cid"); err != nil || enabled { + t.Fatalf("GetAutoConfirm=%v want false, err=%v", enabled, err) + } +} diff --git a/internal/db/sessions.go b/internal/db/sessions.go new file mode 100644 index 0000000..ad7c6b7 --- /dev/null +++ b/internal/db/sessions.go @@ -0,0 +1,91 @@ +package db + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "crypto/rand" + "encoding/base64" +) + +// SessionTTL 会话有效期(24 小时,与 Python SESSION_EXPIRE_SECONDS 一致)。 +const SessionTTL = 24 * time.Hour + +// Sessions 会话表操作(HttpOnly Cookie 会话)。 +type Sessions struct { + DB *sql.DB +} + +// Create 为已认证用户创建会话,返回 session_id。 +func (s *Sessions) Create(ctx context.Context, u *User) (string, error) { + sessionID, err := randomSessionID() + if err != nil { + return "", fmt.Errorf("生成 session id: %w", err) + } + now := time.Now().Unix() + expires := now + int64(SessionTTL.Seconds()) + isAdmin := 0 + if u.IsAdmin { + isAdmin = 1 + } + _, err = s.DB.ExecContext(ctx, + `INSERT INTO sessions (session_id, user_id, username, is_admin, expires_at, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, + sessionID, u.ID, u.Username, isAdmin, expires, now) + if err != nil { + return "", fmt.Errorf("写入 session: %w", err) + } + return sessionID, nil +} + +// Get 取会话;过期或不存在返回 ErrNotFound,并清理过期记录。 +func (s *Sessions) Get(ctx context.Context, sessionID string) (*Session, error) { + if sessionID == "" { + return nil, ErrNotFound + } + var sess Session + var isAdmin int + err := s.DB.QueryRowContext(ctx, + `SELECT session_id, user_id, username, is_admin, expires_at FROM sessions WHERE session_id=?`, + sessionID).Scan(&sess.SessionID, &sess.UserID, &sess.Username, &isAdmin, &sess.ExpiresAt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + sess.IsAdmin = isAdmin != 0 + if sess.ExpiresAt <= time.Now().Unix() { + _, _ = s.DB.ExecContext(ctx, `DELETE FROM sessions WHERE session_id=?`, sessionID) + return nil, ErrNotFound + } + return &sess, nil +} + +// Delete 删除会话(登出)。 +func (s *Sessions) Delete(ctx context.Context, sessionID string) error { + _, err := s.DB.ExecContext(ctx, `DELETE FROM sessions WHERE session_id=?`, sessionID) + return err +} + +// DeleteExpired 清理所有过期会话(可由定时任务调用)。 +func (s *Sessions) DeleteExpired(ctx context.Context) (int64, error) { + res, err := s.DB.ExecContext(ctx, `DELETE FROM sessions WHERE expires_at <= ?`, time.Now().Unix()) + if err != nil { + return 0, err + } + n, _ := res.RowsAffected() + return n, nil +} + +// randomSessionID 生成 URL 安全的随机会话 ID(对应 Python secrets.token_urlsafe(32))。 +func randomSessionID() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} diff --git a/internal/db/store.go b/internal/db/store.go new file mode 100644 index 0000000..d7252cd --- /dev/null +++ b/internal/db/store.go @@ -0,0 +1,45 @@ +package db + +import "database/sql" + +// Store 聚合各 repository,供上层(HTTP server、account supervisor 等)统一持有。 +type Store struct { + DB *sql.DB + Users *Users + Sessions *Sessions + Cookies *Cookies + Items *Items + Cards *Cards + DeliveryRules *DeliveryRules + Orders *Orders + Keywords *Keywords + DefaultReps *DefaultReplies + ItemReps *ItemReplies + AIReply *AIReply + Notifications *Notifications + Settings *SystemSettings + WSMessages *WSMessageStore + PublishBatches *ItemPublishBatches +} + +// NewStore 基于 *sql.DB 构造聚合 store。 +func NewStore(db *sql.DB) *Store { + return &Store{ + DB: db, + Users: &Users{DB: db}, + Sessions: &Sessions{DB: db}, + Cookies: &Cookies{DB: db}, + Items: &Items{DB: db}, + Cards: &Cards{DB: db}, + DeliveryRules: &DeliveryRules{DB: db}, + Orders: &Orders{DB: db}, + Keywords: &Keywords{DB: db}, + DefaultReps: &DefaultReplies{DB: db}, + ItemReps: &ItemReplies{DB: db}, + AIReply: &AIReply{DB: db}, + Notifications: &Notifications{DB: db}, + Settings: &SystemSettings{DB: db}, + WSMessages: &WSMessageStore{DB: db}, + PublishBatches: &ItemPublishBatches{DB: db}, + } +} diff --git a/internal/db/users.go b/internal/db/users.go new file mode 100644 index 0000000..bb0f20d --- /dev/null +++ b/internal/db/users.go @@ -0,0 +1,182 @@ +package db + +import ( + "context" + "database/sql" + "errors" + "fmt" +) + +// ErrNotFound 未找到记录。 +var ErrNotFound = errors.New("记录不存在") + +// ErrUsernameTaken 表示目标用户名已被其他用户占用。 +var ErrUsernameTaken = errors.New("用户名已存在") + +// Users 用户相关查询。所有方法都直接接受 *sql.DB,由调用方控制事务边界。 +type Users struct { + DB *sql.DB +} + +// IsSystemInitialized 系统是否已初始化(至少存在 admin 用户)。 +// 对应 Python db_manager.is_system_initialized()。 +func (u *Users) IsSystemInitialized(ctx context.Context) (bool, error) { + var exists int + err := u.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE is_admin=1)`).Scan(&exists) + if err != nil { + return false, fmt.Errorf("检查系统初始化: %w", err) + } + return exists == 1, nil +} + +// GetAdmin 返回首个管理员账号。 +func (u *Users) GetAdmin(ctx context.Context) (*User, error) { + return u.scanUser(ctx, `SELECT id, username, email, password_hash, is_active, is_admin, created_at, updated_at + FROM users WHERE is_admin=1 ORDER BY id LIMIT 1`) +} + +// Create 创建用户,密码用 bcrypt 哈希。 +// 用户名或邮箱重复时返回 false(对应 Python IntegrityError → return False)。 +func (u *Users) Create(ctx context.Context, username, email, plainPassword string) (bool, error) { + hash, err := HashPassword(plainPassword) + if err != nil { + return false, fmt.Errorf("哈希密码: %w", err) + } + res, err := u.DB.ExecContext(ctx, + `INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)`, + username, email, hash) + if err != nil { + // UNIQUE 冲突 → 用户名/邮箱已存在。 + return false, nil + } + n, _ := res.RowsAffected() + return n > 0, nil +} + +// GetByUsername 按用户名查询。 +func (u *Users) GetByUsername(ctx context.Context, username string) (*User, error) { + return u.scanUser(ctx, `SELECT id, username, email, password_hash, is_active, is_admin, created_at, updated_at + FROM users WHERE username = ?`, username) +} + +// GetByEmail 按邮箱查询。 +func (u *Users) GetByEmail(ctx context.Context, email string) (*User, error) { + return u.scanUser(ctx, `SELECT id, username, email, password_hash, is_active, is_admin, created_at, updated_at + FROM users WHERE email = ?`, email) +} + +// GetByID 按 ID 查询。 +func (u *Users) GetByID(ctx context.Context, id int64) (*User, error) { + return u.scanUser(ctx, `SELECT id, username, email, password_hash, is_active, is_admin, created_at, updated_at + FROM users WHERE id = ?`, id) +} + +// VerifyAndUpgrade 验证密码;若命中老 SHA-256 哈希则静默升级到 bcrypt。 +// 返回 (user, ok)。ok=false 表示密码错误或用户不存在/未激活。 +func (u *Users) VerifyAndUpgrade(ctx context.Context, username, plainPassword string) (*User, bool, error) { + user, err := u.GetByUsername(ctx, username) + if err != nil { + if errors.Is(err, ErrNotFound) { + return nil, false, nil + } + return nil, false, err + } + if !user.IsActive { + return nil, false, nil + } + matched, needsUpgrade, err := VerifyPassword(user.PasswordHash, plainPassword) + if err != nil || !matched { + return nil, false, err + } + if needsUpgrade { + // 静默升级到 bcrypt。 + if hash, e := HashPassword(plainPassword); e == nil { + _, _ = u.DB.ExecContext(ctx, + `UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`, + hash, user.ID) + user.PasswordHash = hash + } + } + return user, true, nil +} + +// UpdatePassword 更新密码(bcrypt)。返回是否找到用户。 +func (u *Users) UpdatePassword(ctx context.Context, username, plainPassword string) (bool, error) { + hash, err := HashPassword(plainPassword) + if err != nil { + return false, fmt.Errorf("哈希密码: %w", err) + } + res, err := u.DB.ExecContext(ctx, + `UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE username=?`, + hash, username) + if err != nil { + return false, err + } + n, _ := res.RowsAffected() + return n > 0, nil +} + +// UpdateCredentials 原子更新用户名及可选密码,并撤销该用户的全部登录会话。 +func (u *Users) UpdateCredentials(ctx context.Context, userID int64, username, plainPassword string) error { + tx, err := u.DB.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + var exists int + if err := tx.QueryRowContext(ctx, + `SELECT EXISTS(SELECT 1 FROM users WHERE username=? AND id<>?)`, username, userID).Scan(&exists); err != nil { + return err + } + if exists != 0 { + return ErrUsernameTaken + } + + var res sql.Result + if plainPassword != "" { + hash, err := HashPassword(plainPassword) + if err != nil { + return fmt.Errorf("哈希密码: %w", err) + } + res, err = tx.ExecContext(ctx, + `UPDATE users SET username=?, password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`, + username, hash, userID) + } else { + res, err = tx.ExecContext(ctx, + `UPDATE users SET username=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`, username, userID) + } + if err != nil { + return err + } + if rows, _ := res.RowsAffected(); rows == 0 { + return ErrNotFound + } + if _, err := tx.ExecContext(ctx, `DELETE FROM sessions WHERE user_id=?`, userID); err != nil { + return err + } + return tx.Commit() +} + +// SetAdmin 标记用户为管理员(init-admin CLI 用)。 +func (u *Users) SetAdmin(ctx context.Context, username string) error { + _, err := u.DB.ExecContext(ctx, `UPDATE users SET is_admin=1 WHERE username=?`, username) + return err +} + +func (u *Users) scanUser(ctx context.Context, query string, args ...any) (*User, error) { + var usr User + var isActive, isAdmin int + err := u.DB.QueryRowContext(ctx, query, args...).Scan( + &usr.ID, &usr.Username, &usr.Email, &usr.PasswordHash, + &isActive, &isAdmin, &usr.CreatedAt, &usr.UpdatedAt) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + usr.IsActive = isActive != 0 + usr.IsAdmin = isAdmin != 0 + return &usr, nil +} diff --git a/internal/db/ws_message.go b/internal/db/ws_message.go new file mode 100644 index 0000000..7885919 --- /dev/null +++ b/internal/db/ws_message.go @@ -0,0 +1,34 @@ +package db + +import ( + "context" + "database/sql" +) + +// WSMessage 原始 WS 收包记录。 +type WSMessage struct { + CookieID string + Direction string + RawText string + ParsedJSON string + MessageKind string + ParseStatus string + Error string +} + +// WSMessageStore 保存 WS 消息。 +type WSMessageStore struct{ DB *sql.DB } + +// Add 记录一条 WS 消息。 +func (w *WSMessageStore) Add(ctx context.Context, m WSMessage) error { + if m.Direction == "" { + m.Direction = "in" + } + if m.ParseStatus == "" { + m.ParseStatus = "raw" + } + _, err := w.DB.ExecContext(ctx, + "INSERT INTO ws_messages (cookie_id, direction, raw_text, parsed_json, message_kind, parse_status, error, created_at) VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP)", + m.CookieID, m.Direction, m.RawText, m.ParsedJSON, m.MessageKind, m.ParseStatus, m.Error) + return err +} diff --git a/internal/engine/account.go b/internal/engine/account.go new file mode 100644 index 0000000..73e49f4 --- /dev/null +++ b/internal/engine/account.go @@ -0,0 +1,641 @@ +// Package engine 实现单账号运行时:WebSocket 连接生命周期、token 刷新、 +// 消息分发主循环(信号量限并发 + 防抖 + 去重)、重连策略。 +// +// 移植自 Python XianyuAutoAsync.py 的 main() / handle_message / +// _handle_message_with_semaphore / _schedule_debounced_reply / token_refresh_loop。 +// +// 业务逻辑(自动发货、回复)在 Phase 3 通过 Handler 接口注入, +// Phase 2 先搭好骨架并跑通"收消息→解密→去重→防抖→回调"。 +package engine + +import ( + "context" + "fmt" + "log/slog" + "strings" + "sync" + "time" + + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/protocol" + "xianyu-go/internal/xianyu/ws" +) + +// 常量,与 Python 端一致。 +const ( + MaxConnectionFailures = 5 // 连续失败上限,触发密码登录刷新 + MessageSemaphoreSize = 100 // 并发消息处理上限 + MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复 + MessageExpireTime = time.Hour // 去重有效期 + ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理 + HeartbeatInterval = 15 * time.Second + TokenRefreshInterval = 1 * time.Hour + TokenRefreshMinGap = time.Minute + MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie + PasswordLoginMinGap = 30 * time.Minute +) + +// Handler 是业务逻辑注入点(Phase 3 实现)。 +// 收到一条防抖后的聊天消息时回调;返回错误仅记录日志、不影响主循环。 +type Handler interface { + HandleChatMessage(ctx context.Context, m ChatMessage) error + // HandleSystemMessage 处理订单状态等非聊天消息(如 redReminder)。 + HandleSystemMessage(ctx context.Context, m SystemMessage) error + // OnPasswordLoginRefresh 连续失败触发密码登录刷新(Phase 5 sidecar);返回是否成功。 + OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool +} + +// ChatMessage 防抖后投递给业务层的一条聊天消息。 +type ChatMessage struct { + AccountID string // cookie_id + CookieStr string + ChatID string + SenderUserID string + SenderName string + Text string + ItemID string + Raw map[string]any // 解密后的完整消息 +} + +// SystemMessage 订单状态等系统消息。 +type SystemMessage struct { + AccountID string + CookieStr string + RedReminder string // message["3"]["redReminder"],订单状态文本 + UserID string + Raw map[string]any +} + +// RuntimeStatus 是账号引擎的实时连接状态,不写入数据库。 +type RuntimeStatus struct { + State string `json:"state"` + Message string `json:"message,omitempty"` + Connected bool `json:"connected"` + Failures int `json:"failures"` + UpdatedAt time.Time `json:"updated_at"` +} + +const ( + RuntimeStarting = "starting" + RuntimeConnecting = "connecting" + RuntimeOnline = "online" + RuntimeReconnecting = "reconnecting" + RuntimeAuthExpired = "auth_expired" + RuntimeVerificationRequired = "verification_required" + RuntimeError = "error" + RuntimeStopped = "stopped" +) + +// Account 单账号运行时。 +type Account struct { + CookieID string + CookieStr string + UserID string // unb(myid) + + store *db.Store + mtop *mtop.Client + wsDialer wsDialer + handler Handler + logger *slog.Logger + + // 运行时状态(受 mu 保护) + mu sync.Mutex + currentToken string + deviceID string + connFailures int + lastMsgReceived time.Time + lastTokenRefresh time.Time + lastPasswordLogin time.Time + runtimeState string + runtimeMessage string + runtimeUpdatedAt time.Time + stopFn context.CancelFunc + stopped bool + conn *ws.Conn + + // 去重 + dedupMu sync.Mutex + processed map[string]time.Time + + // 防抖:chat_id → 防抖句柄 + debounceMu sync.Mutex + debounceTimers map[string]*debounceEntry + + // 消息处理信号量 + sem chan struct{} + + delivery *DeliveryService + reply *ReplyService +} + +type debounceEntry struct { + timer *time.Timer + lastMsg ChatMessage + deadline time.Time +} + +// wsDialer 抽象 ws.Dial,便于测试替身。 +type wsDialer interface { + Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (*ws.Conn, error) +} + +type defaultDialer struct{} + +func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (*ws.Conn, error) { + return ws.Dial(ctx, cfg, logger) +} + +// Config 构造 Account 所需依赖。 +type Config struct { + CookieID string + CookieStr string + Store *db.Store + Handler Handler + Logger *slog.Logger +} + +// New 构造单账号运行时(未启动)。 +func New(cfg Config) *Account { + logger := cfg.Logger + if logger == nil { + logger = slog.Default() + } + cookies := protocol.TransCookies(cfg.CookieStr) + myid := cookies["unb"] + a := &Account{ + CookieID: cfg.CookieID, + CookieStr: cfg.CookieStr, + UserID: myid, + store: cfg.Store, + mtop: &mtop.Client{}, + wsDialer: defaultDialer{}, + handler: cfg.Handler, + logger: logger.With("account", cfg.CookieID), + deviceID: protocol.GenerateDeviceID(myid), + processed: make(map[string]time.Time), + debounceTimers: make(map[string]*debounceEntry), + sem: make(chan struct{}, MessageSemaphoreSize), + runtimeState: RuntimeStarting, + runtimeMessage: "正在启动账号服务", + runtimeUpdatedAt: time.Now(), + } + if cfg.Store != nil { + var orderFetcher OrderDetailFetcher + if fetcher, ok := cfg.Handler.(OrderDetailFetcher); ok { + orderFetcher = fetcher + } + a.delivery = NewDeliveryService(cfg.CookieID, cfg.Store, a, orderFetcher, nil, logger) + a.delivery.SetCookieSource(a.currentCookieStr, a.replaceCookieStr) + a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger) + } + return a +} + +// Run 阻塞运行账号主循环,直到 ctx 取消或不可恢复错误。 +// 调用方应在独立 goroutine 中运行;Stop 可优雅停止。 +func (a *Account) Run(parent context.Context) error { + ctx, cancel := context.WithCancel(parent) + a.mu.Lock() + a.stopFn = cancel + a.mu.Unlock() + + for { + if ctx.Err() != nil { + return ctx.Err() + } + // 账号是否被禁用。 + if !a.store.Cookies.GetStatus(ctx, a.CookieID) { + a.logger.Info("账号已禁用,停止主循环") + return nil + } + + // 1) 刷新 token。 + token, cookieStr, err := a.refreshToken(ctx) + if err != nil { + a.logger.Error("刷新 token 失败", "err", err) + a.mu.Lock() + a.connFailures++ + failures := a.connFailures + a.mu.Unlock() + a.setRuntimeError(err) + if failures >= MaxConnectionFailures { + if err := a.handleMaxFailures(ctx); err != nil { + return err + } + continue + } + if sleepCtx(ctx, a.retryDelay("token_refresh")) != nil { + return ctx.Err() + } + continue + } + a.mu.Lock() + a.currentToken = token + a.CookieStr = cookieStr + a.connFailures = 0 + a.mu.Unlock() + a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务") + + // 2) 连接 WS + 注册。 + var recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) + if a.store != nil && a.store.WSMessages != nil { + recorder = func(direction, rawText, parsedJSON, parseStatus, errMsg string) { + _ = a.store.WSMessages.Add(context.Background(), db.WSMessage{ + CookieID: a.CookieID, + Direction: direction, + RawText: rawText, + ParsedJSON: parsedJSON, + MessageKind: "", + ParseStatus: parseStatus, + Error: errMsg, + }) + } + } + a.mu.Lock() + deviceID := a.deviceID + a.mu.Unlock() + conn, err := a.wsDialer.Dial(ctx, ws.Config{ + CookieStr: cookieStr, + DeviceID: deviceID, + AccessToken: token, + Recorder: recorder, + }, a.logger) + if err != nil { + a.logger.Error("WS 连接失败", "err", err) + a.mu.Lock() + a.connFailures++ + failures := a.connFailures + a.mu.Unlock() + a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试") + if failures >= MaxConnectionFailures { + if err := a.handleMaxFailures(ctx); err != nil { + return err + } + continue + } + if sleepCtx(ctx, a.retryDelay("ws_dial")) != nil { + return ctx.Err() + } + continue + } + a.mu.Lock() + a.conn = conn + a.mu.Unlock() + a.setRuntimeState(RuntimeOnline, "消息服务连接正常") + + // 3) 心跳 + 消息接收。 + hbCtx, hbCancel := context.WithCancel(ctx) + var hbErr error + go func() { + hbErr = conn.HeartbeatLoop(hbCtx, HeartbeatInterval) + hbCancel() + }() + + recvErr := conn.ReceiveLoop(ctx, a.dispatch) + hbCancel() + _ = conn.Close() + + // 连接结束:清 token,统计失败,决定重连或密码刷新。 + a.mu.Lock() + a.currentToken = "" + a.conn = nil + a.connFailures++ + failures := a.connFailures + a.mu.Unlock() + a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,稍后自动重连") + a.logger.Warn("WS 连接结束", "err", recvErr, "failures", failures, "heartbeat_err", hbErr) + + if failures >= MaxConnectionFailures { + if err := a.handleMaxFailures(ctx); err != nil { + return err + } + continue + } + if sleepCtx(ctx, a.retryDelay(errString(recvErr))) != nil { + return ctx.Err() + } + } +} + +// Stop 优雅停止。 +func (a *Account) Stop() { + a.mu.Lock() + defer a.mu.Unlock() + if a.stopped { + return + } + a.stopped = true + a.runtimeState = RuntimeStopped + a.runtimeMessage = "账号服务已停止" + a.runtimeUpdatedAt = time.Now() + if a.stopFn != nil { + a.stopFn() + } + // 取消所有防抖定时器。 + a.debounceMu.Lock() + for _, e := range a.debounceTimers { + if e.timer != nil { + e.timer.Stop() + } + } + a.debounceTimers = make(map[string]*debounceEntry) + a.debounceMu.Unlock() +} + +// handleMaxFailures 连续失败达上限:尝试密码登录刷新;失败则返回 err 触发上层重启实例。 +func (a *Account) handleMaxFailures(ctx context.Context) error { + a.logger.Warn("连续失败达上限,触发密码登录刷新", "failures", MaxConnectionFailures) + a.mu.Lock() + lastMsg := a.lastMsgReceived + lastLogin := a.lastPasswordLogin + a.mu.Unlock() + if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown { + a.logger.Warn("最近仍收到消息,跳过密码登录刷新", "cooldown", MessageCooldown) + a.resetFailures() + return sleepCtx(ctx, a.retryDelay("recent_message_skip_password_login")) + } + if !lastLogin.IsZero() && time.Since(lastLogin) < PasswordLoginMinGap { + remain := PasswordLoginMinGap - time.Since(lastLogin) + a.logger.Warn("密码登录刷新冷却中,跳过本次刷新", "remain", remain.Round(time.Second)) + a.resetFailures() + return sleepCtx(ctx, minDuration(remain, time.Minute)) + } + + a.mu.Lock() + a.lastPasswordLogin = time.Now() + a.mu.Unlock() + if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) { + if d, err := a.store.Cookies.GetDetails(ctx, a.CookieID); err == nil && d != nil && d.Value != "" { + a.replaceCookieStr(d.Value) + } + a.logger.Info("密码登录刷新成功,重置失败计数") + a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接") + a.resetFailures() + return sleepCtx(ctx, 2*time.Second) + } + a.resetFailures() + a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录") + return fmt.Errorf("账号 %s 连续失败 %d 次且密码登录刷新失败,需重启实例", a.CookieID, MaxConnectionFailures) +} + +func (a *Account) resetFailures() { + a.mu.Lock() + defer a.mu.Unlock() + a.connFailures = 0 +} + +// retryDelay 移植自 _calculate_retry_delay。 +func (a *Account) retryDelay(errMsg string) time.Duration { + a.mu.Lock() + f := a.connFailures + a.mu.Unlock() + if f < 1 { + f = 1 + } + secs := 0 + switch { + case contains(errMsg, "no close frame received or sent"): + secs = min(3*f, 15) + case contains(errMsg, "connection refused") || contains(errMsg, "timeout"): + secs = min(10*f, 60) + default: + secs = min(5*f, 30) + } + return time.Duration(secs) * time.Second +} + +// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。 +func (a *Account) refreshToken(ctx context.Context) (string, string, error) { + a.mu.Lock() + cookieStr := a.CookieStr + last := a.lastTokenRefresh + if !last.IsZero() && time.Since(last) < TokenRefreshMinGap { + remain := TokenRefreshMinGap - time.Since(last) + a.mu.Unlock() + a.logger.Info("等待 token 刷新冷却", "remain", remain.Round(time.Second)) + if err := sleepCtx(ctx, remain); err != nil { + return "", "", err + } + a.mu.Lock() + cookieStr = a.CookieStr + } + a.lastTokenRefresh = time.Now() + a.mu.Unlock() + deviceID := strings.TrimSpace(a.deviceID) + if deviceID == "" { + if unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" { + deviceID = protocol.GenerateDeviceID(unb) + a.mu.Lock() + a.deviceID = deviceID + a.mu.Unlock() + } + } + res, err := a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID) + if res != nil && res.UpdatedCookies != "" && res.UpdatedCookies != cookieStr { + a.replaceCookieStr(res.UpdatedCookies) + cookieStr = res.UpdatedCookies + if a.store != nil { + if d, e := a.store.Cookies.GetDetails(ctx, a.CookieID); e == nil { + _ = a.store.Cookies.Save(ctx, a.CookieID, res.UpdatedCookies, d.UserID) + } + } + } + if err != nil { + return "", "", err + } + if res == nil { + return "", "", fmt.Errorf("token API 未返回结果") + } + // 若 cookie 被刷新,持久化回 DB(与 Python update_config_cookies 一致)。 + if res.UpdatedCookies != cookieStr { + a.mu.Lock() + a.CookieStr = res.UpdatedCookies + cookieStr = res.UpdatedCookies + a.mu.Unlock() + if a.store != nil { + // 保留原 user_id:用 GetDetails 取后回写。 + if d, e := a.store.Cookies.GetDetails(ctx, a.CookieID); e == nil { + _ = a.store.Cookies.Save(ctx, a.CookieID, res.UpdatedCookies, d.UserID) + } + } + } + return res.AccessToken, cookieStr, nil +} + +// RuntimeStatus 返回账号当前连接状态的线程安全快照。 +func (a *Account) RuntimeStatus() RuntimeStatus { + a.mu.Lock() + defer a.mu.Unlock() + return RuntimeStatus{ + State: a.runtimeState, + Message: a.runtimeMessage, + Connected: a.conn != nil && a.runtimeState == RuntimeOnline, + Failures: a.connFailures, + UpdatedAt: a.runtimeUpdatedAt, + } +} + +func (a *Account) setRuntimeState(state, message string) { + a.mu.Lock() + defer a.mu.Unlock() + a.runtimeState = state + a.runtimeMessage = message + a.runtimeUpdatedAt = time.Now() +} + +func (a *Account) setRuntimeError(err error) { + msg := strings.ToLower(errString(err)) + switch { + case strings.Contains(msg, "验证"), strings.Contains(msg, "captcha"), strings.Contains(msg, "risk"), strings.Contains(msg, "rgv587"), strings.Contains(msg, "fail_sys_user_validate"): + a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证") + case strings.Contains(msg, "登录凭证已失效"), strings.Contains(msg, "fail_sys_token_exoired"), strings.Contains(msg, "fail_sys_token_expired"), strings.Contains(msg, "cookie 缺少 unb"): + a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录") + default: + a.setRuntimeState(RuntimeReconnecting, "连接异常,系统将在限速后自动重试") + } +} + +// SendText 通过当前 WebSocket 给买家发送文本消息。 +func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) error { + text = strings.TrimSpace(text) + if text == "" { + return nil + } + conn, myID, err := a.currentSenderState() + if err != nil { + return err + } + sendCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + return conn.SendText(sendCtx, myID, chatID, toUserID, text) +} + +// SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。 +func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error { + imageURL = strings.TrimSpace(imageURL) + if imageURL == "" { + return nil + } + if strings.HasPrefix(imageURL, "/static/") || strings.HasPrefix(imageURL, "static/") { + return fmt.Errorf("Go 运行时暂不支持本地图片自动上传到闲鱼 CDN: %s", imageURL) + } + conn, myID, err := a.currentSenderState() + if err != nil { + return err + } + sendCtx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + return conn.SendImage(sendCtx, myID, chatID, toUserID, imageURL, 800, 600) +} + +// ManualFullDelivery 对已存在订单执行完整手动发货:匹配卡券、确认发货、发送给买家并更新本地订单。 +func (a *Account) ManualFullDelivery(ctx context.Context, order *db.Order) (int, error) { + if order == nil { + return 0, fmt.Errorf("订单不存在") + } + if a.delivery == nil { + return 0, fmt.Errorf("账号 %s 未初始化发货服务", a.CookieID) + } + if strings.TrimSpace(order.ItemID) == "" { + return 0, fmt.Errorf("订单缺少商品ID,无法匹配发货规则") + } + if strings.TrimSpace(order.BuyerID) == "" { + return 0, fmt.Errorf("订单缺少买家ID,无法发送卡券") + } + if strings.TrimSpace(order.ChatID) == "" { + return 0, fmt.Errorf("订单缺少 chat_id,无法发送卡券;请等待买家发消息后再试") + } + if _, _, err := a.currentSenderState(); err != nil { + return 0, err + } + + quantity := 1 + if a.store.Items.MultiQuantityDelivery(ctx, a.CookieID, order.ItemID) { + if q := parseIntSafe(order.Quantity); q > 1 { + quantity = q + } + } + contents, err := a.delivery.collectDeliveryContentsWithSpec(ctx, order.ItemID, order.OrderID, order.BuyerID, order.SpecName, order.SpecValue, quantity) + if err != nil { + return 0, err + } + if len(contents) == 0 { + return 0, fmt.Errorf("未匹配到发货规则或卡券获取失败") + } + for i, content := range contents { + if err := a.delivery.sendContent(ctx, content, order.ChatID, order.BuyerID); err != nil { + return i, err + } + if len(contents) > 1 && i < len(contents)-1 { + if err := sleepCtx(ctx, time.Second); err != nil { + return i + 1, err + } + } + } + a.delivery.markDeliverySent(order.OrderID) + sysShip := true + _ = a.store.Orders.Upsert(ctx, order.OrderID, db.OrderUpsertOpts{ + CookieID: order.CookieID, + OrderStatus: "shipped", + SystemShipped: &sysShip, + ItemID: order.ItemID, + BuyerID: order.BuyerID, + ReceiverName: order.ReceiverName, + ReceiverPhone: order.ReceiverPhone, + ReceiverAddr: order.ReceiverAddr, + ReceiverCity: order.ReceiverCity, + ChatID: order.ChatID, + SpecName: order.SpecName, + SpecValue: order.SpecValue, + Quantity: order.Quantity, + Amount: order.Amount, + }) + return len(contents), nil +} + +func (a *Account) currentSenderState() (*ws.Conn, string, error) { + a.mu.Lock() + defer a.mu.Unlock() + if a.conn == nil { + return nil, "", fmt.Errorf("账号 %s 当前没有可用 WebSocket 连接", a.CookieID) + } + myID := strings.TrimSpace(a.UserID) + if myID == "" { + myID = protocol.TransCookies(a.CookieStr)["unb"] + } + if myID == "" { + return nil, "", fmt.Errorf("账号 %s 缺少 unb,无法发送消息", a.CookieID) + } + return a.conn, myID, nil +} + +func (a *Account) replaceCookieStr(cookieStr string) { + a.mu.Lock() + defer a.mu.Unlock() + a.CookieStr = cookieStr + if unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" { + if a.UserID != "" && a.UserID != unb { + a.deviceID = protocol.GenerateDeviceID(unb) + } + a.UserID = unb + if a.deviceID == "" { + a.deviceID = protocol.GenerateDeviceID(unb) + } + } +} + +// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。 +func (a *Account) UpdateCookie(cookieStr string) { + if strings.TrimSpace(cookieStr) == "" { + return + } + a.replaceCookieStr(cookieStr) +} + +func minDuration(a, b time.Duration) time.Duration { + if a < b { + return a + } + return b +} diff --git a/internal/engine/ai.go b/internal/engine/ai.go new file mode 100644 index 0000000..fc9ce26 --- /dev/null +++ b/internal/engine/ai.go @@ -0,0 +1,186 @@ +// ai.go AI 回复实现(优先级3)。调用 OpenAI 兼容 chat completions 接口。 +// 移植自 Python ai_reply_engine.generate_reply 的核心:用商品信息 + 自定义 prompt 生成回复。 +// 砍价/对话历史追踪(bargain_count、ai_conversations)留后续完善,本实现为单轮无状态回复。 +package engine + +import ( + "context" + "fmt" + "log/slog" + "regexp" + "strings" + + "github.com/sashabaranov/go-openai" + + "xianyu-go/internal/db" +) + +const ( + defaultAIBaseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1" + defaultAIModel = "qwen-plus" +) + +// AIReplierImpl AI 回复实现。 +type AIReplierImpl struct { + cookieID string + store *db.Store + logger *slog.Logger +} + +// NewAIReplier 构造。 +func NewAIReplier(cookieID string, store *db.Store, logger *slog.Logger) *AIReplierImpl { + if logger == nil { + logger = slog.Default() + } + return &AIReplierImpl{ + cookieID: cookieID, + store: store, + logger: logger.With("account", cookieID, "subsys", "ai"), + } +} + +// Reply 实现 AIReplier 接口。 +func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error) { + cfg, err := a.store.AIReply.Get(ctx, a.cookieID) + if err != nil || cfg == nil || !cfg.AIEnabled { + return nil, nil // 未启用 AI + } + aiCfg, err := a.globalAIConfig(ctx) + if err != nil { + return nil, fmt.Errorf("读取全局 AI 配置失败: %w", err) + } + if aiCfg.APIKey == "" { + a.logger.Warn("AI 已启用但未配置 APIKey") + return nil, nil + } + + // 取商品信息构造 system prompt。 + itemTitle, itemPrice, itemDesc := a.itemInfo(ctx, m.ItemID) + systemPrompt := buildSystemPrompt(cfg.CustomPrompts, itemTitle, itemPrice, itemDesc, cfg.MaxDiscountPercent, cfg.MaxDiscountAmount) + + // 调 OpenAI 兼容接口。 + clientCfg := openai.DefaultConfig(aiCfg.APIKey) + if aiCfg.BaseURL != "" { + clientCfg.BaseURL = aiCfg.BaseURL + } + client := openai.NewClientWithConfig(clientCfg) + + resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{ + Model: aiCfg.Model, + Messages: []openai.ChatCompletionMessage{ + {Role: openai.ChatMessageRoleSystem, Content: systemPrompt}, + {Role: openai.ChatMessageRoleUser, Content: m.Text}, + }, + Temperature: 0.7, + }) + if err != nil { + return nil, fmt.Errorf("AI 调用失败: %w", err) + } + if len(resp.Choices) == 0 { + return nil, nil + } + reply := strings.TrimSpace(resp.Choices[0].Message.Content) + if reply == "" { + return nil, nil + } + return &ReplyResult{Text: reply}, nil +} + +type globalAIConfig struct { + APIKey string + BaseURL string + Model string +} + +func (a *AIReplierImpl) globalAIConfig(ctx context.Context) (*globalAIConfig, error) { + apiKey, err := a.store.Settings.Get(ctx, "ai_api_key") + if err != nil { + return nil, err + } + baseURL, err := a.store.Settings.Get(ctx, "ai_api_url") + if err != nil { + return nil, err + } + if strings.TrimSpace(baseURL) == "" { + baseURL, err = a.store.Settings.Get(ctx, "ai_base_url") + if err != nil { + return nil, err + } + } + model, err := a.store.Settings.Get(ctx, "ai_model") + if err != nil { + return nil, err + } + + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + if baseURL == "" { + baseURL = defaultAIBaseURL + } + model = strings.TrimSpace(model) + if model == "" { + model = defaultAIModel + } + return &globalAIConfig{ + APIKey: strings.TrimSpace(apiKey), + BaseURL: baseURL, + Model: model, + }, nil +} + +// itemInfo 取商品标题/价格/描述。 +func (a *AIReplierImpl) itemInfo(ctx context.Context, itemID string) (title string, price float64, desc string) { + it, err := a.store.Items.Get(ctx, a.cookieID, itemID) + if err != nil || it == nil { + return "商品信息获取失败", 0, "暂无商品描述" + } + title = it.ItemTitle + if title == "" { + title = "未知商品" + } + price = parsePrice(it.ItemPrice) + desc = it.ItemDetail + if desc == "" { + desc = "暂无商品描述" + } + return +} + +// buildSystemPrompt 构造 system 提示词。 +// 优先用自定义 prompt,否则用默认模板(含商品信息)。 +func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemDesc string, maxDiscountPercent, maxDiscountAmount int) string { + if strings.TrimSpace(customPrompts) != "" { + return strings.ReplaceAll(customPrompts, "{item_title}", itemTitle) + } + if maxDiscountPercent <= 0 { + maxDiscountPercent = 10 + } + if maxDiscountAmount <= 0 { + maxDiscountAmount = 100 + } + return fmt.Sprintf(`你是闲鱼卖家的自动回复助手。请根据商品信息友好地回复买家。 + +商品信息: +- 标题:%s +- 价格:%.2f 元 +- 描述:%s + +要求: +1. 语气友好自然,像真人卖家 +2. 回答简洁,不要过长 +3. 涉及价格让步时,最多优惠 %.0f%% 或 %.0f 元 +4. 不要编造商品没有的功能 +5. 直接回复内容,不要加引号或解释`, itemTitle, itemPrice, itemDesc, float64(maxDiscountPercent), float64(maxDiscountAmount)) +} + +var priceRe = regexp.MustCompile(`[^\d.]`) + +// parsePrice 复刻 Python _parse_price:移除非数字字符后转 float。 +func parsePrice(s string) float64 { + cleaned := priceRe.ReplaceAllString(s, "") + if cleaned == "" { + return 0 + } + var f float64 + fmt.Sscanf(cleaned, "%f", &f) + return f +} diff --git a/internal/engine/delivery.go b/internal/engine/delivery.go new file mode 100644 index 0000000..6d03216 --- /dev/null +++ b/internal/engine/delivery.go @@ -0,0 +1,882 @@ +// delivery.go 实现卡密自动发货全流程。 +// 移植自 Python _handle_auto_delivery + _auto_delivery: +// +// 商品归属校验 → 提取 order_id → 四重防重(延迟锁/冷却 + 加锁后复查) +// → 多规格/多数量检查 → 规则双向模糊匹配 → 延时 → 确认发货(mtop consign) +// → 入库 → 发消息 → 防重标记 → 通知 +package engine + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +// 自动发货触发关键字(买家"我已付款"等系统消息)。 +var autoDeliveryKeywords = []string{ + "[我已付款,等待你发货]", + "[已付款,待发货]", + "我已付款,等待你发货", + "[记得及时发货]", +} + +// IsAutoDeliveryTrigger 消息文本是否触发自动发货。 +func IsAutoDeliveryTrigger(text string) bool { + for _, kw := range autoDeliveryKeywords { + if strings.Contains(text, kw) { + return true + } + } + return false +} + +// 发货锁与冷却配置。 +const ( + DeliveryCooldown = 10 * time.Minute // 同一订单 10 分钟内不重复发货 + DeliveryLockHold = 10 * time.Minute // 发货后持有延迟锁 10 分钟 + ConfirmCooldown = 30 * time.Second // 同一订单确认发货冷却 +) + +// DeliverySender 抽象"发送消息给买家"的能力(由 Account 注入,复用其 WS 连接)。 +type DeliverySender interface { + SendText(ctx context.Context, chatID, toUserID, text string) error + SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64) error +} + +// OrderDetailFetcher 抽象"取订单详情"(多规格/多数量需要,Phase 5 由 sidecar 提供)。 +type OrderDetailFetcher interface { + Fetch(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*OrderDetail, error) +} + +// OrderDetail 订单详情关键字段。 +type OrderDetail struct { + Quantity string + SpecName string + SpecValue string + Amount string + OrderStatus string +} + +// Notifier 发货通知(Phase 3 后段实现,先接口占位)。 +type Notifier interface { + NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) +} + +// DeliveryService 单账号发货服务(每个 Account 持有一个)。 +type DeliveryService struct { + cookieID string + store *db.Store + mtop *mtop.Client + sender DeliverySender + fetcher OrderDetailFetcher // 可为 nil(未配置多规格/多数量时不调用) + notifier Notifier // 可为 nil + logger *slog.Logger + + // 防重状态 + mu sync.Mutex + locks map[string]*deliveryLock // order_id → 延迟锁 + lastDelivery map[string]time.Time // order_id → 上次发货时间(冷却) + confirmedOrder map[string]time.Time // order_id → 上次确认发货时间 + + // cookie 源/汇:与 Account 共享可变 cookie(发货/确认发货会刷新 cookie) + cookieSrc func() string + cookieSink func(string) +} + +type deliveryLock struct { + locked bool + releasedAt time.Time + timer *time.Timer + mux sync.Mutex // per-order 串行锁 +} + +// NewDeliveryService 构造。 +func NewDeliveryService(cookieID string, store *db.Store, sender DeliverySender, + fetcher OrderDetailFetcher, notifier Notifier, logger *slog.Logger) *DeliveryService { + if logger == nil { + logger = slog.Default() + } + return &DeliveryService{ + cookieID: cookieID, + store: store, + mtop: &mtop.Client{}, + sender: sender, + fetcher: fetcher, + notifier: notifier, + logger: logger.With("account", cookieID, "subsys", "delivery"), + locks: make(map[string]*deliveryLock), + lastDelivery: make(map[string]time.Time), + confirmedOrder: make(map[string]time.Time), + } +} + +// Handle 收到一条聊天消息,若为自动发货触发关键字则执行发货流程。 +// 由 Account 在防抖后调用(HandleChatMessage 适配)。 +func (d *DeliveryService) Handle(ctx context.Context, m ChatMessage) error { + if !IsAutoDeliveryTrigger(m.Text) { + return nil + } + return d.handleAutoDelivery(ctx, m.Raw, m.ChatID, m.SenderUserID, m.SenderName, m.ItemID) +} + +// handleAutoDelivery 发货主流程。 +func (d *DeliveryService) handleAutoDelivery(ctx context.Context, raw map[string]any, + chatID, sendUserID, sendUserName, itemID string) error { + // 1. 商品归属校验。 + if itemID != "" && itemID != "未知商品" { + if _, err := d.store.Items.Get(ctx, d.cookieID, itemID); err != nil { + d.logger.Warn("商品不属于当前账号或查询失败,跳过发货", "item_id", itemID, "err", err) + return nil + } + } + + // 2. 提取 order_id。 + orderID := extractOrderID(raw) + if orderID == "" { + d.logger.Warn("未能提取到订单ID,跳过自动发货") + return nil + } + + // 3. 四重防重(延迟锁 + 冷却 + 加锁后复查)。 + if d.isLockHeld(orderID) { + d.logger.Info("订单延迟锁持有中,跳过发货", "order_id", orderID) + return nil + } + if !d.canAutoDelivery(orderID) { + d.logger.Info("订单冷却期内,跳过发货", "order_id", orderID) + return nil + } + + // 加订单级互斥锁(同一 order_id 串行处理)。 + unlock := d.acquireOrderLock(orderID) + defer unlock() + + if d.isLockHeld(orderID) { + d.logger.Info("获取锁后延迟锁仍持有,跳过", "order_id", orderID) + return nil + } + if !d.canAutoDelivery(orderID) { + d.logger.Info("获取锁后仍在冷却期,跳过", "order_id", orderID) + return nil + } + + // 4. 订单详情只抓取一次:用于补全实付金额,并按需读取规格/购买数量。 + quantity := 1 + specName, specValue := "", "" + isMultiSpec := d.store.Items.IsMultiSpec(ctx, d.cookieID, itemID) + isMultiQuantity := d.store.Items.MultiQuantityDelivery(ctx, d.cookieID, itemID) + needDetail := isMultiSpec || isMultiQuantity + if existing, err := d.store.Orders.Get(ctx, orderID); err != nil || strings.TrimSpace(existing.Amount) == "" { + needDetail = true + } + if d.fetcher != nil && needDetail { + od, err := d.fetcher.Fetch(ctx, d.cookieID, orderID, itemID, sendUserID, d.cookieStr()) + if err != nil { + d.logger.Warn("获取订单详情失败,继续尝试自动发货", "order_id", orderID, "err", err) + } else if od != nil { + specName, specValue = od.SpecName, od.SpecValue + _ = d.store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{ + CookieID: d.cookieID, ItemID: itemID, BuyerID: sendUserID, + SpecName: od.SpecName, SpecValue: od.SpecValue, Quantity: od.Quantity, + Amount: od.Amount, OrderStatus: od.OrderStatus, + }) + if isMultiQuantity { + if q := parseIntSafe(od.Quantity); q > 1 { + quantity = q + d.logger.Info("多数量发货", "quantity", quantity, "order_id", orderID) + } + } + } + } + + // 5. 循环获取发货内容。 + contents, err := d.collectDeliveryContentsWithSpec(ctx, itemID, orderID, sendUserID, specName, specValue, quantity) + if err != nil { + d.notify(sendUserName, sendUserID, itemID, "自动发货处理异常: "+err.Error(), chatID) + return err + } + if len(contents) == 0 { + d.logger.Warn("未找到匹配的发货规则或获取发货内容失败", "order_id", orderID) + d.notify(sendUserName, sendUserID, itemID, "未找到匹配的发货规则或获取发货内容失败", chatID) + return nil + } + + // 6. 标记已发货 + 延迟锁 + 入库 system_shipped。 + d.markDeliverySent(orderID) + sysShip := true + _ = d.store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{ + SystemShipped: &sysShip, + ChatID: chatID, + ItemID: itemID, + BuyerID: sendUserID, + CookieID: d.cookieID, + }) + + // 7. 逐条发送,多数量间隔 1s。 + for i, c := range contents { + if err := d.sendContent(ctx, c, chatID, sendUserID); err != nil { + d.logger.Error("发送发货内容失败", "index", i, "err", err) + } + if len(contents) > 1 && i < len(contents)-1 { + if sleepCtx(ctx, time.Second) != nil { + return ctx.Err() + } + } + } + + // 8. 通知。 + msg := "发货成功" + if len(contents) > 1 { + msg = fmt.Sprintf("多数量发货成功,共发送 %d 个卡券", len(contents)) + } + d.notify(sendUserName, sendUserID, itemID, msg, chatID) + d.logger.Info("自动发货完成", "order_id", orderID, "count", len(contents)) + return nil +} + +// collectDeliveryContents 调用 quantity 次 _auto_delivery 等价逻辑,收集发货内容。 +func (d *DeliveryService) collectDeliveryContents(ctx context.Context, itemID, orderID, sendUserID string, quantity int) ([]string, error) { + return d.collectDeliveryContentsWithSpec(ctx, itemID, orderID, sendUserID, "", "", quantity) +} + +func (d *DeliveryService) collectDeliveryContentsWithSpec(ctx context.Context, itemID, orderID, sendUserID, specName, specValue string, quantity int) ([]string, error) { + contents := make([]string, 0, quantity) + for i := 0; i < quantity; i++ { + batch, err := d.autoDeliveryOnce(ctx, itemID, orderID, sendUserID, specName, specValue) + if err != nil { + d.logger.Error("获取发货内容异常", "index", i, "err", err) + continue + } + contents = append(contents, batch...) + } + return contents, nil +} + +// autoDeliveryOnce 单次发货内容获取:匹配规则 → 延时 → 确认发货 → 卡券内容。 +// 移植自 _auto_delivery。 +func (d *DeliveryService) autoDeliveryOnce(ctx context.Context, itemID, orderID, sendUserID, knownSpecName, knownSpecValue string) ([]string, error) { + // 搜索文本 = 商品标题 + 详情。 + searchText := d.buildSearchText(ctx, itemID) + + // 多规格处理。 + isMultiSpec := d.store.Items.IsMultiSpec(ctx, d.cookieID, itemID) + specName, specValue := strings.TrimSpace(knownSpecName), strings.TrimSpace(knownSpecValue) + if isMultiSpec && (specName == "" || specValue == "") && d.fetcher != nil { + od, err := d.fetcher.Fetch(ctx, d.cookieID, orderID, itemID, sendUserID, d.cookieStr()) + if err != nil || od == nil || od.SpecName == "" || od.SpecValue == "" { + d.logger.Warn("多规格商品但无规格信息,跳过", "order_id", orderID, "err", err) + return nil, nil + } + specName, specValue = od.SpecName, od.SpecValue + } + if isMultiSpec && (specName == "" || specValue == "") { + d.logger.Warn("多规格商品缺少规格信息,跳过", "order_id", orderID) + return nil, nil + } + + // 新规则按 item_id + 规格精确匹配;旧规则自动回退关键词。 + if !isMultiSpec { + specName, specValue = "", "" + } + rules, err := d.store.DeliveryRules.MatchForOrder(ctx, d.cookieID, itemID, searchText, specName, specValue) + if err != nil { + return nil, fmt.Errorf("匹配发货规则失败: %w", err) + } + if len(rules) == 0 { + d.logger.Warn("未找到匹配的发货规则", "search_text", trunc(searchText, 50)) + return nil, nil + } + if len(rules) > 1 { + d.logger.Warn("匹配到多个发货规则,无法确定,跳过", "count", len(rules)) + return nil, nil + } + rule := rules[0] + + // 延时。 + if rule.CardDelaySeconds > 0 { + d.logger.Info("执行发货延时", "seconds", rule.CardDelaySeconds) + if sleepCtx(ctx, time.Duration(rule.CardDelaySeconds)*time.Second) != nil { + return nil, ctx.Err() + } + } + + // 确认发货(mtop consign)。auto_confirm 仅控制平台订单状态, + // 不影响后续卡券内容发送。 + if d.shouldAutoConfirm(ctx, orderID) { + d.logger.Info("确认发货", "order_id", orderID) + cookieStr := d.cookieStr() + ok, ret, updated, cerr := d.mtop.ConsignContext(ctx, cookieStr, orderID) + if cerr != nil { + d.logger.Warn("确认发货请求失败,继续发送内容", "err", cerr) + } else { + if updated != cookieStr && updated != "" { + d.setCookieStr(updated) + if err := d.store.Cookies.Save(ctx, d.cookieID, updated, 0); err != nil { + d.logger.Warn("保存确认发货更新后的 Cookie 失败", "err", err) + } + } + if ok { + d.recordConfirm(orderID) + } else { + d.logger.Warn("确认发货未成功,仍发送内容", "ret", ret) + } + } + } + + // 卡券内容。 + if orderID == "" { + d.logger.Info("无订单ID,跳过发货内容处理") + return nil, nil + } + deliveryCount := rule.DeliveryCount + if deliveryCount <= 0 { + deliveryCount = 1 + } + contents := make([]string, 0, deliveryCount) + for i := 0; i < deliveryCount; i++ { + content := d.cardContent(ctx, rule, orderID, itemID, sendUserID, specName, specValue) + if content == "" { + break + } + contents = append(contents, processDeliveryContentWithDescription(content, rule.CardDescription)) + _ = d.store.Cards.IncrementDeliveryTimes(ctx, rule.ID) + } + return contents, nil +} + +// buildSearchText 商品标题 + 空格 + 详情。 +func (d *DeliveryService) buildSearchText(ctx context.Context, itemID string) string { + it, err := d.store.Items.Get(ctx, d.cookieID, itemID) + if err != nil || it == nil { + return itemID + } + parts := []string{} + if strings.TrimSpace(it.ItemTitle) != "" { + parts = append(parts, strings.TrimSpace(it.ItemTitle)) + } + if strings.TrimSpace(it.ItemDetail) != "" { + parts = append(parts, strings.TrimSpace(it.ItemDetail)) + } + if len(parts) == 0 { + return itemID + } + return strings.Join(parts, " ") +} + +// cardContent 按卡券类型取发货内容。 +func (d *DeliveryService) cardContent(ctx context.Context, rule db.DeliveryRule, orderID, itemID, buyerID, specName, specValue string) string { + switch rule.CardType { + case "text": + return rule.TextContent + case "data": + c, err := d.store.Cards.ConsumeBatchData(ctx, rule.CardID) + if err != nil { + d.logger.Error("消费批量数据失败", "card_id", rule.CardID, "err", err) + return "" + } + return c + case "image": + if rule.ImageURL == "" { + d.logger.Error("图片卡券缺少 URL", "card_id", rule.CardID) + return "" + } + return fmt.Sprintf("__IMAGE_SEND__%d|%s", rule.CardID, rule.ImageURL) + case "api": + content, err := d.apiCardContent(ctx, rule, orderID, itemID, buyerID, specName, specValue) + if err != nil { + d.logger.Error("API 卡券调用失败", "card_id", rule.CardID, "err", err) + return "" + } + return content + } + return "" +} + +func (d *DeliveryService) apiCardContent(ctx context.Context, rule db.DeliveryRule, orderID, itemID, buyerID, specName, specValue string) (string, error) { + cfg := rule.APIConfigMap() + if len(cfg) == 0 { + return "", fmt.Errorf("API 配置为空") + } + endpoint := strings.TrimSpace(anyString(cfg["url"])) + if endpoint == "" { + return "", fmt.Errorf("API 配置缺少 url") + } + method := strings.ToUpper(strings.TrimSpace(anyString(cfg["method"]))) + if method == "" { + method = http.MethodGet + } + if method != http.MethodGet && method != http.MethodPost { + return "", fmt.Errorf("不支持的 HTTP 方法: %s", method) + } + timeoutSeconds := anyInt(cfg["timeout"]) + if timeoutSeconds <= 0 { + timeoutSeconds = 10 + } + if timeoutSeconds > 120 { + timeoutSeconds = 120 + } + headers := parseAPIMap(cfg["headers"]) + params := parseAPIMap(cfg["params"]) + params = d.replaceAPIParams(ctx, params, orderID, itemID, buyerID, specName, specValue) + + var lastErr error + for attempt := 0; attempt < 4; attempt++ { + if attempt > 0 { + if err := sleepCtx(ctx, time.Duration(attempt*2)*time.Second); err != nil { + return "", err + } + } + content, retry, err := d.callAPIOnce(ctx, endpoint, method, headers, params, time.Duration(timeoutSeconds)*time.Second) + if err == nil { + return content, nil + } + lastErr = err + if !retry { + break + } + } + return "", lastErr +} + +func (d *DeliveryService) callAPIOnce(ctx context.Context, endpoint, method string, headers, params map[string]any, timeout time.Duration) (content string, retry bool, err error) { + reqCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + var body io.Reader + if method == http.MethodPost { + raw, err := json.Marshal(params) + if err != nil { + return "", false, err + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(reqCtx, method, endpoint, body) + if err != nil { + return "", false, err + } + for k, v := range headers { + if strings.TrimSpace(k) == "" { + continue + } + req.Header.Set(k, anyString(v)) + } + if method == http.MethodPost && req.Header.Get("Content-Type") == "" { + req.Header.Set("Content-Type", "application/json") + } + if method == http.MethodGet && len(params) > 0 { + q := req.URL.Query() + for k, v := range params { + q.Set(k, anyString(v)) + } + req.URL.RawQuery = q.Encode() + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", true, err + } + defer resp.Body.Close() + raw, readErr := io.ReadAll(resp.Body) + if readErr != nil { + return "", true, readErr + } + if resp.StatusCode != http.StatusOK { + retry := resp.StatusCode >= 500 || resp.StatusCode == http.StatusRequestTimeout + return "", retry, fmt.Errorf("API 返回状态 %d: %s", resp.StatusCode, trunc(string(raw), 200)) + } + content = parseAPIContent(raw) + if strings.TrimSpace(content) == "" { + return "", false, fmt.Errorf("API 返回内容为空") + } + return content, false, nil +} + +func parseAPIMap(v any) map[string]any { + if v == nil { + return map[string]any{} + } + switch x := v.(type) { + case map[string]any: + return x + case map[string]string: + out := make(map[string]any, len(x)) + for k, v := range x { + out[k] = v + } + return out + case string: + x = strings.TrimSpace(x) + if x == "" { + return map[string]any{} + } + var m map[string]any + if err := json.Unmarshal([]byte(x), &m); err == nil { + return m + } + } + return map[string]any{} +} + +func (d *DeliveryService) replaceAPIParams(ctx context.Context, params map[string]any, orderID, itemID, buyerID, specName, specValue string) map[string]any { + mapping := map[string]string{ + "order_id": orderID, + "item_id": itemID, + "buyer_id": buyerID, + "cookie_id": d.cookieID, + "spec_name": specName, + "spec_value": specValue, + } + if orderID != "" { + if ord, err := d.store.Orders.Get(ctx, orderID); err == nil && ord != nil { + mapping["order_amount"] = ord.Amount + mapping["order_quantity"] = ord.Quantity + } + } + if itemID != "" { + if it, err := d.store.Items.Get(ctx, d.cookieID, itemID); err == nil && it != nil { + itemDetail := it.ItemDetail + var detail map[string]any + if json.Unmarshal([]byte(itemDetail), &detail) == nil { + if d, ok := detail["detail"].(string); ok { + itemDetail = d + } + } + mapping["item_detail"] = itemDetail + } + } + return replaceRecursive(params, mapping).(map[string]any) +} + +func replaceRecursive(v any, mapping map[string]string) any { + switch x := v.(type) { + case map[string]any: + out := make(map[string]any, len(x)) + for k, v := range x { + out[k] = replaceRecursive(v, mapping) + } + return out + case []any: + out := make([]any, len(x)) + for i, v := range x { + out[i] = replaceRecursive(v, mapping) + } + return out + case string: + out := x + for k, v := range mapping { + out = strings.ReplaceAll(out, "{"+k+"}", v) + } + return out + default: + return v + } +} + +func parseAPIContent(raw []byte) string { + var v any + if json.Unmarshal(raw, &v) != nil { + return strings.TrimSpace(string(raw)) + } + if m, ok := v.(map[string]any); ok { + for _, key := range []string{"data", "content", "card"} { + if val, ok := m[key]; ok && val != nil { + return anyString(val) + } + } + } + return anyString(v) +} + +func anyString(v any) string { + switch x := v.(type) { + case string: + return x + case nil: + return "" + default: + b, _ := json.Marshal(x) + return string(b) + } +} + +func anyInt(v any) int { + switch x := v.(type) { + case int: + return x + case int64: + return int(x) + case float64: + return int(x) + case json.Number: + n, _ := strconv.Atoi(x.String()) + return n + case string: + n, _ := strconv.Atoi(strings.TrimSpace(x)) + return n + default: + return 0 + } +} + +// sendContent 发送一条发货内容(文本或图片)。 +func (d *DeliveryService) sendContent(ctx context.Context, content, chatID, toUserID string) error { + if d.sender == nil { + return nil + } + if strings.HasPrefix(content, "__IMAGE_SEND__") { + rest := strings.TrimPrefix(content, "__IMAGE_SEND__") + var cardID int64 + imageURL := rest + if i := strings.Index(rest, "|"); i >= 0 { + cardID = int64(parseIntSafe(rest[:i])) + imageURL = rest[i+1:] + } + return d.sender.SendImage(ctx, chatID, toUserID, imageURL, cardID) + } + return d.sender.SendText(ctx, chatID, toUserID, content) +} + +// processDeliveryContentWithDescription 复刻 Python 备注/变量替换逻辑。 +func processDeliveryContentWithDescription(content, description string) string { + if strings.HasPrefix(content, "__IMAGE_SEND__") { + return content + } + desc := strings.TrimSpace(description) + if desc == "" { + return content + } + if strings.Contains(desc, "{DELIVERY_CONTENT}") { + return strings.ReplaceAll(desc, "{DELIVERY_CONTENT}", content) + } + return desc + "\n\n" + content +} + +func (d *DeliveryService) notify(buyerName, buyerID, itemID, message, chatID string) { + if d.notifier != nil { + d.notifier.NotifyDelivery(d.cookieID, buyerName, buyerID, itemID, message, chatID) + } +} + +// ---- 防重状态机 ---- + +func (d *DeliveryService) isLockHeld(orderID string) bool { + d.mu.Lock() + defer d.mu.Unlock() + l, ok := d.locks[orderID] + return ok && l.locked +} + +func (d *DeliveryService) canAutoDelivery(orderID string) bool { + if orderID == "" { + return true + } + d.mu.Lock() + defer d.mu.Unlock() + if last, ok := d.lastDelivery[orderID]; ok { + if time.Since(last) < DeliveryCooldown { + return false + } + } + return true +} + +func (d *DeliveryService) markDeliverySent(orderID string) { + d.mu.Lock() + defer d.mu.Unlock() + d.lastDelivery[orderID] = time.Now() + // 设置延迟锁,10 分钟后释放。 + l := &deliveryLock{locked: true} + if old, ok := d.locks[orderID]; ok && old.timer != nil { + old.timer.Stop() + } + l.timer = time.AfterFunc(DeliveryLockHold, func() { + d.mu.Lock() + defer d.mu.Unlock() + if cur, ok := d.locks[orderID]; ok { + cur.locked = false + cur.releasedAt = time.Now() + } + }) + d.locks[orderID] = l +} + +// acquireOrderLock 返回释放函数,对同一 order_id 串行化。 +// 简化实现:用一个 per-order 互斥(map 里存 *sync.Mutex)。 +func (d *DeliveryService) acquireOrderLock(orderID string) func() { + d.mu.Lock() + l, ok := d.locks[orderID] + if !ok { + l = &deliveryLock{} + d.locks[orderID] = l + } + d.mu.Unlock() + l.mux.Lock() + return l.mux.Unlock +} + +func (d *DeliveryService) shouldConfirm(orderID string) bool { + d.mu.Lock() + defer d.mu.Unlock() + if last, ok := d.confirmedOrder[orderID]; ok { + if time.Since(last) < ConfirmCooldown { + return false + } + } + return true +} + +func (d *DeliveryService) shouldAutoConfirm(ctx context.Context, orderID string) bool { + if orderID == "" { + return false + } + enabled, err := d.store.Cookies.GetAutoConfirm(ctx, d.cookieID) + if err != nil { + d.logger.Warn("读取自动确认发货设置失败,跳过确认发货", "err", err) + return false + } + if !enabled { + d.logger.Info("自动确认发货已关闭,跳过确认发货", "order_id", orderID) + return false + } + return d.shouldConfirm(orderID) +} + +func (d *DeliveryService) recordConfirm(orderID string) { + d.mu.Lock() + defer d.mu.Unlock() + d.confirmedOrder[orderID] = time.Now() +} + +// SetCookieSource 让 DeliveryService 与 Account 共享可变 cookie。 +func (d *DeliveryService) SetCookieSource(src func() string, sink func(string)) { + d.cookieSrc = src + d.cookieSink = sink +} + +// cookieStr 取当前 cookie。 +func (d *DeliveryService) cookieStr() string { + if d.cookieSrc != nil { + return d.cookieSrc() + } + return "" +} + +func (d *DeliveryService) setCookieStr(s string) { + if d.cookieSink != nil { + d.cookieSink(s) + } +} + +// ---- 提取与辅助 ---- + +// 订单 ID 提取正则(复刻 Python _extract_order_id 的多模式兜底)。 +var orderIDPatterns = []*regexp.Regexp{ + regexp.MustCompile(`orderId[=:](\d{10,})`), + regexp.MustCompile(`order_detail\?id=(\d{10,})`), + regexp.MustCompile(`bizOrderId[=:](\d{10,})`), +} + +// extractOrderID 从解密消息中提取订单 ID。 +// 优先从 message["1"]["6"]["3"]["5"](dxCard JSON)的 button.targetUrl 中提取。 +func extractOrderID(decrypted map[string]any) string { + // 方法1:从 button/main targetUrl 提取。 + if contentJSON := nestedString(decrypted, "1", "6", "3", "5"); contentJSON != "" { + if id := extractOrderIDFromContent(contentJSON); id != "" { + return id + } + } + // 方法2:兜底——整个消息转字符串搜模式。 + raw, _ := json.Marshal(decrypted) + rawStr := string(raw) + for _, p := range orderIDPatterns { + if m := p.FindStringSubmatch(rawStr); len(m) > 1 { + return m[1] + } + } + return "" +} + +func extractOrderIDFromContent(contentJSON string) string { + var c map[string]any + if err := json.Unmarshal([]byte(contentJSON), &c); err != nil { + return "" + } + // dxCard.item.main.exContent.button.targetUrl → orderId=xxx + buttonURL := nestedString(c, "dxCard", "item", "main", "exContent", "button", "targetUrl") + if id := matchOrderID(buttonURL); id != "" { + return id + } + // dxCard.item.main.targetUrl → order_detail?id=xxx + mainURL := nestedString(c, "dxCard", "item", "main", "targetUrl") + if id := matchOrderID(mainURL); id != "" { + return id + } + // dynamicOperation.changeContent.dxCard... + dynURL := nestedString(c, "dynamicOperation", "changeContent", "dxCard", "item", "main", "exContent", "button", "targetUrl") + return matchOrderID(dynURL) +} + +func matchOrderID(url string) string { + if url == "" { + return "" + } + for _, p := range orderIDPatterns { + if m := p.FindStringSubmatch(url); len(m) > 1 { + return m[1] + } + } + return "" +} + +// nestedString 沿 path 取嵌套 map 中的字符串值。 +func nestedString(m map[string]any, path ...string) string { + cur := m + for i, k := range path { + if i == len(path)-1 { + if s, ok := cur[k].(string); ok { + return s + } + return "" + } + next, ok := cur[k].(map[string]any) + if !ok { + return "" + } + cur = next + } + return "" +} + +func filterMultiSpec(rules []db.DeliveryRule, multiSpec bool) []db.DeliveryRule { + out := rules[:0] + for _, r := range rules { + if r.IsMultiSpec == multiSpec { + out = append(out, r) + } + } + return out +} + +func parseIntSafe(s string) int { + n, _ := strconv.Atoi(strings.TrimSpace(s)) + return n +} + +func trunc(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + "..." +} diff --git a/internal/engine/delivery_test.go b/internal/engine/delivery_test.go new file mode 100644 index 0000000..2c41d06 --- /dev/null +++ b/internal/engine/delivery_test.go @@ -0,0 +1,269 @@ +package engine + +import ( + "context" + "path/filepath" + "testing" + "time" + + "xianyu-go/internal/db" +) + +func newDeliveryStore(t *testing.T) (*db.Store, func()) { + t.Helper() + d, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("Open: %v", err) + } + s := db.NewStore(d) + // 初始化 admin + 一个账号。 + s.Users.Create(context.Background(), "admin", "a@e.com", "pw") + admin, _ := s.Users.GetByUsername(context.Background(), "admin") + s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID) + return s, func() { d.Close() } +} + +// TestIsAutoDeliveryTrigger 触发关键字检测。 +func TestIsAutoDeliveryTrigger(t *testing.T) { + cases := map[string]bool{ + "[我已付款,等待你发货]": true, + "买家说:[我已付款,等待你发货] 谢谢": true, + "[已付款,待发货]": true, + "[记得及时发货]": true, + "我已付款,等待你发货": true, + "你好,这个还在吗": false, + "已付款,待发货": false, // 无括号变体不在触发列表中 + "": false, + } + for in, want := range cases { + if got := IsAutoDeliveryTrigger(in); got != want { + t.Errorf("IsAutoDeliveryTrigger(%q)=%v want %v", in, got, want) + } + } +} + +// TestExtractOrderID 从真实样本结构提取订单 ID。 +func TestExtractOrderID(t *testing.T) { + // dxCard 的 button.targetUrl 含 orderId。 + msg := map[string]any{ + "1": map[string]any{ + "6": map[string]any{ + "3": map[string]any{ + "5": `{"dxCard":{"item":{"main":{"exContent":{"button":{"targetUrl":"fleamarket://adjust_price?bizOrderId=2503688126356636370"}}}}}}`, + }, + }, + }, + } + if id := extractOrderID(msg); id != "2503688126356636370" { + t.Errorf("extractOrderID=%q want 2503688126356636370", id) + } +} + +// TestExtractOrderID_FallbackString 整消息字符串兜底。 +func TestExtractOrderID_FallbackString(t *testing.T) { + msg := map[string]any{ + "raw": "some text with bizOrderId=98765432109987654 inside", + } + if id := extractOrderID(msg); id != "98765432109987654" { + t.Errorf("fallback extractOrderID=%q", id) + } +} + +// TestDeliveryRuleMatching 验证双向模糊匹配 SQL 与多规格过滤。 +func TestDeliveryRuleMatching(t *testing.T) { + s, cleanup := newDeliveryStore(t) + defer cleanup() + ctx := context.Background() + admin, _ := s.Users.GetByUsername(ctx, "admin") + + // 一个 text 卡券 + 一个 data 卡券(非多规格)。 + s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,data_content,enabled,user_id) VALUES + (1,'VIP卡','text','您的卡密:ABC123',NULL,1,?), + (2,'数据卡','data',NULL,'line1\nline2\nline3',1,?)`, admin.ID, admin.ID) + // 多规格卡券。 + s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,is_multi_spec,spec_name,spec_value,user_id) VALUES + (3,'红色版','text','红色发货码',1,1,'颜色','红',?)`, admin.ID) + // 发货规则:关键字"VIP" → 卡券1;"商品" → 卡券2;"红色" → 卡券3。 + s.DB.ExecContext(ctx, `INSERT INTO delivery_rules (id,keyword,card_id,enabled,user_id) VALUES + (1,'VIP',1,1,?),(2,'商品',2,1,?),(3,'红色',3,1,?)`, admin.ID, admin.ID, admin.ID) + + // 非多规格匹配:商品文本"我的VIP商品"应命中规则1(VIP 含于文本,长度优先)+规则2("商品"含于文本)。 + rules, err := s.DeliveryRules.MatchByKeyword(ctx, "我的VIP商品") + if err != nil { + t.Fatalf("MatchByKeyword: %v", err) + } + if len(rules) != 2 { + t.Fatalf("应匹配2条非多规格规则,got %d", len(rules)) + } + // 长度降序:VIP(3) > 商品(2),规则1应在前。 + if rules[0].ID != 1 { + t.Errorf("应按关键字长度降序,首条=%d want 1", rules[0].ID) + } + + // 多规格匹配。 + msRules, err := s.DeliveryRules.MatchByKeywordAndSpec(ctx, "红色商品", "颜色", "红") + if err != nil { + t.Fatalf("MatchByKeywordAndSpec: %v", err) + } + if len(msRules) != 1 || msRules[0].ID != 3 { + t.Fatalf("多规格应只匹配规则3,got %+v", msRules) + } +} + +func TestDeliveryRuleMatchingByItemAndVariant(t *testing.T) { + s, cleanup := newDeliveryStore(t) + defer cleanup() + ctx := context.Background() + admin, _ := s.Users.GetByUsername(ctx, "admin") + + _, _ = s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES + (11,'30天库存','text','CODE30',1,?), + (12,'90天库存','text','CODE90',1,?)`, admin.ID, admin.ID) + _, _ = s.DB.ExecContext(ctx, `INSERT INTO delivery_rules + (id,keyword,card_id,delivery_count,enabled,user_id,cookie_id,item_id) + VALUES (21,'会员',11,1,1,?,'cid','item-vip')`, admin.ID) + _, _ = s.DB.ExecContext(ctx, `INSERT INTO delivery_rule_variants + (rule_id,spec_name,spec_value,card_id,delivery_count,enabled) VALUES + (21,'套餐','30天',11,1,1),(21,'套餐','90天',12,2,1)`) + + rules, err := s.DeliveryRules.MatchForOrder(ctx, "cid", "item-vip", "任意标题", "套餐", "90天") + if err != nil { + t.Fatalf("MatchForOrder: %v", err) + } + if len(rules) != 1 || rules[0].CardID != 12 || rules[0].DeliveryCount != 2 { + t.Fatalf("规格映射错误: %+v", rules) + } + other, err := s.DeliveryRules.MatchForOrder(ctx, "other", "item-vip", "任意标题", "套餐", "90天") + if err != nil { + t.Fatal(err) + } + if len(other) != 0 { + t.Fatalf("其他账号不应命中规则: %+v", other) + } +} + +// TestConsumeBatchData data 卡券逐行消费。 +func TestConsumeBatchData(t *testing.T) { + s, cleanup := newDeliveryStore(t) + defer cleanup() + ctx := context.Background() + admin, _ := s.Users.GetByUsername(ctx, "admin") + // 创建一个 data 卡券(id=2)。 + s.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,data_content,enabled,user_id) VALUES (2,'数据卡','data','line1'||char(10)||'line2'||char(10)||'line3',1,?)`, admin.ID) + + c1, err := s.Cards.ConsumeBatchData(ctx, 2) + if err != nil { + t.Fatalf("ConsumeBatchData: %v", err) + } + if c1 != "line1" { + t.Errorf("首次消费=%q want line1", c1) + } + c2, _ := s.Cards.ConsumeBatchData(ctx, 2) + if c2 != "line2" { + t.Errorf("二次消费=%q want line2", c2) + } + c3, _ := s.Cards.ConsumeBatchData(ctx, 2) + if c3 != "line3" { + t.Errorf("三次消费=%q want line3", c3) + } + // 第四次应失败(已空)。 + if _, err := s.Cards.ConsumeBatchData(ctx, 2); err == nil { + t.Fatal("数据耗尽应报错") + } +} + +// TestDedupMachine 四重防重:冷却 + 延迟锁。 +func TestDedupMachine(t *testing.T) { + s, cleanup := newDeliveryStore(t) + defer cleanup() + d := NewDeliveryService("cid", s, nil, nil, nil, nil) + d.SetCookieSource(func() string { return "" }, func(string) {}) + + // 冷却:无发货记录时允许。 + if !d.canAutoDelivery("order1") { + t.Fatal("首次应允许发货") + } + // 标记已发货 → 10 分钟冷却。 + d.markDeliverySent("order1") + if d.canAutoDelivery("order1") { + t.Fatal("发货后应进入冷却期") + } + if !d.isLockHeld("order1") { + t.Fatal("发货后延迟锁应持有") + } + // 不同订单不受影响。 + if !d.canAutoDelivery("order2") { + t.Fatal("order2 不应受 order1 冷却影响") + } +} + +func TestShouldAutoConfirmRespectsAccountSetting(t *testing.T) { + s, cleanup := newDeliveryStore(t) + defer cleanup() + ctx := context.Background() + d := NewDeliveryService("cid", s, nil, nil, nil, nil) + + if !d.shouldAutoConfirm(ctx, "order1") { + t.Fatal("默认开启时应允许自动确认发货") + } + if _, err := s.DB.ExecContext(ctx, `UPDATE cookies SET auto_confirm=0 WHERE id=?`, "cid"); err != nil { + t.Fatalf("关闭 auto_confirm: %v", err) + } + if d.shouldAutoConfirm(ctx, "order2") { + t.Fatal("关闭设置后不应自动确认发货") + } + if d.shouldAutoConfirm(ctx, "") { + t.Fatal("缺少订单 ID 时不应自动确认发货") + } +} + +// TestProcessDeliveryContentWithDescription 备注/变量替换。 +func TestProcessDeliveryContentWithDescription(t *testing.T) { + // 有 {DELIVERY_CONTENT} 变量。 + got := processDeliveryContentWithDescription("ABC123", "您的卡密是 {DELIVERY_CONTENT},请妥善保管") + want := "您的卡密是 ABC123,请妥善保管" + if got != want { + t.Errorf("变量替换: got %q want %q", got, want) + } + // 无变量:备注 + 内容。 + got = processDeliveryContentWithDescription("ABC123", "温馨提示") + if got != "温馨提示\n\nABC123" { + t.Errorf("无变量组合: got %q", got) + } + // 图片标记不处理。 + got = processDeliveryContentWithDescription("__IMAGE_SEND__1|http://x", "备注") + if got != "__IMAGE_SEND__1|http://x" { + t.Errorf("图片标记不应处理: got %q", got) + } + // 无备注直接返回。 + got = processDeliveryContentWithDescription("ABC123", "") + if got != "ABC123" { + t.Errorf("无备注: got %q", got) + } +} + +// TestAcquireOrderLockSerializes 同一 order_id 串行化。 +func TestAcquireOrderLockSerializes(t *testing.T) { + s, cleanup := newDeliveryStore(t) + defer cleanup() + d := NewDeliveryService("cid", s, nil, nil, nil, nil) + + done := make(chan struct{}) + // 先获取锁。 + unlock := d.acquireOrderLock("orderX") + go func() { + defer close(done) + d.acquireOrderLock("orderX") // 应阻塞 + }() + select { + case <-done: + t.Fatal("锁未释放前第二个获取应阻塞") + case <-time.After(100 * time.Millisecond): + } + unlock() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("释放后第二个应能获取") + } +} diff --git a/internal/engine/dispatch.go b/internal/engine/dispatch.go new file mode 100644 index 0000000..59d4cd5 --- /dev/null +++ b/internal/engine/dispatch.go @@ -0,0 +1,438 @@ +package engine + +import ( + "context" + "encoding/json" + "strings" + "time" +) + +// dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做: +// 标记消息接收时间 → 提取消息 ID 去重 → 信号量限并发 → 分类(聊天/系统)→ 防抖投递。 +func (a *Account) dispatch(decrypted map[string]any) { + a.mu.Lock() + a.lastMsgReceived = time.Now() + a.mu.Unlock() + + // 信号量限并发(非阻塞获取,超限则丢弃并告警——避免阻塞 WS 读取)。 + select { + case a.sem <- struct{}{}: + default: + a.logger.Warn("消息处理并发达上限,丢弃消息", "limit", MessageSemaphoreSize) + return + } + go func() { + defer func() { <-a.sem }() + a.handleMessage(decrypted) + }() +} + +// handleMessage 分类并投递消息。 +func (a *Account) handleMessage(decrypted map[string]any) { + chat := extractChatMessage(decrypted, a.CookieID, a.currentCookieStr()) + if chat != nil && chat.Text != "" { + // 去重。 + if !a.markAndCheckDedup(decrypted, chat) { + return + } + // 自动发货触发消息必须立即处理,不能进入普通聊天防抖。 + // 否则闲鱼紧随其后的系统提示(如“不想宝贝被砍价”)可能覆盖付款卡片, + // 造成未发货且进入 AI 回复。 + if IsAutoDeliveryTrigger(chat.Text) { + a.cancelDebouncedReply(chat.ChatID) + if a.delivery != nil { + if err := a.delivery.Handle(context.Background(), *chat); err != nil { + a.logger.Error("处理自动发货失败", "err", err, "chat_id", chat.ChatID) + } + } + if a.handler != nil { + if err := a.handler.HandleChatMessage(context.Background(), *chat); err != nil { + a.logger.Error("处理聊天消息失败", "err", err, "chat_id", chat.ChatID) + } + } + return + } + + // 普通聊天消息走防抖,合并连续文本后再自动回复。 + a.scheduleDebouncedReply(*chat) + return + } + sys := extractSystemMessage(decrypted, a.CookieID, a.currentCookieStr()) + if sys != nil && sys.RedReminder != "" && a.handler != nil { + if err := a.handler.HandleSystemMessage(context.Background(), *sys); err != nil { + a.logger.Error("处理系统消息失败", "err", err) + } + } +} + +func (a *Account) cancelDebouncedReply(chatID string) { + if chatID == "" { + return + } + a.debounceMu.Lock() + defer a.debounceMu.Unlock() + if old, ok := a.debounceTimers[chatID]; ok { + if old.timer != nil { + old.timer.Stop() + } + delete(a.debounceTimers, chatID) + } +} + +// markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。 +// 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。 +func (a *Account) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool { + msgID := extractMessageID(decrypted) + if msgID == "" { + // 备用标识:chat_id + text + create_time。 + createTime := "0" + if m1, ok := decrypted["1"].(map[string]any); ok { + if t, ok := m1["5"]; ok { + createTime = toString(t) + } + } + msgID = chat.ChatID + "_" + chat.Text + "_" + createTime + } + + a.dedupMu.Lock() + defer a.dedupMu.Unlock() + now := time.Now() + if last, ok := a.processed[msgID]; ok { + if now.Sub(last) < MessageExpireTime { + a.logger.Info("消息已处理过,跳过", "msg_id", truncID(msgID)) + return false + } + } + a.processed[msgID] = now + + // 清理:超上限时删过期记录,仍超则删最旧一半。 + if len(a.processed) > ProcessedIDsMaxSize { + a.cleanupDedupLocked(now) + } + return true +} + +func (a *Account) cleanupDedupLocked(now time.Time) { + for id, t := range a.processed { + if now.Sub(t) > MessageExpireTime { + delete(a.processed, id) + } + } + if len(a.processed) > ProcessedIDsMaxSize { + // 删最旧一半。 + type kv struct { + id string + t time.Time + } + all := make([]kv, 0, len(a.processed)) + for id, t := range a.processed { + all = append(all, kv{id, t}) + } + // 简单选择:按时间升序,删前一半。 + for i := 0; i < len(all); i++ { + for j := i + 1; j < len(all); j++ { + if all[j].t.Before(all[i].t) { + all[i], all[j] = all[j], all[i] + } + } + } + remove := len(all) / 2 + for i := 0; i < remove; i++ { + delete(a.processed, all[i].id) + } + } +} + +// scheduleDebouncedReply 为 chat_id 调度防抖回复: +// 同一 chat_id 连续来消息时取消旧定时器、用最新消息重新计时,1s 后投递最后一条。 +func (a *Account) scheduleDebouncedReply(chat ChatMessage) { + a.debounceMu.Lock() + defer a.debounceMu.Unlock() + + deadline := time.Now() + // 取消旧定时器。 + if old, ok := a.debounceTimers[chat.ChatID]; ok && old.timer != nil { + old.timer.Stop() + } + entry := &debounceEntry{lastMsg: chat, deadline: deadline} + a.debounceTimers[chat.ChatID] = entry + + entry.timer = time.AfterFunc(MessageDebounceDelay, func() { + a.debounceMu.Lock() + cur, ok := a.debounceTimers[chat.ChatID] + if !ok || cur.deadline != deadline { + // 期间有新消息,跳过旧消息处理。 + a.debounceMu.Unlock() + return + } + delete(a.debounceTimers, chat.ChatID) + lastMsg := cur.lastMsg + a.debounceMu.Unlock() + + if a.delivery != nil { + if err := a.delivery.Handle(context.Background(), lastMsg); err != nil { + a.logger.Error("处理自动发货失败", "err", err, "chat_id", chat.ChatID) + } + if IsAutoDeliveryTrigger(lastMsg.Text) { + return + } + } + if a.reply != nil { + if err := a.reply.Handle(context.Background(), lastMsg); err != nil { + a.logger.Error("处理自动回复失败", "err", err, "chat_id", chat.ChatID) + } + } + if a.handler != nil { + if err := a.handler.HandleChatMessage(context.Background(), lastMsg); err != nil { + a.logger.Error("处理聊天消息失败", "err", err, "chat_id", chat.ChatID) + } + } + }) +} + +// extractMessageID 从 message["1"]["10"]["bizTag"] 或 extJson 中提取 messageId。 +// 移植自 _extract_message_id。 +func extractMessageID(decrypted map[string]any) string { + m1, ok := decrypted["1"].(map[string]any) + if !ok { + return "" + } + m10, ok := m1["10"].(map[string]any) + if !ok { + return "" + } + // bizTag 是 JSON 字符串:{"sourceId":"...","messageId":"..."} + if biz, _ := m10["bizTag"].(string); biz != "" { + if id := parseMessageIDFromJSON(biz); id != "" { + return id + } + } + if ext, _ := m10["extJson"].(string); ext != "" { + if id := parseMessageIDFromJSON(ext); id != "" { + return id + } + } + return "" +} + +func parseMessageIDFromJSON(s string) string { + var m map[string]any + if err := json.Unmarshal([]byte(s), &m); err != nil { + return "" + } + if id, ok := m["messageId"].(string); ok { + return id + } + return "" +} + +// extractChatMessage 从解密消息中提取聊天消息字段。 +func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *ChatMessage { + m1, ok := decrypted["1"].(map[string]any) + if !ok { + return nil + } + m10, _ := m1["10"].(map[string]any) + if m10 == nil { + return nil + } + reminder, _ := m10["reminderContent"].(string) + if reminder == "" { + return nil + } + if isNonUserChatNotice(m1, m10, reminder) { + return nil + } + chatID := toString(m1["2"]) + // chat_id 形如 "47983389096@goofish",去掉后缀。 + if i := strings.Index(chatID, "@"); i >= 0 { + chatID = chatID[:i] + } + senderUserID, _ := m10["senderUserId"].(string) + senderName, _ := m10["senderNick"].(string) + reminderURL, _ := m10["reminderUrl"].(string) + itemID := extractItemID(reminderURL) + return &ChatMessage{ + AccountID: accountID, + CookieStr: cookieStr, + ChatID: chatID, + SenderUserID: senderUserID, + SenderName: senderName, + Text: reminder, + ItemID: itemID, + Raw: decrypted, + } +} + +// isNonUserChatNotice 判断闲鱼 IM 中不应进入自动回复/自动发货的系统提示或交易卡片。 +// 典型样本: +// - contentType=14:“有蚂蚁森林能量可领”“不想宝贝被砍价?设置不砍价回复”“退款成功” +// - contentType=26:交易卡片,如“我已拍下,待付款”“我发起了退款申请” +// 例外:付款待发货卡片要进入自动发货,因此保留。 +func isNonUserChatNotice(m1, m10 map[string]any, reminder string) bool { + contentType := messageContentType(m1, m10) + switch contentType { + case "14": + return true + case "26": + return !IsAutoDeliveryTrigger(reminder) + } + return false +} + +func messageContentType(m1, m10 map[string]any) string { + if ext, _ := m10["extJson"].(string); ext != "" { + var extJSON map[string]any + if json.Unmarshal([]byte(ext), &extJSON) == nil { + if v := toString(extJSON["contentType"]); v != "" { + return v + } + } + } + m6, _ := m1["6"].(map[string]any) + if m6 == nil { + return "" + } + m63, _ := m6["3"].(map[string]any) + if m63 == nil { + return "" + } + if v := toString(m63["4"]); v != "" { + return v + } + if contentJSON, _ := m63["5"].(string); contentJSON != "" { + var content map[string]any + if json.Unmarshal([]byte(contentJSON), &content) == nil { + return toString(content["contentType"]) + } + } + return "" +} + +// extractSystemMessage 提取订单状态等系统消息(message["3"])。 +func extractSystemMessage(decrypted map[string]any, accountID, cookieStr string) *SystemMessage { + m3, ok := decrypted["3"].(map[string]any) + if !ok { + return nil + } + red, _ := m3["redReminder"].(string) + uid, _ := m3["userId"].(string) + if red == "" && uid == "" { + return nil + } + return &SystemMessage{ + AccountID: accountID, + CookieStr: cookieStr, + RedReminder: red, + UserID: uid, + Raw: decrypted, + } +} + +// extractItemID 从 reminderUrl 中正则提取 itemId=xxx。 +func extractItemID(url string) string { + const key = "itemId=" + i := strings.Index(url, key) + if i < 0 { + return "" + } + s := url[i+len(key):] + if j := strings.IndexAny(s, "&\n\r"); j >= 0 { + s = s[:j] + } + return s +} + +func (a *Account) currentCookieStr() string { + a.mu.Lock() + defer a.mu.Unlock() + return a.CookieStr +} + +// ---- 小工具 ---- + +func contains(s, sub string) bool { return strings.Contains(strings.ToLower(s), strings.ToLower(sub)) } + +func toString(v any) string { + switch x := v.(type) { + case string: + return x + case float64: + // JSON 数字 → 整数字符串。 + return trimFloatInt(x) + default: + b, _ := json.Marshal(v) + return string(b) + } +} + +func trimFloatInt(f float64) string { + if f == float64(int64(f)) { + return int64ToString(int64(f)) + } + return ftoa(f) +} + +func int64ToString(n int64) string { + if n == 0 { + return "0" + } + neg := n < 0 + if neg { + n = -n + } + var b [20]byte + i := len(b) + for n > 0 { + i-- + b[i] = byte('0' + n%10) + n /= 10 + } + if neg { + i-- + b[i] = '-' + } + return string(b[i:]) +} + +func ftoa(f float64) string { return jsonNumber(f) } + +func jsonNumber(f float64) string { + b, _ := json.Marshal(f) + return string(b) +} + +func truncID(id string) string { + if len(id) > 50 { + return id[:50] + "..." + } + return id +} + +func errString(err error) string { + if err == nil { + return "" + } + return err.Error() +} + +func sleepCtx(ctx context.Context, d time.Duration) error { + if d <= 0 { + return nil + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go new file mode 100644 index 0000000..c77564e --- /dev/null +++ b/internal/engine/engine_test.go @@ -0,0 +1,343 @@ +package engine + +import ( + "context" + "encoding/json" + "fmt" + "path/filepath" + "sync" + "testing" + "time" + + "xianyu-go/internal/db" +) + +// recordingHandler 记录收到的聊天/系统消息,用于断言防抖与去重行为。 +type recordingHandler struct { + mu sync.Mutex + chats []ChatMessage + systems []SystemMessage + refresh int +} + +func (h *recordingHandler) HandleChatMessage(_ context.Context, m ChatMessage) error { + h.mu.Lock() + defer h.mu.Unlock() + h.chats = append(h.chats, m) + return nil +} +func (h *recordingHandler) HandleSystemMessage(_ context.Context, m SystemMessage) error { + h.mu.Lock() + defer h.mu.Unlock() + h.systems = append(h.systems, m) + return nil +} +func (h *recordingHandler) OnPasswordLoginRefresh(_ context.Context, _ string) bool { + h.mu.Lock() + defer h.mu.Unlock() + h.refresh++ + return true +} + +func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, func()) { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "test.db") + d, err := db.Open(context.Background(), dbPath) + if err != nil { + t.Fatalf("Open: %v", err) + } + store := db.NewStore(d) + store.Users.Create(context.Background(), "admin", "a@e.com", "pw") + admin, _ := store.Users.GetByUsername(context.Background(), "admin") + store.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID) + store.Cookies.SetStatus(context.Background(), "cid", true) + + h := &recordingHandler{} + acc := New(Config{ + CookieID: "cid", + CookieStr: "unb=123; _m_h5_tk=tk_1;", + Store: store, + Handler: h, + }) + return acc, h, store, func() { d.Close() } +} + +// TestExtractChatMessage_RealSample 用真实抓包样本验证消息字段提取。 +func TestExtractChatMessage_RealSample(t *testing.T) { + decrypted := mustDecryptGoldenSample(t) + chat := extractChatMessage(decrypted, "cid", "cookie") + if chat == nil { + t.Fatal("应为聊天消息") + } + if chat.ChatID != "47983389009" { + t.Errorf("ChatID=%q want 47983389009", chat.ChatID) + } + if chat.Text != "[我已拍下,待付款]" { + t.Errorf("Text=%q want [我已拍下,待付款]", chat.Text) + } + if chat.ItemID != "900052644277" { + t.Errorf("ItemID=%q want 900052644277", chat.ItemID) + } +} + +func TestExtractChatMessage_FiltersContentType14Notice(t *testing.T) { + decrypted := mustContentType14Notice(t) + if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil { + t.Fatalf("contentType=14 系统提示不应进入聊天回复: %+v", chat) + } +} + +func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) { + decrypted := mustRefundTradeCard(t) + if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil { + t.Fatalf("退款交易卡片不应进入聊天回复: %+v", chat) + } +} + +func TestExtractChatMessage_KeepsPaidDeliveryCard(t *testing.T) { + decrypted := mustPaidDeliveryCard(t) + chat := extractChatMessage(decrypted, "cid", "cookie") + if chat == nil { + t.Fatal("付款待发货卡片应保留用于自动发货") + } + if chat.Text != "[我已付款,等待你发货]" { + t.Fatalf("Text=%q", chat.Text) + } + if chat.ItemID != "1063177864132" { + t.Fatalf("ItemID=%q", chat.ItemID) + } +} + +func TestIsAutoDeliveryTriggerPaidCard(t *testing.T) { + if !IsAutoDeliveryTrigger("[我已付款,等待你发货]") { + t.Fatal("付款待发货卡片应触发自动发货") + } + if IsAutoDeliveryTrigger("[我已拍下,待付款]") { + t.Fatal("仅拍下未付款不应触发自动发货") + } +} + +// TestDedup_SkipsDuplicateWithinExpiry 同一消息 ID 1 小时内只处理一次。 +func TestDedup_SkipsDuplicateWithinExpiry(t *testing.T) { + acc, h, _, cleanup := newAccountForTest(t) + defer cleanup() + defer acc.Stop() + + decrypted := mustDecryptGoldenSample(t) + chat := extractChatMessage(decrypted, "cid", "cookie") + + // 首次:标记并应继续。 + if !acc.markAndCheckDedup(decrypted, chat) { + t.Fatal("首次应允许处理") + } + // 第二次同一消息 ID:应跳过。 + if acc.markAndCheckDedup(decrypted, chat) { + t.Fatal("重复消息应被去重跳过") + } + h.mu.Lock() + defer h.mu.Unlock() + if len(h.chats) != 0 { + t.Errorf("去重阶段不应投递消息,got %d", len(h.chats)) + } +} + +// TestDebounce_CoalescesRapidMessages 连续消息只投递最后一条。 +func TestDebounce_CoalescesRapidMessages(t *testing.T) { + acc, h, _, cleanup := newAccountForTest(t) + defer cleanup() + defer acc.Stop() + + decrypted := mustDecryptGoldenSample(t) + chat := extractChatMessage(decrypted, "cid", "cookie") + // 修改文本模拟连续多条。 + chat1 := *chat + chat1.Text = "第一条" + chat2 := *chat + chat2.Text = "第二条" + chat3 := *chat + chat3.Text = "第三条" + + // 用不同 decrypted(不同 msgID)触发防抖,验证同一 chat_id 合并。 + acc.scheduleDebouncedReply(chat1) + acc.scheduleDebouncedReply(chat2) + acc.scheduleDebouncedReply(chat3) + + // 等待防抖延迟 + 余量。 + time.Sleep(MessageDebounceDelay + 200*time.Millisecond) + + h.mu.Lock() + defer h.mu.Unlock() + if len(h.chats) != 1 { + t.Fatalf("防抖应只投递最后一条,got %d", len(h.chats)) + } + if h.chats[0].Text != "第三条" { + t.Errorf("应投递最后一条,got %q", h.chats[0].Text) + } +} + +// TestExtractItemID reminderUrl 中提取 itemId。 +func TestExtractItemID(t *testing.T) { + cases := map[string]string{ + "fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063": "900052644277", + "noitemid": "", + "fleamarket://x?itemId=ABC123": "ABC123", + } + for in, want := range cases { + if got := extractItemID(in); got != want { + t.Errorf("extractItemID(%q)=%q want %q", in, got, want) + } + } +} + +// mustDecryptGoldenSample 复用 protocol 包的真实样本:直接硬编码一条最小解密结构, +// 避免循环依赖。这里构造一个等价的最小消息用于字段提取测试。 +func mustDecryptGoldenSample(t *testing.T) map[string]any { + t.Helper() + // 真实样本关键字段(来自 protocol golden test 解密输出): + // message["1"]["2"]="47983389009@goofish", ["1"]["10"]["reminderContent"]="[我已拍下,待付款]", + // ["1"]["10"]["reminderUrl"] 含 itemId=900052644277 + s := `{ + "1": { + "2": "47983389009@goofish", + "10": { + "reminderContent": "[我已拍下,待付款]", + "senderNick": "买家昵称", + "senderUserId": "3149637063", + "reminderUrl": "fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063" + } + }, + "3": { + "redReminder": "等待买家付款", + "userId": "3149637063" + } + }` + var m map[string]any + if err := json.Unmarshal([]byte(s), &m); err != nil { + t.Fatalf("unmarshal: %v", err) + } + return m +} + +func mustContentType14Notice(t *testing.T) map[string]any { + t.Helper() + s := "{" + + "\"1\":{" + + "\"2\":\"63107041124@goofish\"," + + "\"10\":{" + + "\"extJson\":\"{\\\"contentType\\\":\\\"14\\\",\\\"messageId\\\":\\\"d050b73332b94d5a8901cff78519483a\\\"}\"," + + "\"reminderContent\":\"[不想宝贝被砍价?设置不砍价回复 ]\"," + + "\"senderUserId\":\"2222315258815\"," + + "\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" + + "}," + + "\"6\":{\"3\":{\"4\":14,\"5\":\"{\\\"contentType\\\":14,\\\"tip\\\":{\\\"argInfo\\\":{\\\"arg1\\\":\\\"NoBargainGuide\\\"}}}\"}}" + + "}" + + "}" + var m map[string]any + if err := json.Unmarshal([]byte(s), &m); err != nil { + t.Fatalf("unmarshal: %v", err) + } + return m +} + +func mustRefundTradeCard(t *testing.T) map[string]any { + t.Helper() + s := "{" + + "\"1\":{" + + "\"2\":\"63107041124@goofish\"," + + "\"10\":{" + + "\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:eeg858GGuju9\\\",\\\"taskName\\\":\\\"发起退款申请_卖家-新逆向url\\\"}\"," + + "\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"3a03978b7a374da898b3d7a084cbedb6\\\"}\"," + + "\"redReminder\":\"买家申请退款\"," + + "\"reminderContent\":\"[我发起了退款申请]\"," + + "\"senderUserId\":\"2222315258815\"," + + "\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" + + "}," + + "\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" + + "}" + + "}" + var m map[string]any + if err := json.Unmarshal([]byte(s), &m); err != nil { + t.Fatalf("unmarshal: %v", err) + } + return m +} + +func mustPaidDeliveryCard(t *testing.T) map[string]any { + t.Helper() + s := "{" + + "\"1\":{" + + "\"2\":\"63107041124@goofish\"," + + "\"10\":{" + + "\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:4Ytd4BSQKIiz\\\",\\\"taskName\\\":\\\"付款完成待发货_卖家-正向升级\\\"}\"," + + "\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"4e449a32c59c499594c4c5dffa5ddef0\\\"}\"," + + "\"redReminder\":\"等待卖家发货\"," + + "\"reminderContent\":\"[我已付款,等待你发货]\"," + + "\"senderUserId\":\"2222315258815\"," + + "\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" + + "}," + + "\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" + + "}" + + "}" + var m map[string]any + if err := json.Unmarshal([]byte(s), &m); err != nil { + t.Fatalf("unmarshal: %v", err) + } + return m +} + +// TestExtractSystemMessage 系统消息提取。 +func TestExtractSystemMessage(t *testing.T) { + m := mustDecryptGoldenSample(t) + sys := extractSystemMessage(m, "cid", "cookie") + if sys == nil { + t.Fatal("应为系统消息") + } + if sys.RedReminder != "等待买家付款" { + t.Errorf("RedReminder=%q", sys.RedReminder) + } +} + +// TestRetryDelay 复刻 _calculate_retry_delay 的分段逻辑。 +func TestRetryDelay(t *testing.T) { + acc, _, _, cleanup := newAccountForTest(t) + defer cleanup() + defer acc.Stop() + + acc.connFailures = 1 + if d := acc.retryDelay("no close frame received or sent"); d != 3*time.Second { + t.Errorf("close-frame failures=1: %v want 3s", d) + } + acc.connFailures = 10 + if d := acc.retryDelay("no close frame received or sent"); d != 15*time.Second { + t.Errorf("close-frame failures=10: %v want 15s (capped)", d) + } + acc.connFailures = 2 + if d := acc.retryDelay("connection refused"); d != 20*time.Second { + t.Errorf("refused failures=2: %v want 20s", d) + } + acc.connFailures = 10 + if d := acc.retryDelay("connection refused"); d != 60*time.Second { + t.Errorf("refused failures=10: %v want 60s (capped)", d) + } + acc.connFailures = 1 + if d := acc.retryDelay("some other error"); d != 5*time.Second { + t.Errorf("other failures=1: %v want 5s", d) + } +} + +func TestRuntimeStatusClassifiesAuthenticationFailures(t *testing.T) { + acc, _, _, cleanup := newAccountForTest(t) + defer cleanup() + + acc.setRuntimeError(fmt.Errorf("token API 登录凭证已失效: FAIL_SYS_TOKEN_EXOIRED")) + status := acc.RuntimeStatus() + if status.State != RuntimeAuthExpired || status.Connected { + t.Fatalf("status=%+v", status) + } + + acc.setRuntimeError(fmt.Errorf("FAIL_SYS_USER_VALIDATE: captcha required")) + status = acc.RuntimeStatus() + if status.State != RuntimeVerificationRequired { + t.Fatalf("status=%+v", status) + } +} diff --git a/internal/engine/reply.go b/internal/engine/reply.go new file mode 100644 index 0000000..3301feb --- /dev/null +++ b/internal/engine/reply.go @@ -0,0 +1,223 @@ +// reply.go 四级回复引擎:API → 关键词 → AI → 默认回复。 +// 移植自 Python _process_chat_message_reply + get_keyword_reply/get_default_reply/get_ai_reply。 +// +// Phase 3 实现:关键词(含商品ID优先+变量替换+空回复标记)、默认回复(指定商品优先+reply_once+变量替换)。 +// API 回复(调外部 /xianyu/reply 接口)和 AI 回复(OpenAI 兼容)留接口注入。 +package engine + +import ( + "context" + "fmt" + "log/slog" + "strings" + + "xianyu-go/internal/db" +) + +// ReplyResult 回复结果。 +type ReplyResult struct { + Text string // 文本回复(可空) + ImageURL string // 图片回复(可空) + Source string // 回复来源:API/关键词/AI/默认 + Skip bool // true 表示匹配到空回复,不发送任何内容 +} + +// APIReplier 外部 API 回复(优先级1)。返回 nil 表示无回复。 +type APIReplier interface { + Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error) +} + +// AIReplier AI 回复(优先级3)。返回 nil 表示无回复。 +type AIReplier interface { + Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error) +} + +// ReplyService 单账号回复服务。 +type ReplyService struct { + cookieID string + store *db.Store + api APIReplier // 可为 nil + ai AIReplier // 可为 nil + sender DeliverySender + logger *slog.Logger +} + +// NewReplyService 构造。 +func NewReplyService(cookieID string, store *db.Store, sender DeliverySender, + api APIReplier, ai AIReplier, logger *slog.Logger) *ReplyService { + if logger == nil { + logger = slog.Default() + } + return &ReplyService{ + cookieID: cookieID, + store: store, + api: api, + ai: ai, + sender: sender, + logger: logger.With("account", cookieID, "subsys", "reply"), + } +} + +// Handle 收到一条聊天消息,按四级优先级回复。 +// 由 Account 在防抖后调用。返回是否产生了回复。 +func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error { + res := r.resolve(ctx, m) + if res == nil || res.Skip { + return nil + } + // 发送:图片优先,文本随后。 + if r.sender == nil { + return nil + } + if res.ImageURL != "" { + if err := r.sender.SendImage(ctx, m.ChatID, m.SenderUserID, res.ImageURL, 0); err != nil { + r.logger.Error("发送回复图片失败", "err", err) + } + } + if res.Text != "" { + if err := r.sender.SendText(ctx, m.ChatID, m.SenderUserID, res.Text); err != nil { + r.logger.Error("发送回复文本失败", "err", err) + } + } + return nil +} + +// resolve 按优先级确定回复内容(不发送)。 +func (r *ReplyService) resolve(ctx context.Context, m ChatMessage) *ReplyResult { + // 优先级1:API 回复。 + if r.api != nil { + if res, err := r.api.Reply(ctx, m); err != nil { + r.logger.Error("API 回复失败", "err", err) + } else if res != nil { + res.Source = "API" + return res + } + } + + // 优先级2:关键词匹配。 + if res := r.keywordReply(ctx, m); res != nil { + return res + } + + // 优先级3:AI 回复。 + if r.ai != nil { + if res, err := r.ai.Reply(ctx, m); err != nil { + r.logger.Error("AI 回复失败", "err", err) + } else if res != nil { + res.Source = "AI" + return res + } + } + + // 优先级4:默认回复。 + return r.defaultReply(ctx, m) +} + +// keywordReply 关键词匹配。返回 nil 表示无匹配; +// 返回 Skip=true 表示匹配到空回复(不发送)。 +// 移植自 get_keyword_reply:商品ID关键词优先 → 通用关键词。 +func (r *ReplyService) keywordReply(ctx context.Context, m ChatMessage) *ReplyResult { + kws, err := r.store.Keywords.AllWithType(ctx, r.cookieID) + if err != nil || len(kws) == 0 { + return nil + } + msgLower := strings.ToLower(m.Text) + + // 1. 商品ID关键词优先。 + if m.ItemID != "" { + for _, kw := range kws { + if kw.ItemID == m.ItemID && strings.Contains(msgLower, strings.ToLower(kw.Keyword)) { + return r.keywordResult(kw, m) + } + } + } + // 2. 通用关键词(无 item_id)。 + for _, kw := range kws { + if kw.ItemID == "" && strings.Contains(msgLower, strings.ToLower(kw.Keyword)) { + return r.keywordResult(kw, m) + } + } + return nil +} + +func (r *ReplyService) keywordResult(kw db.Keyword, m ChatMessage) *ReplyResult { + if kw.Type == "image" && kw.ImageURL != "" { + return &ReplyResult{ImageURL: kw.ImageURL, Source: "关键词"} + } + if strings.TrimSpace(kw.Reply) == "" { + return &ReplyResult{Skip: true, Source: "关键词"} // EMPTY_REPLY + } + return &ReplyResult{Text: formatReply(kw.Reply, m), Source: "关键词"} +} + +// defaultReply 默认回复。移植自 get_default_reply: +// 指定商品回复优先 → 账号默认回复(reply_once 防重复 + 变量替换)。 +func (r *ReplyService) defaultReply(ctx context.Context, m ChatMessage) *ReplyResult { + // 1. 指定商品回复。 + if m.ItemID != "" { + if ir, err := r.store.ItemReps.Get(ctx, r.cookieID, m.ItemID); err == nil && ir != nil && strings.TrimSpace(ir.ReplyContent) != "" { + return &ReplyResult{Text: formatReplyWithItem(ir.ReplyContent, m), Source: "默认"} + } + } + // 2. 账号默认回复。 + dr, err := r.store.DefaultReps.Get(ctx, r.cookieID) + if err != nil || dr == nil || !dr.Enabled { + return nil + } + // reply_once:已回复过则跳过。 + if dr.ReplyOnce && m.ChatID != "" { + if r.store.DefaultReps.HasRecord(ctx, r.cookieID, m.ChatID) { + r.logger.Info("chat_id 已用过默认回复,跳过(reply_once)", "chat_id", m.ChatID) + return nil + } + } + // 文字和图片都为空 → 空回复标记。 + if strings.TrimSpace(dr.ReplyContent) == "" && strings.TrimSpace(dr.ReplyImageURL) == "" { + return &ReplyResult{Skip: true, Source: "默认"} + } + // 记录已回复。 + if dr.ReplyOnce && m.ChatID != "" { + _ = r.store.DefaultReps.AddRecord(ctx, r.cookieID, m.ChatID) + } + res := &ReplyResult{Source: "默认"} + if strings.TrimSpace(dr.ReplyContent) != "" { + res.Text = formatReply(dr.ReplyContent, m) + } + if strings.TrimSpace(dr.ReplyImageURL) != "" { + res.ImageURL = dr.ReplyImageURL + } + return res +} + +// formatReply 变量替换:{send_user_name} {send_user_id} {send_message}。 +// 复刻 Python reply.format(...);若替换出错返回原文。 +func formatReply(template string, m ChatMessage) string { + return safeFormat(template, map[string]string{ + "send_user_name": m.SenderName, + "send_user_id": m.SenderUserID, + "send_message": m.Text, + }) +} + +// formatReplyWithItem 含 {item_id} 变量。 +func formatReplyWithItem(template string, m ChatMessage) string { + return safeFormat(template, map[string]string{ + "send_user_name": m.SenderName, + "send_user_id": m.SenderUserID, + "send_message": m.Text, + "item_id": m.ItemID, + }) +} + +// safeFormat 实现 Python str.format 的命名占位符子集。 +// Python 用 {send_user_name},Go 标准库不支持,手动替换。 +func safeFormat(template string, vars map[string]string) string { + out := template + for k, v := range vars { + out = strings.ReplaceAll(out, "{"+k+"}", v) + } + return out +} + +// 占位防未用 fmt(未来错误信息用)。 +var _ = fmt.Sprintf diff --git a/internal/engine/reply_test.go b/internal/engine/reply_test.go new file mode 100644 index 0000000..3f17082 --- /dev/null +++ b/internal/engine/reply_test.go @@ -0,0 +1,169 @@ +package engine + +import ( + "context" + "path/filepath" + "testing" + + "xianyu-go/internal/db" +) + +func newReplyStore(t *testing.T) (*db.Store, func()) { + t.Helper() + d, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("Open: %v", err) + } + s := db.NewStore(d) + s.Users.Create(context.Background(), "admin", "a@e.com", "pw") + admin, _ := s.Users.GetByUsername(context.Background(), "admin") + s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID) + return s, func() { d.Close() } +} + +func chatMsg(text, itemID, chatID string) ChatMessage { + return ChatMessage{ + AccountID: "cid", CookieStr: "", + ChatID: chatID, SenderUserID: "buyer1", SenderName: "买家", + Text: text, ItemID: itemID, + } +} + +// TestKeywordReply_MatchAndVariableSubst 关键词匹配 + 变量替换。 +func TestKeywordReply_MatchAndVariableSubst(t *testing.T) { + s, cleanup := newReplyStore(t) + defer cleanup() + ctx := context.Background() + // 关键词 "在吗" → "你好{send_user_name},在的,请问要{send_message}吗" + s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','你好{send_user_name},在的','text')`) + + r := NewReplyService("cid", s, nil, nil, nil, nil) + res := r.resolve(ctx, chatMsg("老板在吗", "item1", "chat1")) + if res == nil || res.Source != "关键词" { + t.Fatalf("应命中关键词,got %+v", res) + } + if res.Text != "你好买家,在的" { + t.Errorf("变量替换: got %q want 你好买家,在的", res.Text) + } +} + +// TestKeywordReply_ItemIDPriority 商品ID关键词优先于通用关键词。 +func TestKeywordReply_ItemIDPriority(t *testing.T) { + s, cleanup := newReplyStore(t) + defer cleanup() + ctx := context.Background() + s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,item_id,type) VALUES + ('cid','价格','通用价格回复','','text'), + ('cid','价格','该商品专属价格回复','item1','text')`) + + r := NewReplyService("cid", s, nil, nil, nil, nil) + res := r.resolve(ctx, chatMsg("价格多少", "item1", "chat1")) + if res == nil || res.Text != "该商品专属价格回复" { + t.Errorf("应优先商品ID关键词,got %+v", res) + } + // 无 item_id 时走通用。 + res2 := r.resolve(ctx, chatMsg("价格多少", "", "chat1")) + if res2 == nil || res2.Text != "通用价格回复" { + t.Errorf("无itemID应走通用,got %+v", res2) + } +} + +// TestKeywordReply_EmptyReplySkip 匹配到空回复 → Skip。 +func TestKeywordReply_EmptyReplySkip(t *testing.T) { + s, cleanup := newReplyStore(t) + defer cleanup() + ctx := context.Background() + s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','静默','','text')`) + r := NewReplyService("cid", s, nil, nil, nil, nil) + res := r.resolve(ctx, chatMsg("静默一下", "item1", "chat1")) + if res == nil || !res.Skip { + t.Fatalf("空回复应 Skip=true,got %+v", res) + } +} + +// TestDefaultReply_ItemReplyFirst 指定商品回复优先于账号默认回复。 +func TestDefaultReply_ItemReplyFirst(t *testing.T) { + s, cleanup := newReplyStore(t) + defer cleanup() + ctx := context.Background() + s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'账号默认回复',0)`) + s.DB.ExecContext(ctx, `INSERT INTO item_replay (item_id,cookie_id,reply_content) VALUES ('item1','cid','该商品专属默认回复')`) + + r := NewReplyService("cid", s, nil, nil, nil, nil) + res := r.resolve(ctx, chatMsg("任意消息", "item1", "chat1")) + if res == nil || res.Text != "该商品专属默认回复" { + t.Errorf("应优先指定商品回复,got %+v", res) + } +} + +// TestDefaultReply_ReplyOnce reply_once 防重复。 +func TestDefaultReply_ReplyOnce(t *testing.T) { + s, cleanup := newReplyStore(t) + defer cleanup() + ctx := context.Background() + s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认问候',1)`) + + r := NewReplyService("cid", s, nil, nil, nil, nil) + // 首次:应回复。 + res1 := r.resolve(ctx, chatMsg("在吗", "item1", "chatX")) + if res1 == nil || res1.Text != "默认问候" { + t.Fatalf("首次应回复,got %+v", res1) + } + // 第二次同 chat_id:reply_once 应跳过。 + res2 := r.resolve(ctx, chatMsg("还在吗", "item1", "chatX")) + if res2 != nil { + t.Fatalf("reply_once 应跳过第二次,got %+v", res2) + } + // 不同 chat_id:应回复。 + res3 := r.resolve(ctx, chatMsg("在吗", "item1", "chatY")) + if res3 == nil || res3.Text != "默认问候" { + t.Fatalf("不同 chat_id 应回复,got %+v", res3) + } +} + +// TestPriority_Order 四级优先级:关键词 > 默认(无API/AI时)。 +func TestPriority_Order(t *testing.T) { + s, cleanup := newReplyStore(t) + defer cleanup() + ctx := context.Background() + s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','关键词回复','text')`) + s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认回复',0)`) + + r := NewReplyService("cid", s, nil, nil, nil, nil) + // 命中关键词 → 关键词回复。 + res := r.resolve(ctx, chatMsg("在吗", "", "chat1")) + if res == nil || res.Source != "关键词" { + t.Errorf("应优先关键词,got %+v", res) + } + // 不命中关键词 → 默认回复。 + res2 := r.resolve(ctx, chatMsg("别的消息", "", "chat1")) + if res2 == nil || res2.Source != "默认" { + t.Errorf("无关键词应走默认,got %+v", res2) + } +} + +// TestFormatReply 变量替换。 +func TestFormatReply(t *testing.T) { + m := chatMsg("想买", "item1", "chat1") + m.SenderName = "张三" + got := formatReply("你好{send_user_name},你说{send_message}", m) + if got != "你好张三,你说想买" { + t.Errorf("formatReply=%q", got) + } +} + +// TestParsePrice 价格解析。 +func TestParsePrice(t *testing.T) { + cases := map[string]float64{ + "¥99.5": 99.5, + "100元": 100, + "": 0, + "abc": 0, + "12.34": 12.34, + } + for in, want := range cases { + if got := parsePrice(in); got != want { + t.Errorf("parsePrice(%q)=%v want %v", in, got, want) + } + } +} diff --git a/internal/logsafe/logsafe.go b/internal/logsafe/logsafe.go new file mode 100644 index 0000000..5b06e69 --- /dev/null +++ b/internal/logsafe/logsafe.go @@ -0,0 +1,29 @@ +// Package logsafe contains helpers for logging identifiers without leaking +// account tokens, verification URLs, or full platform IDs. +package logsafe + +import ( + "crypto/sha256" + "encoding/hex" + "net/url" + "strings" +) + +// ID returns a short stable fingerprint for a sensitive identifier. +func ID(s string) string { + s = strings.TrimSpace(s) + if s == "" { + return "" + } + sum := sha256.Sum256([]byte(s)) + return hex.EncodeToString(sum[:])[:12] +} + +// URL returns origin + path for URLs that may contain session tokens. +func URL(raw string) string { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u.Scheme == "" || u.Host == "" { + return "" + } + return u.Scheme + "://" + u.Host + u.EscapedPath() +} diff --git a/internal/notify/notifier.go b/internal/notify/notifier.go new file mode 100644 index 0000000..bb2990d --- /dev/null +++ b/internal/notify/notifier.go @@ -0,0 +1,298 @@ +// Package notify 多渠道通知:dingtalk/feishu/lark/bark/webhook/wechat/telegram/email。 +// 移植自 Python _send_*_notification 系列。每个渠道解析 config JSON 后 POST。 +// email 用 SMTP(net/smtp);其余为 HTTP POST。 +package notify + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/smtp" + "strconv" + "strings" + "time" + + "xianyu-go/internal/db" +) + +// Notifier 通知发送器(实现 engine.Notifier 接口)。 +type Notifier struct { + cookieID string + store *db.Store + logger *slog.Logger + httpc *http.Client +} + +// New 构造。 +func New(cookieID string, store *db.Store, logger *slog.Logger) *Notifier { + if logger == nil { + logger = slog.Default() + } + return &Notifier{ + cookieID: cookieID, + store: store, + logger: logger.With("account", cookieID, "subsys", "notify"), + httpc: &http.Client{Timeout: 10 * time.Second}, + } +} + +// NotifyDelivery 实现 engine.Notifier.NotifyDelivery。 +// accountID 为 cookie_id。向该账号所有已启用渠道发送发货通知。 +func (n *Notifier) NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string) { + channels, err := n.store.Notifications.AccountChannels(context.Background(), accountID) + if err != nil || len(channels) == 0 { + return + } + // 复刻 Python 通知文案。 + body := fmt.Sprintf("🚨 自动发货通知\n\n账号: %s\n买家: %s (ID: %s)\n商品ID: %s\n聊天ID: %s\n结果: %s\n时间: %s\n\n请及时处理!", + accountID, buyerName, buyerID, itemID, fallback(chatID, "未知"), message, time.Now().Format("2006-01-02 15:04:05")) + for _, ch := range channels { + if err := n.send(ch, body); err != nil { + n.logger.Error("发送通知失败", "channel", ch.Type, "err", err) + } + } +} + +func (n *Notifier) send(ch db.NotificationChannel, message string) error { + cfg := parseConfig(ch.Config) + switch ch.Type { + case "ding_talk", "dingtalk": + return n.sendDingTalk(cfg, message) + case "feishu", "lark": + return n.sendFeishu(cfg, message) + case "bark": + return n.sendBark(cfg, message) + case "webhook": + return n.sendWebhook(cfg, message) + case "wechat": + return n.sendWeChat(cfg, message) + case "telegram": + return n.sendTelegram(cfg, message) + case "email": + return n.sendEmail(cfg, message) + case "qq": + // QQ 渠道配置未标准化,跳过。 + return fmt.Errorf("qq 渠道暂不支持") + default: + return fmt.Errorf("不支持的通知渠道类型: %s", ch.Type) + } +} + +// parseConfig 解析 config JSON,失败时兼容旧格式 {"config": }。 +func parseConfig(config string) map[string]any { + if config == "" { + return map[string]any{} + } + var m map[string]any + if err := json.Unmarshal([]byte(config), &m); err != nil { + return map[string]any{"config": config} + } + return m +} + +// ---- 钉钉 ---- +func (n *Notifier) sendDingTalk(cfg map[string]any, message string) error { + webhook := strOr(cfg, "webhook_url", strOr(cfg, "config", "")) + secret := strOr(cfg, "secret", "") + if webhook == "" { + return fmt.Errorf("钉钉 webhook_url 为空") + } + if secret != "" { + ts := strconv.FormatInt(time.Now().UnixMilli(), 10) + stringToSign := ts + "\n" + secret + h := hmac.New(sha256.New, []byte(secret)) + h.Write([]byte(stringToSign)) + sign := base64.StdEncoding.EncodeToString(h.Sum(nil)) + webhook += "×tamp=" + ts + "&sign=" + sign + } + payload := map[string]any{ + "msgtype": "markdown", + "markdown": map[string]any{ + "title": "闲鱼自动回复通知", + "text": message, + }, + } + return n.postJSON(webhook, payload) +} + +// ---- 飞书 ---- +func (n *Notifier) sendFeishu(cfg map[string]any, message string) error { + webhook := strOr(cfg, "webhook_url", "") + secret := strOr(cfg, "secret", "") + if webhook == "" { + return fmt.Errorf("飞书 webhook_url 为空") + } + ts := strconv.FormatInt(time.Now().Unix(), 10) + data := map[string]any{ + "msg_type": "text", + "content": map[string]any{"text": message}, + "timestamp": ts, + } + if secret != "" { + stringToSign := ts + "\n" + secret + h := hmac.New(sha256.New, []byte(stringToSign)) + h.Write([]byte("")) + data["sign"] = base64.StdEncoding.EncodeToString(h.Sum(nil)) + } + return n.postJSON(webhook, data) +} + +// ---- Bark ---- +func (n *Notifier) sendBark(cfg map[string]any, message string) error { + server := strings.TrimRight(strOr(cfg, "server_url", "https://api.day.app"), "/") + deviceKey := strOr(cfg, "device_key", "") + if deviceKey == "" { + return fmt.Errorf("bark device_key 为空") + } + data := map[string]any{ + "device_key": deviceKey, + "title": strOr(cfg, "title", "闲鱼自动回复通知"), + "body": message, + "sound": strOr(cfg, "sound", "default"), + "group": strOr(cfg, "group", "xianyu"), + } + if icon := strOr(cfg, "icon", ""); icon != "" { + data["icon"] = icon + } + if u := strOr(cfg, "url", ""); u != "" { + data["url"] = u + } + return n.postJSON(server+"/push", data) +} + +// ---- Webhook ---- +func (n *Notifier) sendWebhook(cfg map[string]any, message string) error { + webhook := strOr(cfg, "webhook_url", "") + if webhook == "" { + return fmt.Errorf("webhook_url 为空") + } + method := strings.ToUpper(strOr(cfg, "http_method", "POST")) + headers := map[string]any{} + if h := strOr(cfg, "headers", ""); h != "" { + _ = json.Unmarshal([]byte(h), &headers) + } + data := map[string]any{ + "message": message, + "timestamp": time.Now().Format("2006-01-02 15:04:05"), + "source": "xianyu-auto-reply", + } + body, _ := json.Marshal(data) + req, err := http.NewRequest(method, webhook, bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + for k, v := range headers { + req.Header.Set(k, fmt.Sprintf("%v", v)) + } + resp, err := n.httpc.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + io.Copy(io.Discard, resp.Body) + if resp.StatusCode >= 300 { + return fmt.Errorf("webhook 状态码 %d", resp.StatusCode) + } + return nil +} + +// ---- 企业微信 ---- +func (n *Notifier) sendWeChat(cfg map[string]any, message string) error { + webhook := strOr(cfg, "webhook_url", "") + if webhook == "" { + return fmt.Errorf("微信 webhook_url 为空") + } + return n.postJSON(webhook, map[string]any{ + "msgtype": "text", + "text": map[string]any{"content": message}, + }) +} + +// ---- Telegram ---- +func (n *Notifier) sendTelegram(cfg map[string]any, message string) error { + botToken := strOr(cfg, "bot_token", "") + chatID := strOr(cfg, "chat_id", "") + if botToken == "" || chatID == "" { + return fmt.Errorf("telegram bot_token/chat_id 不完整") + } + url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken) + return n.postJSON(url, map[string]any{ + "chat_id": chatID, + "text": message, + "parse_mode": "HTML", + }) +} + +// ---- 邮件 ---- +func (n *Notifier) sendEmail(cfg map[string]any, message string) error { + server := strOr(cfg, "smtp_server", "") + port := strOr(cfg, "smtp_port", "587") + user := strOr(cfg, "smtp_user", "") + pass := strOr(cfg, "smtp_password", "") + from := strOr(cfg, "smtp_from", "") + to := strOr(cfg, "to_email", strOr(cfg, "email", "")) + if server == "" || user == "" || to == "" { + return fmt.Errorf("邮件配置不完整") + } + if from == "" { + from = user + } + addr := server + ":" + port + auth := smtp.PlainAuth("", user, pass, server) + msg := strings.Join([]string{ + "From: " + from, + "To: " + to, + "Subject: =?UTF-8?B?" + base64.StdEncoding.EncodeToString([]byte("闲鱼自动发货通知")) + "?=", + "MIME-Version: 1.0", + "Content-Type: text/plain; charset=UTF-8", + "", + message, + }, "\r\n") + return smtp.SendMail(addr, auth, from, []string{to}, []byte(msg)) +} + +// postJSON 通用 JSON POST。 +func (n *Notifier) postJSON(url string, payload any) error { + body, err := json.Marshal(payload) + if err != nil { + return err + } + resp, err := n.httpc.Post(url, "application/json", bytes.NewReader(body)) + if err != nil { + return err + } + defer resp.Body.Close() + io.Copy(io.Discard, resp.Body) + if resp.StatusCode >= 300 { + return fmt.Errorf("状态码 %d", resp.StatusCode) + } + return nil +} + +// strOr 从 map 取字符串,缺失返回 fallback。 +func strOr(m map[string]any, key, fallback string) string { + if v, ok := m[key]; ok { + switch x := v.(type) { + case string: + return x + default: + return fmt.Sprintf("%v", x) + } + } + return fallback +} + +func fallback(s, def string) string { + if s == "" { + return def + } + return s +} diff --git a/internal/notify/notifier_test.go b/internal/notify/notifier_test.go new file mode 100644 index 0000000..8f91100 --- /dev/null +++ b/internal/notify/notifier_test.go @@ -0,0 +1,170 @@ +package notify + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "xianyu-go/internal/db" +) + +func newNotifyStore(t *testing.T) (*db.Store, func()) { + t.Helper() + d, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("Open: %v", err) + } + s := db.NewStore(d) + s.Users.Create(context.Background(), "admin", "a@e.com", "pw") + admin, _ := s.Users.GetByUsername(context.Background(), "admin") + s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID) + return s, func() { d.Close() } +} + +// TestSendDingTalk 钉钉渠道 POST 正确 payload。 +func TestSendDingTalk(t *testing.T) { + s, cleanup := newNotifyStore(t) + defer cleanup() + + var got map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(b, &got) + w.WriteHeader(200) + })) + defer srv.Close() + + n := New("cid", s, nil) + cfg := `{"webhook_url":"` + srv.URL + `"}` + ch := db.NotificationChannel{ID: 1, Name: "钉钉", Type: "ding_talk", Config: cfg} + if err := n.send(ch, "测试消息"); err != nil { + t.Fatalf("send dingtalk: %v", err) + } + if got["msgtype"] != "markdown" { + t.Errorf("msgtype=%v want markdown", got["msgtype"]) + } + md, _ := got["markdown"].(map[string]any) + if md["text"] != "测试消息" { + t.Errorf("text=%v", md["text"]) + } +} + +// TestSendTelegram Telegram 渠道。 +func TestSendTelegram(t *testing.T) { + s, cleanup := newNotifyStore(t) + defer cleanup() + + var got map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(b, &got) + w.WriteHeader(200) + })) + defer srv.Close() + + n := New("cid", s, nil) + // 用 config 覆盖 API URL 不可行(硬编码),故直接调内部 sendTelegram。 + cfg := map[string]any{"bot_token": "TOKEN", "chat_id": "123"} + // 临时替换 httpc 的 URL:用 srv.URL 作为 webhook。sendTelegram 硬编码了 telegram API, + // 这里改用 dingtalk server 验证 JSON 形状已覆盖;Telegram 单独验证配置校验。 + if err := n.sendTelegram(cfg, "hi"); err == nil { + // 实际会尝试连 api.telegram.org,可能失败;仅验证不 panic。 + } + // 配置不全应返回 error。 + if err := n.sendTelegram(map[string]any{"bot_token": ""}, "hi"); err == nil { + t.Fatal("缺 chat_id 应报错") + } + _ = got +} + +// TestRouteByChannelType 渠道类型路由。 +func TestRouteByChannelType(t *testing.T) { + s, cleanup := newNotifyStore(t) + defer cleanup() + n := New("cid", s, nil) + + // 不支持的类型应返回 error。 + err := n.send(db.NotificationChannel{Type: "unknown"}, "x") + if err == nil { + t.Fatal("未知渠道应报错") + } + // QQ 渠道暂不支持。 + if err := n.send(db.NotificationChannel{Type: "qq"}, "x"); err == nil { + t.Fatal("qq 渠道应报错") + } +} + +// TestNotifyDelivery_NoChannels 无通知配置时不报错。 +func TestNotifyDelivery_NoChannels(t *testing.T) { + s, cleanup := newNotifyStore(t) + defer cleanup() + n := New("cid", s, nil) + // 不应 panic。 + n.NotifyDelivery("cid", "买家", "b1", "item1", "发货成功", "chat1") +} + +// TestNotifyDelivery_WithChannel 有渠道时发送。 +func TestNotifyDelivery_WithChannel(t *testing.T) { + s, cleanup := newNotifyStore(t) + defer cleanup() + ctx := context.Background() + admin, _ := s.Users.GetByUsername(ctx, "admin") + _ = admin + + var gotBody string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + gotBody = string(b) + w.WriteHeader(200) + })) + defer srv.Close() + + // 插入一个 webhook 渠道 + 绑定。 + res, _ := s.DB.ExecContext(ctx, + `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('测试','webhook',?,1,1)`, + `{"webhook_url":"`+srv.URL+`"}`) + chID, _ := res.LastInsertId() + s.DB.ExecContext(ctx, + `INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('cid',?,1)`, chID) + + n := New("cid", s, nil) + n.NotifyDelivery("cid", "买家甲", "b1", "item1", "发货成功", "chat1") + if gotBody == "" { + t.Fatal("应发送通知") + } + if !contains(gotBody, "买家甲") || !contains(gotBody, "发货成功") { + t.Errorf("通知正文异常: %s", gotBody) + } +} + +// TestParseConfig 旧格式兼容。 +func TestParseConfig(t *testing.T) { + // 标准 JSON。 + m := parseConfig(`{"webhook_url":"http://x"}`) + if m["webhook_url"] != "http://x" { + t.Errorf("JSON 解析: %v", m) + } + // 旧格式字符串。 + m2 := parseConfig(`http://old`) + if m2["config"] != "http://old" { + t.Errorf("旧格式兼容: %v", m2) + } + // 空字符串。 + m3 := parseConfig("") + if len(m3) != 0 { + t.Errorf("空配置: %v", m3) + } +} + +func contains(s, sub string) bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +} diff --git a/internal/server/admin_handlers.go b/internal/server/admin_handlers.go new file mode 100644 index 0000000..0e7ee3b --- /dev/null +++ b/internal/server/admin_handlers.go @@ -0,0 +1,118 @@ +package server + +import ( + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// mountAdminReal 管理员端点。 +func (s *Server) mountAdminReal(r chi.Router) { + r.Get("/admin/users", s.adminListUsers) + r.Delete("/admin/users/{user_id}", s.adminDeleteUser) + r.Get("/admin/cookies", s.adminListCookies) + r.Get("/admin/stats", s.adminStats) +} + +func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) { + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT id, username, email, is_active, is_admin, created_at FROM users ORDER BY id`) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + var out []map[string]any + for rows.Next() { + var id int64 + var username, email, createdAt string + var isActive, isAdmin int + if err := rows.Scan(&id, &username, &email, &isActive, &isAdmin, &createdAt); err != nil { + continue + } + // 统计每个用户的账号数。 + var cookieCount int + s.Store.DB.QueryRowContext(r.Context(), + `SELECT COUNT(*) FROM cookies WHERE user_id=?`, id).Scan(&cookieCount) + out = append(out, map[string]any{ + "id": id, "username": username, "email": email, + "is_active": isActive != 0, "is_admin": isAdmin != 0, + "created_at": createdAt, "cookie_count": cookieCount, + }) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) { + uid, err := strconv.ParseInt(chi.URLParam(r, "user_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效用户ID") + return + } + // 不允许删除自己。 + sess := authSess(r) + if sess.UserID == uid { + writeErr(w, http.StatusBadRequest, "不能删除当前登录用户") + return + } + _, err = s.Store.DB.ExecContext(r.Context(), `DELETE FROM users WHERE id=?`, uid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) { + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT c.id, c.user_id, COALESCE(c.remark,''), c.created_at, u.username + FROM cookies c LEFT JOIN users u ON c.user_id=u.id ORDER BY c.created_at DESC`) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + var out []map[string]any + for rows.Next() { + var id string + var uid int64 + var remark, createdAt, username string + if err := rows.Scan(&id, &uid, &remark, &createdAt, &username); err != nil { + continue + } + out = append(out, map[string]any{ + "id": id, "user_id": uid, "remark": remark, + "created_at": createdAt, "owner": username, + "enabled": s.Store.Cookies.GetStatus(r.Context(), id), + }) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) { + // 字段名与前端 AdminStats 接口对齐: + // total_users / total_cookies / active_cookies / total_cards / total_keywords / total_orders + var totalUsers, totalCookies, totalCards, totalOrders, totalKeywords int64 + s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM users`).Scan(&totalUsers) + s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM cookies`).Scan(&totalCookies) + s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM cards`).Scan(&totalCards) + s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM orders`).Scan(&totalOrders) + s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM keywords`).Scan(&totalKeywords) + + // 活跃账号:cookie_status.enabled=1 的数量(无记录默认启用,故统计 enabled=1 或无记录的)。 + var activeCookies int64 + s.Store.DB.QueryRowContext(r.Context(), ` + SELECT COUNT(*) FROM cookies c + WHERE NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0) + `).Scan(&activeCookies) + + writeJSON(w, http.StatusOK, map[string]int64{ + "total_users": totalUsers, + "total_cookies": totalCookies, + "active_cookies": activeCookies, + "total_cards": totalCards, + "total_keywords": totalKeywords, + "total_orders": totalOrders, + }) +} diff --git a/internal/server/analytics_handlers.go b/internal/server/analytics_handlers.go new file mode 100644 index 0000000..558f582 --- /dev/null +++ b/internal/server/analytics_handlers.go @@ -0,0 +1,211 @@ +package server + +import ( + "net/http" + "strings" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" +) + +// mountAnalyticsReal 订单分析端点(仪表盘 BI 报表用)。 +func (s *Server) mountAnalyticsReal(r chi.Router) { + r.Get("/analytics/orders", s.orderAnalytics) + r.Get("/analytics/orders/valid", s.validOrders) +} + +// 有效订单状态(只统计这几种,与 Python 一致)。 +var validOrderStatuses = []string{"pending_ship", "shipped", "completed"} + +// orderAnalytics 订单分析:收益统计 + 按日/状态/城市/商品分布。 +// 移植自 Python get_order_analytics。 +func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + startDate := r.URL.Query().Get("start_date") + endDate := r.URL.Query().Get("end_date") + + // 构建 WHERE 条件(user_id 通过 cookies 关联过滤)。 + where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses) + // 金额清洗:去掉 ¥ 和逗号后转 REAL。 + amountClean := `CAST(REPLACE(REPLACE(amount, '¥', ''), ',', '') AS REAL)` + amountFilter := ` AND amount IS NOT NULL AND amount != '' AND amount != 'N/A'` + + // 1. 收益统计。 + var rev struct { + TotalOrders int + TotalAmount float64 + AvgAmount float64 + UniqueBuyers int + UniqueItems int + } + s.Store.DB.QueryRowContext(r.Context(), ` + SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0), + COALESCE(AVG(`+amountClean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id) + FROM orders `+where+amountFilter, params...).Scan( + &rev.TotalOrders, &rev.TotalAmount, &rev.AvgAmount, &rev.UniqueBuyers, &rev.UniqueItems) + + // 2. 按日统计。 + daily := []map[string]any{} + rows, err := s.Store.DB.QueryContext(r.Context(), ` + SELECT DATE(created_at), COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0) + FROM orders `+where+amountFilter+` + GROUP BY DATE(created_at) ORDER BY DATE(created_at) DESC LIMIT 30`, params...) + if err == nil { + for rows.Next() { + var date string + var count int + var amount float64 + if rows.Scan(&date, &count, &amount) == nil { + daily = append(daily, map[string]any{ + "date": date, "order_count": count, "amount": round2(amount), + }) + } + } + rows.Close() + } + + // 3. 按状态统计。 + statusStats := []map[string]any{} + rows, err = s.Store.DB.QueryContext(r.Context(), ` + SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0) + FROM orders `+where+amountFilter+` + GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, params...) + if err == nil { + for rows.Next() { + var status string + var count int + var amount float64 + if rows.Scan(&status, &count, &amount) == nil { + statusStats = append(statusStats, map[string]any{ + "status": status, "count": count, "amount": round2(amount), + }) + } + } + rows.Close() + } + + // 4. 按城市统计。 + cityStats := []map[string]any{} + rows, err = s.Store.DB.QueryContext(r.Context(), ` + SELECT receiver_city, COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0) + FROM orders `+where+amountFilter+` + AND receiver_city IS NOT NULL AND receiver_city != '' + GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, params...) + if err == nil { + for rows.Next() { + var city string + var count int + var amount float64 + if rows.Scan(&city, &count, &amount) == nil { + cityStats = append(cityStats, map[string]any{ + "city": city, "order_count": count, "total_amount": round2(amount), + }) + } + } + rows.Close() + } + + // 5. 商品排行。 + itemStats := []map[string]any{} + rows, err = s.Store.DB.QueryContext(r.Context(), ` + SELECT item_id, COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0), COALESCE(AVG(`+amountClean+`),0) + FROM orders `+where+amountFilter+` + AND item_id IS NOT NULL AND item_id != '' + GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, params...) + if err == nil { + for rows.Next() { + var itemID string + var count int + var total, avg float64 + if rows.Scan(&itemID, &count, &total, &avg) == nil { + itemStats = append(itemStats, map[string]any{ + "item_id": itemID, "order_count": count, + "total_amount": round2(total), "avg_amount": round2(avg), + }) + } + } + rows.Close() + } + + writeJSON(w, http.StatusOK, map[string]any{ + "revenue_stats": map[string]any{ + "total_orders": rev.TotalOrders, "total_amount": round2(rev.TotalAmount), + "avg_amount": round2(rev.AvgAmount), "unique_buyers": rev.UniqueBuyers, + "unique_items": rev.UniqueItems, + }, + "daily_stats": daily, + "status_stats": statusStats, + "city_stats": cityStats, + "item_stats": itemStats, + }) +} + +// validOrders 有效订单明细列表(用于统计中的订单明细)。 +func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + startDate := r.URL.Query().Get("start_date") + endDate := r.URL.Query().Get("end_date") + where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses) + + rows, err := s.Store.DB.QueryContext(r.Context(), ` + SELECT order_id, item_id, buyer_id, amount, order_status, cookie_id, created_at + FROM orders `+where+` ORDER BY created_at DESC LIMIT 500`, params...) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + out := []map[string]any{} + for rows.Next() { + var orderID, itemID, buyerID, amount, status, cookieID, createdAt string + if rows.Scan(&orderID, &itemID, &buyerID, &amount, &status, &cookieID, &createdAt) == nil { + out = append(out, map[string]any{ + "order_id": orderID, "item_id": itemID, "buyer_id": buyerID, + "amount": amount, "order_status": status, "cookie_id": cookieID, + "created_at": createdAt, + }) + } + } + writeJSON(w, http.StatusOK, out) +} + +// buildAnalyticsWhere 构建 WHERE 子句(user_id 经 cookies 关联过滤 + 日期 + 状态)。 +// 返回 (whereClause, params),whereClause 已含 WHERE 前缀。 +func buildAnalyticsWhere(startDate, endDate string, userID int64, statuses []string) (string, []any) { + conds := []string{} + params := []any{} + if startDate != "" { + conds = append(conds, "DATE(created_at) >= ?") + params = append(params, startDate) + } + if endDate != "" { + conds = append(conds, "DATE(created_at) <= ?") + params = append(params, endDate) + } + if userID != 0 { + conds = append(conds, "EXISTS (SELECT 1 FROM cookies WHERE cookies.id = orders.cookie_id AND cookies.user_id = ?)") + params = append(params, userID) + } + if len(statuses) > 0 { + ph := strings.Repeat("?,", len(statuses)) + ph = strings.TrimSuffix(ph, ",") + conds = append(conds, "order_status IN ("+ph+")") + for _, s := range statuses { + params = append(params, s) + } + } + where := "" + if len(conds) > 0 { + where = "WHERE " + strings.Join(conds, " AND ") + } + // 后续 AND 需要前置空格。 + if where != "" { + where += " " + } + return where, params +} + +func round2(f float64) float64 { + return float64(int(f*100+0.5)) / 100 +} diff --git a/internal/server/auth_handlers.go b/internal/server/auth_handlers.go new file mode 100644 index 0000000..af4cda4 --- /dev/null +++ b/internal/server/auth_handlers.go @@ -0,0 +1,228 @@ +package server + +import ( + "errors" + "net/http" + "strings" + "unicode/utf8" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" +) + +// loginRequest 对应 Python LoginRequest。 +type loginRequest struct { + Username string `json:"username,omitempty"` + Email string `json:"email,omitempty"` + Password string `json:"password,omitempty"` + VerificationCode string `json:"verification_code,omitempty"` +} + +// loginResponse 对应 Python LoginResponse。 +type loginResponse struct { + Success bool `json:"success"` + Token *string `json:"token"` + Message string `json:"message"` + UserID int64 `json:"user_id,omitempty"` + Username string `json:"username,omitempty"` + IsAdmin bool `json:"is_admin"` +} + +// login 用户名密码登录(邮箱登录同走此接口,按字段判断)。 +func (s *Server) login(w http.ResponseWriter, r *http.Request) { + var req loginRequest + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + + var resp loginResponse + + switch { + case req.Username != "" && req.Password != "": + sid, user, err := s.Auth.Login(r.Context(), req.Username, req.Password) + if err != nil || user == nil || sid == "" { + resp = loginResponse{Success: false, Message: "用户名或密码错误"} + writeJSON(w, http.StatusOK, resp) + return + } + resp = loginResponse{ + Success: true, Token: nil, Message: "登录成功", + UserID: user.ID, Username: user.Username, + IsAdmin: user.IsAdmin, + } + s.Auth.SetSessionCookie(w, sid) + writeJSON(w, http.StatusOK, resp) + return + case req.Email != "" && req.Password != "": + user, err := s.Store.Users.GetByEmail(r.Context(), req.Email) + if err != nil || user == nil { + resp = loginResponse{Success: false, Message: "邮箱或密码错误"} + writeJSON(w, http.StatusOK, resp) + return + } + sid, loginUser, lerr := s.Auth.Login(r.Context(), user.Username, req.Password) + if lerr != nil || loginUser == nil || sid == "" { + resp = loginResponse{Success: false, Message: "邮箱或密码错误"} + writeJSON(w, http.StatusOK, resp) + return + } + resp = loginResponse{ + Success: true, Token: nil, Message: "登录成功", + UserID: loginUser.ID, Username: loginUser.Username, + IsAdmin: loginUser.IsAdmin, + } + s.Auth.SetSessionCookie(w, sid) + writeJSON(w, http.StatusOK, resp) + return + default: + writeErr(w, http.StatusBadRequest, "缺少登录凭据") + } +} + +// verify 校验会话有效性。返回 authenticated / initialized / is_admin。 +func (s *Server) verify(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + initialized, _ := s.Store.Users.IsSystemInitialized(ctx) + sess := auth.SessionFromContext(ctx) + if sess != nil { + writeJSON(w, http.StatusOK, map[string]any{ + "authenticated": true, + "user_id": sess.UserID, + "username": sess.Username, + "is_admin": sess.IsAdmin, + "initialized": initialized, + }) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "authenticated": false, + "initialized": initialized, + }) +} + +// logout 登出。 +func (s *Server) logout(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + if sess != nil { + s.Auth.Logout(r.Context(), sess.SessionID) + } + s.Auth.ClearSessionCookie(w) + writeJSON(w, http.StatusOK, map[string]any{"message": "已登出"}) +} + +// changeAdminPassword 修改管理员密码。 +func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) { + var req struct { + CurrentPassword string `json:"current_password"` + NewPassword string `json:"new_password"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + ctx := r.Context() + sess := auth.SessionFromContext(ctx) + if sess == nil || !sess.IsAdmin { + writeErr(w, http.StatusForbidden, "仅管理员可执行此操作") + return + } + // 校验当前密码。 + user, ok, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword) + if !ok || user == nil { + writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "当前密码错误"}) + return + } + if _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil { + writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "更新失败"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功"}) +} + +// changePassword 修改当前用户密码。 +func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) { + var req struct { + CurrentPassword string `json:"current_password"` + NewPassword string `json:"new_password"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + ctx := r.Context() + sess := auth.SessionFromContext(ctx) + if sess == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") + return + } + user, _, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword) + if user == nil { + writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "当前密码错误"}) + return + } + if _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil { + writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "更新失败"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功"}) +} + +// updateCredentials 修改当前登录用户的用户名和/或密码,并撤销全部旧会话。 +func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) { + var req struct { + CurrentPassword string `json:"current_password"` + NewUsername string `json:"new_username"` + NewPassword string `json:"new_password"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + sess := auth.SessionFromContext(r.Context()) + if sess == nil { + writeErr(w, http.StatusUnauthorized, "未授权访问") + return + } + username := strings.TrimSpace(req.NewUsername) + usernameLength := utf8.RuneCountInString(username) + if usernameLength < 3 || usernameLength > 64 { + writeErr(w, http.StatusBadRequest, "用户名长度必须为 3 到 64 个字符") + return + } + if strings.TrimSpace(req.CurrentPassword) == "" { + writeErr(w, http.StatusBadRequest, "请输入当前密码") + return + } + if req.NewPassword != "" && utf8.RuneCountInString(req.NewPassword) < 8 { + writeErr(w, http.StatusBadRequest, "新密码至少需要 8 个字符") + return + } + if username == sess.Username && req.NewPassword == "" { + writeErr(w, http.StatusBadRequest, "用户名和密码均未修改") + return + } + user, ok, err := s.Store.Users.VerifyAndUpgrade(r.Context(), sess.Username, req.CurrentPassword) + if err != nil { + writeErr(w, http.StatusInternalServerError, "验证当前密码失败") + return + } + if !ok || user == nil || user.ID != sess.UserID { + writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "当前密码错误"}) + return + } + if err := s.Store.Users.UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil { + if errors.Is(err, db.ErrUsernameTaken) { + writeJSON(w, http.StatusConflict, map[string]any{"success": false, "message": "用户名已被占用"}) + return + } + writeErr(w, http.StatusInternalServerError, "更新登录凭据失败") + return + } + s.Auth.ClearSessionCookie(w) + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "message": "登录凭据已更新,请使用新用户名和密码重新登录", + "requires_relogin": true, + }) +} diff --git a/internal/server/card_handlers.go b/internal/server/card_handlers.go new file mode 100644 index 0000000..d3c5c00 --- /dev/null +++ b/internal/server/card_handlers.go @@ -0,0 +1,419 @@ +package server + +import ( + "context" + "database/sql" + "net/http" + "strconv" + "strings" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" +) + +// mountCardsReal 卡券与发货规则 CRUD(真实实现)。 +func (s *Server) mountCardsReal(r chi.Router) { + r.Get("/cards", s.listCards) + r.Post("/cards", s.createCard) + r.Get("/cards/{card_id}/details", s.getCard) + r.Get("/cards/{card_id}", s.getCard) + r.Put("/cards/{card_id}", s.updateCard) + r.Delete("/cards/{card_id}", s.deleteCard) + r.Get("/delivery-rules", s.listDeliveryRules) + r.Post("/delivery-rules", s.createDeliveryRule) + r.Put("/delivery-rules/{rule_id}", s.updateDeliveryRule) + r.Delete("/delivery-rules/{rule_id}", s.deleteDeliveryRule) +} + +func (s *Server) listCards(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + cards, err := s.Store.Cards.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + writeJSON(w, http.StatusOK, cards) +} + +func (s *Server) getCard(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效卡券ID") + return + } + cf, err := s.Store.Cards.Get(r.Context(), id) + if err != nil { + writeErr(w, http.StatusNotFound, "卡券不存在") + return + } + writeJSON(w, http.StatusOK, cf) +} + +func (s *Server) createCard(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + cf, err := decodeCard(r) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + cf.UserID = sess.UserID + id, err := s.Store.Cards.Create(r.Context(), cf) + if err != nil { + writeErr(w, http.StatusInternalServerError, "创建失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id}) +} + +func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效卡券ID") + return + } + cf, err := decodeCard(r) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + cf.ID = id + if err := s.Store.Cards.Update(r.Context(), cf); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效卡券ID") + return + } + if err := s.Store.Cards.Delete(r.Context(), id); err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func decodeCard(r *http.Request) (*db.CardFull, error) { + var req struct { + Name string `json:"name"` + Type string `json:"type"` + APIConfig string `json:"api_config"` + TextContent string `json:"text_content"` + DataContent string `json:"data_content"` + ImageURL string `json:"image_url"` + Description string `json:"description"` + Enabled bool `json:"enabled"` + DelaySeconds int `json:"delay_seconds"` + IsMultiSpec bool `json:"is_multi_spec"` + SpecName string `json:"spec_name"` + SpecValue string `json:"spec_value"` + } + if err := decodeJSON(r, &req); err != nil { + return nil, err + } + if req.Name == "" || req.Type == "" { + return nil, errStr("名称和类型不能为空") + } + return &db.CardFull{ + Name: req.Name, Type: req.Type, APIConfig: req.APIConfig, TextContent: req.TextContent, + DataContent: req.DataContent, ImageURL: req.ImageURL, Description: req.Description, + Enabled: req.Enabled, DelaySeconds: req.DelaySeconds, IsMultiSpec: req.IsMultiSpec, + SpecName: req.SpecName, SpecValue: req.SpecValue, + }, nil +} + +// ---- 发货规则 CRUD ---- + +type deliveryVariantRequest struct { + ID int64 `json:"id,omitempty"` + SpecName string `json:"spec_name"` + SpecValue string `json:"spec_value"` + CardID int64 `json:"card_id"` + DeliveryCount int `json:"delivery_count"` + Enabled *bool `json:"enabled,omitempty"` +} + +type deliveryRuleRequest struct { + Keyword string `json:"keyword"` + CookieID string `json:"cookie_id"` + ItemID string `json:"item_id"` + Enabled bool `json:"enabled"` + Description string `json:"description"` + Variants []deliveryVariantRequest `json:"variants"` + CardID int64 `json:"card_id"` + DeliveryCount int `json:"delivery_count"` +} + +func (s *Server) listDeliveryRules(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT dr.id,dr.keyword,COALESCE(dr.cookie_id,''),COALESCE(dr.item_id,''), + dr.enabled,COALESCE(dr.description,''),dr.delivery_times, + COALESCE((SELECT item_title FROM item_info i + WHERE i.cookie_id=dr.cookie_id AND i.item_id=dr.item_id LIMIT 1),'') + FROM delivery_rules dr WHERE dr.user_id=? ORDER BY dr.id DESC`, sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + out := []map[string]any{} + for rows.Next() { + var id int64 + var deliveryTimes, enabled int + var keyword, cookieID, itemID, desc, itemTitle string + if err := rows.Scan(&id, &keyword, &cookieID, &itemID, &enabled, &desc, &deliveryTimes, &itemTitle); err != nil { + writeErr(w, http.StatusInternalServerError, "读取发货规则失败") + return + } + variants, err := s.deliveryRuleVariants(r.Context(), id) + if err != nil { + writeErr(w, http.StatusInternalServerError, "读取规格映射失败") + return + } + var legacyCardID int64 + legacyCardName := "" + legacyCount := 1 + if len(variants) > 0 { + legacyCardID, _ = variants[0]["card_id"].(int64) + legacyCardName, _ = variants[0]["card_name"].(string) + legacyCount, _ = variants[0]["delivery_count"].(int) + } + out = append(out, map[string]any{ + "id": id, "keyword": keyword, "cookie_id": cookieID, "item_id": itemID, "item_title": itemTitle, + "card_id": legacyCardID, "card_name": legacyCardName, "delivery_count": legacyCount, + "enabled": enabled != 0, "description": desc, "delivery_times": deliveryTimes, "variants": variants, + }) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) createDeliveryRule(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + var req deliveryRuleRequest + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := normalizeDeliveryRuleRequest(&req); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if !s.deliveryRuleItemOwned(r, sess.UserID, req.CookieID, req.ItemID) { + writeErr(w, http.StatusForbidden, "商品不属于当前用户") + return + } + tx, err := s.Store.DB.BeginTx(r.Context(), nil) + if err != nil { + writeErr(w, http.StatusInternalServerError, "创建失败") + return + } + defer tx.Rollback() + first := req.Variants[0] + res, err := tx.ExecContext(r.Context(), + `INSERT INTO delivery_rules + (keyword,card_id,delivery_count,enabled,description,user_id,cookie_id,item_id) + VALUES (?,?,?,?,?,?,?,?)`, + req.Keyword, first.CardID, first.DeliveryCount, req.Enabled, req.Description, + sess.UserID, req.CookieID, req.ItemID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "创建失败") + return + } + id, _ := res.LastInsertId() + if err := insertDeliveryVariants(r.Context(), tx, sess.UserID, id, req.Variants); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if err := tx.Commit(); err != nil { + writeErr(w, http.StatusInternalServerError, "创建失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id}) +} + +func (s *Server) updateDeliveryRule(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效规则ID") + return + } + var req deliveryRuleRequest + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := normalizeDeliveryRuleRequest(&req); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + sess := auth.SessionFromContext(r.Context()) + if !s.deliveryRuleItemOwned(r, sess.UserID, req.CookieID, req.ItemID) { + writeErr(w, http.StatusForbidden, "商品不属于当前用户") + return + } + tx, err := s.Store.DB.BeginTx(r.Context(), nil) + if err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + defer tx.Rollback() + first := req.Variants[0] + res, err := tx.ExecContext(r.Context(), + `UPDATE delivery_rules SET keyword=?,card_id=?,delivery_count=?,enabled=?,description=?, + cookie_id=?,item_id=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`, + req.Keyword, first.CardID, first.DeliveryCount, req.Enabled, req.Description, + req.CookieID, req.ItemID, id, sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + if n, _ := res.RowsAffected(); n == 0 { + writeErr(w, http.StatusNotFound, "发货规则不存在") + return + } + if _, err := tx.ExecContext(r.Context(), `DELETE FROM delivery_rule_variants WHERE rule_id=?`, id); err != nil { + writeErr(w, http.StatusInternalServerError, "更新规格映射失败") + return + } + if err := insertDeliveryVariants(r.Context(), tx, sess.UserID, id, req.Variants); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if err := tx.Commit(); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteDeliveryRule(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效规则ID") + return + } + sess := auth.SessionFromContext(r.Context()) + res, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM delivery_rules WHERE id=? AND user_id=?`, id, sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + if n, _ := res.RowsAffected(); n == 0 { + writeErr(w, http.StatusNotFound, "发货规则不存在") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func normalizeDeliveryRuleRequest(req *deliveryRuleRequest) error { + req.Keyword = strings.TrimSpace(req.Keyword) + req.CookieID = strings.TrimSpace(req.CookieID) + req.ItemID = strings.TrimSpace(req.ItemID) + req.Description = strings.TrimSpace(req.Description) + if len(req.Variants) == 0 && req.CardID > 0 { + req.Variants = []deliveryVariantRequest{{CardID: req.CardID, DeliveryCount: req.DeliveryCount}} + } + if req.ItemID == "" && req.Keyword == "" { + return errStr("请选择商品或填写旧规则关键词") + } + if len(req.Variants) == 0 { + return errStr("至少需要一条卡密映射") + } + seen := map[string]bool{} + for i := range req.Variants { + v := &req.Variants[i] + v.SpecName = strings.TrimSpace(v.SpecName) + v.SpecValue = strings.TrimSpace(v.SpecValue) + if v.CardID <= 0 { + return errStr("每条规格映射都必须选择卡密") + } + if (v.SpecName == "") != (v.SpecValue == "") { + return errStr("规格名称和规格值必须同时填写") + } + if v.DeliveryCount <= 0 { + v.DeliveryCount = 1 + } + key := v.SpecName + "\x00" + v.SpecValue + if seen[key] { + return errStr("同一规则中不能存在重复规格") + } + seen[key] = true + } + return nil +} + +func (s *Server) deliveryRuleItemOwned(r *http.Request, userID int64, cookieID, itemID string) bool { + if itemID == "" { + return true + } + all, err := s.Store.Cookies.AllForUser(r.Context(), userID) + if err != nil || cookieID == "" { + return false + } + if _, ok := all[cookieID]; !ok { + return false + } + _, err = s.Store.Items.Get(r.Context(), cookieID, itemID) + return err == nil +} + +func insertDeliveryVariants(ctx context.Context, tx *sql.Tx, userID, ruleID int64, variants []deliveryVariantRequest) error { + for _, v := range variants { + var exists int + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, v.CardID, userID).Scan(&exists); err != nil { + return err + } + if exists == 0 { + return errStr("选择的卡密不存在或不属于当前用户") + } + enabled := true + if v.Enabled != nil { + enabled = *v.Enabled + } + if _, err := tx.ExecContext(ctx, + `INSERT INTO delivery_rule_variants + (rule_id,spec_name,spec_value,card_id,delivery_count,enabled) VALUES (?,?,?,?,?,?)`, + ruleID, v.SpecName, v.SpecValue, v.CardID, v.DeliveryCount, enabled); err != nil { + return err + } + } + return nil +} + +func (s *Server) deliveryRuleVariants(ctx context.Context, ruleID int64) ([]map[string]any, error) { + rows, err := s.Store.DB.QueryContext(ctx, + `SELECT v.id,v.spec_name,v.spec_value,v.card_id,v.delivery_count,v.enabled,c.name,c.type + FROM delivery_rule_variants v JOIN cards c ON c.id=v.card_id + WHERE v.rule_id=? ORDER BY v.id`, ruleID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []map[string]any{} + for rows.Next() { + var id, cardID int64 + var specName, specValue, cardName, cardType string + var deliveryCount, enabled int + if err := rows.Scan(&id, &specName, &specValue, &cardID, &deliveryCount, &enabled, &cardName, &cardType); err != nil { + return nil, err + } + out = append(out, map[string]any{ + "id": id, "spec_name": specName, "spec_value": specValue, "card_id": cardID, + "card_name": cardName, "card_type": cardType, "delivery_count": deliveryCount, "enabled": enabled != 0, + }) + } + return out, rows.Err() +} + +func errStr(s string) error { return &simpleError{s} } + +type simpleError struct{ msg string } + +func (e *simpleError) Error() string { return e.msg } diff --git a/internal/server/cookie_handlers.go b/internal/server/cookie_handlers.go new file mode 100644 index 0000000..e87ac2d --- /dev/null +++ b/internal/server/cookie_handlers.go @@ -0,0 +1,381 @@ +package server + +import ( + "context" + "net/http" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" + "xianyu-go/internal/engine" +) + +// mountCookies 账号 cookie 管理端点。 +func (s *Server) mountCookies(r chi.Router) { + r.Get("/cookies", s.listCookies) + r.Get("/cookies/details", s.listCookieDetails) + r.Get("/cookies/runtime-status", s.listCookieRuntimeStatus) + r.Post("/cookies", s.addCookie) + r.Put("/cookies/{cid}", s.updateCookie) + r.Put("/cookies/{cid}/login-info", s.updateCookieLoginInfo) + r.Get("/cookie/{cid}/details", s.getCookieDetails) + r.Put("/cookies/{cid}/status", s.setCookieStatus) + r.Delete("/cookies/{cid}", s.deleteCookie) + r.Put("/cookies/{cid}/auto-confirm", s.setCookieAutoConfirm) + r.Get("/cookies/{cid}/auto-confirm", s.getCookieAutoConfirm) + r.Put("/cookies/{cid}/remark", s.setCookieRemark) + r.Put("/cookies/{cid}/pause-duration", s.setCookiePauseDuration) + r.Get("/cookies/{cid}/pause-duration", s.getCookiePauseDuration) +} + +// listCookieRuntimeStatus 返回本地账号引擎状态,不请求闲鱼 API,可安全用于前端轮询。 +func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "获取账号失败") + return + } + runtime := map[string]engine.RuntimeStatus{} + if s.Manager != nil { + runtime = s.Manager.RuntimeStatuses() + } + result := make(map[string]engine.RuntimeStatus, len(all)) + for cid := range all { + if !s.Store.Cookies.GetStatus(r.Context(), cid) { + result[cid] = engine.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()} + continue + } + if status, ok := runtime[cid]; ok { + result[cid] = status + continue + } + result[cid] = engine.RuntimeStatus{State: engine.RuntimeError, Message: "账号服务未运行", UpdatedAt: time.Now()} + } + writeJSON(w, http.StatusOK, result) +} + +// listCookies 列出当前用户的 cookie_id。 +func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "获取账号失败") + return + } + ids := make([]string, 0, len(all)) + for id := range all { + ids = append(ids, id) + } + writeJSON(w, http.StatusOK, ids) +} + +// listCookieDetails 账号非敏感详情(不含 cookie 明文/密码,遵循 Fork 安全基线)。 +func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "获取账号失败") + return + } + result := make([]map[string]any, 0, len(all)) + for cid := range all { + d, err := s.Store.Cookies.GetDetails(r.Context(), cid) + if err != nil || d == nil { + continue + } + nickname, avatarURL, profileErr := s.refreshAccountProfile(r.Context(), d) + result = append(result, map[string]any{ + "id": d.ID, + "has_cookie": true, + "enabled": s.Store.Cookies.GetStatus(r.Context(), cid), + "auto_confirm": d.AutoConfirm, + "remark": d.Remark, + "pause_duration": d.PauseDuration, + "username": d.Username, + "nickname": nickname, + "avatar_url": avatarURL, + "profile_error": profileErr, + "ai_enabled": false, + }) + } + writeJSON(w, http.StatusOK, result) +} + +// getCookieDetails 单个账号非敏感详情。 +func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + sess := auth.SessionFromContext(r.Context()) + all, _ := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if _, ok := all[cid]; !ok { + writeErr(w, http.StatusForbidden, "无权限操作该Cookie") + return + } + d, err := s.Store.Cookies.GetDetails(r.Context(), cid) + if err != nil { + writeErr(w, http.StatusNotFound, "账号不存在") + return + } + nickname, avatarURL, profileErr := s.refreshAccountProfile(r.Context(), d) + writeJSON(w, http.StatusOK, map[string]any{ + "id": d.ID, + "enabled": s.Store.Cookies.GetStatus(r.Context(), cid), + "auto_confirm": d.AutoConfirm, + "remark": d.Remark, + "pause_duration": d.PauseDuration, + "show_browser": d.ShowBrowser, + "username": d.Username, + "nickname": nickname, + "avatar_url": avatarURL, + "profile_error": profileErr, + "has_cookie": true, + }) +} + +// addCookie 添加账号 cookie。 +func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) { + var req struct { + ID string `json:"id"` + Value string `json:"value"` + } + if err := decodeJSON(r, &req); err != nil || req.ID == "" || req.Value == "" { + writeErr(w, http.StatusBadRequest, "缺少 id 或 value") + return + } + sess := auth.SessionFromContext(r.Context()) + if err := s.Store.Cookies.Save(r.Context(), req.ID, req.Value, sess.UserID); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil { + s.refreshAccountProfile(r.Context(), d) + } + if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) { + _ = s.Manager.Restart(r.Context(), req.ID) + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": req.ID}) +} + +// updateCookie 更新 cookie 值。 +func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + Value string `json:"value"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + sess := auth.SessionFromContext(r.Context()) + if err := s.Store.Cookies.Save(r.Context(), cid, req.Value, sess.UserID); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil { + s.refreshAccountProfile(r.Context(), d) + } + if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) { + _ = s.Manager.Restart(r.Context(), cid) + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。 +func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + Username string `json:"username"` + Password string `json:"password"` + LoginPassword string `json:"login_password"` + ShowBrowser bool `json:"show_browser"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + password := req.Password + if password == "" { + password = req.LoginPassword + } + sb := 0 + if req.ShowBrowser { + sb = 1 + } + _, err := s.Store.DB.ExecContext(r.Context(), + `UPDATE cookies SET username=?, password=?, show_browser=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`, + req.Username, password, sb, cid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// setCookieStatus 启用/禁用账号。 +func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + Enabled bool `json:"enabled"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.Store.Cookies.SetStatus(r.Context(), cid, req.Enabled); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + // 启停引擎实例。 + if req.Enabled { + // 重启拉取最新 cookie。 + if d, e := s.Store.Cookies.GetDetails(r.Context(), cid); e == nil { + _ = s.Manager.Restart(r.Context(), cid) + _ = d + } + } else { + s.Manager.Stop(cid) + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// deleteCookie 删除账号。 +func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + s.Manager.Stop(cid) + if err := s.Store.Cookies.Delete(r.Context(), cid); err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// setCookieAutoConfirm 设置自动确认发货。 +func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + AutoConfirm bool `json:"auto_confirm"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + v := 0 + if req.AutoConfirm { + v = 1 + } + s.Store.DB.ExecContext(r.Context(), + `UPDATE cookies SET auto_confirm=? WHERE id=?`, v, cid) + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// getCookieAutoConfirm 获取自动确认发货设置。 +func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + d, err := s.Store.Cookies.GetDetails(r.Context(), cid) + if err != nil { + writeErr(w, http.StatusNotFound, "账号不存在") + return + } + writeJSON(w, http.StatusOK, map[string]any{"auto_confirm": d.AutoConfirm}) +} + +// setCookieRemark 设置备注。 +func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + Remark string `json:"remark"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + s.Store.DB.ExecContext(r.Context(), + `UPDATE cookies SET remark=? WHERE id=?`, req.Remark, cid) + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// setCookiePauseDuration 设置暂停时长。 +func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + PauseDuration int `json:"pause_duration"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + s.Store.DB.ExecContext(r.Context(), + `UPDATE cookies SET pause_duration=? WHERE id=?`, req.PauseDuration, cid) + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// getCookiePauseDuration 获取暂停时长。 +func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + writeJSON(w, http.StatusOK, map[string]any{"pause_duration": s.Store.Cookies.GetPauseDuration(r.Context(), cid)}) +} + +func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail) (string, string, string) { + if d == nil { + return "", "", "" + } + if s.MTop == nil { + return accountProfileFallback(d), "", "账号资料客户端未初始化" + } + + profile, err := s.MTop.FetchUserProfile(ctx, d.Value) + if err != nil { + if s.Logger != nil { + s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", err) + } + return accountProfileFallback(d), "", truncate(err.Error(), 180) + } + + if profile.UpdatedCookies != "" && profile.UpdatedCookies != d.Value { + if err := s.Store.Cookies.Save(ctx, d.ID, profile.UpdatedCookies, d.UserID); err != nil && s.Logger != nil { + s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err) + } + d.Value = profile.UpdatedCookies + } + + apiNickname := strings.TrimSpace(profile.Nickname) + apiAvatarURL := normalizeProfileAvatarURL(profile.AvatarURL) + if err := s.Store.Cookies.UpdateProfile(ctx, d.ID, apiNickname, apiAvatarURL); err != nil && s.Logger != nil { + s.Logger.Warn("保存账号资料失败", "account", d.ID, "err", err) + } + if apiNickname == "" { + apiNickname = accountProfileFallback(d) + } + return apiNickname, apiAvatarURL, "" +} + +func accountProfileFallback(d *db.CookieDetail) string { + return fallback(d.Remark, "账号 "+truncate(d.ID, 6)) +} + +func normalizeProfileAvatarURL(raw string) string { + raw = strings.TrimSpace(raw) + if raw == "" { + return "" + } + if strings.HasPrefix(raw, "//") { + return "https:" + raw + } + if strings.HasPrefix(raw, "http://") { + return "https://" + strings.TrimPrefix(raw, "http://") + } + return raw +} + +func truncate(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] +} + +func atoi(s string) int { n, _ := strconv.Atoi(s); return n } diff --git a/internal/server/default_reply_handlers.go b/internal/server/default_reply_handlers.go new file mode 100644 index 0000000..9743ebb --- /dev/null +++ b/internal/server/default_reply_handlers.go @@ -0,0 +1,140 @@ +package server + +import ( + "net/http" + + "github.com/go-chi/chi/v5" +) + +// btoi bool→int(SQLite 无原生 bool)。 +func btoi(b bool) int { + if b { + return 1 + } + return 0 +} + +// nullIfEmpty 空串存为 NULL。 +func nullIfEmpty(s string) any { + if s == "" { + return nil + } + return s +} + +// mountDefaultRepliesReal 默认回复端点。 +func (s *Server) mountDefaultRepliesReal(r chi.Router) { + r.Get("/default-replies/{cid}", s.getDefaultReply) + r.Put("/default-replies/{cid}", s.setDefaultReply) + r.Get("/default-replies", s.listDefaultReplies) + r.Delete("/default-replies/{cid}", s.deleteDefaultReply) + r.Get("/api/default-replies", s.listDefaultRepliesMap) + r.Get("/api/default-reply/{cid}", s.getDefaultReply) + r.Put("/api/default-reply/{cid}", s.setDefaultReply) + r.Delete("/api/default-reply/{cid}", s.deleteDefaultReply) + r.Post("/api/default-reply/{cid}/clear-records", s.clearDefaultReplyRecords) +} + +func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + dr, err := s.Store.DefaultReps.Get(r.Context(), cid) + if err != nil { + writeJSON(w, http.StatusOK, map[string]any{"enabled": false, "reply_content": "", "reply_once": false}) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "enabled": dr.Enabled, "reply_content": dr.ReplyContent, + "reply_image_url": dr.ReplyImageURL, "reply_once": dr.ReplyOnce, + }) +} + +func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + Enabled bool `json:"enabled"` + ReplyContent string `json:"reply_content"` + ReplyImageURL string `json:"reply_image_url"` + ReplyOnce bool `json:"reply_once"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + _, err := s.Store.DB.ExecContext(r.Context(), + `INSERT OR REPLACE INTO default_replies (cookie_id, enabled, reply_content, reply_image_url, reply_once, updated_at) + VALUES (?,?,?,?,?,CURRENT_TIMESTAMP)`, + cid, btoi(req.Enabled), req.ReplyContent, nullIfEmpty(req.ReplyImageURL), btoi(req.ReplyOnce)) + if err != nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) { + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT cookie_id, enabled, reply_content, reply_once, reply_image_url FROM default_replies`) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + var out []map[string]any + for rows.Next() { + var cid, content, imageURL string + var enabled, replyOnce int + if err := rows.Scan(&cid, &enabled, &content, &replyOnce, &imageURL); err != nil { + continue + } + out = append(out, map[string]any{ + "cookie_id": cid, "enabled": enabled != 0, "reply_content": content, + "reply_once": replyOnce != 0, "reply_image_url": imageURL, + }) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) { + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT cookie_id, enabled, COALESCE(reply_content, ''), reply_once, COALESCE(reply_image_url, '') FROM default_replies`) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + out := make(map[string]any) + for rows.Next() { + var cid, content, imageURL string + var enabled, replyOnce int + if err := rows.Scan(&cid, &enabled, &content, &replyOnce, &imageURL); err != nil { + continue + } + out[cid] = map[string]any{ + "cookie_id": cid, + "enabled": enabled != 0, + "reply_content": content, + "reply_once": replyOnce != 0, + "reply_image_url": imageURL, + } + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + _, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_replies WHERE cookie_id=?`, cid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) clearDefaultReplyRecords(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + if _, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_reply_records WHERE cookie_id=?`, cid); err != nil { + writeErr(w, http.StatusInternalServerError, "清空失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} diff --git a/internal/server/endpoint_test.go b/internal/server/endpoint_test.go new file mode 100644 index 0000000..5828f03 --- /dev/null +++ b/internal/server/endpoint_test.go @@ -0,0 +1,234 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" +) + +// loginHelper 登录并返回会话 cookie。 +func loginHelper(t *testing.T, h http.Handler) *http.Cookie { + t.Helper() + body := `{"username":"admin","password":"pw"}` + req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body)) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("login status=%d", rec.Code) + } + return rec.Result().Cookies()[0] +} + +// TestOrderListAndDetail 订单列表 + 详情 + 状态码归一。 +func TestOrderListAndDetail(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + ctx := context.Background() + // 插入一条订单(order_status 用数字码 "2" 测试归一)。 + store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id) VALUES ('ord1','item1','buyer1','2','acc1')`) + store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_detail) VALUES ('acc1','item1','测试商品','{"pic_info":{"picUrl":"https://img.example/item.png"}}')`) + + h := srv.Router() + cookie := loginHelper(t, h) + + // 列表。 + req := httptest.NewRequest(http.MethodGet, "/api/orders", nil) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("list status=%d body=%s", rec.Code, rec.Body.String()) + } + var resp struct { + Success bool `json:"success"` + Total int `json:"total"` + Data []map[string]any `json:"data"` + } + json.Unmarshal(rec.Body.Bytes(), &resp) + if !resp.Success || resp.Total != 1 { + t.Fatalf("订单列表异常: %+v", resp) + } + if resp.Data[0]["order_status"] != "pending_ship" { + t.Errorf("状态归一: got %v want pending_ship", resp.Data[0]["order_status"]) + } + if resp.Data[0]["item_title"] != "测试商品" { + t.Errorf("item_title: %v", resp.Data[0]["item_title"]) + } + if resp.Data[0]["item_image"] != "https://img.example/item.png" { + t.Errorf("item_image: %v", resp.Data[0]["item_image"]) + } + + // 详情。 + req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord1", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("detail status=%d", rec2.Code) + } + var det map[string]any + json.Unmarshal(rec2.Body.Bytes(), &det) + if det["order_id"] != "ord1" { + t.Errorf("详情异常: %+v", det) + } + if det["item_image"] != "https://img.example/item.png" { + t.Errorf("详情 item_image: %v", det["item_image"]) + } + + // 删除。 + req3 := httptest.NewRequest(http.MethodDelete, "/api/orders/ord1", nil) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + if rec3.Code != 200 { + t.Fatalf("delete status=%d", rec3.Code) + } +} + +// TestCardCRUD 卡券增删改查。 +func TestCardCRUD(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + // 创建。 + body := `{"name":"测试卡","type":"text","text_content":"卡密ABC","enabled":true}` + req := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(body)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String()) + } + var cr map[string]any + json.Unmarshal(rec.Body.Bytes(), &cr) + id := cr["id"].(float64) + if id == 0 { + t.Fatal("应返回 id") + } + + // 列表。 + req2 := httptest.NewRequest(http.MethodGet, "/cards", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + var arr []map[string]any + json.Unmarshal(rec2.Body.Bytes(), &arr) + if len(arr) != 1 || arr[0]["name"] != "测试卡" { + t.Fatalf("列表异常: %+v", arr) + } + + // 更新。 + updBody := `{"name":"改名卡","type":"text","text_content":"卡密XYZ","enabled":true}` + req3 := httptest.NewRequest(http.MethodPut, "/cards/"+itoa(int64(id)), strings.NewReader(updBody)) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + if rec3.Code != 200 { + t.Fatalf("update status=%d", rec3.Code) + } + + // 获取验证改名。 + req4 := httptest.NewRequest(http.MethodGet, "/cards/"+itoa(int64(id)), nil) + req4.AddCookie(cookie) + rec4 := httptest.NewRecorder() + h.ServeHTTP(rec4, req4) + var got map[string]any + json.Unmarshal(rec4.Body.Bytes(), &got) + if got["name"] != "改名卡" { + t.Errorf("改名后应=改名卡, got %v", got["name"]) + } + + // 删除。 + req5 := httptest.NewRequest(http.MethodDelete, "/cards/"+itoa(int64(id)), nil) + req5.AddCookie(cookie) + rec5 := httptest.NewRecorder() + h.ServeHTTP(rec5, req5) + if rec5.Code != 200 { + t.Fatalf("delete status=%d", rec5.Code) + } +} + +func itoa(n int64) string { return strconv.FormatInt(n, 10) } + +// TestDeliveryRuleCRUD 发货规则增删。 +func TestDeliveryRuleCRUD(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + ctx := context.Background() + // 先建一个卡券供规则引用。 + store.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES (1,'卡','text','c',1,1)`) + + h := srv.Router() + cookie := loginHelper(t, h) + + body := `{"keyword":"VIP","card_id":1,"delivery_count":1,"enabled":true}` + req := httptest.NewRequest(http.MethodPost, "/delivery-rules", strings.NewReader(body)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String()) + } + + // 列表。 + req2 := httptest.NewRequest(http.MethodGet, "/delivery-rules", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + var arr []map[string]any + json.Unmarshal(rec2.Body.Bytes(), &arr) + if len(arr) != 1 || arr[0]["keyword"] != "VIP" { + t.Fatalf("规则列表异常: %+v", arr) + } +} + +func TestDeliveryRuleVariantCRUD(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + ctx := context.Background() + admin, _ := store.Users.GetByUsername(ctx, "admin") + _, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES + (31,'30天库存','text','A',1,?),(32,'90天库存','text','B',1,?)`, admin.ID, admin.ID) + _, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title,is_multi_spec) VALUES + ('acc1','item-vip','视频会员',1)`) + + h := srv.Router() + cookie := loginHelper(t, h) + body := `{"keyword":"视频会员","cookie_id":"acc1","item_id":"item-vip","enabled":true,"description":"会员发货","variants":[{"spec_name":"套餐","spec_value":"30天","card_id":31,"delivery_count":1,"enabled":true},{"spec_name":"套餐","spec_value":"90天","card_id":32,"delivery_count":2,"enabled":true}]}` + req := httptest.NewRequest(http.MethodPost, "/delivery-rules", strings.NewReader(body)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String()) + } + + listReq := httptest.NewRequest(http.MethodGet, "/delivery-rules", nil) + listReq.AddCookie(cookie) + listRec := httptest.NewRecorder() + h.ServeHTTP(listRec, listReq) + var rules []struct { + CookieID string `json:"cookie_id"` + ItemID string `json:"item_id"` + Variants []struct { + SpecValue string `json:"spec_value"` + CardID int64 `json:"card_id"` + DeliveryCount int `json:"delivery_count"` + } `json:"variants"` + } + if err := json.Unmarshal(listRec.Body.Bytes(), &rules); err != nil { + t.Fatal(err) + } + if len(rules) != 1 || rules[0].CookieID != "acc1" || rules[0].ItemID != "item-vip" || len(rules[0].Variants) != 2 { + t.Fatalf("规则返回异常: %+v body=%s", rules, listRec.Body.String()) + } + if rules[0].Variants[1].SpecValue != "90天" || rules[0].Variants[1].CardID != 32 || rules[0].Variants[1].DeliveryCount != 2 { + t.Fatalf("规格返回异常: %+v", rules[0].Variants) + } +} diff --git a/internal/server/extras_test.go b/internal/server/extras_test.go new file mode 100644 index 0000000..1afa672 --- /dev/null +++ b/internal/server/extras_test.go @@ -0,0 +1,388 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestKeywordsCRUD 关键字增删查。 +func TestKeywordsCRUD(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + // 添加(普通 + 商品ID)。 + post := func(body string) { + req := httptest.NewRequest(http.MethodPost, "/keywords/acc1", strings.NewReader(body)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("add keyword status=%d body=%s", rec.Code, rec.Body.String()) + } + } + post(`{"keyword":"在吗","reply":"在的"}`) + post(`{"keyword":"价格","reply":"50元","item_id":"item1"}`) + + // 列表(带类型)。 + req := httptest.NewRequest(http.MethodGet, "/keywords-with-type/acc1", nil) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + var arr []map[string]any + json.Unmarshal(rec.Body.Bytes(), &arr) + if len(arr) != 2 { + t.Fatalf("应2条关键字,got %d", len(arr)) + } + + // 按索引删除第一条。 + req2 := httptest.NewRequest(http.MethodDelete, "/keywords/acc1/0", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("delete status=%d", rec2.Code) + } +} + +// TestDefaultReplyCRUD 默认回复。 +func TestDefaultReplyCRUD(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + // 设置。 + body := `{"enabled":true,"reply_content":"你好老板","reply_once":true}` + req := httptest.NewRequest(http.MethodPut, "/default-replies/acc1", strings.NewReader(body)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("set status=%d", rec.Code) + } + + // 读取。 + req2 := httptest.NewRequest(http.MethodGet, "/default-replies/acc1", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + var dr map[string]any + json.Unmarshal(rec2.Body.Bytes(), &dr) + if dr["enabled"] != true || dr["reply_content"] != "你好老板" || dr["reply_once"] != true { + t.Fatalf("默认回复异常: %+v", dr) + } + + // 前端兼容路径:/api/default-reply/* 与 /api/default-replies。 + req3 := httptest.NewRequest(http.MethodPut, "/api/default-reply/acc1", strings.NewReader(body)) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + if rec3.Code != 200 { + t.Fatalf("compat set status=%d", rec3.Code) + } + req4 := httptest.NewRequest(http.MethodGet, "/api/default-replies", nil) + req4.AddCookie(cookie) + rec4 := httptest.NewRecorder() + h.ServeHTTP(rec4, req4) + var all map[string]map[string]any + json.Unmarshal(rec4.Body.Bytes(), &all) + if all["acc1"]["reply_content"] != "你好老板" { + t.Fatalf("兼容默认回复列表异常: %+v", all) + } + req5 := httptest.NewRequest(http.MethodPost, "/api/default-reply/acc1/clear-records", nil) + req5.AddCookie(cookie) + rec5 := httptest.NewRecorder() + h.ServeHTTP(rec5, req5) + if rec5.Code != 200 { + t.Fatalf("clear records status=%d", rec5.Code) + } +} + +// TestNotificationChannelCRUD 通知渠道 + 绑定。 +func TestNotificationChannelCRUD(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + // 创建渠道。 + body := `{"name":"我的钉钉","type":"dingtalk","config":"{\"webhook_url\":\"http://x\"}","enabled":true}` + req := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(body)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("create channel status=%d body=%s", rec.Code, rec.Body.String()) + } + var cr map[string]any + json.Unmarshal(rec.Body.Bytes(), &cr) + id := int64(cr["id"].(float64)) + + // 绑定到账号。 + bindBody := `{"channel_ids":[` + itoa(id) + `]}` + req2 := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(bindBody)) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("bind status=%d", rec2.Code) + } + + // 查询绑定。 + req3 := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + var b map[string]any + json.Unmarshal(rec3.Body.Bytes(), &b) + ids, _ := b["channel_ids"].([]any) + if len(ids) != 1 { + t.Fatalf("绑定数异常: %+v", b) + } +} + +// TestSystemSettings 系统设置。 +func TestSystemSettings(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + // 公开设置无需登录。 + req := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("public settings status=%d", rec.Code) + } + var pub map[string]any + json.Unmarshal(rec.Body.Bytes(), &pub) + if _, ok := pub["theme_color"]; !ok { + t.Fatalf("公开设置应含 theme_color: %+v", pub) + } + + // 已认证:设置 + 读取全部。 + body := `{"value":"green"}` + req2 := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader(body)) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("set status=%d", rec2.Code) + } + + req3 := httptest.NewRequest(http.MethodGet, "/system-settings", nil) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + var all map[string]any + json.Unmarshal(rec3.Body.Bytes(), &all) + if all["theme_color"] != "green" { + t.Fatalf("设置未生效: %+v", all["theme_color"]) + } +} + +// TestAIReplySettings AI 回复设置。 +func TestAIReplySettings(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + body := `{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"按商品信息回复"}` + req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(body)) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("set ai status=%d", rec.Code) + } + + // 账号级设置只包含开关、议价策略和自定义提示词;模型/API Key/URL 走系统设置。 + req2 := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + var cfg map[string]any + json.Unmarshal(rec2.Body.Bytes(), &cfg) + if cfg["ai_enabled"] != true || + cfg["max_discount_percent"] != float64(12) || + cfg["max_discount_amount"] != float64(88) || + cfg["max_bargain_rounds"] != float64(4) || + cfg["custom_prompts"] != "按商品信息回复" { + t.Fatalf("AI 设置异常: %+v", cfg) + } + if _, ok := cfg["model_name"]; ok { + t.Fatalf("账号级 AI 设置不应返回模型: %+v", cfg) + } + if _, ok := cfg["api_key"]; ok { + t.Fatalf("账号级 AI 设置不应返回 API Key: %+v", cfg) + } + + req3 := httptest.NewRequest(http.MethodGet, "/ai-reply-settings", nil) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + var all map[string]map[string]any + json.Unmarshal(rec3.Body.Bytes(), &all) + if all["acc1"]["ai_enabled"] != true { + t.Fatalf("AI 设置列表异常: %+v", all) + } +} + +func TestParseOpenAIModels(t *testing.T) { + models, err := parseOpenAIModels([]byte(`{"data":[{"id":"qwen-plus"},{"id":"qwen-max"},{"name":"fallback-name"}]}`)) + if err != nil { + t.Fatalf("parse models: %v", err) + } + want := []string{"qwen-plus", "qwen-max", "fallback-name"} + if len(models) != len(want) { + t.Fatalf("models length=%d want=%d: %+v", len(models), len(want), models) + } + for i := range want { + if models[i] != want[i] { + t.Fatalf("models[%d]=%q want=%q: %+v", i, models[i], want[i], models) + } + } +} + +// TestItems 物品列表 + 多规格设置。 +func TestItems(t *testing.T) { + srv, store, cleanup := newTestServer(t) + defer cleanup() + ctx := context.Background() + store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it1','商品A')`) + h := srv.Router() + cookie := loginHelper(t, h) + + // 列表。 + req := httptest.NewRequest(http.MethodGet, "/items", nil) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + var arr []map[string]any + json.Unmarshal(rec.Body.Bytes(), &arr) + if len(arr) != 1 || arr[0]["item_title"] != "商品A" { + t.Fatalf("物品列表异常: %+v", arr) + } + + // 设置多规格。 + body := `{"is_multi_spec":true}` + req2 := httptest.NewRequest(http.MethodPut, "/items/acc1/it1/multi-spec", strings.NewReader(body)) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("multi-spec status=%d", rec2.Code) + } + + // 验证。 + it, err := store.Items.Get(ctx, "acc1", "it1") + if err != nil || it == nil { + t.Fatalf("Get 失败: err=%v it=%v", err, it) + } + if !it.IsMultiSpec { + t.Fatal("多规格应已开启") + } +} + +func TestOrderImportCompat(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + body := `[{"order_id":"order-import-1","item_id":"item-import-1","item_title":"导入商品","buyer_id":"buyer1","status":"pending_ship","quantity":2,"amount":"19.90"}]` + req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("import status=%d body=%s", rec.Code, rec.Body.String()) + } + var res map[string]any + json.Unmarshal(rec.Body.Bytes(), &res) + if res["success_count"] != float64(1) { + t.Fatalf("导入结果异常: %+v", res) + } + + req2 := httptest.NewRequest(http.MethodGet, "/api/orders/order-import-1", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("get imported order status=%d body=%s", rec2.Code, rec2.Body.String()) + } + var order map[string]any + json.Unmarshal(rec2.Body.Bytes(), &order) + if order["cookie_id"] != "acc1" || order["status"] != "pending_ship" { + t.Fatalf("导入订单异常: %+v", order) + } +} + +// TestAdminEndpoints 管理员统计 + 用户列表 + 非 admin 被拒。 +func TestAdminEndpoints(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + cookie := loginHelper(t, h) + + // stats。 + req := httptest.NewRequest(http.MethodGet, "/admin/stats", nil) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("stats status=%d", rec.Code) + } + var stats map[string]any + json.Unmarshal(rec.Body.Bytes(), &stats) + if stats["total_users"] == nil || stats["total_cookies"] == nil { + t.Fatalf("stats 异常: %+v", stats) + } + + // 用户列表。 + req2 := httptest.NewRequest(http.MethodGet, "/admin/users", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + var users []map[string]any + json.Unmarshal(rec2.Body.Bytes(), &users) + if len(users) != 1 || users[0]["username"] != "admin" { + t.Fatalf("用户列表异常: %+v", users) + } + + // 创建普通用户验证 admin 隔离。 + srv.Store.Users.Create(context.Background(), "user2", "u2@e.com", "pw") + // 普通用户不应能访问 admin(需单独登录验证,此处仅验证 admin 能看到)。 + req3 := httptest.NewRequest(http.MethodGet, "/admin/users", nil) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + var users2 []map[string]any + json.Unmarshal(rec3.Body.Bytes(), &users2) + if len(users2) != 2 { + t.Fatalf("应2用户,got %d", len(users2)) + } +} + +// TestPublicSettingsNoAuth 公开设置无需登录。 +func TestPublicSettingsNoAuth(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + req := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("公开设置应无需登录,status=%d", rec.Code) + } +} diff --git a/internal/server/helpers.go b/internal/server/helpers.go new file mode 100644 index 0000000..13878b1 --- /dev/null +++ b/internal/server/helpers.go @@ -0,0 +1,37 @@ +package server + +import ( + "encoding/json" + "net/http" +) + +// writeJSON 写 JSON 响应。 +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +// errDetail 构造 {"detail": msg} 错误体(与 Python FastAPI 默认错误格式一致)。 +func errDetail(msg string) map[string]any { + return map[string]any{"detail": msg} +} + +// writeErr 写错误响应。 +func writeErr(w http.ResponseWriter, status int, msg string) { + writeJSON(w, status, errDetail(msg)) +} + +// decodeJSON 解析请求体 JSON。 +func decodeJSON(r *http.Request, v any) error { + dec := json.NewDecoder(r.Body) + return dec.Decode(v) +} + +// fallback 空字符串返回默认值。 +func fallback(s, def string) string { + if s == "" { + return def + } + return s +} diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go new file mode 100644 index 0000000..a1c3564 --- /dev/null +++ b/internal/server/item_handlers.go @@ -0,0 +1,524 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +// mountItemsReal 物品端点(真实实现)。 +func (s *Server) mountItemsReal(r chi.Router) { + r.Get("/items", s.listItems) + r.Post("/items/get-all-from-account", s.syncItemsFromAccount) + r.Post("/items/get-by-page", s.syncItemsPageFromAccount) + r.Post("/items/publish", s.publishItem) + r.Post("/items/publish-batches/preview", s.previewItemPublishBatch) + r.Post("/items/publish-batches", s.startItemPublishBatch) + r.Get("/items/publish-batches/{batch_id}", s.getItemPublishBatch) + r.Post("/items/publish-batches/{batch_id}/cancel", s.cancelItemPublishBatch) + r.Post("/items/publish-batches/{batch_id}/retry-failed", s.retryFailedItemPublishBatch) + r.Get("/items/publish-batches/{batch_id}/result.csv", s.downloadItemPublishBatchResult) + r.Get("/items/cookie/{cookie_id}", s.listItemsByCookie) + r.Post("/items/{cookie_id}", s.createItem) + r.Get("/items/{cookie_id}/{item_id}", s.getItem) + r.Put("/items/{cookie_id}/{item_id}", s.updateItem) + r.Delete("/items/{cookie_id}/{item_id}", s.deleteItem) + r.Put("/items/{cookie_id}/{item_id}/multi-spec", s.setItemMultiSpec) + r.Put("/items/{cookie_id}/{item_id}/multi-quantity-delivery", s.setItemMultiQuantity) +} + +func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { + if err := r.ParseMultipartForm(32 << 20); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误,请使用 multipart/form-data") + return + } + cookieID := strings.TrimSpace(r.FormValue("cookie_id")) + if cookieID == "" { + writeErr(w, http.StatusBadRequest, "请选择发布账号") + return + } + cookieValue, userID, ok := s.cookieForCurrentUser(w, r, cookieID) + if !ok { + return + } + title := strings.TrimSpace(r.FormValue("title")) + description := strings.TrimSpace(r.FormValue("description")) + priceCents, err := parseMoneyCents(r.FormValue("price")) + if err != nil || priceCents <= 0 { + writeErr(w, http.StatusBadRequest, "商品价格必须大于 0") + return + } + origCents, _ := parseMoneyCents(r.FormValue("original_price")) + quantity, err := strconv.Atoi(strings.TrimSpace(r.FormValue("quantity"))) + if err != nil || quantity <= 0 { + writeErr(w, http.StatusBadRequest, "库存数量必须大于 0") + return + } + postageMode := strings.TrimSpace(r.FormValue("postage_mode")) + if postageMode == "" { + postageMode = "free" + } + postageCents, _ := parseMoneyCents(r.FormValue("postage")) + images, err := readPublishImages(r, 9) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) + defer cancel() + client := s.MTop + if client == nil { + client = &mtop.Client{} + } + res, err := client.PublishItem(ctx, cookieValue, mtop.PublishItemRequest{ + Title: title, + Description: description, + PriceCents: priceCents, + OriginalPriceCents: origCents, + Quantity: quantity, + PostageMode: postageMode, + PostageCents: postageCents, + Images: images, + }) + if err != nil { + var perr *mtop.PublishError + if errors.As(err, &perr) { + status := http.StatusBadGateway + msg := perr.Error() + if perr.Code == mtop.PublishErrorStockPermissionMissing { + status = http.StatusForbidden + msg = "该账号没有库存发布权限,无法按库存数量发布商品" + } + writeJSON(w, status, map[string]any{ + "success": false, + "code": perr.Code, + "message": msg, + "ret": perr.Ret, + }) + return + } + writeErr(w, http.StatusBadGateway, err.Error()) + return + } + if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue { + _ = s.Store.Cookies.Save(r.Context(), cookieID, res.UpdatedCookies, userID) + } + if res.ItemID != "" { + detail := map[string]any{ + "item_image": res.ImageURL, + "web_url": res.ItemURL, + "category_name": res.CategoryName, + "quantity": res.Quantity, + "publish_raw": res.RawData, + } + detailJSON, _ := json.Marshal(detail) + if err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{ + CookieID: cookieID, + ItemID: res.ItemID, + ItemTitle: res.Title, + ItemDescription: description, + ItemCategory: res.CategoryID, + ItemPrice: res.PriceText, + ItemDetail: string(detailJSON), + MultiQuantityDelivery: quantity > 1, + }); err != nil && s.Logger != nil { + s.Logger.Warn("保存发布商品失败", "cookie_id", cookieID, "item_id", res.ItemID, "err", err) + } + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "message": "商品发布成功", + "item_id": res.ItemID, + "item_url": res.ItemURL, + "item_image": res.ImageURL, + "item_title": res.Title, + "item_price": res.PriceText, + "quantity": res.Quantity, + "category_id": res.CategoryID, + "category_name": res.CategoryName, + }) +} + +func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) { + if r.MultipartForm == nil || r.MultipartForm.File == nil { + return nil, errors.New("至少上传 1 张商品图片") + } + files := r.MultipartForm.File["images"] + if len(files) == 0 { + files = r.MultipartForm.File["image"] + } + if len(files) == 0 { + return nil, errors.New("至少上传 1 张商品图片") + } + if len(files) > maxImages { + return nil, fmt.Errorf("商品图片最多 %d 张", maxImages) + } + images := make([]mtop.PublishImage, 0, len(files)) + for _, fh := range files { + f, err := fh.Open() + if err != nil { + return nil, fmt.Errorf("读取图片失败: %w", err) + } + data, err := io.ReadAll(io.LimitReader(f, 10<<20)) + _ = f.Close() + if err != nil { + return nil, fmt.Errorf("读取图片失败: %w", err) + } + if len(data) == 0 { + return nil, errors.New("图片文件为空") + } + contentType := fh.Header.Get("Content-Type") + if contentType == "" { + contentType = http.DetectContentType(data) + } + if !strings.HasPrefix(contentType, "image/") { + return nil, errors.New("只能上传图片文件") + } + images = append(images, mtop.PublishImage{Filename: fh.Filename, ContentType: contentType, Data: data}) + } + return images, nil +} + +func parseMoneyCents(raw string) (int64, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return 0, nil + } + raw = strings.TrimPrefix(raw, "¥") + raw = strings.TrimPrefix(raw, "¥") + parts := strings.Split(raw, ".") + if len(parts) > 2 { + return 0, fmt.Errorf("金额格式错误") + } + yuan, err := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 64) + if err != nil { + return 0, err + } + cents := int64(0) + if len(parts) == 2 { + frac := strings.TrimSpace(parts[1]) + if len(frac) > 2 { + frac = frac[:2] + } + for len(frac) < 2 { + frac += "0" + } + cents, err = strconv.ParseInt(frac, 10, 64) + if err != nil { + return 0, err + } + } + return yuan*100 + cents, nil +} + +func (s *Server) listItems(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + result := []map[string]any{} + for cid := range all { + items, _ := s.Store.Items.AllForCookie(r.Context(), cid) + for _, it := range items { + result = append(result, itemToMap(it)) + } + } + writeJSON(w, http.StatusOK, result) +} + +func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) { + var req struct { + CookieID string `json:"cookie_id"` + PageSize int `json:"page_size"` + MaxPages int `json:"max_pages"` + } + if err := decodeJSON(r, &req); err != nil || req.CookieID == "" { + writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数") + return + } + cookieValue, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID) + if !ok { + return + } + if req.PageSize <= 0 { + req.PageSize = 20 + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) + defer cancel() + client := &mtop.Client{} + res, err := client.FetchAllItems(ctx, cookieValue, req.PageSize, req.MaxPages) + if err != nil { + writeErr(w, http.StatusBadGateway, err.Error()) + return + } + if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue { + _ = s.Store.Cookies.Save(r.Context(), req.CookieID, res.UpdatedCookies, userID) + } + saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items) + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "message": "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(saved) + " 件", + "total_count": len(res.Items), + "total_pages": res.TotalPages, + "saved_count": saved, + }) +} + +func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request) { + var req struct { + CookieID string `json:"cookie_id"` + PageNumber int `json:"page_number"` + PageSize int `json:"page_size"` + } + if err := decodeJSON(r, &req); err != nil || req.CookieID == "" { + writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数") + return + } + cookieValue, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID) + if !ok { + return + } + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + client := &mtop.Client{} + res, err := client.FetchItemsPage(ctx, cookieValue, req.PageNumber, req.PageSize) + if err != nil { + writeErr(w, http.StatusBadGateway, err.Error()) + return + } + if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue { + _ = s.Store.Cookies.Save(r.Context(), req.CookieID, res.UpdatedCookies, userID) + } + saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items) + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "message": "成功获取第" + strconv.Itoa(res.PageNumber) + "页 " + strconv.Itoa(len(res.Items)) + " 个商品", + "page_number": res.PageNumber, + "page_size": res.PageSize, + "current_count": len(res.Items), + "saved_count": saved, + }) +} + +func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) { + sess := auth.SessionFromContext(r.Context()) + all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询账号失败") + return "", 0, false + } + value, ok := all[cookieID] + if !ok { + writeErr(w, http.StatusForbidden, "无权限操作该账号") + return "", 0, false + } + if value == "" { + writeErr(w, http.StatusBadRequest, "账号 cookie 为空") + return "", 0, false + } + return value, sess.UserID, true +} + +func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) int { + saved := 0 + for _, item := range items { + priceText := item.PriceText + if priceText == "" { + priceText = item.Price + } + err := s.Store.Items.UpsertBasic(ctx, &db.ItemInfoRow{ + CookieID: cookieID, + ItemID: item.ID, + ItemTitle: item.Title, + ItemDescription: "", + ItemCategory: item.CategoryID, + ItemPrice: priceText, + ItemDetail: item.ItemDetail, + }) + if err == nil { + saved++ + } else if s.Logger != nil { + s.Logger.Warn("保存商品失败", "cookie_id", cookieID, "item_id", item.ID, "err", err) + } + } + return saved +} + +func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + items, err := s.Store.Items.AllForCookie(r.Context(), cid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + out := make([]map[string]any, 0, len(items)) + for _, it := range items { + out = append(out, itemToMap(it)) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) getItem(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + it, err := s.Store.Items.Get(r.Context(), cid, itemID) + if err != nil { + writeErr(w, http.StatusNotFound, "商品不存在") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "cookie_id": it.CookieID, "item_id": it.ItemID, "item_title": it.ItemTitle, + "item_description": it.ItemDescription, "item_category": it.ItemCategory, + "item_price": it.ItemPrice, "item_detail": it.ItemDetail, + "is_multi_spec": it.IsMultiSpec, "multi_quantity_delivery": it.MultiQuantityDelivery, + }) +} + +func (s *Server) createItem(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + var req struct { + ItemID string `json:"item_id"` + ItemTitle string `json:"item_title"` + ItemDescription string `json:"item_description"` + ItemCategory string `json:"item_category"` + ItemPrice string `json:"item_price"` + ItemDetail string `json:"item_detail"` + IsMultiSpec bool `json:"is_multi_spec"` + MultiQuantityDelivery bool `json:"multi_quantity_delivery"` + IsMultiQtyShip bool `json:"is_multi_qty_ship"` + } + if err := decodeJSON(r, &req); err != nil || req.ItemID == "" { + writeErr(w, http.StatusBadRequest, "缺少商品 ID") + return + } + if req.MultiQuantityDelivery || req.IsMultiQtyShip { + req.MultiQuantityDelivery = true + } + if err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{ + CookieID: cid, ItemID: req.ItemID, ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription, + ItemCategory: req.ItemCategory, ItemPrice: req.ItemPrice, ItemDetail: req.ItemDetail, + IsMultiSpec: req.IsMultiSpec, MultiQuantityDelivery: req.MultiQuantityDelivery, + }); err != nil { + writeErr(w, http.StatusInternalServerError, "新增失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + var req struct { + ItemTitle string `json:"item_title"` + ItemDescription string `json:"item_description"` + ItemCategory string `json:"item_category"` + ItemPrice string `json:"item_price"` + ItemDetail string `json:"item_detail"` + IsMultiSpec bool `json:"is_multi_spec"` + MultiQuantityDelivery bool `json:"multi_quantity_delivery"` + IsMultiQtyShip bool `json:"is_multi_qty_ship"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.Store.Items.Upsert(r.Context(), &db.ItemInfoRow{ + CookieID: cid, ItemID: itemID, ItemTitle: req.ItemTitle, ItemDescription: req.ItemDescription, + ItemCategory: req.ItemCategory, ItemPrice: req.ItemPrice, ItemDetail: req.ItemDetail, + IsMultiSpec: req.IsMultiSpec, MultiQuantityDelivery: req.MultiQuantityDelivery || req.IsMultiQtyShip, + }); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + if err := s.Store.Items.Delete(r.Context(), cid, itemID); err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + var req struct { + IsMultiSpec bool `json:"is_multi_spec"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.Store.Items.SetMultiSpec(r.Context(), cid, itemID, req.IsMultiSpec); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + var req struct { + MultiQuantityDelivery bool `json:"multi_quantity_delivery"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.Store.Items.SetMultiQuantity(r.Context(), cid, itemID, req.MultiQuantityDelivery); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func itemToMap(it db.ItemInfoRow) map[string]any { + imageURL := itemImageFromDetail(it.ItemDetail) + return map[string]any{ + "id": it.ID, + "cookie_id": it.CookieID, "item_id": it.ItemID, "item_title": it.ItemTitle, + "item_description": it.ItemDescription, "item_category": it.ItemCategory, + "item_price": it.ItemPrice, "item_detail": it.ItemDetail, + "item_image": imageURL, + "is_multi_spec": it.IsMultiSpec, "multi_quantity_delivery": it.MultiQuantityDelivery, + "is_multi_qty_ship": it.MultiQuantityDelivery, + } +} + +func itemImageFromDetail(detail string) string { + if detail == "" { + return "" + } + var m map[string]any + if err := json.Unmarshal([]byte(detail), &m); err != nil { + return "" + } + if pic, ok := m["pic_info"].(map[string]any); ok { + if url, ok := pic["picUrl"].(string); ok { + return url + } + } + if url, ok := m["item_image"].(string); ok { + return url + } + return "" +} diff --git a/internal/server/item_publish_batch_handlers.go b/internal/server/item_publish_batch_handlers.go new file mode 100644 index 0000000..ae54cb9 --- /dev/null +++ b/internal/server/item_publish_batch_handlers.go @@ -0,0 +1,975 @@ +package server + +import ( + "archive/zip" + "bytes" + "context" + "crypto/rand" + "encoding/csv" + "encoding/hex" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "mime" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" + "xianyu-go/internal/xianyu/mtop" +) + +const maxPublishBatchRows = 50 + +type publishBatchPreviewRow struct { + RowNo int `json:"row_no"` + Valid bool `json:"valid"` + Errors []string `json:"errors,omitempty"` + CookieID string `json:"cookie_id"` + Title string `json:"title"` + Price string `json:"price"` + Quantity int `json:"quantity"` + Images []string `json:"images"` + AutoCreateDeliveryRule bool `json:"auto_create_delivery_rule"` + CardGroupID int64 `json:"card_group_id"` + DeliveryCount int `json:"delivery_count"` +} + +type publishBatchParsedRow struct { + RowNo int + CookieID string + Title string + Description string + Price string + OriginalPrice string + Quantity int + PostageMode string + Postage string + Images []string + AutoCreateDeliveryRule bool + CardGroupID int64 + DeliveryCount int + Errors []string + Raw map[string]any +} + +func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + if err := r.ParseMultipartForm(256 << 20); err != nil { + writeErr(w, http.StatusBadRequest, "解析上传文件失败") + return + } + defaultCookieID := strings.TrimSpace(r.FormValue("default_cookie_id")) + if defaultCookieID != "" && !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) { + writeErr(w, http.StatusForbidden, "默认账号不属于当前用户") + return + } + source, sourceHeader, err := r.FormFile("file") + if err != nil { + writeErr(w, http.StatusBadRequest, "缺少商品表格文件") + return + } + defer source.Close() + sourceBytes, err := io.ReadAll(io.LimitReader(source, 20<<20)) + if err != nil { + writeErr(w, http.StatusBadRequest, "读取商品表格失败") + return + } + batchID := "batch_" + randomHex(12) + uploadDir := filepath.Join(s.publishUploadRoot(), "publish_batches", batchID) + if err := os.MkdirAll(uploadDir, 0o755); err != nil { + writeErr(w, http.StatusInternalServerError, "创建上传目录失败") + return + } + sourceName := safeBaseName(sourceHeader.Filename) + if sourceName == "" { + sourceName = "products.csv" + } + _ = os.WriteFile(filepath.Join(uploadDir, sourceName), sourceBytes, 0o644) + + if zipFile, zipHeader, err := r.FormFile("images_zip"); err == nil { + defer zipFile.Close() + zipBytes, err := io.ReadAll(io.LimitReader(zipFile, 200<<20)) + if err != nil { + writeErr(w, http.StatusBadRequest, "读取图片 zip 失败") + return + } + zipName := safeBaseName(zipHeader.Filename) + if zipName == "" { + zipName = "images.zip" + } + if err := os.WriteFile(filepath.Join(uploadDir, zipName), zipBytes, 0o644); err != nil { + writeErr(w, http.StatusInternalServerError, "保存图片 zip 失败") + return + } + if err := extractPublishImagesZip(zipBytes, uploadDir); err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + } + + maps, err := parsePublishSheetBytes(sourceBytes, sourceName) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + if len(maps) > maxPublishBatchRows { + writeErr(w, http.StatusBadRequest, fmt.Sprintf("单个批次最多支持 %d 条商品", maxPublishBatchRows)) + return + } + parsed := s.parsePublishRows(r.Context(), sess.UserID, defaultCookieID, uploadDir, maps) + rows := make([]db.ItemPublishBatchRow, 0, len(parsed)) + previewRows := make([]publishBatchPreviewRow, 0, len(parsed)) + valid, invalid := 0, 0 + for _, p := range parsed { + isValid := len(p.Errors) == 0 + if isValid { + valid++ + } else { + invalid++ + } + imagesJSON, _ := json.Marshal(p.Images) + rawJSON, _ := json.Marshal(p.Raw) + status := "pending" + errMsg := "" + if !isValid { + status = "failed" + errMsg = strings.Join(p.Errors, ";") + } + rows = append(rows, db.ItemPublishBatchRow{ + RowNo: p.RowNo, + CookieID: p.CookieID, + Title: p.Title, + Description: p.Description, + Price: p.Price, + OriginalPrice: p.OriginalPrice, + Quantity: p.Quantity, + PostageMode: p.PostageMode, + Postage: p.Postage, + ImagesJSON: string(imagesJSON), + AutoCreateDeliveryRule: p.AutoCreateDeliveryRule, + CardGroupID: p.CardGroupID, + DeliveryCount: p.DeliveryCount, + Status: status, + ErrorMessage: errMsg, + RawJSON: string(rawJSON), + }) + previewRows = append(previewRows, publishBatchPreviewRow{ + RowNo: p.RowNo, + Valid: isValid, + Errors: p.Errors, + CookieID: p.CookieID, + Title: p.Title, + Price: p.Price, + Quantity: p.Quantity, + Images: p.Images, + AutoCreateDeliveryRule: p.AutoCreateDeliveryRule, + CardGroupID: p.CardGroupID, + DeliveryCount: p.DeliveryCount, + }) + } + if len(rows) == 0 { + writeErr(w, http.StatusBadRequest, "表格中没有有效数据行") + return + } + if err := s.Store.PublishBatches.Create(r.Context(), &db.ItemPublishBatch{ + ID: batchID, + UserID: sess.UserID, + DefaultCookieID: defaultCookieID, + Filename: sourceName, + UploadDir: uploadDir, + Status: "preview", + }, rows); err != nil { + writeErr(w, http.StatusInternalServerError, "保存预检结果失败") + return + } + _ = s.Store.PublishBatches.Recount(r.Context(), batchID) + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "preview_id": batchID, + "total": len(rows), + "valid": valid, + "invalid": invalid, + "rows": previewRows, + }) +} + +func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + var req struct { + PreviewID string `json:"preview_id"` + BatchID string `json:"batch_id"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + batchID := strings.TrimSpace(req.PreviewID) + if batchID == "" { + batchID = strings.TrimSpace(req.BatchID) + } + if batchID == "" { + writeErr(w, http.StatusBadRequest, "缺少 preview_id") + return + } + batch, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID) + if err != nil { + writeErr(w, http.StatusNotFound, "批量任务不存在") + return + } + if batch.Status != "preview" && batch.Status != "pending" && batch.Status != "completed" { + writeErr(w, http.StatusBadRequest, "当前任务状态不能开始发布") + return + } + pending, err := s.Store.PublishBatches.PendingRows(r.Context(), batch.ID, false) + if err != nil { + writeErr(w, http.StatusInternalServerError, "读取任务失败") + return + } + if len(pending) == 0 { + writeErr(w, http.StatusBadRequest, "没有可发布的商品行") + return + } + if err := s.Store.PublishBatches.SetBatchStatus(r.Context(), batch.ID, "running"); err != nil { + writeErr(w, http.StatusInternalServerError, "启动任务失败") + return + } + go s.runItemPublishBatch(context.Background(), sess.UserID, batch.ID, false) + writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batch.ID}) +} + +func (s *Server) getItemPublishBatch(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + batchID := chi.URLParam(r, "batch_id") + batch, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID) + if err != nil { + writeErr(w, http.StatusNotFound, "批量任务不存在") + return + } + rows, err := s.Store.PublishBatches.Rows(r.Context(), batch.ID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "读取任务明细失败") + return + } + writeJSON(w, http.StatusOK, publishBatchToMap(batch, rows)) +} + +func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + batchID := chi.URLParam(r, "batch_id") + if _, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID); err != nil { + writeErr(w, http.StatusNotFound, "批量任务不存在") + return + } + if err := s.Store.PublishBatches.SetBatchStatus(r.Context(), batchID, "canceled"); err != nil { + writeErr(w, http.StatusInternalServerError, "取消任务失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + batchID := chi.URLParam(r, "batch_id") + if _, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID); err != nil { + writeErr(w, http.StatusNotFound, "批量任务不存在") + return + } + if err := s.Store.PublishBatches.ResetFailed(r.Context(), batchID); err != nil { + writeErr(w, http.StatusInternalServerError, "重置失败项失败") + return + } + _ = s.Store.PublishBatches.Recount(r.Context(), batchID) + if err := s.Store.PublishBatches.SetBatchStatus(r.Context(), batchID, "running"); err != nil { + writeErr(w, http.StatusInternalServerError, "启动重试失败") + return + } + go s.runItemPublishBatch(context.Background(), sess.UserID, batchID, false) + writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batchID}) +} + +func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + batchID := chi.URLParam(r, "batch_id") + batch, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID) + if err != nil { + writeErr(w, http.StatusNotFound, "批量任务不存在") + return + } + rows, err := s.Store.PublishBatches.Rows(r.Context(), batch.ID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "读取任务明细失败") + return + } + var buf bytes.Buffer + buf.WriteString("\xEF\xBB\xBF") + cw := csv.NewWriter(&buf) + _ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "商品ID", "商品URL", "错误原因"}) + for _, row := range rows { + _ = cw.Write([]string{ + strconv.Itoa(row.RowNo), row.Status, row.CookieID, row.Title, row.Price, + strconv.Itoa(row.Quantity), row.ItemID, row.ItemURL, row.ErrorMessage, + }) + } + cw.Flush() + filename := fmt.Sprintf("publish_result_%s.csv", batch.ID) + w.Header().Set("Content-Type", "text/csv; charset=utf-8") + w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filename)) + _, _ = w.Write(buf.Bytes()) +} + +func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID string, failedOnly bool) { + rows, err := s.Store.PublishBatches.PendingRows(ctx, batchID, failedOnly) + if err != nil { + if s.Logger != nil { + s.Logger.Warn("读取批量发布行失败", "batch", batchID, "err", err) + } + return + } + client := s.MTop + if client == nil { + client = &mtop.Client{} + } + for idx, row := range rows { + status, err := s.Store.PublishBatches.BatchStatus(ctx, batchID) + if err != nil || status == "canceled" { + _ = s.Store.PublishBatches.Recount(ctx, batchID) + return + } + _ = s.Store.PublishBatches.MarkRowRunning(ctx, row.ID) + if err := s.publishBatchRow(ctx, userID, client, row); err != nil { + _ = s.Store.PublishBatches.MarkRowFailed(ctx, row.ID, err.Error()) + } + _ = s.Store.PublishBatches.Recount(ctx, batchID) + if idx < len(rows)-1 { + delay := time.Duration(10+idx%21) * time.Second + timer := time.NewTimer(delay) + select { + case <-ctx.Done(): + timer.Stop() + return + case <-timer.C: + } + } + } + _ = s.Store.PublishBatches.Recount(ctx, batchID) + batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID) + if err == nil && batch.Status != "canceled" { + finalStatus := "completed" + if batch.SuccessCount == 0 && batch.FailedCount > 0 { + finalStatus = "failed" + } + _ = s.Store.PublishBatches.SetBatchStatus(ctx, batchID, finalStatus) + } +} + +func (s *Server) publishBatchRow(ctx context.Context, userID int64, client *mtop.Client, row db.ItemPublishBatchRow) error { + batch, err := s.Store.PublishBatches.Get(ctx, userID, row.BatchID) + if err != nil { + return errors.New("批量任务不存在") + } + cookieValue, err := s.cookieValueForUser(ctx, userID, row.CookieID) + if err != nil { + return err + } + priceCents, err := parseMoneyCents(row.Price) + if err != nil || priceCents <= 0 { + return errors.New("商品价格必须大于 0") + } + origCents, _ := parseMoneyCents(row.OriginalPrice) + postageCents, _ := parseMoneyCents(row.Postage) + images, err := loadBatchPublishImages(ctx, batch.UploadDir, row) + if err != nil { + return err + } + pctx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + res, err := client.PublishItem(pctx, cookieValue, mtop.PublishItemRequest{ + Title: row.Title, + Description: firstNonEmpty(row.Description, row.Title), + PriceCents: priceCents, + OriginalPriceCents: origCents, + Quantity: row.Quantity, + PostageMode: row.PostageMode, + PostageCents: postageCents, + Images: images, + }) + if err != nil { + var perr *mtop.PublishError + if errors.As(err, &perr) && perr.Code == mtop.PublishErrorStockPermissionMissing { + return errors.New("该账号没有库存发布权限,无法按库存数量发布商品") + } + return err + } + if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue { + _ = s.Store.Cookies.Save(ctx, row.CookieID, res.UpdatedCookies, userID) + } + if res.ItemID != "" { + detail := map[string]any{ + "item_image": res.ImageURL, + "web_url": res.ItemURL, + "category_name": res.CategoryName, + "quantity": res.Quantity, + "publish_raw": res.RawData, + } + detailJSON, _ := json.Marshal(detail) + _ = s.Store.Items.Upsert(ctx, &db.ItemInfoRow{ + CookieID: row.CookieID, + ItemID: res.ItemID, + ItemTitle: firstNonEmpty(res.Title, row.Title), + ItemDescription: row.Description, + ItemCategory: res.CategoryID, + ItemPrice: res.PriceText, + ItemDetail: string(detailJSON), + MultiQuantityDelivery: row.Quantity > 1, + }) + if row.AutoCreateDeliveryRule && row.CardGroupID > 0 { + _ = s.createPublishDeliveryRule(ctx, userID, row, res) + } + } + rawJSON, _ := json.Marshal(res.RawData) + return s.Store.PublishBatches.MarkRowSuccess(ctx, row.ID, res.ItemID, res.ItemURL, string(rawJSON)) +} + +func (s *Server) createPublishDeliveryRule(ctx context.Context, userID int64, row db.ItemPublishBatchRow, res *mtop.PublishItemResult) error { + tx, err := s.Store.DB.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + req := []deliveryVariantRequest{{CardID: row.CardGroupID, DeliveryCount: row.DeliveryCount}} + ruleRes, err := tx.ExecContext(ctx, + `INSERT INTO delivery_rules + (keyword,card_id,delivery_count,enabled,description,user_id,cookie_id,item_id) + VALUES (?,?,?,?,?,?,?,?)`, + firstNonEmpty(res.Title, row.Title), row.CardGroupID, row.DeliveryCount, true, "批量铺货自动创建", + userID, row.CookieID, res.ItemID) + if err != nil { + return err + } + ruleID, _ := ruleRes.LastInsertId() + if err := insertDeliveryVariants(ctx, tx, userID, ruleID, req); err != nil { + return err + } + return tx.Commit() +} + +func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCookieID, uploadDir string, input []map[string]any) []publishBatchParsedRow { + out := make([]publishBatchParsedRow, 0, len(input)) + for i, m := range input { + row := publishBatchParsedRow{ + RowNo: i + 2, + CookieID: firstImportString(m, "cookie_id", "账号ID", "账号id", "账号"), + Title: firstImportString(m, "title", "标题", "商品标题", "商品名称"), + Description: firstImportString(m, "description", "描述", "商品描述", "商品详情"), + Price: firstImportString(m, "price", "价格", "商品价格"), + OriginalPrice: firstImportString(m, "original_price", "原价"), + PostageMode: firstImportString(m, "postage_mode", "邮费模式"), + Postage: firstImportString(m, "postage", "邮费"), + Raw: m, + } + if row.CookieID == "" { + row.CookieID = defaultCookieID + } + if row.Description == "" { + row.Description = row.Title + } + if row.PostageMode == "" { + row.PostageMode = "free" + } + row.PostageMode = strings.ToLower(row.PostageMode) + if row.PostageMode == "包邮" || row.PostageMode == "free_shipping" { + row.PostageMode = "free" + } + if row.PostageMode == "固定邮费" || row.PostageMode == "一口价邮费" { + row.PostageMode = "fixed" + } + row.Quantity = atoiPublishDefault(firstImportString(m, "quantity", "库存", "数量"), 1) + row.DeliveryCount = atoiPublishDefault(firstImportString(m, "delivery_count", "发货数量"), 1) + row.CardGroupID = int64(atoiPublishDefault(firstImportString(m, "card_group_id", "卡密组ID", "卡密组id", "卡密ID", "卡密id"), 0)) + row.AutoCreateDeliveryRule = parseLooseBool(firstImportString(m, "auto_create_delivery_rule", "自动创建发货规则")) + row.Images = splitImageRefs(firstImportString(m, "images", "image", "图片", "商品图片")) + if row.CookieID == "" { + row.Errors = append(row.Errors, "缺少账号ID") + } else if !s.cookieOwnedByUser(ctx, userID, row.CookieID) { + row.Errors = append(row.Errors, "账号不存在或不属于当前用户") + } + if strings.TrimSpace(row.Title) == "" { + row.Errors = append(row.Errors, "缺少标题") + } + if cents, err := parseMoneyCents(row.Price); err != nil || cents <= 0 { + row.Errors = append(row.Errors, "价格必须大于 0") + } + if row.Quantity <= 0 { + row.Errors = append(row.Errors, "库存必须大于 0") + } + if row.PostageMode != "free" && row.PostageMode != "fixed" { + row.Errors = append(row.Errors, "邮费模式必须是 free 或 fixed") + } + if row.PostageMode == "fixed" { + if cents, err := parseMoneyCents(row.Postage); err != nil || cents < 0 { + row.Errors = append(row.Errors, "固定邮费格式错误") + } + } + if len(row.Images) == 0 { + row.Errors = append(row.Errors, "缺少图片") + } + if len(row.Images) > 9 { + row.Errors = append(row.Errors, "商品图片最多 9 张") + } + for _, ref := range row.Images { + if err := validateBatchImageRef(uploadDir, ref); err != nil { + row.Errors = append(row.Errors, err.Error()) + } + } + if row.AutoCreateDeliveryRule { + if row.CardGroupID <= 0 { + row.Errors = append(row.Errors, "自动创建发货规则需要填写卡密组ID") + } else if !s.cardOwnedByUser(ctx, userID, row.CardGroupID) { + row.Errors = append(row.Errors, "卡密组不存在或不属于当前用户") + } + if row.DeliveryCount <= 0 { + row.Errors = append(row.Errors, "发货数量必须大于 0") + } + } + out = append(out, row) + } + return out +} + +func parsePublishSheetBytes(raw []byte, filename string) ([]map[string]any, error) { + if len(bytes.TrimSpace(raw)) == 0 { + return nil, fmt.Errorf("导入内容为空") + } + switch strings.ToLower(filepath.Ext(filename)) { + case ".xlsx": + return parseXLSXPublishSheet(raw) + case ".csv": + return parseDelimitedPublishSheet(raw, ',') + case ".tsv": + return parseDelimitedPublishSheet(raw, '\t') + case ".xls": + return nil, fmt.Errorf("暂不支持旧版 .xls,请另存为 .xlsx 或 CSV 后导入") + default: + return parseDelimitedPublishSheet(raw, ',') + } +} + +func parseDelimitedPublishSheet(raw []byte, comma rune) ([]map[string]any, error) { + reader := csv.NewReader(bytes.NewReader(raw)) + reader.Comma = comma + reader.FieldsPerRecord = -1 + reader.LazyQuotes = true + records, err := reader.ReadAll() + if err != nil { + return nil, fmt.Errorf("解析表格失败: %w", err) + } + if len(records) < 2 { + return nil, fmt.Errorf("表格至少需要表头和一行数据") + } + return rowsToPublishMaps(records[0], records[1:]), nil +} + +func parseXLSXPublishSheet(raw []byte) ([]map[string]any, error) { + zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + return nil, fmt.Errorf("解析 xlsx 失败: %w", err) + } + shared := xlsxSharedStrings(zr) + var sheet *zip.File + for _, f := range zr.File { + if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") { + sheet = f + break + } + } + if sheet == nil { + return nil, fmt.Errorf("xlsx 中未找到工作表") + } + rc, err := sheet.Open() + if err != nil { + return nil, err + } + defer rc.Close() + var ws xlsxWorksheet + if err := xml.NewDecoder(rc).Decode(&ws); err != nil { + return nil, fmt.Errorf("解析工作表失败: %w", err) + } + rows := make([][]string, 0, len(ws.SheetData.Rows)) + for _, row := range ws.SheetData.Rows { + values := []string{} + for _, cell := range row.Cells { + idx := xlsxCellIndex(cell.Ref) + for len(values) <= idx { + values = append(values, "") + } + values[idx] = xlsxCellValue(cell, shared) + } + rows = append(rows, values) + } + if len(rows) < 2 { + return nil, fmt.Errorf("xlsx 至少需要表头和一行数据") + } + return rowsToPublishMaps(rows[0], rows[1:]), nil +} + +func rowsToPublishMaps(headers []string, rows [][]string) []map[string]any { + keys := make([]string, len(headers)) + for i, h := range headers { + keys[i] = normalizePublishHeader(h) + } + out := make([]map[string]any, 0, len(rows)) + for _, row := range rows { + m := map[string]any{} + nonEmpty := false + for i, key := range keys { + if key == "" || i >= len(row) { + continue + } + value := strings.TrimSpace(row[i]) + if value != "" { + nonEmpty = true + } + m[key] = value + } + if nonEmpty { + out = append(out, m) + } + } + return out +} + +func normalizePublishHeader(header string) string { + h := strings.ToLower(strings.TrimSpace(header)) + h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h) + switch h { + case "cookieid", "账号id", "账号", "闲鱼账号": + return "cookie_id" + case "title", "itemtitle", "标题", "商品标题", "商品名称": + return "title" + case "description", "desc", "itemdescription", "描述", "商品描述", "商品详情": + return "description" + case "price", "itemprice", "价格", "商品价格": + return "price" + case "originalprice", "原价": + return "original_price" + case "quantity", "库存", "数量": + return "quantity" + case "postagemode", "邮费模式": + return "postage_mode" + case "postage", "邮费": + return "postage" + case "images", "image", "图片", "商品图片": + return "images" + case "autocreatedeliveryrule", "自动创建发货规则": + return "auto_create_delivery_rule" + case "cardgroupid", "cardid", "卡密组id", "卡密id": + return "card_group_id" + case "deliverycount", "发货数量": + return "delivery_count" + default: + return strings.TrimSpace(header) + } +} + +func extractPublishImagesZip(raw []byte, dest string) error { + zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + return fmt.Errorf("解析图片 zip 失败: %w", err) + } + for _, f := range zr.File { + if f.FileInfo().IsDir() { + continue + } + rel, err := safeZipPath(f.Name) + if err != nil { + return err + } + target := filepath.Join(dest, rel) + if !strings.HasPrefix(target, filepath.Clean(dest)+string(os.PathSeparator)) { + return fmt.Errorf("zip 内路径不安全: %s", f.Name) + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + rc, err := f.Open() + if err != nil { + return err + } + data, err := io.ReadAll(io.LimitReader(rc, 10<<20)) + _ = rc.Close() + if err != nil { + return err + } + if len(data) == 0 { + continue + } + if !strings.HasPrefix(http.DetectContentType(data), "image/") { + continue + } + if err := os.WriteFile(target, data, 0o644); err != nil { + return err + } + } + return nil +} + +func loadBatchPublishImages(ctx context.Context, uploadDir string, row db.ItemPublishBatchRow) ([]mtop.PublishImage, error) { + var refs []string + if err := json.Unmarshal([]byte(row.ImagesJSON), &refs); err != nil { + return nil, fmt.Errorf("图片字段格式错误") + } + if len(refs) == 0 { + return nil, errors.New("至少上传 1 张商品图片") + } + images := make([]mtop.PublishImage, 0, len(refs)) + for _, ref := range refs { + var data []byte + var contentType string + var filename string + var err error + if isHTTPURL(ref) { + data, contentType, err = downloadImageURL(ctx, ref) + filename = pathBaseFromURL(ref) + } else { + data, contentType, filename, err = readBatchImageFile(uploadDir, ref) + } + if err != nil { + return nil, err + } + images = append(images, mtop.PublishImage{Filename: filename, ContentType: contentType, Data: data}) + } + return images, nil +} + +func readBatchImageFile(uploadDir, ref string) ([]byte, string, string, error) { + rel, err := safeZipPath(ref) + if err != nil { + return nil, "", "", err + } + path := filepath.Join(uploadDir, rel) + data, err := os.ReadFile(path) + if err != nil { + return nil, "", "", fmt.Errorf("读取图片失败: %s", ref) + } + if len(data) == 0 { + return nil, "", "", fmt.Errorf("图片文件为空: %s", ref) + } + contentType := http.DetectContentType(data) + if !strings.HasPrefix(contentType, "image/") { + return nil, "", "", fmt.Errorf("不是有效图片: %s", ref) + } + return data, contentType, filepath.Base(rel), nil +} + +func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, "", fmt.Errorf("图片 URL 无效: %s", rawURL) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, "", fmt.Errorf("下载图片失败: %s", rawURL) + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, "", fmt.Errorf("下载图片失败: %s HTTP %d", rawURL, resp.StatusCode) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20)) + if err != nil { + return nil, "", fmt.Errorf("读取远程图片失败: %s", rawURL) + } + contentType := resp.Header.Get("Content-Type") + if i := strings.Index(contentType, ";"); i >= 0 { + contentType = contentType[:i] + } + if contentType == "" || contentType == "application/octet-stream" { + contentType = http.DetectContentType(data) + } + if !strings.HasPrefix(contentType, "image/") { + return nil, "", fmt.Errorf("远程文件不是图片: %s", rawURL) + } + return data, contentType, nil +} + +func validateBatchImageRef(uploadDir, ref string) error { + if isHTTPURL(ref) { + return nil + } + rel, err := safeZipPath(ref) + if err != nil { + return err + } + path := filepath.Join(uploadDir, rel) + info, err := os.Stat(path) + if err != nil || info.IsDir() { + return fmt.Errorf("图片文件不存在: %s", ref) + } + return nil +} + +func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) map[string]any { + outRows := make([]map[string]any, 0, len(rows)) + pending := 0 + running := 0 + for _, row := range rows { + if row.Status == "pending" { + pending++ + } + if row.Status == "running" { + running++ + } + var refs []string + _ = json.Unmarshal([]byte(row.ImagesJSON), &refs) + outRows = append(outRows, map[string]any{ + "id": row.ID, "row_no": row.RowNo, "cookie_id": row.CookieID, "title": row.Title, + "price": row.Price, "quantity": row.Quantity, "images": refs, + "auto_create_delivery_rule": row.AutoCreateDeliveryRule, + "card_group_id": row.CardGroupID, "delivery_count": row.DeliveryCount, + "status": row.Status, "item_id": row.ItemID, "item_url": row.ItemURL, + "error_message": row.ErrorMessage, + }) + } + return map[string]any{ + "id": batch.ID, "status": batch.Status, "filename": batch.Filename, + "total": batch.TotalCount, "success": batch.SuccessCount, "failed": batch.FailedCount, + "pending": pending, "running": running, "rows": outRows, + "created_at": batch.CreatedAt, "updated_at": batch.UpdatedAt, + } +} + +func (s *Server) cookieOwnedByUser(ctx context.Context, userID int64, cookieID string) bool { + all, err := s.Store.Cookies.AllForUser(ctx, userID) + if err != nil { + return false + } + _, ok := all[cookieID] + return ok +} + +func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID string) (string, error) { + all, err := s.Store.Cookies.AllForUser(ctx, userID) + if err != nil { + return "", err + } + value, ok := all[cookieID] + if !ok || strings.TrimSpace(value) == "" { + return "", errors.New("账号不存在或 Cookie 为空") + } + return value, nil +} + +func (s *Server) cardOwnedByUser(ctx context.Context, userID, cardID int64) bool { + var exists int + err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, cardID, userID).Scan(&exists) + return err == nil && exists != 0 +} + +func (s *Server) publishUploadRoot() string { + return defaultPublishUploadRoot() +} + +func defaultPublishUploadRoot() string { + if v := strings.TrimSpace(os.Getenv("XIANYU_UPLOAD_DIR")); v != "" { + return v + } + return filepath.Join("data", "uploads") +} + +func randomHex(n int) string { + buf := make([]byte, n) + if _, err := rand.Read(buf); err != nil { + return strconv.FormatInt(time.Now().UnixNano(), 36) + } + return hex.EncodeToString(buf) +} + +func safeBaseName(name string) string { + name = strings.TrimSpace(filepath.Base(name)) + name = strings.ReplaceAll(name, string(os.PathSeparator), "_") + if name == "." || name == "/" { + return "" + } + return name +} + +func safeZipPath(raw string) (string, error) { + raw = strings.TrimSpace(strings.ReplaceAll(raw, "\\", "/")) + if raw == "" || strings.HasPrefix(raw, "/") { + return "", fmt.Errorf("图片路径不安全: %s", raw) + } + clean := filepath.Clean(raw) + if clean == "." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) || clean == ".." { + return "", fmt.Errorf("图片路径不安全: %s", raw) + } + return clean, nil +} + +func splitImageRefs(raw string) []string { + raw = strings.ReplaceAll(raw, "\n", ";") + raw = strings.ReplaceAll(raw, ";", ";") + parts := strings.Split(raw, ";") + out := []string{} + for _, p := range parts { + p = strings.TrimSpace(p) + if p != "" { + out = append(out, p) + } + } + return out +} + +func parseLooseBool(raw string) bool { + raw = strings.ToLower(strings.TrimSpace(raw)) + switch raw { + case "1", "true", "yes", "y", "on", "是", "开启", "启用": + return true + default: + return false + } +} + +func atoiPublishDefault(raw string, def int) int { + raw = strings.TrimSpace(raw) + if raw == "" { + return def + } + if f, err := strconv.ParseFloat(raw, 64); err == nil { + return int(f) + } + return def +} + +func isHTTPURL(ref string) bool { + ref = strings.ToLower(strings.TrimSpace(ref)) + return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://") +} + +func pathBaseFromURL(rawURL string) string { + base := filepath.Base(strings.Split(rawURL, "?")[0]) + if base == "." || base == "/" || base == "" { + exts, _ := mime.ExtensionsByType(http.DetectContentType(nil)) + if len(exts) > 0 { + return "image" + exts[0] + } + return "image.jpg" + } + return base +} + +func firstNonEmpty(values ...string) string { + for _, v := range values { + if strings.TrimSpace(v) != "" { + return v + } + } + return "" +} diff --git a/internal/server/keyword_handlers.go b/internal/server/keyword_handlers.go new file mode 100644 index 0000000..6cfd19f --- /dev/null +++ b/internal/server/keyword_handlers.go @@ -0,0 +1,172 @@ +package server + +import ( + "net/http" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" +) + +// mountKeywordsReal 关键字端点。 +func (s *Server) mountKeywordsReal(r chi.Router) { + r.Get("/keywords/{cid}", s.listKeywords) + r.Post("/keywords/{cid}", s.addKeyword) + r.Get("/keywords-with-item-id/{cid}", s.listKeywordsWithItemID) + r.Post("/keywords-with-item-id/{cid}", s.addKeywordWithItemID) + r.Get("/keywords-with-type/{cid}", s.listKeywordsWithType) + r.Delete("/keywords/{cid}/{index}", s.deleteKeyword) +} + +func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + rows, err := s.Store.Keywords.AllRows(r.Context(), cid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + out := make([]map[string]any, 0, len(rows)) + for _, k := range rows { + out = append(out, map[string]any{"keyword": k.Keyword, "reply": k.Reply}) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + rows, err := s.Store.Keywords.AllRows(r.Context(), cid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + out := make([]map[string]any, 0, len(rows)) + for _, k := range rows { + out = append(out, map[string]any{"keyword": k.Keyword, "reply": k.Reply, "item_id": k.ItemID}) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + rows, err := s.Store.Keywords.AllRows(r.Context(), cid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + out := make([]map[string]any, 0, len(rows)) + for _, k := range rows { + out = append(out, map[string]any{ + "keyword": k.Keyword, "reply": k.Reply, "item_id": k.ItemID, + "type": k.Type, "image_url": k.ImageURL, + }) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + Keyword string `json:"keyword"` + Reply string `json:"reply"` + } + if err := decodeJSON(r, &req); err != nil || req.Keyword == "" { + writeErr(w, http.StatusBadRequest, "keyword 必填") + return + } + if _, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, "", "text", ""); err != nil { + writeErr(w, http.StatusInternalServerError, "添加失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + Keyword string `json:"keyword"` + Reply string `json:"reply"` + ItemID string `json:"item_id"` + } + if err := decodeJSON(r, &req); err != nil || req.Keyword == "" { + writeErr(w, http.StatusBadRequest, "keyword 必填") + return + } + if _, err := s.Store.Keywords.Add(r.Context(), cid, req.Keyword, req.Reply, req.ItemID, "text", ""); err != nil { + writeErr(w, http.StatusInternalServerError, "添加失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + index := atoiDefault(chi.URLParam(r, "index"), -1) + if err := s.Store.Keywords.DeleteByIndex(r.Context(), cid, index); err != nil { + writeErr(w, http.StatusNotFound, "关键字不存在") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// ---- 指定商品回复 ---- +func (s *Server) mountItemRepliesReal(r chi.Router) { + r.Get("/itemReplays", s.listItemReplies) + r.Get("/item-reply/{cookie_id}/{item_id}", s.getItemReply) + r.Put("/item-reply/{cookie_id}/{item_id}", s.setItemReply) + r.Delete("/item-reply/{cookie_id}/{item_id}", s.deleteItemReply) +} + +func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + all, _ := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + var result []map[string]any + for cid := range all { + rows, _ := s.Store.ItemReps.AllForUser(r.Context(), cid) + for _, ir := range rows { + result = append(result, map[string]any{ + "item_id": ir.ItemID, "cookie_id": ir.CookieID, "reply_content": ir.ReplyContent, + }) + } + } + writeJSON(w, http.StatusOK, result) +} + +func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + ir, err := s.Store.ItemReps.Get(r.Context(), cid, itemID) + if err != nil { + writeJSON(w, http.StatusOK, map[string]any{"reply_content": ""}) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "item_id": ir.ItemID, "cookie_id": ir.CookieID, "reply_content": ir.ReplyContent, + }) +} + +func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + var req struct { + ReplyContent string `json:"reply_content"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.Store.ItemReps.Set(r.Context(), cid, itemID, req.ReplyContent); err != nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteItemReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + itemID := chi.URLParam(r, "item_id") + if err := s.Store.ItemReps.Delete(r.Context(), cid, itemID); err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} diff --git a/internal/server/notification_handlers.go b/internal/server/notification_handlers.go new file mode 100644 index 0000000..abf5dfe --- /dev/null +++ b/internal/server/notification_handlers.go @@ -0,0 +1,205 @@ +package server + +import ( + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/db" +) + +// mountNotificationsReal 通知渠道 + 账号绑定。 +func (s *Server) mountNotificationsReal(r chi.Router) { + r.Get("/notification-channels", s.listChannels) + r.Post("/notification-channels", s.createChannel) + r.Put("/notification-channels/{channel_id}", s.updateChannel) + r.Delete("/notification-channels/{channel_id}", s.deleteChannel) + r.Get("/message-notifications", s.listMessageNotifications) + r.Delete("/message-notifications/account/{cid}", s.deleteAccountNotifications) + r.Delete("/message-notifications/{notification_id}", s.deleteMessageNotification) + r.Get("/message-notifications/{cid}", s.getAccountBindings) + r.Post("/message-notifications/{cid}", s.setAccountBindings) +} + +func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + chs, err := s.Store.Notifications.AllChannelsForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + writeJSON(w, http.StatusOK, chs) +} + +func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + var req struct { + Name string `json:"name"` + Type string `json:"type"` + Config string `json:"config"` + Enabled bool `json:"enabled"` + } + if err := decodeJSON(r, &req); err != nil || req.Name == "" || req.Type == "" { + writeErr(w, http.StatusBadRequest, "name 和 type 必填") + return + } + id, err := s.Store.Notifications.CreateChannel(r.Context(), &db.NotificationChannelRow{ + Name: req.Name, Type: req.Type, Config: req.Config, Enabled: req.Enabled, UserID: sess.UserID, + }) + if err != nil { + writeErr(w, http.StatusInternalServerError, "创建失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id}) +} + +func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效ID") + return + } + var req struct { + Name string `json:"name"` + Type string `json:"type"` + Config string `json:"config"` + Enabled bool `json:"enabled"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.Store.Notifications.UpdateChannel(r.Context(), &db.NotificationChannelRow{ + ID: id, Name: req.Name, Type: req.Type, Config: req.Config, Enabled: req.Enabled, + }); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "channel_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效ID") + return + } + if err := s.Store.Notifications.DeleteChannel(r.Context(), id); err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + ids, err := s.Store.Notifications.AccountBindings(r.Context(), cid) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"cookie_id": cid, "channel_ids": ids}) +} + +func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT mn.id, mn.cookie_id, mn.channel_id, COALESCE(nc.name, ''), mn.enabled + FROM message_notifications mn + JOIN cookies c ON c.id=mn.cookie_id + LEFT JOIN notification_channels nc ON nc.id=mn.channel_id + WHERE c.user_id=? + ORDER BY mn.id DESC`, sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + out := make(map[string][]map[string]any) + for rows.Next() { + var id, channelID int64 + var cookieID, channelName string + var enabled int + if err := rows.Scan(&id, &cookieID, &channelID, &channelName, &enabled); err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + out[cookieID] = append(out[cookieID], map[string]any{ + "id": id, + "channel_id": channelID, + "channel_name": channelName, + "enabled": enabled != 0, + }) + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cid") + var req struct { + ChannelIDs []int64 `json:"channel_ids"` + ChannelID int64 `json:"channel_id"` + Enabled *bool `json:"enabled"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if req.ChannelID != 0 { + enabled := true + if req.Enabled != nil { + enabled = *req.Enabled + } + _, err := s.Store.DB.ExecContext(r.Context(), + `INSERT INTO message_notifications (cookie_id, channel_id, enabled) + VALUES (?, ?, ?) + ON CONFLICT(cookie_id, channel_id) DO UPDATE SET + enabled=excluded.enabled, + updated_at=CURRENT_TIMESTAMP`, + cid, req.ChannelID, btoi(enabled)) + if err != nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) + return + } + if err := s.Store.Notifications.SetBindings(r.Context(), cid, req.ChannelIDs); err != nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + id, err := strconv.ParseInt(chi.URLParam(r, "notification_id"), 10, 64) + if err != nil { + writeErr(w, http.StatusBadRequest, "无效ID") + return + } + _, err = s.Store.DB.ExecContext(r.Context(), + `DELETE FROM message_notifications + WHERE id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, + id, sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + cid := chi.URLParam(r, "cid") + _, err := s.Store.DB.ExecContext(r.Context(), + `DELETE FROM message_notifications + WHERE cookie_id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, + cid, sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go new file mode 100644 index 0000000..fa10a39 --- /dev/null +++ b/internal/server/order_handlers.go @@ -0,0 +1,985 @@ +package server + +import ( + "archive/zip" + "bytes" + "context" + "encoding/csv" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/http" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" +) + +// mountOrders 订单端点(真实实现)。 +func (s *Server) mountOrdersReal(r chi.Router) { + r.Get("/api/orders", s.listOrders) + r.Get("/api/orders/{order_id}", s.getOrder) + r.Post("/api/orders/refresh", s.refreshOrders) + r.Post("/api/orders/{order_id}/refresh", s.refreshSingleOrder) + r.Post("/api/orders/manual-ship", s.manualShipOrders) + r.Post("/api/orders/import", s.importOrders) + r.Delete("/api/orders/{order_id}", s.deleteOrder) + r.Put("/api/orders/{order_id}", s.updateOrder) +} + +// listOrders 分页查询当前用户订单。 +func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) { + sess := auth.SessionFromContext(r.Context()) + page := atoiDefault(r.URL.Query().Get("page"), 1) + pageSize := atoiDefault(r.URL.Query().Get("page_size"), 20) + cookieID := r.URL.Query().Get("cookie_id") + status := r.URL.Query().Get("status") + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + + all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + if cookieID != "" { + for k := range all { + if k != cookieID { + delete(all, k) + } + } + } + var orders []map[string]any + for cid := range all { + itemRows, _ := s.Store.Items.AllForCookie(r.Context(), cid) + itemsByID := make(map[string]db.ItemInfoRow, len(itemRows)) + for _, item := range itemRows { + itemsByID[item.ItemID] = item + } + rows, err := s.Store.Orders.ByCookie(r.Context(), cid, 1000) + if err != nil { + continue + } + for _, o := range rows { + st := db.NormalizeOrderStatus(o.OrderStatus) + if status != "" && st != status { + continue + } + item := itemsByID[o.ItemID] + orders = append(orders, map[string]any{ + "order_id": o.OrderID, + "item_id": o.ItemID, + "item_title": item.ItemTitle, + "item_image": itemImageFromDetail(item.ItemDetail), + "buyer_id": o.BuyerID, + "spec_name": o.SpecName, + "spec_value": o.SpecValue, + "quantity": o.Quantity, + "amount": o.Amount, + "order_status": st, + "status": st, + "cookie_id": cid, + "is_bargain": o.IsBargain, + "system_shipped": o.SystemShipped, + "receiver_name": o.ReceiverName, + "receiver_phone": o.ReceiverPhone, + "receiver_address": o.ReceiverAddr, + "receiver_city": o.ReceiverCity, + "created_at": o.CreatedAt, + "updated_at": o.UpdatedAt, + }) + } + } + + total := len(orders) + totalPages := (total + pageSize - 1) / pageSize + start := (page - 1) * pageSize + end := start + pageSize + if start > total { + start = total + } + if end > total { + end = total + } + paged := []map[string]any{} + if start < end { + paged = orders[start:end] + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "data": paged, + "total": total, + "page": page, + "page_size": pageSize, + "total_pages": totalPages, + }) +} + +// getOrder 订单详情。 +func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) { + orderID := chi.URLParam(r, "order_id") + o, err := s.Store.Orders.Get(r.Context(), orderID) + if err != nil { + writeErr(w, http.StatusNotFound, "订单不存在") + return + } + itemTitle, itemImage := "", "" + if item, itemErr := s.Store.Items.Get(r.Context(), o.CookieID, o.ItemID); itemErr == nil { + itemTitle = item.ItemTitle + itemImage = itemImageFromDetail(item.ItemDetail) + } + writeJSON(w, http.StatusOK, map[string]any{ + "order_id": o.OrderID, + "item_id": o.ItemID, + "item_title": itemTitle, + "item_image": itemImage, + "buyer_id": o.BuyerID, + "spec_name": o.SpecName, + "spec_value": o.SpecValue, + "quantity": o.Quantity, + "amount": o.Amount, + "order_status": db.NormalizeOrderStatus(o.OrderStatus), + "status": db.NormalizeOrderStatus(o.OrderStatus), + "cookie_id": o.CookieID, + "is_bargain": o.IsBargain, + "system_shipped": o.SystemShipped, + "receiver_name": o.ReceiverName, + "receiver_phone": o.ReceiverPhone, + "receiver_address": o.ReceiverAddr, + "receiver_city": o.ReceiverCity, + "created_at": o.CreatedAt, + "updated_at": o.UpdatedAt, + }) +} + +func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { + if s.Browser == nil { + writeErr(w, http.StatusServiceUnavailable, "浏览器自动化未启用,无法刷新订单") + return + } + sess := auth.SessionFromContext(r.Context()) + all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询账号失败") + return + } + cookieID := r.FormValue("cookie_id") + status := r.FormValue("status") + if cookieID != "" { + value, ok := all[cookieID] + if !ok { + writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问") + return + } + all = map[string]string{cookieID: value} + } + + type refreshTarget struct { + OrderID string + CurrentStatus string + } + ordersByCookie := map[string][]refreshTarget{} + for cid := range all { + rows, err := s.Store.Orders.ByCookie(r.Context(), cid, 1000) + if err != nil { + continue + } + for _, row := range rows { + currentStatus := db.NormalizeOrderStatus(row.OrderStatus) + if status != "" && status != "all" && currentStatus != status { + continue + } + // 稳定状态无需反复抓取;但历史订单若缺少实付金额,仍需补全详情。 + if isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" { + continue + } + ordersByCookie[cid] = append(ordersByCookie[cid], refreshTarget{ + OrderID: row.OrderID, + CurrentStatus: currentStatus, + }) + } + } + + total := 0 + for _, targets := range ordersByCookie { + total += len(targets) + } + if total == 0 { + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "message": "没有需要刷新的订单", + "summary": map[string]int{"total": 0, "updated": 0, "no_change": 0, "failed": 0}, + "results": []any{}, + }) + return + } + + updated, noChange, failed := 0, 0, 0 + results := []map[string]any{} + for cid, targets := range ordersByCookie { + cookieValue := all[cid] + if cookieValue == "" { + failed += len(targets) + continue + } + orderIDs := make([]string, 0, len(targets)) + currentStatus := make(map[string]string, len(targets)) + for _, target := range targets { + orderIDs = append(orderIDs, target.OrderID) + currentStatus[target.OrderID] = target.CurrentStatus + } + ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute) + batch, err := s.Browser.BatchRefreshOrders(ctx, orderIDs, cid, cookieValue) + cancel() + if err != nil { + failed += len(targets) + results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": err.Error()}) + continue + } + rawOrders, _ := batch["orders"].([]map[string]any) + for _, raw := range rawOrders { + orderID := stringFromAny(raw["order_id"]) + if raw["success"] == false { + failed++ + results = append(results, map[string]any{ + "order_id": orderID, + "success": false, + "error": stringFromAny(raw["error"]), + }) + continue + } + newStatus := db.NormalizeOrderStatus(stringFromAny(raw["order_status"])) + if newStatus == "unknown" { + newStatus = currentStatus[orderID] + } + err := s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{ + CookieID: cid, + OrderStatus: newStatus, + SpecName: stringFromAny(raw["spec_name"]), + SpecValue: stringFromAny(raw["spec_value"]), + Quantity: stringFromAny(raw["quantity"]), + Amount: stringFromAny(raw["amount"]), + }) + if err != nil { + failed++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "error": "更新数据库失败"}) + continue + } + changed := newStatus != "" && newStatus != currentStatus[orderID] + if changed { + updated++ + } else { + noChange++ + } + results = append(results, map[string]any{ + "order_id": orderID, + "success": true, + "old_status": currentStatus[orderID], + "new_status": newStatus, + }) + } + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "message": "订单刷新完成", + "summary": map[string]int{"total": total, "updated": updated, "no_change": noChange, "failed": failed}, + "results": results, + }) +} + +func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { + if s.Browser == nil { + writeErr(w, http.StatusServiceUnavailable, "浏览器自动化未启用,无法刷新订单") + return + } + orderID := chi.URLParam(r, "order_id") + order, err := s.Store.Orders.Get(r.Context(), orderID) + if err != nil { + writeErr(w, http.StatusNotFound, "订单不存在") + return + } + cookieID := order.CookieID + cookieValue, _, ok := s.cookieForCurrentUser(w, r, cookieID) + if !ok { + return + } + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + detail, err := s.Browser.FetchOrderDetail(ctx, orderID, cookieID, cookieValue, s.Store.Items.IsMultiSpec(ctx, cookieID, order.ItemID)) + if err != nil { + writeErr(w, http.StatusBadGateway, err.Error()) + return + } + if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieValue { + _ = s.Store.Cookies.Save(r.Context(), cookieID, detail.UpdatedCookies, 0) + if s.Manager != nil { + if account, running := s.Manager.GetInstance(cookieID); running { + account.UpdateCookie(detail.UpdatedCookies) + } + } + } + status := db.NormalizeOrderStatus(detail.OrderStatus) + if status == "unknown" { + status = db.NormalizeOrderStatus(order.OrderStatus) + } + if err := s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{ + CookieID: cookieID, + OrderStatus: status, + SpecName: detail.SpecName, + SpecValue: detail.SpecValue, + Quantity: detail.Quantity, + Amount: detail.Amount, + }); err != nil { + writeErr(w, http.StatusInternalServerError, "更新订单失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "订单刷新完成", "order": detail}) +} + +// deleteOrder 删除订单。 +func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) { + orderID := chi.URLParam(r, "order_id") + _, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM orders WHERE order_id=?`, orderID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "删除失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// updateOrder 更新订单(手动发货等)。 +func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) { + orderID := chi.URLParam(r, "order_id") + var req struct { + OrderStatus string `json:"order_status"` + Status string `json:"status"` + ItemID string `json:"item_id"` + BuyerID string `json:"buyer_id"` + SpecName string `json:"spec_name"` + SpecValue string `json:"spec_value"` + Quantity any `json:"quantity"` + Amount any `json:"amount"` + ReceiverName string `json:"receiver_name"` + ReceiverPhone string `json:"receiver_phone"` + ReceiverAddress string `json:"receiver_address"` + ReceiverCity string `json:"receiver_city"` + ChatID string `json:"chat_id"` + SystemShipped *bool `json:"system_shipped"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + status := req.OrderStatus + if status == "" { + status = req.Status + } + if err := s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{ + OrderStatus: status, + ItemID: req.ItemID, + BuyerID: req.BuyerID, + SpecName: req.SpecName, + SpecValue: req.SpecValue, + Quantity: stringFromAny(req.Quantity), + Amount: stringFromAny(req.Amount), + ReceiverName: req.ReceiverName, + ReceiverPhone: req.ReceiverPhone, + ReceiverAddr: req.ReceiverAddress, + ReceiverCity: req.ReceiverCity, + ChatID: req.ChatID, + SystemShipped: req.SystemShipped, + }); err != nil { + writeErr(w, http.StatusInternalServerError, "更新失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) { + var req struct { + OrderIDs []string `json:"order_ids"` + ShipMode string `json:"ship_mode"` + CustomContent string `json:"custom_content"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if len(req.OrderIDs) == 0 { + writeErr(w, http.StatusBadRequest, "缺少订单ID") + return + } + if req.ShipMode == "" { + req.ShipMode = "status_only" + } + if req.ShipMode != "status_only" && req.ShipMode != "full_delivery" { + writeErr(w, http.StatusBadRequest, "发货模式必须是 status_only 或 full_delivery") + return + } + + sess := auth.SessionFromContext(r.Context()) + userCookies, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询账号失败") + return + } + + successCount, failedCount := 0, 0 + results := make([]map[string]any, 0, len(req.OrderIDs)) + for _, orderID := range req.OrderIDs { + orderID = strings.TrimSpace(orderID) + if orderID == "" { + continue + } + order, err := s.Store.Orders.Get(r.Context(), orderID) + if err != nil || order == nil { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "订单不存在"}) + continue + } + cookieValue, ok := userCookies[order.CookieID] + if !ok { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "无权操作此订单"}) + continue + } + if req.ShipMode == "full_delivery" { + if s.Manager == nil { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "账号管理器未初始化"}) + continue + } + acc, running := s.Manager.GetInstance(order.CookieID) + if !running { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "该账号未在线运行,无法执行完整发货"}) + continue + } + sent, err := acc.ManualFullDelivery(r.Context(), order) + if err != nil { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": err.Error()}) + continue + } + successCount++ + results = append(results, map[string]any{ + "order_id": orderID, + "success": true, + "message": fmt.Sprintf("完整发货成功,已发送%d条卡券信息给买家", sent), + }) + continue + } + if s.MTop == nil { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "mtop 客户端未初始化"}) + continue + } + ok, ret, updatedCookies, err := s.MTop.ConsignContext(r.Context(), cookieValue, orderID) + if err != nil { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "确认发货异常: " + err.Error()}) + continue + } + if updatedCookies != "" && updatedCookies != cookieValue { + _ = s.Store.Cookies.Save(r.Context(), order.CookieID, updatedCookies, sess.UserID) + if s.Manager != nil { + if acc, running := s.Manager.GetInstance(order.CookieID); running { + acc.UpdateCookie(updatedCookies) + } + } + } + if !ok { + failedCount++ + msg := "确认发货失败" + if len(ret) > 0 { + msg += ": " + strings.Join(ret, "; ") + } + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": msg}) + continue + } + sysShip := true + _ = s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{ + CookieID: order.CookieID, + OrderStatus: "shipped", + SystemShipped: &sysShip, + ItemID: order.ItemID, + BuyerID: order.BuyerID, + ReceiverName: order.ReceiverName, + ReceiverPhone: order.ReceiverPhone, + ReceiverAddr: order.ReceiverAddr, + ReceiverCity: order.ReceiverCity, + ChatID: order.ChatID, + SpecName: order.SpecName, + SpecValue: order.SpecValue, + Quantity: order.Quantity, + Amount: order.Amount, + }) + successCount++ + results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "已成功修改闲鱼发货状态"}) + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": failedCount == 0, + "message": fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount), + "success_count": successCount, + "failed_count": failedCount, + "results": results, + }) +} + +func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) { + orders, err := parseImportedOrders(r) + if err != nil { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + sess := auth.SessionFromContext(r.Context()) + userCookies, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询账号失败") + return + } + defaultCookieID := "" + if len(userCookies) == 1 { + for cid := range userCookies { + defaultCookieID = cid + } + } + + successCount, failedCount := 0, 0 + results := make([]map[string]any, 0, len(orders)) + for _, raw := range orders { + orderID := firstImportString(raw, "order_id") + if orderID == "" { + failedCount++ + results = append(results, map[string]any{"order_id": "unknown", "success": false, "message": "缺少必需字段: order_id"}) + continue + } + cookieID := firstImportString(raw, "cookie_id") + if cookieID == "" { + cookieID = defaultCookieID + } + if cookieID == "" { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "缺少必需字段: cookie_id"}) + continue + } + if _, ok := userCookies[cookieID]; !ok { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "无权操作此账号的订单"}) + continue + } + status := firstImportString(raw, "order_status", "status", "status_text") + if status != "" { + status = db.NormalizeOrderStatus(status) + } + itemID := firstImportString(raw, "item_id") + if err := s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{ + CookieID: cookieID, + ItemID: itemID, + BuyerID: firstImportString(raw, "buyer_id"), + OrderStatus: status, + SpecName: firstImportString(raw, "spec_name"), + SpecValue: firstImportString(raw, "spec_value"), + Quantity: firstImportString(raw, "quantity"), + Amount: firstImportString(raw, "amount"), + ReceiverName: firstImportString(raw, "receiver_name"), + ReceiverPhone: firstImportString(raw, "receiver_phone"), + ReceiverAddr: firstImportString(raw, "receiver_address"), + ReceiverCity: firstImportString(raw, "receiver_city"), + ChatID: firstImportString(raw, "chat_id"), + }); err != nil { + failedCount++ + results = append(results, map[string]any{"order_id": orderID, "success": false, "message": err.Error()}) + continue + } + if itemID != "" { + _ = s.Store.Items.UpsertBasic(r.Context(), &db.ItemInfoRow{ + CookieID: cookieID, + ItemID: itemID, + ItemTitle: firstImportString(raw, "item_title"), + ItemPrice: firstImportString(raw, "item_price"), + ItemDetail: firstImportString(raw, "item_detail", "item_description"), + }) + } + successCount++ + results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "订单已导入"}) + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "message": fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount), + "total": len(orders), + "success_count": successCount, + "failed_count": failedCount, + "results": results, + }) +} + +func atoiDefault(s string, def int) int { + if s == "" { + return def + } + n, err := strconv.Atoi(s) + if err != nil { + return def + } + return n +} + +func isStableOrderStatus(status string) bool { + switch status { + case "shipped", "completed", "cancelled": + return true + default: + return false + } +} + +func stringFromAny(v any) string { + switch x := v.(type) { + case nil: + return "" + case string: + return x + case fmt.Stringer: + return x.String() + case float64: + if x == float64(int64(x)) { + return strconv.FormatInt(int64(x), 10) + } + return strconv.FormatFloat(x, 'f', -1, 64) + case int: + return strconv.Itoa(x) + case int64: + return strconv.FormatInt(x, 10) + case bool: + return strconv.FormatBool(x) + default: + return fmt.Sprint(x) + } +} + +func parseImportedOrders(r *http.Request) ([]map[string]any, error) { + ct := r.Header.Get("Content-Type") + if strings.HasPrefix(ct, "multipart/form-data") { + if err := r.ParseMultipartForm(32 << 20); err != nil { + return nil, fmt.Errorf("解析上传文件失败: %w", err) + } + file, header, err := r.FormFile("file") + if err != nil { + return nil, fmt.Errorf("缺少上传文件") + } + defer file.Close() + raw, err := io.ReadAll(file) + if err != nil { + return nil, fmt.Errorf("读取上传文件失败: %w", err) + } + return parseImportedOrderBytes(raw, header.Filename) + } + raw, err := io.ReadAll(r.Body) + if err != nil { + return nil, fmt.Errorf("读取请求失败: %w", err) + } + return parseImportedOrderBytes(raw, "orders.json") +} + +func parseImportedOrderBytes(raw []byte, filename string) ([]map[string]any, error) { + if len(bytes.TrimSpace(raw)) == 0 { + return nil, fmt.Errorf("导入内容为空") + } + switch strings.ToLower(filepath.Ext(filename)) { + case ".xlsx": + return parseXLSXOrders(raw) + case ".csv": + return parseDelimitedOrders(raw, ',') + case ".tsv": + return parseDelimitedOrders(raw, '\t') + case ".xls": + return nil, fmt.Errorf("暂不支持旧版 .xls,请另存为 .xlsx 或 CSV 后导入") + default: + if bytes.HasPrefix(bytes.TrimSpace(raw), []byte("[")) || bytes.HasPrefix(bytes.TrimSpace(raw), []byte("{")) { + return parseJSONOrders(raw) + } + return parseDelimitedOrders(raw, ',') + } +} + +func parseJSONOrders(raw []byte) ([]map[string]any, error) { + var arr []map[string]any + if err := json.Unmarshal(raw, &arr); err == nil { + return normalizeImportOrderMaps(arr), nil + } + var single map[string]any + if err := json.Unmarshal(raw, &single); err != nil { + return nil, fmt.Errorf("解析 JSON 失败: %w", err) + } + return normalizeImportOrderMaps([]map[string]any{single}), nil +} + +func parseDelimitedOrders(raw []byte, comma rune) ([]map[string]any, error) { + reader := csv.NewReader(bytes.NewReader(raw)) + reader.Comma = comma + reader.FieldsPerRecord = -1 + reader.LazyQuotes = true + records, err := reader.ReadAll() + if err != nil { + return nil, fmt.Errorf("解析表格失败: %w", err) + } + if len(records) < 2 { + return nil, fmt.Errorf("表格至少需要表头和一行数据") + } + headers := normalizeImportHeaders(records[0]) + out := make([]map[string]any, 0, len(records)-1) + for _, row := range records[1:] { + m := make(map[string]any) + nonEmpty := false + for i, h := range headers { + if h == "" || i >= len(row) { + continue + } + v := strings.TrimSpace(row[i]) + if v != "" { + nonEmpty = true + } + m[h] = v + } + if nonEmpty { + out = append(out, m) + } + } + return out, nil +} + +func parseXLSXOrders(raw []byte) ([]map[string]any, error) { + zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + return nil, fmt.Errorf("解析 xlsx 失败: %w", err) + } + shared := xlsxSharedStrings(zr) + var sheet *zip.File + for _, f := range zr.File { + if strings.HasPrefix(f.Name, "xl/worksheets/sheet") && strings.HasSuffix(f.Name, ".xml") { + sheet = f + break + } + } + if sheet == nil { + return nil, fmt.Errorf("xlsx 中未找到工作表") + } + rc, err := sheet.Open() + if err != nil { + return nil, err + } + defer rc.Close() + var ws xlsxWorksheet + if err := xml.NewDecoder(rc).Decode(&ws); err != nil { + return nil, fmt.Errorf("解析工作表失败: %w", err) + } + rows := make([][]string, 0, len(ws.SheetData.Rows)) + for _, row := range ws.SheetData.Rows { + values := []string{} + for _, cell := range row.Cells { + idx := xlsxCellIndex(cell.Ref) + for len(values) <= idx { + values = append(values, "") + } + values[idx] = xlsxCellValue(cell, shared) + } + rows = append(rows, values) + } + if len(rows) < 2 { + return nil, fmt.Errorf("xlsx 至少需要表头和一行数据") + } + headers := normalizeImportHeaders(rows[0]) + out := make([]map[string]any, 0, len(rows)-1) + for _, row := range rows[1:] { + m := make(map[string]any) + nonEmpty := false + for i, h := range headers { + if h == "" || i >= len(row) { + continue + } + v := strings.TrimSpace(row[i]) + if v != "" { + nonEmpty = true + } + m[h] = v + } + if nonEmpty { + out = append(out, m) + } + } + return out, nil +} + +type xlsxWorksheet struct { + SheetData struct { + Rows []xlsxRow `xml:"row"` + } `xml:"sheetData"` +} + +type xlsxRow struct { + Cells []xlsxCell `xml:"c"` +} + +type xlsxCell struct { + Ref string `xml:"r,attr"` + Type string `xml:"t,attr"` + Value string `xml:"v"` + InlineStr string `xml:"is>t"` +} + +type xlsxSST struct { + Items []struct { + Inner string `xml:",innerxml"` + } `xml:"si"` +} + +func xlsxSharedStrings(zr *zip.Reader) []string { + for _, f := range zr.File { + if f.Name != "xl/sharedStrings.xml" { + continue + } + rc, err := f.Open() + if err != nil { + return nil + } + defer rc.Close() + var sst xlsxSST + if err := xml.NewDecoder(rc).Decode(&sst); err != nil { + return nil + } + out := make([]string, 0, len(sst.Items)) + for _, item := range sst.Items { + out = append(out, xmlCharData(item.Inner)) + } + return out + } + return nil +} + +func xlsxCellValue(cell xlsxCell, shared []string) string { + switch cell.Type { + case "s": + idx, _ := strconv.Atoi(strings.TrimSpace(cell.Value)) + if idx >= 0 && idx < len(shared) { + return shared[idx] + } + case "inlineStr": + return strings.TrimSpace(cell.InlineStr) + } + return strings.TrimSpace(cell.Value) +} + +func xlsxCellIndex(ref string) int { + idx := 0 + for _, r := range ref { + if r < 'A' || r > 'Z' { + break + } + idx = idx*26 + int(r-'A'+1) + } + if idx == 0 { + return 0 + } + return idx - 1 +} + +func xmlCharData(inner string) string { + dec := xml.NewDecoder(strings.NewReader("" + inner + "")) + var parts []string + for { + tok, err := dec.Token() + if err != nil { + break + } + if data, ok := tok.(xml.CharData); ok { + parts = append(parts, string(data)) + } + } + return strings.TrimSpace(strings.Join(parts, "")) +} + +func normalizeImportOrderMaps(in []map[string]any) []map[string]any { + out := make([]map[string]any, 0, len(in)) + for _, raw := range in { + m := make(map[string]any) + for k, v := range raw { + m[normalizeImportHeader(k)] = v + } + out = append(out, m) + } + return out +} + +func normalizeImportHeaders(headers []string) []string { + out := make([]string, len(headers)) + for i, h := range headers { + out[i] = normalizeImportHeader(h) + } + return out +} + +func normalizeImportHeader(header string) string { + h := strings.ToLower(strings.TrimSpace(header)) + h = strings.NewReplacer(" ", "", "_", "", "-", "", "(", "(", ")", ")").Replace(h) + switch h { + case "orderid", "订单号", "订单id", "订单编号": + return "order_id" + case "cookieid", "账号id", "账号", "闲鱼账号": + return "cookie_id" + case "itemid", "商品id", "商品编号": + return "item_id" + case "itemtitle", "商品标题", "商品名称": + return "item_title" + case "itemprice", "商品价格": + return "item_price" + case "itemdetail", "itemdescription", "商品描述", "商品详情": + return "item_detail" + case "buyerid", "买家id": + return "buyer_id" + case "status", "orderstatus", "订单状态", "状态": + return "status" + case "specname", "规格名": + return "spec_name" + case "specvalue", "规格值": + return "spec_value" + case "quantity", "数量": + return "quantity" + case "amount", "金额", "订单金额": + return "amount" + case "receivername", "收件人", "收货人": + return "receiver_name" + case "receiverphone", "手机号", "收件电话", "收货电话": + return "receiver_phone" + case "receiveraddress", "地址", "收件地址", "收货地址": + return "receiver_address" + case "receivercity", "城市", "收件城市", "收货城市": + return "receiver_city" + case "chatid", "会话id": + return "chat_id" + default: + return header + } +} + +func firstImportString(m map[string]any, keys ...string) string { + for _, k := range keys { + if v, ok := m[k]; ok { + s := strings.TrimSpace(stringFromAny(v)) + if s != "" { + return s + } + } + } + return "" +} diff --git a/internal/server/qrlogin_handlers.go b/internal/server/qrlogin_handlers.go new file mode 100644 index 0000000..05d9f13 --- /dev/null +++ b/internal/server/qrlogin_handlers.go @@ -0,0 +1,66 @@ +package server + +import ( + "net/http" + + "github.com/go-chi/chi/v5" +) + +// mountQRLoginReal 扫码登录端点(纯 HTTP,不需要浏览器)。 +func (s *Server) mountQRLoginReal(r chi.Router) { + r.Post("/qr-login/generate", s.generateQRLogin) + r.Get("/qr-login/check/{session_id}", s.checkQRLoginStatus) + r.Post("/qr-login/complete-verification/{session_id}", s.completeQRVerification) +} + +// generateQRLogin 生成扫码登录二维码。 +func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) { + sessionID, qrCodeURL, err := s.QRLogin.GenerateQRCode(r.Context()) + if err != nil { + s.Logger.Error("生成二维码失败", "err", err) + writeJSON(w, http.StatusOK, map[string]any{ + "success": false, + "message": "生成二维码失败: " + err.Error(), + }) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "session_id": sessionID, + "qr_code_url": qrCodeURL, + }) +} + +// checkQRLoginStatus 检查扫码登录状态。 +func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) { + sessionID := chi.URLParam(r, "session_id") + if sessionID == "" { + writeErr(w, http.StatusBadRequest, "缺少 session_id") + return + } + result := s.QRLogin.GetSessionStatus(sessionID) + writeJSON(w, http.StatusOK, result) +} + +// completeQRVerification 用户完成风控验证后调用,提取真实 cookie 并入库。 +func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) { + sessionID := chi.URLParam(r, "session_id") + if sessionID == "" { + writeErr(w, http.StatusBadRequest, "缺少 session_id") + return + } + cookies, unb, err := s.QRLogin.CompleteVerification(r.Context(), sessionID) + if err != nil { + s.Logger.Error("验证完成处理失败", "err", err) + writeJSON(w, http.StatusOK, map[string]any{ + "success": false, + "message": err.Error(), + }) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "success": true, + "cookies": cookies, + "unb": unb, + }) +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..b8264b4 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,303 @@ +// Package server 实现 HTTP API 服务(chi 路由),移植自 Python reply_server.py 的 ~115 端点。 +// 复用 internal/auth 中间件、internal/db.Store、internal/account.Manager。 +// 端点按分组组织在同一 package 的多个 handler 文件中。 +package server + +import ( + "bytes" + "context" + "io/fs" + "log/slog" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + + "xianyu-go/internal/account" + "xianyu-go/internal/auth" + "xianyu-go/internal/browser" + "xianyu-go/internal/db" + "xianyu-go/internal/webui" + "xianyu-go/internal/xianyu/mtop" + "xianyu-go/internal/xianyu/qrlogin" +) + +// Server 聚合 HTTP 服务依赖。 +type Server struct { + Store *db.Store + Auth *auth.Service + Manager *account.Manager + Browser *browser.Manager + MTop *mtop.Client + QRLogin *qrlogin.Manager + Logger *slog.Logger + WebDir string // 前端静态资源目录(含 index.html) + Addr string +} + +// New 构造。bm 为浏览器管理器(风控验证后用浏览器提取 cookie;为 nil 则禁用浏览器自动化)。 +func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure bool, webDir, addr string, logger *slog.Logger) *Server { + if logger == nil { + logger = slog.New(slog.NewTextHandler(os.Stdout, nil)) + } + qrMgr := qrlogin.NewManager(logger) + if bm != nil { + qrMgr.SetSidecarRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) { + return bm.QRCookieRefresh(ctx, tmpCookies, verificationURL, onScreenshot) + }) + } + return &Server{ + Store: store, + Auth: &auth.Service{Store: store, Logger: logger, Secure: secure}, + Manager: manager, + Browser: bm, + MTop: &mtop.Client{}, + QRLogin: qrMgr, + Logger: logger, + WebDir: webDir, + Addr: addr, + } +} + +// Router 构建完整路由树。 +func (s *Server) Router() http.Handler { + r := chi.NewRouter() + r.Use(middleware.RealIP) + r.Use(middleware.RequestID) + r.Use(middleware.Recoverer) + // 请求日志(精简)。 + r.Use(s.requestLogger) + + // 健康检查(无需认证)。 + r.Get("/health", s.health) + + // 认证组(无需登录的端点,但解析会话以判断登录态)。 + r.Group(func(r chi.Router) { + r.Use(s.Auth.Middleware) // 解析 session,不强制登录 + r.Post("/login", s.login) + r.Get("/verify", s.verify) + r.Post("/logout", s.logout) + }) + r.Post("/change-admin-password", s.authMiddleware(http.HandlerFunc(s.changeAdminPassword)).ServeHTTP) + r.Post("/change-password", s.authMiddleware(http.HandlerFunc(s.changePassword)).ServeHTTP) + + // 认证后的 API。 + r.Group(func(r chi.Router) { + r.Use(s.Auth.Middleware) + r.Use(auth.RequireAuth) + r.Put("/account/credentials", s.updateCredentials) + + // 账号 cookie + s.mountCookies(r) + // 扫码登录 + s.mountQRLoginReal(r) + // 订单 + s.mountOrdersReal(r) + // 订单分析(仪表盘) + s.mountAnalyticsReal(r) + // 卡密 + 发货规则 + s.mountCardsReal(r) + // 商品 + s.mountItemsReal(r) + // 关键字 + 指定商品回复 + s.mountKeywordsReal(r) + s.mountItemRepliesReal(r) + // 默认回复 + s.mountDefaultRepliesReal(r) + // 通知 + s.mountNotificationsReal(r) + // 系统设置(已认证) + s.mountSettings(r) + // AI 设置 + s.mountAIReply(r) + // 用户 + s.mountUser(r) + + // 管理员专用。 + r.Group(func(r chi.Router) { + r.Use(auth.RequireAdmin) + s.mountAdmin(r) + }) + }) + + // 公开系统设置(无需登录,前端登录页读取主题等)。 + s.mountPublicSettings(r) + + // SPA 静态资源 catch-all(最后挂载)。 + s.mountSPA(r) + return r +} + +// mountPublicSettings 公开系统设置(无需登录)。 +func (s *Server) mountPublicSettings(r chi.Router) { + r.Get("/system-settings/public", s.publicSettings) +} + +// authMiddleware 仅对单个 handler 应用会话解析 + RequireAuth。 +func (s *Server) authMiddleware(h http.Handler) http.Handler { + return s.Auth.Middleware(auth.RequireAuth(h)) +} + +// requestLogger 记录请求完成状态、耗时和 chi request_id。 +func (s *Server) requestLogger(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) + next.ServeHTTP(ww, r) + status := ww.Status() + if status == 0 { + status = http.StatusOK + } + + level := slog.LevelDebug + if status >= 500 { + level = slog.LevelError + } else if status >= 400 { + level = slog.LevelWarn + } + s.Logger.LogAttrs(r.Context(), level, "HTTP 请求完成", + slog.String("method", r.Method), + slog.String("path", r.URL.Path), + slog.Int("status", status), + slog.Int("bytes", ww.BytesWritten()), + slog.Duration("duration", time.Since(start)), + slog.String("request_id", middleware.GetReqID(r.Context())), + slog.String("remote", r.RemoteAddr), + ) + }) +} + +// mountSPA 挂载前端静态资源与 SPA catch-all。 +// +// 前端 vite base 为 /static/,构建后 index.html 引用 /static/assets/...、/static/favicon.svg。 +// 故静态资源统一从 /static/ 前缀提供;非 API 的 GET 请求(/、/login 等客户端路由) +// 返回 /static/index.html,交给 React Router 接管。 +func (s *Server) mountSPA(r chi.Router) { + if s.WebDir != "" { + s.mountDirSPA(r) + return + } + embedded, err := webui.Static() + if err != nil { + return + } + s.mountFSSPA(r, embedded) +} + +func (s *Server) mountDirSPA(r chi.Router) { + indexFile := filepath.Join(s.WebDir, "index.html") + // /static/* 直接作为静态文件服务(assets/、favicon.svg 等)。 + // StripPrefix("/static/") 后,URL /static/assets/x.js → WebDir/assets/x.js。 + staticFiles := http.StripPrefix("/static/", http.FileServer(http.Dir(s.WebDir))) + r.Handle("/static/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/static/" || r.URL.Path == "/static/index.html" { + setNoStore(w) + } + staticFiles.ServeHTTP(w, r) + })) + + // SPA catch-all:非 API 的 GET 请求返回 index.html。 + r.Get("/*", func(w http.ResponseWriter, r *http.Request) { + if isAPIPath(r.URL.Path) { + writeJSON(w, http.StatusNotFound, errDetail("接口不存在")) + return + } + if _, err := os.Stat(indexFile); err != nil { + writeJSON(w, http.StatusNotFound, errDetail("前端未构建")) + return + } + setNoStore(w) + http.ServeFile(w, r, indexFile) + }) +} + +func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) { + staticFiles := http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))) + r.Handle("/static/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/static/" || r.URL.Path == "/static/index.html" { + setNoStore(w) + } + staticFiles.ServeHTTP(w, r) + })) + + r.Get("/*", func(w http.ResponseWriter, r *http.Request) { + if isAPIPath(r.URL.Path) { + writeJSON(w, http.StatusNotFound, errDetail("接口不存在")) + return + } + index, err := fs.ReadFile(staticFS, "index.html") + if err != nil { + writeJSON(w, http.StatusNotFound, errDetail("前端未构建")) + return + } + setNoStore(w) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + http.ServeContent(w, r, "index.html", time.Time{}, bytes.NewReader(index)) + }) +} + +func setNoStore(w http.ResponseWriter) { + w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Expires", "0") +} + +// isAPIPath 判断是否为 API 路径(不应被 SPA 拦截)。 +// 覆盖前端 vite proxy 列表中的所有后端前缀。 +func isAPIPath(path string) bool { + apiPrefixes := []string{ + "/api/", "/admin/", "/health", "/login", "/logout", "/verify", + "/change-password", "/change-admin-password", "/account/", + "/cookies", "/cookie/", "/orders", "/analytics", + "/cards", "/delivery-rules", "/items", "/keywords", "/default-replies", "/default-reply", + "/notification-channels", "/message-notifications", + "/system-settings", "/ai-reply", "/ai-reply-settings", + "/ai-models", + "/user-settings", "/logs", "/risk-control", + "/item-reply", "/itemReplays", + "/register", "/registration-status", "/login-info-status", + "/qr-login", "/password-login", "/face-verification", + "/generate-captcha", "/verify-captcha", "/geetest", "/send-verification-code", + "/backup", "/upload-image", "/send-message", "/xianyu", + "/static/", // 静态资源(由 /static/* handler 处理,不进 catch-all) + } + for _, p := range apiPrefixes { + if strings.HasPrefix(path, p) { + return true + } + } + return false +} + +// health 健康检查。 +func (s *Server) health(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"status": "ok"}) +} + +// 占位:各分组 mount 方法在 handlers 文件中实现。 +// 为避免大文件,mount* 方法分文件定义但属于 Server。 + +// Run 启动 HTTP 服务(阻塞)。 +func (s *Server) Run(ctx context.Context) error { + srv := &http.Server{ + Addr: s.Addr, + Handler: s.Router(), + } + go func() { + <-ctx.Done() + shCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := srv.Shutdown(shCtx); err != nil { + s.Logger.Warn("HTTP 服务关闭异常", "err", err) + } + }() + s.Logger.Info("HTTP 服务启动", "addr", s.Addr) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + return err + } + return nil +} diff --git a/internal/server/server_test.go b/internal/server/server_test.go new file mode 100644 index 0000000..64035f2 --- /dev/null +++ b/internal/server/server_test.go @@ -0,0 +1,311 @@ +package server + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "xianyu-go/internal/account" + "xianyu-go/internal/db" + "xianyu-go/internal/engine" +) + +func newTestServer(t *testing.T) (*Server, *db.Store, func()) { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "test.db") + d, err := db.Open(context.Background(), dbPath) + if err != nil { + t.Fatalf("Open: %v", err) + } + store := db.NewStore(d) + store.Users.Create(context.Background(), "admin", "a@e.com", "pw") + store.Users.SetAdmin(context.Background(), "admin") + // 一个账号。 + admin, _ := store.Users.GetByUsername(context.Background(), "admin") + store.Cookies.Save(context.Background(), "acc1", "unb=123; _m_h5_tk=tk1_1;", admin.ID) + + mgr := account.NewManager(store, noopHandler{}, nil) + srv := New(store, mgr, nil, false, "", ":0", nil) + srv.MTop.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader( + `{"ret":["SUCCESS::调用成功"],"data":{"module":{"base":{"displayName":"测试账号","avatar":"https://img.alicdn.com/test-avatar.jpg"}}}}`, + )), + Request: req, + }, nil + })} + return srv, store, func() { d.Close() } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +type noopHandler struct{} + +func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil } +func (noopHandler) HandleSystemMessage(context.Context, engine.SystemMessage) error { return nil } +func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false } + +// TestLoginVerifyLogout 登录→verify→登出 全链路。 +func TestLoginVerifyLogout(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + // 1) 登录(用户名密码)。 + body := `{"username":"admin","password":"pw"}` + req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body)) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String()) + } + var lr loginResponse + json.Unmarshal(rec.Body.Bytes(), &lr) + if !lr.Success || !lr.IsAdmin { + t.Fatalf("登录响应异常: %+v", lr) + } + cookie := rec.Result().Cookies()[0] + if cookie.Name != "session" || cookie.Value == "" || !cookie.HttpOnly { + t.Fatalf("Cookie 异常: %+v", cookie) + } + + // 2) verify 带 cookie 应 authenticated。 + req2 := httptest.NewRequest(http.MethodGet, "/verify", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + var v map[string]any + json.Unmarshal(rec2.Body.Bytes(), &v) + if v["authenticated"] != true || v["initialized"] != true { + t.Fatalf("verify 异常: %+v", v) + } + + // 3) 无 cookie verify 应未认证。 + req3 := httptest.NewRequest(http.MethodGet, "/verify", nil) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + json.Unmarshal(rec3.Body.Bytes(), &v) + if v["authenticated"] == true { + t.Fatal("无 cookie 应未认证") + } + + // 4) 登出。 + req4 := httptest.NewRequest(http.MethodPost, "/logout", nil) + req4.AddCookie(cookie) + rec4 := httptest.NewRecorder() + h.ServeHTTP(rec4, req4) + // 登出后 cookie 应被清除(MaxAge=-1)。 + dc := rec4.Result().Cookies() + cleared := false + for _, c := range dc { + if c.Name == "session" && c.MaxAge < 0 { + cleared = true + } + } + if !cleared { + t.Fatal("登出应清除 cookie") + } +} + +// TestLoginWrongPassword 错误密码。 +func TestLoginWrongPassword(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + body := `{"username":"admin","password":"wrong"}` + req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body)) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + var lr loginResponse + json.Unmarshal(rec.Body.Bytes(), &lr) + if lr.Success { + t.Fatal("错误密码不应成功") + } +} + +func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`)) + loginRec := httptest.NewRecorder() + h.ServeHTTP(loginRec, loginReq) + sessionCookie := loginRec.Result().Cookies()[0] + + updateReq := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader( + `{"current_password":"pw","new_username":"operator","new_password":"newpassword"}`, + )) + updateReq.AddCookie(sessionCookie) + updateRec := httptest.NewRecorder() + h.ServeHTTP(updateRec, updateReq) + if updateRec.Code != http.StatusOK { + t.Fatalf("update status=%d body=%s", updateRec.Code, updateRec.Body.String()) + } + var updateResult map[string]any + json.Unmarshal(updateRec.Body.Bytes(), &updateResult) + if updateResult["success"] != true || updateResult["requires_relogin"] != true { + t.Fatalf("update result=%+v", updateResult) + } + + verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil) + verifyReq.AddCookie(sessionCookie) + verifyRec := httptest.NewRecorder() + h.ServeHTTP(verifyRec, verifyReq) + var verifyResult map[string]any + json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult) + if verifyResult["authenticated"] == true || verifyResult["initialized"] != true { + t.Fatalf("旧会话应失效且系统仍已初始化: %+v", verifyResult) + } + + oldLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`)) + oldLoginRec := httptest.NewRecorder() + h.ServeHTTP(oldLoginRec, oldLoginReq) + var oldLogin loginResponse + json.Unmarshal(oldLoginRec.Body.Bytes(), &oldLogin) + if oldLogin.Success { + t.Fatal("旧用户名不应继续登录") + } + + newLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"operator","password":"newpassword"}`)) + newLoginRec := httptest.NewRecorder() + h.ServeHTTP(newLoginRec, newLoginReq) + var newLogin loginResponse + json.Unmarshal(newLoginRec.Body.Bytes(), &newLogin) + if !newLogin.Success { + t.Fatalf("新凭据登录失败: %s", newLoginRec.Body.String()) + } +} + +// TestCookiesDetailsRequiresAuth 未登录访问受保护端点应 401。 +func TestCookiesDetailsRequiresAuth(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("未登录应 401,got %d", rec.Code) + } +} + +// TestCookiesDetailsWithAuth 登录后能取账号详情。 +func TestCookiesDetailsWithAuth(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + // 登录拿 cookie。 + body := `{"username":"admin","password":"pw"}` + req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body)) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + cookie := rec.Result().Cookies()[0] + + // 取详情。 + req2 := httptest.NewRequest(http.MethodGet, "/cookies/details", nil) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("status=%d body=%s", rec2.Code, rec2.Body.String()) + } + var arr []map[string]any + json.Unmarshal(rec2.Body.Bytes(), &arr) + if len(arr) != 1 || arr[0]["id"] != "acc1" { + t.Fatalf("账号详情异常: %+v", arr) + } + // 不应返回 cookie 明文(安全基线)。 + if _, has := arr[0]["value"]; has { + t.Fatal("不应返回 cookie 明文") + } + if arr[0]["has_cookie"] != true { + t.Fatal("应 has_cookie=true") + } +} + +func TestCookieRuntimeStatusWithAuth(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`)) + loginRec := httptest.NewRecorder() + h.ServeHTTP(loginRec, loginReq) + cookie := loginRec.Result().Cookies()[0] + + req := httptest.NewRequest(http.MethodGet, "/cookies/runtime-status", nil) + req.AddCookie(cookie) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } + var statuses map[string]engine.RuntimeStatus + if err := json.Unmarshal(rec.Body.Bytes(), &statuses); err != nil { + t.Fatal(err) + } + if statuses["acc1"].State != engine.RuntimeError { + t.Fatalf("未启动账号应返回 error,got %+v", statuses["acc1"]) + } +} + +// TestAddAndDeleteCookie 添加/删除账号。 +func TestAddAndDeleteCookie(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + body := `{"username":"admin","password":"pw"}` + req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body)) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + cookie := rec.Result().Cookies()[0] + + // 添加。 + addBody := `{"id":"acc2","value":"unb=456; _m_h5_tk=tk2_2;"}` + req2 := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(addBody)) + req2.AddCookie(cookie) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("add status=%d body=%s", rec2.Code, rec2.Body.String()) + } + + // 删除。 + req3 := httptest.NewRequest(http.MethodDelete, "/cookies/acc2", nil) + req3.AddCookie(cookie) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + if rec3.Code != 200 { + t.Fatalf("delete status=%d body=%s", rec3.Code, rec3.Body.String()) + } +} + +// TestHealth 健康检查无需认证。 +func TestHealth(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + h := srv.Router() + + req := httptest.NewRequest(http.MethodGet, "/health", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("health status=%d", rec.Code) + } +} diff --git a/internal/server/settings_handlers.go b/internal/server/settings_handlers.go new file mode 100644 index 0000000..5971a04 --- /dev/null +++ b/internal/server/settings_handlers.go @@ -0,0 +1,337 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/go-chi/chi/v5" + + "xianyu-go/internal/auth" + "xianyu-go/internal/db" +) + +// authSess 从上下文取会话。 +func authSess(r *http.Request) *db.Session { + return auth.SessionFromContext(r.Context()) +} + +// mountSettingsReal 系统设置端点(已认证)。public 单独挂载在顶层。 +func (s *Server) mountSettingsReal(r chi.Router) { + r.Get("/system-settings", s.allSettings) + r.Put("/system-settings/{key}", s.setSetting) + r.Post("/ai-models", s.listAIModels) +} + +func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) { + m, err := s.Store.Settings.Public(r.Context()) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + writeJSON(w, http.StatusOK, m) +} + +func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) { + m, err := s.Store.Settings.All(r.Context()) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + writeJSON(w, http.StatusOK, m) +} + +func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) { + key := chi.URLParam(r, "key") + var req struct { + Value string `json:"value"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + if err := s.Store.Settings.Set(r.Context(), key, req.Value); err != nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +// ---- AI 回复设置 ---- + +func (s *Server) mountAIReplyReal(r chi.Router) { + r.Get("/ai-reply-settings", s.listAIReply) + r.Get("/ai-reply-settings/{cookie_id}", s.getAIReply) + r.Put("/ai-reply-settings/{cookie_id}", s.setAIReply) +} + +func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) { + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT cookie_id, ai_enabled, max_discount_percent, max_discount_amount, + max_bargain_rounds, COALESCE(custom_prompts, '') + FROM ai_reply_settings`) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + + result := make(map[string]any) + for rows.Next() { + var cookieID, customPrompts string + var enabled, maxDiscountPercent, maxDiscountAmount, maxBargainRounds int + if err := rows.Scan(&cookieID, &enabled, &maxDiscountPercent, &maxDiscountAmount, &maxBargainRounds, &customPrompts); err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + result[cookieID] = map[string]any{ + "cookie_id": cookieID, + "ai_enabled": enabled != 0, + "max_discount_percent": maxDiscountPercent, + "max_discount_amount": maxDiscountAmount, + "max_bargain_rounds": maxBargainRounds, + "custom_prompts": customPrompts, + } + } + writeJSON(w, http.StatusOK, result) +} + +func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + cfg, err := s.Store.AIReply.Get(r.Context(), cid) + if err != nil { + writeJSON(w, http.StatusOK, map[string]any{ + "ai_enabled": false, + "max_discount_percent": 10, + "max_discount_amount": 100, + "max_bargain_rounds": 3, + "custom_prompts": "", + }) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "cookie_id": cfg.CookieID, + "ai_enabled": cfg.AIEnabled, + "max_discount_percent": cfg.MaxDiscountPercent, + "max_discount_amount": cfg.MaxDiscountAmount, + "max_bargain_rounds": cfg.MaxBargainRounds, + "custom_prompts": cfg.CustomPrompts, + }) +} + +func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) { + cid := chi.URLParam(r, "cookie_id") + var req struct { + AIEnabled bool `json:"ai_enabled"` + MaxDiscountPercent int `json:"max_discount_percent"` + MaxDiscountAmount int `json:"max_discount_amount"` + MaxBargainRounds int `json:"max_bargain_rounds"` + CustomPrompts string `json:"custom_prompts"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + _, err := s.Store.DB.ExecContext(r.Context(), + `INSERT INTO ai_reply_settings + (cookie_id, ai_enabled, max_discount_percent, max_discount_amount, + max_bargain_rounds, custom_prompts, updated_at) + VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP) + ON CONFLICT(cookie_id) DO UPDATE SET + ai_enabled=excluded.ai_enabled, + max_discount_percent=excluded.max_discount_percent, + max_discount_amount=excluded.max_discount_amount, + max_bargain_rounds=excluded.max_bargain_rounds, + custom_prompts=excluded.custom_prompts, + updated_at=CURRENT_TIMESTAMP`, + cid, btoi(req.AIEnabled), req.MaxDiscountPercent, req.MaxDiscountAmount, + req.MaxBargainRounds, nullIfEmpty(req.CustomPrompts)) + if err != nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} + +func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) { + var req struct { + BaseURL string `json:"base_url"` + APIKey string `json:"api_key"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + baseURL := strings.TrimSpace(req.BaseURL) + if baseURL == "" { + v, err := s.Store.Settings.Get(r.Context(), "ai_api_url") + if err != nil { + writeErr(w, http.StatusInternalServerError, "读取AI地址失败") + return + } + baseURL = v + } + if baseURL == "" { + baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1" + } + apiKey := strings.TrimSpace(req.APIKey) + if apiKey == "" { + v, err := s.Store.Settings.Get(r.Context(), "ai_api_key") + if err != nil { + writeErr(w, http.StatusInternalServerError, "读取AI Key失败") + return + } + apiKey = v + } + + models, err := fetchOpenAIModels(r.Context(), baseURL, apiKey) + if err != nil { + writeErr(w, http.StatusBadGateway, err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"models": models}) +} + +func fetchOpenAIModels(ctx context.Context, baseURL, apiKey string) ([]string, error) { + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + if baseURL == "" { + return nil, fmt.Errorf("AI API 地址为空") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/models", nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + if strings.TrimSpace(apiKey) != "" { + req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(apiKey)) + } + client := &http.Client{Timeout: 20 * time.Second} + resp, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("读取模型失败: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("读取模型失败: HTTP %d %s", resp.StatusCode, truncate(string(raw), 180)) + } + models, err := parseOpenAIModels(raw) + if err != nil { + return nil, err + } + if len(models) == 0 { + return nil, fmt.Errorf("模型列表为空") + } + return models, nil +} + +func parseOpenAIModels(raw []byte) ([]string, error) { + var payload any + if err := json.Unmarshal(raw, &payload); err != nil { + return nil, fmt.Errorf("解析模型列表失败: %w", err) + } + seen := make(map[string]bool) + var out []string + add := func(v string) { + v = strings.TrimSpace(v) + if v == "" || seen[v] { + return + } + seen[v] = true + out = append(out, v) + } + var walk func(any) + walk = func(v any) { + switch x := v.(type) { + case []any: + for _, item := range x { + walk(item) + } + case map[string]any: + if id, _ := x["id"].(string); id != "" { + add(id) + } else if name, _ := x["name"].(string); name != "" { + add(name) + } + case string: + add(x) + } + } + if root, ok := payload.(map[string]any); ok { + if data, ok := root["data"]; ok { + walk(data) + } else if models, ok := root["models"]; ok { + walk(models) + } + } else { + walk(payload) + } + return out, nil +} + +// ---- 用户设置 ---- + +func (s *Server) mountUserReal(r chi.Router) { + r.Get("/user-settings", s.listUserSettings) + r.Put("/user-settings/{key}", s.setUserSetting) + r.Get("/user-settings/{key}", s.getUserSetting) +} + +func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + rows, err := s.Store.DB.QueryContext(r.Context(), + `SELECT key, value FROM user_settings WHERE user_id=?`, sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询失败") + return + } + defer rows.Close() + m := make(map[string]string) + for rows.Next() { + var k, v string + if rows.Scan(&k, &v) == nil { + m[k] = v + } + } + writeJSON(w, http.StatusOK, m) +} + +func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + key := chi.URLParam(r, "key") + var v string + err := s.Store.DB.QueryRowContext(r.Context(), + `SELECT value FROM user_settings WHERE user_id=? AND key=?`, sess.UserID, key).Scan(&v) + if err != nil { + writeJSON(w, http.StatusOK, map[string]any{"value": ""}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"value": v}) +} + +func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) { + sess := authSess(r) + key := chi.URLParam(r, "key") + var req struct { + Value string `json:"value"` + } + if err := decodeJSON(r, &req); err != nil { + writeErr(w, http.StatusBadRequest, "请求格式错误") + return + } + _, err := s.Store.DB.ExecContext(r.Context(), + `INSERT OR REPLACE INTO user_settings (user_id, key, value, updated_at) VALUES (?,?,?,CURRENT_TIMESTAMP)`, + sess.UserID, key, req.Value) + if err != nil { + writeErr(w, http.StatusInternalServerError, "保存失败") + return + } + writeJSON(w, http.StatusOK, map[string]any{"success": true}) +} diff --git a/internal/server/spa_test.go b/internal/server/spa_test.go new file mode 100644 index 0000000..3148998 --- /dev/null +++ b/internal/server/spa_test.go @@ -0,0 +1,96 @@ +package server + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +// TestSPAServing 前端静态资源 + index.html 提供。 +func TestSPAServing(t *testing.T) { + // 构造一个临时 web 目录(模拟构建产物)。 + webDir := t.TempDir() + os.WriteFile(filepath.Join(webDir, "index.html"), []byte("SPA"), 0644) + os.MkdirAll(filepath.Join(webDir, "assets"), 0755) + os.WriteFile(filepath.Join(webDir, "assets", "app.js"), []byte("console.log(1)"), 0644) + os.WriteFile(filepath.Join(webDir, "favicon.svg"), []byte(""), 0644) + + srv, _, cleanup := newTestServer(t) + defer cleanup() + srv.WebDir = webDir + h := srv.Router() + + // 1) / 应返回 index.html。 + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("/ status=%d", rec.Code) + } + if rec.Body.String() != "SPA" { + t.Errorf("/ 应返回 index.html,got %q", rec.Body.String()) + } + + // 2) /static/assets/app.js 应返回 JS(vite base=/static/)。 + req2 := httptest.NewRequest(http.MethodGet, "/static/assets/app.js", nil) + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req2) + if rec2.Code != 200 { + t.Fatalf("/static/assets/app.js status=%d", rec2.Code) + } + if rec2.Body.String() != "console.log(1)" { + t.Errorf("JS 内容异常: %q", rec2.Body.String()) + } + + // 3) /static/favicon.svg。 + req3 := httptest.NewRequest(http.MethodGet, "/static/favicon.svg", nil) + rec3 := httptest.NewRecorder() + h.ServeHTTP(rec3, req3) + if rec3.Code != 200 { + t.Fatalf("favicon status=%d", rec3.Code) + } + + // 4) 客户端路由(如 /dashboard)应返回 index.html(React Router 接管)。 + req4 := httptest.NewRequest(http.MethodGet, "/dashboard", nil) + rec4 := httptest.NewRecorder() + h.ServeHTTP(rec4, req4) + if rec4.Code != 200 || rec4.Body.String() != "SPA" { + t.Errorf("客户端路由应返回 index.html,status=%d body=%q", rec4.Code, rec4.Body.String()) + } + + // 5) API 路径不应返回 index.html。 + req5 := httptest.NewRequest(http.MethodGet, "/api/orders", nil) + rec5 := httptest.NewRecorder() + h.ServeHTTP(rec5, req5) + // /api/orders 需认证,应 401(不是 index.html)。 + if rec5.Body.String() == "SPA" { + t.Error("API 路径不应返回 index.html") + } +} + +// TestSPAEmbeddedWithoutWebDir 未配置 WebDir 时使用内嵌 SPA。 +func TestSPAEmbeddedWithoutWebDir(t *testing.T) { + srv, _, cleanup := newTestServer(t) + defer cleanup() + srv.WebDir = "" + h := srv.Router() + + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("无 WebDir 应返回内嵌 SPA,got %d body=%s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), `
`) { + t.Fatalf("内嵌 SPA index.html 异常: %q", rec.Body.String()) + } +} + +func init() { + // newTestServer 用 context.Background,确保可用。 + _ = context.Background +} diff --git a/internal/server/stub_handlers.go b/internal/server/stub_handlers.go new file mode 100644 index 0000000..e3e2331 --- /dev/null +++ b/internal/server/stub_handlers.go @@ -0,0 +1,16 @@ +package server + +import "github.com/go-chi/chi/v5" + +// stub_handlers.go 原为各分组的 501 占位;现已全部由 Real 实现替换。 +// 保留本文件作为 mount* 方法名到 Real 实现的别名,保持 server.go 调用简洁。 + +func (s *Server) mountItems(r chi.Router) { s.mountItemsReal(r) } +func (s *Server) mountKeywords(r chi.Router) { s.mountKeywordsReal(r) } +func (s *Server) mountDefaultReplies(r chi.Router) { s.mountDefaultRepliesReal(r) } +func (s *Server) mountNotifications(r chi.Router) { s.mountNotificationsReal(r) } +func (s *Server) mountSettings(r chi.Router) { s.mountSettingsReal(r) } +func (s *Server) mountAIReply(r chi.Router) { s.mountAIReplyReal(r) } +func (s *Server) mountUser(r chi.Router) { s.mountUserReal(r) } +func (s *Server) mountAdmin(r chi.Router) { s.mountAdminReal(r) } + diff --git a/internal/webui/static/assets/index-D2SGgSWO.css b/internal/webui/static/assets/index-D2SGgSWO.css new file mode 100644 index 0000000..fec92d9 --- /dev/null +++ b/internal/webui/static/assets/index-D2SGgSWO.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{right:-.25rem}.-right-6{right:-1.5rem}.-top-6{top:-1.5rem}.bottom-10{bottom:2.5rem}.bottom-\[-10\%\]{bottom:-10%}.left-0{left:0}.left-1{left:.25rem}.left-2{left:.5rem}.left-4{left:1rem}.left-5{left:1.25rem}.left-7{left:1.75rem}.left-\[-10\%\]{left:-10%}.right-0{right:0}.right-10{right:2.5rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-\[-10\%\]{right:-10%}.top-0{top:0}.top-1{top:.25rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-3{top:.75rem}.top-4{top:1rem}.top-\[-10\%\]{top:-10%}.top-\[calc\(100\%\+6px\)\]{top:calc(100% + 6px)}.-z-10{z-index:-10}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.col-span-2{grid-column:span 2 / span 2}.col-span-full{grid-column:1 / -1}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-10{margin-bottom:2.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-64{margin-left:16rem}.mr-2{margin-right:.5rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.aspect-square{aspect-ratio:1 / 1}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-80{height:20rem}.h-9{height:2.25rem}.h-\[280px\]{height:280px}.h-\[300px\]{height:300px}.h-\[350px\]{height:350px}.h-\[42px\]{height:42px}.h-\[48px\]{height:48px}.h-\[60\%\]{height:60%}.h-\[800px\]{height:800px}.h-full{height:100%}.h-screen{height:100vh}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-\[400px\]{max-height:400px}.max-h-\[60vh\]{max-height:60vh}.max-h-\[90vh\]{max-height:90vh}.min-h-\[100px\]{min-height:100px}.min-h-\[400px\]{min-height:400px}.min-h-\[500px\]{min-height:500px}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[10\%\]{width:10%}.w-\[12\%\]{width:12%}.w-\[15\%\]{width:15%}.w-\[20\%\]{width:20%}.w-\[25\%\]{width:25%}.w-\[60\%\]{width:60%}.w-\[800px\]{width:800px}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-6xl{max-width:72rem}.max-w-\[100px\]{max-width:100px}.max-w-\[1400px\]{max-width:1400px}.max-w-\[200px\]{max-width:200px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-xl{max-width:36rem}.flex-1{flex:1 1 0%}.flex-shrink-0,.shrink-0{flex-shrink:0}.table-fixed{table-layout:fixed}.border-collapse{border-collapse:collapse}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1\/2{--tw-translate-x: 50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-6{--tw-translate-x: 1.5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-7{--tw-translate-x: 1.75rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-8{--tw-translate-x: 2rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\[1\.02\]{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-50>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(249 250 251 / var(--tw-divide-opacity, 1))}.self-end{align-self:flex-end}.self-center{align-self:center}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.scroll-smooth{scroll-behavior:smooth}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1.5rem}.rounded-3xl{border-radius:2rem}.rounded-\[2\.5rem\]{border-radius:2.5rem}.rounded-\[2rem\]{border-radius:2rem}.rounded-\[3rem\]{border-radius:3rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-4{border-width:4px}.border-y{border-top-width:1px;border-bottom-width:1px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-50{--tw-border-opacity: 1;border-color:rgb(249 250 251 / var(--tw-border-opacity, 1))}.border-purple-200{--tw-border-opacity: 1;border-color:rgb(233 213 255 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.bg-\[\#0094f7\]{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F4F5F7\]{--tw-bg-opacity: 1;background-color:rgb(244 245 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F7F8FA\]{--tw-bg-opacity: 1;background-color:rgb(247 248 250 / var(--tw-bg-opacity, 1))}.bg-\[\#FAFAFA\]{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-\[\#f5f5f7\]{--tw-bg-opacity: 1;background-color:rgb(245 245 247 / var(--tw-bg-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-black\/60{background-color:#0009}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200\/30{background-color:#bfdbfe4d}.bg-blue-200\/40{background-color:#bfdbfe66}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-100\/50{background-color:#f3f4f680}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-200\/50{background-color:#e5e7eb80}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-pink-50{--tw-bg-opacity: 1;background-color:rgb(253 242 248 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-50{--tw-bg-opacity: 1;background-color:rgb(250 245 255 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/25{background-color:#ffffff40}.bg-white\/30{background-color:#ffffff4d}.bg-white\/70{background-color:#ffffffb3}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-opacity-10{--tw-bg-opacity: .1}.bg-gradient-to-bl{background-image:linear-gradient(to bottom left,var(--tw-gradient-stops))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-\[\#0094f7\]{--tw-gradient-from: #0094f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 148 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-\[\#0094f7\]\/10{--tw-gradient-from: rgb(0 148 247 / .1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 148 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-\[\#0094f7\]\/20{--tw-gradient-from: rgb(0 148 247 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 148 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-\[\#287efe\]{--tw-gradient-from: #287efe var(--tw-gradient-from-position);--tw-gradient-to: rgb(40 126 254 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-400{--tw-gradient-from: #60a5fa var(--tw-gradient-from-position);--tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-400\/10{--tw-gradient-from: rgb(96 165 250 / .1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-400\/20{--tw-gradient-from: rgb(96 165 250 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-100{--tw-gradient-from: #f3f4f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(243 244 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-300{--tw-gradient-from: #d1d5db var(--tw-gradient-from-position);--tw-gradient-to: rgb(209 213 219 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-400{--tw-gradient-from: #9ca3af var(--tw-gradient-from-position);--tw-gradient-to: rgb(156 163 175 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-400{--tw-gradient-from: #4ade80 var(--tw-gradient-from-position);--tw-gradient-to: rgb(74 222 128 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-50{--tw-gradient-from: #f0fdf4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(240 253 244 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-400{--tw-gradient-from: #c084fc var(--tw-gradient-from-position);--tw-gradient-to: rgb(192 132 252 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-400\/10{--tw-gradient-from: rgb(192 132 252 / .1) var(--tw-gradient-from-position);--tw-gradient-to: rgb(192 132 252 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-400\/20{--tw-gradient-from: rgb(192 132 252 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(192 132 252 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-50{--tw-gradient-from: #faf5ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(250 245 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-50{--tw-gradient-from: #fef2f2 var(--tw-gradient-from-position);--tw-gradient-to: rgb(254 242 242 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-white{--tw-gradient-from: #fff var(--tw-gradient-from-position);--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-\[\#0071e3\]{--tw-gradient-to: #0071e3 var(--tw-gradient-to-position)}.to-\[\#0071e3\]\/20{--tw-gradient-to: rgb(0 113 227 / .2) var(--tw-gradient-to-position)}.to-\[\#0094f7\]{--tw-gradient-to: #0094f7 var(--tw-gradient-to-position)}.to-blue-100{--tw-gradient-to: #dbeafe var(--tw-gradient-to-position)}.to-blue-100\/50{--tw-gradient-to: rgb(219 234 254 / .5) var(--tw-gradient-to-position)}.to-blue-50\/30{--tw-gradient-to: rgb(239 246 255 / .3) var(--tw-gradient-to-position)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-blue-500\/20{--tw-gradient-to: rgb(59 130 246 / .2) var(--tw-gradient-to-position)}.to-gray-200{--tw-gradient-to: #e5e7eb var(--tw-gradient-to-position)}.to-gray-400{--tw-gradient-to: #9ca3af var(--tw-gradient-to-position)}.to-gray-50{--tw-gradient-to: #f9fafb var(--tw-gradient-to-position)}.to-gray-500{--tw-gradient-to: #6b7280 var(--tw-gradient-to-position)}.to-green-100{--tw-gradient-to: #dcfce7 var(--tw-gradient-to-position)}.to-green-500{--tw-gradient-to: #22c55e var(--tw-gradient-to-position)}.to-purple-100{--tw-gradient-to: #f3e8ff var(--tw-gradient-to-position)}.to-purple-100\/50{--tw-gradient-to: rgb(243 232 255 / .5) var(--tw-gradient-to-position)}.to-purple-50\/30{--tw-gradient-to: rgb(250 245 255 / .3) var(--tw-gradient-to-position)}.to-purple-500{--tw-gradient-to: #a855f7 var(--tw-gradient-to-position)}.to-purple-500\/20{--tw-gradient-to: rgb(168 85 247 / .2) var(--tw-gradient-to-position)}.to-red-100{--tw-gradient-to: #fee2e2 var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-3\.5{padding:.875rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-24{padding-top:6rem;padding-bottom:6rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.pb-10{padding-bottom:2.5rem}.pb-20{padding-bottom:5rem}.pb-24{padding-bottom:6rem}.pl-10{padding-left:2.5rem}.pl-11{padding-left:2.75rem}.pl-14{padding-left:3.5rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pr-10{padding-right:2.5rem}.pr-11{padding-right:2.75rem}.pr-12{padding-right:3rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pt-4{padding-top:1rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-relaxed{line-height:1.625}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.text-\[\#111\]{--tw-text-opacity: 1;color:rgb(17 17 17 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-600{--tw-text-opacity: 1;color:rgb(219 39 119 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/30{color:#ffffff4d}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-30{opacity:.3}.opacity-60{opacity:.6}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_20px_60px_-15px_rgba\(0\,0\,0\,0\.05\)\]{--tw-shadow: 0 20px 60px -15px rgba(0,0,0,.05);--tw-shadow-colored: 0 20px 60px -15px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[4px_0_24px_rgba\(0\,0\,0\,0\.02\)\]{--tw-shadow: 4px 0 24px rgba(0,0,0,.02);--tw-shadow-colored: 4px 0 24px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-blue-100{--tw-shadow-color: #dbeafe;--tw-shadow: var(--tw-shadow-colored)}.shadow-blue-200{--tw-shadow-color: #bfdbfe;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200{--tw-shadow-color: #e5e7eb;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200\/70{--tw-shadow-color: rgb(229 231 235 / .7);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-white{--tw-ring-opacity: 1;--tw-ring-color: rgb(255 255 255 / var(--tw-ring-opacity, 1))}.blur-2xl{--tw-blur: blur(40px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-\[120px\]{--tw-blur: blur(120px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-3xl{--tw-backdrop-blur: blur(64px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.squircle{-webkit-mask-image:url(/static/squircle.svg);mask-image:url(/static/squircle.svg);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;border-radius:0}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{height:100%;width:100%}body{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:#f4f5f7;color:#fff;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ios-card{background:#fff;border-radius:24px;border:1px solid rgba(0,0,0,.02);box-shadow:0 8px 24px #0000000a;transition:transform .2s ease,box-shadow .2s ease}.ios-card:hover{box-shadow:0 12px 32px #0000000f}.ios-input{background:#f7f8fa;border:1px solid transparent;transition:all .3s cubic-bezier(.25,.8,.25,1);color:#111;font-weight:500}.ios-input:focus{background:#fff;border-color:#0094f7;box-shadow:0 0 0 4px #0094f74d;outline:none}.ios-input::-moz-placeholder{color:#9ca3af;font-weight:400}.ios-input::placeholder{color:#9ca3af;font-weight:400}.ios-btn-primary{background:#0094f7;color:#fff;font-weight:700;border:none;transition:all .2s cubic-bezier(.25,.8,.25,1);cursor:pointer}.ios-btn-primary:hover:not(:disabled){background:#0071e3;transform:translateY(-1px);box-shadow:0 8px 20px #0094f74d}.ios-btn-primary:active:not(:disabled){transform:translateY(1px);box-shadow:0 2px 8px #0094f733}.ios-btn-primary:disabled{background:#f0f0f0;color:#aaa;box-shadow:none;transform:none;cursor:not-allowed}.ios-btn-secondary{background:#f7f8fa;color:#fff;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-secondary:hover{background:#e5e7eb;border-color:#d1d5db}.ios-btn-danger{background:#fee2e2;color:#dc2626;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-danger:hover{background:#fecaca;border-color:#fca5a5}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0000001a;border-radius:10px}::-webkit-scrollbar-thumb:hover{background:#0003}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .5s cubic-bezier(.16,1,.3,1) forwards}@keyframes slideUp{0%{opacity:0;transform:translateY(30px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}.animate-slide-up{animation:slideUp .3s cubic-bezier(.16,1,.3,1) forwards}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}::-moz-selection{background:#0094f7;color:#fff}::selection{background:#0094f7;color:#fff}.text-brand{color:#0094f7}.bg-brand{background-color:#0094f7}.border-brand{border-color:#0094f7}.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:9999px;font-size:12px;font-weight:600}.status-badge-success{background-color:#d1fae5;color:#065f46}.status-badge-warning{background-color:#fef3c7;color:#92400e}.status-badge-error{background-color:#fee2e2;color:#991b1b}.status-badge-info{background-color:#dbeafe;color:#1e40af}.loading-skeleton{background:linear-gradient(90deg,#f3f4f6,#e5e7eb,#f3f4f6);background-size:200% 100%;animation:loading 1.5s ease-in-out infinite}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;align-items:center;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto;display:flex;flex-direction:column;background-color:#fff;border-radius:2.5rem;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}.modal-header{flex-shrink:0;padding:2rem 2rem 1.5rem;border-bottom:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-body{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:2rem}.modal-footer{flex-shrink:0;padding:1.5rem 2rem 2rem;border-top:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-container-lg{max-width:64rem}.modal-overlay-centered{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-overlay-centered .modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto 0;display:flex;flex-direction:column;background-color:#fff;border-radius:2.5rem;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}@media(max-width:768px){.ios-card{border-radius:16px}.ios-input{font-size:16px}.modal-container{max-width:calc(100% - 2rem);max-height:90vh;border-radius:1.5rem}.modal-header,.modal-body,.modal-footer{padding-left:1.5rem;padding-right:1.5rem}}.hover\:translate-y-\[-4px\]:hover{--tw-translate-y: -4px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-110:hover{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-\[\#0094f7\]:hover{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.hover\:border-\[\#0094f7\]\/30:hover{border-color:#0094f74d}.hover\:border-blue-400\/30:hover{border-color:#60a5fa4d}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:border-purple-400\/30:hover{border-color:#c084fc4d}.hover\:bg-\[\#0094f7\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#FFFDE7\]\/50:hover{background-color:#fffde780}.hover\:bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-50:hover{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/40:hover{background-color:#fff6}.hover\:bg-white\/50:hover{background-color:#ffffff80}.hover\:from-\[\#0071e3\]:hover{--tw-gradient-from: #0071e3 var(--tw-gradient-from-position);--tw-gradient-to: rgb(0 113 227 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-blue-100:hover{--tw-gradient-from: #dbeafe var(--tw-gradient-from-position);--tw-gradient-to: rgb(219 234 254 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-gray-200:hover{--tw-gradient-from: #e5e7eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(229 231 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-green-100:hover{--tw-gradient-from: #dcfce7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 252 231 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-100:hover{--tw-gradient-from: #f3e8ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(243 232 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-500:hover{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-red-100:hover{--tw-gradient-from: #fee2e2 var(--tw-gradient-from-position);--tw-gradient-to: rgb(254 226 226 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:to-\[\#0071e3\]:hover{--tw-gradient-to: #0071e3 var(--tw-gradient-to-position)}.hover\:to-blue-200:hover{--tw-gradient-to: #bfdbfe var(--tw-gradient-to-position)}.hover\:to-gray-300:hover{--tw-gradient-to: #d1d5db var(--tw-gradient-to-position)}.hover\:to-green-200:hover{--tw-gradient-to: #bbf7d0 var(--tw-gradient-to-position)}.hover\:to-purple-200:hover{--tw-gradient-to: #e9d5ff var(--tw-gradient-to-position)}.hover\:to-purple-600:hover{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.hover\:to-red-200:hover{--tw-gradient-to: #fecaca var(--tw-gradient-to-position)}.hover\:text-\[\#0094f7\]:hover{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.hover\:text-black:hover{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:shadow-2xl:hover{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-xl:hover{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-\[\#0094f7\]:focus{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.focus\:border-blue-400:focus{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.focus\:border-purple-400:focus{--tw-border-opacity: 1;border-color:rgb(192 132 252 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-0:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-4:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-\[\#0094f7\]:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(0 148 247 / var(--tw-ring-opacity, 1))}.focus\:ring-\[\#0094f7\]\/20:focus{--tw-ring-color: rgb(0 148 247 / .2)}.focus\:ring-purple-400\/20:focus{--tw-ring-color: rgb(192 132 252 / .2)}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-25:disabled{opacity:.25}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.disabled\:opacity-70:disabled{opacity:.7}.group:focus-within .group-focus-within\:text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.group:focus-within .group-focus-within\:text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:rotate-12{--tw-rotate: 12deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-125{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-150{--tw-scale-x: 1.5;--tw-scale-y: 1.5;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media(min-width:640px){.sm\:w-64{width:16rem}.sm\:w-auto{width:auto}.sm\:flex-none{flex:none}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-\[1fr_180px\]{grid-template-columns:1fr 180px}.sm\:flex-row{flex-direction:row}.sm\:gap-8{gap:2rem}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:w-auto{width:auto}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-\[1fr_1fr_1\.4fr_90px_40px\]{grid-template-columns:1fr 1fr 1.4fr 90px 40px}.md\:grid-cols-\[1fr_auto\]{grid-template-columns:1fr auto}.md\:flex-row{flex-direction:row}.md\:items-end{align-items:flex-end}.md\:items-center{align-items:center}.md\:border-l{border-left-width:1px}.md\:border-t-0{border-top-width:0px}.md\:p-12{padding:3rem}.md\:pl-6{padding-left:1.5rem}.md\:pt-0{padding-top:0}}@media(min-width:1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:self-auto{align-self:auto}}@media(min-width:1280px){.xl\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}} diff --git a/internal/webui/static/assets/index-Iccu2KVx.js b/internal/webui/static/assets/index-Iccu2KVx.js new file mode 100644 index 0000000..2732ee7 --- /dev/null +++ b/internal/webui/static/assets/index-Iccu2KVx.js @@ -0,0 +1,408 @@ +var jM=Object.defineProperty;var _M=(e,t,r)=>t in e?jM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var dp=(e,t,r)=>_M(e,typeof t!="symbol"?t+"":t,r);function SM(e,t){for(var r=0;rn[l]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))n(l);new MutationObserver(l=>{for(const s of l)if(s.type==="childList")for(const c of s.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(l){const s={};return l.integrity&&(s.integrity=l.integrity),l.referrerPolicy&&(s.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?s.credentials="include":l.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(l){if(l.ep)return;l.ep=!0;const s=r(l);fetch(l.href,s)}})();function kn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hp={exports:{}},hs={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var sj;function NM(){if(sj)return hs;sj=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(n,l,s){var c=null;if(s!==void 0&&(c=""+s),l.key!==void 0&&(c=""+l.key),"key"in l){s={};for(var d in l)d!=="key"&&(s[d]=l[d])}else s=l;return l=s.ref,{$$typeof:e,type:n,key:c,ref:l!==void 0?l:null,props:s}}return hs.Fragment=t,hs.jsx=r,hs.jsxs=r,hs}var uj;function OM(){return uj||(uj=1,hp.exports=NM()),hp.exports}var f=OM(),mp={exports:{}},Ae={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var cj;function AM(){if(cj)return Ae;cj=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),x=Symbol.iterator;function w(C){return C===null||typeof C!="object"?null:(C=x&&C[x]||C["@@iterator"],typeof C=="function"?C:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,N={};function A(C,U,ee){this.props=C,this.context=U,this.refs=N,this.updater=ee||j}A.prototype.isReactComponent={},A.prototype.setState=function(C,U){if(typeof C!="object"&&typeof C!="function"&&C!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,C,U,"setState")},A.prototype.forceUpdate=function(C){this.updater.enqueueForceUpdate(this,C,"forceUpdate")};function O(){}O.prototype=A.prototype;function P(C,U,ee){this.props=C,this.context=U,this.refs=N,this.updater=ee||j}var k=P.prototype=new O;k.constructor=P,_(k,A.prototype),k.isPureReactComponent=!0;var z=Array.isArray;function T(){}var R={H:null,A:null,T:null,S:null},$=Object.prototype.hasOwnProperty;function Z(C,U,ee){var le=ee.ref;return{$$typeof:e,type:C,key:U,ref:le!==void 0?le:null,props:ee}}function X(C,U){return Z(C.type,U,C.props)}function L(C){return typeof C=="object"&&C!==null&&C.$$typeof===e}function K(C){var U={"=":"=0",":":"=2"};return"$"+C.replace(/[=:]/g,function(ee){return U[ee]})}var se=/\/+/g;function ce(C,U){return typeof C=="object"&&C!==null&&C.key!=null?K(""+C.key):U.toString(36)}function he(C){switch(C.status){case"fulfilled":return C.value;case"rejected":throw C.reason;default:switch(typeof C.status=="string"?C.then(T,T):(C.status="pending",C.then(function(U){C.status==="pending"&&(C.status="fulfilled",C.value=U)},function(U){C.status==="pending"&&(C.status="rejected",C.reason=U)})),C.status){case"fulfilled":return C.value;case"rejected":throw C.reason}}throw C}function q(C,U,ee,le,me){var pe=typeof C;(pe==="undefined"||pe==="boolean")&&(C=null);var be=!1;if(C===null)be=!0;else switch(pe){case"bigint":case"string":case"number":be=!0;break;case"object":switch(C.$$typeof){case e:case t:be=!0;break;case p:return be=C._init,q(be(C._payload),U,ee,le,me)}}if(be)return me=me(C),be=le===""?"."+ce(C,0):le,z(me)?(ee="",be!=null&&(ee=be.replace(se,"$&/")+"/"),q(me,U,ee,"",function(we){return we})):me!=null&&(L(me)&&(me=X(me,ee+(me.key==null||C&&C.key===me.key?"":(""+me.key).replace(se,"$&/")+"/")+be)),U.push(me)),1;be=0;var Me=le===""?".":le+":";if(z(C))for(var J=0;J>>1,M=q[te];if(0>>1;tel(ee,ue))lel(me,ee)?(q[te]=me,q[le]=ue,te=le):(q[te]=ee,q[U]=ue,te=U);else if(lel(me,ue))q[te]=me,q[le]=ue,te=le;else break e}}return W}function l(q,W){var ue=q.sortIndex-W.sortIndex;return ue!==0?ue:q.id-W.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var c=Date,d=c.now();e.unstable_now=function(){return c.now()-d}}var h=[],m=[],p=1,y=null,x=3,w=!1,j=!1,_=!1,N=!1,A=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;function k(q){for(var W=r(m);W!==null;){if(W.callback===null)n(m);else if(W.startTime<=q)n(m),W.sortIndex=W.expirationTime,t(h,W);else break;W=r(m)}}function z(q){if(_=!1,k(q),!j)if(r(h)!==null)j=!0,T||(T=!0,K());else{var W=r(m);W!==null&&he(z,W.startTime-q)}}var T=!1,R=-1,$=5,Z=-1;function X(){return N?!0:!(e.unstable_now()-Z<$)}function L(){if(N=!1,T){var q=e.unstable_now();Z=q;var W=!0;try{e:{j=!1,_&&(_=!1,O(R),R=-1),w=!0;var ue=x;try{t:{for(k(q),y=r(h);y!==null&&!(y.expirationTime>q&&X());){var te=y.callback;if(typeof te=="function"){y.callback=null,x=y.priorityLevel;var M=te(y.expirationTime<=q);if(q=e.unstable_now(),typeof M=="function"){y.callback=M,k(q),W=!0;break t}y===r(h)&&n(h),k(q)}else n(h);y=r(h)}if(y!==null)W=!0;else{var C=r(m);C!==null&&he(z,C.startTime-q),W=!1}}break e}finally{y=null,x=ue,w=!1}W=void 0}}finally{W?K():T=!1}}}var K;if(typeof P=="function")K=function(){P(L)};else if(typeof MessageChannel<"u"){var se=new MessageChannel,ce=se.port2;se.port1.onmessage=L,K=function(){ce.postMessage(null)}}else K=function(){A(L,0)};function he(q,W){R=A(function(){q(e.unstable_now())},W)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125te?(q.sortIndex=ue,t(m,q),r(h)===null&&q===r(m)&&(_?(O(R),R=-1):_=!0,he(z,ue-te))):(q.sortIndex=M,t(h,q),j||w||(j=!0,T||(T=!0,K()))),q},e.unstable_shouldYield=X,e.unstable_wrapCallback=function(q){var W=x;return function(){var ue=x;x=W;try{return q.apply(this,arguments)}finally{x=ue}}}})(yp)),yp}var hj;function kM(){return hj||(hj=1,vp.exports=CM()),vp.exports}var gp={exports:{}},er={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var mj;function MM(){if(mj)return er;mj=1;var e=so();function t(h){var m="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),gp.exports=MM(),gp.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var vj;function TM(){if(vj)return ms;vj=1;var e=kM(),t=so(),r=UO();function n(a){var i="https://react.dev/errors/"+a;if(1M||(a.current=te[M],te[M]=null,M--)}function ee(a,i){M++,te[M]=a.current,a.current=i}var le=C(null),me=C(null),pe=C(null),be=C(null);function Me(a,i){switch(ee(pe,i),ee(me,a),ee(le,null),i.nodeType){case 9:case 11:a=(a=i.documentElement)&&(a=a.namespaceURI)?Mw(a):0;break;default:if(a=i.tagName,i=i.namespaceURI)i=Mw(i),a=Tw(i,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}U(le),ee(le,a)}function J(){U(le),U(me),U(pe)}function we(a){a.memoizedState!==null&&ee(be,a);var i=le.current,o=Tw(i,a.type);i!==o&&(ee(me,a),ee(le,o))}function Oe(a){me.current===a&&(U(le),U(me)),be.current===a&&(U(be),us._currentValue=ue)}var ie,Ie;function _e(a){if(ie===void 0)try{throw Error()}catch(o){var i=o.stack.trim().match(/\n( *(at )?)/);ie=i&&i[1]||"",Ie=-1)":-1v||I[u]!==V[v]){var re=` +`+I[u].replace(" at new "," at ");return a.displayName&&re.includes("")&&(re=re.replace("",a.displayName)),re}while(1<=u&&0<=v);break}}}finally{ct=!1,Error.prepareStackTrace=o}return(o=a?a.displayName||a.name:"")?_e(o):""}function ht(a,i){switch(a.tag){case 26:case 27:case 5:return _e(a.type);case 16:return _e("Lazy");case 13:return a.child!==i&&i!==null?_e("Suspense Fallback"):_e("Suspense");case 19:return _e("SuspenseList");case 0:case 15:return ft(a.type,!1);case 11:return ft(a.type.render,!1);case 1:return ft(a.type,!0);case 31:return _e("Activity");default:return""}}function nn(a){try{var i="",o=null;do i+=ht(a,o),o=a,a=a.return;while(a);return i}catch(u){return` +Error generating stack: `+u.message+` +`+u.stack}}var Pn=Object.prototype.hasOwnProperty,zn=e.unstable_scheduleCallback,D=e.unstable_cancelCallback,oe=e.unstable_shouldYield,fe=e.unstable_requestPaint,Pe=e.unstable_now,Sr=e.unstable_getCurrentPriorityLevel,pn=e.unstable_ImmediatePriority,fi=e.unstable_UserBlockingPriority,Rn=e.unstable_NormalPriority,vn=e.unstable_LowPriority,mu=e.unstable_IdlePriority,Wd=e.log,Jd=e.unstable_setDisableYieldValue,wo=null,Nr=null;function Sa(a){if(typeof Wd=="function"&&Jd(a),Nr&&typeof Nr.setStrictMode=="function")try{Nr.setStrictMode(wo,a)}catch{}}var Or=Math.clz32?Math.clz32:s5,l5=Math.log,o5=Math.LN2;function s5(a){return a>>>=0,a===0?32:31-(l5(a)/o5|0)|0}var pu=256,vu=262144,yu=4194304;function di(a){var i=a&42;if(i!==0)return i;switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return a&261888;case 262144:case 524288:case 1048576:case 2097152:return a&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return a&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return a}}function gu(a,i,o){var u=a.pendingLanes;if(u===0)return 0;var v=0,g=a.suspendedLanes,S=a.pingedLanes;a=a.warmLanes;var E=u&134217727;return E!==0?(u=E&~g,u!==0?v=di(u):(S&=E,S!==0?v=di(S):o||(o=E&~a,o!==0&&(v=di(o))))):(E=u&~g,E!==0?v=di(E):S!==0?v=di(S):o||(o=u&~a,o!==0&&(v=di(o)))),v===0?0:i!==0&&i!==v&&(i&g)===0&&(g=v&-v,o=i&-i,g>=o||g===32&&(o&4194048)!==0)?i:v}function jo(a,i){return(a.pendingLanes&~(a.suspendedLanes&~a.pingedLanes)&i)===0}function u5(a,i){switch(a){case 1:case 2:case 4:case 8:case 64:return i+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return i+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function dx(){var a=yu;return yu<<=1,(yu&62914560)===0&&(yu=4194304),a}function eh(a){for(var i=[],o=0;31>o;o++)i.push(a);return i}function _o(a,i){a.pendingLanes|=i,i!==268435456&&(a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0)}function c5(a,i,o,u,v,g){var S=a.pendingLanes;a.pendingLanes=o,a.suspendedLanes=0,a.pingedLanes=0,a.warmLanes=0,a.expiredLanes&=o,a.entangledLanes&=o,a.errorRecoveryDisabledLanes&=o,a.shellSuspendCounter=0;var E=a.entanglements,I=a.expirationTimes,V=a.hiddenUpdates;for(o=S&~o;0"u")return null;try{return a.activeElement||a.body}catch{return a.body}}var v5=/[\n"\\]/g;function Br(a){return a.replace(v5,function(i){return"\\"+i.charCodeAt(0).toString(16)+" "})}function lh(a,i,o,u,v,g,S,E){a.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?a.type=S:a.removeAttribute("type"),i!=null?S==="number"?(i===0&&a.value===""||a.value!=i)&&(a.value=""+$r(i)):a.value!==""+$r(i)&&(a.value=""+$r(i)):S!=="submit"&&S!=="reset"||a.removeAttribute("value"),i!=null?oh(a,S,$r(i)):o!=null?oh(a,S,$r(o)):u!=null&&a.removeAttribute("value"),v==null&&g!=null&&(a.defaultChecked=!!g),v!=null&&(a.checked=v&&typeof v!="function"&&typeof v!="symbol"),E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?a.name=""+$r(E):a.removeAttribute("name")}function Nx(a,i,o,u,v,g,S,E){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(a.type=g),i!=null||o!=null){if(!(g!=="submit"&&g!=="reset"||i!=null)){ih(a);return}o=o!=null?""+$r(o):"",i=i!=null?""+$r(i):o,E||i===a.value||(a.value=i),a.defaultValue=i}u=u??v,u=typeof u!="function"&&typeof u!="symbol"&&!!u,a.checked=E?a.checked:!!u,a.defaultChecked=!!u,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(a.name=S),ih(a)}function oh(a,i,o){i==="number"&&wu(a.ownerDocument)===a||a.defaultValue===""+o||(a.defaultValue=""+o)}function sl(a,i,o,u){if(a=a.options,i){i={};for(var v=0;v"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),dh=!1;if($n)try{var Ao={};Object.defineProperty(Ao,"passive",{get:function(){dh=!0}}),window.addEventListener("test",Ao,Ao),window.removeEventListener("test",Ao,Ao)}catch{dh=!1}var Oa=null,hh=null,_u=null;function Tx(){if(_u)return _u;var a,i=hh,o=i.length,u,v="value"in Oa?Oa.value:Oa.textContent,g=v.length;for(a=0;a=ko),Ix=" ",$x=!1;function Bx(a,i){switch(a){case"keyup":return K5.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function qx(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var dl=!1;function G5(a,i){switch(a){case"compositionend":return qx(i);case"keypress":return i.which!==32?null:($x=!0,Ix);case"textInput":return a=i.data,a===Ix&&$x?null:a;default:return null}}function V5(a,i){if(dl)return a==="compositionend"||!gh&&Bx(a,i)?(a=Tx(),_u=hh=Oa=null,dl=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(i.ctrlKey||i.altKey||i.metaKey)||i.ctrlKey&&i.altKey){if(i.char&&1=i)return{node:o,offset:i-a};a=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=Fx(o)}}function Qx(a,i){return a&&i?a===i?!0:a&&a.nodeType===3?!1:i&&i.nodeType===3?Qx(a,i.parentNode):"contains"in a?a.contains(i):a.compareDocumentPosition?!!(a.compareDocumentPosition(i)&16):!1:!1}function Wx(a){a=a!=null&&a.ownerDocument!=null&&a.ownerDocument.defaultView!=null?a.ownerDocument.defaultView:window;for(var i=wu(a.document);i instanceof a.HTMLIFrameElement;){try{var o=typeof i.contentWindow.location.href=="string"}catch{o=!1}if(o)a=i.contentWindow;else break;i=wu(a.document)}return i}function wh(a){var i=a&&a.nodeName&&a.nodeName.toLowerCase();return i&&(i==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||i==="textarea"||a.contentEditable==="true")}var tk=$n&&"documentMode"in document&&11>=document.documentMode,hl=null,jh=null,Po=null,_h=!1;function Jx(a,i,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;_h||hl==null||hl!==wu(u)||(u=hl,"selectionStart"in u&&wh(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Po&&Do(Po,u)||(Po=u,u=vc(jh,"onSelect"),0>=S,v-=S,yn=1<<32-Or(i)+v|o<Ce?(Re=xe,xe=null):Re=xe.sibling;var qe=F(H,xe,G[Ce],ne);if(qe===null){xe===null&&(xe=Re);break}a&&xe&&qe.alternate===null&&i(H,xe),B=g(qe,B,Ce),Be===null?je=qe:Be.sibling=qe,Be=qe,xe=Re}if(Ce===G.length)return o(H,xe),Le&&qn(H,Ce),je;if(xe===null){for(;CeCe?(Re=xe,xe=null):Re=xe.sibling;var Xa=F(H,xe,qe.value,ne);if(Xa===null){xe===null&&(xe=Re);break}a&&xe&&Xa.alternate===null&&i(H,xe),B=g(Xa,B,Ce),Be===null?je=Xa:Be.sibling=Xa,Be=Xa,xe=Re}if(qe.done)return o(H,xe),Le&&qn(H,Ce),je;if(xe===null){for(;!qe.done;Ce++,qe=G.next())qe=ae(H,qe.value,ne),qe!==null&&(B=g(qe,B,Ce),Be===null?je=qe:Be.sibling=qe,Be=qe);return Le&&qn(H,Ce),je}for(xe=u(xe);!qe.done;Ce++,qe=G.next())qe=Q(xe,H,Ce,qe.value,ne),qe!==null&&(a&&qe.alternate!==null&&xe.delete(qe.key===null?Ce:qe.key),B=g(qe,B,Ce),Be===null?je=qe:Be.sibling=qe,Be=qe);return a&&xe.forEach(function(wM){return i(H,wM)}),Le&&qn(H,Ce),je}function Ze(H,B,G,ne){if(typeof G=="object"&&G!==null&&G.type===_&&G.key===null&&(G=G.props.children),typeof G=="object"&&G!==null){switch(G.$$typeof){case w:e:{for(var je=G.key;B!==null;){if(B.key===je){if(je=G.type,je===_){if(B.tag===7){o(H,B.sibling),ne=v(B,G.props.children),ne.return=H,H=ne;break e}}else if(B.elementType===je||typeof je=="object"&&je!==null&&je.$$typeof===$&&_i(je)===B.type){o(H,B.sibling),ne=v(B,G.props),Bo(ne,G),ne.return=H,H=ne;break e}o(H,B);break}else i(H,B);B=B.sibling}G.type===_?(ne=gi(G.props.children,H.mode,ne,G.key),ne.return=H,H=ne):(ne=Du(G.type,G.key,G.props,null,H.mode,ne),Bo(ne,G),ne.return=H,H=ne)}return S(H);case j:e:{for(je=G.key;B!==null;){if(B.key===je)if(B.tag===4&&B.stateNode.containerInfo===G.containerInfo&&B.stateNode.implementation===G.implementation){o(H,B.sibling),ne=v(B,G.children||[]),ne.return=H,H=ne;break e}else{o(H,B);break}else i(H,B);B=B.sibling}ne=kh(G,H.mode,ne),ne.return=H,H=ne}return S(H);case $:return G=_i(G),Ze(H,B,G,ne)}if(he(G))return ye(H,B,G,ne);if(K(G)){if(je=K(G),typeof je!="function")throw Error(n(150));return G=je.call(G),Ne(H,B,G,ne)}if(typeof G.then=="function")return Ze(H,B,Bu(G),ne);if(G.$$typeof===P)return Ze(H,B,Ru(H,G),ne);qu(H,G)}return typeof G=="string"&&G!==""||typeof G=="number"||typeof G=="bigint"?(G=""+G,B!==null&&B.tag===6?(o(H,B.sibling),ne=v(B,G),ne.return=H,H=ne):(o(H,B),ne=Ch(G,H.mode,ne),ne.return=H,H=ne),S(H)):o(H,B)}return function(H,B,G,ne){try{$o=0;var je=Ze(H,B,G,ne);return Sl=null,je}catch(xe){if(xe===_l||xe===Iu)throw xe;var Be=Er(29,xe,null,H.mode);return Be.lanes=ne,Be.return=H,Be}finally{}}}var Ni=jb(!0),_b=jb(!1),Ma=!1;function Uh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Hh(a,i){a=a.updateQueue,i.updateQueue===a&&(i.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,callbacks:null})}function Ta(a){return{lane:a,tag:0,payload:null,callback:null,next:null}}function Da(a,i,o){var u=a.updateQueue;if(u===null)return null;if(u=u.shared,(Ke&2)!==0){var v=u.pending;return v===null?i.next=i:(i.next=v.next,v.next=i),u.pending=i,i=Tu(a),lb(a,null,o),i}return Mu(a,u,i,o),Tu(a)}function qo(a,i,o){if(i=i.updateQueue,i!==null&&(i=i.shared,(o&4194048)!==0)){var u=i.lanes;u&=a.pendingLanes,o|=u,i.lanes=o,mx(a,o)}}function Kh(a,i){var o=a.updateQueue,u=a.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var v=null,g=null;if(o=o.firstBaseUpdate,o!==null){do{var S={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};g===null?v=g=S:g=g.next=S,o=o.next}while(o!==null);g===null?v=g=i:g=g.next=i}else v=g=i;o={baseState:u.baseState,firstBaseUpdate:v,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},a.updateQueue=o;return}a=o.lastBaseUpdate,a===null?o.firstBaseUpdate=i:a.next=i,o.lastBaseUpdate=i}var Yh=!1;function Uo(){if(Yh){var a=jl;if(a!==null)throw a}}function Ho(a,i,o,u){Yh=!1;var v=a.updateQueue;Ma=!1;var g=v.firstBaseUpdate,S=v.lastBaseUpdate,E=v.shared.pending;if(E!==null){v.shared.pending=null;var I=E,V=I.next;I.next=null,S===null?g=V:S.next=V,S=I;var re=a.alternate;re!==null&&(re=re.updateQueue,E=re.lastBaseUpdate,E!==S&&(E===null?re.firstBaseUpdate=V:E.next=V,re.lastBaseUpdate=I))}if(g!==null){var ae=v.baseState;S=0,re=V=I=null,E=g;do{var F=E.lane&-536870913,Q=F!==E.lane;if(Q?(ze&F)===F:(u&F)===F){F!==0&&F===wl&&(Yh=!0),re!==null&&(re=re.next={lane:0,tag:E.tag,payload:E.payload,callback:null,next:null});e:{var ye=a,Ne=E;F=i;var Ze=o;switch(Ne.tag){case 1:if(ye=Ne.payload,typeof ye=="function"){ae=ye.call(Ze,ae,F);break e}ae=ye;break e;case 3:ye.flags=ye.flags&-65537|128;case 0:if(ye=Ne.payload,F=typeof ye=="function"?ye.call(Ze,ae,F):ye,F==null)break e;ae=y({},ae,F);break e;case 2:Ma=!0}}F=E.callback,F!==null&&(a.flags|=64,Q&&(a.flags|=8192),Q=v.callbacks,Q===null?v.callbacks=[F]:Q.push(F))}else Q={lane:F,tag:E.tag,payload:E.payload,callback:E.callback,next:null},re===null?(V=re=Q,I=ae):re=re.next=Q,S|=F;if(E=E.next,E===null){if(E=v.shared.pending,E===null)break;Q=E,E=Q.next,Q.next=null,v.lastBaseUpdate=Q,v.shared.pending=null}}while(!0);re===null&&(I=ae),v.baseState=I,v.firstBaseUpdate=V,v.lastBaseUpdate=re,g===null&&(v.shared.lanes=0),Ia|=S,a.lanes=S,a.memoizedState=ae}}function Sb(a,i){if(typeof a!="function")throw Error(n(191,a));a.call(i)}function Nb(a,i){var o=a.callbacks;if(o!==null)for(a.callbacks=null,a=0;ag?g:8;var S=q.T,E={};q.T=E,cm(a,!1,i,o);try{var I=v(),V=q.S;if(V!==null&&V(E,I),I!==null&&typeof I=="object"&&typeof I.then=="function"){var re=ck(I,u);Go(a,i,re,Dr(a))}else Go(a,i,u,Dr(a))}catch(ae){Go(a,i,{then:function(){},status:"rejected",reason:ae},Dr())}finally{W.p=g,S!==null&&E.types!==null&&(S.types=E.types),q.T=S}}function vk(){}function sm(a,i,o,u){if(a.tag!==5)throw Error(n(476));var v=n1(a).queue;r1(a,v,i,ue,o===null?vk:function(){return a1(a),o(u)})}function n1(a){var i=a.memoizedState;if(i!==null)return i;i={memoizedState:ue,baseState:ue,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Yn,lastRenderedState:ue},next:null};var o={};return i.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Yn,lastRenderedState:o},next:null},a.memoizedState=i,a=a.alternate,a!==null&&(a.memoizedState=i),i}function a1(a){var i=n1(a);i.next===null&&(i=a.alternate.memoizedState),Go(a,i.next.queue,{},Dr())}function um(){return Xt(us)}function i1(){return jt().memoizedState}function l1(){return jt().memoizedState}function yk(a){for(var i=a.return;i!==null;){switch(i.tag){case 24:case 3:var o=Dr();a=Ta(o);var u=Da(i,a,o);u!==null&&(yr(u,i,o),qo(u,i,o)),i={cache:Ih()},a.payload=i;return}i=i.return}}function gk(a,i,o){var u=Dr();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Qu(a)?s1(i,o):(o=Ah(a,i,o,u),o!==null&&(yr(o,a,u),u1(o,i,u)))}function o1(a,i,o){var u=Dr();Go(a,i,o,u)}function Go(a,i,o,u){var v={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Qu(a))s1(i,v);else{var g=a.alternate;if(a.lanes===0&&(g===null||g.lanes===0)&&(g=i.lastRenderedReducer,g!==null))try{var S=i.lastRenderedState,E=g(S,o);if(v.hasEagerState=!0,v.eagerState=E,Ar(E,S))return Mu(a,i,v,0),Je===null&&ku(),!1}catch{}finally{}if(o=Ah(a,i,v,u),o!==null)return yr(o,a,u),u1(o,i,u),!0}return!1}function cm(a,i,o,u){if(u={lane:2,revertLane:Um(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Qu(a)){if(i)throw Error(n(479))}else i=Ah(a,o,u,2),i!==null&&yr(i,a,2)}function Qu(a){var i=a.alternate;return a===Ee||i!==null&&i===Ee}function s1(a,i){Ol=Ku=!0;var o=a.pending;o===null?i.next=i:(i.next=o.next,o.next=i),a.pending=i}function u1(a,i,o){if((o&4194048)!==0){var u=i.lanes;u&=a.pendingLanes,o|=u,i.lanes=o,mx(a,o)}}var Vo={readContext:Xt,use:Vu,useCallback:mt,useContext:mt,useEffect:mt,useImperativeHandle:mt,useLayoutEffect:mt,useInsertionEffect:mt,useMemo:mt,useReducer:mt,useRef:mt,useState:mt,useDebugValue:mt,useDeferredValue:mt,useTransition:mt,useSyncExternalStore:mt,useId:mt,useHostTransitionStatus:mt,useFormState:mt,useActionState:mt,useOptimistic:mt,useMemoCache:mt,useCacheRefresh:mt};Vo.useEffectEvent=mt;var c1={readContext:Xt,use:Vu,useCallback:function(a,i){return lr().memoizedState=[a,i===void 0?null:i],a},useContext:Xt,useEffect:Vb,useImperativeHandle:function(a,i,o){o=o!=null?o.concat([a]):null,Fu(4194308,4,Qb.bind(null,i,a),o)},useLayoutEffect:function(a,i){return Fu(4194308,4,a,i)},useInsertionEffect:function(a,i){Fu(4,2,a,i)},useMemo:function(a,i){var o=lr();i=i===void 0?null:i;var u=a();if(Oi){Sa(!0);try{a()}finally{Sa(!1)}}return o.memoizedState=[u,i],u},useReducer:function(a,i,o){var u=lr();if(o!==void 0){var v=o(i);if(Oi){Sa(!0);try{o(i)}finally{Sa(!1)}}}else v=i;return u.memoizedState=u.baseState=v,a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:v},u.queue=a,a=a.dispatch=gk.bind(null,Ee,a),[u.memoizedState,a]},useRef:function(a){var i=lr();return a={current:a},i.memoizedState=a},useState:function(a){a=nm(a);var i=a.queue,o=o1.bind(null,Ee,i);return i.dispatch=o,[a.memoizedState,o]},useDebugValue:lm,useDeferredValue:function(a,i){var o=lr();return om(o,a,i)},useTransition:function(){var a=nm(!1);return a=r1.bind(null,Ee,a.queue,!0,!1),lr().memoizedState=a,[!1,a]},useSyncExternalStore:function(a,i,o){var u=Ee,v=lr();if(Le){if(o===void 0)throw Error(n(407));o=o()}else{if(o=i(),Je===null)throw Error(n(349));(ze&127)!==0||Mb(u,i,o)}v.memoizedState=o;var g={value:o,getSnapshot:i};return v.queue=g,Vb(Db.bind(null,u,g,a),[a]),u.flags|=2048,El(9,{destroy:void 0},Tb.bind(null,u,g,o,i),null),o},useId:function(){var a=lr(),i=Je.identifierPrefix;if(Le){var o=gn,u=yn;o=(u&~(1<<32-Or(u)-1)).toString(32)+o,i="_"+i+"R_"+o,o=Yu++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?S.createElement("select",{is:u.is}):S.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?S.createElement(v,{is:u.is}):S.createElement(v)}}g[Gt]=i,g[fr]=u;e:for(S=i.child;S!==null;){if(S.tag===5||S.tag===6)g.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===i)break e;for(;S.sibling===null;){if(S.return===null||S.return===i)break e;S=S.return}S.sibling.return=S.return,S=S.sibling}i.stateNode=g;e:switch(Zt(g,v,u),v){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Vn(i)}}return at(i),Sm(i,i.type,a===null?null:a.memoizedProps,i.pendingProps,o),null;case 6:if(a&&i.stateNode!=null)a.memoizedProps!==u&&Vn(i);else{if(typeof u!="string"&&i.stateNode===null)throw Error(n(166));if(a=pe.current,xl(i)){if(a=i.stateNode,o=i.memoizedProps,u=null,v=Vt,v!==null)switch(v.tag){case 27:case 5:u=v.memoizedProps}a[Gt]=i,a=!!(a.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||Cw(a.nodeValue,o)),a||Ca(i,!0)}else a=yc(a).createTextNode(u),a[Gt]=i,i.stateNode=a}return at(i),null;case 31:if(o=i.memoizedState,a===null||a.memoizedState!==null){if(u=xl(i),o!==null){if(a===null){if(!u)throw Error(n(318));if(a=i.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(n(557));a[Gt]=i}else xi(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;at(i),a=!1}else o=Ph(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=o),a=!0;if(!a)return i.flags&256?(kr(i),i):(kr(i),null);if((i.flags&128)!==0)throw Error(n(558))}return at(i),null;case 13:if(u=i.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(v=xl(i),u!==null&&u.dehydrated!==null){if(a===null){if(!v)throw Error(n(318));if(v=i.memoizedState,v=v!==null?v.dehydrated:null,!v)throw Error(n(317));v[Gt]=i}else xi(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;at(i),v=!1}else v=Ph(),a!==null&&a.memoizedState!==null&&(a.memoizedState.hydrationErrors=v),v=!0;if(!v)return i.flags&256?(kr(i),i):(kr(i),null)}return kr(i),(i.flags&128)!==0?(i.lanes=o,i):(o=u!==null,a=a!==null&&a.memoizedState!==null,o&&(u=i.child,v=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(v=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==v&&(u.flags|=2048)),o!==a&&o&&(i.child.flags|=8192),rc(i,i.updateQueue),at(i),null);case 4:return J(),a===null&&Gm(i.stateNode.containerInfo),at(i),null;case 10:return Hn(i.type),at(i),null;case 19:if(U(wt),u=i.memoizedState,u===null)return at(i),null;if(v=(i.flags&128)!==0,g=u.rendering,g===null)if(v)Fo(u,!1);else{if(pt!==0||a!==null&&(a.flags&128)!==0)for(a=i.child;a!==null;){if(g=Hu(a),g!==null){for(i.flags|=128,Fo(u,!1),a=g.updateQueue,i.updateQueue=a,rc(i,a),i.subtreeFlags=0,a=o,o=i.child;o!==null;)ob(o,a),o=o.sibling;return ee(wt,wt.current&1|2),Le&&qn(i,u.treeForkCount),i.child}a=a.sibling}u.tail!==null&&Pe()>oc&&(i.flags|=128,v=!0,Fo(u,!1),i.lanes=4194304)}else{if(!v)if(a=Hu(g),a!==null){if(i.flags|=128,v=!0,a=a.updateQueue,i.updateQueue=a,rc(i,a),Fo(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!Le)return at(i),null}else 2*Pe()-u.renderingStartTime>oc&&o!==536870912&&(i.flags|=128,v=!0,Fo(u,!1),i.lanes=4194304);u.isBackwards?(g.sibling=i.child,i.child=g):(a=u.last,a!==null?a.sibling=g:i.child=g,u.last=g)}return u.tail!==null?(a=u.tail,u.rendering=a,u.tail=a.sibling,u.renderingStartTime=Pe(),a.sibling=null,o=wt.current,ee(wt,v?o&1|2:o&1),Le&&qn(i,u.treeForkCount),a):(at(i),null);case 22:case 23:return kr(i),Vh(),u=i.memoizedState!==null,a!==null?a.memoizedState!==null!==u&&(i.flags|=8192):u&&(i.flags|=8192),u?(o&536870912)!==0&&(i.flags&128)===0&&(at(i),i.subtreeFlags&6&&(i.flags|=8192)):at(i),o=i.updateQueue,o!==null&&rc(i,o.retryQueue),o=null,a!==null&&a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(o=a.memoizedState.cachePool.pool),u=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(u=i.memoizedState.cachePool.pool),u!==o&&(i.flags|=2048),a!==null&&U(ji),null;case 24:return o=null,a!==null&&(o=a.memoizedState.cache),i.memoizedState.cache!==o&&(i.flags|=2048),Hn(St),at(i),null;case 25:return null;case 30:return null}throw Error(n(156,i.tag))}function _k(a,i){switch(Th(i),i.tag){case 1:return a=i.flags,a&65536?(i.flags=a&-65537|128,i):null;case 3:return Hn(St),J(),a=i.flags,(a&65536)!==0&&(a&128)===0?(i.flags=a&-65537|128,i):null;case 26:case 27:case 5:return Oe(i),null;case 31:if(i.memoizedState!==null){if(kr(i),i.alternate===null)throw Error(n(340));xi()}return a=i.flags,a&65536?(i.flags=a&-65537|128,i):null;case 13:if(kr(i),a=i.memoizedState,a!==null&&a.dehydrated!==null){if(i.alternate===null)throw Error(n(340));xi()}return a=i.flags,a&65536?(i.flags=a&-65537|128,i):null;case 19:return U(wt),null;case 4:return J(),null;case 10:return Hn(i.type),null;case 22:case 23:return kr(i),Vh(),a!==null&&U(ji),a=i.flags,a&65536?(i.flags=a&-65537|128,i):null;case 24:return Hn(St),null;case 25:return null;default:return null}}function P1(a,i){switch(Th(i),i.tag){case 3:Hn(St),J();break;case 26:case 27:case 5:Oe(i);break;case 4:J();break;case 31:i.memoizedState!==null&&kr(i);break;case 13:kr(i);break;case 19:U(wt);break;case 10:Hn(i.type);break;case 22:case 23:kr(i),Vh(),a!==null&&U(ji);break;case 24:Hn(St)}}function Zo(a,i){try{var o=i.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var v=u.next;o=v;do{if((o.tag&a)===a){u=void 0;var g=o.create,S=o.inst;u=g(),S.destroy=u}o=o.next}while(o!==v)}}catch(E){Ge(i,i.return,E)}}function Ra(a,i,o){try{var u=i.updateQueue,v=u!==null?u.lastEffect:null;if(v!==null){var g=v.next;u=g;do{if((u.tag&a)===a){var S=u.inst,E=S.destroy;if(E!==void 0){S.destroy=void 0,v=i;var I=o,V=E;try{V()}catch(re){Ge(v,I,re)}}}u=u.next}while(u!==g)}}catch(re){Ge(i,i.return,re)}}function z1(a){var i=a.updateQueue;if(i!==null){var o=a.stateNode;try{Nb(i,o)}catch(u){Ge(a,a.return,u)}}}function R1(a,i,o){o.props=Ai(a.type,a.memoizedProps),o.state=a.memoizedState;try{o.componentWillUnmount()}catch(u){Ge(a,i,u)}}function Qo(a,i){try{var o=a.ref;if(o!==null){switch(a.tag){case 26:case 27:case 5:var u=a.stateNode;break;case 30:u=a.stateNode;break;default:u=a.stateNode}typeof o=="function"?a.refCleanup=o(u):o.current=u}}catch(v){Ge(a,i,v)}}function xn(a,i){var o=a.ref,u=a.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(v){Ge(a,i,v)}finally{a.refCleanup=null,a=a.alternate,a!=null&&(a.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(v){Ge(a,i,v)}else o.current=null}function L1(a){var i=a.type,o=a.memoizedProps,u=a.stateNode;try{e:switch(i){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(v){Ge(a,a.return,v)}}function Nm(a,i,o){try{var u=a.stateNode;Yk(u,a.type,o,i),u[fr]=i}catch(v){Ge(a,a.return,v)}}function I1(a){return a.tag===5||a.tag===3||a.tag===26||a.tag===27&&Ha(a.type)||a.tag===4}function Om(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||I1(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.tag===27&&Ha(a.type)||a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function Am(a,i,o){var u=a.tag;if(u===5||u===6)a=a.stateNode,i?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(a,i):(i=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,i.appendChild(a),o=o._reactRootContainer,o!=null||i.onclick!==null||(i.onclick=In));else if(u!==4&&(u===27&&Ha(a.type)&&(o=a.stateNode,i=null),a=a.child,a!==null))for(Am(a,i,o),a=a.sibling;a!==null;)Am(a,i,o),a=a.sibling}function nc(a,i,o){var u=a.tag;if(u===5||u===6)a=a.stateNode,i?o.insertBefore(a,i):o.appendChild(a);else if(u!==4&&(u===27&&Ha(a.type)&&(o=a.stateNode),a=a.child,a!==null))for(nc(a,i,o),a=a.sibling;a!==null;)nc(a,i,o),a=a.sibling}function $1(a){var i=a.stateNode,o=a.memoizedProps;try{for(var u=a.type,v=i.attributes;v.length;)i.removeAttributeNode(v[0]);Zt(i,u,o),i[Gt]=a,i[fr]=o}catch(g){Ge(a,a.return,g)}}var Xn=!1,At=!1,Em=!1,B1=typeof WeakSet=="function"?WeakSet:Set,$t=null;function Sk(a,i){if(a=a.containerInfo,Fm=Sc,a=Wx(a),wh(a)){if("selectionStart"in a)var o={start:a.selectionStart,end:a.selectionEnd};else e:{o=(o=a.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var v=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{o.nodeType,g.nodeType}catch{o=null;break e}var S=0,E=-1,I=-1,V=0,re=0,ae=a,F=null;t:for(;;){for(var Q;ae!==o||v!==0&&ae.nodeType!==3||(E=S+v),ae!==g||u!==0&&ae.nodeType!==3||(I=S+u),ae.nodeType===3&&(S+=ae.nodeValue.length),(Q=ae.firstChild)!==null;)F=ae,ae=Q;for(;;){if(ae===a)break t;if(F===o&&++V===v&&(E=S),F===g&&++re===u&&(I=S),(Q=ae.nextSibling)!==null)break;ae=F,F=ae.parentNode}ae=Q}o=E===-1||I===-1?null:{start:E,end:I}}else o=null}o=o||{start:0,end:0}}else o=null;for(Zm={focusedElem:a,selectionRange:o},Sc=!1,$t=i;$t!==null;)if(i=$t,a=i.child,(i.subtreeFlags&1028)!==0&&a!==null)a.return=i,$t=a;else for(;$t!==null;){switch(i=$t,g=i.alternate,a=i.flags,i.tag){case 0:if((a&4)!==0&&(a=i.updateQueue,a=a!==null?a.events:null,a!==null))for(o=0;o title"))),Zt(g,u,o),g[Gt]=a,It(g),u=g;break e;case"link":var S=Gw("link","href",v).get(u+(o.href||""));if(S){for(var E=0;EZe&&(S=Ze,Ze=Ne,Ne=S);var H=Zx(E,Ne),B=Zx(E,Ze);if(H&&B&&(Q.rangeCount!==1||Q.anchorNode!==H.node||Q.anchorOffset!==H.offset||Q.focusNode!==B.node||Q.focusOffset!==B.offset)){var G=ae.createRange();G.setStart(H.node,H.offset),Q.removeAllRanges(),Ne>Ze?(Q.addRange(G),Q.extend(B.node,B.offset)):(G.setEnd(B.node,B.offset),Q.addRange(G))}}}}for(ae=[],Q=E;Q=Q.parentNode;)Q.nodeType===1&&ae.push({element:Q,left:Q.scrollLeft,top:Q.scrollTop});for(typeof E.focus=="function"&&E.focus(),E=0;Eo?32:o,q.T=null,o=zm,zm=null;var g=Ba,S=Jn;if(Tt=0,Dl=Ba=null,Jn=0,(Ke&6)!==0)throw Error(n(331));var E=Ke;if(Ke|=4,Q1(g.current),X1(g,g.current,S,o),Ke=E,ns(0,!1),Nr&&typeof Nr.onPostCommitFiberRoot=="function")try{Nr.onPostCommitFiberRoot(wo,g)}catch{}return!0}finally{W.p=v,q.T=u,pw(a,i)}}function yw(a,i,o){i=Ur(o,i),i=mm(a.stateNode,i,2),a=Da(a,i,2),a!==null&&(_o(a,2),bn(a))}function Ge(a,i,o){if(a.tag===3)yw(a,a,o);else for(;i!==null;){if(i.tag===3){yw(i,a,o);break}else if(i.tag===1){var u=i.stateNode;if(typeof i.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&($a===null||!$a.has(u))){a=Ur(o,a),o=g1(2),u=Da(i,o,2),u!==null&&(x1(o,u,i,a),_o(u,2),bn(u));break}}i=i.return}}function $m(a,i,o){var u=a.pingCache;if(u===null){u=a.pingCache=new Ak;var v=new Set;u.set(i,v)}else v=u.get(i),v===void 0&&(v=new Set,u.set(i,v));v.has(o)||(Mm=!0,v.add(o),a=Tk.bind(null,a,i,o),i.then(a,a))}function Tk(a,i,o){var u=a.pingCache;u!==null&&u.delete(i),a.pingedLanes|=a.suspendedLanes&o,a.warmLanes&=~o,Je===a&&(ze&o)===o&&(pt===4||pt===3&&(ze&62914560)===ze&&300>Pe()-lc?(Ke&2)===0&&Pl(a,0):Tm|=o,Tl===ze&&(Tl=0)),bn(a)}function gw(a,i){i===0&&(i=dx()),a=yi(a,i),a!==null&&(_o(a,i),bn(a))}function Dk(a){var i=a.memoizedState,o=0;i!==null&&(o=i.retryLane),gw(a,o)}function Pk(a,i){var o=0;switch(a.tag){case 31:case 13:var u=a.stateNode,v=a.memoizedState;v!==null&&(o=v.retryLane);break;case 19:u=a.stateNode;break;case 22:u=a.stateNode._retryCache;break;default:throw Error(n(314))}u!==null&&u.delete(i),gw(a,o)}function zk(a,i){return zn(a,i)}var hc=null,Rl=null,Bm=!1,mc=!1,qm=!1,Ua=0;function bn(a){a!==Rl&&a.next===null&&(Rl===null?hc=Rl=a:Rl=Rl.next=a),mc=!0,Bm||(Bm=!0,Lk())}function ns(a,i){if(!qm&&mc){qm=!0;do for(var o=!1,u=hc;u!==null;){if(a!==0){var v=u.pendingLanes;if(v===0)var g=0;else{var S=u.suspendedLanes,E=u.pingedLanes;g=(1<<31-Or(42|a)+1)-1,g&=v&~(S&~E),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(o=!0,jw(u,g))}else g=ze,g=gu(u,u===Je?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||jo(u,g)||(o=!0,jw(u,g));u=u.next}while(o);qm=!1}}function Rk(){xw()}function xw(){mc=Bm=!1;var a=0;Ua!==0&&Vk()&&(a=Ua);for(var i=Pe(),o=null,u=hc;u!==null;){var v=u.next,g=bw(u,i);g===0?(u.next=null,o===null?hc=v:o.next=v,v===null&&(Rl=o)):(o=u,(a!==0||(g&3)!==0)&&(mc=!0)),u=v}Tt!==0&&Tt!==5||ns(a),Ua!==0&&(Ua=0)}function bw(a,i){for(var o=a.suspendedLanes,u=a.pingedLanes,v=a.expirationTimes,g=a.pendingLanes&-62914561;0E)break;var re=I.transferSize,ae=I.initiatorType;re&&kw(ae)&&(I=I.responseEnd,S+=re*(I"u"?null:document;function Uw(a,i,o){var u=Ll;if(u&&typeof i=="string"&&i){var v=Br(i);v='link[rel="'+a+'"][href="'+v+'"]',typeof o=="string"&&(v+='[crossorigin="'+o+'"]'),qw.has(v)||(qw.add(v),a={rel:a,crossOrigin:o,href:i},u.querySelector(v)===null&&(i=u.createElement("link"),Zt(i,"link",a),It(i),u.head.appendChild(i)))}}function rM(a){ea.D(a),Uw("dns-prefetch",a,null)}function nM(a,i){ea.C(a,i),Uw("preconnect",a,i)}function aM(a,i,o){ea.L(a,i,o);var u=Ll;if(u&&a&&i){var v='link[rel="preload"][as="'+Br(i)+'"]';i==="image"&&o&&o.imageSrcSet?(v+='[imagesrcset="'+Br(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(v+='[imagesizes="'+Br(o.imageSizes)+'"]')):v+='[href="'+Br(a)+'"]';var g=v;switch(i){case"style":g=Il(a);break;case"script":g=$l(a)}Xr.has(g)||(a=y({rel:"preload",href:i==="image"&&o&&o.imageSrcSet?void 0:a,as:i},o),Xr.set(g,a),u.querySelector(v)!==null||i==="style"&&u.querySelector(os(g))||i==="script"&&u.querySelector(ss(g))||(i=u.createElement("link"),Zt(i,"link",a),It(i),u.head.appendChild(i)))}}function iM(a,i){ea.m(a,i);var o=Ll;if(o&&a){var u=i&&typeof i.as=="string"?i.as:"script",v='link[rel="modulepreload"][as="'+Br(u)+'"][href="'+Br(a)+'"]',g=v;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=$l(a)}if(!Xr.has(g)&&(a=y({rel:"modulepreload",href:a},i),Xr.set(g,a),o.querySelector(v)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(ss(g)))return}u=o.createElement("link"),Zt(u,"link",a),It(u),o.head.appendChild(u)}}}function lM(a,i,o){ea.S(a,i,o);var u=Ll;if(u&&a){var v=ll(u).hoistableStyles,g=Il(a);i=i||"default";var S=v.get(g);if(!S){var E={loading:0,preload:null};if(S=u.querySelector(os(g)))E.loading=5;else{a=y({rel:"stylesheet",href:a,"data-precedence":i},o),(o=Xr.get(g))&&np(a,o);var I=S=u.createElement("link");It(I),Zt(I,"link",a),I._p=new Promise(function(V,re){I.onload=V,I.onerror=re}),I.addEventListener("load",function(){E.loading|=1}),I.addEventListener("error",function(){E.loading|=2}),E.loading|=4,xc(S,i,u)}S={type:"stylesheet",instance:S,count:1,state:E},v.set(g,S)}}}function oM(a,i){ea.X(a,i);var o=Ll;if(o&&a){var u=ll(o).hoistableScripts,v=$l(a),g=u.get(v);g||(g=o.querySelector(ss(v)),g||(a=y({src:a,async:!0},i),(i=Xr.get(v))&&ap(a,i),g=o.createElement("script"),It(g),Zt(g,"link",a),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(v,g))}}function sM(a,i){ea.M(a,i);var o=Ll;if(o&&a){var u=ll(o).hoistableScripts,v=$l(a),g=u.get(v);g||(g=o.querySelector(ss(v)),g||(a=y({src:a,async:!0,type:"module"},i),(i=Xr.get(v))&&ap(a,i),g=o.createElement("script"),It(g),Zt(g,"link",a),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(v,g))}}function Hw(a,i,o,u){var v=(v=pe.current)?gc(v):null;if(!v)throw Error(n(446));switch(a){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(i=Il(o.href),o=ll(v).hoistableStyles,u=o.get(i),u||(u={type:"style",instance:null,count:0,state:null},o.set(i,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){a=Il(o.href);var g=ll(v).hoistableStyles,S=g.get(a);if(S||(v=v.ownerDocument||v,S={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(a,S),(g=v.querySelector(os(a)))&&!g._p&&(S.instance=g,S.state.loading=5),Xr.has(a)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},Xr.set(a,o),g||uM(v,a,o,S.state))),i&&u===null)throw Error(n(528,""));return S}if(i&&u!==null)throw Error(n(529,""));return null;case"script":return i=o.async,o=o.src,typeof o=="string"&&i&&typeof i!="function"&&typeof i!="symbol"?(i=$l(o),o=ll(v).hoistableScripts,u=o.get(i),u||(u={type:"script",instance:null,count:0,state:null},o.set(i,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(n(444,a))}}function Il(a){return'href="'+Br(a)+'"'}function os(a){return'link[rel="stylesheet"]['+a+"]"}function Kw(a){return y({},a,{"data-precedence":a.precedence,precedence:null})}function uM(a,i,o,u){a.querySelector('link[rel="preload"][as="style"]['+i+"]")?u.loading=1:(i=a.createElement("link"),u.preload=i,i.addEventListener("load",function(){return u.loading|=1}),i.addEventListener("error",function(){return u.loading|=2}),Zt(i,"link",o),It(i),a.head.appendChild(i))}function $l(a){return'[src="'+Br(a)+'"]'}function ss(a){return"script[async]"+a}function Yw(a,i,o){if(i.count++,i.instance===null)switch(i.type){case"style":var u=a.querySelector('style[data-href~="'+Br(o.href)+'"]');if(u)return i.instance=u,It(u),u;var v=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(a.ownerDocument||a).createElement("style"),It(u),Zt(u,"style",v),xc(u,o.precedence,a),i.instance=u;case"stylesheet":v=Il(o.href);var g=a.querySelector(os(v));if(g)return i.state.loading|=4,i.instance=g,It(g),g;u=Kw(o),(v=Xr.get(v))&&np(u,v),g=(a.ownerDocument||a).createElement("link"),It(g);var S=g;return S._p=new Promise(function(E,I){S.onload=E,S.onerror=I}),Zt(g,"link",u),i.state.loading|=4,xc(g,o.precedence,a),i.instance=g;case"script":return g=$l(o.src),(v=a.querySelector(ss(g)))?(i.instance=v,It(v),v):(u=o,(v=Xr.get(g))&&(u=y({},o),ap(u,v)),a=a.ownerDocument||a,v=a.createElement("script"),It(v),Zt(v,"link",u),a.head.appendChild(v),i.instance=v);case"void":return null;default:throw Error(n(443,i.type))}else i.type==="stylesheet"&&(i.state.loading&4)===0&&(u=i.instance,i.state.loading|=4,xc(u,o.precedence,a));return i.instance}function xc(a,i,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),v=u.length?u[u.length-1]:null,g=v,S=0;S title"):null)}function cM(a,i,o){if(o===1||i.itemProp!=null)return!1;switch(a){case"meta":case"title":return!0;case"style":if(typeof i.precedence!="string"||typeof i.href!="string"||i.href==="")break;return!0;case"link":if(typeof i.rel!="string"||typeof i.href!="string"||i.href===""||i.onLoad||i.onError)break;switch(i.rel){case"stylesheet":return a=i.disabled,typeof i.precedence=="string"&&a==null;default:return!0}case"script":if(i.async&&typeof i.async!="function"&&typeof i.async!="symbol"&&!i.onLoad&&!i.onError&&i.src&&typeof i.src=="string")return!0}return!1}function Xw(a){return!(a.type==="stylesheet"&&(a.state.loading&3)===0)}function fM(a,i,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var v=Il(u.href),g=i.querySelector(os(v));if(g){i=g._p,i!==null&&typeof i=="object"&&typeof i.then=="function"&&(a.count++,a=wc.bind(a),i.then(a,a)),o.state.loading|=4,o.instance=g,It(g);return}g=i.ownerDocument||i,u=Kw(u),(v=Xr.get(v))&&np(u,v),g=g.createElement("link"),It(g);var S=g;S._p=new Promise(function(E,I){S.onload=E,S.onerror=I}),Zt(g,"link",u),o.instance=g}a.stylesheets===null&&(a.stylesheets=new Map),a.stylesheets.set(o,i),(i=o.state.preload)&&(o.state.loading&3)===0&&(a.count++,o=wc.bind(a),i.addEventListener("load",o),i.addEventListener("error",o))}}var ip=0;function dM(a,i){return a.stylesheets&&a.count===0&&_c(a,a.stylesheets),0ip?50:800)+i);return a.unsuspend=o,function(){a.unsuspend=null,clearTimeout(u),clearTimeout(v)}}:null}function wc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)_c(this,this.stylesheets);else if(this.unsuspend){var a=this.unsuspend;this.unsuspend=null,a()}}}var jc=null;function _c(a,i){a.stylesheets=null,a.unsuspend!==null&&(a.count++,jc=new Map,i.forEach(hM,a),jc=null,wc.call(a))}function hM(a,i){if(!(i.state.loading&4)){var o=jc.get(a);if(o)var u=o.get(null);else{o=new Map,jc.set(a,o);for(var v=a.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),pp.exports=TM(),pp.exports}var PM=DM();const zM=kn(PM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const RM=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),LM=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),gj=e=>{const t=LM(e);return t.charAt(0).toUpperCase()+t.slice(1)},HO=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),IM=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var $M={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const BM=b.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:l="",children:s,iconNode:c,...d},h)=>b.createElement("svg",{ref:h,...$M,width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:HO("lucide",l),...!s&&!IM(d)&&{"aria-hidden":"true"},...d},[...c.map(([m,p])=>b.createElement(m,p)),...Array.isArray(s)?s:[s]]));/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Se=(e,t)=>{const r=b.forwardRef(({className:n,...l},s)=>b.createElement(BM,{ref:s,iconNode:t,className:HO(`lucide-${RM(gj(e))}`,`lucide-${e}`,n),...l}));return r.displayName=gj(e),r};/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qM=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],xj=Se("activity",qM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const UM=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],bj=Se("arrow-right",UM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const HM=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],ra=Se("bot",HM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const KM=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],KO=Se("box",KM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const YM=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Zc=Se("check",YM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const GM=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],VM=Se("chevron-down",GM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const XM=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],FM=Se("chevron-left",XM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ZM=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],QM=Se("chevron-right",ZM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const WM=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],wj=Se("circle-alert",WM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const JM=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],jj=Se("clock",JM);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const eT=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],_j=Se("code",eT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const tT=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],ty=Se("credit-card",tT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const rT=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],nT=Se("database",rT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const aT=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],iT=Se("dollar-sign",aT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lT=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],YO=Se("external-link",lT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const oT=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Ns=Se("eye-off",oT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const sT=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Xl=Se("eye",sT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const uT=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Sj=Se("file-text",uT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Nj=Se("image",cT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fT=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],ry=Se("key",fT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const dT=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],hT=Se("layers",dT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mT=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],pT=Se("layout-dashboard",mT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vT=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Wa=Se("loader-circle",vT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yT=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],Oj=Se("lock-keyhole",yT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gT=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],xT=Se("lock",gT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bT=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],wT=Se("log-out",bT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jT=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],_T=Se("mail",jT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ST=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Fa=Se("message-square",ST);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const NT=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],ny=Se("package-check",NT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const OT=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],GO=Se("package",OT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const AT=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],Qc=Se("pen",AT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ET=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Hi=Se("plus",ET);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const CT=[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],kT=Se("power-off",CT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const MT=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],ay=Se("power",MT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const TT=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],Aj=Se("qr-code",TT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const DT=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],la=Se("refresh-cw",DT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const PT=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],oa=Se("save",PT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zT=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],RT=Se("search",zT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const LT=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],u0=Se("settings",LT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const IT=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],VO=Se("shield-check",IT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $T=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],XO=Se("shopping-bag",$T);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const BT=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],Ej=Se("shopping-cart",BT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qT=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],c0=Se("sparkles",qT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const UT=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],f0=Se("square-pen",UT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const HT=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],ei=Se("trash-2",HT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const KT=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],YT=Se("trending-up",KT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const GT=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],Cs=Se("truck",GT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const VT=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],XT=Se("upload",VT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const FT=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],ZT=Se("user-round",FT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const QT=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],iy=Se("user",QT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const WT=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],FO=Se("users",WT);/** + * @license lucide-react v0.562.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const JT=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],gr=Se("x",JT),eD=({activeTab:e,setActiveTab:t,onLogout:r})=>{const n=[{id:"dashboard",icon:pT,label:"仪表盘"},{id:"accounts",icon:FO,label:"账号管理"},{id:"orders",icon:XO,label:"订单管理"},{id:"cards",icon:ty,label:"卡密库存"},{id:"items",icon:KO,label:"商品列表"},{id:"keywords",icon:Fa,label:"自动化规则"},{id:"settings",icon:u0,label:"系统与AI"}];return f.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[f.jsxs("div",{className:"p-6",children:[f.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[f.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:f.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),f.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",f.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),f.jsx("nav",{className:"space-y-2",children:n.map(l=>{const s=l.icon,c=e===l.id;return f.jsxs("button",{onClick:()=>t(l.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${c?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[f.jsx(s,{className:`w-5 h-5 transition-colors ${c?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),f.jsx("span",{className:"text-sm tracking-wide",children:l.label}),c&&f.jsx(c0,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},l.id)})})]}),f.jsx("div",{className:"p-6 border-t border-gray-50",children:f.jsxs("button",{onClick:r,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[f.jsx(wT,{className:"w-5 h-5"}),f.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},tD=e=>{if(!e)return"";const t=new URLSearchParams;for(const[n,l]of Object.entries(e))l!=null&&t.set(n,String(l));const r=t.toString();return r?`?${r}`:""},ad=async(e,t,r={})=>{const n=tD(r.params),l=`${t}${n}`,s=await fetch(l,{method:e,credentials:"include",headers:{...r.body===void 0?{}:{"Content-Type":"application/json"}},body:r.body===void 0?void 0:JSON.stringify(r.body)}),d=(s.headers.get("content-type")||"").includes("application/json");if(!s.ok){const h=d?await s.json().catch(()=>{}):await s.text().catch(()=>{}),m=typeof h=="string"?h:(h==null?void 0:h.detail)||(h==null?void 0:h.message)||(h==null?void 0:h.msg);throw new Error(m||`请求失败: ${s.status}`)}return d?await s.json():await s.text()},Pt=async(e,t)=>ad("GET",e,{params:t}),Ir=async(e,t)=>ad("POST",e,{body:t}),ar=async(e,t)=>ad("PUT",e,{body:t}),uo=async(e,t)=>ad("DELETE",e,{params:t}),rD=async e=>Ir("/login",e),ZO=async()=>Pt("/verify"),nD=async e=>ar("/account/credentials",e),aD=async(e,t)=>Ir("/cookies",{id:e,value:t}),iD=(e,t)=>{const r=e.avatar_url||"";if(!r)return"";try{const n=new URL(r,window.location.origin);return n.hostname.endsWith("alicdn.com")&&n.searchParams.set("_v",t),n.toString()}catch{return r}},d0=async()=>{const e=await Pt("/cookies/details"),t=Date.now().toString();return e.map(r=>({id:r.id,value:"",cookie:"",enabled:r.enabled,auto_confirm:r.auto_confirm,remark:r.remark,note:r.remark,pause_duration:r.pause_duration,username:r.username||"",login_password:"",show_browser:r.show_browser,nickname:r.nickname||r.remark||`账号 ${r.id.substring(0,6)}`,avatar_url:iD(r,t),profile_error:r.profile_error||"",ai_enabled:!1}))},lD=async()=>Pt("/cookies/runtime-status"),oD=async()=>Ir("/qr-login/generate"),sD=async e=>Pt(`/qr-login/check/${e}`),uD=async(e,t)=>ar(`/cookies/${e}/status`,{enabled:t}),cD=async e=>uo(`/cookies/${e}`),fD=async(e,t)=>ar(`/cookies/${e}/remark`,{remark:t}),dD=async(e,t)=>ar(`/cookies/${e}/auto-confirm`,{auto_confirm:t}),hD=async(e,t)=>ar(`/cookies/${e}/pause-duration`,{pause_duration:t}),mD=async(e,t)=>ar(`/cookies/${e}`,{id:e,value:t}),pD=async(e,t)=>ar(`/cookies/${e}/login-info`,t),vD=async()=>Pt("/ai-reply-settings"),Cj=async(e,t,r=1,n=20)=>{const l={page:r,page_size:n};t&&t!=="all"&&(l.status=t);const s=await Pt("/api/orders",l),d=(s.orders||s.data||[]).map(h=>({...h,id:h.id||h.order_id,status:h.status||h.order_status||"processing",quantity:Number(h.quantity||1)}));return{success:!0,data:d,total:s.total||d.length,page:s.page||r,page_size:s.page_size||n,total_pages:s.total_pages||1}},yD=async(e,t)=>ar(`/api/orders/${e}`,t),gD=async e=>uo(`/api/orders/${e}`),xD=async(e,t)=>{const r=new FormData,n=await fetch("/api/orders/refresh",{method:"POST",credentials:"include",body:r}),l=await n.json().catch(()=>({}));if(!n.ok||l.success===!1)throw new Error(l.detail||l.message||`订单同步失败: ${n.status}`);return l},bD=async e=>Ir(`/api/orders/${e}/refresh`),wD=async(e,t,r)=>Ir("/api/orders/manual-ship",{order_ids:e,ship_mode:t,custom_content:r}),jD=async e=>{const t=e instanceof FormData,r=await fetch("/api/orders/import",{method:"POST",credentials:"include",headers:{...t?{}:{"Content-Type":"application/json"}},body:t?e:JSON.stringify(e)}),n=await r.json().catch(()=>({}));if(!r.ok||n.success===!1)throw new Error(n.detail||n.message||`订单导入失败: ${r.status}`);return n},_D=async()=>Pt("/admin/stats"),kj=async(e=7)=>{let t;if(typeof e=="number"){const r=new Date,n=new Date;n.setDate(n.getDate()-e),t={start_date:n.toISOString().split("T")[0],end_date:r.toISOString().split("T")[0]}}else t=e;return Pt("/analytics/orders",t)},SD=async e=>(await Pt("/analytics/orders/valid",{start_date:e.start_date,end_date:e.end_date})).orders||[],ND=e=>{let t=e.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...e,api_config:t||void 0}},QO=e=>({...e,api_config:e.api_config?JSON.stringify(e.api_config):""}),Gl=async()=>{const e=await Pt("/cards");return(Array.isArray(e)?e:e.cards||[]).map(ND)},OD=async e=>Ir("/cards",QO(e)),Mj=async(e,t)=>ar(`/cards/${e}`,QO(t)),AD=async e=>uo(`/cards/${e}`),id=async()=>{const e=await Pt("/items");return(Array.isArray(e)?e:e.items||[]).map(r=>({...r,id:r.id||`${r.cookie_id}-${r.item_id}`,is_multi_qty_ship:r.is_multi_qty_ship??r.multi_quantity_delivery??!1}))},ED=async e=>Ir("/items/get-all-from-account",{cookie_id:e}),CD=async(e,t)=>uo(`/items/${e}/${t}`),kD=async(e,t)=>Ir(`/items/${e}`,t),MD=async(e,t,r)=>ar(`/items/${e}/${t}`,r),TD=async(e,t,r)=>ar(`/items/${e}/${t}/multi-spec`,{is_multi_spec:r}),DD=async(e,t,r)=>ar(`/items/${e}/${t}/multi-quantity-delivery`,{multi_quantity_delivery:r}),PD=async()=>{const e=await Pt("/delivery-rules");return(Array.isArray(e)?e:e.data||e.rules||[]).map(r=>({id:String(r.id),name:r.description||r.keyword||"",item_keyword:r.keyword||"",cookie_id:r.cookie_id||"",item_id:r.item_id||"",item_title:r.item_title||"",card_group_id:r.card_id||0,card_group_name:r.card_name||"",priority:r.delivery_count||1,enabled:r.enabled||!1,variants:(r.variants||[]).map(n=>({id:n.id?String(n.id):void 0,spec_name:n.spec_name||"",spec_value:n.spec_value||"",card_id:Number(n.card_id||0),card_name:n.card_name||"",card_type:n.card_type,delivery_count:Number(n.delivery_count||1),enabled:n.enabled!==!1}))}))},Tj=async e=>{const t={keyword:e.item_keyword,cookie_id:e.cookie_id||"",item_id:e.item_id||"",card_id:e.card_group_id,delivery_count:e.priority,enabled:e.enabled??!0,description:e.name,variants:e.variants||[]};return e.id?ar(`/delivery-rules/${e.id}`,t):Ir("/delivery-rules",t)},zD=async e=>uo(`/delivery-rules/${e}`),RD=async e=>{if(!e)return[];const t=await Pt(`/keywords-with-item-id/${e}`);return(Array.isArray(t)?t:[]).map((n,l)=>({id:String(l),keyword:n.keyword||"",reply_content:n.reply||"",match_type:"exact",enabled:!0}))},LD=async(e,t)=>{const r=await Pt(`/keywords-with-item-id/${t}`),n=Array.isArray(r)?r:[];if(e.id){const l=parseInt(e.id);l>=0&&l{const r=await Pt(`/keywords-with-item-id/${t}`),n=Array.isArray(r)?r:[],l=parseInt(e);return l>=0&&l{const e=await Pt("/system-settings");return e.data||e},BD=async e=>{const t=Object.entries(e).map(([r,n])=>ar(`/system-settings/${r}`,{value:String(n)}));return await Promise.all(t),{success:!0,message:"Settings saved"}},qD=async e=>Pt(`/ai-reply-settings/${e}`),UD=async(e,t)=>{const r={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ar(`/ai-reply-settings/${e}`,r)},HD=async(e,t="")=>(await Ir("/ai-models",{base_url:e,api_key:t})).models||[],KD=async()=>Pt("/api/default-replies"),YD=async e=>{const t=await Pt(`/api/default-reply/${e}`);return{cookie_id:e,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},GD=async(e,t)=>ar(`/api/default-reply/${e}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),VD=async e=>uo(`/api/default-reply/${e}`),XD=async e=>Ir(`/api/default-reply/${e}/clear-records`,{});function WO(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var l=e.length;for(t=0;t{var{children:r,width:n,height:l,viewBox:s,className:c,style:d,title:h,desc:m}=e,p=eP(e,JD),y=s||{width:n,height:l,x:0,y:0},x=Ue("recharts-surface",c);return b.createElement("svg",ly({},ur(p),{className:x,width:n,height:l,style:d,viewBox:"".concat(y.x," ").concat(y.y," ").concat(y.width," ").concat(y.height),ref:t}),b.createElement("title",null,h),b.createElement("desc",null,m),r)}),rP=["children","className"];function oy(){return oy=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var{children:r,className:n}=e,l=nP(e,rP),s=Ue("recharts-layer",n);return b.createElement("g",oy({className:s},ur(l),{ref:t}),r)}),Jt=UO(),tA=b.createContext(null),iP=()=>b.useContext(tA);function tt(e){return function(){return e}}const rA=Math.cos,of=Math.sin,mn=Math.sqrt,sf=Math.PI,ld=2*sf,sy=Math.PI,uy=2*sy,Mi=1e-6,lP=uy-Mi;function nA(e){this._+=e[0];for(let t=1,r=e.length;t=0))throw new Error(`invalid digits: ${e}`);if(t>15)return nA;const r=10**t;return function(n){this._+=n[0];for(let l=1,s=n.length;lMi)if(!(Math.abs(y*h-m*p)>Mi)||!s)this._append`L${this._x1=t},${this._y1=r}`;else{let w=n-c,j=l-d,_=h*h+m*m,N=w*w+j*j,A=Math.sqrt(_),O=Math.sqrt(x),P=s*Math.tan((sy-Math.acos((_+x-N)/(2*A*O)))/2),k=P/O,z=P/A;Math.abs(k-1)>Mi&&this._append`L${t+k*p},${r+k*y}`,this._append`A${s},${s},0,0,${+(y*w>p*j)},${this._x1=t+z*h},${this._y1=r+z*m}`}}arc(t,r,n,l,s,c){if(t=+t,r=+r,n=+n,c=!!c,n<0)throw new Error(`negative radius: ${n}`);let d=n*Math.cos(l),h=n*Math.sin(l),m=t+d,p=r+h,y=1^c,x=c?l-s:s-l;this._x1===null?this._append`M${m},${p}`:(Math.abs(this._x1-m)>Mi||Math.abs(this._y1-p)>Mi)&&this._append`L${m},${p}`,n&&(x<0&&(x=x%uy+uy),x>lP?this._append`A${n},${n},0,1,${y},${t-d},${r-h}A${n},${n},0,1,${y},${this._x1=m},${this._y1=p}`:x>Mi&&this._append`A${n},${n},0,${+(x>=sy)},${y},${this._x1=t+n*Math.cos(s)},${this._y1=r+n*Math.sin(s)}`)}rect(t,r,n,l){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+l}h${-n}Z`}toString(){return this._}}function p0(e){let t=3;return e.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return e},()=>new sP(t)}function v0(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function aA(e){this._context=e}aA.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function od(e){return new aA(e)}function iA(e){return e[0]}function lA(e){return e[1]}function oA(e,t){var r=tt(!0),n=null,l=od,s=null,c=p0(d);e=typeof e=="function"?e:e===void 0?iA:tt(e),t=typeof t=="function"?t:t===void 0?lA:tt(t);function d(h){var m,p=(h=v0(h)).length,y,x=!1,w;for(n==null&&(s=l(w=c())),m=0;m<=p;++m)!(m=w;--j)d.point(P[j],k[j]);d.lineEnd(),d.areaEnd()}A&&(P[x]=+e(N,x,y),k[x]=+t(N,x,y),d.point(n?+n(N,x,y):P[x],r?+r(N,x,y):k[x]))}if(O)return d=null,O+""||null}function p(){return oA().defined(l).curve(c).context(s)}return m.x=function(y){return arguments.length?(e=typeof y=="function"?y:tt(+y),n=null,m):e},m.x0=function(y){return arguments.length?(e=typeof y=="function"?y:tt(+y),m):e},m.x1=function(y){return arguments.length?(n=y==null?null:typeof y=="function"?y:tt(+y),m):n},m.y=function(y){return arguments.length?(t=typeof y=="function"?y:tt(+y),r=null,m):t},m.y0=function(y){return arguments.length?(t=typeof y=="function"?y:tt(+y),m):t},m.y1=function(y){return arguments.length?(r=y==null?null:typeof y=="function"?y:tt(+y),m):r},m.lineX0=m.lineY0=function(){return p().x(e).y(t)},m.lineY1=function(){return p().x(e).y(r)},m.lineX1=function(){return p().x(n).y(t)},m.defined=function(y){return arguments.length?(l=typeof y=="function"?y:tt(!!y),m):l},m.curve=function(y){return arguments.length?(c=y,s!=null&&(d=c(s)),m):c},m.context=function(y){return arguments.length?(y==null?s=d=null:d=c(s=y),m):s},m}class sA{constructor(t,r){this._context=t,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function uP(e){return new sA(e,!0)}function cP(e){return new sA(e,!1)}const y0={draw(e,t){const r=mn(t/sf);e.moveTo(r,0),e.arc(0,0,r,0,ld)}},fP={draw(e,t){const r=mn(t/5)/2;e.moveTo(-3*r,-r),e.lineTo(-r,-r),e.lineTo(-r,-3*r),e.lineTo(r,-3*r),e.lineTo(r,-r),e.lineTo(3*r,-r),e.lineTo(3*r,r),e.lineTo(r,r),e.lineTo(r,3*r),e.lineTo(-r,3*r),e.lineTo(-r,r),e.lineTo(-3*r,r),e.closePath()}},uA=mn(1/3),dP=uA*2,hP={draw(e,t){const r=mn(t/dP),n=r*uA;e.moveTo(0,-r),e.lineTo(n,0),e.lineTo(0,r),e.lineTo(-n,0),e.closePath()}},mP={draw(e,t){const r=mn(t),n=-r/2;e.rect(n,n,r,r)}},pP=.8908130915292852,cA=of(sf/10)/of(7*sf/10),vP=of(ld/10)*cA,yP=-rA(ld/10)*cA,gP={draw(e,t){const r=mn(t*pP),n=vP*r,l=yP*r;e.moveTo(0,-r),e.lineTo(n,l);for(let s=1;s<5;++s){const c=ld*s/5,d=rA(c),h=of(c);e.lineTo(h*r,-d*r),e.lineTo(d*n-h*l,h*n+d*l)}e.closePath()}},xp=mn(3),xP={draw(e,t){const r=-mn(t/(xp*3));e.moveTo(0,r*2),e.lineTo(-xp*r,-r),e.lineTo(xp*r,-r),e.closePath()}},Fr=-.5,Zr=mn(3)/2,cy=1/mn(12),bP=(cy/2+1)*3,wP={draw(e,t){const r=mn(t/bP),n=r/2,l=r*cy,s=n,c=r*cy+r,d=-s,h=c;e.moveTo(n,l),e.lineTo(s,c),e.lineTo(d,h),e.lineTo(Fr*n-Zr*l,Zr*n+Fr*l),e.lineTo(Fr*s-Zr*c,Zr*s+Fr*c),e.lineTo(Fr*d-Zr*h,Zr*d+Fr*h),e.lineTo(Fr*n+Zr*l,Fr*l-Zr*n),e.lineTo(Fr*s+Zr*c,Fr*c-Zr*s),e.lineTo(Fr*d+Zr*h,Fr*h-Zr*d),e.closePath()}};function jP(e,t){let r=null,n=p0(l);e=typeof e=="function"?e:tt(e||y0),t=typeof t=="function"?t:tt(t===void 0?64:+t);function l(){let s;if(r||(r=s=n()),e.apply(this,arguments).draw(r,+t.apply(this,arguments)),s)return r=null,s+""||null}return l.type=function(s){return arguments.length?(e=typeof s=="function"?s:tt(s),l):e},l.size=function(s){return arguments.length?(t=typeof s=="function"?s:tt(+s),l):t},l.context=function(s){return arguments.length?(r=s??null,l):r},l}function uf(){}function cf(e,t,r){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+r)/6)}function fA(e){this._context=e}fA.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:cf(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:cf(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function _P(e){return new fA(e)}function dA(e){this._context=e}dA.prototype={areaStart:uf,areaEnd:uf,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:cf(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function SP(e){return new dA(e)}function hA(e){this._context=e}hA.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+e)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:cf(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function NP(e){return new hA(e)}function mA(e){this._context=e}mA.prototype={areaStart:uf,areaEnd:uf,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function OP(e){return new mA(e)}function Dj(e){return e<0?-1:1}function Pj(e,t,r){var n=e._x1-e._x0,l=t-e._x1,s=(e._y1-e._y0)/(n||l<0&&-0),c=(r-e._y1)/(l||n<0&&-0),d=(s*l+c*n)/(n+l);return(Dj(s)+Dj(c))*Math.min(Math.abs(s),Math.abs(c),.5*Math.abs(d))||0}function zj(e,t){var r=e._x1-e._x0;return r?(3*(e._y1-e._y0)/r-t)/2:t}function bp(e,t,r){var n=e._x0,l=e._y0,s=e._x1,c=e._y1,d=(s-n)/3;e._context.bezierCurveTo(n+d,l+d*t,s-d,c-d*r,s,c)}function ff(e){this._context=e}ff.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:bp(this,this._t0,zj(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var r=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,bp(this,zj(this,r=Pj(this,e,t)),r);break;default:bp(this,this._t0,r=Pj(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=r}}};function pA(e){this._context=new vA(e)}(pA.prototype=Object.create(ff.prototype)).point=function(e,t){ff.prototype.point.call(this,t,e)};function vA(e){this._context=e}vA.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,r,n,l,s){this._context.bezierCurveTo(t,e,n,r,s,l)}};function AP(e){return new ff(e)}function EP(e){return new pA(e)}function yA(e){this._context=e}yA.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,r=e.length;if(r)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),r===2)this._context.lineTo(e[1],t[1]);else for(var n=Rj(e),l=Rj(t),s=0,c=1;c=0;--t)l[t]=(c[t]-l[t+1])/s[t];for(s[r-1]=(e[r]+l[r-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var r=this._x*(1-this._t)+e*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=e,this._y=t}};function kP(e){return new sd(e,.5)}function MP(e){return new sd(e,0)}function TP(e){return new sd(e,1)}function Yi(e,t){if((c=e.length)>1)for(var r=1,n,l,s=e[t[0]],c,d=s.length;r=0;)r[t]=t;return r}function DP(e,t){return e[t]}function PP(e){const t=[];return t.key=e,t}function zP(){var e=tt([]),t=fy,r=Yi,n=DP;function l(s){var c=Array.from(e.apply(this,arguments),PP),d,h=c.length,m=-1,p;for(const y of s)for(d=0,++m;d0){for(var r,n,l=0,s=e[0].length,c;l0){for(var r=0,n=e[t[0]],l,s=n.length;r0)||!((s=(l=e[t[0]]).length)>0))){for(var r=0,n=1,l,s,c;n1&&arguments[1]!==void 0?arguments[1]:HP,r=10**t,n=Math.round(e*r)/r;return Object.is(n,-0)?0:n}function yt(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n{var d=r[c-1];return typeof d=="string"?l+d+s:d!==void 0?l+ti(d)+s:l+s},"")}var Ht=e=>e===0?0:e>0?1:-1,dn=e=>typeof e=="number"&&e!=+e,Vi=e=>typeof e=="string"&&e.indexOf("%")===e.length-1,de=e=>(typeof e=="number"||e instanceof Number)&&!dn(e),An=e=>de(e)||typeof e=="string",KP=0,Ms=e=>{var t=++KP;return"".concat(e||"").concat(t)},nr=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!de(t)&&typeof t!="string")return n;var s;if(Vi(t)){if(r==null)return n;var c=t.indexOf("%");s=r*parseFloat(t.slice(0,c))/100}else s=+t;return dn(s)&&(s=n),l&&r!=null&&s>r&&(s=r),s},xA=e=>{if(!Array.isArray(e))return!1;for(var t=e.length,r={},n=0;nn&&(typeof t=="function"?t(n):Gi(n,t))===r)}var xt=e=>e===null||typeof e>"u",Gs=e=>xt(e)?e:"".concat(e.charAt(0).toUpperCase()).concat(e.slice(1));function xr(e){return e!=null}function Ji(){}var YP=["type","size","sizeType"];function dy(){return dy=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var t="symbol".concat(Gs(e));return wA[t]||y0},JP=(e,t,r)=>{if(t==="area")return e;switch(r){case"cross":return 5*e*e/9;case"diamond":return .5*e*e/Math.sqrt(3);case"square":return e*e;case"star":{var n=18*QP;return 1.25*e*e*(Math.tan(n)-Math.tan(n*2)*Math.tan(n)**2)}case"triangle":return Math.sqrt(3)*e*e/4;case"wye":return(21-10*Math.sqrt(3))*e*e/8;default:return Math.PI*e*e/4}},e6=(e,t)=>{wA["symbol".concat(Gs(e))]=t},w0=e=>{var{type:t="circle",size:r=64,sizeType:n="area"}=e,l=FP(e,YP),s=Yj(Yj({},l),{},{type:t,size:r,sizeType:n}),c="circle";typeof t=="string"&&(c=t);var d=()=>{var x=WP(c),w=jP().type(x).size(JP(r,n,c)),j=w();if(j!==null)return j},{className:h,cx:m,cy:p}=s,y=ur(s);return de(m)&&de(p)&&de(r)?b.createElement("path",dy({},y,{className:Ue("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(p,")"),d:d()})):null};w0.registerSymbol=e6;var jA=e=>"radius"in e&&"startAngle"in e&&"endAngle"in e,j0=(e,t)=>{if(!e||typeof e=="function"||typeof e=="boolean")return null;var r=e;if(b.isValidElement(e)&&(r=e.props),typeof r!="object"&&typeof r!="function")return null;var n={};return Object.keys(r).forEach(l=>{h0(l)&&(n[l]=(s=>r[l](r,s)))}),n},t6=(e,t,r)=>n=>(e(t,r,n),null),Vs=(e,t,r)=>{if(e===null||typeof e!="object"&&typeof e!="function")return null;var n=null;return Object.keys(e).forEach(l=>{var s=e[l];h0(l)&&typeof s=="function"&&(n||(n={}),n[l]=t6(s,t,r))}),n};function Gj(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function r6(e){for(var t=1;t(c[d]===void 0&&n[d]!==void 0&&(c[d]=n[d]),c),r);return s}function df(){return df=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var x=p.formatter||l,w=Ue({"recharts-legend-item":!0,["legend-item-".concat(y)]:!0,inactive:p.inactive});if(p.type==="none")return null;var j=p.inactive?s:p.color,_=x?x(p.value,p,y):p.value;return b.createElement("li",df({className:w,style:h,key:"legend-item-".concat(y)},Vs(e,p,y)),b.createElement(m0,{width:r,height:r,viewBox:d,style:m,"aria-label":"".concat(_," legend icon")},b.createElement(f6,{data:p,iconType:c,inactiveColor:s})),b.createElement("span",{className:"recharts-legend-item-text",style:{color:j}},_))})}var h6=e=>{var t=Mt(e,c6),{payload:r,layout:n,align:l}=t;if(!r||!r.length)return null;var s={padding:0,margin:0,textAlign:n==="horizontal"?l:"left"};return b.createElement("ul",{className:"recharts-default-legend",style:s},b.createElement(d6,df({},t,{payload:r})))},Ep={},Cp={},Xj;function m6(){return Xj||(Xj=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r,n){const l=new Map;for(let s=0;s=0}e.isLength=t})(Pp)),Pp}var Wj;function _0(){return Wj||(Wj=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=v6();function r(n){return n!=null&&typeof n!="function"&&t.isLength(n.length)}e.isArrayLike=r})(Dp)),Dp}var zp={},Jj;function y6(){return Jj||(Jj=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return typeof r=="object"&&r!==null}e.isObjectLike=t})(zp)),zp}var e_;function g6(){return e_||(e_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=_0(),r=y6();function n(l){return r.isObjectLike(l)&&t.isArrayLike(l)}e.isArrayLikeObject=n})(Tp)),Tp}var Rp={},Lp={},t_;function x6(){return t_||(t_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=b0();function r(n){return function(l){return t.get(l,n)}}e.property=r})(Lp)),Lp}var Ip={},$p={},Bp={},qp={},r_;function SA(){return r_||(r_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return r!==null&&(typeof r=="object"||typeof r=="function")}e.isObject=t})(qp)),qp}var Up={},n_;function NA(){return n_||(n_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return r==null||typeof r!="object"&&typeof r!="function"}e.isPrimitive=t})(Up)),Up}var Hp={},a_;function OA(){return a_||(a_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r,n){return r===n||Number.isNaN(r)&&Number.isNaN(n)}e.isEqualsSameValueZero=t})(Hp)),Hp}var i_;function b6(){return i_||(i_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=SA(),r=NA(),n=OA();function l(p,y,x){return typeof x!="function"?l(p,y,()=>{}):s(p,y,function w(j,_,N,A,O,P){const k=x(j,_,N,A,O,P);return k!==void 0?!!k:s(j,_,w,P)},new Map)}function s(p,y,x,w){if(y===p)return!0;switch(typeof y){case"object":return c(p,y,x,w);case"function":return Object.keys(y).length>0?s(p,{...y},x,w):n.isEqualsSameValueZero(p,y);default:return t.isObject(p)?typeof y=="string"?y==="":!0:n.isEqualsSameValueZero(p,y)}}function c(p,y,x,w){if(y==null)return!0;if(Array.isArray(y))return h(p,y,x,w);if(y instanceof Map)return d(p,y,x,w);if(y instanceof Set)return m(p,y,x,w);const j=Object.keys(y);if(p==null||r.isPrimitive(p))return j.length===0;if(j.length===0)return!0;if(w!=null&&w.has(y))return w.get(y)===p;w==null||w.set(y,p);try{for(let _=0;_{})}e.isMatch=r})($p)),$p}var Kp={},Yp={},Gp={},o_;function w6(){return o_||(o_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return Object.getOwnPropertySymbols(r).filter(n=>Object.prototype.propertyIsEnumerable.call(r,n))}e.getSymbols=t})(Gp)),Gp}var Vp={},s_;function S0(){return s_||(s_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}e.getTag=t})(Vp)),Vp}var Xp={},u_;function EA(){return u_||(u_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t="[object RegExp]",r="[object String]",n="[object Number]",l="[object Boolean]",s="[object Arguments]",c="[object Symbol]",d="[object Date]",h="[object Map]",m="[object Set]",p="[object Array]",y="[object Function]",x="[object ArrayBuffer]",w="[object Object]",j="[object Error]",_="[object DataView]",N="[object Uint8Array]",A="[object Uint8ClampedArray]",O="[object Uint16Array]",P="[object Uint32Array]",k="[object BigUint64Array]",z="[object Int8Array]",T="[object Int16Array]",R="[object Int32Array]",$="[object BigInt64Array]",Z="[object Float32Array]",X="[object Float64Array]";e.argumentsTag=s,e.arrayBufferTag=x,e.arrayTag=p,e.bigInt64ArrayTag=$,e.bigUint64ArrayTag=k,e.booleanTag=l,e.dataViewTag=_,e.dateTag=d,e.errorTag=j,e.float32ArrayTag=Z,e.float64ArrayTag=X,e.functionTag=y,e.int16ArrayTag=T,e.int32ArrayTag=R,e.int8ArrayTag=z,e.mapTag=h,e.numberTag=n,e.objectTag=w,e.regexpTag=t,e.setTag=m,e.stringTag=r,e.symbolTag=c,e.uint16ArrayTag=O,e.uint32ArrayTag=P,e.uint8ArrayTag=N,e.uint8ClampedArrayTag=A})(Xp)),Xp}var Fp={},c_;function j6(){return c_||(c_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}e.isTypedArray=t})(Fp)),Fp}var f_;function CA(){return f_||(f_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=w6(),r=S0(),n=EA(),l=NA(),s=j6();function c(p,y){return d(p,void 0,p,new Map,y)}function d(p,y,x,w=new Map,j=void 0){const _=j==null?void 0:j(p,y,x,w);if(_!==void 0)return _;if(l.isPrimitive(p))return p;if(w.has(p))return w.get(p);if(Array.isArray(p)){const N=new Array(p.length);w.set(p,N);for(let A=0;At.isMatch(s,l)}e.matches=n})(Ip)),Ip}var Zp={},Qp={},Wp={},m_;function N6(){return m_||(m_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=CA(),r=S0(),n=EA();function l(s,c){return t.cloneDeepWith(s,(d,h,m,p)=>{const y=c==null?void 0:c(d,h,m,p);if(y!==void 0)return y;if(typeof s=="object"){if(r.getTag(s)===n.objectTag&&typeof s.constructor!="function"){const x={};return p.set(s,x),t.copyProperties(x,s,m,p),x}switch(Object.prototype.toString.call(s)){case n.numberTag:case n.stringTag:case n.booleanTag:{const x=new s.constructor(s==null?void 0:s.valueOf());return t.copyProperties(x,s),x}case n.argumentsTag:{const x={};return t.copyProperties(x,s),x.length=s.length,x[Symbol.iterator]=s[Symbol.iterator],x}default:return}}})}e.cloneDeepWith=l})(Wp)),Wp}var p_;function O6(){return p_||(p_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=N6();function r(n){return t.cloneDeepWith(n)}e.cloneDeep=r})(Qp)),Qp}var Jp={},ev={},v_;function kA(){return v_||(v_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=/^(?:0|[1-9]\d*)$/;function r(n,l=Number.MAX_SAFE_INTEGER){switch(typeof n){case"number":return Number.isInteger(n)&&n>=0&&n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?m:d;return lv.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,lv}var N_;function z6(){return N_||(N_=1,iv.exports=P6()),iv.exports}/** + * @license React + * use-sync-external-store-shim/with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var O_;function R6(){if(O_)return av;O_=1;var e=so(),t=z6();function r(m,p){return m===p&&(m!==0||1/m===1/p)||m!==m&&p!==p}var n=typeof Object.is=="function"?Object.is:r,l=t.useSyncExternalStore,s=e.useRef,c=e.useEffect,d=e.useMemo,h=e.useDebugValue;return av.useSyncExternalStoreWithSelector=function(m,p,y,x,w){var j=s(null);if(j.current===null){var _={hasValue:!1,value:null};j.current=_}else _=j.current;j=d(function(){function A(T){if(!O){if(O=!0,P=T,T=x(T),w!==void 0&&_.hasValue){var R=_.value;if(w(R,T))return k=R}return k=T}if(R=k,n(P,T))return R;var $=x(T);return w!==void 0&&w(R,$)?(P=T,R):(P=T,k=$)}var O=!1,P,k,z=y===void 0?null:y;return[function(){return A(p())},z===null?void 0:function(){return A(z())}]},[p,y,x,w]);var N=l(m,j[0],j[1]);return c(function(){_.hasValue=!0,_.value=N},[N]),h(N),N},av}var A_;function L6(){return A_||(A_=1,nv.exports=R6()),nv.exports}var I6=L6(),N0=b.createContext(null),$6=e=>e,rt=()=>{var e=b.useContext(N0);return e?e.store.dispatch:$6},Wc=()=>{},B6=()=>Wc,q6=(e,t)=>e===t;function ge(e){var t=b.useContext(N0),r=b.useMemo(()=>t?n=>{if(n!=null)return e(n)}:Wc,[t,e]);return I6.useSyncExternalStoreWithSelector(t?t.subscription.addNestedSub:B6,t?t.store.getState:Wc,t?t.store.getState:Wc,r,q6)}function U6(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!="function")throw new TypeError(t)}function H6(e,t=`expected an object, instead received ${typeof e}`){if(typeof e!="object")throw new TypeError(t)}function K6(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(r=>typeof r=="function")){const r=e.map(n=>typeof n=="function"?`function ${n.name||"unnamed"}()`:typeof n).join(", ");throw new TypeError(`${t}[${r}]`)}}var E_=e=>Array.isArray(e)?e:[e];function Y6(e){const t=Array.isArray(e[0])?e[0]:e;return K6(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function G6(e,t){const r=[],{length:n}=e;for(let l=0;l{r=Tc(),c.resetResultsCount()},c.resultsCount=()=>s,c.resetResultsCount=()=>{s=0},c}function Z6(e,...t){const r=typeof e=="function"?{memoize:e,memoizeOptions:t}:e,n=(...l)=>{let s=0,c=0,d,h={},m=l.pop();typeof m=="object"&&(h=m,m=l.pop()),U6(m,`createSelector expects an output function after the inputs, but received: [${typeof m}]`);const p={...r,...h},{memoize:y,memoizeOptions:x=[],argsMemoize:w=TA,argsMemoizeOptions:j=[]}=p,_=E_(x),N=E_(j),A=Y6(l),O=y(function(){return s++,m.apply(null,arguments)},..._),P=w(function(){c++;const z=G6(A,arguments);return d=O.apply(null,z),d},...N);return Object.assign(P,{resultFunc:m,memoizedResultFunc:O,dependencies:A,dependencyRecomputations:()=>c,resetDependencyRecomputations:()=>{c=0},lastResult:()=>d,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:y,argsMemoize:w})};return Object.assign(n,{withTypes:()=>n}),n}var Y=Z6(TA),Q6=Object.assign((e,t=Y)=>{H6(e,`createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof e}`);const r=Object.keys(e),n=r.map(s=>e[s]);return t(n,(...s)=>s.reduce((c,d,h)=>(c[r[h]]=d,c),{}))},{withTypes:()=>Q6}),ov={},sv={},uv={},k_;function W6(){return k_||(k_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return typeof n=="symbol"?1:n===null?2:n===void 0?3:n!==n?4:0}const r=(n,l,s)=>{if(n!==l){const c=t(n),d=t(l);if(c===d&&c===0){if(nl)return s==="desc"?-1:1}return s==="desc"?d-c:c-d}return 0};e.compareValues=r})(uv)),uv}var cv={},fv={},M_;function DA(){return M_||(M_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return typeof r=="symbol"||r instanceof Symbol}e.isSymbol=t})(fv)),fv}var T_;function J6(){return T_||(T_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=DA(),r=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,n=/^\w*$/;function l(s,c){return Array.isArray(s)?!1:typeof s=="number"||typeof s=="boolean"||s==null||t.isSymbol(s)?!0:typeof s=="string"&&(n.test(s)||!r.test(s))||c!=null&&Object.hasOwn(c,s)}e.isKey=l})(cv)),cv}var D_;function ez(){return D_||(D_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=W6(),r=J6(),n=x0();function l(s,c,d,h){if(s==null)return[];d=h?void 0:d,Array.isArray(s)||(s=Object.values(s)),Array.isArray(c)||(c=c==null?[null]:[c]),c.length===0&&(c=[null]),Array.isArray(d)||(d=d==null?[]:[d]),d=d.map(w=>String(w));const m=(w,j)=>{let _=w;for(let N=0;Nj==null||w==null?j:typeof w=="object"&&"key"in w?Object.hasOwn(j,w.key)?j[w.key]:m(j,w.path):typeof w=="function"?w(j):Array.isArray(w)?m(j,w):typeof j=="object"?j[w]:j,y=c.map(w=>(Array.isArray(w)&&w.length===1&&(w=w[0]),w==null||typeof w=="function"||Array.isArray(w)||r.isKey(w)?w:{key:w,path:n.toPath(w)}));return s.map(w=>({original:w,criteria:y.map(j=>p(j,w))})).slice().sort((w,j)=>{for(let _=0;_w.original)}e.orderBy=l})(sv)),sv}var dv={},P_;function tz(){return P_||(P_=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r,n=1){const l=[],s=Math.floor(n),c=(d,h)=>{for(let m=0;m1&&n.isIterateeCall(s,c[0],c[1])?c=[]:d>2&&n.isIterateeCall(c[0],c[1],c[2])&&(c=[c[0]]),t.orderBy(s,r.flatten(c),["asc"])}e.sortBy=l})(ov)),ov}var mv,L_;function nz(){return L_||(L_=1,mv=rz().sortBy),mv}var az=nz();const ud=kn(az);var zA=e=>e.legend.settings,iz=e=>e.legend.size,lz=e=>e.legend.payload,oz=Y([lz,zA],(e,t)=>{var{itemSorter:r}=t,n=e.flat(1);return r?ud(n,r):n});function sz(){return ge(oz)}var Dc=1;function RA(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],[t,r]=b.useState({height:0,left:0,top:0,width:0}),n=b.useCallback(l=>{if(l!=null){var s=l.getBoundingClientRect(),c={height:s.height,left:s.left,top:s.top,width:s.width};(Math.abs(c.height-t.height)>Dc||Math.abs(c.left-t.left)>Dc||Math.abs(c.top-t.top)>Dc||Math.abs(c.width-t.width)>Dc)&&r({height:c.height,left:c.left,top:c.top,width:c.width})}},[t.width,t.height,t.top,t.left,...e]);return[t,n]}function Qt(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var uz=typeof Symbol=="function"&&Symbol.observable||"@@observable",I_=uz,pv=()=>Math.random().toString(36).substring(7).split("").join("."),cz={INIT:`@@redux/INIT${pv()}`,REPLACE:`@@redux/REPLACE${pv()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${pv()}`},hf=cz;function O0(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function LA(e,t,r){if(typeof e!="function")throw new Error(Qt(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(Qt(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(Qt(1));return r(LA)(e,t)}let n=e,l=t,s=new Map,c=s,d=0,h=!1;function m(){c===s&&(c=new Map,s.forEach((N,A)=>{c.set(A,N)}))}function p(){if(h)throw new Error(Qt(3));return l}function y(N){if(typeof N!="function")throw new Error(Qt(4));if(h)throw new Error(Qt(5));let A=!0;m();const O=d++;return c.set(O,N),function(){if(A){if(h)throw new Error(Qt(6));A=!1,m(),c.delete(O),s=null}}}function x(N){if(!O0(N))throw new Error(Qt(7));if(typeof N.type>"u")throw new Error(Qt(8));if(typeof N.type!="string")throw new Error(Qt(17));if(h)throw new Error(Qt(9));try{h=!0,l=n(l,N)}finally{h=!1}return(s=c).forEach(O=>{O()}),N}function w(N){if(typeof N!="function")throw new Error(Qt(10));n=N,x({type:hf.REPLACE})}function j(){const N=y;return{subscribe(A){if(typeof A!="object"||A===null)throw new Error(Qt(11));function O(){const k=A;k.next&&k.next(p())}return O(),{unsubscribe:N(O)}},[I_](){return this}}}return x({type:hf.INIT}),{dispatch:x,subscribe:y,getState:p,replaceReducer:w,[I_]:j}}function fz(e){Object.keys(e).forEach(t=>{const r=e[t];if(typeof r(void 0,{type:hf.INIT})>"u")throw new Error(Qt(12));if(typeof r(void 0,{type:hf.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Qt(13))})}function IA(e){const t=Object.keys(e),r={};for(let s=0;s"u")throw d&&d.type,new Error(Qt(14));m[y]=j,h=h||j!==w}return h=h||n.length!==Object.keys(c).length,h?m:c}}function mf(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function dz(...e){return t=>(r,n)=>{const l=t(r,n);let s=()=>{throw new Error(Qt(15))};const c={getState:l.getState,dispatch:(h,...m)=>s(h,...m)},d=e.map(h=>h(c));return s=mf(...d)(l.dispatch),{...l,dispatch:s}}}function $A(e){return O0(e)&&"type"in e&&typeof e.type=="string"}var BA=Symbol.for("immer-nothing"),$_=Symbol.for("immer-draftable"),cr=Symbol.for("immer-state");function sn(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var zr=Object,to=zr.getPrototypeOf,pf="constructor",cd="prototype",hy="configurable",vf="enumerable",Jc="writable",Ts="value",ca=e=>!!e&&!!e[cr];function hn(e){var t;return e?qA(e)||dd(e)||!!e[$_]||!!((t=e[pf])!=null&&t[$_])||hd(e)||md(e):!1}var hz=zr[cd][pf].toString(),B_=new WeakMap;function qA(e){if(!e||!A0(e))return!1;const t=to(e);if(t===null||t===zr[cd])return!0;const r=zr.hasOwnProperty.call(t,pf)&&t[pf];if(r===Object)return!0;if(!Vl(r))return!1;let n=B_.get(r);return n===void 0&&(n=Function.toString.call(r),B_.set(r,n)),n===hz}function fd(e,t,r=!0){Xs(e)===0?(r?Reflect.ownKeys(e):zr.keys(e)).forEach(l=>{t(l,e[l],e)}):e.forEach((n,l)=>t(l,n,e))}function Xs(e){const t=e[cr];return t?t.type_:dd(e)?1:hd(e)?2:md(e)?3:0}var q_=(e,t,r=Xs(e))=>r===2?e.has(t):zr[cd].hasOwnProperty.call(e,t),my=(e,t,r=Xs(e))=>r===2?e.get(t):e[t],yf=(e,t,r,n=Xs(e))=>{n===2?e.set(t,r):n===3?e.add(r):e[t]=r};function mz(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}var dd=Array.isArray,hd=e=>e instanceof Map,md=e=>e instanceof Set,A0=e=>typeof e=="object",Vl=e=>typeof e=="function",vv=e=>typeof e=="boolean";function pz(e){const t=+e;return Number.isInteger(t)&&String(t)===e}var ta=e=>e.copy_||e.base_,E0=e=>e.modified_?e.copy_:e.base_;function py(e,t){if(hd(e))return new Map(e);if(md(e))return new Set(e);if(dd(e))return Array[cd].slice.call(e);const r=qA(e);if(t===!0||t==="class_only"&&!r){const n=zr.getOwnPropertyDescriptors(e);delete n[cr];let l=Reflect.ownKeys(n);for(let s=0;s1&&zr.defineProperties(e,{set:Pc,add:Pc,clear:Pc,delete:Pc}),zr.freeze(e),t&&fd(e,(r,n)=>{C0(n,!0)},!1)),e}function vz(){sn(2)}var Pc={[Ts]:vz};function pd(e){return e===null||!A0(e)?!0:zr.isFrozen(e)}var gf="MapSet",vy="Patches",U_="ArrayMethods",UA={};function Xi(e){const t=UA[e];return t||sn(0,e),t}var H_=e=>!!UA[e],Ds,HA=()=>Ds,yz=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:H_(gf)?Xi(gf):void 0,arrayMethodsPlugin_:H_(U_)?Xi(U_):void 0});function K_(e,t){t&&(e.patchPlugin_=Xi(vy),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function yy(e){gy(e),e.drafts_.forEach(gz),e.drafts_=null}function gy(e){e===Ds&&(Ds=e.parent_)}var Y_=e=>Ds=yz(Ds,e);function gz(e){const t=e[cr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function G_(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];if(e!==void 0&&e!==r){r[cr].modified_&&(yy(t),sn(4)),hn(e)&&(e=V_(t,e));const{patchPlugin_:l}=t;l&&l.generateReplacementPatches_(r[cr].base_,e,t)}else e=V_(t,r);return xz(t,e,!0),yy(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==BA?e:void 0}function V_(e,t){if(pd(t))return t;const r=t[cr];if(!r)return xf(t,e.handledSet_,e);if(!vd(r,e))return t;if(!r.modified_)return r.base_;if(!r.finalized_){const{callbacks_:n}=r;if(n)for(;n.length>0;)n.pop()(e);GA(r,e)}return r.copy_}function xz(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&C0(t,r)}function KA(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var vd=(e,t)=>e.scope_===t,bz=[];function YA(e,t,r,n){const l=ta(e),s=e.type_;if(n!==void 0&&my(l,n,s)===t){yf(l,n,r,s);return}if(!e.draftLocations_){const d=e.draftLocations_=new Map;fd(l,(h,m)=>{if(ca(m)){const p=d.get(m)||[];p.push(h),d.set(m,p)}})}const c=e.draftLocations_.get(t)??bz;for(const d of c)yf(l,d,r,s)}function wz(e,t,r){e.callbacks_.push(function(l){var d;const s=t;if(!s||!vd(s,l))return;(d=l.mapSetPlugin_)==null||d.fixSetContents(s);const c=E0(s);YA(e,s.draft_??s,c,r),GA(s,l)})}function GA(e,t){var n;if(e.modified_&&!e.finalized_&&(e.type_===3||e.type_===1&&e.allIndicesReassigned_||(((n=e.assigned_)==null?void 0:n.size)??0)>0)){const{patchPlugin_:l}=t;if(l){const s=l.getPath(e);s&&l.generatePatches_(e,s,t)}KA(e)}}function jz(e,t,r){const{scope_:n}=e;if(ca(r)){const l=r[cr];vd(l,n)&&l.callbacks_.push(function(){ef(e);const c=E0(l);YA(e,r,c,t)})}else hn(r)&&e.callbacks_.push(function(){const s=ta(e);e.type_===3?s.has(r)&&xf(r,n.handledSet_,n):my(s,t,e.type_)===r&&n.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&xf(my(e.copy_,t,e.type_),n.handledSet_,n)})}function xf(e,t,r){return!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1||ca(e)||t.has(e)||!hn(e)||pd(e)||(t.add(e),fd(e,(n,l)=>{if(ca(l)){const s=l[cr];if(vd(s,r)){const c=E0(s);yf(e,n,c,e.type_),KA(s)}}else hn(l)&&xf(l,t,r)})),e}function _z(e,t){const r=dd(e),n={type_:r?1:0,scope_:t?t.scope_:HA(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let l=n,s=bf;r&&(l=[n],s=Ps);const{revoke:c,proxy:d}=Proxy.revocable(l,s);return n.draft_=d,n.revoke_=c,[d,n]}var bf={get(e,t){if(t===cr)return e;let r=e.scope_.arrayMethodsPlugin_;const n=e.type_===1&&typeof t=="string";if(n&&r!=null&&r.isArrayOperationMethod(t))return r.createMethodInterceptor(e,t);const l=ta(e);if(!q_(l,t,e.type_))return Sz(e,l,t);const s=l[t];if(e.finalized_||!hn(s)||n&&e.operationMethod&&(r!=null&&r.isMutatingArrayMethod(e.operationMethod))&&pz(t))return s;if(s===yv(e.base_,t)){ef(e);const c=e.type_===1?+t:t,d=by(e.scope_,s,e,c);return e.copy_[c]=d}return s},has(e,t){return t in ta(e)},ownKeys(e){return Reflect.ownKeys(ta(e))},set(e,t,r){const n=VA(ta(e),t);if(n!=null&&n.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const l=yv(ta(e),t),s=l==null?void 0:l[cr];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_.set(t,!1),!0;if(mz(r,l)&&(r!==void 0||q_(e.base_,t,e.type_)))return!0;ef(e),xy(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_.set(t,!0),jz(e,t,r)),!0},deleteProperty(e,t){return ef(e),yv(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),xy(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const r=ta(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{[Jc]:!0,[hy]:e.type_!==1||t!=="length",[vf]:n[vf],[Ts]:r[t]}},defineProperty(){sn(11)},getPrototypeOf(e){return to(e.base_)},setPrototypeOf(){sn(12)}},Ps={};for(let e in bf){let t=bf[e];Ps[e]=function(){const r=arguments;return r[0]=r[0][0],t.apply(this,r)}}Ps.deleteProperty=function(e,t){return Ps.set.call(this,e,t,void 0)};Ps.set=function(e,t,r){return bf.set.call(this,e[0],t,r,e[0])};function yv(e,t){const r=e[cr];return(r?ta(r):e)[t]}function Sz(e,t,r){var l;const n=VA(t,r);return n?Ts in n?n[Ts]:(l=n.get)==null?void 0:l.call(e.draft_):void 0}function VA(e,t){if(!(t in e))return;let r=to(e);for(;r;){const n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=to(r)}}function xy(e){e.modified_||(e.modified_=!0,e.parent_&&xy(e.parent_))}function ef(e){e.copy_||(e.assigned_=new Map,e.copy_=py(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Nz=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(r,n,l)=>{if(Vl(r)&&!Vl(n)){const c=n;n=r;const d=this;return function(m=c,...p){return d.produce(m,y=>n.call(this,y,...p))}}Vl(n)||sn(6),l!==void 0&&!Vl(l)&&sn(7);let s;if(hn(r)){const c=Y_(this),d=by(c,r,void 0);let h=!0;try{s=n(d),h=!1}finally{h?yy(c):gy(c)}return K_(c,l),G_(s,c)}else if(!r||!A0(r)){if(s=n(r),s===void 0&&(s=r),s===BA&&(s=void 0),this.autoFreeze_&&C0(s,!0),l){const c=[],d=[];Xi(vy).generateReplacementPatches_(r,s,{patches_:c,inversePatches_:d}),l(c,d)}return s}else sn(1,r)},this.produceWithPatches=(r,n)=>{if(Vl(r))return(d,...h)=>this.produceWithPatches(d,m=>r(m,...h));let l,s;return[this.produce(r,n,(d,h)=>{l=d,s=h}),l,s]},vv(t==null?void 0:t.autoFreeze)&&this.setAutoFreeze(t.autoFreeze),vv(t==null?void 0:t.useStrictShallowCopy)&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),vv(t==null?void 0:t.useStrictIteration)&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){hn(t)||sn(8),ca(t)&&(t=fn(t));const r=Y_(this),n=by(r,t,void 0);return n[cr].isManual_=!0,gy(r),n}finishDraft(t,r){const n=t&&t[cr];(!n||!n.isManual_)&&sn(9);const{scope_:l}=n;return K_(l,r),G_(void 0,l)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}setUseStrictIteration(t){this.useStrictIteration_=t}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(t,r){let n;for(n=r.length-1;n>=0;n--){const s=r[n];if(s.path.length===0&&s.op==="replace"){t=s.value;break}}n>-1&&(r=r.slice(n+1));const l=Xi(vy).applyPatches_;return ca(t)?l(t,r):this.produce(t,s=>l(s,r))}};function by(e,t,r,n){const[l,s]=hd(t)?Xi(gf).proxyMap_(t,r):md(t)?Xi(gf).proxySet_(t,r):_z(t,r);return((r==null?void 0:r.scope_)??HA()).drafts_.push(l),s.callbacks_=(r==null?void 0:r.callbacks_)??[],s.key_=n,r&&n!==void 0?wz(r,s,n):s.callbacks_.push(function(h){var p;(p=h.mapSetPlugin_)==null||p.fixSetContents(s);const{patchPlugin_:m}=h;s.modified_&&m&&m.generatePatches_(s,[],h)}),l}function fn(e){return ca(e)||sn(10,e),XA(e)}function XA(e){if(!hn(e)||pd(e))return e;const t=e[cr];let r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=py(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=py(e,!0);return fd(r,(l,s)=>{yf(r,l,XA(s))},n),t&&(t.finalized_=!1),r}var Oz=new Nz,FA=Oz.produce;function ZA(e){return({dispatch:r,getState:n})=>l=>s=>typeof s=="function"?s(r,n,e):l(s)}var Az=ZA(),Ez=ZA,Cz=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?mf:mf.apply(null,arguments)};function en(e,t){function r(...n){if(t){let l=t(...n);if(!l)throw new Error(Rr(0));return{type:e,payload:l.payload,..."meta"in l&&{meta:l.meta},..."error"in l&&{error:l.error}}}return{type:e,payload:n[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=n=>$A(n)&&n.type===e,r}var QA=class Os extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,Os.prototype)}static get[Symbol.species](){return Os}concat(...t){return super.concat.apply(this,t)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new Os(...t[0].concat(this)):new Os(...t.concat(this))}};function X_(e){return hn(e)?FA(e,()=>{}):e}function zc(e,t,r){return e.has(t)?e.get(t):e.set(t,r(t)).get(t)}function kz(e){return typeof e=="boolean"}var Mz=()=>function(t){const{thunk:r=!0,immutableCheck:n=!0,serializableCheck:l=!0,actionCreatorCheck:s=!0}=t??{};let c=new QA;return r&&(kz(r)?c.push(Az):c.push(Ez(r.extraArgument))),c},WA="RTK_autoBatch",st=()=>e=>({payload:e,meta:{[WA]:!0}}),F_=e=>t=>{setTimeout(t,e)},JA=(e={type:"raf"})=>t=>(...r)=>{const n=t(...r);let l=!0,s=!1,c=!1;const d=new Set,h=e.type==="tick"?queueMicrotask:e.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:F_(10):e.type==="callback"?e.queueNotification:F_(e.timeout),m=()=>{c=!1,s&&(s=!1,d.forEach(p=>p()))};return Object.assign({},n,{subscribe(p){const y=()=>l&&p(),x=n.subscribe(y);return d.add(p),()=>{x(),d.delete(p)}},dispatch(p){var y;try{return l=!((y=p==null?void 0:p.meta)!=null&&y[WA]),s=!l,s&&(c||(c=!0,h(m))),n.dispatch(p)}finally{l=!0}}})},Tz=e=>function(r){const{autoBatch:n=!0}=r??{};let l=new QA(e);return n&&l.push(JA(typeof n=="object"?n:void 0)),l};function Dz(e){const t=Mz(),{reducer:r=void 0,middleware:n,devTools:l=!0,preloadedState:s=void 0,enhancers:c=void 0}=e||{};let d;if(typeof r=="function")d=r;else if(O0(r))d=IA(r);else throw new Error(Rr(1));let h;typeof n=="function"?h=n(t):h=t();let m=mf;l&&(m=Cz({trace:!1,...typeof l=="object"&&l}));const p=dz(...h),y=Tz(p);let x=typeof c=="function"?c(y):y();const w=m(...x);return LA(d,s,w)}function eE(e){const t={},r=[];let n;const l={addCase(s,c){const d=typeof s=="string"?s:s.type;if(!d)throw new Error(Rr(28));if(d in t)throw new Error(Rr(29));return t[d]=c,l},addAsyncThunk(s,c){return c.pending&&(t[s.pending.type]=c.pending),c.rejected&&(t[s.rejected.type]=c.rejected),c.fulfilled&&(t[s.fulfilled.type]=c.fulfilled),c.settled&&r.push({matcher:s.settled,reducer:c.settled}),l},addMatcher(s,c){return r.push({matcher:s,reducer:c}),l},addDefaultCase(s){return n=s,l}};return e(l),[t,r,n]}function Pz(e){return typeof e=="function"}function zz(e,t){let[r,n,l]=eE(t),s;if(Pz(e))s=()=>X_(e());else{const d=X_(e);s=()=>d}function c(d=s(),h){let m=[r[h.type],...n.filter(({matcher:p})=>p(h)).map(({reducer:p})=>p)];return m.filter(p=>!!p).length===0&&(m=[l]),m.reduce((p,y)=>{if(y)if(ca(p)){const w=y(p,h);return w===void 0?p:w}else{if(hn(p))return FA(p,x=>y(x,h));{const x=y(p,h);if(x===void 0){if(p===null)return p;throw Error("A case reducer on a non-draftable value must not return undefined")}return x}}return p},d)}return c.getInitialState=s,c}var Rz="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",Lz=(e=21)=>{let t="",r=e;for(;r--;)t+=Rz[Math.random()*64|0];return t},Iz=Symbol.for("rtk-slice-createasyncthunk");function $z(e,t){return`${e}/${t}`}function Bz({creators:e}={}){var r;const t=(r=e==null?void 0:e.asyncThunk)==null?void 0:r[Iz];return function(l){const{name:s,reducerPath:c=s}=l;if(!s)throw new Error(Rr(11));const d=(typeof l.reducers=="function"?l.reducers(Uz()):l.reducers)||{},h=Object.keys(d),m={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},p={addCase(k,z){const T=typeof k=="string"?k:k.type;if(!T)throw new Error(Rr(12));if(T in m.sliceCaseReducersByType)throw new Error(Rr(13));return m.sliceCaseReducersByType[T]=z,p},addMatcher(k,z){return m.sliceMatchers.push({matcher:k,reducer:z}),p},exposeAction(k,z){return m.actionCreators[k]=z,p},exposeCaseReducer(k,z){return m.sliceCaseReducersByName[k]=z,p}};h.forEach(k=>{const z=d[k],T={reducerName:k,type:$z(s,k),createNotation:typeof l.reducers=="function"};Kz(z)?Gz(T,z,p,t):Hz(T,z,p)});function y(){const[k={},z=[],T=void 0]=typeof l.extraReducers=="function"?eE(l.extraReducers):[l.extraReducers],R={...k,...m.sliceCaseReducersByType};return zz(l.initialState,$=>{for(let Z in R)$.addCase(Z,R[Z]);for(let Z of m.sliceMatchers)$.addMatcher(Z.matcher,Z.reducer);for(let Z of z)$.addMatcher(Z.matcher,Z.reducer);T&&$.addDefaultCase(T)})}const x=k=>k,w=new Map,j=new WeakMap;let _;function N(k,z){return _||(_=y()),_(k,z)}function A(){return _||(_=y()),_.getInitialState()}function O(k,z=!1){function T($){let Z=$[k];return typeof Z>"u"&&z&&(Z=zc(j,T,A)),Z}function R($=x){const Z=zc(w,z,()=>new WeakMap);return zc(Z,$,()=>{const X={};for(const[L,K]of Object.entries(l.selectors??{}))X[L]=qz(K,$,()=>zc(j,$,A),z);return X})}return{reducerPath:k,getSelectors:R,get selectors(){return R(T)},selectSlice:T}}const P={name:s,reducer:N,actions:m.actionCreators,caseReducers:m.sliceCaseReducersByName,getInitialState:A,...O(c),injectInto(k,{reducerPath:z,...T}={}){const R=z??c;return k.inject({reducerPath:R,reducer:N},T),{...P,...O(R,!0)}}};return P}}function qz(e,t,r,n){function l(s,...c){let d=t(s);return typeof d>"u"&&n&&(d=r()),e(d,...c)}return l.unwrapped=e,l}var jr=Bz();function Uz(){function e(t,r){return{_reducerDefinitionType:"asyncThunk",payloadCreator:t,...r}}return e.withTypes=()=>e,{reducer(t){return Object.assign({[t.name](...r){return t(...r)}}[t.name],{_reducerDefinitionType:"reducer"})},preparedReducer(t,r){return{_reducerDefinitionType:"reducerWithPrepare",prepare:t,reducer:r}},asyncThunk:e}}function Hz({type:e,reducerName:t,createNotation:r},n,l){let s,c;if("reducer"in n){if(r&&!Yz(n))throw new Error(Rr(17));s=n.reducer,c=n.prepare}else s=n;l.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,c?en(e,c):en(e))}function Kz(e){return e._reducerDefinitionType==="asyncThunk"}function Yz(e){return e._reducerDefinitionType==="reducerWithPrepare"}function Gz({type:e,reducerName:t},r,n,l){if(!l)throw new Error(Rr(18));const{payloadCreator:s,fulfilled:c,pending:d,rejected:h,settled:m,options:p}=r,y=l(e,s,p);n.exposeAction(t,y),c&&n.addCase(y.fulfilled,c),d&&n.addCase(y.pending,d),h&&n.addCase(y.rejected,h),m&&n.addMatcher(y.settled,m),n.exposeCaseReducer(t,{fulfilled:c||Rc,pending:d||Rc,rejected:h||Rc,settled:m||Rc})}function Rc(){}var Vz="task",tE="listener",rE="completed",k0="cancelled",Xz=`task-${k0}`,Fz=`task-${rE}`,wy=`${tE}-${k0}`,Zz=`${tE}-${rE}`,yd=class{constructor(e){dp(this,"name","TaskAbortError");dp(this,"message");this.code=e,this.message=`${Vz} ${k0} (reason: ${e})`}},M0=(e,t)=>{if(typeof e!="function")throw new TypeError(Rr(32))},wf=()=>{},nE=(e,t=wf)=>(e.catch(t),e),aE=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Ii=e=>{if(e.aborted)throw new yd(e.reason)};function iE(e,t){let r=wf;return new Promise((n,l)=>{const s=()=>l(new yd(e.reason));if(e.aborted){s();return}r=aE(e,s),t.finally(()=>r()).then(n,l)}).finally(()=>{r=wf})}var Qz=async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(r){return{status:r instanceof yd?"cancelled":"rejected",error:r}}finally{t==null||t()}},jf=e=>t=>nE(iE(e,t).then(r=>(Ii(e),r))),lE=e=>{const t=jf(e);return r=>t(new Promise(n=>setTimeout(n,r)))},{assign:Wl}=Object,Z_={},gd="listenerMiddleware",Wz=(e,t)=>{const r=n=>aE(e,()=>n.abort(e.reason));return(n,l)=>{M0(n);const s=new AbortController;r(s);const c=Qz(async()=>{Ii(e),Ii(s.signal);const d=await n({pause:jf(s.signal),delay:lE(s.signal),signal:s.signal});return Ii(s.signal),d},()=>s.abort(Fz));return l!=null&&l.autoJoin&&t.push(c.catch(wf)),{result:jf(e)(c),cancel(){s.abort(Xz)}}}},Jz=(e,t)=>{const r=async(n,l)=>{Ii(t);let s=()=>{};const d=[new Promise((h,m)=>{let p=e({predicate:n,effect:(y,x)=>{x.unsubscribe(),h([y,x.getState(),x.getOriginalState()])}});s=()=>{p(),m()}})];l!=null&&d.push(new Promise(h=>setTimeout(h,l,null)));try{const h=await iE(t,Promise.race(d));return Ii(t),h}finally{s()}};return(n,l)=>nE(r(n,l))},oE=e=>{let{type:t,actionCreator:r,matcher:n,predicate:l,effect:s}=e;if(t)l=en(t).match;else if(r)t=r.type,l=r.match;else if(n)l=n;else if(!l)throw new Error(Rr(21));return M0(s),{predicate:l,type:t,effect:s}},sE=Wl(e=>{const{type:t,predicate:r,effect:n}=oE(e);return{id:Lz(),effect:n,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error(Rr(22))}}},{withTypes:()=>sE}),Q_=(e,t)=>{const{type:r,effect:n,predicate:l}=oE(t);return Array.from(e.values()).find(s=>(typeof r=="string"?s.type===r:s.predicate===l)&&s.effect===n)},jy=e=>{e.pending.forEach(t=>{t.abort(wy)})},e8=(e,t)=>()=>{for(const r of t.keys())jy(r);e.clear()},W_=(e,t,r)=>{try{e(t,r)}catch(n){setTimeout(()=>{throw n},0)}},uE=Wl(en(`${gd}/add`),{withTypes:()=>uE}),t8=en(`${gd}/removeAll`),cE=Wl(en(`${gd}/remove`),{withTypes:()=>cE}),r8=(...e)=>{console.error(`${gd}/error`,...e)},Fs=(e={})=>{const t=new Map,r=new Map,n=w=>{const j=r.get(w)??0;r.set(w,j+1)},l=w=>{const j=r.get(w)??1;j===1?r.delete(w):r.set(w,j-1)},{extra:s,onError:c=r8}=e;M0(c);const d=w=>(w.unsubscribe=()=>t.delete(w.id),t.set(w.id,w),j=>{w.unsubscribe(),j!=null&&j.cancelActive&&jy(w)}),h=w=>{const j=Q_(t,w)??sE(w);return d(j)};Wl(h,{withTypes:()=>h});const m=w=>{const j=Q_(t,w);return j&&(j.unsubscribe(),w.cancelActive&&jy(j)),!!j};Wl(m,{withTypes:()=>m});const p=async(w,j,_,N)=>{const A=new AbortController,O=Jz(h,A.signal),P=[];try{w.pending.add(A),n(w),await Promise.resolve(w.effect(j,Wl({},_,{getOriginalState:N,condition:(k,z)=>O(k,z).then(Boolean),take:O,delay:lE(A.signal),pause:jf(A.signal),extra:s,signal:A.signal,fork:Wz(A.signal,P),unsubscribe:w.unsubscribe,subscribe:()=>{t.set(w.id,w)},cancelActiveListeners:()=>{w.pending.forEach((k,z,T)=>{k!==A&&(k.abort(wy),T.delete(k))})},cancel:()=>{A.abort(wy),w.pending.delete(A)},throwIfCancelled:()=>{Ii(A.signal)}})))}catch(k){k instanceof yd||W_(c,k,{raisedBy:"effect"})}finally{await Promise.all(P),A.abort(Zz),l(w),w.pending.delete(A)}},y=e8(t,r);return{middleware:w=>j=>_=>{if(!$A(_))return j(_);if(uE.match(_))return h(_.payload);if(t8.match(_)){y();return}if(cE.match(_))return m(_.payload);let N=w.getState();const A=()=>{if(N===Z_)throw new Error(Rr(23));return N};let O;try{if(O=j(_),t.size>0){const P=w.getState(),k=Array.from(t.values());for(const z of k){let T=!1;try{T=z.predicate(_,P,N)}catch(R){T=!1,W_(c,R,{raisedBy:"predicate"})}T&&p(z,_,w,A)}}}finally{N=Z_}return O},startListening:h,stopListening:m,clearListeners:y}};function Rr(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var n8={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},fE=jr({name:"chartLayout",initialState:n8,reducers:{setLayout(e,t){e.layoutType=t.payload},setChartSize(e,t){e.width=t.payload.width,e.height=t.payload.height},setMargin(e,t){var r,n,l,s;e.margin.top=(r=t.payload.top)!==null&&r!==void 0?r:0,e.margin.right=(n=t.payload.right)!==null&&n!==void 0?n:0,e.margin.bottom=(l=t.payload.bottom)!==null&&l!==void 0?l:0,e.margin.left=(s=t.payload.left)!==null&&s!==void 0?s:0},setScale(e,t){e.scale=t.payload}}}),{setMargin:a8,setLayout:i8,setChartSize:l8,setScale:o8}=fE.actions,s8=fE.reducer;function dE(e,t,r){return Array.isArray(e)&&e&&t+r!==0?e.slice(t,r+1):e}function ke(e){return Number.isFinite(e)}function En(e){return typeof e=="number"&&e>0&&Number.isFinite(e)}function J_(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Fl(e){for(var t=1;t{if(t&&r){var{width:n,height:l}=r,{align:s,verticalAlign:c,layout:d}=t;if((d==="vertical"||d==="horizontal"&&c==="middle")&&s!=="center"&&de(e[s]))return Fl(Fl({},e),{},{[s]:e[s]+(n||0)});if((d==="horizontal"||d==="vertical"&&s==="center")&&c!=="middle"&&de(e[c]))return Fl(Fl({},e),{},{[c]:e[c]+(l||0)})}return e},Mn=(e,t)=>e==="horizontal"&&t==="xAxis"||e==="vertical"&&t==="yAxis"||e==="centric"&&t==="angleAxis"||e==="radial"&&t==="radiusAxis",hE=(e,t,r,n)=>{if(n)return e.map(d=>d.coordinate);var l,s,c=e.map(d=>(d.coordinate===t&&(l=!0),d.coordinate===r&&(s=!0),d.coordinate));return l||c.push(t),s||c.push(r),c},mE=(e,t,r)=>{if(!e)return null;var{duplicateDomain:n,type:l,range:s,scale:c,realScaleType:d,isCategorical:h,categoricalDomain:m,tickCount:p,ticks:y,niceTicks:x,axisType:w}=e;if(!c)return null;var j=d==="scaleBand"&&c.bandwidth?c.bandwidth()/2:2,_=l==="category"&&c.bandwidth?c.bandwidth()/j:0;if(_=w==="angleAxis"&&s&&s.length>=2?Ht(s[0]-s[1])*2*_:_,y||x){var N=(y||x||[]).map((A,O)=>{var P=n?n.indexOf(A):A,k=c.map(P);return ke(k)?{coordinate:k+_,value:A,offset:_,index:O}:null}).filter(xr);return N}return h&&m?m.map((A,O)=>{var P=c.map(A);return ke(P)?{coordinate:P+_,value:A,index:O,offset:_}:null}).filter(xr):c.ticks&&p!=null?c.ticks(p).map((A,O)=>{var P=c.map(A);return ke(P)?{coordinate:P+_,value:A,index:O,offset:_}:null}).filter(xr):c.domain().map((A,O)=>{var P=c.map(A);return ke(P)?{coordinate:P+_,value:n?n[A]:A,index:O,offset:_}:null}).filter(xr)},h8=(e,t)=>{if(!t||t.length!==2||!de(t[0])||!de(t[1]))return e;var r=Math.min(t[0],t[1]),n=Math.max(t[0],t[1]),l=[e[0],e[1]];return(!de(e[0])||e[0]n)&&(l[1]=n),l[0]>n&&(l[0]=n),l[1]{var t,r=e.length;if(!(r<=0)){var n=(t=e[0])===null||t===void 0?void 0:t.length;if(!(n==null||n<=0))for(var l=0;l=0?(m[0]=s,s+=x,m[1]=s):(m[0]=c,c+=x,m[1]=c)}}}},p8=e=>{var t,r=e.length;if(!(r<=0)){var n=(t=e[0])===null||t===void 0?void 0:t.length;if(!(n==null||n<=0))for(var l=0;l=0?(h[0]=s,s+=m,h[1]=s):(h[0]=0,h[1]=0)}}}},v8={sign:m8,expand:RP,none:Yi,silhouette:LP,wiggle:IP,positive:p8},y8=(e,t,r)=>{var n,l=(n=v8[r])!==null&&n!==void 0?n:Yi,s=zP().keys(t).value((d,h)=>Number(We(d,h,0))).order(fy).offset(l),c=s(e);return c.forEach((d,h)=>{d.forEach((m,p)=>{var y=We(e[p],t[h],0);Array.isArray(y)&&y.length===2&&de(y[0])&&de(y[1])&&(m[0]=y[0],m[1]=y[1])})}),c};function pE(e){return e==null?void 0:String(e)}function e2(e){var{axis:t,ticks:r,bandSize:n,entry:l,index:s,dataKey:c}=e;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!xt(l[t.dataKey])){var d=bA(r,"value",l[t.dataKey]);if(d)return d.coordinate+n/2}return r!=null&&r[s]?r[s].coordinate+n/2:null}var h=We(l,xt(c)?t.dataKey:c),m=t.scale.map(h);return de(m)?m:null}var t2=e=>{var{axis:t,ticks:r,offset:n,bandSize:l,entry:s,index:c}=e;if(t.type==="category")return r[c]?r[c].coordinate+n:null;var d=We(s,t.dataKey,t.scale.domain()[c]);if(xt(d))return null;var h=t.scale.map(d);return de(h)?h-l/2+n:null},g8=e=>{var{numericAxis:t}=e,r=t.scale.domain();if(t.type==="number"){var n=Math.min(r[0],r[1]),l=Math.max(r[0],r[1]);return n<=0&&l>=0?0:l<0?l:n}return r[0]},x8=e=>{var t=e.flat(2).filter(de);return[Math.min(...t),Math.max(...t)]},b8=e=>[e[0]===1/0?0:e[0],e[1]===-1/0?0:e[1]],w8=(e,t,r)=>{if(e!=null)return b8(Object.keys(e).reduce((n,l)=>{var s=e[l];if(!s)return n;var{stackedData:c}=s,d=c.reduce((h,m)=>{var p=dE(m,t,r),y=x8(p);return!ke(y[0])||!ke(y[1])?h:[Math.min(h[0],y[0]),Math.max(h[1],y[1])]},[1/0,-1/0]);return[Math.min(d[0],n[0]),Math.max(d[1],n[1])]},[1/0,-1/0]))},r2=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,n2=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,ro=(e,t,r)=>{if(e&&e.scale&&e.scale.bandwidth){var n=e.scale.bandwidth();if(!r||n>0)return n}if(e&&t&&t.length>=2){for(var l=ud(t,p=>p.coordinate),s=1/0,c=1,d=l.length;c{if(t==="horizontal")return e.chartX;if(t==="vertical")return e.chartY},_8=(e,t)=>t==="centric"?e.angle:e.radius,ya=e=>e.layout.width,ga=e=>e.layout.height,S8=e=>e.layout.scale,vE=e=>e.layout.margin,xd=Y(e=>e.cartesianAxis.xAxis,e=>Object.values(e)),bd=Y(e=>e.cartesianAxis.yAxis,e=>Object.values(e)),yE="data-recharts-item-index",gE="data-recharts-item-id",Zs=60;function i2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Lc(e){for(var t=1;te.brush.height;function C8(e){var t=bd(e);return t.reduce((r,n)=>{if(n.orientation==="left"&&!n.mirror&&!n.hide){var l=typeof n.width=="number"?n.width:Zs;return r+l}return r},0)}function k8(e){var t=bd(e);return t.reduce((r,n)=>{if(n.orientation==="right"&&!n.mirror&&!n.hide){var l=typeof n.width=="number"?n.width:Zs;return r+l}return r},0)}function M8(e){var t=xd(e);return t.reduce((r,n)=>n.orientation==="top"&&!n.mirror&&!n.hide?r+n.height:r,0)}function T8(e){var t=xd(e);return t.reduce((r,n)=>n.orientation==="bottom"&&!n.mirror&&!n.hide?r+n.height:r,0)}var zt=Y([ya,ga,vE,E8,C8,k8,M8,T8,zA,iz],(e,t,r,n,l,s,c,d,h,m)=>{var p={left:(r.left||0)+l,right:(r.right||0)+s},y={top:(r.top||0)+c,bottom:(r.bottom||0)+d},x=Lc(Lc({},y),p),w=x.bottom;x.bottom+=n,x=d8(x,h,m);var j=e-x.left-x.right,_=t-x.top-x.bottom;return Lc(Lc({brushBottom:w},x),{},{width:Math.max(j,0),height:Math.max(_,0)})}),D8=Y(zt,e=>({x:e.left,y:e.top,width:e.width,height:e.height})),T0=Y(ya,ga,(e,t)=>({x:0,y:0,width:e,height:t})),P8=b.createContext(null),ir=()=>b.useContext(P8)!=null,wd=e=>e.brush,jd=Y([wd,zt,vE],(e,t,r)=>({height:e.height,x:de(e.x)?e.x:t.left,y:de(e.y)?e.y:t.top+t.height+t.brushBottom-((r==null?void 0:r.bottom)||0),width:de(e.width)?e.width:t.width})),gv={},xv={},bv={},l2;function z8(){return l2||(l2=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r,n,{signal:l,edges:s}={}){let c,d=null;const h=s!=null&&s.includes("leading"),m=s==null||s.includes("trailing"),p=()=>{d!==null&&(r.apply(c,d),c=void 0,d=null)},y=()=>{m&&p(),_()};let x=null;const w=()=>{x!=null&&clearTimeout(x),x=setTimeout(()=>{x=null,y()},n)},j=()=>{x!==null&&(clearTimeout(x),x=null)},_=()=>{j(),c=void 0,d=null},N=()=>{p()},A=function(...O){if(l!=null&&l.aborted)return;c=this,d=O;const P=x==null;w(),h&&P&&p()};return A.schedule=w,A.cancel=_,A.flush=N,l==null||l.addEventListener("abort",_,{once:!0}),A}e.debounce=t})(bv)),bv}var o2;function R8(){return o2||(o2=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=z8();function r(n,l=0,s={}){typeof s!="object"&&(s={});const{leading:c=!1,trailing:d=!0,maxWait:h}=s,m=Array(2);c&&(m[0]="leading"),d&&(m[1]="trailing");let p,y=null;const x=t.debounce(function(..._){p=n.apply(this,_),y=null},l,{edges:m}),w=function(..._){return h!=null&&(y===null&&(y=Date.now()),Date.now()-y>=h)?(p=n.apply(this,_),y=Date.now(),x.cancel(),x.schedule(),p):(x.apply(this,_),p)},j=()=>(x.flush(),p);return w.cancel=x.cancel,w.flush=j,w}e.debounce=r})(xv)),xv}var s2;function L8(){return s2||(s2=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=R8();function r(n,l=0,s={}){const{leading:c=!0,trailing:d=!0}=s;return t.debounce(n,l,{leading:c,maxWait:l,trailing:d})}e.throttle=r})(gv)),gv}var wv,u2;function I8(){return u2||(u2=1,wv=L8().throttle),wv}var $8=I8();const B8=kn($8);var _f=function(t,r){for(var n=arguments.length,l=new Array(n>2?n-2:0),s=2;sl[c++]))}},Sn={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},xE=(e,t,r)=>{var{width:n=Sn.width,height:l=Sn.height,aspect:s,maxHeight:c}=r,d=Vi(n)?e:Number(n),h=Vi(l)?t:Number(l);return s&&s>0&&(d?h=d/s:h&&(d=h*s),c&&h!=null&&h>c&&(h=c)),{calculatedWidth:d,calculatedHeight:h}},q8={width:0,height:0,overflow:"visible"},U8={width:0,overflowX:"visible"},H8={height:0,overflowY:"visible"},K8={},Y8=e=>{var{width:t,height:r}=e,n=Vi(t),l=Vi(r);return n&&l?q8:n?U8:l?H8:K8};function G8(e){var{width:t,height:r,aspect:n}=e,l=t,s=r;return l===void 0&&s===void 0?(l=Sn.width,s=Sn.height):l===void 0?l=n&&n>0?void 0:Sn.width:s===void 0&&(s=n&&n>0?void 0:Sn.height),{width:l,height:s}}function _y(){return _y=Object.assign?Object.assign.bind():function(e){for(var t=1;t({width:r,height:n}),[r,n]);return Z8(l)?b.createElement(bE.Provider,{value:l},t):null}var D0=()=>b.useContext(bE),Q8=b.forwardRef((e,t)=>{var{aspect:r,initialDimension:n=Sn.initialDimension,width:l,height:s,minWidth:c=Sn.minWidth,minHeight:d,maxHeight:h,children:m,debounce:p=Sn.debounce,id:y,className:x,onResize:w,style:j={}}=e,_=b.useRef(null),N=b.useRef();N.current=w,b.useImperativeHandle(t,()=>_.current);var[A,O]=b.useState({containerWidth:n.width,containerHeight:n.height}),P=b.useCallback(($,Z)=>{O(X=>{var L=Math.round($),K=Math.round(Z);return X.containerWidth===L&&X.containerHeight===K?X:{containerWidth:L,containerHeight:K}})},[]);b.useEffect(()=>{if(_.current==null||typeof ResizeObserver>"u")return Ji;var $=K=>{var se,ce=K[0];if(ce!=null){var{width:he,height:q}=ce.contentRect;P(he,q),(se=N.current)===null||se===void 0||se.call(N,he,q)}};p>0&&($=B8($,p,{trailing:!0,leading:!1}));var Z=new ResizeObserver($),{width:X,height:L}=_.current.getBoundingClientRect();return P(X,L),Z.observe(_.current),()=>{Z.disconnect()}},[P,p]);var{containerWidth:k,containerHeight:z}=A;_f(!r||r>0,"The aspect(%s) must be greater than zero.",r);var{calculatedWidth:T,calculatedHeight:R}=xE(k,z,{width:l,height:s,aspect:r,maxHeight:h});return _f(T!=null&&T>0||R!=null&&R>0,`The width(%s) and height(%s) of chart should be greater than 0, + please check the style of container, or the props width(%s) and height(%s), + or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the + height and width.`,T,R,l,s,c,d,r),b.createElement("div",{id:y?"".concat(y):void 0,className:Ue("recharts-responsive-container",x),style:f2(f2({},j),{},{width:l,height:s,minWidth:c,minHeight:d,maxHeight:h}),ref:_},b.createElement("div",{style:Y8({width:l,height:s})},b.createElement(wE,{width:T,height:R},m)))}),ps=b.forwardRef((e,t)=>{var r=D0();if(En(r.width)&&En(r.height))return e.children;var{width:n,height:l}=G8({width:e.width,height:e.height,aspect:e.aspect}),{calculatedWidth:s,calculatedHeight:c}=xE(void 0,void 0,{width:n,height:l,aspect:e.aspect,maxHeight:e.maxHeight});return de(s)&&de(c)?b.createElement(wE,{width:s,height:c},e.children):b.createElement(Q8,_y({},e,{width:n,height:l,ref:t}))});function P0(e){if(e)return{x:e.x,y:e.y,upperWidth:"upperWidth"in e?e.upperWidth:e.width,lowerWidth:"lowerWidth"in e?e.lowerWidth:e.width,width:e.width,height:e.height}}var _d=()=>{var e,t=ir(),r=ge(D8),n=ge(jd),l=(e=ge(wd))===null||e===void 0?void 0:e.padding;return!t||!n||!l?r:{width:n.width-l.left-l.right,height:n.height-l.top-l.bottom,x:l.left,y:l.top}},W8={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},jE=()=>{var e;return(e=ge(zt))!==null&&e!==void 0?e:W8},z0=()=>ge(ya),R0=()=>ge(ga),J8=()=>ge(e=>e.layout.margin),$e=e=>e.layout.layoutType,el=()=>ge($e),L0=()=>{var e=el();if(e==="horizontal"||e==="vertical")return e},_E=e=>{var t=e.layout.layoutType;if(t==="centric"||t==="radial")return t},eR=()=>{var e=el();return e!==void 0},Qs=e=>{var t=rt(),r=ir(),{width:n,height:l}=e,s=D0(),c=n,d=l;return s&&(c=s.width>0?s.width:n,d=s.height>0?s.height:l),b.useEffect(()=>{!r&&En(c)&&En(d)&&t(l8({width:c,height:d}))},[t,r,c,d]),null},SE=Symbol.for("immer-nothing"),d2=Symbol.for("immer-draftable"),Lr=Symbol.for("immer-state");function un(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var zs=Object.getPrototypeOf;function no(e){return!!e&&!!e[Lr]}function Fi(e){var t;return e?NE(e)||Array.isArray(e)||!!e[d2]||!!((t=e.constructor)!=null&&t[d2])||Ws(e)||Nd(e):!1}var tR=Object.prototype.constructor.toString(),h2=new WeakMap;function NE(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if(typeof r!="function")return!1;let n=h2.get(r);return n===void 0&&(n=Function.toString.call(r),h2.set(r,n)),n===tR}function Sf(e,t,r=!0){Sd(e)===0?(r?Reflect.ownKeys(e):Object.keys(e)).forEach(l=>{t(l,e[l],e)}):e.forEach((n,l)=>t(l,n,e))}function Sd(e){const t=e[Lr];return t?t.type_:Array.isArray(e)?1:Ws(e)?2:Nd(e)?3:0}function Sy(e,t){return Sd(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function OE(e,t,r){const n=Sd(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function rR(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ws(e){return e instanceof Map}function Nd(e){return e instanceof Set}function Ti(e){return e.copy_||e.base_}function Ny(e,t){if(Ws(e))return new Map(e);if(Nd(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=NE(e);if(t===!0||t==="class_only"&&!r){const n=Object.getOwnPropertyDescriptors(e);delete n[Lr];let l=Reflect.ownKeys(n);for(let s=0;s1&&Object.defineProperties(e,{set:Ic,add:Ic,clear:Ic,delete:Ic}),Object.freeze(e),t&&Object.values(e).forEach(r=>I0(r,!0))),e}function nR(){un(2)}var Ic={value:nR};function Od(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var aR={};function Zi(e){const t=aR[e];return t||un(0,e),t}var Rs;function AE(){return Rs}function iR(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function m2(e,t){t&&(Zi("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Oy(e){Ay(e),e.drafts_.forEach(lR),e.drafts_=null}function Ay(e){e===Rs&&(Rs=e.parent_)}function p2(e){return Rs=iR(Rs,e)}function lR(e){const t=e[Lr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function v2(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return e!==void 0&&e!==r?(r[Lr].modified_&&(Oy(t),un(4)),Fi(e)&&(e=Nf(t,e),t.parent_||Of(t,e)),t.patches_&&Zi("Patches").generateReplacementPatches_(r[Lr].base_,e,t.patches_,t.inversePatches_)):e=Nf(t,r,[]),Oy(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==SE?e:void 0}function Nf(e,t,r){if(Od(t))return t;const n=e.immer_.shouldUseStrictIteration(),l=t[Lr];if(!l)return Sf(t,(s,c)=>y2(e,l,t,s,c,r),n),t;if(l.scope_!==e)return t;if(!l.modified_)return Of(e,l.base_,!0),l.base_;if(!l.finalized_){l.finalized_=!0,l.scope_.unfinalizedDrafts_--;const s=l.copy_;let c=s,d=!1;l.type_===3&&(c=new Set(s),s.clear(),d=!0),Sf(c,(h,m)=>y2(e,l,s,h,m,r,d),n),Of(e,s,!1),r&&e.patches_&&Zi("Patches").generatePatches_(l,r,e.patches_,e.inversePatches_)}return l.copy_}function y2(e,t,r,n,l,s,c){if(l==null||typeof l!="object"&&!c)return;const d=Od(l);if(!(d&&!c)){if(no(l)){const h=s&&t&&t.type_!==3&&!Sy(t.assigned_,n)?s.concat(n):void 0,m=Nf(e,l,h);if(OE(r,n,m),no(m))e.canAutoFreeze_=!1;else return}else c&&r.add(l);if(Fi(l)&&!d){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[n]===l&&d)return;Nf(e,l),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&(Ws(r)?r.has(n):Object.prototype.propertyIsEnumerable.call(r,n))&&Of(e,l)}}}function Of(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&I0(t,r)}function oR(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:AE(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let l=n,s=$0;r&&(l=[n],s=Ls);const{revoke:c,proxy:d}=Proxy.revocable(l,s);return n.draft_=d,n.revoke_=c,d}var $0={get(e,t){if(t===Lr)return e;const r=Ti(e);if(!Sy(r,t))return sR(e,r,t);const n=r[t];return e.finalized_||!Fi(n)?n:n===jv(e.base_,t)?(_v(e),e.copy_[t]=Cy(n,e)):n},has(e,t){return t in Ti(e)},ownKeys(e){return Reflect.ownKeys(Ti(e))},set(e,t,r){const n=EE(Ti(e),t);if(n!=null&&n.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const l=jv(Ti(e),t),s=l==null?void 0:l[Lr];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(rR(r,l)&&(r!==void 0||Sy(e.base_,t)))return!0;_v(e),Ey(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return jv(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,_v(e),Ey(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const r=Ti(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){un(11)},getPrototypeOf(e){return zs(e.base_)},setPrototypeOf(){un(12)}},Ls={};Sf($0,(e,t)=>{Ls[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ls.deleteProperty=function(e,t){return Ls.set.call(this,e,t,void 0)};Ls.set=function(e,t,r){return $0.set.call(this,e[0],t,r,e[0])};function jv(e,t){const r=e[Lr];return(r?Ti(r):e)[t]}function sR(e,t,r){var l;const n=EE(t,r);return n?"value"in n?n.value:(l=n.get)==null?void 0:l.call(e.draft_):void 0}function EE(e,t){if(!(t in e))return;let r=zs(e);for(;r;){const n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=zs(r)}}function Ey(e){e.modified_||(e.modified_=!0,e.parent_&&Ey(e.parent_))}function _v(e){e.copy_||(e.copy_=Ny(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var uR=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,r,n)=>{if(typeof t=="function"&&typeof r!="function"){const s=r;r=t;const c=this;return function(h=s,...m){return c.produce(h,p=>r.call(this,p,...m))}}typeof r!="function"&&un(6),n!==void 0&&typeof n!="function"&&un(7);let l;if(Fi(t)){const s=p2(this),c=Cy(t,void 0);let d=!0;try{l=r(c),d=!1}finally{d?Oy(s):Ay(s)}return m2(s,n),v2(l,s)}else if(!t||typeof t!="object"){if(l=r(t),l===void 0&&(l=t),l===SE&&(l=void 0),this.autoFreeze_&&I0(l,!0),n){const s=[],c=[];Zi("Patches").generateReplacementPatches_(t,l,s,c),n(s,c)}return l}else un(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(c,...d)=>this.produceWithPatches(c,h=>t(h,...d));let n,l;return[this.produce(t,r,(c,d)=>{n=c,l=d}),n,l]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof(e==null?void 0:e.useStrictIteration)=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Fi(e)||un(8),no(e)&&(e=cR(e));const t=p2(this),r=Cy(e,void 0);return r[Lr].isManual_=!0,Ay(t),r}finishDraft(e,t){const r=e&&e[Lr];(!r||!r.isManual_)&&un(9);const{scope_:n}=r;return m2(n,t),v2(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const l=t[r];if(l.path.length===0&&l.op==="replace"){e=l.value;break}}r>-1&&(t=t.slice(r+1));const n=Zi("Patches").applyPatches_;return no(e)?n(e,t):this.produce(e,l=>n(l,t))}};function Cy(e,t){const r=Ws(e)?Zi("MapSet").proxyMap_(e,t):Nd(e)?Zi("MapSet").proxySet_(e,t):oR(e,t);return(t?t.scope_:AE()).drafts_.push(r),r}function cR(e){return no(e)||un(10,e),CE(e)}function CE(e){if(!Fi(e)||Od(e))return e;const t=e[Lr];let r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=Ny(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=Ny(e,!0);return Sf(r,(l,s)=>{OE(r,l,CE(s))},n),t&&(t.finalized_=!1),r}var fR=new uR;fR.produce;var dR={settings:{layout:"horizontal",align:"center",verticalAlign:"middle",itemSorter:"value"},size:{width:0,height:0},payload:[]},kE=jr({name:"legend",initialState:dR,reducers:{setLegendSize(e,t){e.size.width=t.payload.width,e.size.height=t.payload.height},setLegendSettings(e,t){e.settings.align=t.payload.align,e.settings.layout=t.payload.layout,e.settings.verticalAlign=t.payload.verticalAlign,e.settings.itemSorter=t.payload.itemSorter},addLegendPayload:{reducer(e,t){e.payload.push(t.payload)},prepare:st()},replaceLegendPayload:{reducer(e,t){var{prev:r,next:n}=t.payload,l=fn(e).payload.indexOf(r);l>-1&&(e.payload[l]=n)},prepare:st()},removeLegendPayload:{reducer(e,t){var r=fn(e).payload.indexOf(t.payload);r>-1&&e.payload.splice(r,1)},prepare:st()}}}),{setLegendSize:g2,setLegendSettings:hR,addLegendPayload:ME,replaceLegendPayload:TE,removeLegendPayload:DE}=kE.actions,mR=kE.reducer,pR=["contextPayload"];function ky(){return ky=Object.assign?Object.assign.bind():function(e){for(var t=1;t{t(hR(e))},[t,e]),null}function NR(e){var t=rt();return b.useEffect(()=>(t(g2(e)),()=>{t(g2({width:0,height:0}))}),[t,e]),null}function OR(e,t,r,n){return e==="vertical"&&t!=null?{height:t}:e==="horizontal"?{width:r||n}:null}var AR={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",layout:"horizontal",verticalAlign:"bottom"};function PE(e){var t=Mt(e,AR),r=sz(),n=iP(),l=J8(),{width:s,height:c,wrapperStyle:d,portal:h}=t,[m,p]=RA([r]),y=z0(),x=R0();if(y==null||x==null)return null;var w=y-((l==null?void 0:l.left)||0)-((l==null?void 0:l.right)||0),j=OR(t.layout,c,s,w),_=h?d:ao(ao({position:"absolute",width:(j==null?void 0:j.width)||s||"auto",height:(j==null?void 0:j.height)||c||"auto"},_R(d,t,l,y,x,m)),d),N=h??n;if(N==null||r==null)return null;var A=b.createElement("div",{className:"recharts-legend-wrapper",style:_,ref:p},b.createElement(SR,{layout:t.layout,align:t.align,verticalAlign:t.verticalAlign,itemSorter:t.itemSorter}),!h&&b.createElement(NR,{width:m.width,height:m.height}),b.createElement(jR,ky({},t,j,{margin:l,chartWidth:y,chartHeight:x,contextPayload:r})));return Jt.createPortal(A,N)}PE.displayName="Legend";function My(){return My=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var{separator:t=ql.separator,contentStyle:r,itemStyle:n,labelStyle:l=ql.labelStyle,payload:s,formatter:c,itemSorter:d,wrapperClassName:h,labelClassName:m,label:p,labelFormatter:y,accessibilityLayer:x=ql.accessibilityLayer}=e,w=()=>{if(s&&s.length){var z={padding:0,margin:0},T=(d?ud(s,d):s).map((R,$)=>{if(R.type==="none")return null;var Z=R.formatter||c||MR,{value:X,name:L}=R,K=X,se=L;if(Z){var ce=Z(X,L,R,$,s);if(Array.isArray(ce))[K,se]=ce;else if(ce!=null)K=ce;else return null}var he=vs(vs({},ql.itemStyle),{},{color:R.color||ql.itemStyle.color},n);return b.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat($),style:he},An(se)?b.createElement("span",{className:"recharts-tooltip-item-name"},se):null,An(se)?b.createElement("span",{className:"recharts-tooltip-item-separator"},t):null,b.createElement("span",{className:"recharts-tooltip-item-value"},K),b.createElement("span",{className:"recharts-tooltip-item-unit"},R.unit||""))});return b.createElement("ul",{className:"recharts-tooltip-item-list",style:z},T)}return null},j=vs(vs({},ql.contentStyle),r),_=vs({margin:0},l),N=!xt(p),A=N?p:"",O=Ue("recharts-default-tooltip",h),P=Ue("recharts-tooltip-label",m);N&&y&&s!==void 0&&s!==null&&(A=y(p,s));var k=x?{role:"status","aria-live":"assertive"}:{};return b.createElement("div",My({className:O,style:j},k),b.createElement("p",{className:P,style:_},b.isValidElement(A)?A:"".concat(A)),w())},ys="recharts-tooltip-wrapper",DR={visibility:"hidden"};function PR(e){var{coordinate:t,translateX:r,translateY:n}=e;return Ue(ys,{["".concat(ys,"-right")]:de(r)&&t&&de(t.x)&&r>=t.x,["".concat(ys,"-left")]:de(r)&&t&&de(t.x)&&r=t.y,["".concat(ys,"-top")]:de(n)&&t&&de(t.y)&&n0?l:0),y=r[n]+l;if(t[n])return c[n]?p:y;var x=h[n];if(x==null)return 0;if(c[n]){var w=p,j=x;return wN?Math.max(p,x):Math.max(y,x)}function zR(e){var{translateX:t,translateY:r,useTranslate3d:n}=e;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function RR(e){var{allowEscapeViewBox:t,coordinate:r,offsetTop:n,offsetLeft:l,position:s,reverseDirection:c,tooltipBox:d,useTranslate3d:h,viewBox:m}=e,p,y,x;return d.height>0&&d.width>0&&r?(y=w2({allowEscapeViewBox:t,coordinate:r,key:"x",offset:l,position:s,reverseDirection:c,tooltipDimension:d.width,viewBox:m,viewBoxDimension:m.width}),x=w2({allowEscapeViewBox:t,coordinate:r,key:"y",offset:n,position:s,reverseDirection:c,tooltipDimension:d.height,viewBox:m,viewBoxDimension:m.height}),p=zR({translateX:y,translateY:x,useTranslate3d:h})):p=DR,{cssProperties:p,cssClasses:PR({translateX:y,translateY:x,coordinate:r})}}function j2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function $c(e){for(var t=1;t{if(t.key==="Escape"){var r,n,l,s;this.setState({dismissed:!0,dismissedAtCoordinate:{x:(r=(n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==null&&r!==void 0?r:0,y:(l=(s=this.props.coordinate)===null||s===void 0?void 0:s.y)!==null&&l!==void 0?l:0}})}})}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}componentDidUpdate(){var t,r;this.state.dismissed&&(((t=this.props.coordinate)===null||t===void 0?void 0:t.x)!==this.state.dismissedAtCoordinate.x||((r=this.props.coordinate)===null||r===void 0?void 0:r.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}render(){var{active:t,allowEscapeViewBox:r,animationDuration:n,animationEasing:l,children:s,coordinate:c,hasPayload:d,isAnimationActive:h,offset:m,position:p,reverseDirection:y,useTranslate3d:x,viewBox:w,wrapperStyle:j,lastBoundingBox:_,innerRef:N,hasPortalFromProps:A}=this.props,O=typeof m=="number"?m:m.x,P=typeof m=="number"?m:m.y,{cssClasses:k,cssProperties:z}=RR({allowEscapeViewBox:r,coordinate:c,offsetLeft:O,offsetTop:P,position:p,reverseDirection:y,tooltipBox:{height:_.height,width:_.width},useTranslate3d:x,viewBox:w}),T=A?{}:$c($c({transition:h&&t?"transform ".concat(n,"ms ").concat(l):void 0},z),{},{pointerEvents:"none",visibility:!this.state.dismissed&&t&&d?"visible":"hidden",position:"absolute",top:0,left:0}),R=$c($c({},T),{},{visibility:!this.state.dismissed&&t&&d?"visible":"hidden"},j);return b.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:k,style:R,ref:N},s)}}var zE=()=>{var e;return(e=ge(t=>t.rootProps.accessibilityLayer))!==null&&e!==void 0?e:!0};function Dy(){return Dy=Object.assign?Object.assign.bind():function(e){for(var t=1;tke(e.x)&&ke(e.y),O2=e=>e.base!=null&&Af(e.base)&&Af(e),gs=e=>e.x,xs=e=>e.y,HR=(e,t)=>{if(typeof e=="function")return e;var r="curve".concat(Gs(e));if((r==="curveMonotone"||r==="curveBump")&&t){var n=N2["".concat(r).concat(t==="vertical"?"Y":"X")];if(n)return n}return N2[r]||od},A2={connectNulls:!1,type:"linear"},KR=e=>{var{type:t=A2.type,points:r=[],baseLine:n,layout:l,connectNulls:s=A2.connectNulls}=e,c=HR(t,l),d=s?r.filter(Af):r;if(Array.isArray(n)){var h,m=r.map((j,_)=>S2(S2({},j),{},{base:n[_]}));l==="vertical"?h=Mc().y(xs).x1(gs).x0(j=>j.base.x):h=Mc().x(gs).y1(xs).y0(j=>j.base.y);var p=h.defined(O2).curve(c),y=s?m.filter(O2):m;return p(y)}var x;l==="vertical"&&de(n)?x=Mc().y(xs).x1(gs).x0(n):de(n)?x=Mc().x(gs).y1(xs).y0(n):x=oA().x(gs).y(xs);var w=x.defined(Af).curve(c);return w(d)},Jl=e=>{var{className:t,points:r,path:n,pathRef:l}=e,s=el();if((!r||!r.length)&&!n)return null;var c={type:e.type,points:e.points,baseLine:e.baseLine,layout:e.layout||s,connectNulls:e.connectNulls},d=r&&r.length?KR(c):n;return b.createElement("path",Dy({},wr(e),j0(e),{className:Ue("recharts-curve",t),d:d===null?void 0:d,ref:l}))},YR=["x","y","top","left","width","height","className"];function Py(){return Py=Object.assign?Object.assign.bind():function(e){for(var t=1;t"M".concat(e,",").concat(l,"v").concat(n,"M").concat(s,",").concat(t,"h").concat(r),JR=e=>{var{x:t=0,y:r=0,top:n=0,left:l=0,width:s=0,height:c=0,className:d}=e,h=ZR(e,YR),m=GR({x:t,y:r,top:n,left:l,width:s,height:c},h);return!de(t)||!de(r)||!de(s)||!de(c)||!de(n)||!de(l)?null:b.createElement("path",Py({},ur(m),{className:Ue("recharts-cross",d),d:WR(t,r,s,c,n,l)}))};function e7(e,t,r,n){var l=n/2;return{stroke:"none",fill:"#ccc",x:e==="horizontal"?t.x-l:r.left+.5,y:e==="horizontal"?r.top+.5:t.y-l,width:e==="horizontal"?n:r.width-1,height:e==="horizontal"?r.height-1:n}}function C2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function k2(e){for(var t=1;te.replace(/([A-Z])/g,t=>"-".concat(t.toLowerCase())),RE=(e,t,r)=>e.map(n=>"".concat(a7(n)," ").concat(t,"ms ").concat(r)).join(","),i7=(e,t)=>[Object.keys(e),Object.keys(t)].reduce((r,n)=>r.filter(l=>n.includes(l))),Is=(e,t)=>Object.keys(t).reduce((r,n)=>k2(k2({},r),{},{[n]:e(n,t[n])}),{});function M2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Dt(e){for(var t=1;te+(t-e)*r,zy=e=>{var{from:t,to:r}=e;return t!==r},LE=(e,t,r)=>{var n=Is((l,s)=>{if(zy(s)){var[c,d]=e(s.from,s.to,s.velocity);return Dt(Dt({},s),{},{from:c,velocity:d})}return s},t);return r<1?Is((l,s)=>zy(s)&&n[l]!=null?Dt(Dt({},s),{},{velocity:Ef(s.velocity,n[l].velocity,r),from:Ef(s.from,n[l].from,r)}):s,t):LE(e,n,r-1)};function u7(e,t,r,n,l,s){var c,d=n.reduce((x,w)=>Dt(Dt({},x),{},{[w]:{from:e[w],velocity:0,to:t[w]}}),{}),h=()=>Is((x,w)=>w.from,d),m=()=>!Object.values(d).filter(zy).length,p=null,y=x=>{c||(c=x);var w=x-c,j=w/r.dt;d=LE(r,d,j),l(Dt(Dt(Dt({},e),t),h())),c=x,m()||(p=s.setTimeout(y))};return()=>(p=s.setTimeout(y),()=>{var x;(x=p)===null||x===void 0||x()})}function c7(e,t,r,n,l,s,c){var d=null,h=l.reduce((y,x)=>{var w=e[x],j=t[x];return w==null||j==null?y:Dt(Dt({},y),{},{[x]:[w,j]})},{}),m,p=y=>{m||(m=y);var x=(y-m)/n,w=Is((_,N)=>Ef(...N,r(x)),h);if(s(Dt(Dt(Dt({},e),t),w)),x<1)d=c.setTimeout(p);else{var j=Is((_,N)=>Ef(...N,r(1)),h);s(Dt(Dt(Dt({},e),t),j))}};return()=>(d=c.setTimeout(p),()=>{var y;(y=d)===null||y===void 0||y()})}const f7=(e,t,r,n,l,s)=>{var c=i7(e,t);return r==null?()=>(l(Dt(Dt({},e),t)),()=>{}):r.isStepper===!0?u7(e,t,r,c,l,s):c7(e,t,r,n,c,l,s)};var Cf=1e-4,IE=(e,t)=>[0,3*e,3*t-6*e,3*e-3*t+1],$E=(e,t)=>e.map((r,n)=>r*t**n).reduce((r,n)=>r+n),T2=(e,t)=>r=>{var n=IE(e,t);return $E(n,r)},d7=(e,t)=>r=>{var n=IE(e,t),l=[...n.map((s,c)=>s*c).slice(1),0];return $E(l,r)},h7=e=>{var t,r=e.split("(");if(r.length!==2||r[0]!=="cubic-bezier")return null;var n=(t=r[1])===null||t===void 0||(t=t.split(")")[0])===null||t===void 0?void 0:t.split(",");if(n==null||n.length!==4)return null;var l=n.map(s=>parseFloat(s));return[l[0],l[1],l[2],l[3]]},m7=function(){for(var t=arguments.length,r=new Array(t),n=0;n{var l=T2(e,r),s=T2(t,n),c=d7(e,r),d=m=>m>1?1:m<0?0:m,h=m=>{for(var p=m>1?1:m,y=p,x=0;x<8;++x){var w=l(y)-p,j=c(y);if(Math.abs(w-p)0&&arguments[0]!==void 0?arguments[0]:{},{stiff:r=100,damping:n=8,dt:l=17}=t,s=(c,d,h)=>{var m=-(c-d)*r,p=h*n,y=h+(m-p)*l/1e3,x=h*l/1e3+c;return Math.abs(x-d){if(typeof e=="string")switch(e){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return D2(e);case"spring":return v7();default:if(e.split("(")[0]==="cubic-bezier")return D2(e)}return typeof e=="function"?e:null};function g7(e){var t,r=()=>null,n=!1,l=null,s=c=>{if(!n){if(Array.isArray(c)){if(!c.length)return;var d=c,[h,...m]=d;if(typeof h=="number"){l=e.setTimeout(s.bind(null,m),h);return}s(h),l=e.setTimeout(s.bind(null,m));return}typeof c=="string"&&(t=c,r(t)),typeof c=="object"&&(t=c,r(t)),typeof c=="function"&&c()}};return{stop:()=>{n=!0},start:c=>{n=!1,l&&(l(),l=null),s(c)},subscribe:c=>(r=c,()=>{r=()=>null}),getTimeoutController:()=>e}}class x7{setTimeout(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=performance.now(),l=null,s=c=>{c-n>=r?t(c):typeof requestAnimationFrame=="function"&&(l=requestAnimationFrame(s))};return l=requestAnimationFrame(s),()=>{l!=null&&cancelAnimationFrame(l)}}}function b7(){return g7(new x7)}var w7=b.createContext(b7);function j7(e,t){var r=b.useContext(w7);return b.useMemo(()=>t??r(e),[e,t,r])}var _7=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),Js={isSsr:_7()},S7={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},P2={t:0},Sv={t:1};function eu(e){var t=Mt(e,S7),{isActive:r,canBegin:n,duration:l,easing:s,begin:c,onAnimationEnd:d,onAnimationStart:h,children:m}=t,p=r==="auto"?!Js.isSsr:r,y=j7(t.animationId,t.animationManager),[x,w]=b.useState(p?P2:Sv),j=b.useRef(null);return b.useEffect(()=>{p||w(Sv)},[p]),b.useEffect(()=>{if(!p||!n)return Ji;var _=f7(P2,Sv,y7(s),l,w,y.getTimeoutController()),N=()=>{j.current=_()};return y.start([h,c,N,l,d]),()=>{y.stop(),j.current&&j.current(),d()}},[p,n,l,s,c,h,d,y]),m(x.t)}function tu(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",r=b.useRef(Ms(t)),n=b.useRef(e);return n.current!==e&&(r.current=Ms(t),n.current=e),r.current}var N7=["radius"],O7=["radius"],z2,R2,L2,I2,$2,B2,q2,U2,H2,K2;function Y2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function G2(e){for(var t=1;t{var s=ti(r),c=ti(n),d=Math.min(Math.abs(s)/2,Math.abs(c)/2),h=c>=0?1:-1,m=s>=0?1:-1,p=c>=0&&s>=0||c<0&&s<0?1:0,y;if(d>0&&Array.isArray(l)){for(var x=[0,0,0,0],w=0,j=4;wd?d:N}y=yt(z2||(z2=wn(["M",",",""])),e,t+h*x[0]),x[0]>0&&(y+=yt(R2||(R2=wn(["A ",",",",0,0,",",",",",""])),x[0],x[0],p,e+m*x[0],t)),y+=yt(L2||(L2=wn(["L ",",",""])),e+r-m*x[1],t),x[1]>0&&(y+=yt(I2||(I2=wn(["A ",",",",0,0,",`, + `,",",""])),x[1],x[1],p,e+r,t+h*x[1])),y+=yt($2||($2=wn(["L ",",",""])),e+r,t+n-h*x[2]),x[2]>0&&(y+=yt(B2||(B2=wn(["A ",",",",0,0,",`, + `,",",""])),x[2],x[2],p,e+r-m*x[2],t+n)),y+=yt(q2||(q2=wn(["L ",",",""])),e+m*x[3],t+n),x[3]>0&&(y+=yt(U2||(U2=wn(["A ",",",",0,0,",`, + `,",",""])),x[3],x[3],p,e,t+n-h*x[3])),y+="Z"}else if(d>0&&l===+l&&l>0){var A=Math.min(d,l);y=yt(H2||(H2=wn(["M ",",",` + A `,",",",0,0,",",",",",` + L `,",",` + A `,",",",0,0,",",",",",` + L `,",",` + A `,",",",0,0,",",",",",` + L `,",",` + A `,",",",0,0,",",",","," Z"])),e,t+h*A,A,A,p,e+m*A,t,e+r-m*A,t,A,A,p,e+r,t+h*A,e+r,t+n-h*A,A,A,p,e+r-m*A,t+n,e+m*A,t+n,A,A,p,e,t+n-h*A)}else y=yt(K2||(K2=wn(["M ",","," h "," v "," h "," Z"])),e,t,r,n,-r);return y},F2={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},BE=e=>{var t=Mt(e,F2),r=b.useRef(null),[n,l]=b.useState(-1);b.useEffect(()=>{if(r.current&&r.current.getTotalLength)try{var W=r.current.getTotalLength();W&&l(W)}catch{}},[]);var{x:s,y:c,width:d,height:h,radius:m,className:p}=t,{animationEasing:y,animationDuration:x,animationBegin:w,isAnimationActive:j,isUpdateAnimationActive:_}=t,N=b.useRef(d),A=b.useRef(h),O=b.useRef(s),P=b.useRef(c),k=b.useMemo(()=>({x:s,y:c,width:d,height:h,radius:m}),[s,c,d,h,m]),z=tu(k,"rectangle-");if(s!==+s||c!==+c||d!==+d||h!==+h||d===0||h===0)return null;var T=Ue("recharts-rectangle",p);if(!_){var R=ur(t),{radius:$}=R,Z=V2(R,N7);return b.createElement("path",kf({},Z,{x:ti(s),y:ti(c),width:ti(d),height:ti(h),radius:typeof m=="number"?m:void 0,className:T,d:X2(s,c,d,h,m)}))}var X=N.current,L=A.current,K=O.current,se=P.current,ce="0px ".concat(n===-1?1:n,"px"),he="".concat(n,"px 0px"),q=RE(["strokeDasharray"],x,typeof y=="string"?y:F2.animationEasing);return b.createElement(eu,{animationId:z,key:z,canBegin:n>0,duration:x,easing:y,isActive:_,begin:w},W=>{var ue=lt(X,d,W),te=lt(L,h,W),M=lt(K,s,W),C=lt(se,c,W);r.current&&(N.current=ue,A.current=te,O.current=M,P.current=C);var U;j?W>0?U={transition:q,strokeDasharray:he}:U={strokeDasharray:ce}:U={strokeDasharray:he};var ee=ur(t),{radius:le}=ee,me=V2(ee,O7);return b.createElement("path",kf({},me,{radius:typeof m=="number"?m:void 0,className:T,d:X2(M,C,ue,te,m),ref:r,style:G2(G2({},U),t.style)}))})};function Z2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Q2(e){for(var t=1;te*180/Math.PI,Et=(e,t,r,n)=>({x:e+Math.cos(-Mf*n)*r,y:t+Math.sin(-Mf*n)*r}),qE=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},z7=(e,t)=>{var{x:r,y:n}=e,{x:l,y:s}=t;return Math.sqrt((r-l)**2+(n-s)**2)},R7=(e,t)=>{var{x:r,y:n}=e,{cx:l,cy:s}=t,c=z7({x:r,y:n},{x:l,y:s});if(c<=0)return{radius:c,angle:0};var d=(r-l)/c,h=Math.acos(d);return n>s&&(h=2*Math.PI-h),{radius:c,angle:P7(h),angleInRadian:h}},L7=e=>{var{startAngle:t,endAngle:r}=e,n=Math.floor(t/360),l=Math.floor(r/360),s=Math.min(n,l);return{startAngle:t-s*360,endAngle:r-s*360}},I7=(e,t)=>{var{startAngle:r,endAngle:n}=t,l=Math.floor(r/360),s=Math.floor(n/360),c=Math.min(l,s);return e+c*360},$7=(e,t)=>{var{chartX:r,chartY:n}=e,{radius:l,angle:s}=R7({x:r,y:n},t),{innerRadius:c,outerRadius:d}=t;if(ld||l===0)return null;var{startAngle:h,endAngle:m}=L7(t),p=s,y;if(h<=m){for(;p>m;)p-=360;for(;p=h&&p<=m}else{for(;p>h;)p-=360;for(;p=m&&p<=h}return y?Q2(Q2({},t),{},{radius:l,angle:I7(p,t)}):null};function UE(e){var{cx:t,cy:r,radius:n,startAngle:l,endAngle:s}=e,c=Et(t,r,n,l),d=Et(t,r,n,s);return{points:[c,d],cx:t,cy:r,radius:n,startAngle:l,endAngle:s}}var W2,J2,eS,tS,rS,nS,aS;function Ry(){return Ry=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var r=Ht(t-e),n=Math.min(Math.abs(t-e),359.999);return r*n},Bc=e=>{var{cx:t,cy:r,radius:n,angle:l,sign:s,isExternal:c,cornerRadius:d,cornerIsExternal:h}=e,m=d*(c?1:-1)+n,p=Math.asin(d/m)/Mf,y=h?l:l+s*p,x=Et(t,r,m,y),w=Et(t,r,n,y),j=h?l-s*p:l,_=Et(t,r,m*Math.cos(p*Mf),j);return{center:x,circleTangency:w,lineTangency:_,theta:p}},HE=e=>{var{cx:t,cy:r,innerRadius:n,outerRadius:l,startAngle:s,endAngle:c}=e,d=B7(s,c),h=s+d,m=Et(t,r,l,s),p=Et(t,r,l,h),y=yt(W2||(W2=Pi(["M ",",",` + A `,",",`,0, + `,",",`, + `,",",` + `])),m.x,m.y,l,l,+(Math.abs(d)>180),+(s>h),p.x,p.y);if(n>0){var x=Et(t,r,n,s),w=Et(t,r,n,h);y+=yt(J2||(J2=Pi(["L ",",",` + A `,",",`,0, + `,",",`, + `,","," Z"])),w.x,w.y,n,n,+(Math.abs(d)>180),+(s<=h),x.x,x.y)}else y+=yt(eS||(eS=Pi(["L ",","," Z"])),t,r);return y},q7=e=>{var{cx:t,cy:r,innerRadius:n,outerRadius:l,cornerRadius:s,forceCornerRadius:c,cornerIsExternal:d,startAngle:h,endAngle:m}=e,p=Ht(m-h),{circleTangency:y,lineTangency:x,theta:w}=Bc({cx:t,cy:r,radius:l,angle:h,sign:p,cornerRadius:s,cornerIsExternal:d}),{circleTangency:j,lineTangency:_,theta:N}=Bc({cx:t,cy:r,radius:l,angle:m,sign:-p,cornerRadius:s,cornerIsExternal:d}),A=d?Math.abs(h-m):Math.abs(h-m)-w-N;if(A<0)return c?yt(tS||(tS=Pi(["M ",",",` + a`,",",",0,0,1,",`,0 + a`,",",",0,0,1,",`,0 + `])),x.x,x.y,s,s,s*2,s,s,-s*2):HE({cx:t,cy:r,innerRadius:n,outerRadius:l,startAngle:h,endAngle:m});var O=yt(rS||(rS=Pi(["M ",",",` + A`,",",",0,0,",",",",",` + A`,",",",0,",",",",",",",` + A`,",",",0,0,",",",",",` + `])),x.x,x.y,s,s,+(p<0),y.x,y.y,l,l,+(A>180),+(p<0),j.x,j.y,s,s,+(p<0),_.x,_.y);if(n>0){var{circleTangency:P,lineTangency:k,theta:z}=Bc({cx:t,cy:r,radius:n,angle:h,sign:p,isExternal:!0,cornerRadius:s,cornerIsExternal:d}),{circleTangency:T,lineTangency:R,theta:$}=Bc({cx:t,cy:r,radius:n,angle:m,sign:-p,isExternal:!0,cornerRadius:s,cornerIsExternal:d}),Z=d?Math.abs(h-m):Math.abs(h-m)-z-$;if(Z<0&&s===0)return"".concat(O,"L").concat(t,",").concat(r,"Z");O+=yt(nS||(nS=Pi(["L",",",` + A`,",",",0,0,",",",",",` + A`,",",",0,",",",",",",",` + A`,",",",0,0,",",",",","Z"])),R.x,R.y,s,s,+(p<0),T.x,T.y,n,n,+(Z>180),+(p>0),P.x,P.y,s,s,+(p<0),k.x,k.y)}else O+=yt(aS||(aS=Pi(["L",",","Z"])),t,r);return O},U7={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},KE=e=>{var t=Mt(e,U7),{cx:r,cy:n,innerRadius:l,outerRadius:s,cornerRadius:c,forceCornerRadius:d,cornerIsExternal:h,startAngle:m,endAngle:p,className:y}=t;if(s0&&Math.abs(m-p)<360?_=q7({cx:r,cy:n,innerRadius:l,outerRadius:s,cornerRadius:Math.min(j,w/2),forceCornerRadius:d,cornerIsExternal:h,startAngle:m,endAngle:p}):_=HE({cx:r,cy:n,innerRadius:l,outerRadius:s,startAngle:m,endAngle:p}),b.createElement("path",Ry({},ur(t),{className:x,d:_}))};function H7(e,t,r){if(e==="horizontal")return[{x:t.x,y:r.top},{x:t.x,y:r.top+r.height}];if(e==="vertical")return[{x:r.left,y:t.y},{x:r.left+r.width,y:t.y}];if(jA(t)){if(e==="centric"){var{cx:n,cy:l,innerRadius:s,outerRadius:c,angle:d}=t,h=Et(n,l,s,d),m=Et(n,l,c,d);return[{x:h.x,y:h.y},{x:m.x,y:m.y}]}return UE(t)}}var Nv={},Ov={},Av={},iS;function K7(){return iS||(iS=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=DA();function r(n){return t.isSymbol(n)?NaN:Number(n)}e.toNumber=r})(Av)),Av}var lS;function Y7(){return lS||(lS=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=K7();function r(n){return n?(n=t.toNumber(n),n===1/0||n===-1/0?(n<0?-1:1)*Number.MAX_VALUE:n===n?n:0):n===0?n:0}e.toFinite=r})(Ov)),Ov}var oS;function G7(){return oS||(oS=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=PA(),r=Y7();function n(l,s,c){c&&typeof c!="number"&&t.isIterateeCall(l,s,c)&&(s=c=void 0),l=r.toFinite(l),s===void 0?(s=l,l=0):s=r.toFinite(s),c=c===void 0?lt?1:e>=t?0:NaN}function F7(e,t){return e==null||t==null?NaN:te?1:t>=e?0:NaN}function B0(e){let t,r,n;e.length!==2?(t=ri,r=(d,h)=>ri(e(d),h),n=(d,h)=>e(d)-h):(t=e===ri||e===F7?e:Z7,r=e,n=e);function l(d,h,m=0,p=d.length){if(m>>1;r(d[y],h)<0?m=y+1:p=y}while(m>>1;r(d[y],h)<=0?m=y+1:p=y}while(mm&&n(d[y-1],h)>-n(d[y],h)?y-1:y}return{left:l,center:c,right:s}}function Z7(){return 0}function GE(e){return e===null?NaN:+e}function*Q7(e,t){for(let r of e)r!=null&&(r=+r)>=r&&(yield r)}const W7=B0(ri),ru=W7.right;B0(GE).center;class uS extends Map{constructor(t,r=tL){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,l]of t)this.set(n,l)}get(t){return super.get(cS(this,t))}has(t){return super.has(cS(this,t))}set(t,r){return super.set(J7(this,t),r)}delete(t){return super.delete(eL(this,t))}}function cS({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):r}function J7({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):(e.set(n,r),r)}function eL({_intern:e,_key:t},r){const n=t(r);return e.has(n)&&(r=e.get(n),e.delete(n)),r}function tL(e){return e!==null&&typeof e=="object"?e.valueOf():e}function rL(e=ri){if(e===ri)return VE;if(typeof e!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=e(t,r);return n||n===0?n:(e(r,r)===0)-(e(t,t)===0)}}function VE(e,t){return(e==null||!(e>=e))-(t==null||!(t>=t))||(et?1:0)}const nL=Math.sqrt(50),aL=Math.sqrt(10),iL=Math.sqrt(2);function Tf(e,t,r){const n=(t-e)/Math.max(0,r),l=Math.floor(Math.log10(n)),s=n/Math.pow(10,l),c=s>=nL?10:s>=aL?5:s>=iL?2:1;let d,h,m;return l<0?(m=Math.pow(10,-l)/c,d=Math.round(e*m),h=Math.round(t*m),d/mt&&--h,m=-m):(m=Math.pow(10,l)*c,d=Math.round(e/m),h=Math.round(t/m),d*mt&&--h),h0))return[];if(e===t)return[e];const n=t=l))return[];const d=s-l+1,h=new Array(d);if(n)if(c<0)for(let m=0;m=n)&&(r=n);return r}function dS(e,t){let r;for(const n of e)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function XE(e,t,r=0,n=1/0,l){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(e.length-1,n)),!(r<=t&&t<=n))return e;for(l=l===void 0?VE:rL(l);n>r;){if(n-r>600){const h=n-r+1,m=t-r+1,p=Math.log(h),y=.5*Math.exp(2*p/3),x=.5*Math.sqrt(p*y*(h-y)/h)*(m-h/2<0?-1:1),w=Math.max(r,Math.floor(t-m*y/h+x)),j=Math.min(n,Math.floor(t+(h-m)*y/h+x));XE(e,t,w,j,l)}const s=e[t];let c=r,d=n;for(bs(e,r,t),l(e[n],s)>0&&bs(e,r,n);c0;)--d}l(e[r],s)===0?bs(e,r,d):(++d,bs(e,d,n)),d<=t&&(r=d+1),t<=d&&(n=d-1)}return e}function bs(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function lL(e,t,r){if(e=Float64Array.from(Q7(e)),!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return dS(e);if(t>=1)return fS(e);var n,l=(n-1)*t,s=Math.floor(l),c=fS(XE(e,s).subarray(0,s+1)),d=dS(e.subarray(s+1));return c+(d-c)*(l-s)}}function oL(e,t,r=GE){if(!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(e[0],0,e);if(t>=1)return+r(e[n-1],n-1,e);var n,l=(n-1)*t,s=Math.floor(l),c=+r(e[s],s,e),d=+r(e[s+1],s+1,e);return c+(d-c)*(l-s)}}function sL(e,t,r){e=+e,t=+t,r=(l=arguments.length)<2?(t=e,e=0,1):l<3?1:+r;for(var n=-1,l=Math.max(0,Math.ceil((t-e)/r))|0,s=new Array(l);++n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?qc(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?qc(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=fL.exec(e))?new br(t[1],t[2],t[3],1):(t=dL.exec(e))?new br(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=hL.exec(e))?qc(t[1],t[2],t[3],t[4]):(t=mL.exec(e))?qc(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=pL.exec(e))?xS(t[1],t[2]/100,t[3]/100,1):(t=vL.exec(e))?xS(t[1],t[2]/100,t[3]/100,t[4]):hS.hasOwnProperty(e)?vS(hS[e]):e==="transparent"?new br(NaN,NaN,NaN,0):null}function vS(e){return new br(e>>16&255,e>>8&255,e&255,1)}function qc(e,t,r,n){return n<=0&&(e=t=r=NaN),new br(e,t,r,n)}function xL(e){return e instanceof nu||(e=qs(e)),e?(e=e.rgb(),new br(e.r,e.g,e.b,e.opacity)):new br}function qy(e,t,r,n){return arguments.length===1?xL(e):new br(e,t,r,n??1)}function br(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}H0(br,qy,ZE(nu,{brighter(e){return e=e==null?Df:Math.pow(Df,e),new br(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?$s:Math.pow($s,e),new br(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new br($i(this.r),$i(this.g),$i(this.b),Pf(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:yS,formatHex:yS,formatHex8:bL,formatRgb:gS,toString:gS}));function yS(){return`#${zi(this.r)}${zi(this.g)}${zi(this.b)}`}function bL(){return`#${zi(this.r)}${zi(this.g)}${zi(this.b)}${zi((isNaN(this.opacity)?1:this.opacity)*255)}`}function gS(){const e=Pf(this.opacity);return`${e===1?"rgb(":"rgba("}${$i(this.r)}, ${$i(this.g)}, ${$i(this.b)}${e===1?")":`, ${e})`}`}function Pf(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function $i(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function zi(e){return e=$i(e),(e<16?"0":"")+e.toString(16)}function xS(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new cn(e,t,r,n)}function QE(e){if(e instanceof cn)return new cn(e.h,e.s,e.l,e.opacity);if(e instanceof nu||(e=qs(e)),!e)return new cn;if(e instanceof cn)return e;e=e.rgb();var t=e.r/255,r=e.g/255,n=e.b/255,l=Math.min(t,r,n),s=Math.max(t,r,n),c=NaN,d=s-l,h=(s+l)/2;return d?(t===s?c=(r-n)/d+(r0&&h<1?0:c,new cn(c,d,h,e.opacity)}function wL(e,t,r,n){return arguments.length===1?QE(e):new cn(e,t,r,n??1)}function cn(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}H0(cn,wL,ZE(nu,{brighter(e){return e=e==null?Df:Math.pow(Df,e),new cn(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?$s:Math.pow($s,e),new cn(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,l=2*r-n;return new br(Cv(e>=240?e-240:e+120,l,n),Cv(e,l,n),Cv(e<120?e+240:e-120,l,n),this.opacity)},clamp(){return new cn(bS(this.h),Uc(this.s),Uc(this.l),Pf(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Pf(this.opacity);return`${e===1?"hsl(":"hsla("}${bS(this.h)}, ${Uc(this.s)*100}%, ${Uc(this.l)*100}%${e===1?")":`, ${e})`}`}}));function bS(e){return e=(e||0)%360,e<0?e+360:e}function Uc(e){return Math.max(0,Math.min(1,e||0))}function Cv(e,t,r){return(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)*255}const K0=e=>()=>e;function jL(e,t){return function(r){return e+r*t}}function _L(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}function SL(e){return(e=+e)==1?WE:function(t,r){return r-t?_L(t,r,e):K0(isNaN(t)?r:t)}}function WE(e,t){var r=t-e;return r?jL(e,r):K0(isNaN(e)?t:e)}const wS=(function e(t){var r=SL(t);function n(l,s){var c=r((l=qy(l)).r,(s=qy(s)).r),d=r(l.g,s.g),h=r(l.b,s.b),m=WE(l.opacity,s.opacity);return function(p){return l.r=c(p),l.g=d(p),l.b=h(p),l.opacity=m(p),l+""}}return n.gamma=e,n})(1);function NL(e,t){t||(t=[]);var r=e?Math.min(t.length,e.length):0,n=t.slice(),l;return function(s){for(l=0;lr&&(s=t.slice(r,s),d[c]?d[c]+=s:d[++c]=s),(n=n[0])===(l=l[0])?d[c]?d[c]+=l:d[++c]=l:(d[++c]=null,h.push({i:c,x:zf(n,l)})),r=kv.lastIndex;return rt&&(r=e,e=t,t=r),function(n){return Math.max(e,Math.min(t,n))}}function RL(e,t,r){var n=e[0],l=e[1],s=t[0],c=t[1];return l2?LL:RL,h=m=null,y}function y(x){return x==null||isNaN(x=+x)?s:(h||(h=d(e.map(n),t,r)))(n(c(x)))}return y.invert=function(x){return c(l((m||(m=d(t,e.map(n),zf)))(x)))},y.domain=function(x){return arguments.length?(e=Array.from(x,Rf),p()):e.slice()},y.range=function(x){return arguments.length?(t=Array.from(x),p()):t.slice()},y.rangeRound=function(x){return t=Array.from(x),r=Y0,p()},y.clamp=function(x){return arguments.length?(c=x?!0:sr,p()):c!==sr},y.interpolate=function(x){return arguments.length?(r=x,p()):r},y.unknown=function(x){return arguments.length?(s=x,y):s},function(x,w){return n=x,l=w,p()}}function G0(){return Ad()(sr,sr)}function IL(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Lf(e,t){if(!isFinite(e)||e===0)return null;var r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function io(e){return e=Lf(Math.abs(e)),e?e[1]:NaN}function $L(e,t){return function(r,n){for(var l=r.length,s=[],c=0,d=e[0],h=0;l>0&&d>0&&(h+d+1>n&&(d=Math.max(1,n-h)),s.push(r.substring(l-=d,l+d)),!((h+=d+1)>n));)d=e[c=(c+1)%e.length];return s.reverse().join(t)}}function BL(e){return function(t){return t.replace(/[0-9]/g,function(r){return e[+r]})}}var qL=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Us(e){if(!(t=qL.exec(e)))throw new Error("invalid format: "+e);var t;return new V0({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}Us.prototype=V0.prototype;function V0(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}V0.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function UL(e){e:for(var t=e.length,r=1,n=-1,l;r0&&(n=0);break}return n>0?e.slice(0,n)+e.slice(l+1):e}var If;function HL(e,t){var r=Lf(e,t);if(!r)return If=void 0,e.toPrecision(t);var n=r[0],l=r[1],s=l-(If=Math.max(-8,Math.min(8,Math.floor(l/3)))*3)+1,c=n.length;return s===c?n:s>c?n+new Array(s-c+1).join("0"):s>0?n.slice(0,s)+"."+n.slice(s):"0."+new Array(1-s).join("0")+Lf(e,Math.max(0,t+s-1))[0]}function _S(e,t){var r=Lf(e,t);if(!r)return e+"";var n=r[0],l=r[1];return l<0?"0."+new Array(-l).join("0")+n:n.length>l+1?n.slice(0,l+1)+"."+n.slice(l+1):n+new Array(l-n.length+2).join("0")}const SS={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:IL,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>_S(e*100,t),r:_S,s:HL,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function NS(e){return e}var OS=Array.prototype.map,AS=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function KL(e){var t=e.grouping===void 0||e.thousands===void 0?NS:$L(OS.call(e.grouping,Number),e.thousands+""),r=e.currency===void 0?"":e.currency[0]+"",n=e.currency===void 0?"":e.currency[1]+"",l=e.decimal===void 0?".":e.decimal+"",s=e.numerals===void 0?NS:BL(OS.call(e.numerals,String)),c=e.percent===void 0?"%":e.percent+"",d=e.minus===void 0?"−":e.minus+"",h=e.nan===void 0?"NaN":e.nan+"";function m(y,x){y=Us(y);var w=y.fill,j=y.align,_=y.sign,N=y.symbol,A=y.zero,O=y.width,P=y.comma,k=y.precision,z=y.trim,T=y.type;T==="n"?(P=!0,T="g"):SS[T]||(k===void 0&&(k=12),z=!0,T="g"),(A||w==="0"&&j==="=")&&(A=!0,w="0",j="=");var R=(x&&x.prefix!==void 0?x.prefix:"")+(N==="$"?r:N==="#"&&/[boxX]/.test(T)?"0"+T.toLowerCase():""),$=(N==="$"?n:/[%p]/.test(T)?c:"")+(x&&x.suffix!==void 0?x.suffix:""),Z=SS[T],X=/[defgprs%]/.test(T);k=k===void 0?6:/[gprs]/.test(T)?Math.max(1,Math.min(21,k)):Math.max(0,Math.min(20,k));function L(K){var se=R,ce=$,he,q,W;if(T==="c")ce=Z(K)+ce,K="";else{K=+K;var ue=K<0||1/K<0;if(K=isNaN(K)?h:Z(Math.abs(K),k),z&&(K=UL(K)),ue&&+K==0&&_!=="+"&&(ue=!1),se=(ue?_==="("?_:d:_==="-"||_==="("?"":_)+se,ce=(T==="s"&&!isNaN(K)&&If!==void 0?AS[8+If/3]:"")+ce+(ue&&_==="("?")":""),X){for(he=-1,q=K.length;++heW||W>57){ce=(W===46?l+K.slice(he+1):K.slice(he))+ce,K=K.slice(0,he);break}}}P&&!A&&(K=t(K,1/0));var te=se.length+K.length+ce.length,M=te>1)+se+K+ce+M.slice(te);break;default:K=M+se+K+ce;break}return s(K)}return L.toString=function(){return y+""},L}function p(y,x){var w=Math.max(-8,Math.min(8,Math.floor(io(x)/3)))*3,j=Math.pow(10,-w),_=m((y=Us(y),y.type="f",y),{suffix:AS[8+w/3]});return function(N){return _(j*N)}}return{format:m,formatPrefix:p}}var Hc,X0,JE;YL({thousands:",",grouping:[3],currency:["$",""]});function YL(e){return Hc=KL(e),X0=Hc.format,JE=Hc.formatPrefix,Hc}function GL(e){return Math.max(0,-io(Math.abs(e)))}function VL(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(io(t)/3)))*3-io(Math.abs(e)))}function XL(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,io(t)-io(e))+1}function eC(e,t,r,n){var l=$y(e,t,r),s;switch(n=Us(n??",f"),n.type){case"s":{var c=Math.max(Math.abs(e),Math.abs(t));return n.precision==null&&!isNaN(s=VL(l,c))&&(n.precision=s),JE(n,c)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(s=XL(l,Math.max(Math.abs(e),Math.abs(t))))&&(n.precision=s-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(s=GL(l))&&(n.precision=s-(n.type==="%")*2);break}}return X0(n)}function si(e){var t=e.domain;return e.ticks=function(r){var n=t();return Ly(n[0],n[n.length-1],r??10)},e.tickFormat=function(r,n){var l=t();return eC(l[0],l[l.length-1],r??10,n)},e.nice=function(r){r==null&&(r=10);var n=t(),l=0,s=n.length-1,c=n[l],d=n[s],h,m,p=10;for(d0;){if(m=Iy(c,d,r),m===h)return n[l]=c,n[s]=d,t(n);if(m>0)c=Math.floor(c/m)*m,d=Math.ceil(d/m)*m;else if(m<0)c=Math.ceil(c*m)/m,d=Math.floor(d*m)/m;else break;h=m}return e},e}function tC(){var e=G0();return e.copy=function(){return au(e,tC())},rn.apply(e,arguments),si(e)}function rC(e){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(e=Array.from(n,Rf),r):e.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return rC(e).unknown(t)},e=arguments.length?Array.from(e,Rf):[0,1],si(r)}function nC(e,t){e=e.slice();var r=0,n=e.length-1,l=e[r],s=e[n],c;return sMath.pow(e,t)}function JL(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function kS(e){return(t,r)=>-e(-t,r)}function F0(e){const t=e(ES,CS),r=t.domain;let n=10,l,s;function c(){return l=JL(n),s=WL(n),r()[0]<0?(l=kS(l),s=kS(s),e(FL,ZL)):e(ES,CS),t}return t.base=function(d){return arguments.length?(n=+d,c()):n},t.domain=function(d){return arguments.length?(r(d),c()):r()},t.ticks=d=>{const h=r();let m=h[0],p=h[h.length-1];const y=p0){for(;x<=w;++x)for(j=1;jp)break;A.push(_)}}else for(;x<=w;++x)for(j=n-1;j>=1;--j)if(_=x>0?j/s(-x):j*s(x),!(_p)break;A.push(_)}A.length*2{if(d==null&&(d=10),h==null&&(h=n===10?"s":","),typeof h!="function"&&(!(n%1)&&(h=Us(h)).precision==null&&(h.trim=!0),h=X0(h)),d===1/0)return h;const m=Math.max(1,n*d/t.ticks().length);return p=>{let y=p/s(Math.round(l(p)));return y*nr(nC(r(),{floor:d=>s(Math.floor(l(d))),ceil:d=>s(Math.ceil(l(d)))})),t}function aC(){const e=F0(Ad()).domain([1,10]);return e.copy=()=>au(e,aC()).base(e.base()),rn.apply(e,arguments),e}function MS(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function TS(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function Z0(e){var t=1,r=e(MS(t),TS(t));return r.constant=function(n){return arguments.length?e(MS(t=+n),TS(t)):t},si(r)}function iC(){var e=Z0(Ad());return e.copy=function(){return au(e,iC()).constant(e.constant())},rn.apply(e,arguments)}function DS(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function e9(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function t9(e){return e<0?-e*e:e*e}function Q0(e){var t=e(sr,sr),r=1;function n(){return r===1?e(sr,sr):r===.5?e(e9,t9):e(DS(r),DS(1/r))}return t.exponent=function(l){return arguments.length?(r=+l,n()):r},si(t)}function W0(){var e=Q0(Ad());return e.copy=function(){return au(e,W0()).exponent(e.exponent())},rn.apply(e,arguments),e}function r9(){return W0.apply(null,arguments).exponent(.5)}function PS(e){return Math.sign(e)*e*e}function n9(e){return Math.sign(e)*Math.sqrt(Math.abs(e))}function lC(){var e=G0(),t=[0,1],r=!1,n;function l(s){var c=n9(e(s));return isNaN(c)?n:r?Math.round(c):c}return l.invert=function(s){return e.invert(PS(s))},l.domain=function(s){return arguments.length?(e.domain(s),l):e.domain()},l.range=function(s){return arguments.length?(e.range((t=Array.from(s,Rf)).map(PS)),l):t.slice()},l.rangeRound=function(s){return l.range(s).round(!0)},l.round=function(s){return arguments.length?(r=!!s,l):r},l.clamp=function(s){return arguments.length?(e.clamp(s),l):e.clamp()},l.unknown=function(s){return arguments.length?(n=s,l):n},l.copy=function(){return lC(e.domain(),t).round(r).clamp(e.clamp()).unknown(n)},rn.apply(l,arguments),si(l)}function oC(){var e=[],t=[],r=[],n;function l(){var c=0,d=Math.max(1,t.length);for(r=new Array(d-1);++c0?r[d-1]:e[0],d=r?[n[r-1],t]:[n[m-1],n[m]]},c.unknown=function(h){return arguments.length&&(s=h),c},c.thresholds=function(){return n.slice()},c.copy=function(){return sC().domain([e,t]).range(l).unknown(s)},rn.apply(si(c),arguments)}function uC(){var e=[.5],t=[0,1],r,n=1;function l(s){return s!=null&&s<=s?t[ru(e,s,0,n)]:r}return l.domain=function(s){return arguments.length?(e=Array.from(s),n=Math.min(e.length,t.length-1),l):e.slice()},l.range=function(s){return arguments.length?(t=Array.from(s),n=Math.min(e.length,t.length-1),l):t.slice()},l.invertExtent=function(s){var c=t.indexOf(s);return[e[c-1],e[c]]},l.unknown=function(s){return arguments.length?(r=s,l):r},l.copy=function(){return uC().domain(e).range(t).unknown(r)},rn.apply(l,arguments)}const Mv=new Date,Tv=new Date;function Rt(e,t,r,n){function l(s){return e(s=arguments.length===0?new Date:new Date(+s)),s}return l.floor=s=>(e(s=new Date(+s)),s),l.ceil=s=>(e(s=new Date(s-1)),t(s,1),e(s),s),l.round=s=>{const c=l(s),d=l.ceil(s);return s-c(t(s=new Date(+s),c==null?1:Math.floor(c)),s),l.range=(s,c,d)=>{const h=[];if(s=l.ceil(s),d=d==null?1:Math.floor(d),!(s0))return h;let m;do h.push(m=new Date(+s)),t(s,d),e(s);while(mRt(c=>{if(c>=c)for(;e(c),!s(c);)c.setTime(c-1)},(c,d)=>{if(c>=c)if(d<0)for(;++d<=0;)for(;t(c,-1),!s(c););else for(;--d>=0;)for(;t(c,1),!s(c););}),r&&(l.count=(s,c)=>(Mv.setTime(+s),Tv.setTime(+c),e(Mv),e(Tv),Math.floor(r(Mv,Tv))),l.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?l.filter(n?c=>n(c)%s===0:c=>l.count(0,c)%s===0):l)),l}const $f=Rt(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);$f.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?Rt(t=>{t.setTime(Math.floor(t/e)*e)},(t,r)=>{t.setTime(+t+r*e)},(t,r)=>(r-t)/e):$f);$f.range;const aa=1e3,Jr=aa*60,ia=Jr*60,fa=ia*24,J0=fa*7,zS=fa*30,Dv=fa*365,Ri=Rt(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*aa)},(e,t)=>(t-e)/aa,e=>e.getUTCSeconds());Ri.range;const eg=Rt(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*aa)},(e,t)=>{e.setTime(+e+t*Jr)},(e,t)=>(t-e)/Jr,e=>e.getMinutes());eg.range;const tg=Rt(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*Jr)},(e,t)=>(t-e)/Jr,e=>e.getUTCMinutes());tg.range;const rg=Rt(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*aa-e.getMinutes()*Jr)},(e,t)=>{e.setTime(+e+t*ia)},(e,t)=>(t-e)/ia,e=>e.getHours());rg.range;const ng=Rt(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*ia)},(e,t)=>(t-e)/ia,e=>e.getUTCHours());ng.range;const iu=Rt(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*Jr)/fa,e=>e.getDate()-1);iu.range;const Ed=Rt(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/fa,e=>e.getUTCDate()-1);Ed.range;const cC=Rt(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/fa,e=>Math.floor(e/fa));cC.range;function tl(e){return Rt(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*Jr)/J0)}const Cd=tl(0),Bf=tl(1),a9=tl(2),i9=tl(3),lo=tl(4),l9=tl(5),o9=tl(6);Cd.range;Bf.range;a9.range;i9.range;lo.range;l9.range;o9.range;function rl(e){return Rt(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/J0)}const kd=rl(0),qf=rl(1),s9=rl(2),u9=rl(3),oo=rl(4),c9=rl(5),f9=rl(6);kd.range;qf.range;s9.range;u9.range;oo.range;c9.range;f9.range;const ag=Rt(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());ag.range;const ig=Rt(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());ig.range;const da=Rt(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());da.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Rt(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*e)});da.range;const ha=Rt(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());ha.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Rt(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*e)});ha.range;function fC(e,t,r,n,l,s){const c=[[Ri,1,aa],[Ri,5,5*aa],[Ri,15,15*aa],[Ri,30,30*aa],[s,1,Jr],[s,5,5*Jr],[s,15,15*Jr],[s,30,30*Jr],[l,1,ia],[l,3,3*ia],[l,6,6*ia],[l,12,12*ia],[n,1,fa],[n,2,2*fa],[r,1,J0],[t,1,zS],[t,3,3*zS],[e,1,Dv]];function d(m,p,y){const x=pN).right(c,x);if(w===c.length)return e.every($y(m/Dv,p/Dv,y));if(w===0)return $f.every(Math.max($y(m,p,y),1));const[j,_]=c[x/c[w-1][2]53)return null;"w"in ie||(ie.w=1),"Z"in ie?(_e=zv(ws(ie.y,0,1)),ct=_e.getUTCDay(),_e=ct>4||ct===0?qf.ceil(_e):qf(_e),_e=Ed.offset(_e,(ie.V-1)*7),ie.y=_e.getUTCFullYear(),ie.m=_e.getUTCMonth(),ie.d=_e.getUTCDate()+(ie.w+6)%7):(_e=Pv(ws(ie.y,0,1)),ct=_e.getDay(),_e=ct>4||ct===0?Bf.ceil(_e):Bf(_e),_e=iu.offset(_e,(ie.V-1)*7),ie.y=_e.getFullYear(),ie.m=_e.getMonth(),ie.d=_e.getDate()+(ie.w+6)%7)}else("W"in ie||"U"in ie)&&("w"in ie||(ie.w="u"in ie?ie.u%7:"W"in ie?1:0),ct="Z"in ie?zv(ws(ie.y,0,1)).getUTCDay():Pv(ws(ie.y,0,1)).getDay(),ie.m=0,ie.d="W"in ie?(ie.w+6)%7+ie.W*7-(ct+5)%7:ie.w+ie.U*7-(ct+6)%7);return"Z"in ie?(ie.H+=ie.Z/100|0,ie.M+=ie.Z%100,zv(ie)):Pv(ie)}}function $(J,we,Oe,ie){for(var Ie=0,_e=we.length,ct=Oe.length,ft,ht;Ie<_e;){if(ie>=ct)return-1;if(ft=we.charCodeAt(Ie++),ft===37){if(ft=we.charAt(Ie++),ht=z[ft in RS?we.charAt(Ie++):ft],!ht||(ie=ht(J,Oe,ie))<0)return-1}else if(ft!=Oe.charCodeAt(ie++))return-1}return ie}function Z(J,we,Oe){var ie=m.exec(we.slice(Oe));return ie?(J.p=p.get(ie[0].toLowerCase()),Oe+ie[0].length):-1}function X(J,we,Oe){var ie=w.exec(we.slice(Oe));return ie?(J.w=j.get(ie[0].toLowerCase()),Oe+ie[0].length):-1}function L(J,we,Oe){var ie=y.exec(we.slice(Oe));return ie?(J.w=x.get(ie[0].toLowerCase()),Oe+ie[0].length):-1}function K(J,we,Oe){var ie=A.exec(we.slice(Oe));return ie?(J.m=O.get(ie[0].toLowerCase()),Oe+ie[0].length):-1}function se(J,we,Oe){var ie=_.exec(we.slice(Oe));return ie?(J.m=N.get(ie[0].toLowerCase()),Oe+ie[0].length):-1}function ce(J,we,Oe){return $(J,t,we,Oe)}function he(J,we,Oe){return $(J,r,we,Oe)}function q(J,we,Oe){return $(J,n,we,Oe)}function W(J){return c[J.getDay()]}function ue(J){return s[J.getDay()]}function te(J){return h[J.getMonth()]}function M(J){return d[J.getMonth()]}function C(J){return l[+(J.getHours()>=12)]}function U(J){return 1+~~(J.getMonth()/3)}function ee(J){return c[J.getUTCDay()]}function le(J){return s[J.getUTCDay()]}function me(J){return h[J.getUTCMonth()]}function pe(J){return d[J.getUTCMonth()]}function be(J){return l[+(J.getUTCHours()>=12)]}function Me(J){return 1+~~(J.getUTCMonth()/3)}return{format:function(J){var we=T(J+="",P);return we.toString=function(){return J},we},parse:function(J){var we=R(J+="",!1);return we.toString=function(){return J},we},utcFormat:function(J){var we=T(J+="",k);return we.toString=function(){return J},we},utcParse:function(J){var we=R(J+="",!0);return we.toString=function(){return J},we}}}var RS={"-":"",_:" ",0:"0"},Kt=/^\s*\d+/,y9=/^%/,g9=/[\\^$*+?|[\]().{}]/g;function He(e,t,r){var n=e<0?"-":"",l=(n?-e:e)+"",s=l.length;return n+(s[t.toLowerCase(),r]))}function b9(e,t,r){var n=Kt.exec(t.slice(r,r+1));return n?(e.w=+n[0],r+n[0].length):-1}function w9(e,t,r){var n=Kt.exec(t.slice(r,r+1));return n?(e.u=+n[0],r+n[0].length):-1}function j9(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.U=+n[0],r+n[0].length):-1}function _9(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.V=+n[0],r+n[0].length):-1}function S9(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.W=+n[0],r+n[0].length):-1}function LS(e,t,r){var n=Kt.exec(t.slice(r,r+4));return n?(e.y=+n[0],r+n[0].length):-1}function IS(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function N9(e,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function O9(e,t,r){var n=Kt.exec(t.slice(r,r+1));return n?(e.q=n[0]*3-3,r+n[0].length):-1}function A9(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function $S(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function E9(e,t,r){var n=Kt.exec(t.slice(r,r+3));return n?(e.m=0,e.d=+n[0],r+n[0].length):-1}function BS(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function C9(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function k9(e,t,r){var n=Kt.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function M9(e,t,r){var n=Kt.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function T9(e,t,r){var n=Kt.exec(t.slice(r,r+6));return n?(e.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function D9(e,t,r){var n=y9.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function P9(e,t,r){var n=Kt.exec(t.slice(r));return n?(e.Q=+n[0],r+n[0].length):-1}function z9(e,t,r){var n=Kt.exec(t.slice(r));return n?(e.s=+n[0],r+n[0].length):-1}function qS(e,t){return He(e.getDate(),t,2)}function R9(e,t){return He(e.getHours(),t,2)}function L9(e,t){return He(e.getHours()%12||12,t,2)}function I9(e,t){return He(1+iu.count(da(e),e),t,3)}function dC(e,t){return He(e.getMilliseconds(),t,3)}function $9(e,t){return dC(e,t)+"000"}function B9(e,t){return He(e.getMonth()+1,t,2)}function q9(e,t){return He(e.getMinutes(),t,2)}function U9(e,t){return He(e.getSeconds(),t,2)}function H9(e){var t=e.getDay();return t===0?7:t}function K9(e,t){return He(Cd.count(da(e)-1,e),t,2)}function hC(e){var t=e.getDay();return t>=4||t===0?lo(e):lo.ceil(e)}function Y9(e,t){return e=hC(e),He(lo.count(da(e),e)+(da(e).getDay()===4),t,2)}function G9(e){return e.getDay()}function V9(e,t){return He(Bf.count(da(e)-1,e),t,2)}function X9(e,t){return He(e.getFullYear()%100,t,2)}function F9(e,t){return e=hC(e),He(e.getFullYear()%100,t,2)}function Z9(e,t){return He(e.getFullYear()%1e4,t,4)}function Q9(e,t){var r=e.getDay();return e=r>=4||r===0?lo(e):lo.ceil(e),He(e.getFullYear()%1e4,t,4)}function W9(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+He(t/60|0,"0",2)+He(t%60,"0",2)}function US(e,t){return He(e.getUTCDate(),t,2)}function J9(e,t){return He(e.getUTCHours(),t,2)}function eI(e,t){return He(e.getUTCHours()%12||12,t,2)}function tI(e,t){return He(1+Ed.count(ha(e),e),t,3)}function mC(e,t){return He(e.getUTCMilliseconds(),t,3)}function rI(e,t){return mC(e,t)+"000"}function nI(e,t){return He(e.getUTCMonth()+1,t,2)}function aI(e,t){return He(e.getUTCMinutes(),t,2)}function iI(e,t){return He(e.getUTCSeconds(),t,2)}function lI(e){var t=e.getUTCDay();return t===0?7:t}function oI(e,t){return He(kd.count(ha(e)-1,e),t,2)}function pC(e){var t=e.getUTCDay();return t>=4||t===0?oo(e):oo.ceil(e)}function sI(e,t){return e=pC(e),He(oo.count(ha(e),e)+(ha(e).getUTCDay()===4),t,2)}function uI(e){return e.getUTCDay()}function cI(e,t){return He(qf.count(ha(e)-1,e),t,2)}function fI(e,t){return He(e.getUTCFullYear()%100,t,2)}function dI(e,t){return e=pC(e),He(e.getUTCFullYear()%100,t,2)}function hI(e,t){return He(e.getUTCFullYear()%1e4,t,4)}function mI(e,t){var r=e.getUTCDay();return e=r>=4||r===0?oo(e):oo.ceil(e),He(e.getUTCFullYear()%1e4,t,4)}function pI(){return"+0000"}function HS(){return"%"}function KS(e){return+e}function YS(e){return Math.floor(+e/1e3)}var Ul,vC,yC;vI({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function vI(e){return Ul=v9(e),vC=Ul.format,Ul.parse,yC=Ul.utcFormat,Ul.utcParse,Ul}function yI(e){return new Date(e)}function gI(e){return e instanceof Date?+e:+new Date(+e)}function lg(e,t,r,n,l,s,c,d,h,m){var p=G0(),y=p.invert,x=p.domain,w=m(".%L"),j=m(":%S"),_=m("%I:%M"),N=m("%I %p"),A=m("%a %d"),O=m("%b %d"),P=m("%B"),k=m("%Y");function z(T){return(h(T)t(l/(e.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(l,s)=>lL(e,s/n))},r.copy=function(){return wC(t).domain(e)},xa.apply(r,arguments)}function Td(){var e=0,t=.5,r=1,n=1,l,s,c,d,h,m=sr,p,y=!1,x;function w(_){return isNaN(_=+_)?x:(_=.5+((_=+p(_))-s)*(n*_e.chartData,Dd=Y([ba],e=>{var t=e.chartData!=null?e.chartData.length-1:0;return{chartData:e.chartData,computedData:e.computedData,dataEndIndex:t,dataStartIndex:0}}),NC=(e,t,r,n)=>n?Dd(e):ba(e),OC=(e,t,r)=>r?Dd(e):ba(e);function ma(e){if(Array.isArray(e)&&e.length===2){var[t,r]=e;if(ke(t)&&ke(r))return!0}return!1}function GS(e,t,r){return r?e:[Math.min(e[0],t[0]),Math.max(e[1],t[1])]}function AC(e,t){if(t&&typeof e!="function"&&Array.isArray(e)&&e.length===2){var[r,n]=e,l,s;if(ke(r))l=r;else if(typeof r=="function")return;if(ke(n))s=n;else if(typeof n=="function")return;var c=[l,s];if(ma(c))return c}}function _I(e,t,r){if(!(!r&&t==null)){if(typeof e=="function"&&t!=null)try{var n=e(t,r);if(ma(n))return GS(n,t,r)}catch{}if(Array.isArray(e)&&e.length===2){var[l,s]=e,c,d;if(l==="auto")t!=null&&(c=Math.min(...t));else if(de(l))c=l;else if(typeof l=="function")try{t!=null&&(c=l(t==null?void 0:t[0]))}catch{}else if(typeof l=="string"&&r2.test(l)){var h=r2.exec(l);if(h==null||h[1]==null||t==null)c=void 0;else{var m=+h[1];c=t[0]-m}}else c=t==null?void 0:t[0];if(s==="auto")t!=null&&(d=Math.max(...t));else if(de(s))d=s;else if(typeof s=="function")try{t!=null&&(d=s(t==null?void 0:t[1]))}catch{}else if(typeof s=="string"&&n2.test(s)){var p=n2.exec(s);if(p==null||p[1]==null||t==null)d=void 0;else{var y=+p[1];d=t[1]+y}}else d=t==null?void 0:t[1];var x=[c,d];if(ma(x))return t==null?x:GS(x,t,r)}}}var ho=1e9,SI={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},cg,ut=!0,tn="[DecimalError] ",Bi=tn+"Invalid argument: ",ug=tn+"Exponent out of range: ",mo=Math.floor,Di=Math.pow,NI=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Pr,Ut=1e7,it=7,EC=9007199254740991,Uf=mo(EC/it),ve={};ve.absoluteValue=ve.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};ve.comparedTo=ve.cmp=function(e){var t,r,n,l,s=this;if(e=new s.constructor(e),s.s!==e.s)return s.s||-e.s;if(s.e!==e.e)return s.e>e.e^s.s<0?1:-1;for(n=s.d.length,l=e.d.length,t=0,r=ne.d[t]^s.s<0?1:-1;return n===l?0:n>l^s.s<0?1:-1};ve.decimalPlaces=ve.dp=function(){var e=this,t=e.d.length-1,r=(t-e.e)*it;if(t=e.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};ve.dividedBy=ve.div=function(e){return sa(this,new this.constructor(e))};ve.dividedToIntegerBy=ve.idiv=function(e){var t=this,r=t.constructor;return et(sa(t,new r(e),0,1),r.precision)};ve.equals=ve.eq=function(e){return!this.cmp(e)};ve.exponent=function(){return kt(this)};ve.greaterThan=ve.gt=function(e){return this.cmp(e)>0};ve.greaterThanOrEqualTo=ve.gte=function(e){return this.cmp(e)>=0};ve.isInteger=ve.isint=function(){return this.e>this.d.length-2};ve.isNegative=ve.isneg=function(){return this.s<0};ve.isPositive=ve.ispos=function(){return this.s>0};ve.isZero=function(){return this.s===0};ve.lessThan=ve.lt=function(e){return this.cmp(e)<0};ve.lessThanOrEqualTo=ve.lte=function(e){return this.cmp(e)<1};ve.logarithm=ve.log=function(e){var t,r=this,n=r.constructor,l=n.precision,s=l+5;if(e===void 0)e=new n(10);else if(e=new n(e),e.s<1||e.eq(Pr))throw Error(tn+"NaN");if(r.s<1)throw Error(tn+(r.s?"NaN":"-Infinity"));return r.eq(Pr)?new n(0):(ut=!1,t=sa(Hs(r,s),Hs(e,s),s),ut=!0,et(t,l))};ve.minus=ve.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?MC(t,e):CC(t,(e.s=-e.s,e))};ve.modulo=ve.mod=function(e){var t,r=this,n=r.constructor,l=n.precision;if(e=new n(e),!e.s)throw Error(tn+"NaN");return r.s?(ut=!1,t=sa(r,e,0,1).times(e),ut=!0,r.minus(t)):et(new n(r),l)};ve.naturalExponential=ve.exp=function(){return kC(this)};ve.naturalLogarithm=ve.ln=function(){return Hs(this)};ve.negated=ve.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};ve.plus=ve.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?CC(t,e):MC(t,(e.s=-e.s,e))};ve.precision=ve.sd=function(e){var t,r,n,l=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Bi+e);if(t=kt(l)+1,n=l.d.length-1,r=n*it+1,n=l.d[n],n){for(;n%10==0;n/=10)r--;for(n=l.d[0];n>=10;n/=10)r++}return e&&t>r?t:r};ve.squareRoot=ve.sqrt=function(){var e,t,r,n,l,s,c,d=this,h=d.constructor;if(d.s<1){if(!d.s)return new h(0);throw Error(tn+"NaN")}for(e=kt(d),ut=!1,l=Math.sqrt(+d),l==0||l==1/0?(t=Nn(d.d),(t.length+e)%2==0&&(t+="0"),l=Math.sqrt(t),e=mo((e+1)/2)-(e<0||e%2),l==1/0?t="5e"+e:(t=l.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new h(t)):n=new h(l.toString()),r=h.precision,l=c=r+3;;)if(s=n,n=s.plus(sa(d,s,c+2)).times(.5),Nn(s.d).slice(0,c)===(t=Nn(n.d)).slice(0,c)){if(t=t.slice(c-3,c+1),l==c&&t=="4999"){if(et(s,r+1,0),s.times(s).eq(d)){n=s;break}}else if(t!="9999")break;c+=4}return ut=!0,et(n,r)};ve.times=ve.mul=function(e){var t,r,n,l,s,c,d,h,m,p=this,y=p.constructor,x=p.d,w=(e=new y(e)).d;if(!p.s||!e.s)return new y(0);for(e.s*=p.s,r=p.e+e.e,h=x.length,m=w.length,h=0;){for(t=0,l=h+n;l>n;)d=s[l]+w[n]*x[l-n-1]+t,s[l--]=d%Ut|0,t=d/Ut|0;s[l]=(s[l]+t)%Ut|0}for(;!s[--c];)s.pop();return t?++r:s.shift(),e.d=s,e.e=r,ut?et(e,y.precision):e};ve.toDecimalPlaces=ve.todp=function(e,t){var r=this,n=r.constructor;return r=new n(r),e===void 0?r:(Cn(e,0,ho),t===void 0?t=n.rounding:Cn(t,0,8),et(r,e+kt(r)+1,t))};ve.toExponential=function(e,t){var r,n=this,l=n.constructor;return e===void 0?r=Qi(n,!0):(Cn(e,0,ho),t===void 0?t=l.rounding:Cn(t,0,8),n=et(new l(n),e+1,t),r=Qi(n,!0,e+1)),r};ve.toFixed=function(e,t){var r,n,l=this,s=l.constructor;return e===void 0?Qi(l):(Cn(e,0,ho),t===void 0?t=s.rounding:Cn(t,0,8),n=et(new s(l),e+kt(l)+1,t),r=Qi(n.abs(),!1,e+kt(n)+1),l.isneg()&&!l.isZero()?"-"+r:r)};ve.toInteger=ve.toint=function(){var e=this,t=e.constructor;return et(new t(e),kt(e)+1,t.rounding)};ve.toNumber=function(){return+this};ve.toPower=ve.pow=function(e){var t,r,n,l,s,c,d=this,h=d.constructor,m=12,p=+(e=new h(e));if(!e.s)return new h(Pr);if(d=new h(d),!d.s){if(e.s<1)throw Error(tn+"Infinity");return d}if(d.eq(Pr))return d;if(n=h.precision,e.eq(Pr))return et(d,n);if(t=e.e,r=e.d.length-1,c=t>=r,s=d.s,c){if((r=p<0?-p:p)<=EC){for(l=new h(Pr),t=Math.ceil(n/it+4),ut=!1;r%2&&(l=l.times(d),XS(l.d,t)),r=mo(r/2),r!==0;)d=d.times(d),XS(d.d,t);return ut=!0,e.s<0?new h(Pr).div(l):et(l,n)}}else if(s<0)throw Error(tn+"NaN");return s=s<0&&e.d[Math.max(t,r)]&1?-1:1,d.s=1,ut=!1,l=e.times(Hs(d,n+m)),ut=!0,l=kC(l),l.s=s,l};ve.toPrecision=function(e,t){var r,n,l=this,s=l.constructor;return e===void 0?(r=kt(l),n=Qi(l,r<=s.toExpNeg||r>=s.toExpPos)):(Cn(e,1,ho),t===void 0?t=s.rounding:Cn(t,0,8),l=et(new s(l),e,t),r=kt(l),n=Qi(l,e<=r||r<=s.toExpNeg,e)),n};ve.toSignificantDigits=ve.tosd=function(e,t){var r=this,n=r.constructor;return e===void 0?(e=n.precision,t=n.rounding):(Cn(e,1,ho),t===void 0?t=n.rounding:Cn(t,0,8)),et(new n(r),e,t)};ve.toString=ve.valueOf=ve.val=ve.toJSON=ve[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=kt(e),r=e.constructor;return Qi(e,t<=r.toExpNeg||t>=r.toExpPos)};function CC(e,t){var r,n,l,s,c,d,h,m,p=e.constructor,y=p.precision;if(!e.s||!t.s)return t.s||(t=new p(e)),ut?et(t,y):t;if(h=e.d,m=t.d,c=e.e,l=t.e,h=h.slice(),s=c-l,s){for(s<0?(n=h,s=-s,d=m.length):(n=m,l=c,d=h.length),c=Math.ceil(y/it),d=c>d?c+1:d+1,s>d&&(s=d,n.length=1),n.reverse();s--;)n.push(0);n.reverse()}for(d=h.length,s=m.length,d-s<0&&(s=d,n=m,m=h,h=n),r=0;s;)r=(h[--s]=h[s]+m[s]+r)/Ut|0,h[s]%=Ut;for(r&&(h.unshift(r),++l),d=h.length;h[--d]==0;)h.pop();return t.d=h,t.e=l,ut?et(t,y):t}function Cn(e,t,r){if(e!==~~e||er)throw Error(Bi+e)}function Nn(e){var t,r,n,l=e.length-1,s="",c=e[0];if(l>0){for(s+=c,t=1;tc?1:-1;else for(d=h=0;dl[d]?1:-1;break}return h}function r(n,l,s){for(var c=0;s--;)n[s]-=c,c=n[s]1;)n.shift()}return function(n,l,s,c){var d,h,m,p,y,x,w,j,_,N,A,O,P,k,z,T,R,$,Z=n.constructor,X=n.s==l.s?1:-1,L=n.d,K=l.d;if(!n.s)return new Z(n);if(!l.s)throw Error(tn+"Division by zero");for(h=n.e-l.e,R=K.length,z=L.length,w=new Z(X),j=w.d=[],m=0;K[m]==(L[m]||0);)++m;if(K[m]>(L[m]||0)&&--h,s==null?O=s=Z.precision:c?O=s+(kt(n)-kt(l))+1:O=s,O<0)return new Z(0);if(O=O/it+2|0,m=0,R==1)for(p=0,K=K[0],O++;(m1&&(K=e(K,p),L=e(L,p),R=K.length,z=L.length),k=R,_=L.slice(0,R),N=_.length;N=Ut/2&&++T;do p=0,d=t(K,_,R,N),d<0?(A=_[0],R!=N&&(A=A*Ut+(_[1]||0)),p=A/T|0,p>1?(p>=Ut&&(p=Ut-1),y=e(K,p),x=y.length,N=_.length,d=t(y,_,x,N),d==1&&(p--,r(y,R16)throw Error(ug+kt(e));if(!e.s)return new p(Pr);for(ut=!1,d=y,c=new p(.03125);e.abs().gte(.1);)e=e.times(c),m+=5;for(n=Math.log(Di(2,m))/Math.LN10*2+5|0,d+=n,r=l=s=new p(Pr),p.precision=d;;){if(l=et(l.times(e),d),r=r.times(++h),c=s.plus(sa(l,r,d)),Nn(c.d).slice(0,d)===Nn(s.d).slice(0,d)){for(;m--;)s=et(s.times(s),d);return p.precision=y,t==null?(ut=!0,et(s,y)):s}s=c}}function kt(e){for(var t=e.e*it,r=e.d[0];r>=10;r/=10)t++;return t}function Rv(e,t,r){if(t>e.LN10.sd())throw ut=!0,r&&(e.precision=r),Error(tn+"LN10 precision limit exceeded");return et(new e(e.LN10),t)}function Za(e){for(var t="";e--;)t+="0";return t}function Hs(e,t){var r,n,l,s,c,d,h,m,p,y=1,x=10,w=e,j=w.d,_=w.constructor,N=_.precision;if(w.s<1)throw Error(tn+(w.s?"NaN":"-Infinity"));if(w.eq(Pr))return new _(0);if(t==null?(ut=!1,m=N):m=t,w.eq(10))return t==null&&(ut=!0),Rv(_,m);if(m+=x,_.precision=m,r=Nn(j),n=r.charAt(0),s=kt(w),Math.abs(s)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)w=w.times(e),r=Nn(w.d),n=r.charAt(0),y++;s=kt(w),n>1?(w=new _("0."+r),s++):w=new _(n+"."+r.slice(1))}else return h=Rv(_,m+2,N).times(s+""),w=Hs(new _(n+"."+r.slice(1)),m-x).plus(h),_.precision=N,t==null?(ut=!0,et(w,N)):w;for(d=c=w=sa(w.minus(Pr),w.plus(Pr),m),p=et(w.times(w),m),l=3;;){if(c=et(c.times(p),m),h=d.plus(sa(c,new _(l),m)),Nn(h.d).slice(0,m)===Nn(d.d).slice(0,m))return d=d.times(2),s!==0&&(d=d.plus(Rv(_,m+2,N).times(s+""))),d=sa(d,new _(y),m),_.precision=N,t==null?(ut=!0,et(d,N)):d;d=h,l+=2}}function VS(e,t){var r,n,l;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(l=t.length;t.charCodeAt(l-1)===48;)--l;if(t=t.slice(n,l),t){if(l-=n,r=r-n-1,e.e=mo(r/it),e.d=[],n=(r+1)%it,r<0&&(n+=it),nUf||e.e<-Uf))throw Error(ug+r)}else e.s=0,e.e=0,e.d=[0];return e}function et(e,t,r){var n,l,s,c,d,h,m,p,y=e.d;for(c=1,s=y[0];s>=10;s/=10)c++;if(n=t-c,n<0)n+=it,l=t,m=y[p=0];else{if(p=Math.ceil((n+1)/it),s=y.length,p>=s)return e;for(m=s=y[p],c=1;s>=10;s/=10)c++;n%=it,l=n-it+c}if(r!==void 0&&(s=Di(10,c-l-1),d=m/s%10|0,h=t<0||y[p+1]!==void 0||m%s,h=r<4?(d||h)&&(r==0||r==(e.s<0?3:2)):d>5||d==5&&(r==4||h||r==6&&(n>0?l>0?m/Di(10,c-l):0:y[p-1])%10&1||r==(e.s<0?8:7))),t<1||!y[0])return h?(s=kt(e),y.length=1,t=t-s-1,y[0]=Di(10,(it-t%it)%it),e.e=mo(-t/it)||0):(y.length=1,y[0]=e.e=e.s=0),e;if(n==0?(y.length=p,s=1,p--):(y.length=p+1,s=Di(10,it-n),y[p]=l>0?(m/Di(10,c-l)%Di(10,l)|0)*s:0),h)for(;;)if(p==0){(y[0]+=s)==Ut&&(y[0]=1,++e.e);break}else{if(y[p]+=s,y[p]!=Ut)break;y[p--]=0,s=1}for(n=y.length;y[--n]===0;)y.pop();if(ut&&(e.e>Uf||e.e<-Uf))throw Error(ug+kt(e));return e}function MC(e,t){var r,n,l,s,c,d,h,m,p,y,x=e.constructor,w=x.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new x(e),ut?et(t,w):t;if(h=e.d,y=t.d,n=t.e,m=e.e,h=h.slice(),c=m-n,c){for(p=c<0,p?(r=h,c=-c,d=y.length):(r=y,n=m,d=h.length),l=Math.max(Math.ceil(w/it),d)+2,c>l&&(c=l,r.length=1),r.reverse(),l=c;l--;)r.push(0);r.reverse()}else{for(l=h.length,d=y.length,p=l0;--l)h[d++]=0;for(l=y.length;l>c;){if(h[--l]0?s=s.charAt(0)+"."+s.slice(1)+Za(n):c>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(l<0?"e":"e+")+l):l<0?(s="0."+Za(-l-1)+s,r&&(n=r-c)>0&&(s+=Za(n))):l>=c?(s+=Za(l+1-c),r&&(n=r-l-1)>0&&(s=s+"."+Za(n))):((n=l+1)0&&(l+1===c&&(s+="."),s+=Za(n))),e.s<0?"-"+s:s}function XS(e,t){if(e.length>t)return e.length=t,!0}function TC(e){var t,r,n;function l(s){var c=this;if(!(c instanceof l))return new l(s);if(c.constructor=l,s instanceof l){c.s=s.s,c.e=s.e,c.d=(s=s.d)?s.slice():s;return}if(typeof s=="number"){if(s*0!==0)throw Error(Bi+s);if(s>0)c.s=1;else if(s<0)s=-s,c.s=-1;else{c.s=0,c.e=0,c.d=[0];return}if(s===~~s&&s<1e7){c.e=0,c.d=[s];return}return VS(c,s.toString())}else if(typeof s!="string")throw Error(Bi+s);if(s.charCodeAt(0)===45?(s=s.slice(1),c.s=-1):c.s=1,NI.test(s))VS(c,s);else throw Error(Bi+s)}if(l.prototype=ve,l.ROUND_UP=0,l.ROUND_DOWN=1,l.ROUND_CEIL=2,l.ROUND_FLOOR=3,l.ROUND_HALF_UP=4,l.ROUND_HALF_DOWN=5,l.ROUND_HALF_EVEN=6,l.ROUND_HALF_CEIL=7,l.ROUND_HALF_FLOOR=8,l.clone=TC,l.config=l.set=OI,e===void 0&&(e={}),e)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=l[t+1]&&n<=l[t+2])this[r]=n;else throw Error(Bi+r+": "+n);if((n=e[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(Bi+r+": "+n);return this}var cg=TC(SI);Pr=new cg(1);const Ve=cg;function DC(e){var t;return e===0?t=1:t=Math.floor(new Ve(e).abs().log(10).toNumber())+1,t}function PC(e,t,r){for(var n=new Ve(e),l=0,s=[];n.lt(t)&&l<1e5;)s.push(n.toNumber()),n=n.add(r),l++;return s}var zC=e=>{var[t,r]=e,[n,l]=[t,r];return t>r&&([n,l]=[r,t]),[n,l]},RC=(e,t,r)=>{if(e.lte(0))return new Ve(0);var n=DC(e.toNumber()),l=new Ve(10).pow(n),s=e.div(l),c=n!==1?.05:.1,d=new Ve(Math.ceil(s.div(c).toNumber())).add(r).mul(c),h=d.mul(l);return t?new Ve(h.toNumber()):new Ve(Math.ceil(h.toNumber()))},AI=(e,t,r)=>{var n=new Ve(1),l=new Ve(e);if(!l.isint()&&r){var s=Math.abs(e);s<1?(n=new Ve(10).pow(DC(e)-1),l=new Ve(Math.floor(l.div(n).toNumber())).mul(n)):s>1&&(l=new Ve(Math.floor(e)))}else e===0?l=new Ve(Math.floor((t-1)/2)):r||(l=new Ve(Math.floor(e)));for(var c=Math.floor((t-1)/2),d=[],h=0;h4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((r-t)/(n-1)))return{step:new Ve(0),tickMin:new Ve(0),tickMax:new Ve(0)};var c=RC(new Ve(r).sub(t).div(n-1),l,s),d;t<=0&&r>=0?d=new Ve(0):(d=new Ve(t).add(r).div(2),d=d.sub(new Ve(d).mod(c)));var h=Math.ceil(d.sub(t).div(c).toNumber()),m=Math.ceil(new Ve(r).sub(d).div(c).toNumber()),p=h+m+1;return p>n?LC(t,r,n,l,s+1):(p0?m+(n-p):m,h=r>0?h:h+(n-p)),{step:c,tickMin:d.sub(new Ve(h).mul(c)),tickMax:d.add(new Ve(m).mul(c))})},EI=function(t){var[r,n]=t,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=Math.max(l,2),[d,h]=zC([r,n]);if(d===-1/0||h===1/0){var m=h===1/0?[d,...Array(l-1).fill(1/0)]:[...Array(l-1).fill(-1/0),h];return r>n?m.reverse():m}if(d===h)return AI(d,l,s);var{step:p,tickMin:y,tickMax:x}=LC(d,h,c,s,0),w=PC(y,x.add(new Ve(.1).mul(p)),p);return r>n?w.reverse():w},CI=function(t,r){var[n,l]=t,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[c,d]=zC([n,l]);if(c===-1/0||d===1/0)return[n,l];if(c===d)return[c];var h=Math.max(r,2),m=RC(new Ve(d).sub(c).div(h-1),s,0),p=[...PC(new Ve(c),new Ve(d),m),d];return s===!1&&(p=p.map(y=>Math.round(y))),n>l?p.reverse():p},IC=e=>e.rootProps.maxBarSize,kI=e=>e.rootProps.barGap,$C=e=>e.rootProps.barCategoryGap,MI=e=>e.rootProps.barSize,lu=e=>e.rootProps.stackOffset,BC=e=>e.rootProps.reverseStackOrder,fg=e=>e.options.chartName,dg=e=>e.rootProps.syncId,qC=e=>e.rootProps.syncMethod,hg=e=>e.options.eventEmitter,TI=e=>e.rootProps.baseValue,Ct={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},ki={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},jn={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},Pd=(e,t)=>{if(!(!e||!t))return e!=null&&e.reversed?[t[1],t[0]]:t};function zd(e,t,r){if(r!=="auto")return r;if(e!=null)return Mn(e,t)?"category":"number"}function FS(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Hf(e){for(var t=1;t{if(t!=null)return e.polarAxis.angleAxis[t]},mg=Y([RI,_E],(e,t)=>{var r;if(e!=null)return e;var n=(r=zd(t,"angleAxis",ZS.type))!==null&&r!==void 0?r:"category";return Hf(Hf({},ZS),{},{type:n})}),LI=(e,t)=>e.polarAxis.radiusAxis[t],pg=Y([LI,_E],(e,t)=>{var r;if(e!=null)return e;var n=(r=zd(t,"radiusAxis",QS.type))!==null&&r!==void 0?r:"category";return Hf(Hf({},QS),{},{type:n})}),Rd=e=>e.polarOptions,vg=Y([ya,ga,zt],qE),UC=Y([Rd,vg],(e,t)=>{if(e!=null)return nr(e.innerRadius,t,0)}),HC=Y([Rd,vg],(e,t)=>{if(e!=null)return nr(e.outerRadius,t,t*.8)}),II=e=>{if(e==null)return[0,0];var{startAngle:t,endAngle:r}=e;return[t,r]},KC=Y([Rd],II);Y([mg,KC],Pd);var YC=Y([vg,UC,HC],(e,t,r)=>{if(!(e==null||t==null||r==null))return[t,r]});Y([pg,YC],Pd);var GC=Y([$e,Rd,UC,HC,ya,ga],(e,t,r,n,l,s)=>{if(!(e!=="centric"&&e!=="radial"||t==null||r==null||n==null)){var{cx:c,cy:d,startAngle:h,endAngle:m}=t;return{cx:nr(c,l,l/2),cy:nr(d,s,s/2),innerRadius:r,outerRadius:n,startAngle:h,endAngle:m,clockWise:!1}}}),dt=(e,t)=>t,ou=(e,t,r)=>r;function Ld(e){return e==null?void 0:e.id}function VC(e,t,r){var{chartData:n=[]}=t,{allowDuplicatedCategory:l,dataKey:s}=r,c=new Map;return e.forEach(d=>{var h,m=(h=d.data)!==null&&h!==void 0?h:n;if(!(m==null||m.length===0)){var p=Ld(d);m.forEach((y,x)=>{var w=s==null||l?x:String(We(y,s,null)),j=We(y,d.dataKey,0),_;c.has(w)?_=c.get(w):_={},Object.assign(_,{[p]:j}),c.set(w,_)})}}),Array.from(c.values())}function Id(e){return"stackId"in e&&e.stackId!=null&&e.dataKey!=null}var $d=(e,t)=>e===t?!0:e==null||t==null?!1:e[0]===t[0]&&e[1]===t[1];function Bd(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===0&&t.length===0?!0:e===t}function $I(e,t){if(e.length===t.length){for(var r=0;r{var t=$e(e);return t==="horizontal"?"xAxis":t==="vertical"?"yAxis":t==="centric"?"angleAxis":"radiusAxis"},po=e=>e.tooltip.settings.axisId;function BI(e){if(e in As)return As[e]();var t="scale".concat(Gs(e));if(t in As)return As[t]()}function WS(e){var t=e.ticks,r=e.bandwidth,n=e.range(),l=[Math.min(...n),Math.max(...n)];return{domain:()=>e.domain(),range:(function(s){function c(){return s.apply(this,arguments)}return c.toString=function(){return s.toString()},c})(()=>l),rangeMin:()=>l[0],rangeMax:()=>l[1],isInRange(s){var c=l[0],d=l[1];return c<=d?s>=c&&s<=d:s>=d&&s<=c},bandwidth:r?()=>r.call(e):void 0,ticks:t?s=>t.call(e,s):void 0,map:(s,c)=>{var d=e(s);if(d!=null){if(e.bandwidth&&c!==null&&c!==void 0&&c.position){var h=e.bandwidth();switch(c.position){case"middle":d+=h/2;break;case"end":d+=h;break}}return d}}}}function JS(e,t,r){if(typeof e=="function")return WS(e.copy().domain(t).range(r));if(e!=null){var n=BI(e);if(n!=null)return n.domain(t).range(r),WS(n)}}var XC=(e,t)=>{if(t!=null)switch(e){case"linear":{if(!ma(t)){for(var r,n,l=0;ln)&&(n=s))}return r!==void 0&&n!==void 0?[r,n]:void 0}return t}default:return t}};function eN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Kf(e){for(var t=1;te.cartesianAxis.xAxis[t],wa=(e,t)=>{var r=FC(e,t);return r??Bt},qt={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:Ky,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"left",padding:{top:0,bottom:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"number",unit:void 0,width:Zs},ZC=(e,t)=>e.cartesianAxis.yAxis[t],ja=(e,t)=>{var r=ZC(e,t);return r??qt},KI={domain:[0,"auto"],includeHidden:!1,reversed:!1,allowDataOverflow:!1,allowDuplicatedCategory:!1,dataKey:void 0,id:0,name:"",range:[64,64],scale:"auto",type:"number",unit:""},yg=(e,t)=>{var r=e.cartesianAxis.zAxis[t];return r??KI},bt=(e,t,r)=>{switch(t){case"xAxis":return wa(e,r);case"yAxis":return ja(e,r);case"zAxis":return yg(e,r);case"angleAxis":return mg(e,r);case"radiusAxis":return pg(e,r);default:throw new Error("Unexpected axis type: ".concat(t))}},YI=(e,t,r)=>{switch(t){case"xAxis":return wa(e,r);case"yAxis":return ja(e,r);default:throw new Error("Unexpected axis type: ".concat(t))}},vo=(e,t,r)=>{switch(t){case"xAxis":return wa(e,r);case"yAxis":return ja(e,r);case"angleAxis":return mg(e,r);case"radiusAxis":return pg(e,r);default:throw new Error("Unexpected axis type: ".concat(t))}},QC=e=>e.graphicalItems.cartesianItems.some(t=>t.type==="bar")||e.graphicalItems.polarItems.some(t=>t.type==="radialBar");function gg(e,t){return r=>{switch(e){case"xAxis":return"xAxisId"in r&&r.xAxisId===t;case"yAxis":return"yAxisId"in r&&r.yAxisId===t;case"zAxis":return"zAxisId"in r&&r.zAxisId===t;case"angleAxis":return"angleAxisId"in r&&r.angleAxisId===t;case"radiusAxis":return"radiusAxisId"in r&&r.radiusAxisId===t;default:return!1}}}var qd=e=>e.graphicalItems.cartesianItems,GI=Y([dt,ou],gg),xg=(e,t,r)=>e.filter(r).filter(n=>(t==null?void 0:t.includeHidden)===!0?!0:!n.hide),su=Y([qd,bt,GI],xg,{memoizeOptions:{resultEqualityCheck:Bd}}),WC=Y([su],e=>e.filter(t=>t.type==="area"||t.type==="bar").filter(Id)),JC=e=>e.filter(t=>!("stackId"in t)||t.stackId===void 0),VI=Y([su],JC),bg=e=>e.map(t=>t.data).filter(Boolean).flat(1),XI=Y([su],bg,{memoizeOptions:{resultEqualityCheck:Bd}}),wg=(e,t)=>{var{chartData:r=[],dataStartIndex:n,dataEndIndex:l}=t;return e.length>0?e:r.slice(n,l+1)},jg=Y([XI,NC],wg),_g=(e,t,r)=>(t==null?void 0:t.dataKey)!=null?e.map(n=>({value:We(n,t.dataKey)})):r.length>0?r.map(n=>n.dataKey).flatMap(n=>e.map(l=>({value:We(l,n)}))):e.map(n=>({value:n})),Ud=Y([jg,bt,su],_g);function e3(e,t){switch(e){case"xAxis":return t.direction==="x";case"yAxis":return t.direction==="y";default:return!1}}function tf(e){if(An(e)||e instanceof Date){var t=Number(e);if(ke(t))return t}}function tN(e){if(Array.isArray(e)){var t=[tf(e[0]),tf(e[1])];return ma(t)?t:void 0}var r=tf(e);if(r!=null)return[r,r]}function pa(e){return e.map(tf).filter(xr)}function FI(e,t,r){return!r||typeof t!="number"||dn(t)?[]:r.length?pa(r.flatMap(n=>{var l=We(e,n.dataKey),s,c;if(Array.isArray(l)?[s,c]=l:s=c=l,!(!ke(s)||!ke(c)))return[t-s,t+c]})):[]}var Lt=e=>{var t=Yt(e),r=po(e);return vo(e,t,r)},uu=Y([Lt],e=>e==null?void 0:e.dataKey),ZI=Y([WC,NC,Lt],VC),t3=(e,t,r,n)=>{var l={},s=t.reduce((c,d)=>{if(d.stackId==null)return c;var h=c[d.stackId];return h==null&&(h=[]),h.push(d),c[d.stackId]=h,c},l);return Object.fromEntries(Object.entries(s).map(c=>{var[d,h]=c,m=n?[...h].reverse():h,p=m.map(Ld);return[d,{stackedData:y8(e,p,r),graphicalItems:m}]}))},Yf=Y([ZI,WC,lu,BC],t3),r3=(e,t,r,n)=>{var{dataStartIndex:l,dataEndIndex:s}=t;if(n==null&&r!=="zAxis"){var c=w8(e,l,s);if(!(c!=null&&c[0]===0&&c[1]===0))return c}},QI=Y([bt],e=>e.allowDataOverflow),Sg=e=>{var t;if(e==null||!("domain"in e))return Ky;if(e.domain!=null)return e.domain;if("ticks"in e&&e.ticks!=null){if(e.type==="number"){var r=pa(e.ticks);return[Math.min(...r),Math.max(...r)]}if(e.type==="category")return e.ticks.map(String)}return(t=e==null?void 0:e.domain)!==null&&t!==void 0?t:Ky},Ng=Y([bt],Sg),Og=Y([Ng,QI],AC),WI=Y([Yf,ba,dt,Og],r3,{memoizeOptions:{resultEqualityCheck:$d}}),Hd=e=>e.errorBars,JI=(e,t,r)=>e.flatMap(n=>t[n.id]).filter(Boolean).filter(n=>e3(r,n)),Gf=function(){for(var t=arguments.length,r=new Array(t),n=0;n{var s,c;if(r.length>0&&e.forEach(d=>{r.forEach(h=>{var m,p,y=(m=n[h.id])===null||m===void 0?void 0:m.filter(A=>e3(l,A)),x=We(d,(p=t.dataKey)!==null&&p!==void 0?p:h.dataKey),w=FI(d,x,y);if(w.length>=2){var j=Math.min(...w),_=Math.max(...w);(s==null||jc)&&(c=_)}var N=tN(x);N!=null&&(s=s==null?N[0]:Math.min(s,N[0]),c=c==null?N[1]:Math.max(c,N[1]))})}),(t==null?void 0:t.dataKey)!=null&&e.forEach(d=>{var h=tN(We(d,t.dataKey));h!=null&&(s=s==null?h[0]:Math.min(s,h[0]),c=c==null?h[1]:Math.max(c,h[1]))}),ke(s)&&ke(c))return[s,c]},e$=Y([jg,bt,VI,Hd,dt],Ag,{memoizeOptions:{resultEqualityCheck:$d}});function t$(e){var{value:t}=e;if(An(t)||t instanceof Date)return t}var r$=(e,t,r)=>{var n=e.map(t$).filter(l=>l!=null);return r&&(t.dataKey==null||t.allowDuplicatedCategory&&xA(n))?YE(0,e.length):t.allowDuplicatedCategory?n:Array.from(new Set(n))},n3=e=>e.referenceElements.dots,yo=(e,t,r)=>e.filter(n=>n.ifOverflow==="extendDomain").filter(n=>t==="xAxis"?n.xAxisId===r:n.yAxisId===r),n$=Y([n3,dt,ou],yo),a3=e=>e.referenceElements.areas,a$=Y([a3,dt,ou],yo),i3=e=>e.referenceElements.lines,i$=Y([i3,dt,ou],yo),l3=(e,t)=>{if(e!=null){var r=pa(e.map(n=>t==="xAxis"?n.x:n.y));if(r.length!==0)return[Math.min(...r),Math.max(...r)]}},l$=Y(n$,dt,l3),o3=(e,t)=>{if(e!=null){var r=pa(e.flatMap(n=>[t==="xAxis"?n.x1:n.y1,t==="xAxis"?n.x2:n.y2]));if(r.length!==0)return[Math.min(...r),Math.max(...r)]}},o$=Y([a$,dt],o3);function s$(e){var t;if(e.x!=null)return pa([e.x]);var r=(t=e.segment)===null||t===void 0?void 0:t.map(n=>n.x);return r==null||r.length===0?[]:pa(r)}function u$(e){var t;if(e.y!=null)return pa([e.y]);var r=(t=e.segment)===null||t===void 0?void 0:t.map(n=>n.y);return r==null||r.length===0?[]:pa(r)}var s3=(e,t)=>{if(e!=null){var r=e.flatMap(n=>t==="xAxis"?s$(n):u$(n));if(r.length!==0)return[Math.min(...r),Math.max(...r)]}},c$=Y([i$,dt],s3),f$=Y(l$,c$,o$,(e,t,r)=>Gf(e,r,t)),Eg=(e,t,r,n,l,s,c,d)=>{if(r!=null)return r;var h=c==="vertical"&&d==="xAxis"||c==="horizontal"&&d==="yAxis",m=h?Gf(n,s,l):Gf(s,l);return _I(t,m,e.allowDataOverflow)},d$=Y([bt,Ng,Og,WI,e$,f$,$e,dt],Eg,{memoizeOptions:{resultEqualityCheck:$d}}),h$=[0,1],Cg=(e,t,r,n,l,s,c)=>{if(!((e==null||r==null||r.length===0)&&c===void 0)){var{dataKey:d,type:h}=e,m=Mn(t,s);if(m&&d==null){var p;return YE(0,(p=r==null?void 0:r.length)!==null&&p!==void 0?p:0)}return h==="category"?r$(n,e,m):l==="expand"?h$:c}},kg=Y([bt,$e,jg,Ud,lu,dt,d$],Cg);function m$(e){return e in As}var u3=(e,t,r)=>{if(e!=null){var{scale:n,type:l}=e;if(n==="auto")return l==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!t)?"point":l==="category"?"band":"linear";if(typeof n=="string"){var s="scale".concat(Gs(n));return m$(s)?s:"point"}}},ci=Y([bt,QC,fg],u3);function Mg(e,t,r,n){if(!(r==null||n==null))return typeof e.scale=="function"?JS(e.scale,r,n):JS(t,r,n)}var Tg=(e,t,r)=>{var n=Sg(t);if(!(r!=="auto"&&r!=="linear")){if(t!=null&&t.tickCount&&Array.isArray(n)&&(n[0]==="auto"||n[1]==="auto")&&ma(e))return EI(e,t.tickCount,t.allowDecimals);if(t!=null&&t.tickCount&&t.type==="number"&&ma(e))return CI(e,t.tickCount,t.allowDecimals)}},Dg=Y([kg,vo,ci],Tg),Pg=(e,t,r,n)=>{if(n!=="angleAxis"&&(e==null?void 0:e.type)==="number"&&ma(t)&&Array.isArray(r)&&r.length>0){var l,s,c=t[0],d=(l=r[0])!==null&&l!==void 0?l:0,h=t[1],m=(s=r[r.length-1])!==null&&s!==void 0?s:0;return[Math.min(c,d),Math.max(h,m)]}return t},p$=Y([bt,kg,Dg,dt],Pg),v$=Y(Ud,bt,(e,t)=>{if(!(!t||t.type!=="number")){var r=1/0,n=Array.from(pa(e.map(y=>y.value))).sort((y,x)=>y-x),l=n[0],s=n[n.length-1];if(l==null||s==null)return 1/0;var c=s-l;if(c===0)return 1/0;for(var d=0;dl,(e,t,r,n,l)=>{if(!ke(e))return 0;var s=t==="vertical"?n.height:n.width;if(l==="gap")return e*s/2;if(l==="no-gap"){var c=nr(r,e*s),d=e*s/2;return d-c-(d-c)/s*c}return 0}),y$=(e,t,r)=>{var n=wa(e,t);return n==null||typeof n.padding!="string"?0:c3(e,"xAxis",t,r,n.padding)},g$=(e,t,r)=>{var n=ja(e,t);return n==null||typeof n.padding!="string"?0:c3(e,"yAxis",t,r,n.padding)},x$=Y(wa,y$,(e,t)=>{var r,n;if(e==null)return{left:0,right:0};var{padding:l}=e;return typeof l=="string"?{left:t,right:t}:{left:((r=l.left)!==null&&r!==void 0?r:0)+t,right:((n=l.right)!==null&&n!==void 0?n:0)+t}}),b$=Y(ja,g$,(e,t)=>{var r,n;if(e==null)return{top:0,bottom:0};var{padding:l}=e;return typeof l=="string"?{top:t,bottom:t}:{top:((r=l.top)!==null&&r!==void 0?r:0)+t,bottom:((n=l.bottom)!==null&&n!==void 0?n:0)+t}}),w$=Y([zt,x$,jd,wd,(e,t,r)=>r],(e,t,r,n,l)=>{var{padding:s}=n;return l?[s.left,r.width-s.right]:[e.left+t.left,e.left+e.width-t.right]}),j$=Y([zt,$e,b$,jd,wd,(e,t,r)=>r],(e,t,r,n,l,s)=>{var{padding:c}=l;return s?[n.height-c.bottom,c.top]:t==="horizontal"?[e.top+e.height-r.bottom,e.top+r.top]:[e.top+r.top,e.top+e.height-r.bottom]}),cu=(e,t,r,n)=>{var l;switch(t){case"xAxis":return w$(e,r,n);case"yAxis":return j$(e,r,n);case"zAxis":return(l=yg(e,r))===null||l===void 0?void 0:l.range;case"angleAxis":return KC(e);case"radiusAxis":return YC(e,r);default:return}},f3=Y([bt,cu],Pd),_$=Y([ci,p$],XC),Kd=Y([bt,ci,_$,f3],Mg);Y([su,Hd,dt],JI);function d3(e,t){return e.idt.id?1:0}var Yd=(e,t)=>t,Gd=(e,t,r)=>r,S$=Y(xd,Yd,Gd,(e,t,r)=>e.filter(n=>n.orientation===t).filter(n=>n.mirror===r).sort(d3)),N$=Y(bd,Yd,Gd,(e,t,r)=>e.filter(n=>n.orientation===t).filter(n=>n.mirror===r).sort(d3)),h3=(e,t)=>({width:e.width,height:t.height}),O$=(e,t)=>{var r=typeof t.width=="number"?t.width:Zs;return{width:r,height:e.height}},m3=Y(zt,wa,h3),A$=(e,t,r)=>{switch(t){case"top":return e.top;case"bottom":return r-e.bottom;default:return 0}},E$=(e,t,r)=>{switch(t){case"left":return e.left;case"right":return r-e.right;default:return 0}},C$=Y(ga,zt,S$,Yd,Gd,(e,t,r,n,l)=>{var s={},c;return r.forEach(d=>{var h=h3(t,d);c==null&&(c=A$(t,n,e));var m=n==="top"&&!l||n==="bottom"&&l;s[d.id]=c-Number(m)*h.height,c+=(m?-1:1)*h.height}),s}),k$=Y(ya,zt,N$,Yd,Gd,(e,t,r,n,l)=>{var s={},c;return r.forEach(d=>{var h=O$(t,d);c==null&&(c=E$(t,n,e));var m=n==="left"&&!l||n==="right"&&l;s[d.id]=c-Number(m)*h.width,c+=(m?-1:1)*h.width}),s}),M$=(e,t)=>{var r=wa(e,t);if(r!=null)return C$(e,r.orientation,r.mirror)},T$=Y([zt,wa,M$,(e,t)=>t],(e,t,r,n)=>{if(t!=null){var l=r==null?void 0:r[n];return l==null?{x:e.left,y:0}:{x:e.left,y:l}}}),D$=(e,t)=>{var r=ja(e,t);if(r!=null)return k$(e,r.orientation,r.mirror)},P$=Y([zt,ja,D$,(e,t)=>t],(e,t,r,n)=>{if(t!=null){var l=r==null?void 0:r[n];return l==null?{x:0,y:e.top}:{x:l,y:e.top}}}),p3=Y(zt,ja,(e,t)=>{var r=typeof t.width=="number"?t.width:Zs;return{width:r,height:e.height}}),rN=(e,t,r)=>{switch(t){case"xAxis":return m3(e,r).width;case"yAxis":return p3(e,r).height;default:return}},v3=(e,t,r,n)=>{if(r!=null){var{allowDuplicatedCategory:l,type:s,dataKey:c}=r,d=Mn(e,n),h=t.map(m=>m.value);if(c&&d&&s==="category"&&l&&xA(h))return h}},zg=Y([$e,Ud,bt,dt],v3),y3=(e,t,r,n)=>{if(!(r==null||r.dataKey==null)){var{type:l,scale:s}=r,c=Mn(e,n);if(c&&(l==="number"||s!=="auto"))return t.map(d=>d.value)}},Rg=Y([$e,Ud,vo,dt],y3),nN=Y([$e,YI,ci,Kd,zg,Rg,cu,Dg,dt],(e,t,r,n,l,s,c,d,h)=>{if(t!=null){var m=Mn(e,h);return{angle:t.angle,interval:t.interval,minTickGap:t.minTickGap,orientation:t.orientation,tick:t.tick,tickCount:t.tickCount,tickFormatter:t.tickFormatter,ticks:t.ticks,type:t.type,unit:t.unit,axisType:h,categoricalDomain:s,duplicateDomain:l,isCategorical:m,niceTicks:d,range:c,realScaleType:r,scale:n}}}),z$=(e,t,r,n,l,s,c,d,h)=>{if(!(t==null||n==null)){var m=Mn(e,h),{type:p,ticks:y,tickCount:x}=t,w=r==="scaleBand"&&typeof n.bandwidth=="function"?n.bandwidth()/2:2,j=p==="category"&&n.bandwidth?n.bandwidth()/w:0;j=h==="angleAxis"&&s!=null&&s.length>=2?Ht(s[0]-s[1])*2*j:j;var _=y||l;return _?_.map((N,A)=>{var O=c?c.indexOf(N):N,P=n.map(O);return ke(P)?{index:A,coordinate:P+j,value:N,offset:j}:null}).filter(xr):m&&d?d.map((N,A)=>{var O=n.map(N);return ke(O)?{coordinate:O+j,value:N,index:A,offset:j}:null}).filter(xr):n.ticks?n.ticks(x).map((N,A)=>{var O=n.map(N);return ke(O)?{coordinate:O+j,value:N,index:A,offset:j}:null}).filter(xr):n.domain().map((N,A)=>{var O=n.map(N);return ke(O)?{coordinate:O+j,value:c?c[N]:N,index:A,offset:j}:null}).filter(xr)}},g3=Y([$e,vo,ci,Kd,Dg,cu,zg,Rg,dt],z$),R$=(e,t,r,n,l,s,c)=>{if(!(t==null||r==null||n==null||n[0]===n[1])){var d=Mn(e,c),{tickCount:h}=t,m=0;return m=c==="angleAxis"&&(n==null?void 0:n.length)>=2?Ht(n[0]-n[1])*2*m:m,d&&s?s.map((p,y)=>{var x=r.map(p);return ke(x)?{coordinate:x+m,value:p,index:y,offset:m}:null}).filter(xr):r.ticks?r.ticks(h).map((p,y)=>{var x=r.map(p);return ke(x)?{coordinate:x+m,value:p,index:y,offset:m}:null}).filter(xr):r.domain().map((p,y)=>{var x=r.map(p);return ke(x)?{coordinate:x+m,value:l?l[p]:p,index:y,offset:m}:null}).filter(xr)}},ai=Y([$e,vo,Kd,cu,zg,Rg,dt],R$),ii=Y(bt,Kd,(e,t)=>{if(!(e==null||t==null))return Kf(Kf({},e),{},{scale:t})}),L$=Y([bt,ci,kg,f3],Mg);Y((e,t,r)=>yg(e,r),L$,(e,t)=>{if(!(e==null||t==null))return Kf(Kf({},e),{},{scale:t})});var I$=Y([$e,xd,bd],(e,t,r)=>{switch(e){case"horizontal":return t.some(n=>n.reversed)?"right-to-left":"left-to-right";case"vertical":return r.some(n=>n.reversed)?"bottom-to-top":"top-to-bottom";case"centric":case"radial":return"left-to-right";default:return}}),x3=e=>e.options.defaultTooltipEventType,b3=e=>e.options.validateTooltipEventTypes;function w3(e,t,r){if(e==null)return t;var n=e?"axis":"item";return r==null?t:r.includes(n)?n:t}function Lg(e,t){var r=x3(e),n=b3(e);return w3(t,r,n)}function $$(e){return ge(t=>Lg(t,e))}var j3=(e,t)=>{var r,n=Number(t);if(!(dn(n)||t==null))return n>=0?e==null||(r=e[n])===null||r===void 0?void 0:r.value:void 0},B$=e=>e.tooltip.settings,Ja={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},q$={itemInteraction:{click:Ja,hover:Ja},axisInteraction:{click:Ja,hover:Ja},keyboardInteraction:Ja,syncInteraction:{active:!1,index:null,dataKey:void 0,label:void 0,coordinate:void 0,sourceViewBox:void 0,graphicalItemId:void 0},tooltipItemPayloads:[],settings:{shared:void 0,trigger:"hover",axisId:0,active:!1,defaultIndex:void 0}},_3=jr({name:"tooltip",initialState:q$,reducers:{addTooltipEntrySettings:{reducer(e,t){e.tooltipItemPayloads.push(t.payload)},prepare:st()},replaceTooltipEntrySettings:{reducer(e,t){var{prev:r,next:n}=t.payload,l=fn(e).tooltipItemPayloads.indexOf(r);l>-1&&(e.tooltipItemPayloads[l]=n)},prepare:st()},removeTooltipEntrySettings:{reducer(e,t){var r=fn(e).tooltipItemPayloads.indexOf(t.payload);r>-1&&e.tooltipItemPayloads.splice(r,1)},prepare:st()},setTooltipSettingsState(e,t){e.settings=t.payload},setActiveMouseOverItemIndex(e,t){e.syncInteraction.active=!1,e.keyboardInteraction.active=!1,e.itemInteraction.hover.active=!0,e.itemInteraction.hover.index=t.payload.activeIndex,e.itemInteraction.hover.dataKey=t.payload.activeDataKey,e.itemInteraction.hover.graphicalItemId=t.payload.activeGraphicalItemId,e.itemInteraction.hover.coordinate=t.payload.activeCoordinate},mouseLeaveChart(e){e.itemInteraction.hover.active=!1,e.axisInteraction.hover.active=!1},mouseLeaveItem(e){e.itemInteraction.hover.active=!1},setActiveClickItemIndex(e,t){e.syncInteraction.active=!1,e.itemInteraction.click.active=!0,e.keyboardInteraction.active=!1,e.itemInteraction.click.index=t.payload.activeIndex,e.itemInteraction.click.dataKey=t.payload.activeDataKey,e.itemInteraction.click.graphicalItemId=t.payload.activeGraphicalItemId,e.itemInteraction.click.coordinate=t.payload.activeCoordinate},setMouseOverAxisIndex(e,t){e.syncInteraction.active=!1,e.axisInteraction.hover.active=!0,e.keyboardInteraction.active=!1,e.axisInteraction.hover.index=t.payload.activeIndex,e.axisInteraction.hover.dataKey=t.payload.activeDataKey,e.axisInteraction.hover.coordinate=t.payload.activeCoordinate},setMouseClickAxisIndex(e,t){e.syncInteraction.active=!1,e.keyboardInteraction.active=!1,e.axisInteraction.click.active=!0,e.axisInteraction.click.index=t.payload.activeIndex,e.axisInteraction.click.dataKey=t.payload.activeDataKey,e.axisInteraction.click.coordinate=t.payload.activeCoordinate},setSyncInteraction(e,t){e.syncInteraction=t.payload},setKeyboardInteraction(e,t){e.keyboardInteraction.active=t.payload.active,e.keyboardInteraction.index=t.payload.activeIndex,e.keyboardInteraction.coordinate=t.payload.activeCoordinate}}}),{addTooltipEntrySettings:U$,replaceTooltipEntrySettings:H$,removeTooltipEntrySettings:K$,setTooltipSettingsState:Y$,setActiveMouseOverItemIndex:S3,mouseLeaveItem:G$,mouseLeaveChart:N3,setActiveClickItemIndex:V$,setMouseOverAxisIndex:O3,setMouseClickAxisIndex:X$,setSyncInteraction:Yy,setKeyboardInteraction:Gy}=_3.actions,F$=_3.reducer;function aN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Kc(e){for(var t=1;t{if(t==null)return Ja;var l=J$(e,t,r);if(l==null)return Ja;if(l.active)return l;if(e.keyboardInteraction.active)return e.keyboardInteraction;if(e.syncInteraction.active&&e.syncInteraction.index!=null)return e.syncInteraction;var s=e.settings.active===!0;if(eB(l)){if(s)return Kc(Kc({},l),{},{active:!0})}else if(n!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:n,graphicalItemId:void 0};return Kc(Kc({},Ja),{},{coordinate:l.coordinate})};function tB(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(e instanceof Date){var t=e.valueOf();return Number.isFinite(t)?t:void 0}var r=Number(e);return Number.isFinite(r)?r:void 0}function rB(e,t){var r=tB(e),n=t[0],l=t[1];if(r===void 0)return!1;var s=Math.min(n,l),c=Math.max(n,l);return r>=s&&r<=c}function nB(e,t,r){if(r==null||t==null)return!0;var n=We(e,t);return n==null||!ma(r)?!0:rB(n,r)}var Ig=(e,t,r,n)=>{var l=e==null?void 0:e.index;if(l==null)return null;var s=Number(l);if(!ke(s))return l;var c=0,d=1/0;t.length>0&&(d=t.length-1);var h=Math.max(c,Math.min(s,d)),m=t[h];return m==null||nB(m,r,n)?String(h):null},E3=(e,t,r,n,l,s,c)=>{if(s!=null){var d=c[0],h=d==null?void 0:d.getPosition(s);if(h!=null)return h;var m=l==null?void 0:l[Number(s)];if(m)switch(r){case"horizontal":return{x:m.coordinate,y:(n.top+t)/2};default:return{x:(n.left+e)/2,y:m.coordinate}}}},C3=(e,t,r,n)=>{if(t==="axis")return e.tooltipItemPayloads;if(e.tooltipItemPayloads.length===0)return[];var l;if(r==="hover"?l=e.itemInteraction.hover.graphicalItemId:l=e.itemInteraction.click.graphicalItemId,l==null&&n!=null){var s=e.tooltipItemPayloads[0];return s!=null?[s]:[]}return e.tooltipItemPayloads.filter(c=>{var d;return((d=c.settings)===null||d===void 0?void 0:d.graphicalItemId)===l})},k3=e=>e.options.tooltipPayloadSearcher,go=e=>e.tooltip;function iN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function lN(e){for(var t=1;t{if(!(t==null||s==null)){var{chartData:d,computedData:h,dataStartIndex:m,dataEndIndex:p}=r,y=[];return e.reduce((x,w)=>{var j,{dataDefinedOnItem:_,settings:N}=w,A=oB(_,d),O=Array.isArray(A)?dE(A,m,p):A,P=(j=N==null?void 0:N.dataKey)!==null&&j!==void 0?j:n,k=N==null?void 0:N.nameKey,z;if(n&&Array.isArray(O)&&!Array.isArray(O[0])&&c==="axis"?z=bA(O,n,l):z=s(O,t,h,k),Array.isArray(z))z.forEach(R=>{var $=lN(lN({},N),{},{name:R.name,unit:R.unit,color:void 0,fill:void 0});x.push(a2({tooltipEntrySettings:$,dataKey:R.dataKey,payload:R.payload,value:We(R.payload,R.dataKey),name:R.name}))});else{var T;x.push(a2({tooltipEntrySettings:N,dataKey:P,payload:z,value:We(z,P),name:(T=We(z,k))!==null&&T!==void 0?T:N==null?void 0:N.name}))}return x},y)}},$g=Y([Lt,QC,fg],u3),sB=Y([e=>e.graphicalItems.cartesianItems,e=>e.graphicalItems.polarItems],(e,t)=>[...e,...t]),uB=Y([Yt,po],gg),xo=Y([sB,Lt,uB],xg,{memoizeOptions:{resultEqualityCheck:Bd}}),cB=Y([xo],e=>e.filter(Id)),fB=Y([xo],bg,{memoizeOptions:{resultEqualityCheck:Bd}}),bo=Y([fB,ba],wg),dB=Y([cB,ba,Lt],VC),Bg=Y([bo,Lt,xo],_g),T3=Y([Lt],Sg),hB=Y([Lt],e=>e.allowDataOverflow),D3=Y([T3,hB],AC),mB=Y([xo],e=>e.filter(Id)),pB=Y([dB,mB,lu,BC],t3),vB=Y([pB,ba,Yt,D3],r3),yB=Y([xo],JC),gB=Y([bo,Lt,yB,Hd,Yt],Ag,{memoizeOptions:{resultEqualityCheck:$d}}),xB=Y([n3,Yt,po],yo),bB=Y([xB,Yt],l3),wB=Y([a3,Yt,po],yo),jB=Y([wB,Yt],o3),_B=Y([i3,Yt,po],yo),SB=Y([_B,Yt],s3),NB=Y([bB,SB,jB],Gf),OB=Y([Lt,T3,D3,vB,gB,NB,$e,Yt],Eg),fu=Y([Lt,$e,bo,Bg,lu,Yt,OB],Cg),AB=Y([fu,Lt,$g],Tg),EB=Y([Lt,fu,AB,Yt],Pg),P3=e=>{var t=Yt(e),r=po(e),n=!1;return cu(e,t,r,n)},z3=Y([Lt,P3],Pd),R3=Y([Lt,$g,EB,z3],Mg),CB=Y([$e,Bg,Lt,Yt],v3),kB=Y([$e,Bg,Lt,Yt],y3),MB=(e,t,r,n,l,s,c,d)=>{if(t){var{type:h}=t,m=Mn(e,d);if(n){var p=r==="scaleBand"&&n.bandwidth?n.bandwidth()/2:2,y=h==="category"&&n.bandwidth?n.bandwidth()/p:0;return y=d==="angleAxis"&&l!=null&&(l==null?void 0:l.length)>=2?Ht(l[0]-l[1])*2*y:y,m&&c?c.map((x,w)=>{var j=n.map(x);return ke(j)?{coordinate:j+y,value:x,index:w,offset:y}:null}).filter(xr):n.domain().map((x,w)=>{var j=n.map(x);return ke(j)?{coordinate:j+y,value:s?s[x]:x,index:w,offset:y}:null}).filter(xr)}}},_a=Y([$e,Lt,$g,R3,P3,CB,kB,Yt],MB),qg=Y([x3,b3,B$],(e,t,r)=>w3(r.shared,e,t)),L3=e=>e.tooltip.settings.trigger,Ug=e=>e.tooltip.settings.defaultIndex,du=Y([go,qg,L3,Ug],A3),li=Y([du,bo,uu,fu],Ig),I3=Y([_a,li],j3),Hg=Y([du],e=>{if(e)return e.dataKey}),TB=Y([du],e=>{if(e)return e.graphicalItemId}),$3=Y([go,qg,L3,Ug],C3),DB=Y([ya,ga,$e,zt,_a,Ug,$3],E3),PB=Y([du,DB],(e,t)=>e!=null&&e.coordinate?e.coordinate:t),zB=Y([du],e=>{var t;return(t=e==null?void 0:e.active)!==null&&t!==void 0?t:!1}),RB=Y([$3,li,ba,uu,I3,k3,qg],M3),LB=Y([RB],e=>{if(e!=null){var t=e.map(r=>r.payload).filter(r=>r!=null);return Array.from(new Set(t))}});function oN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function sN(e){for(var t=1;tge(Lt),UB=()=>{var e=qB(),t=ge(_a),r=ge(R3);return ro(!e||!r?void 0:sN(sN({},e),{},{scale:r}),t)};function uN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Hl(e){for(var t=1;t{var l=t.find(s=>s&&s.index===r);if(l){if(e==="horizontal")return{x:l.coordinate,y:n.chartY};if(e==="vertical")return{x:n.chartX,y:l.coordinate}}return{x:0,y:0}},VB=(e,t,r,n)=>{var l=t.find(m=>m&&m.index===r);if(l){if(e==="centric"){var s=l.coordinate,{radius:c}=n;return Hl(Hl(Hl({},n),Et(n.cx,n.cy,c,s)),{},{angle:s,radius:c})}var d=l.coordinate,{angle:h}=n;return Hl(Hl(Hl({},n),Et(n.cx,n.cy,d,h)),{},{angle:h,radius:d})}return{angle:0,clockWise:!1,cx:0,cy:0,endAngle:0,innerRadius:0,outerRadius:0,radius:0,startAngle:0,x:0,y:0}};function XB(e,t){var{chartX:r,chartY:n}=e;return r>=t.left&&r<=t.left+t.width&&n>=t.top&&n<=t.top+t.height}var B3=(e,t,r,n,l)=>{var s,c=(s=t==null?void 0:t.length)!==null&&s!==void 0?s:0;if(c<=1||e==null)return 0;if(n==="angleAxis"&&l!=null&&Math.abs(Math.abs(l[1]-l[0])-360)<=1e-6)for(var d=0;d0?(h=r[d-1])===null||h===void 0?void 0:h.coordinate:(m=r[c-1])===null||m===void 0?void 0:m.coordinate,j=(p=r[d])===null||p===void 0?void 0:p.coordinate,_=d>=c-1?(y=r[0])===null||y===void 0?void 0:y.coordinate:(x=r[d+1])===null||x===void 0?void 0:x.coordinate,N=void 0;if(!(w==null||j==null||_==null))if(Ht(j-w)!==Ht(_-j)){var A=[];if(Ht(_-j)===Ht(l[1]-l[0])){N=_;var O=j+l[1]-l[0];A[0]=Math.min(O,(O+w)/2),A[1]=Math.max(O,(O+w)/2)}else{N=w;var P=_+l[1]-l[0];A[0]=Math.min(j,(P+j)/2),A[1]=Math.max(j,(P+j)/2)}var k=[Math.min(j,(N+j)/2),Math.max(j,(N+j)/2)];if(e>k[0]&&e<=k[1]||e>=A[0]&&e<=A[1]){var z;return(z=r[d])===null||z===void 0?void 0:z.index}}else{var T=Math.min(w,_),R=Math.max(w,_);if(e>(T+j)/2&&e<=(R+j)/2){var $;return($=r[d])===null||$===void 0?void 0:$.index}}}else if(t)for(var Z=0;Z(X.coordinate+K.coordinate)/2||Z>0&&Z(X.coordinate+K.coordinate)/2&&e<=(X.coordinate+L.coordinate)/2)return X.index}}return-1},q3=()=>ge(fg),Kg=(e,t)=>t,U3=(e,t,r)=>r,Yg=(e,t,r,n)=>n,FB=Y(_a,e=>ud(e,t=>t.coordinate)),Gg=Y([go,Kg,U3,Yg],A3),Vg=Y([Gg,bo,uu,fu],Ig),ZB=(e,t,r)=>{if(t!=null){var n=go(e);return t==="axis"?r==="hover"?n.axisInteraction.hover.dataKey:n.axisInteraction.click.dataKey:r==="hover"?n.itemInteraction.hover.dataKey:n.itemInteraction.click.dataKey}},H3=Y([go,Kg,U3,Yg],C3),Vf=Y([ya,ga,$e,zt,_a,Yg,H3],E3),QB=Y([Gg,Vf],(e,t)=>{var r;return(r=e.coordinate)!==null&&r!==void 0?r:t}),K3=Y([_a,Vg],j3),WB=Y([H3,Vg,ba,uu,K3,k3,Kg],M3),JB=Y([Gg,Vg],(e,t)=>({isActive:e.active&&t!=null,activeIndex:t})),eq=(e,t,r,n,l,s,c)=>{if(!(!e||!r||!n||!l)&&XB(e,c)){var d=j8(e,t),h=B3(d,s,l,r,n),m=GB(t,l,h,e);return{activeIndex:String(h),activeCoordinate:m}}},tq=(e,t,r,n,l,s,c)=>{if(!(!e||!n||!l||!s||!r)){var d=$7(e,r);if(d){var h=_8(d,t),m=B3(h,c,s,n,l),p=VB(t,s,m,d);return{activeIndex:String(m),activeCoordinate:p}}}},rq=(e,t,r,n,l,s,c,d)=>{if(!(!e||!t||!n||!l||!s))return t==="horizontal"||t==="vertical"?eq(e,t,n,l,s,c,d):tq(e,t,r,n,l,s,c)},nq=Y(e=>e.zIndex.zIndexMap,(e,t)=>t,(e,t,r)=>r,(e,t,r)=>{if(t!=null){var n=e[t];if(n!=null)return r?n.panoramaElement:n.element}}),aq=Y(e=>e.zIndex.zIndexMap,e=>{var t=Object.keys(e).map(n=>parseInt(n,10)).concat(Object.values(Ct)),r=Array.from(new Set(t));return r.sort((n,l)=>n-l)},{memoizeOptions:{resultEqualityCheck:$I}});function cN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function fN(e){for(var t=1;tfN(fN({},e),{},{[t]:{element:void 0,panoramaElement:void 0,consumers:0}}),sq)},cq=new Set(Object.values(Ct));function fq(e){return cq.has(e)}var Y3=jr({name:"zIndex",initialState:uq,reducers:{registerZIndexPortal:{reducer:(e,t)=>{var{zIndex:r}=t.payload;e.zIndexMap[r]?e.zIndexMap[r].consumers+=1:e.zIndexMap[r]={consumers:1,element:void 0,panoramaElement:void 0}},prepare:st()},unregisterZIndexPortal:{reducer:(e,t)=>{var{zIndex:r}=t.payload;e.zIndexMap[r]&&(e.zIndexMap[r].consumers-=1,e.zIndexMap[r].consumers<=0&&!fq(r)&&delete e.zIndexMap[r])},prepare:st()},registerZIndexPortalElement:{reducer:(e,t)=>{var{zIndex:r,element:n,isPanorama:l}=t.payload;e.zIndexMap[r]?l?e.zIndexMap[r].panoramaElement=n:e.zIndexMap[r].element=n:e.zIndexMap[r]={consumers:0,element:l?void 0:n,panoramaElement:l?n:void 0}},prepare:st()},unregisterZIndexPortalElement:{reducer:(e,t)=>{var{zIndex:r}=t.payload;e.zIndexMap[r]&&(t.payload.isPanorama?e.zIndexMap[r].panoramaElement=void 0:e.zIndexMap[r].element=void 0)},prepare:st()}}}),{registerZIndexPortal:dq,unregisterZIndexPortal:hq,registerZIndexPortalElement:mq,unregisterZIndexPortalElement:pq}=Y3.actions,vq=Y3.reducer;function _r(e){var{zIndex:t,children:r}=e,n=eR(),l=n&&t!==void 0&&t!==0,s=ir(),c=rt();b.useLayoutEffect(()=>l?(c(dq({zIndex:t})),()=>{c(hq({zIndex:t}))}):Ji,[c,t,l]);var d=ge(h=>nq(h,t,s));return l?d?Jt.createPortal(r,d):null:r}function Vy(){return Vy=Object.assign?Object.assign.bind():function(e){for(var t=1;tb.useContext(G3),Lv={exports:{}},hN;function Sq(){return hN||(hN=1,(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function l(h,m,p){this.fn=h,this.context=m,this.once=p||!1}function s(h,m,p,y,x){if(typeof p!="function")throw new TypeError("The listener must be a function");var w=new l(p,y||h,x),j=r?r+m:m;return h._events[j]?h._events[j].fn?h._events[j]=[h._events[j],w]:h._events[j].push(w):(h._events[j]=w,h._eventsCount++),h}function c(h,m){--h._eventsCount===0?h._events=new n:delete h._events[m]}function d(){this._events=new n,this._eventsCount=0}d.prototype.eventNames=function(){var m=[],p,y;if(this._eventsCount===0)return m;for(y in p=this._events)t.call(p,y)&&m.push(r?y.slice(1):y);return Object.getOwnPropertySymbols?m.concat(Object.getOwnPropertySymbols(p)):m},d.prototype.listeners=function(m){var p=r?r+m:m,y=this._events[p];if(!y)return[];if(y.fn)return[y.fn];for(var x=0,w=y.length,j=new Array(w);x{if(t&&Array.isArray(e)){var r=Number.parseInt(t,10);if(!dn(r))return e[r]}},Aq={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},V3=jr({name:"options",initialState:Aq,reducers:{createEventEmitter:e=>{e.eventEmitter==null&&(e.eventEmitter=Symbol("rechartsEventEmitter"))}}}),Eq=V3.reducer,{createEventEmitter:Cq}=V3.actions;function kq(e){return e.tooltip.syncInteraction}var Mq={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},X3=jr({name:"chartData",initialState:Mq,reducers:{setChartData(e,t){if(e.chartData=t.payload,t.payload==null){e.dataStartIndex=0,e.dataEndIndex=0;return}t.payload.length>0&&e.dataEndIndex!==t.payload.length-1&&(e.dataEndIndex=t.payload.length-1)},setComputedData(e,t){e.computedData=t.payload},setDataStartEndIndexes(e,t){var{startIndex:r,endIndex:n}=t.payload;r!=null&&(e.dataStartIndex=r),n!=null&&(e.dataEndIndex=n)}}}),{setChartData:pN,setDataStartEndIndexes:Tq,setComputedData:kF}=X3.actions,Dq=X3.reducer,Pq=["x","y"];function vN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Kl(e){for(var t=1;th.rootProps.className);b.useEffect(()=>{if(e==null)return Ji;var h=(m,p,y)=>{if(t!==y&&e===m){if(n==="index"){var x;if(c&&p!==null&&p!==void 0&&(x=p.payload)!==null&&x!==void 0&&x.coordinate&&p.payload.sourceViewBox){var w=p.payload.coordinate,{x:j,y:_}=w,N=Iq(w,Pq),{x:A,y:O,width:P,height:k}=p.payload.sourceViewBox,z=Kl(Kl({},N),{},{x:c.x+(P?(j-A)/P:0)*c.width,y:c.y+(k?(_-O)/k:0)*c.height});r(Kl(Kl({},p),{},{payload:Kl(Kl({},p.payload),{},{coordinate:z})}))}else r(p);return}if(l!=null){var T;if(typeof n=="function"){var R={activeTooltipIndex:p.payload.index==null?void 0:Number(p.payload.index),isTooltipActive:p.payload.active,activeIndex:p.payload.index==null?void 0:Number(p.payload.index),activeLabel:p.payload.label,activeDataKey:p.payload.dataKey,activeCoordinate:p.payload.coordinate},$=n(l,R);T=l[$]}else n==="value"&&(T=l.find(q=>String(q.value)===p.payload.label));var{coordinate:Z}=p.payload;if(T==null||p.payload.active===!1||Z==null||c==null){r(Yy({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:X,y:L}=Z,K=Math.min(X,c.x+c.width),se=Math.min(L,c.y+c.height),ce={x:s==="horizontal"?T.coordinate:K,y:s==="horizontal"?se:T.coordinate},he=Yy({active:p.payload.active,coordinate:ce,dataKey:p.payload.dataKey,index:String(T.index),label:p.payload.label,sourceViewBox:p.payload.sourceViewBox,graphicalItemId:p.payload.graphicalItemId});r(he)}}};return Ks.on(Xy,h),()=>{Ks.off(Xy,h)}},[d,r,t,e,n,l,s,c])}function qq(){var e=ge(dg),t=ge(hg),r=rt();b.useEffect(()=>{if(e==null)return Ji;var n=(l,s,c)=>{t!==c&&e===l&&r(Tq(s))};return Ks.on(mN,n),()=>{Ks.off(mN,n)}},[r,t,e])}function Uq(){var e=rt();b.useEffect(()=>{e(Cq())},[e]),Bq(),qq()}function Hq(e,t,r,n,l,s){var c=ge(w=>ZB(w,e,t)),d=ge(hg),h=ge(dg),m=ge(qC),p=ge(kq),y=p==null?void 0:p.active,x=_d();b.useEffect(()=>{if(!y&&h!=null&&d!=null){var w=Yy({active:s,coordinate:r,dataKey:c,index:l,label:typeof n=="number"?String(n):n,sourceViewBox:x,graphicalItemId:void 0});Ks.emit(Xy,h,w,d)}},[y,r,c,l,n,d,h,m,s,x])}function yN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function gN(e){for(var t=1;t{R(Y$({shared:O,trigger:P,axisId:T,active:l,defaultIndex:$}))},[R,O,P,T,l,$]);var Z=_d(),X=zE(),L=$$(O),{activeIndex:K,isActive:se}=(t=ge(be=>JB(be,L,P,$)))!==null&&t!==void 0?t:{},ce=ge(be=>WB(be,L,P,$)),he=ge(be=>K3(be,L,P,$)),q=ge(be=>QB(be,L,P,$)),W=ce,ue=_q(),te=(r=l??se)!==null&&r!==void 0?r:!1,[M,C]=RA([W,te]),U=L==="axis"?he:void 0;Hq(L,P,q,U,K,te);var ee=z??ue;if(ee==null||Z==null||L==null)return null;var le=W??xN;te||(le=xN),m&&le.length&&(le=MA(le.filter(be=>be.value!=null&&(be.hide!==!0||n.includeHidden)),x,Vq));var me=le.length>0,pe=b.createElement($R,{allowEscapeViewBox:s,animationDuration:c,animationEasing:d,isAnimationActive:p,active:te,coordinate:q,hasPayload:me,offset:y,position:w,reverseDirection:j,useTranslate3d:_,viewBox:Z,wrapperStyle:N,lastBoundingBox:M,innerRef:C,hasPortalFromProps:!!z},Xq(h,gN(gN({},n),{},{payload:le,label:U,active:te,activeIndex:K,coordinate:q,accessibilityLayer:X})));return b.createElement(b.Fragment,null,Jt.createPortal(pe,ee),te&&b.createElement(jq,{cursor:A,tooltipEventType:L,coordinate:q,payload:le,index:K}))}var qi=e=>null;qi.displayName="Cell";function Zq(e,t,r){return(t=Qq(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Qq(e){var t=Wq(e,"string");return typeof t=="symbol"?t:t+""}function Wq(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}class Jq{constructor(t){Zq(this,"cache",new Map),this.maxSize=t}get(t){var r=this.cache.get(t);return r!==void 0&&(this.cache.delete(t),this.cache.set(t,r)),r}set(t,r){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){var n=this.cache.keys().next().value;n!=null&&this.cache.delete(n)}this.cache.set(t,r)}clear(){this.cache.clear()}size(){return this.cache.size}}function bN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function eU(e){for(var t=1;t{try{var r=document.getElementById(jN);r||(r=document.createElement("span"),r.setAttribute("id",jN),r.setAttribute("aria-hidden","true"),document.body.appendChild(r)),Object.assign(r.style,iU,t),r.textContent="".concat(e);var n=r.getBoundingClientRect();return{width:n.width,height:n.height}}catch{return{width:0,height:0}}},ks=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||Js.isSsr)return{width:0,height:0};if(!F3.enableCache)return _N(t,r);var n=lU(t,r),l=wN.get(n);if(l)return l;var s=_N(t,r);return wN.set(n,s),s},Z3;function oU(e,t,r){return(t=sU(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function sU(e){var t=uU(e,"string");return typeof t=="symbol"?t:t+""}function uU(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var SN=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,NN=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,cU=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,fU=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,dU={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},hU=["cm","mm","pt","pc","in","Q","px"];function mU(e){return hU.includes(e)}var Zl="NaN";function pU(e,t){return e*dU[t]}class Wt{static parse(t){var r,[,n,l]=(r=fU.exec(t))!==null&&r!==void 0?r:[];return n==null?Wt.NaN:new Wt(parseFloat(n),l??"")}constructor(t,r){this.num=t,this.unit=r,this.num=t,this.unit=r,dn(t)&&(this.unit=""),r!==""&&!cU.test(r)&&(this.num=NaN,this.unit=""),mU(r)&&(this.num=pU(t,r),this.unit="px")}add(t){return this.unit!==t.unit?new Wt(NaN,""):new Wt(this.num+t.num,this.unit)}subtract(t){return this.unit!==t.unit?new Wt(NaN,""):new Wt(this.num-t.num,this.unit)}multiply(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new Wt(NaN,""):new Wt(this.num*t.num,this.unit||t.unit)}divide(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new Wt(NaN,""):new Wt(this.num/t.num,this.unit||t.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return dn(this.num)}}Z3=Wt;oU(Wt,"NaN",new Z3(NaN,""));function Q3(e){if(e==null||e.includes(Zl))return Zl;for(var t=e;t.includes("*")||t.includes("/");){var r,[,n,l,s]=(r=SN.exec(t))!==null&&r!==void 0?r:[],c=Wt.parse(n??""),d=Wt.parse(s??""),h=l==="*"?c.multiply(d):c.divide(d);if(h.isNaN())return Zl;t=t.replace(SN,h.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var m,[,p,y,x]=(m=NN.exec(t))!==null&&m!==void 0?m:[],w=Wt.parse(p??""),j=Wt.parse(x??""),_=y==="+"?w.add(j):w.subtract(j);if(_.isNaN())return Zl;t=t.replace(NN,_.toString())}return t}var ON=/\(([^()]*)\)/;function vU(e){for(var t=e,r;(r=ON.exec(t))!=null;){var[,n]=r;t=t.replace(ON,Q3(n))}return t}function yU(e){var t=e.replace(/\s+/g,"");return t=vU(t),t=Q3(t),t}function gU(e){try{return yU(e)}catch{return Zl}}function Iv(e){var t=gU(e.slice(5,-1));return t===Zl?"":t}var xU=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],bU=["dx","dy","angle","className","breakAll"];function Fy(){return Fy=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var{children:t,breakAll:r,style:n}=e;try{var l=[];xt(t)||(r?l=t.toString().split(""):l=t.toString().split(W3));var s=l.map(d=>({word:d,width:ks(d,n).width})),c=r?0:ks(" ",n).width;return{wordsWithComputedWidth:s,spaceWidth:c}}catch{return null}};function jU(e){return e==="start"||e==="middle"||e==="end"||e==="inherit"}var e4=(e,t,r,n)=>e.reduce((l,s)=>{var{word:c,width:d}=s,h=l[l.length-1];if(h&&d!=null&&(t==null||n||h.width+d+re.reduce((t,r)=>t.width>r.width?t:r),_U="…",EN=(e,t,r,n,l,s,c,d)=>{var h=e.slice(0,t),m=J3({breakAll:r,style:n,children:h+_U});if(!m)return[!1,[]];var p=e4(m.wordsWithComputedWidth,s,c,d),y=p.length>l||t4(p).width>Number(s);return[y,p]},SU=(e,t,r,n,l)=>{var{maxLines:s,children:c,style:d,breakAll:h}=e,m=de(s),p=String(c),y=e4(t,n,r,l);if(!m||l)return y;var x=y.length>s||t4(y).width>Number(n);if(!x)return y;for(var w=0,j=p.length-1,_=0,N;w<=j&&_<=p.length-1;){var A=Math.floor((w+j)/2),O=A-1,[P,k]=EN(p,O,h,d,s,n,r,l),[z]=EN(p,A,h,d,s,n,r,l);if(!P&&!z&&(w=A+1),P&&z&&(j=A-1),!P&&z){N=k;break}_++}return N||y},CN=e=>{var t=xt(e)?[]:e.toString().split(W3);return[{words:t,width:void 0}]},NU=e=>{var{width:t,scaleToFit:r,children:n,style:l,breakAll:s,maxLines:c}=e;if((t||r)&&!Js.isSsr){var d,h,m=J3({breakAll:s,children:n,style:l});if(m){var{wordsWithComputedWidth:p,spaceWidth:y}=m;d=p,h=y}else return CN(n);return SU({breakAll:s,children:n,maxLines:c,style:l},d,h,t,!!r)}return CN(n)},r4="#808080",OU={angle:0,breakAll:!1,capHeight:"0.71em",fill:r4,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},Vd=b.forwardRef((e,t)=>{var r=Mt(e,OU),{x:n,y:l,lineHeight:s,capHeight:c,fill:d,scaleToFit:h,textAnchor:m,verticalAnchor:p}=r,y=AN(r,xU),x=b.useMemo(()=>NU({breakAll:y.breakAll,children:y.children,maxLines:y.maxLines,scaleToFit:h,style:y.style,width:y.width}),[y.breakAll,y.children,y.maxLines,h,y.style,y.width]),{dx:w,dy:j,angle:_,className:N,breakAll:A}=y,O=AN(y,bU);if(!An(n)||!An(l)||x.length===0)return null;var P=Number(n)+(de(w)?w:0),k=Number(l)+(de(j)?j:0);if(!ke(P)||!ke(k))return null;var z;switch(p){case"start":z=Iv("calc(".concat(c,")"));break;case"middle":z=Iv("calc(".concat((x.length-1)/2," * -").concat(s," + (").concat(c," / 2))"));break;default:z=Iv("calc(".concat(x.length-1," * -").concat(s,")"));break}var T=[],R=x[0];if(h&&R!=null){var $=R.width,{width:Z}=y;T.push("scale(".concat(de(Z)&&de($)?Z/$:1,")"))}return _&&T.push("rotate(".concat(_,", ").concat(P,", ").concat(k,")")),T.length&&(O.transform=T.join(" ")),b.createElement("text",Fy({},ur(O),{ref:t,x:P,y:k,className:Ue("recharts-text",N),textAnchor:m,fill:d.includes("url")?r4:d}),x.map((X,L)=>{var K=X.words.join(A?"":" ");return b.createElement("tspan",{x:P,dy:L===0?z:s,key:"".concat(K,"-").concat(L)},K)}))});Vd.displayName="Text";function kN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function _n(e){for(var t=1;t{var{viewBox:t,position:r,offset:n=0,parentViewBox:l}=e,{x:s,y:c,height:d,upperWidth:h,lowerWidth:m}=P0(t),p=s,y=s+(h-m)/2,x=(p+y)/2,w=(h+m)/2,j=p+h/2,_=d>=0?1:-1,N=_*n,A=_>0?"end":"start",O=_>0?"start":"end",P=h>=0?1:-1,k=P*n,z=P>0?"end":"start",T=P>0?"start":"end",R=l;if(r==="top"){var $={x:p+h/2,y:c-N,horizontalAnchor:"middle",verticalAnchor:A};return R&&($.height=Math.max(c-R.y,0),$.width=h),$}if(r==="bottom"){var Z={x:y+m/2,y:c+d+N,horizontalAnchor:"middle",verticalAnchor:O};return R&&(Z.height=Math.max(R.y+R.height-(c+d),0),Z.width=m),Z}if(r==="left"){var X={x:x-k,y:c+d/2,horizontalAnchor:z,verticalAnchor:"middle"};return R&&(X.width=Math.max(X.x-R.x,0),X.height=d),X}if(r==="right"){var L={x:x+w+k,y:c+d/2,horizontalAnchor:T,verticalAnchor:"middle"};return R&&(L.width=Math.max(R.x+R.width-L.x,0),L.height=d),L}var K=R?{width:w,height:d}:{};return r==="insideLeft"?_n({x:x+k,y:c+d/2,horizontalAnchor:T,verticalAnchor:"middle"},K):r==="insideRight"?_n({x:x+w-k,y:c+d/2,horizontalAnchor:z,verticalAnchor:"middle"},K):r==="insideTop"?_n({x:p+h/2,y:c+N,horizontalAnchor:"middle",verticalAnchor:O},K):r==="insideBottom"?_n({x:y+m/2,y:c+d-N,horizontalAnchor:"middle",verticalAnchor:A},K):r==="insideTopLeft"?_n({x:p+k,y:c+N,horizontalAnchor:T,verticalAnchor:O},K):r==="insideTopRight"?_n({x:p+h-k,y:c+N,horizontalAnchor:z,verticalAnchor:O},K):r==="insideBottomLeft"?_n({x:y+k,y:c+d-N,horizontalAnchor:T,verticalAnchor:A},K):r==="insideBottomRight"?_n({x:y+m-k,y:c+d-N,horizontalAnchor:z,verticalAnchor:A},K):r&&typeof r=="object"&&(de(r.x)||Vi(r.x))&&(de(r.y)||Vi(r.y))?_n({x:s+nr(r.x,w),y:c+nr(r.y,d),horizontalAnchor:"end",verticalAnchor:"end"},K):_n({x:j,y:c+d/2,horizontalAnchor:"middle",verticalAnchor:"middle"},K)},MU=["labelRef"],TU=["content"];function MN(e,t){if(e==null)return{};var r,n,l=DU(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n{var{x:t,y:r,upperWidth:n,lowerWidth:l,width:s,height:c,children:d}=e,h=b.useMemo(()=>({x:t,y:r,upperWidth:n,lowerWidth:l,width:s,height:c}),[t,r,n,l,s,c]);return b.createElement(n4.Provider,{value:h},d)},a4=()=>{var e=b.useContext(n4),t=_d();return e||(t?P0(t):void 0)},IU=b.createContext(null),$U=()=>{var e=b.useContext(IU),t=ge(GC);return e||t},BU=e=>{var{value:t,formatter:r}=e,n=xt(e.children)?t:e.children;return typeof r=="function"?r(n):n},Fg=e=>e!=null&&typeof e=="function",qU=(e,t)=>{var r=Ht(t-e),n=Math.min(Math.abs(t-e),360);return r*n},UU=(e,t,r,n,l)=>{var{offset:s,className:c}=e,{cx:d,cy:h,innerRadius:m,outerRadius:p,startAngle:y,endAngle:x,clockWise:w}=l,j=(m+p)/2,_=qU(y,x),N=_>=0?1:-1,A,O;switch(t){case"insideStart":A=y+N*s,O=w;break;case"insideEnd":A=x-N*s,O=!w;break;case"end":A=x+N*s,O=w;break;default:throw new Error("Unsupported position ".concat(t))}O=_<=0?O:!O;var P=Et(d,h,j,A),k=Et(d,h,j,A+(O?1:-1)*359),z="M".concat(P.x,",").concat(P.y,` + A`).concat(j,",").concat(j,",0,1,").concat(O?0:1,`, + `).concat(k.x,",").concat(k.y),T=xt(e.id)?Ms("recharts-radial-line-"):e.id;return b.createElement("text",na({},n,{dominantBaseline:"central",className:Ue("recharts-radial-bar-label",c)}),b.createElement("defs",null,b.createElement("path",{id:T,d:z})),b.createElement("textPath",{xlinkHref:"#".concat(T)},r))},HU=(e,t,r)=>{var{cx:n,cy:l,innerRadius:s,outerRadius:c,startAngle:d,endAngle:h}=e,m=(d+h)/2;if(r==="outside"){var{x:p,y}=Et(n,l,c+t,m);return{x:p,y,textAnchor:p>=n?"start":"end",verticalAnchor:"middle"}}if(r==="center")return{x:n,y:l,textAnchor:"middle",verticalAnchor:"middle"};if(r==="centerTop")return{x:n,y:l,textAnchor:"middle",verticalAnchor:"start"};if(r==="centerBottom")return{x:n,y:l,textAnchor:"middle",verticalAnchor:"end"};var x=(s+c)/2,{x:w,y:j}=Et(n,l,x,m);return{x:w,y:j,textAnchor:"middle",verticalAnchor:"middle"}},rf=e=>e!=null&&"cx"in e&&de(e.cx),KU={angle:0,offset:5,zIndex:Ct.label,position:"middle",textBreakAll:!1};function YU(e){if(!rf(e))return e;var{cx:t,cy:r,outerRadius:n}=e,l=n*2;return{x:t-n,y:r-n,width:l,upperWidth:l,lowerWidth:l,height:l}}function Qa(e){var t=Mt(e,KU),{viewBox:r,parentViewBox:n,position:l,value:s,children:c,content:d,className:h="",textBreakAll:m,labelRef:p}=t,y=$U(),x=a4(),w=l==="center"?x:y??x,j,_,N;r==null?j=w:rf(r)?j=r:j=P0(r);var A=YU(j);if(!j||xt(s)&&xt(c)&&!b.isValidElement(d)&&typeof d!="function")return null;var O=Es(Es({},t),{},{viewBox:j});if(b.isValidElement(d)){var{labelRef:P}=O,k=MN(O,MU);return b.cloneElement(d,k)}if(typeof d=="function"){var{content:z}=O,T=MN(O,TU);if(_=b.createElement(d,T),b.isValidElement(_))return _}else _=BU(t);var R=ur(t);if(rf(j)){if(l==="insideStart"||l==="insideEnd"||l==="end")return UU(t,l,_,R,j);N=HU(j,t.offset,t.position)}else{if(!A)return null;var $=kU({viewBox:A,position:l,offset:t.offset,parentViewBox:rf(n)?void 0:n});N=Es(Es({x:$.x,y:$.y,textAnchor:$.horizontalAnchor,verticalAnchor:$.verticalAnchor},$.width!==void 0?{width:$.width}:{}),$.height!==void 0?{height:$.height}:{})}return b.createElement(_r,{zIndex:t.zIndex},b.createElement(Vd,na({ref:p,className:Ue("recharts-label",h)},R,N,{textAnchor:jU(R.textAnchor)?R.textAnchor:N.textAnchor,breakAll:m}),_))}Qa.displayName="Label";var GU=(e,t,r)=>{if(!e)return null;var n={viewBox:t,labelRef:r};return e===!0?b.createElement(Qa,na({key:"label-implicit"},n)):An(e)?b.createElement(Qa,na({key:"label-implicit",value:e},n)):b.isValidElement(e)?e.type===Qa?b.cloneElement(e,Es({key:"label-implicit"},n)):b.createElement(Qa,na({key:"label-implicit",content:e},n)):Fg(e)?b.createElement(Qa,na({key:"label-implicit",content:e},n)):e&&typeof e=="object"?b.createElement(Qa,na({},e,{key:"label-implicit"},n)):null};function VU(e){var{label:t,labelRef:r}=e,n=a4();return GU(t,n,r)||null}var $v={},Bv={},DN;function XU(){return DN||(DN=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return r[r.length-1]}e.last=t})(Bv)),Bv}var qv={},PN;function FU(){return PN||(PN=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return Array.isArray(r)?r:Array.from(r)}e.toArray=t})(qv)),qv}var zN;function ZU(){return zN||(zN=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=XU(),r=FU(),n=_0();function l(s){if(n.isArrayLike(s))return t.last(r.toArray(s))}e.last=l})($v)),$v}var Uv,RN;function QU(){return RN||(RN=1,Uv=ZU().last),Uv}var WU=QU();const JU=kn(WU);var eH=["valueAccessor"],tH=["dataKey","clockWise","id","textBreakAll","zIndex"];function Xf(){return Xf=Object.assign?Object.assign.bind():function(e){for(var t=1;tArray.isArray(e.value)?JU(e.value):e.value,i4=b.createContext(void 0),l4=i4.Provider,o4=b.createContext(void 0),aH=o4.Provider;function iH(){return b.useContext(i4)}function lH(){return b.useContext(o4)}function nf(e){var{valueAccessor:t=nH}=e,r=LN(e,eH),{dataKey:n,clockWise:l,id:s,textBreakAll:c,zIndex:d}=r,h=LN(r,tH),m=iH(),p=lH(),y=m||p;return!y||!y.length?null:b.createElement(_r,{zIndex:d??Ct.label},b.createElement(_t,{className:"recharts-label-list"},y.map((x,w)=>{var j,_=xt(n)?t(x,w):We(x.payload,n),N=xt(s)?{}:{id:"".concat(s,"-").concat(w)};return b.createElement(Qa,Xf({key:"label-".concat(w)},ur(x),h,N,{fill:(j=r.fill)!==null&&j!==void 0?j:x.fill,parentViewBox:x.parentViewBox,value:_,textBreakAll:c,viewBox:x.viewBox,index:w,zIndex:0}))})))}nf.displayName="LabelList";function Zg(e){var{label:t}=e;return t?t===!0?b.createElement(nf,{key:"labelList-implicit"}):b.isValidElement(t)||Fg(t)?b.createElement(nf,{key:"labelList-implicit",content:t}):typeof t=="object"?b.createElement(nf,Xf({key:"labelList-implicit"},t,{type:String(t.type)})):null:null}function Zy(){return Zy=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var{cx:t,cy:r,r:n,className:l}=e,s=Ue("recharts-dot",l);return de(t)&&de(r)&&de(n)?b.createElement("circle",Zy({},wr(e),j0(e),{className:s,cx:t,cy:r,r:n})):null},u4=e=>e.graphicalItems.polarItems,oH=Y([dt,ou],gg),Xd=Y([u4,bt,oH],xg),sH=Y([Xd],bg),Fd=Y([sH,Dd],wg),uH=Y([Fd,bt,Xd],_g);Y([Fd,bt,Xd],(e,t,r)=>r.length>0?e.flatMap(n=>r.flatMap(l=>{var s,c=We(n,(s=t.dataKey)!==null&&s!==void 0?s:l.dataKey);return{value:c,errorDomain:[]}})).filter(Boolean):(t==null?void 0:t.dataKey)!=null?e.map(n=>({value:We(n,t.dataKey),errorDomain:[]})):e.map(n=>({value:n,errorDomain:[]})));var IN=()=>{},cH=Y([Fd,bt,Xd,Hd,dt],Ag),fH=Y([bt,Ng,Og,IN,cH,IN,$e,dt],Eg),c4=Y([bt,$e,Fd,uH,lu,dt,fH],Cg),dH=Y([c4,vo,ci],Tg),hH=Y([bt,c4,dH,dt],Pg);Y([ci,hH],XC);var mH={radiusAxis:{},angleAxis:{}},f4=jr({name:"polarAxis",initialState:mH,reducers:{addRadiusAxis(e,t){e.radiusAxis[t.payload.id]=t.payload},removeRadiusAxis(e,t){delete e.radiusAxis[t.payload.id]},addAngleAxis(e,t){e.angleAxis[t.payload.id]=t.payload},removeAngleAxis(e,t){delete e.angleAxis[t.payload.id]}}}),{addRadiusAxis:MF,removeRadiusAxis:TF,addAngleAxis:DF,removeAngleAxis:PF}=f4.actions,pH=f4.reducer;function d4(e){return e&&typeof e=="object"&&"className"in e&&typeof e.className=="string"?e.className:""}function $N(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function BN(e){for(var t=1;tt,Qg=Y([u4,xH],(e,t)=>e.filter(r=>r.type==="pie").find(r=>r.id===t)),bH=[],Wg=(e,t,r)=>(r==null?void 0:r.length)===0?bH:r,h4=Y([Dd,Qg,Wg],(e,t,r)=>{var{chartData:n}=e;if(t!=null){var l;if((t==null?void 0:t.data)!=null&&t.data.length>0?l=t.data:l=n,(!l||!l.length)&&r!=null&&(l=r.map(s=>BN(BN({},t.presentationProps),s.props))),l!=null)return l}}),wH=Y([h4,Qg,Wg],(e,t,r)=>{if(!(e==null||t==null))return e.map((n,l)=>{var s,c=We(n,t.nameKey,t.name),d;return r!=null&&(s=r[l])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?d=r[l].props.fill:typeof n=="object"&&n!=null&&"fill"in n?d=n.fill:d=t.fill,{value:co(c,t.dataKey),color:d,payload:n,type:t.legendType}})}),jH=Y([h4,Qg,Wg,zt],(e,t,r,n)=>{if(!(t==null||e==null))return _K({offset:n,pieSettings:t,displayedData:e,cells:r})}),Hv={exports:{}},Qe={};/** + * @license React + * react-is.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var qN;function _H(){if(qN)return Qe;qN=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),x=Symbol.for("react.view_transition"),w=Symbol.for("react.client.reference");function j(_){if(typeof _=="object"&&_!==null){var N=_.$$typeof;switch(N){case e:switch(_=_.type,_){case r:case l:case n:case h:case m:case x:return _;default:switch(_=_&&_.$$typeof,_){case c:case d:case y:case p:return _;case s:return _;default:return N}}case t:return N}}}return Qe.ContextConsumer=s,Qe.ContextProvider=c,Qe.Element=e,Qe.ForwardRef=d,Qe.Fragment=r,Qe.Lazy=y,Qe.Memo=p,Qe.Portal=t,Qe.Profiler=l,Qe.StrictMode=n,Qe.Suspense=h,Qe.SuspenseList=m,Qe.isContextConsumer=function(_){return j(_)===s},Qe.isContextProvider=function(_){return j(_)===c},Qe.isElement=function(_){return typeof _=="object"&&_!==null&&_.$$typeof===e},Qe.isForwardRef=function(_){return j(_)===d},Qe.isFragment=function(_){return j(_)===r},Qe.isLazy=function(_){return j(_)===y},Qe.isMemo=function(_){return j(_)===p},Qe.isPortal=function(_){return j(_)===t},Qe.isProfiler=function(_){return j(_)===l},Qe.isStrictMode=function(_){return j(_)===n},Qe.isSuspense=function(_){return j(_)===h},Qe.isSuspenseList=function(_){return j(_)===m},Qe.isValidElementType=function(_){return typeof _=="string"||typeof _=="function"||_===r||_===l||_===n||_===h||_===m||typeof _=="object"&&_!==null&&(_.$$typeof===y||_.$$typeof===p||_.$$typeof===c||_.$$typeof===s||_.$$typeof===d||_.$$typeof===w||_.getModuleId!==void 0)},Qe.typeOf=j,Qe}var UN;function SH(){return UN||(UN=1,Hv.exports=_H()),Hv.exports}var NH=SH(),HN=e=>typeof e=="string"?e:e?e.displayName||e.name||"Component":"",KN=null,Kv=null,m4=e=>{if(e===KN&&Array.isArray(Kv))return Kv;var t=[];return b.Children.forEach(e,r=>{xt(r)||(NH.isFragment(r)?t=t.concat(m4(r.props.children)):t.push(r))}),Kv=t,KN=e,t};function Jg(e,t){var r=[],n=[];return Array.isArray(t)?n=t.map(l=>HN(l)):n=[HN(t)],m4(e).forEach(l=>{var s=Gi(l,"type.displayName")||Gi(l,"type.name");s&&n.indexOf(s)!==-1&&r.push(l)}),r}var p4=e=>e&&typeof e=="object"&&"clipDot"in e?!!e.clipDot:!0,Yv={},YN;function OH(){return YN||(YN=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){var l;if(typeof r!="object"||r==null)return!1;if(Object.getPrototypeOf(r)===null)return!0;if(Object.prototype.toString.call(r)!=="[object Object]"){const s=r[Symbol.toStringTag];return s==null||!((l=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag))!=null&&l.writable)?!1:r.toString()===`[object ${s}]`}let n=r;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(r)===n}e.isPlainObject=t})(Yv)),Yv}var Gv,GN;function AH(){return GN||(GN=1,Gv=OH().isPlainObject),Gv}var EH=AH();const CH=kn(EH);var VN,XN,FN,ZN,QN;function WN(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function JN(e){for(var t=1;t{var s=r-n,c;return c=yt(VN||(VN=Ss(["M ",",",""])),e,t),c+=yt(XN||(XN=Ss(["L ",",",""])),e+r,t),c+=yt(FN||(FN=Ss(["L ",",",""])),e+r-s/2,t+l),c+=yt(ZN||(ZN=Ss(["L ",",",""])),e+r-s/2-n,t+l),c+=yt(QN||(QN=Ss(["L ",","," Z"])),e,t),c},DH={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},PH=e=>{var t=Mt(e,DH),{x:r,y:n,upperWidth:l,lowerWidth:s,height:c,className:d}=t,{animationEasing:h,animationDuration:m,animationBegin:p,isUpdateAnimationActive:y}=t,x=b.useRef(null),[w,j]=b.useState(-1),_=b.useRef(l),N=b.useRef(s),A=b.useRef(c),O=b.useRef(r),P=b.useRef(n),k=tu(e,"trapezoid-");if(b.useEffect(()=>{if(x.current&&x.current.getTotalLength)try{var ce=x.current.getTotalLength();ce&&j(ce)}catch{}},[]),r!==+r||n!==+n||l!==+l||s!==+s||c!==+c||l===0&&s===0||c===0)return null;var z=Ue("recharts-trapezoid",d);if(!y)return b.createElement("g",null,b.createElement("path",Ff({},ur(t),{className:z,d:eO(r,n,l,s,c)})));var T=_.current,R=N.current,$=A.current,Z=O.current,X=P.current,L="0px ".concat(w===-1?1:w,"px"),K="".concat(w,"px 0px"),se=RE(["strokeDasharray"],m,h);return b.createElement(eu,{animationId:k,key:k,canBegin:w>0,duration:m,easing:h,isActive:y,begin:p},ce=>{var he=lt(T,l,ce),q=lt(R,s,ce),W=lt($,c,ce),ue=lt(Z,r,ce),te=lt(X,n,ce);x.current&&(_.current=he,N.current=q,A.current=W,O.current=ue,P.current=te);var M=ce>0?{transition:se,strokeDasharray:K}:{strokeDasharray:L};return b.createElement("path",Ff({},ur(t),{className:z,d:eO(ue,te,he,q,W),ref:x,style:JN(JN({},M),t.style)}))})},zH=["option","shapeType","activeClassName"];function RH(e,t){if(e==null)return{};var r,n,l=LH(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n{var n=rt();return(l,s)=>c=>{e==null||e(l,s,c),n(S3({activeIndex:String(s),activeDataKey:t,activeCoordinate:l.tooltipPosition,activeGraphicalItemId:r}))}},tx=e=>{var t=rt();return(r,n)=>l=>{e==null||e(r,n,l),t(G$())}},rx=(e,t,r)=>{var n=rt();return(l,s)=>c=>{e==null||e(l,s,c),n(V$({activeIndex:String(s),activeDataKey:t,activeCoordinate:l.tooltipPosition,activeGraphicalItemId:r}))}};function nx(e){var{tooltipEntrySettings:t}=e,r=rt(),n=ir(),l=b.useRef(null);return b.useLayoutEffect(()=>{n||(l.current===null?r(U$(t)):l.current!==t&&r(H$({prev:l.current,next:t})),l.current=t)},[t,r,n]),b.useLayoutEffect(()=>()=>{l.current&&(r(K$(l.current)),l.current=null)},[r]),null}function y4(e){var{legendPayload:t}=e,r=rt(),n=ir(),l=b.useRef(null);return b.useLayoutEffect(()=>{n||(l.current===null?r(ME(t)):l.current!==t&&r(TE({prev:l.current,next:t})),l.current=t)},[r,n,t]),b.useLayoutEffect(()=>()=>{l.current&&(r(DE(l.current)),l.current=null)},[r]),null}function KH(e){var{legendPayload:t}=e,r=rt(),n=ge($e),l=b.useRef(null);return b.useLayoutEffect(()=>{n!=="centric"&&n!=="radial"||(l.current===null?r(ME(t)):l.current!==t&&r(TE({prev:l.current,next:t})),l.current=t)},[r,n,t]),b.useLayoutEffect(()=>()=>{l.current&&(r(DE(l.current)),l.current=null)},[r]),null}var Vv,YH=()=>{var[e]=b.useState(()=>Ms("uid-"));return e},GH=(Vv=EM.useId)!==null&&Vv!==void 0?Vv:YH;function VH(e,t){var r=GH();return t||(e?"".concat(e,"-").concat(r):r)}var XH=b.createContext(void 0),ax=e=>{var{id:t,type:r,children:n}=e,l=VH("recharts-".concat(r),t);return b.createElement(XH.Provider,{value:l},n(l))},FH={cartesianItems:[],polarItems:[]},g4=jr({name:"graphicalItems",initialState:FH,reducers:{addCartesianGraphicalItem:{reducer(e,t){e.cartesianItems.push(t.payload)},prepare:st()},replaceCartesianGraphicalItem:{reducer(e,t){var{prev:r,next:n}=t.payload,l=fn(e).cartesianItems.indexOf(r);l>-1&&(e.cartesianItems[l]=n)},prepare:st()},removeCartesianGraphicalItem:{reducer(e,t){var r=fn(e).cartesianItems.indexOf(t.payload);r>-1&&e.cartesianItems.splice(r,1)},prepare:st()},addPolarGraphicalItem:{reducer(e,t){e.polarItems.push(t.payload)},prepare:st()},removePolarGraphicalItem:{reducer(e,t){var r=fn(e).polarItems.indexOf(t.payload);r>-1&&e.polarItems.splice(r,1)},prepare:st()}}}),{addCartesianGraphicalItem:ZH,replaceCartesianGraphicalItem:QH,removeCartesianGraphicalItem:WH,addPolarGraphicalItem:JH,removePolarGraphicalItem:eK}=g4.actions,tK=g4.reducer,rK=e=>{var t=rt(),r=b.useRef(null);return b.useLayoutEffect(()=>{r.current===null?t(ZH(e)):r.current!==e&&t(QH({prev:r.current,next:e})),r.current=e},[t,e]),b.useLayoutEffect(()=>()=>{r.current&&(t(WH(r.current)),r.current=null)},[t]),null},x4=b.memo(rK);function nK(e){var t=rt();return b.useLayoutEffect(()=>(t(JH(e)),()=>{t(eK(e))}),[t,e]),null}var aK=["key"],iK=["onMouseEnter","onClick","onMouseLeave"],lK=["id"],oK=["id"];function nO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function gt(e){for(var t=1;tJg(e.children,qi),[e.children]),r=ge(n=>wH(n,e.id,t));return r==null?null:b.createElement(KH,{legendPayload:r})}var hK=b.memo(e=>{var{dataKey:t,nameKey:r,sectors:n,stroke:l,strokeWidth:s,fill:c,name:d,hide:h,tooltipType:m,id:p}=e,y={dataDefinedOnItem:n.map(x=>x.tooltipPayload),getPosition:x=>{var w;return(w=n[Number(x)])===null||w===void 0?void 0:w.tooltipPosition},settings:{stroke:l,strokeWidth:s,fill:c,dataKey:t,nameKey:r,name:co(d,t),hide:h,type:m,color:c,unit:"",graphicalItemId:p}};return b.createElement(nx,{tooltipEntrySettings:y})}),mK=(e,t)=>e>t?"start":enr(typeof t=="function"?t(e):t,r,r*.8),vK=(e,t,r)=>{var{top:n,left:l,width:s,height:c}=t,d=qE(s,c),h=l+nr(e.cx,s,s/2),m=n+nr(e.cy,c,c/2),p=nr(e.innerRadius,d,0),y=pK(r,e.outerRadius,d),x=e.maxRadius||Math.sqrt(s*s+c*c)/2;return{cx:h,cy:m,innerRadius:p,outerRadius:y,maxRadius:x}},yK=(e,t)=>{var r=Ht(t-e),n=Math.min(Math.abs(t-e),360);return r*n},gK=(e,t)=>{if(b.isValidElement(e))return b.cloneElement(e,t);if(typeof e=="function")return e(t);var r=Ue("recharts-pie-label-line",typeof e!="boolean"?e.className:""),{key:n}=t,l=Zd(t,aK);return b.createElement(Jl,oi({},l,{type:"linear",className:r}))},xK=(e,t,r)=>{if(b.isValidElement(e))return b.cloneElement(e,t);var n=r;if(typeof e=="function"&&(n=e(t),b.isValidElement(n)))return n;var l=Ue("recharts-pie-label-text",d4(e));return b.createElement(Vd,oi({},t,{alignmentBaseline:"middle",className:l}),n)};function bK(e){var{sectors:t,props:r,showLabels:n}=e,{label:l,labelLine:s,dataKey:c}=r;if(!n||!l||!t)return null;var d=wr(r),h=Ki(l),m=Ki(s),p=typeof l=="object"&&"offsetRadius"in l&&typeof l.offsetRadius=="number"&&l.offsetRadius||20,y=t.map((x,w)=>{var j=(x.startAngle+x.endAngle)/2,_=Et(x.cx,x.cy,x.outerRadius+p,j),N=gt(gt(gt(gt({},d),x),{},{stroke:"none"},h),{},{index:w,textAnchor:mK(_.x,x.cx)},_),A=gt(gt(gt(gt({},d),x),{},{fill:"none",stroke:x.fill},m),{},{index:w,points:[Et(x.cx,x.cy,x.outerRadius,j),_],key:"line"});return b.createElement(_r,{zIndex:Ct.label,key:"label-".concat(x.startAngle,"-").concat(x.endAngle,"-").concat(x.midAngle,"-").concat(w)},b.createElement(_t,null,s&&gK(s,A),xK(l,N,We(x,c))))});return b.createElement(_t,{className:"recharts-pie-labels"},y)}function wK(e){var{sectors:t,props:r,showLabels:n}=e,{label:l}=r;return typeof l=="object"&&l!=null&&"position"in l?b.createElement(Zg,{label:l}):b.createElement(bK,{sectors:t,props:r,showLabels:n})}function jK(e){var{sectors:t,activeShape:r,inactiveShape:n,allOtherPieProps:l,shape:s,id:c}=e,d=ge(li),h=ge(Hg),m=ge(TB),{onMouseEnter:p,onClick:y,onMouseLeave:x}=l,w=Zd(l,iK),j=ex(p,l.dataKey,c),_=tx(x),N=rx(y,l.dataKey,c);return t==null||t.length===0?null:b.createElement(b.Fragment,null,t.map((A,O)=>{if((A==null?void 0:A.startAngle)===0&&(A==null?void 0:A.endAngle)===0&&t.length!==1)return null;var P=m==null||m===c,k=String(O)===d&&(h==null||l.dataKey===h)&&P,z=d?n:null,T=r&&k?r:z,R=gt(gt({},A),{},{stroke:A.stroke,tabIndex:-1,[yE]:O,[gE]:c});return b.createElement(_t,oi({key:"sector-".concat(A==null?void 0:A.startAngle,"-").concat(A==null?void 0:A.endAngle,"-").concat(A.midAngle,"-").concat(O),tabIndex:-1,className:"recharts-pie-sector"},Vs(w,A,O),{onMouseEnter:j(A,O),onMouseLeave:_(A,O),onClick:N(A,O)}),b.createElement(v4,oi({option:s??T,index:O,shapeType:"sector",isActive:k},R)))}))}function _K(e){var t,{pieSettings:r,displayedData:n,cells:l,offset:s}=e,{cornerRadius:c,startAngle:d,endAngle:h,dataKey:m,nameKey:p,tooltipType:y}=r,x=Math.abs(r.minAngle),w=yK(d,h),j=Math.abs(w),_=n.length<=1?0:(t=r.paddingAngle)!==null&&t!==void 0?t:0,N=n.filter(T=>We(T,m,0)!==0).length,A=(j>=360?N:N-1)*_,O=j-N*x-A,P=n.reduce((T,R)=>{var $=We(R,m,0);return T+(de($)?$:0)},0),k;if(P>0){var z;k=n.map((T,R)=>{var $=We(T,m,0),Z=We(T,p,R),X=vK(r,s,T),L=(de($)?$:0)/P,K,se=gt(gt({},T),l&&l[R]&&l[R].props);R?K=z.endAngle+Ht(w)*_*($!==0?1:0):K=d;var ce=K+Ht(w)*(($!==0?x:0)+L*O),he=(K+ce)/2,q=(X.innerRadius+X.outerRadius)/2,W=[{name:Z,value:$,payload:se,dataKey:m,type:y,graphicalItemId:r.id}],ue=Et(X.cx,X.cy,q,he);return z=gt(gt(gt(gt({},r.presentationProps),{},{percent:L,cornerRadius:typeof c=="string"?parseFloat(c):c,name:Z,tooltipPayload:W,midAngle:he,middleRadius:q,tooltipPosition:ue},se),X),{},{value:$,dataKey:m,startAngle:K,endAngle:ce,payload:se,paddingAngle:Ht(w)*_}),z})}return k}function SK(e){var{showLabels:t,sectors:r,children:n}=e,l=b.useMemo(()=>!t||!r?[]:r.map(s=>({value:s.value,payload:s.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:s.cx,cy:s.cy,innerRadius:s.innerRadius,outerRadius:s.outerRadius,startAngle:s.startAngle,endAngle:s.endAngle,clockWise:!1},fill:s.fill})),[r,t]);return b.createElement(aH,{value:t?l:void 0},n)}function NK(e){var{props:t,previousSectorsRef:r,id:n}=e,{sectors:l,isAnimationActive:s,animationBegin:c,animationDuration:d,animationEasing:h,activeShape:m,inactiveShape:p,onAnimationStart:y,onAnimationEnd:x}=t,w=tu(t,"recharts-pie-"),j=r.current,[_,N]=b.useState(!1),A=b.useCallback(()=>{typeof x=="function"&&x(),N(!1)},[x]),O=b.useCallback(()=>{typeof y=="function"&&y(),N(!0)},[y]);return b.createElement(SK,{showLabels:!_,sectors:l},b.createElement(eu,{animationId:w,begin:c,duration:d,isActive:s,easing:h,onAnimationStart:O,onAnimationEnd:A,key:w},P=>{var k,z=[],T=l&&l[0],R=(k=T==null?void 0:T.startAngle)!==null&&k!==void 0?k:0;return l==null||l.forEach(($,Z)=>{var X=j&&j[Z],L=Z>0?Gi($,"paddingAngle",0):0;if(X){var K=lt(X.endAngle-X.startAngle,$.endAngle-$.startAngle,P),se=gt(gt({},$),{},{startAngle:R+L,endAngle:R+K+L});z.push(se),R=se.endAngle}else{var{endAngle:ce,startAngle:he}=$,q=lt(0,ce-he,P),W=gt(gt({},$),{},{startAngle:R+L,endAngle:R+q+L});z.push(W),R=W.endAngle}}),r.current=z,b.createElement(_t,null,b.createElement(jK,{sectors:z,activeShape:m,inactiveShape:p,allOtherPieProps:t,shape:t.shape,id:n}))}),b.createElement(wK,{showLabels:!_,sectors:l,props:t}),t.children)}var OK={animationBegin:400,animationDuration:1500,animationEasing:"ease",cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,startAngle:0,stroke:"#fff",zIndex:Ct.area};function AK(e){var{id:t}=e,r=Zd(e,lK),{hide:n,className:l,rootTabIndex:s}=e,c=b.useMemo(()=>Jg(e.children,qi),[e.children]),d=ge(p=>jH(p,t,c)),h=b.useRef(null),m=Ue("recharts-pie",l);return n||d==null?(h.current=null,b.createElement(_t,{tabIndex:s,className:m})):b.createElement(_r,{zIndex:e.zIndex},b.createElement(hK,{dataKey:e.dataKey,nameKey:e.nameKey,sectors:d,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,tooltipType:e.tooltipType,id:t}),b.createElement(_t,{tabIndex:s,className:m},b.createElement(NK,{props:gt(gt({},r),{},{sectors:d}),previousSectorsRef:h,id:t})))}function Qy(e){var t=Mt(e,OK),{id:r}=t,n=Zd(t,oK),l=wr(n);return b.createElement(ax,{id:r,type:"pie"},s=>b.createElement(b.Fragment,null,b.createElement(nK,{type:"pie",id:s,data:n.data,dataKey:n.dataKey,hide:n.hide,angleAxisId:0,radiusAxisId:0,name:n.name,nameKey:n.nameKey,tooltipType:n.tooltipType,legendType:n.legendType,fill:n.fill,cx:n.cx,cy:n.cy,startAngle:n.startAngle,endAngle:n.endAngle,paddingAngle:n.paddingAngle,minAngle:n.minAngle,innerRadius:n.innerRadius,outerRadius:n.outerRadius,cornerRadius:n.cornerRadius,presentationProps:l,maxRadius:t.maxRadius}),b.createElement(dK,oi({},n,{id:s})),b.createElement(AK,oi({},n,{id:s}))))}Qy.displayName="Pie";var EK=["points"];function aO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Xv(e){for(var t=1;t{var N,A,O=Xv(Xv(Xv({r:3},c),y),{},{index:_,cx:(N=j.x)!==null&&N!==void 0?N:void 0,cy:(A=j.y)!==null&&A!==void 0?A:void 0,dataKey:s,value:j.value,payload:j.payload,points:t});return b.createElement(PK,{key:"dot-".concat(_),option:r,dotProps:O,className:l})}),w={};return d&&h!=null&&(w.clipPath="url(#clipPath-".concat(p?"":"dots-").concat(h,")")),b.createElement(_r,{zIndex:m},b.createElement(_t,Qf({className:n},w),x))}function iO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function lO(e){for(var t=1;t({top:e.top,bottom:e.bottom,left:e.left,right:e.right})),ZK=Y([FK,ya,ga],(e,t,r)=>{if(!(!e||t==null||r==null))return{x:e.left,y:e.top,width:Math.max(0,t-e.left-e.right),height:Math.max(0,r-e.top-e.bottom)}}),ix=()=>ge(ZK),QK=()=>ge(LB);function oO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Fv(e){for(var t=1;t{var{point:t,childIndex:r,mainColor:n,activeDot:l,dataKey:s,clipPath:c}=e;if(l===!1||t.x==null||t.y==null)return null;var d={index:r,dataKey:s,cx:t.x,cy:t.y,r:4,fill:n??"none",strokeWidth:2,stroke:"#fff",payload:t.payload,value:t.value},h=Fv(Fv(Fv({},d),Ki(l)),j0(l)),m;return b.isValidElement(l)?m=b.cloneElement(l,h):typeof l=="function"?m=l(h):m=b.createElement(s4,h),b.createElement(_t,{className:"recharts-active-dot",clipPath:c},m)};function sO(e){var{points:t,mainColor:r,activeDot:n,itemDataKey:l,clipPath:s,zIndex:c=Ct.activeDot}=e,d=ge(li),h=QK();if(t==null||h==null)return null;var m=t.find(p=>h.includes(p.payload));return xt(m)?null:b.createElement(_r,{zIndex:c},b.createElement(tY,{point:m,childIndex:Number(d),mainColor:r,dataKey:l,activeDot:n,clipPath:s}))}var uO=(e,t,r)=>{var n=r??e;if(!xt(n))return nr(n,t,0)},rY=(e,t,r)=>{var n={},l=e.filter(Id),s=e.filter(m=>m.stackId==null),c=l.reduce((m,p)=>{var y=m[p.stackId];return y==null&&(y=[]),y.push(p),m[p.stackId]=y,m},n),d=Object.entries(c).map(m=>{var p,[y,x]=m,w=x.map(_=>_.dataKey),j=uO(t,r,(p=x[0])===null||p===void 0?void 0:p.barSize);return{stackId:y,dataKeys:w,barSize:j}}),h=s.map(m=>{var p=[m.dataKey].filter(x=>x!=null),y=uO(t,r,m.barSize);return{stackId:void 0,dataKeys:p,barSize:y}});return[...d,...h]};function cO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function Vc(e){for(var t=1;tO+(P.barSize||0),0);x+=(c-1)*d,x>=r&&(x-=(c-1)*d,d=0),x>=r&&y>0&&(p=!0,y*=.9,x=c*y);var w=(r-x)/2>>0,j={offset:w-d,size:0};h=n.reduce((O,P)=>{var k,z={stackId:P.stackId,dataKeys:P.dataKeys,position:{offset:j.offset+j.size+d,size:p?y:(k=P.barSize)!==null&&k!==void 0?k:0}},T=[...O,z];return j=z.position,T},m)}else{var _=nr(t,r,0,!0);r-2*_-(c-1)*d<=0&&(d=0);var N=(r-2*_-(c-1)*d)/c;N>1&&(N>>=0);var A=ke(l)?Math.min(N,l):N;h=n.reduce((O,P,k)=>[...O,{stackId:P.stackId,dataKeys:P.dataKeys,position:{offset:_+(N+d)*k+(N-A)/2,size:A}}],m)}return h}}var oY=(e,t,r,n,l,s,c)=>{var d=xt(c)?t:c,h=lY(r,n,l!==s?l:s,e,d);return l!==s&&h!=null&&(h=h.map(m=>Vc(Vc({},m),{},{position:Vc(Vc({},m.position),{},{offset:m.position.offset-l/2})}))),h},sY=(e,t)=>{var r=Ld(t);if(!(!e||r==null||t==null)){var{stackId:n}=t;if(n!=null){var l=e[n];if(l){var{stackedData:s}=l;if(s)return s.find(c=>c.key===r)}}}},uY=(e,t)=>{if(!(e==null||t==null)){var r=e.find(n=>n.stackId===t.stackId&&t.dataKey!=null&&n.dataKeys.includes(t.dataKey));if(r!=null)return r.position}};function cY(e,t){return e&&typeof e=="object"&&"zIndex"in e&&typeof e.zIndex=="number"&&ke(e.zIndex)?e.zIndex:t}var j4=e=>{var{chartData:t}=e,r=rt(),n=ir();return b.useEffect(()=>n?()=>{}:(r(pN(t)),()=>{r(pN(void 0))}),[t,r,n]),null},fO={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},_4=jr({name:"brush",initialState:fO,reducers:{setBrushSettings(e,t){return t.payload==null?fO:t.payload}}}),{setBrushSettings:IF}=_4.actions,fY=_4.reducer;function dY(e){return(e%180+180)%180}var hY=function(t){var{width:r,height:n}=t,l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=dY(l),c=s*Math.PI/180,d=Math.atan(n/r),h=c>d&&c{e.dots.push(t.payload)},removeDot:(e,t)=>{var r=fn(e).dots.findIndex(n=>n===t.payload);r!==-1&&e.dots.splice(r,1)},addArea:(e,t)=>{e.areas.push(t.payload)},removeArea:(e,t)=>{var r=fn(e).areas.findIndex(n=>n===t.payload);r!==-1&&e.areas.splice(r,1)},addLine:(e,t)=>{e.lines.push(t.payload)},removeLine:(e,t)=>{var r=fn(e).lines.findIndex(n=>n===t.payload);r!==-1&&e.lines.splice(r,1)}}}),{addDot:$F,removeDot:BF,addArea:qF,removeArea:UF,addLine:HF,removeLine:KF}=S4.actions,pY=S4.reducer,vY=b.createContext(void 0),yY=e=>{var{children:t}=e,[r]=b.useState("".concat(Ms("recharts"),"-clip")),n=ix();if(n==null)return null;var{x:l,y:s,width:c,height:d}=n;return b.createElement(vY.Provider,{value:r},b.createElement("defs",null,b.createElement("clipPath",{id:r},b.createElement("rect",{x:l,y:s,height:d,width:c}))),t)};function N4(e,t){if(t<1)return[];if(t===1)return e;for(var r=[],n=0;ne*l)return!1;var s=r();return e*(t-e*s/2-n)>=0&&e*(t+e*s/2-l)<=0}function bY(e,t){return N4(e,t+1)}function wY(e,t,r,n,l){for(var s=(n||[]).slice(),{start:c,end:d}=t,h=0,m=1,p=c,y=function(){var j=n==null?void 0:n[h];if(j===void 0)return{v:N4(n,m)};var _=h,N,A=()=>(N===void 0&&(N=r(j,_)),N),O=j.coordinate,P=h===0||Ys(e,O,A,p,d);P||(h=0,p=c,m+=1),P&&(p=O+e*(A()/2+l),h+=m)},x;m<=s.length;)if(x=y(),x)return x.v;return[]}function jY(e,t,r,n,l){var s=(n||[]).slice(),c=s.length;if(c===0)return[];for(var{start:d,end:h}=t,m=1;m<=c;m++){for(var p=(c-1)%m,y=d,x=!0,w=function(){var k=n[_];if(k==null)return 0;var z=_,T,R=()=>(T===void 0&&(T=r(k,z)),T),$=k.coordinate,Z=_===p||Ys(e,$,R,y,h);if(!Z)return x=!1,1;Z&&(y=$+e*(R()/2+l))},j,_=p;_(_===void 0&&(_=r(w,x)),_);if(x===c-1){var A=e*(j.coordinate+e*N()/2-h);s[x]=j=tr(tr({},j),{},{tickCoord:A>0?j.coordinate-A*e:j.coordinate})}else s[x]=j=tr(tr({},j),{},{tickCoord:j.coordinate});if(j.tickCoord!=null){var O=Ys(e,j.tickCoord,N,d,h);O&&(h=j.tickCoord-e*(N()/2+l),s[x]=tr(tr({},j),{},{isShow:!0}))}},p=c-1;p>=0;p--)m(p);return s}function AY(e,t,r,n,l,s){var c=(n||[]).slice(),d=c.length,{start:h,end:m}=t;if(s){var p=n[d-1];if(p!=null){var y=r(p,d-1),x=e*(p.coordinate+e*y/2-m);if(c[d-1]=p=tr(tr({},p),{},{tickCoord:x>0?p.coordinate-x*e:p.coordinate}),p.tickCoord!=null){var w=Ys(e,p.tickCoord,()=>y,h,m);w&&(m=p.tickCoord-e*(y/2+l),c[d-1]=tr(tr({},p),{},{isShow:!0}))}}}for(var j=s?d-1:d,_=function(O){var P=c[O];if(P==null)return 1;var k=P,z,T=()=>(z===void 0&&(z=r(P,O)),z);if(O===0){var R=e*(k.coordinate-e*T()/2-h);c[O]=k=tr(tr({},k),{},{tickCoord:R<0?k.coordinate-R*e:k.coordinate})}else c[O]=k=tr(tr({},k),{},{tickCoord:k.coordinate});if(k.tickCoord!=null){var $=Ys(e,k.tickCoord,T,h,m);$&&(h=k.tickCoord+e*(T()/2+l),c[O]=tr(tr({},k),{},{isShow:!0}))}},N=0;N{var R=typeof m=="function"?m(z.value,T):z.value;return j==="width"?gY(ks(R,{fontSize:t,letterSpacing:r}),_,y):ks(R,{fontSize:t,letterSpacing:r})[j]},A=l[0],O=l[1],P=l.length>=2&&A!=null&&O!=null?Ht(O.coordinate-A.coordinate):1,k=xY(s,P,j);return h==="equidistantPreserveStart"?wY(P,k,N,l,c):h==="equidistantPreserveEnd"?jY(P,k,N,l,c):(h==="preserveStart"||h==="preserveStartEnd"?w=AY(P,k,N,l,c,h==="preserveStartEnd"):w=OY(P,k,N,l,c),w.filter(z=>z.isShow))}var EY=e=>{var{ticks:t,label:r,labelGapWithTick:n=5,tickSize:l=0,tickMargin:s=0}=e,c=0;if(t){Array.from(t).forEach(p=>{if(p){var y=p.getBoundingClientRect();y.width>c&&(c=y.width)}});var d=r?r.getBoundingClientRect().width:0,h=l+s,m=c+h+d+(r?n:0);return Math.round(m)}return 0},CY=["axisLine","width","height","className","hide","ticks","axisType"];function kY(e,t){if(e==null)return{};var r,n,l=MY(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n{var{ticks:r=[],tick:n,tickLine:l,stroke:s,tickFormatter:c,unit:d,padding:h,tickTextProps:m,orientation:p,mirror:y,x,y:w,width:j,height:_,tickSize:N,tickMargin:A,fontSize:O,letterSpacing:P,getTicksConfig:k,events:z,axisType:T}=e,R=lx(vt(vt({},k),{},{ticks:r}),O,P),$=LY(p,y),Z=IY(p,y),X=wr(k),L=Ki(n),K={};typeof l=="object"&&(K=l);var se=vt(vt({},X),{},{fill:"none"},K),ce=R.map(W=>vt({entry:W},RY(W,x,w,j,_,p,N,y,A))),he=ce.map(W=>{var{entry:ue,line:te}=W;return b.createElement(_t,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(ue.value,"-").concat(ue.coordinate,"-").concat(ue.tickCoord)},l&&b.createElement("line",Wi({},se,te,{className:Ue("recharts-cartesian-axis-tick-line",Gi(l,"className"))})))}),q=ce.map((W,ue)=>{var te,M,{entry:C,tick:U}=W,ee=vt(vt(vt(vt({verticalAnchor:Z},X),{},{textAnchor:$,stroke:"none",fill:s},U),{},{index:ue,payload:C,visibleTicksCount:R.length,tickFormatter:c,padding:h},m),{},{angle:(te=(M=m==null?void 0:m.angle)!==null&&M!==void 0?M:X.angle)!==null&&te!==void 0?te:0}),le=vt(vt({},ee),L);return b.createElement(_t,Wi({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(C.value,"-").concat(C.coordinate,"-").concat(C.tickCoord)},Vs(z,C,ue)),n&&b.createElement($Y,{option:n,tickProps:le,value:"".concat(typeof c=="function"?c(C.value,ue):C.value).concat(d||"")}))});return b.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(T,"-ticks")},q.length>0&&b.createElement(_r,{zIndex:Ct.label},b.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(T,"-tick-labels"),ref:t},q)),he.length>0&&b.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(T,"-tick-lines")},he))}),qY=b.forwardRef((e,t)=>{var{axisLine:r,width:n,height:l,className:s,hide:c,ticks:d,axisType:h}=e,m=kY(e,CY),[p,y]=b.useState(""),[x,w]=b.useState(""),j=b.useRef(null);b.useImperativeHandle(t,()=>({getCalculatedWidth:()=>{var N;return EY({ticks:j.current,label:(N=e.labelRef)===null||N===void 0?void 0:N.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin})}}));var _=b.useCallback(N=>{if(N){var A=N.getElementsByClassName("recharts-cartesian-axis-tick-value");j.current=A;var O=A[0];if(O){var P=window.getComputedStyle(O),k=P.fontSize,z=P.letterSpacing;(k!==p||z!==x)&&(y(k),w(z))}}},[p,x]);return c||n!=null&&n<=0||l!=null&&l<=0?null:b.createElement(_r,{zIndex:e.zIndex},b.createElement(_t,{className:Ue("recharts-cartesian-axis",s)},b.createElement(zY,{x:e.x,y:e.y,width:n,height:l,orientation:e.orientation,mirror:e.mirror,axisLine:r,otherSvgProps:wr(e)}),b.createElement(BY,{ref:_,axisType:h,events:m,fontSize:p,getTicksConfig:e,height:e.height,letterSpacing:x,mirror:e.mirror,orientation:e.orientation,padding:e.padding,stroke:e.stroke,tick:e.tick,tickFormatter:e.tickFormatter,tickLine:e.tickLine,tickMargin:e.tickMargin,tickSize:e.tickSize,tickTextProps:e.tickTextProps,ticks:d,unit:e.unit,width:e.width,x:e.x,y:e.y}),b.createElement(LU,{x:e.x,y:e.y,width:e.width,height:e.height,lowerWidth:e.width,upperWidth:e.width},b.createElement(VU,{label:e.label,labelRef:e.labelRef}),e.children)))}),ox=b.forwardRef((e,t)=>{var r=Mt(e,ua);return b.createElement(qY,Wi({},r,{ref:t}))});ox.displayName="CartesianAxis";var UY=["x1","y1","x2","y2","key"],HY=["offset"],KY=["xAxisId","yAxisId"],YY=["xAxisId","yAxisId"];function mO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function rr(e){for(var t=1;t{var{fill:t}=e;if(!t||t==="none")return null;var{fillOpacity:r,x:n,y:l,width:s,height:c,ry:d}=e;return b.createElement("rect",{x:n,y:l,ry:d,width:s,height:c,stroke:"none",fill:t,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function O4(e){var{option:t,lineItemProps:r}=e,n;if(b.isValidElement(t))n=b.cloneElement(t,r);else if(typeof t=="function")n=t(r);else{var l,{x1:s,y1:c,x2:d,y2:h,key:m}=r,p=Wf(r,UY),y=(l=wr(p))!==null&&l!==void 0?l:{},{offset:x}=y,w=Wf(y,HY);n=b.createElement("line",Li({},w,{x1:s,y1:c,x2:d,y2:h,fill:"none",key:m}))}return n}function QY(e){var{x:t,width:r,horizontal:n=!0,horizontalPoints:l}=e;if(!n||!l||!l.length)return null;var{xAxisId:s,yAxisId:c}=e,d=Wf(e,KY),h=l.map((m,p)=>{var y=rr(rr({},d),{},{x1:t,y1:m,x2:t+r,y2:m,key:"line-".concat(p),index:p});return b.createElement(O4,{key:"line-".concat(p),option:n,lineItemProps:y})});return b.createElement("g",{className:"recharts-cartesian-grid-horizontal"},h)}function WY(e){var{y:t,height:r,vertical:n=!0,verticalPoints:l}=e;if(!n||!l||!l.length)return null;var{xAxisId:s,yAxisId:c}=e,d=Wf(e,YY),h=l.map((m,p)=>{var y=rr(rr({},d),{},{x1:m,y1:t,x2:m,y2:t+r,key:"line-".concat(p),index:p});return b.createElement(O4,{option:n,lineItemProps:y,key:"line-".concat(p)})});return b.createElement("g",{className:"recharts-cartesian-grid-vertical"},h)}function JY(e){var{horizontalFill:t,fillOpacity:r,x:n,y:l,width:s,height:c,horizontalPoints:d,horizontal:h=!0}=e;if(!h||!t||!t.length||d==null)return null;var m=d.map(y=>Math.round(y+l-l)).sort((y,x)=>y-x);l!==m[0]&&m.unshift(0);var p=m.map((y,x)=>{var w=m[x+1],j=w==null,_=j?l+c-y:w-y;if(_<=0)return null;var N=x%t.length;return b.createElement("rect",{key:"react-".concat(x),y,x:n,height:_,width:s,stroke:"none",fill:t[N],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return b.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},p)}function eG(e){var{vertical:t=!0,verticalFill:r,fillOpacity:n,x:l,y:s,width:c,height:d,verticalPoints:h}=e;if(!t||!r||!r.length)return null;var m=h.map(y=>Math.round(y+l-l)).sort((y,x)=>y-x);l!==m[0]&&m.unshift(0);var p=m.map((y,x)=>{var w=m[x+1],j=w==null,_=j?l+c-y:w-y;if(_<=0)return null;var N=x%r.length;return b.createElement("rect",{key:"react-".concat(x),x:y,y:s,width:_,height:d,stroke:"none",fill:r[N],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return b.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},p)}var tG=(e,t)=>{var{xAxis:r,width:n,height:l,offset:s}=e;return hE(lx(rr(rr(rr({},ua),r),{},{ticks:mE(r),viewBox:{x:0,y:0,width:n,height:l}})),s.left,s.left+s.width,t)},rG=(e,t)=>{var{yAxis:r,width:n,height:l,offset:s}=e;return hE(lx(rr(rr(rr({},ua),r),{},{ticks:mE(r),viewBox:{x:0,y:0,width:n,height:l}})),s.top,s.top+s.height,t)},nG={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:Ct.grid};function Wy(e){var t=z0(),r=R0(),n=jE(),l=rr(rr({},Mt(e,nG)),{},{x:de(e.x)?e.x:n.left,y:de(e.y)?e.y:n.top,width:de(e.width)?e.width:n.width,height:de(e.height)?e.height:n.height}),{xAxisId:s,yAxisId:c,x:d,y:h,width:m,height:p,syncWithTicks:y,horizontalValues:x,verticalValues:w}=l,j=ir(),_=ge(Z=>nN(Z,"xAxis",s,j)),N=ge(Z=>nN(Z,"yAxis",c,j));if(!En(m)||!En(p)||!de(d)||!de(h))return null;var A=l.verticalCoordinatesGenerator||tG,O=l.horizontalCoordinatesGenerator||rG,{horizontalPoints:P,verticalPoints:k}=l;if((!P||!P.length)&&typeof O=="function"){var z=x&&x.length,T=O({yAxis:N?rr(rr({},N),{},{ticks:z?x:N.ticks}):void 0,width:t??m,height:r??p,offset:n},z?!0:y);_f(Array.isArray(T),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof T,"]")),Array.isArray(T)&&(P=T)}if((!k||!k.length)&&typeof A=="function"){var R=w&&w.length,$=A({xAxis:_?rr(rr({},_),{},{ticks:R?w:_.ticks}):void 0,width:t??m,height:r??p,offset:n},R?!0:y);_f(Array.isArray($),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof $,"]")),Array.isArray($)&&(k=$)}return b.createElement(_r,{zIndex:l.zIndex},b.createElement("g",{className:"recharts-cartesian-grid"},b.createElement(ZY,{fill:l.fill,fillOpacity:l.fillOpacity,x:l.x,y:l.y,width:l.width,height:l.height,ry:l.ry}),b.createElement(JY,Li({},l,{horizontalPoints:P})),b.createElement(eG,Li({},l,{verticalPoints:k})),b.createElement(QY,Li({},l,{offset:n,horizontalPoints:P,xAxis:_,yAxis:N})),b.createElement(WY,Li({},l,{offset:n,verticalPoints:k,xAxis:_,yAxis:N}))))}Wy.displayName="CartesianGrid";var aG={},A4=jr({name:"errorBars",initialState:aG,reducers:{addErrorBar:(e,t)=>{var{itemId:r,errorBar:n}=t.payload;e[r]||(e[r]=[]),e[r].push(n)},replaceErrorBar:(e,t)=>{var{itemId:r,prev:n,next:l}=t.payload;e[r]&&(e[r]=e[r].map(s=>s.dataKey===n.dataKey&&s.direction===n.direction?l:s))},removeErrorBar:(e,t)=>{var{itemId:r,errorBar:n}=t.payload;e[r]&&(e[r]=e[r].filter(l=>l.dataKey!==n.dataKey||l.direction!==n.direction))}}}),{addErrorBar:YF,replaceErrorBar:GF,removeErrorBar:VF}=A4.actions,iG=A4.reducer,lG=["children"];function oG(e,t){if(e==null)return{};var r,n,l=sG(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n({x:0,y:0,value:0}),errorBarOffset:0},cG=b.createContext(uG);function fG(e){var{children:t}=e,r=oG(e,lG);return b.createElement(cG.Provider,{value:r},t)}function sx(e,t){var r,n,l=ge(m=>wa(m,e)),s=ge(m=>ja(m,t)),c=(r=l==null?void 0:l.allowDataOverflow)!==null&&r!==void 0?r:Bt.allowDataOverflow,d=(n=s==null?void 0:s.allowDataOverflow)!==null&&n!==void 0?n:qt.allowDataOverflow,h=c||d;return{needClip:h,needClipX:c,needClipY:d}}function E4(e){var{xAxisId:t,yAxisId:r,clipPathId:n}=e,l=ix(),{needClipX:s,needClipY:c,needClip:d}=sx(t,r);if(!d||!l)return null;var{x:h,y:m,width:p,height:y}=l;return b.createElement("clipPath",{id:"clipPath-".concat(n)},b.createElement("rect",{x:s?h:h-p/2,y:c?m:m-y/2,width:s?p:p*2,height:c?y:y*2}))}function dG(e){var t=Ki(e),r=3,n=2;if(t!=null){var{r:l,strokeWidth:s}=t,c=Number(l),d=Number(s);return(Number.isNaN(c)||c<0)&&(c=r),(Number.isNaN(d)||d<0)&&(d=n),{r:c,strokeWidth:d}}return{r,strokeWidth:n}}var Zv={exports:{}},Qv={};/** + * @license React + * use-sync-external-store-with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var pO;function hG(){if(pO)return Qv;pO=1;var e=so();function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,l=e.useRef,s=e.useEffect,c=e.useMemo,d=e.useDebugValue;return Qv.useSyncExternalStoreWithSelector=function(h,m,p,y,x){var w=l(null);if(w.current===null){var j={hasValue:!1,value:null};w.current=j}else j=w.current;w=c(function(){function N(z){if(!A){if(A=!0,O=z,z=y(z),x!==void 0&&j.hasValue){var T=j.value;if(x(T,z))return P=T}return P=z}if(T=P,r(O,z))return T;var R=y(z);return x!==void 0&&x(T,R)?(O=z,T):(O=z,P=R)}var A=!1,O,P,k=p===void 0?null:p;return[function(){return N(m())},k===null?void 0:function(){return N(k())}]},[m,p,y,x]);var _=n(h,w[0],w[1]);return s(function(){j.hasValue=!0,j.value=_},[_]),d(_),_},Qv}var vO;function mG(){return vO||(vO=1,Zv.exports=hG()),Zv.exports}mG();function pG(e){e()}function vG(){let e=null,t=null;return{clear(){e=null,t=null},notify(){pG(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const l=t={callback:r,next:null,prev:t};return l.prev?l.prev.next=l:e=l,function(){!n||e===null||(n=!1,l.next?l.next.prev=l.prev:t=l.prev,l.prev?l.prev.next=l.next:e=l.next)}}}}var yO={notify(){},get:()=>[]};function yG(e,t){let r,n=yO,l=0,s=!1;function c(_){p();const N=n.subscribe(_);let A=!1;return()=>{A||(A=!0,N(),y())}}function d(){n.notify()}function h(){j.onStateChange&&j.onStateChange()}function m(){return s}function p(){l++,r||(r=e.subscribe(h),n=vG())}function y(){l--,r&&l===0&&(r(),r=void 0,n.clear(),n=yO)}function x(){s||(s=!0,p())}function w(){s&&(s=!1,y())}const j={addNestedSub:c,notifyNestedSubs:d,handleChangeWrapper:h,isSubscribed:m,trySubscribe:x,tryUnsubscribe:w,getListeners:()=>n};return j}var gG=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",xG=gG(),bG=()=>typeof navigator<"u"&&navigator.product==="ReactNative",wG=bG(),jG=()=>xG||wG?b.useLayoutEffect:b.useEffect,_G=jG();function gO(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function SG(e,t){if(gO(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let l=0;l{const h=yG(l);return{store:l,subscription:h,getServerState:n?()=>n:void 0}},[l,n]),c=b.useMemo(()=>l.getState(),[l]);_G(()=>{const{subscription:h}=s;return h.onStateChange=h.notifyNestedSubs,h.trySubscribe(),c!==l.getState()&&h.notifyNestedSubs(),()=>{h.tryUnsubscribe(),h.onStateChange=void 0}},[s,c]);const d=r||OG;return b.createElement(d.Provider,{value:s},t)}var EG=AG,CG=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius"]);function kG(e,t){return e==null&&t==null?!0:typeof e=="number"&&typeof t=="number"?e===t||e!==e&&t!==t:e===t}function Qd(e,t){var r=new Set([...Object.keys(e),...Object.keys(t)]);for(var n of r)if(CG.has(n)){if(e[n]==null&&t[n]==null)continue;if(!SG(e[n],t[n]))return!1}else if(!kG(e[n],t[n]))return!1;return!0}function Tn(e,t){var r,n;return(r=(n=e.graphicalItems.cartesianItems.find(l=>l.id===t))===null||n===void 0?void 0:n.xAxisId)!==null&&r!==void 0?r:b4}function Dn(e,t){var r,n;return(r=(n=e.graphicalItems.cartesianItems.find(l=>l.id===t))===null||n===void 0?void 0:n.yAxisId)!==null&&r!==void 0?r:b4}var C4=(e,t,r)=>ii(e,"xAxis",Tn(e,t),r),k4=(e,t,r)=>ai(e,"xAxis",Tn(e,t),r),M4=(e,t,r)=>ii(e,"yAxis",Dn(e,t),r),T4=(e,t,r)=>ai(e,"yAxis",Dn(e,t),r),MG=Y([$e,C4,M4,k4,T4],(e,t,r,n,l)=>Mn(e,"xAxis")?ro(t,n,!1):ro(r,l,!1)),TG=(e,t)=>t,D4=Y([qd,TG],(e,t)=>e.filter(r=>r.type==="area").find(r=>r.id===t)),P4=e=>{var t=$e(e),r=Mn(t,"xAxis");return r?"yAxis":"xAxis"},DG=(e,t)=>{var r=P4(e);return r==="yAxis"?Dn(e,t):Tn(e,t)},PG=(e,t,r)=>Yf(e,P4(e),DG(e,t),r),zG=Y([D4,PG],(e,t)=>{var r;if(!(e==null||t==null)){var{stackId:n}=e,l=Ld(e);if(!(n==null||l==null)){var s=(r=t[n])===null||r===void 0?void 0:r.stackedData,c=s==null?void 0:s.find(d=>d.key===l);if(c!=null)return c.map(d=>[d[0],d[1]])}}}),RG=Y([$e,C4,M4,k4,T4,zG,OC,MG,D4,TI],(e,t,r,n,l,s,c,d,h,m)=>{var{chartData:p,dataStartIndex:y,dataEndIndex:x}=c;if(!(h==null||e!=="horizontal"&&e!=="vertical"||t==null||r==null||n==null||l==null||n.length===0||l.length===0||d==null)){var{data:w}=h,j;if(w&&w.length>0?j=w:j=p==null?void 0:p.slice(y,x+1),j!=null)return tV({layout:e,xAxis:t,yAxis:r,xAxisTicks:n,yAxisTicks:l,dataStartIndex:y,areaSettings:h,stackedData:s,displayedData:j,chartBaseValue:m,bandSize:d})}}),LG=["id"],IG=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function Ui(){return Ui=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var{dataKey:t,name:r,stroke:n,fill:l,legendType:s,hide:c}=e;return[{inactive:c,dataKey:t,type:s,color:Jf(n,l),value:co(r,t),payload:e}]},KG=b.memo(e=>{var{dataKey:t,data:r,stroke:n,strokeWidth:l,fill:s,name:c,hide:d,unit:h,tooltipType:m,id:p}=e,y={dataDefinedOnItem:r,getPosition:Ji,settings:{stroke:n,strokeWidth:l,fill:s,dataKey:t,nameKey:void 0,name:co(c,t),hide:d,type:m,color:Jf(n,s),unit:h,graphicalItemId:p}};return b.createElement(nx,{tooltipEntrySettings:y})});function YG(e){var{clipPathId:t,points:r,props:n}=e,{needClip:l,dot:s,dataKey:c}=n,d=wr(n);return b.createElement(RK,{points:r,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:c,baseProps:d,needClip:l,clipPathId:t})}function GG(e){var{showLabels:t,children:r,points:n}=e,l=n.map(s=>{var c,d,h={x:(c=s.x)!==null&&c!==void 0?c:0,y:(d=s.y)!==null&&d!==void 0?d:0,width:0,lowerWidth:0,upperWidth:0,height:0};return Ql(Ql({},h),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:h,fill:void 0})});return b.createElement(l4,{value:t?l:void 0},r)}function bO(e){var{points:t,baseLine:r,needClip:n,clipPathId:l,props:s}=e,{layout:c,type:d,stroke:h,connectNulls:m,isRange:p}=s,{id:y}=s,x=z4(s,LG),w=wr(x),j=ur(x);return b.createElement(b.Fragment,null,(t==null?void 0:t.length)>1&&b.createElement(_t,{clipPath:n?"url(#clipPath-".concat(l,")"):void 0},b.createElement(Jl,Ui({},j,{id:y,points:t,connectNulls:m,type:d,baseLine:r,layout:c,stroke:"none",className:"recharts-area-area"})),h!=="none"&&b.createElement(Jl,Ui({},w,{className:"recharts-area-curve",layout:c,type:d,connectNulls:m,fill:"none",points:t})),h!=="none"&&p&&b.createElement(Jl,Ui({},w,{className:"recharts-area-curve",layout:c,type:d,connectNulls:m,fill:"none",points:r}))),b.createElement(YG,{points:t,props:x,clipPathId:l}))}function VG(e){var t,r,{alpha:n,baseLine:l,points:s,strokeWidth:c}=e,d=(t=s[0])===null||t===void 0?void 0:t.y,h=(r=s[s.length-1])===null||r===void 0?void 0:r.y;if(!ke(d)||!ke(h))return null;var m=n*Math.abs(d-h),p=Math.max(...s.map(y=>y.x||0));return de(l)?p=Math.max(l,p):l&&Array.isArray(l)&&l.length&&(p=Math.max(...l.map(y=>y.x||0),p)),de(p)?b.createElement("rect",{x:0,y:dy.y||0));return de(l)?p=Math.max(l,p):l&&Array.isArray(l)&&l.length&&(p=Math.max(...l.map(y=>y.y||0),p)),de(p)?b.createElement("rect",{x:d({points:c,baseLine:d}),[c,d]),_=tu(j,"recharts-area-"),N=L0(),[A,O]=b.useState(!1),P=!A,k=b.useCallback(()=>{typeof w=="function"&&w(),O(!1)},[w]),z=b.useCallback(()=>{typeof x=="function"&&x(),O(!0)},[x]);if(N==null)return null;var T=l.current,R=s.current;return b.createElement(GG,{showLabels:P,points:c},n.children,b.createElement(eu,{animationId:_,begin:m,duration:p,isActive:h,easing:y,onAnimationEnd:k,onAnimationStart:z,key:_},$=>{if(T){var Z=T.length/c.length,X=$===1?c:c.map((K,se)=>{var ce=Math.floor(se*Z);if(T[ce]){var he=T[ce];return Ql(Ql({},K),{},{x:lt(he.x,K.x,$),y:lt(he.y,K.y,$)})}return K}),L;return de(d)?L=lt(R,d,$):xt(d)||dn(d)?L=lt(R,0,$):L=d.map((K,se)=>{var ce=Math.floor(se*Z);if(Array.isArray(R)&&R[ce]){var he=R[ce];return Ql(Ql({},K),{},{x:lt(he.x,K.x,$),y:lt(he.y,K.y,$)})}return K}),$>0&&(l.current=X,s.current=L),b.createElement(bO,{points:X,baseLine:L,needClip:t,clipPathId:r,props:n})}return $>0&&(l.current=c,s.current=d),b.createElement(_t,null,h&&b.createElement("defs",null,b.createElement("clipPath",{id:"animationClipPath-".concat(r)},b.createElement(FG,{alpha:$,points:c,baseLine:d,layout:N,strokeWidth:n.strokeWidth}))),b.createElement(_t,{clipPath:"url(#animationClipPath-".concat(r,")")},b.createElement(bO,{points:c,baseLine:d,needClip:t,clipPathId:r,props:n})))}),b.createElement(Zg,{label:n.label}))}function QG(e){var{needClip:t,clipPathId:r,props:n}=e,l=b.useRef(null),s=b.useRef();return b.createElement(ZG,{needClip:t,clipPathId:r,props:n,previousPointsRef:l,previousBaselineRef:s})}class WG extends b.PureComponent{render(){var{hide:t,dot:r,points:n,className:l,top:s,left:c,needClip:d,xAxisId:h,yAxisId:m,width:p,height:y,id:x,baseLine:w,zIndex:j}=this.props;if(t)return null;var _=Ue("recharts-area",l),N=x,{r:A,strokeWidth:O}=dG(r),P=p4(r),k=A*2+O,z=d?"url(#clipPath-".concat(P?"":"dots-").concat(N,")"):void 0;return b.createElement(_r,{zIndex:j},b.createElement(_t,{className:_},d&&b.createElement("defs",null,b.createElement(E4,{clipPathId:N,xAxisId:h,yAxisId:m}),!P&&b.createElement("clipPath",{id:"clipPath-dots-".concat(N)},b.createElement("rect",{x:c-k/2,y:s-k/2,width:p+k,height:y+k}))),b.createElement(QG,{needClip:d,clipPathId:N,props:this.props})),b.createElement(sO,{points:n,mainColor:Jf(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:z}),this.props.isRange&&Array.isArray(w)&&b.createElement(sO,{points:w,mainColor:Jf(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:z}))}}var R4={activeDot:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!1,fill:"#3182bd",fillOpacity:.6,hide:!1,isAnimationActive:"auto",legendType:"line",stroke:"#3182bd",strokeWidth:1,type:"linear",label:!1,xAxisId:0,yAxisId:0,zIndex:Ct.area};function JG(e){var t,r=Mt(e,R4),{activeDot:n,animationBegin:l,animationDuration:s,animationEasing:c,connectNulls:d,dot:h,fill:m,fillOpacity:p,hide:y,isAnimationActive:x,legendType:w,stroke:j,xAxisId:_,yAxisId:N}=r,A=z4(r,IG),O=el(),P=q3(),{needClip:k}=sx(_,N),z=ir(),{points:T,isRange:R,baseLine:$}=(t=ge(ce=>RG(ce,e.id,z)))!==null&&t!==void 0?t:{},Z=ix();if(O!=="horizontal"&&O!=="vertical"||Z==null||P!=="AreaChart"&&P!=="ComposedChart")return null;var{height:X,width:L,x:K,y:se}=Z;return!T||!T.length?null:b.createElement(WG,Ui({},A,{activeDot:n,animationBegin:l,animationDuration:s,animationEasing:c,baseLine:$,connectNulls:d,dot:h,fill:m,fillOpacity:p,height:X,hide:y,layout:O,isAnimationActive:x==="auto"?!Js.isSsr:x,isRange:R,legendType:w,needClip:k,points:T,stroke:j,width:L,left:K,top:se,xAxisId:_,yAxisId:N}))}var eV=(e,t,r,n,l)=>{var s=r??t;if(de(s))return s;var c=e==="horizontal"?l:n,d=c.scale.domain();if(c.type==="number"){var h=Math.max(d[0],d[1]),m=Math.min(d[0],d[1]);return s==="dataMin"?m:s==="dataMax"||h<0?h:Math.max(Math.min(d[0],d[1]),0)}return s==="dataMin"?d[0]:s==="dataMax"?d[1]:d[0]};function tV(e){var{areaSettings:{connectNulls:t,baseValue:r,dataKey:n},stackedData:l,layout:s,chartBaseValue:c,xAxis:d,yAxis:h,displayedData:m,dataStartIndex:p,xAxisTicks:y,yAxisTicks:x,bandSize:w}=e,j=l&&l.length,_=eV(s,c,r,d,h),N=s==="horizontal",A=!1,O=m.map((k,z)=>{var T,R,$,Z;if(j)Z=l[p+z];else{var X=We(k,n);Array.isArray(X)?(Z=X,A=!0):Z=[_,X]}var L=(T=(R=Z)===null||R===void 0?void 0:R[1])!==null&&T!==void 0?T:null,K=L==null||j&&!t&&We(k,n)==null;if(N){var se;return{x:e2({axis:d,ticks:y,bandSize:w,entry:k,index:z}),y:K?null:(se=h.scale.map(L))!==null&&se!==void 0?se:null,value:Z,payload:k}}return{x:K?null:($=d.scale.map(L))!==null&&$!==void 0?$:null,y:e2({axis:h,ticks:x,bandSize:w,entry:k,index:z}),value:Z,payload:k}}),P;return j||A?P=O.map(k=>{var z,T=Array.isArray(k.value)?k.value[0]:null;if(N){var R;return{x:k.x,y:T!=null&&k.y!=null&&(R=h.scale.map(T))!==null&&R!==void 0?R:null,payload:k.payload}}return{x:T!=null&&(z=d.scale.map(T))!==null&&z!==void 0?z:null,y:k.y,payload:k.payload}}):P=N?h.scale.map(_):d.scale.map(_),{points:O,baseLine:P??0,isRange:A}}function rV(e){var t=Mt(e,R4),r=ir();return b.createElement(ax,{id:t.id,type:"area"},n=>b.createElement(b.Fragment,null,b.createElement(y4,{legendPayload:HG(t)}),b.createElement(KG,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,tooltipType:t.tooltipType,id:n}),b.createElement(x4,{type:"area",id:n,data:t.data,dataKey:t.dataKey,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,stackId:pE(t.stackId),hide:t.hide,barSize:void 0,baseValue:t.baseValue,isPanorama:r,connectNulls:t.connectNulls}),b.createElement(JG,Ui({},t,{id:n}))))}var L4=b.memo(rV,Qd);L4.displayName="Area";var nV="Invariant failed";function aV(e,t){throw new Error(nV)}function Jy(){return Jy=Object.assign?Object.assign.bind():function(e){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:0;return(n,l)=>{if(de(t))return t;var s=de(n)||xt(n);return s?t(n,l):(s||aV(),r)}},lV=(e,t,r)=>r,oV=(e,t)=>t,hu=Y([qd,oV],(e,t)=>e.filter(r=>r.type==="bar").find(r=>r.id===t)),sV=Y([hu],e=>e==null?void 0:e.maxBarSize),uV=(e,t,r,n)=>n,cV=Y([$e,qd,Tn,Dn,lV],(e,t,r,n,l)=>t.filter(s=>e==="horizontal"?s.xAxisId===r:s.yAxisId===n).filter(s=>s.isPanorama===l).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),fV=(e,t,r)=>{var n=$e(e),l=Tn(e,t),s=Dn(e,t);if(!(l==null||s==null))return n==="horizontal"?Yf(e,"yAxis",s,r):Yf(e,"xAxis",l,r)},dV=(e,t)=>{var r=$e(e),n=Tn(e,t),l=Dn(e,t);if(!(n==null||l==null))return r==="horizontal"?rN(e,"xAxis",n):rN(e,"yAxis",l)},hV=Y([cV,MI,dV],rY),mV=(e,t,r)=>{var n,l,s=hu(e,t);if(s==null)return 0;var c=Tn(e,t),d=Dn(e,t);if(c==null||d==null)return 0;var h=$e(e),m=IC(e),{maxBarSize:p}=s,y=xt(p)?m:p,x,w;return h==="horizontal"?(x=ii(e,"xAxis",c,r),w=ai(e,"xAxis",c,r)):(x=ii(e,"yAxis",d,r),w=ai(e,"yAxis",d,r)),(n=(l=ro(x,w,!0))!==null&&l!==void 0?l:y)!==null&&n!==void 0?n:0},I4=(e,t,r)=>{var n=$e(e),l=Tn(e,t),s=Dn(e,t);if(!(l==null||s==null)){var c,d;return n==="horizontal"?(c=ii(e,"xAxis",l,r),d=ai(e,"xAxis",l,r)):(c=ii(e,"yAxis",s,r),d=ai(e,"yAxis",s,r)),ro(c,d)}},pV=Y([hV,IC,kI,$C,mV,I4,sV],oY),vV=(e,t,r)=>{var n=Tn(e,t);if(n!=null)return ii(e,"xAxis",n,r)},yV=(e,t,r)=>{var n=Dn(e,t);if(n!=null)return ii(e,"yAxis",n,r)},gV=(e,t,r)=>{var n=Tn(e,t);if(n!=null)return ai(e,"xAxis",n,r)},xV=(e,t,r)=>{var n=Dn(e,t);if(n!=null)return ai(e,"yAxis",n,r)},bV=Y([pV,hu],uY),wV=Y([fV,hu],sY),jV=Y([zt,T0,vV,yV,gV,xV,bV,$e,OC,I4,wV,hu,uV],(e,t,r,n,l,s,c,d,h,m,p,y,x)=>{var{chartData:w,dataStartIndex:j,dataEndIndex:_}=h;if(!(y==null||c==null||t==null||d!=="horizontal"&&d!=="vertical"||r==null||n==null||l==null||s==null||m==null)){var{data:N}=y,A;if(N!=null&&N.length>0?A=N:A=w==null?void 0:w.slice(j,_+1),A!=null)return ZV({layout:d,barSettings:y,pos:c,parentViewBox:t,bandSize:m,xAxis:r,yAxis:n,xAxisTicks:l,yAxisTicks:s,stackedData:p,displayedData:A,offset:e,cells:x,dataStartIndex:j})}}),_V=["index"];function e0(){return e0=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var t=b.useContext($4);if(t!=null)return t.stackId;if(e!=null)return pE(e)},AV=(e,t)=>"recharts-bar-stack-clip-path-".concat(e,"-").concat(t),EV=e=>{var t=b.useContext($4);if(t!=null){var{stackId:r}=t;return"url(#".concat(AV(r,e),")")}},B4=e=>{var{index:t}=e,r=SV(e,_V),n=EV(t);return b.createElement(_t,e0({className:"recharts-bar-stack-layer",clipPath:n},r))},CV=["onMouseEnter","onMouseLeave","onClick"],kV=["value","background","tooltipPosition"],MV=["id"],TV=["onMouseEnter","onClick","onMouseLeave"];function va(){return va=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var{dataKey:t,name:r,fill:n,legendType:l,hide:s}=e;return[{inactive:s,dataKey:t,type:l,color:n,value:co(r,t),payload:e}]},IV=b.memo(e=>{var{dataKey:t,stroke:r,strokeWidth:n,fill:l,name:s,hide:c,unit:d,tooltipType:h,id:m}=e,p={dataDefinedOnItem:void 0,getPosition:Ji,settings:{stroke:r,strokeWidth:n,fill:l,dataKey:t,nameKey:void 0,name:co(s,t),hide:c,type:h,color:l,unit:d,graphicalItemId:m}};return b.createElement(nx,{tooltipEntrySettings:p})});function $V(e){var t=ge(li),{data:r,dataKey:n,background:l,allOtherBarProps:s}=e,{onMouseEnter:c,onMouseLeave:d,onClick:h}=s,m=td(s,CV),p=ex(c,n,s.id),y=tx(d),x=rx(h,n,s.id);if(!l||r==null)return null;var w=Ki(l);return b.createElement(_r,{zIndex:cY(l,Ct.barBackground)},r.map((j,_)=>{var{value:N,background:A,tooltipPosition:O}=j,P=td(j,kV);if(!A)return null;var k=p(j,_),z=y(j,_),T=x(j,_),R=or(or(or(or(or({option:l,isActive:String(_)===t},P),{},{fill:"#eee"},A),w),Vs(m,j,_)),{},{onMouseEnter:k,onMouseLeave:z,onClick:T,dataKey:n,index:_,className:"recharts-bar-background-rectangle"});return b.createElement(ed,va({key:"background-bar-".concat(_)},R))}))}function BV(e){var{showLabels:t,children:r,rects:n}=e,l=n==null?void 0:n.map(s=>{var c={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return or(or({},c),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:c,fill:s.fill})});return b.createElement(l4,{value:t?l:void 0},r)}function qV(e){var{shape:t,activeBar:r,baseProps:n,entry:l,index:s,dataKey:c}=e,d=ge(li),h=ge(Hg),m=r&&String(s)===d&&(h==null||c===h),p=m?r:t;return m?b.createElement(_r,{zIndex:Ct.activeBar},b.createElement(B4,{index:s},b.createElement(ed,va({},n,{name:String(n.name)},l,{isActive:m,option:p,index:s,dataKey:c})))):b.createElement(ed,va({},n,{name:String(n.name)},l,{isActive:m,option:p,index:s,dataKey:c}))}function UV(e){var{shape:t,baseProps:r,entry:n,index:l,dataKey:s}=e;return b.createElement(ed,va({},r,{name:String(r.name)},n,{isActive:!1,option:t,index:l,dataKey:s}))}function HV(e){var t,{data:r,props:n}=e,l=(t=wr(n))!==null&&t!==void 0?t:{},{id:s}=l,c=td(l,MV),{shape:d,dataKey:h,activeBar:m}=n,{onMouseEnter:p,onClick:y,onMouseLeave:x}=n,w=td(n,TV),j=ex(p,h,s),_=tx(x),N=rx(y,h,s);return r?b.createElement(b.Fragment,null,r.map((A,O)=>b.createElement(B4,va({index:O,key:"rectangle-".concat(A==null?void 0:A.x,"-").concat(A==null?void 0:A.y,"-").concat(A==null?void 0:A.value,"-").concat(O),className:"recharts-bar-rectangle"},Vs(w,A,O),{onMouseEnter:j(A,O),onMouseLeave:_(A,O),onClick:N(A,O)}),m?b.createElement(qV,{shape:d,activeBar:m,baseProps:c,entry:A,index:O,dataKey:h}):b.createElement(UV,{shape:d,baseProps:c,entry:A,index:O,dataKey:h})))):null}function KV(e){var{props:t,previousRectanglesRef:r}=e,{data:n,layout:l,isAnimationActive:s,animationBegin:c,animationDuration:d,animationEasing:h,onAnimationEnd:m,onAnimationStart:p}=t,y=r.current,x=tu(t,"recharts-bar-"),[w,j]=b.useState(!1),_=!w,N=b.useCallback(()=>{typeof m=="function"&&m(),j(!1)},[m]),A=b.useCallback(()=>{typeof p=="function"&&p(),j(!0)},[p]);return b.createElement(BV,{showLabels:_,rects:n},b.createElement(eu,{animationId:x,begin:c,duration:d,isActive:s,easing:h,onAnimationEnd:N,onAnimationStart:A,key:x},O=>{var P=O===1?n:n==null?void 0:n.map((k,z)=>{var T=y&&y[z];if(T)return or(or({},k),{},{x:lt(T.x,k.x,O),y:lt(T.y,k.y,O),width:lt(T.width,k.width,O),height:lt(T.height,k.height,O)});if(l==="horizontal"){var R=lt(0,k.height,O),$=lt(k.stackedBarStart,k.y,O);return or(or({},k),{},{y:$,height:R})}var Z=lt(0,k.width,O),X=lt(k.stackedBarStart,k.x,O);return or(or({},k),{},{width:Z,x:X})});return O>0&&(r.current=P??null),P==null?null:b.createElement(_t,null,b.createElement(HV,{props:t,data:P}))}),b.createElement(Zg,{label:t.label}),t.children)}function YV(e){var t=b.useRef(null);return b.createElement(KV,{previousRectanglesRef:t,props:e})}var q4=0,GV=(e,t)=>{var r=Array.isArray(e.value)?e.value[1]:e.value;return{x:e.x,y:e.y,value:r,errorVal:We(e,t)}};class VV extends b.PureComponent{render(){var{hide:t,data:r,dataKey:n,className:l,xAxisId:s,yAxisId:c,needClip:d,background:h,id:m}=this.props;if(t||r==null)return null;var p=Ue("recharts-bar",l),y=m;return b.createElement(_t,{className:p,id:m},d&&b.createElement("defs",null,b.createElement(E4,{clipPathId:y,xAxisId:s,yAxisId:c})),b.createElement(_t,{className:"recharts-bar-rectangles",clipPath:d?"url(#clipPath-".concat(y,")"):void 0},b.createElement($V,{data:r,dataKey:n,background:h,allOtherBarProps:this.props}),b.createElement(YV,this.props)))}}var XV={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:q4,xAxisId:0,yAxisId:0,zIndex:Ct.bar};function FV(e){var{xAxisId:t,yAxisId:r,hide:n,legendType:l,minPointSize:s,activeBar:c,animationBegin:d,animationDuration:h,animationEasing:m,isAnimationActive:p}=e,{needClip:y}=sx(t,r),x=el(),w=ir(),j=Jg(e.children,qi),_=ge(O=>jV(O,e.id,w,j));if(x!=="vertical"&&x!=="horizontal")return null;var N,A=_==null?void 0:_[0];return A==null||A.height==null||A.width==null?N=0:N=x==="vertical"?A.height/2:A.width/2,b.createElement(fG,{xAxisId:t,yAxisId:r,data:_,dataPointFormatter:GV,errorBarOffset:N},b.createElement(VV,va({},e,{layout:x,needClip:y,data:_,xAxisId:t,yAxisId:r,hide:n,legendType:l,minPointSize:s,activeBar:c,animationBegin:d,animationDuration:h,animationEasing:m,isAnimationActive:p})))}function ZV(e){var{layout:t,barSettings:{dataKey:r,minPointSize:n},pos:l,bandSize:s,xAxis:c,yAxis:d,xAxisTicks:h,yAxisTicks:m,stackedData:p,displayedData:y,offset:x,cells:w,parentViewBox:j,dataStartIndex:_}=e,N=t==="horizontal"?d:c,A=p?N.scale.domain():null,O=g8({numericAxis:N}),P=N.scale.map(O);return y.map((k,z)=>{var T,R,$,Z,X,L;if(p){var K=p[z+_];if(K==null)return null;T=h8(K,A)}else T=We(k,r),Array.isArray(T)||(T=[O,T]);var se=iV(n,q4)(T[1],z);if(t==="horizontal"){var ce,he=d.scale.map(T[0]),q=d.scale.map(T[1]);if(he==null||q==null)return null;R=t2({axis:c,ticks:h,bandSize:s,offset:l.offset,entry:k,index:z}),$=(ce=q??he)!==null&&ce!==void 0?ce:void 0,Z=l.size;var W=he-q;if(X=dn(W)?0:W,L={x:R,y:x.top,width:Z,height:x.height},Math.abs(se)>0&&Math.abs(X)0&&Math.abs(Z)b.createElement(b.Fragment,null,b.createElement(y4,{legendPayload:LV(t)}),b.createElement(IV,{dataKey:t.dataKey,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,tooltipType:t.tooltipType,id:l}),b.createElement(x4,{type:"bar",id:l,data:void 0,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,stackId:r,hide:t.hide,barSize:t.barSize,minPointSize:t.minPointSize,maxBarSize:t.maxBarSize,isPanorama:n}),b.createElement(_r,{zIndex:t.zIndex},b.createElement(FV,va({},t,{id:l})))))}var t0=b.memo(QV,Qd);t0.displayName="Bar";var WV=["domain","range"],JV=["domain","range"];function jO(e,t){if(e==null)return{};var r,n,l=eX(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n{if(c!=null)return NO(NO({},s),{},{type:c})},[s,c]);return b.useLayoutEffect(()=>{d!=null&&(r.current===null?t(qK(d)):r.current!==d&&t(UK({prev:r.current,next:d})),r.current=d)},[d,t]),b.useLayoutEffect(()=>()=>{r.current&&(t(HK(r.current)),r.current=null)},[t]),null}var uX=e=>{var{xAxisId:t,className:r}=e,n=ge(T0),l=ir(),s="xAxis",c=ge(A=>g3(A,s,t,l)),d=ge(A=>m3(A,t)),h=ge(A=>T$(A,t)),m=ge(A=>FC(A,t));if(d==null||h==null||m==null)return null;var{dangerouslySetInnerHTML:p,ticks:y,scale:x}=e,w=n0(e,rX),{id:j,scale:_}=m,N=n0(m,nX);return b.createElement(ox,r0({},w,N,{x:h.x,y:h.y,width:d.width,height:d.height,className:Ue("recharts-".concat(s," ").concat(s),r),viewBox:n,ticks:c,axisType:s}))},cX={allowDataOverflow:Bt.allowDataOverflow,allowDecimals:Bt.allowDecimals,allowDuplicatedCategory:Bt.allowDuplicatedCategory,angle:Bt.angle,axisLine:ua.axisLine,height:Bt.height,hide:!1,includeHidden:Bt.includeHidden,interval:Bt.interval,label:!1,minTickGap:Bt.minTickGap,mirror:Bt.mirror,orientation:Bt.orientation,padding:Bt.padding,reversed:Bt.reversed,scale:Bt.scale,tick:Bt.tick,tickCount:Bt.tickCount,tickLine:ua.tickLine,tickSize:ua.tickSize,type:Bt.type,xAxisId:0},fX=e=>{var t=Mt(e,cX);return b.createElement(b.Fragment,null,b.createElement(sX,{allowDataOverflow:t.allowDataOverflow,allowDecimals:t.allowDecimals,allowDuplicatedCategory:t.allowDuplicatedCategory,angle:t.angle,dataKey:t.dataKey,domain:t.domain,height:t.height,hide:t.hide,id:t.xAxisId,includeHidden:t.includeHidden,interval:t.interval,minTickGap:t.minTickGap,mirror:t.mirror,name:t.name,orientation:t.orientation,padding:t.padding,reversed:t.reversed,scale:t.scale,tick:t.tick,tickCount:t.tickCount,tickFormatter:t.tickFormatter,ticks:t.ticks,type:t.type,unit:t.unit}),b.createElement(uX,t))},af=b.memo(fX,U4);af.displayName="XAxis";var dX=["type"],hX=["dangerouslySetInnerHTML","ticks","scale"],mX=["id","scale"];function a0(){return a0=Object.assign?Object.assign.bind():function(e){for(var t=1;t{if(c!=null)return AO(AO({},s),{},{type:c})},[c,s]);return b.useLayoutEffect(()=>{d!=null&&(r.current===null?t(KK(d)):r.current!==d&&t(YK({prev:r.current,next:d})),r.current=d)},[d,t]),b.useLayoutEffect(()=>()=>{r.current&&(t(GK(r.current)),r.current=null)},[t]),null}function bX(e){var{yAxisId:t,className:r,width:n,label:l}=e,s=b.useRef(null),c=b.useRef(null),d=ge(T0),h=ir(),m=rt(),p="yAxis",y=ge(T=>p3(T,t)),x=ge(T=>P$(T,t)),w=ge(T=>g3(T,p,t,h)),j=ge(T=>ZC(T,t));if(b.useLayoutEffect(()=>{if(!(n!=="auto"||!y||Fg(l)||b.isValidElement(l)||j==null)){var T=s.current;if(T){var R=T.getCalculatedWidth();Math.round(y.width)!==Math.round(R)&&m(VK({id:t,width:R}))}}},[w,y,m,l,t,n,j]),y==null||x==null||j==null)return null;var{dangerouslySetInnerHTML:_,ticks:N,scale:A}=e,O=i0(e,hX),{id:P,scale:k}=j,z=i0(j,mX);return b.createElement(ox,a0({},O,z,{ref:s,labelRef:c,x:x.x,y:x.y,tickTextProps:n==="auto"?{width:void 0}:{width:n},width:y.width,height:y.height,className:Ue("recharts-".concat(p," ").concat(p),r),viewBox:d,ticks:w,axisType:p}))}var wX={allowDataOverflow:qt.allowDataOverflow,allowDecimals:qt.allowDecimals,allowDuplicatedCategory:qt.allowDuplicatedCategory,angle:qt.angle,axisLine:ua.axisLine,hide:!1,includeHidden:qt.includeHidden,interval:qt.interval,label:!1,minTickGap:qt.minTickGap,mirror:qt.mirror,orientation:qt.orientation,padding:qt.padding,reversed:qt.reversed,scale:qt.scale,tick:qt.tick,tickCount:qt.tickCount,tickLine:ua.tickLine,tickSize:ua.tickSize,type:qt.type,width:qt.width,yAxisId:0},jX=e=>{var t=Mt(e,wX);return b.createElement(b.Fragment,null,b.createElement(xX,{interval:t.interval,id:t.yAxisId,scale:t.scale,type:t.type,domain:t.domain,allowDataOverflow:t.allowDataOverflow,dataKey:t.dataKey,allowDuplicatedCategory:t.allowDuplicatedCategory,allowDecimals:t.allowDecimals,tickCount:t.tickCount,padding:t.padding,includeHidden:t.includeHidden,reversed:t.reversed,ticks:t.ticks,width:t.width,orientation:t.orientation,mirror:t.mirror,hide:t.hide,unit:t.unit,name:t.name,angle:t.angle,minTickGap:t.minTickGap,tick:t.tick,tickFormatter:t.tickFormatter}),b.createElement(bX,t))},lf=b.memo(jX,U4);lf.displayName="YAxis";var _X=(e,t)=>t,ux=Y([_X,$e,GC,Yt,z3,_a,FB,zt],rq),cx=e=>{var t=e.currentTarget.getBoundingClientRect(),r=t.width/e.currentTarget.offsetWidth,n=t.height/e.currentTarget.offsetHeight;return{chartX:Math.round((e.clientX-t.left)/r),chartY:Math.round((e.clientY-t.top)/n)}},H4=en("mouseClick"),K4=Fs();K4.startListening({actionCreator:H4,effect:(e,t)=>{var r=e.payload,n=ux(t.getState(),cx(r));(n==null?void 0:n.activeIndex)!=null&&t.dispatch(X$({activeIndex:n.activeIndex,activeDataKey:void 0,activeCoordinate:n.activeCoordinate}))}});var l0=en("mouseMove"),Y4=Fs(),Xc=null;Y4.startListening({actionCreator:l0,effect:(e,t)=>{var r=e.payload;Xc!==null&&cancelAnimationFrame(Xc);var n=cx(r);Xc=requestAnimationFrame(()=>{var l=t.getState(),s=Lg(l,l.tooltip.settings.shared);if(s==="axis"){var c=ux(l,n);(c==null?void 0:c.activeIndex)!=null?t.dispatch(O3({activeIndex:c.activeIndex,activeDataKey:void 0,activeCoordinate:c.activeCoordinate})):t.dispatch(N3())}Xc=null})}});function SX(e,t){return t instanceof HTMLElement?"HTMLElement <".concat(t.tagName,' class="').concat(t.className,'">'):t===window?"global.window":e==="children"&&typeof t=="object"&&t!==null?"<>":t}var EO={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:"none",syncId:void 0,syncMethod:"index",baseValue:void 0,reverseStackOrder:!1},G4=jr({name:"rootProps",initialState:EO,reducers:{updateOptions:(e,t)=>{var r;e.accessibilityLayer=t.payload.accessibilityLayer,e.barCategoryGap=t.payload.barCategoryGap,e.barGap=(r=t.payload.barGap)!==null&&r!==void 0?r:EO.barGap,e.barSize=t.payload.barSize,e.maxBarSize=t.payload.maxBarSize,e.stackOffset=t.payload.stackOffset,e.syncId=t.payload.syncId,e.syncMethod=t.payload.syncMethod,e.className=t.payload.className,e.baseValue=t.payload.baseValue,e.reverseStackOrder=t.payload.reverseStackOrder}}}),NX=G4.reducer,{updateOptions:OX}=G4.actions,AX=null,EX={updatePolarOptions:(e,t)=>t.payload},V4=jr({name:"polarOptions",initialState:AX,reducers:EX}),{updatePolarOptions:CX}=V4.actions,kX=V4.reducer,X4=en("keyDown"),F4=en("focus"),fx=Fs();fx.startListening({actionCreator:X4,effect:(e,t)=>{var r=t.getState(),n=r.rootProps.accessibilityLayer!==!1;if(n){var{keyboardInteraction:l}=r.tooltip,s=e.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var c=Ig(l,bo(r),uu(r),fu(r)),d=c==null?-1:Number(c);if(!(!Number.isFinite(d)||d<0)){var h=_a(r);if(s==="Enter"){var m=Vf(r,"axis","hover",String(l.index));t.dispatch(Gy({active:!l.active,activeIndex:l.index,activeCoordinate:m}));return}var p=I$(r),y=p==="left-to-right"?1:-1,x=s==="ArrowRight"?1:-1,w=d+x*y;if(!(h==null||w>=h.length||w<0)){var j=Vf(r,"axis","hover",String(w));t.dispatch(Gy({active:!0,activeIndex:w.toString(),activeCoordinate:j}))}}}}}});fx.startListening({actionCreator:F4,effect:(e,t)=>{var r=t.getState(),n=r.rootProps.accessibilityLayer!==!1;if(n){var{keyboardInteraction:l}=r.tooltip;if(!l.active&&l.index==null){var s="0",c=Vf(r,"axis","hover",String(s));t.dispatch(Gy({active:!0,activeIndex:s,activeCoordinate:c}))}}}});var Qr=en("externalEvent"),Z4=Fs(),ey=new Map;Z4.startListening({actionCreator:Qr,effect:(e,t)=>{var{handler:r,reactEvent:n}=e.payload;if(r!=null){n.persist();var l=n.type,s=ey.get(l);s!==void 0&&cancelAnimationFrame(s);var c=requestAnimationFrame(()=>{try{var d=t.getState(),h={activeCoordinate:PB(d),activeDataKey:Hg(d),activeIndex:li(d),activeLabel:I3(d),activeTooltipIndex:li(d),isTooltipActive:zB(d)};r(h,n)}finally{ey.delete(l)}});ey.set(l,c)}}});var MX=Y([go],e=>e.tooltipItemPayloads),TX=Y([MX,(e,t)=>t,(e,t,r)=>r],(e,t,r)=>{if(t!=null){var n=e.find(s=>s.settings.graphicalItemId===r);if(n!=null){var{getPosition:l}=n;if(l!=null)return l(t)}}}),Q4=en("touchMove"),W4=Fs();W4.startListening({actionCreator:Q4,effect:(e,t)=>{var r=e.payload;if(!(r.touches==null||r.touches.length===0)){var n=t.getState(),l=Lg(n,n.tooltip.settings.shared);if(l==="axis"){var s=r.touches[0];if(s==null)return;var c=ux(n,cx({clientX:s.clientX,clientY:s.clientY,currentTarget:r.currentTarget}));(c==null?void 0:c.activeIndex)!=null&&t.dispatch(O3({activeIndex:c.activeIndex,activeDataKey:void 0,activeCoordinate:c.activeCoordinate}))}else if(l==="item"){var d,h=r.touches[0];if(document.elementFromPoint==null||h==null)return;var m=document.elementFromPoint(h.clientX,h.clientY);if(!m||!m.getAttribute)return;var p=m.getAttribute(yE),y=(d=m.getAttribute(gE))!==null&&d!==void 0?d:void 0,x=xo(n).find(_=>_.id===y);if(p==null||x==null||y==null)return;var{dataKey:w}=x,j=TX(n,p,y);t.dispatch(S3({activeDataKey:w,activeIndex:p,activeCoordinate:j,activeGraphicalItemId:y}))}}}});var DX=IA({brush:fY,cartesianAxis:XK,chartData:Dq,errorBars:iG,graphicalItems:tK,layout:s8,legend:mR,options:Eq,polarAxis:pH,polarOptions:kX,referenceElements:pY,rootProps:NX,tooltip:F$,zIndex:vq}),PX=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return Dz({reducer:DX,preloadedState:t,middleware:n=>{var l;return n({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((l="es6")!==null&&l!==void 0?l:"")}).concat([K4.middleware,Y4.middleware,fx.middleware,Z4.middleware,W4.middleware])},enhancers:n=>{var l=n;return typeof n=="function"&&(l=n()),l.concat(JA({type:"raf"}))},devTools:{serialize:{replacer:SX},name:"recharts-".concat(r)}})};function J4(e){var{preloadedState:t,children:r,reduxStoreName:n}=e,l=ir(),s=b.useRef(null);if(l)return r;s.current==null&&(s.current=PX(t,n));var c=N0;return b.createElement(EG,{context:c,store:s.current},r)}function zX(e){var{layout:t,margin:r}=e,n=rt(),l=ir();return b.useEffect(()=>{l||(n(i8(t)),n(a8(r)))},[n,l,t,r]),null}var e5=b.memo(zX,Qd);function t5(e){var t=rt();return b.useEffect(()=>{t(OX(e))},[t,e]),null}function CO(e){var{zIndex:t,isPanorama:r}=e,n=b.useRef(null),l=rt();return b.useLayoutEffect(()=>(n.current&&l(mq({zIndex:t,element:n.current,isPanorama:r})),()=>{l(pq({zIndex:t,isPanorama:r}))}),[l,t,r]),b.createElement("g",{tabIndex:-1,ref:n})}function kO(e){var{children:t,isPanorama:r}=e,n=ge(aq);if(!n||n.length===0)return t;var l=n.filter(c=>c<0),s=n.filter(c=>c>0);return b.createElement(b.Fragment,null,l.map(c=>b.createElement(CO,{key:c,zIndex:c,isPanorama:r})),t,s.map(c=>b.createElement(CO,{key:c,zIndex:c,isPanorama:r})))}var RX=["children"];function LX(e,t){if(e==null)return{};var r,n,l=IX(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n{var r=z0(),n=R0(),l=zE();if(!En(r)||!En(n))return null;var{children:s,otherAttributes:c,title:d,desc:h}=e,m,p;return c!=null&&(typeof c.tabIndex=="number"?m=c.tabIndex:m=l?0:void 0,typeof c.role=="string"?p=c.role:p=l?"application":void 0),b.createElement(m0,rd({},c,{title:d,desc:h,role:p,tabIndex:m,width:r,height:n,style:$X,ref:t}),s)}),qX=e=>{var{children:t}=e,r=ge(jd);if(!r)return null;var{width:n,height:l,y:s,x:c}=r;return b.createElement(m0,{width:n,height:l,x:c,y:s},t)},MO=b.forwardRef((e,t)=>{var{children:r}=e,n=LX(e,RX),l=ir();return l?b.createElement(qX,null,b.createElement(kO,{isPanorama:!0},r)):b.createElement(BX,rd({ref:t},n),b.createElement(kO,{isPanorama:!1},r))});function UX(){var e=rt(),[t,r]=b.useState(null),n=ge(S8);return b.useEffect(()=>{if(t!=null){var l=t.getBoundingClientRect(),s=l.width/t.offsetWidth;ke(s)&&s!==n&&e(o8(s))}},[t,e,n]),r}function TO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(l){return Object.getOwnPropertyDescriptor(e,l).enumerable})),r.push.apply(r,n)}return r}function HX(e){for(var t=1;t(Uq(),null);function nd(e){if(typeof e=="number")return e;if(typeof e=="string"){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var XX=b.forwardRef((e,t)=>{var r,n,l=b.useRef(null),[s,c]=b.useState({containerWidth:nd((r=e.style)===null||r===void 0?void 0:r.width),containerHeight:nd((n=e.style)===null||n===void 0?void 0:n.height)}),d=b.useCallback((m,p)=>{c(y=>{var x=Math.round(m),w=Math.round(p);return y.containerWidth===x&&y.containerHeight===w?y:{containerWidth:x,containerHeight:w}})},[]),h=b.useCallback(m=>{if(typeof t=="function"&&t(m),m!=null&&typeof ResizeObserver<"u"){var{width:p,height:y}=m.getBoundingClientRect();d(p,y);var x=j=>{var _=j[0];if(_!=null){var{width:N,height:A}=_.contentRect;d(N,A)}},w=new ResizeObserver(x);w.observe(m),l.current=w}},[t,d]);return b.useEffect(()=>()=>{var m=l.current;m!=null&&m.disconnect()},[d]),b.createElement(b.Fragment,null,b.createElement(Qs,{width:s.containerWidth,height:s.containerHeight}),b.createElement("div",ni({ref:h},e)))}),FX=b.forwardRef((e,t)=>{var{width:r,height:n}=e,[l,s]=b.useState({containerWidth:nd(r),containerHeight:nd(n)}),c=b.useCallback((h,m)=>{s(p=>{var y=Math.round(h),x=Math.round(m);return p.containerWidth===y&&p.containerHeight===x?p:{containerWidth:y,containerHeight:x}})},[]),d=b.useCallback(h=>{if(typeof t=="function"&&t(h),h!=null){var{width:m,height:p}=h.getBoundingClientRect();c(m,p)}},[t,c]);return b.createElement(b.Fragment,null,b.createElement(Qs,{width:l.containerWidth,height:l.containerHeight}),b.createElement("div",ni({ref:d},e)))}),ZX=b.forwardRef((e,t)=>{var{width:r,height:n}=e;return b.createElement(b.Fragment,null,b.createElement(Qs,{width:r,height:n}),b.createElement("div",ni({ref:t},e)))}),QX=b.forwardRef((e,t)=>{var{width:r,height:n}=e;return typeof r=="string"||typeof n=="string"?b.createElement(FX,ni({},e,{ref:t})):typeof r=="number"&&typeof n=="number"?b.createElement(ZX,ni({},e,{width:r,height:n,ref:t})):b.createElement(b.Fragment,null,b.createElement(Qs,{width:r,height:n}),b.createElement("div",ni({ref:t},e)))});function WX(e){return e?XX:QX}var JX=b.forwardRef((e,t)=>{var{children:r,className:n,height:l,onClick:s,onContextMenu:c,onDoubleClick:d,onMouseDown:h,onMouseEnter:m,onMouseLeave:p,onMouseMove:y,onMouseUp:x,onTouchEnd:w,onTouchMove:j,onTouchStart:_,style:N,width:A,responsive:O,dispatchTouchEvents:P=!0}=e,k=b.useRef(null),z=rt(),[T,R]=b.useState(null),[$,Z]=b.useState(null),X=UX(),L=D0(),K=(L==null?void 0:L.width)>0?L.width:A,se=(L==null?void 0:L.height)>0?L.height:l,ce=b.useCallback(J=>{X(J),typeof t=="function"&&t(J),R(J),Z(J),J!=null&&(k.current=J)},[X,t,R,Z]),he=b.useCallback(J=>{z(H4(J)),z(Qr({handler:s,reactEvent:J}))},[z,s]),q=b.useCallback(J=>{z(l0(J)),z(Qr({handler:m,reactEvent:J}))},[z,m]),W=b.useCallback(J=>{z(N3()),z(Qr({handler:p,reactEvent:J}))},[z,p]),ue=b.useCallback(J=>{z(l0(J)),z(Qr({handler:y,reactEvent:J}))},[z,y]),te=b.useCallback(()=>{z(F4())},[z]),M=b.useCallback(J=>{z(X4(J.key))},[z]),C=b.useCallback(J=>{z(Qr({handler:c,reactEvent:J}))},[z,c]),U=b.useCallback(J=>{z(Qr({handler:d,reactEvent:J}))},[z,d]),ee=b.useCallback(J=>{z(Qr({handler:h,reactEvent:J}))},[z,h]),le=b.useCallback(J=>{z(Qr({handler:x,reactEvent:J}))},[z,x]),me=b.useCallback(J=>{z(Qr({handler:_,reactEvent:J}))},[z,_]),pe=b.useCallback(J=>{P&&z(Q4(J)),z(Qr({handler:j,reactEvent:J}))},[z,P,j]),be=b.useCallback(J=>{z(Qr({handler:w,reactEvent:J}))},[z,w]),Me=WX(O);return b.createElement(G3.Provider,{value:T},b.createElement(tA.Provider,{value:$},b.createElement(Me,{width:K??(N==null?void 0:N.width),height:se??(N==null?void 0:N.height),className:Ue("recharts-wrapper",n),style:HX({position:"relative",cursor:"default",width:K,height:se},N),onClick:he,onContextMenu:C,onDoubleClick:U,onFocus:te,onKeyDown:M,onMouseDown:ee,onMouseEnter:q,onMouseLeave:W,onMouseMove:ue,onMouseUp:le,onTouchEnd:be,onTouchMove:pe,onTouchStart:me,ref:ce},b.createElement(VX,null),r)))}),eF=["width","height","responsive","children","className","style","compact","title","desc"];function tF(e,t){if(e==null)return{};var r,n,l=rF(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n{var{width:r,height:n,responsive:l,children:s,className:c,style:d,compact:h,title:m,desc:p}=e,y=tF(e,eF),x=wr(y);return h?b.createElement(b.Fragment,null,b.createElement(Qs,{width:r,height:n}),b.createElement(MO,{otherAttributes:x,title:m,desc:p},s)):b.createElement(JX,{className:c,style:d,width:r,height:n,responsive:l??!1,onClick:e.onClick,onMouseLeave:e.onMouseLeave,onMouseEnter:e.onMouseEnter,onMouseMove:e.onMouseMove,onMouseDown:e.onMouseDown,onMouseUp:e.onMouseUp,onContextMenu:e.onContextMenu,onDoubleClick:e.onDoubleClick,onTouchStart:e.onTouchStart,onTouchMove:e.onTouchMove,onTouchEnd:e.onTouchEnd},b.createElement(MO,{otherAttributes:x,title:m,desc:p,ref:t},b.createElement(yY,null,s)))});function o0(){return o0=Object.assign?Object.assign.bind():function(e){for(var t=1;tb.createElement(n5,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:iF,tooltipPayloadSearcher:Xg,categoricalChartProps:e,ref:t}));function lF(e){var t=rt();return b.useEffect(()=>{t(CX(e))},[t,e]),null}var oF=["layout"];function s0(){return s0=Object.assign?Object.assign.bind():function(e){for(var t=1;t{var r=Mt(e,vF);return b.createElement(fF,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:pF,tooltipPayloadSearcher:Xg,categoricalChartProps:r,ref:t})}),yF=["axis"],gF=b.forwardRef((e,t)=>b.createElement(n5,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:yF,tooltipPayloadSearcher:Xg,categoricalChartProps:e,ref:t}));const xF=({status:e})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600"},r={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return f.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[e]||t.cancelled}`,children:r[e]||e})},Fc=({title:e,value:t,icon:r,colorClass:n,trend:l})=>f.jsxs("div",{className:"ios-card p-6 rounded-[2rem] flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[f.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${n} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),f.jsxs("div",{className:"flex justify-between items-start mb-6",children:[f.jsx("div",{className:`p-4 rounded-2xl ${n} bg-opacity-10 backdrop-blur-sm`,children:f.jsx(r,{className:`w-6 h-6 ${n.replace("bg-","text-")}`})}),l&&f.jsxs("span",{className:"text-xs font-bold text-white bg-[#0094f7] px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[f.jsx(YT,{className:"w-3 h-3"})," ",l]})]}),f.jsxs("div",{className:"relative z-10",children:[f.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:t}),f.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:e})]})]}),LO=()=>{var te;const[e,t]=b.useState(null),[r,n]=b.useState(null),[l,s]=b.useState("7days"),[c,d]=b.useState(""),[h,m]=b.useState(""),[p,y]=b.useState(null),[x,w]=b.useState(""),[j,_]=b.useState([]),[N,A]=b.useState(!1),[O,P]=b.useState([]),[k,z]=b.useState({}),T=["#0094f7","#3B82F6","#10B981","#F59E0B","#8B5CF6"],R=M=>{const C=new Date,U=C.getFullYear(),ee=String(C.getMonth()+1).padStart(2,"0"),le=String(C.getDate()).padStart(2,"0"),me=`${U}-${ee}-${le}`;let pe;switch(M){case"today":pe={start_date:me,end_date:me};break;case"yesterday":const Me=new Date(C);Me.setDate(Me.getDate()-1);const J=Me.getFullYear(),we=String(Me.getMonth()+1).padStart(2,"0"),Oe=String(Me.getDate()).padStart(2,"0"),ie=`${J}-${we}-${Oe}`;pe={start_date:ie,end_date:ie};break;case"3days":const Ie=new Date(C);Ie.setDate(Ie.getDate()-3);const _e=Ie.getFullYear(),ct=String(Ie.getMonth()+1).padStart(2,"0"),ft=String(Ie.getDate()).padStart(2,"0");pe={start_date:`${_e}-${ct}-${ft}`,end_date:me};break;case"7days":const ht=new Date(C);ht.setDate(ht.getDate()-7);const nn=ht.getFullYear(),Pn=String(ht.getMonth()+1).padStart(2,"0"),zn=String(ht.getDate()).padStart(2,"0");pe={start_date:`${nn}-${Pn}-${zn}`,end_date:me};break;case"30days":const D=new Date(C);D.setDate(D.getDate()-30);const oe=D.getFullYear(),fe=String(D.getMonth()+1).padStart(2,"0"),Pe=String(D.getDate()).padStart(2,"0");pe={start_date:`${oe}-${fe}-${Pe}`,end_date:me};break;case"custom":if(c&&h)pe={start_date:c,end_date:h};else{const vn=new Date(C);vn.setDate(vn.getDate()-7);const mu=vn.getFullYear(),Wd=String(vn.getMonth()+1).padStart(2,"0"),Jd=String(vn.getDate()).padStart(2,"0");pe={start_date:`${mu}-${Wd}-${Jd}`,end_date:me}}break;default:const Sr=new Date(C);Sr.setDate(Sr.getDate()-7);const pn=Sr.getFullYear(),fi=String(Sr.getMonth()+1).padStart(2,"0"),Rn=String(Sr.getDate()).padStart(2,"0");pe={start_date:`${pn}-${fi}-${Rn}`,end_date:me}}const be=$(M,C);be&&kj(be).then(y).catch(console.error),kj(pe).then(n).catch(console.error)},$=(M,C)=>{switch(C.getFullYear(),String(C.getMonth()+1).padStart(2,"0"),String(C.getDate()).padStart(2,"0"),M){case"today":const U=new Date(C);U.setDate(U.getDate()-1);const ee=U.getFullYear(),le=String(U.getMonth()+1).padStart(2,"0"),me=String(U.getDate()).padStart(2,"0");return{start_date:`${ee}-${le}-${me}`,end_date:`${ee}-${le}-${me}`};case"yesterday":const pe=new Date(C);pe.setDate(pe.getDate()-2);const be=pe.getFullYear(),Me=String(pe.getMonth()+1).padStart(2,"0"),J=String(pe.getDate()).padStart(2,"0");return{start_date:`${be}-${Me}-${J}`,end_date:`${be}-${Me}-${J}`};case"7days":const we=new Date(C);we.setDate(we.getDate()-7);const Oe=new Date(we);return Oe.setDate(Oe.getDate()-7),{start_date:`${Oe.getFullYear()}-${String(Oe.getMonth()+1).padStart(2,"0")}-${String(Oe.getDate()).padStart(2,"0")}`,end_date:`${we.getFullYear()}-${String(we.getMonth()+1).padStart(2,"0")}-${String(we.getDate()).padStart(2,"0")}`};case"30days":const ie=new Date(C);ie.setDate(ie.getDate()-30);const Ie=new Date(ie);return Ie.setDate(Ie.getDate()-30),{start_date:`${Ie.getFullYear()}-${String(Ie.getMonth()+1).padStart(2,"0")}-${String(Ie.getDate()).padStart(2,"0")}`,end_date:`${ie.getFullYear()}-${String(ie.getMonth()+1).padStart(2,"0")}-${String(ie.getDate()).padStart(2,"0")}`};default:return null}},Z=()=>{if(!r||!p)return null;const M=r.revenue_stats.total_amount,C=p.revenue_stats.total_amount;if(C===0)return M>0?"+100%":"0%";const U=(M-C)/C*100;return`${U>=0?"+":""}${U.toFixed(1)}%`};b.useEffect(()=>{_D().then(t).catch(console.error),R(l),id().then(M=>{P(M);const C={};M.forEach(U=>{C[U.item_id]=U.item_title||U.item_id}),z(C)}).catch(console.error)},[l]),b.useEffect(()=>{const{startDate:M,endDate:C}=X(l);A(!0),SD({start_date:M,end_date:C}).then(U=>{_(U)}).catch(console.error).finally(()=>A(!1))},[l]);const X=M=>{const C=new Date,U=C.toISOString().split("T")[0];let ee=U;if(M==="7days"){const le=new Date(C);le.setDate(le.getDate()-7),ee=le.toISOString().split("T")[0]}else if(M==="30days"){const le=new Date(C);le.setDate(le.getDate()-30),ee=le.toISOString().split("T")[0]}return{startDate:ee,endDate:U}};if(!e||!r)return f.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:f.jsx(xj,{className:"w-8 h-8 animate-spin text-[#0094f7]"})});const L=((te=r.daily_stats)==null?void 0:te.map(M=>({name:M.date.slice(5),amount:M.amount,orders:M.order_count,avgAmount:M.order_count>0?(M.amount/M.order_count).toFixed(2):0})))||[],K=r.item_stats||[],se=r.revenue_stats.total_orders||0,ce=r.revenue_stats.total_amount||0,he=K.length>0?K.map(M=>({name:(k[M.item_id]||M.item_id).length>12?(k[M.item_id]||M.item_id).substring(0,12)+"...":k[M.item_id]||M.item_id,sales:M.order_count})).sort((M,C)=>C.sales-M.sales).slice(0,10):[],q=K.length>0?K.map(M=>({name:(k[M.item_id]||M.item_id).length>10?(k[M.item_id]||M.item_id).substring(0,10)+"...":k[M.item_id]||M.item_id,value:M.order_count,percent:se>0?M.order_count/se*100:0})).sort((M,C)=>C.value-M.value).slice(0,6).map((M,C)=>({...M,color:T[C%T.length]})):[],W=K.length>0?K.map(M=>({name:(k[M.item_id]||M.item_id).length>12?(k[M.item_id]||M.item_id).substring(0,12)+"...":k[M.item_id]||M.item_id,value:M.total_amount,orderCount:M.order_count,percentage:ce>0?M.total_amount/ce*100:0})).sort((M,C)=>C.value-M.value).slice(0,5).map((M,C)=>({...M,color:T[C%T.length],percentage:M.percentage.toFixed(1)})):[],ue=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}];return f.jsxs("div",{className:"space-y-8 animate-fade-in",children:[f.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),f.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),f.jsx("div",{className:"flex items-center gap-3",children:f.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[f.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),f.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[ue.map(M=>f.jsx("button",{onClick:()=>s(M.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===M.key?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:M.label},M.key)),l==="custom"&&f.jsxs(f.Fragment,{children:[f.jsx("input",{type:"date",value:c,onChange:M=>d(M.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),f.jsx("span",{className:"self-center text-gray-400",children:"-"}),f.jsx("input",{type:"date",value:h,onChange:M=>m(M.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),f.jsx("button",{onClick:()=>R("custom"),className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),f.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[f.jsx(Fc,{title:"累计营收 (CNY)",value:`¥${r.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:iT,colorClass:"bg-blue-400",trend:Z()||void 0}),f.jsx(Fc,{title:"活跃账号 / 总数",value:`${e.active_cookies} / ${e.total_cookies}`,icon:FO,colorClass:"bg-blue-500"}),f.jsx(Fc,{title:"订单数",value:r.revenue_stats.total_orders.toLocaleString(),icon:Ej,colorClass:"bg-blue-500"}),f.jsx(Fc,{title:"库存卡密余量",value:e.total_cards,icon:GO,colorClass:"bg-purple-500"})]}),f.jsxs("div",{className:"ios-card p-8 rounded-[2rem]",children:[f.jsxs("div",{className:"mb-10",children:[f.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),f.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"最近7天的销售额走势"})]}),f.jsx("div",{className:"h-[350px] w-full",children:L.length===0||r.revenue_stats.total_amount===0?f.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[f.jsx(Ej,{className:"w-16 h-16 mb-4 opacity-20"}),f.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),f.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):L.length<=2?f.jsx(ps,{width:"100%",height:"100%",children:f.jsxs(DO,{data:L,margin:{top:30,right:20,left:-20,bottom:30},barCategoryGap:30,children:[f.jsx(af,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#374151",fontSize:14,fontWeight:600},dy:10}),f.jsx(lf,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},tickFormatter:M=>`¥${M}`}),f.jsx(Gc,{contentStyle:{backgroundColor:"#1F2937",borderRadius:"16px",border:"none",boxShadow:"0 20px 40px rgba(0, 0, 0, 0.3)",padding:"12px 16px"},itemStyle:{color:"#0094f7",fontWeight:600},formatter:M=>`营收: ¥${Number(M).toFixed(2)}`}),f.jsx(t0,{dataKey:"amount",fill:"#0094f7",radius:[12,12,0,0],stroke:"#000000",strokeWidth:0,children:L.map((M,C)=>f.jsx(qi,{fill:["#0094f7","#FCD34D","#0071e3"][C%3]},`cell-${C}`))})]})}):f.jsx(ps,{width:"100%",height:"100%",children:f.jsxs(gF,{data:L,margin:{top:10,right:10,left:-20,bottom:0},children:[f.jsx("defs",{children:f.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[f.jsx("stop",{offset:"5%",stopColor:"#0094f7",stopOpacity:.5}),f.jsx("stop",{offset:"95%",stopColor:"#0094f7",stopOpacity:0})]})}),f.jsx(af,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},dy:15}),f.jsx(lf,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500}}),f.jsx(Wy,{vertical:!1,stroke:"#F3F4F6",strokeDasharray:"3 3"}),f.jsx(Gc,{contentStyle:{background:"#1A1A1A",borderRadius:"16px",border:"none",boxShadow:"0 10px 40px rgba(0,0,0,0.2)"},itemStyle:{color:"#0094f7",fontWeight:600},labelStyle:{color:"#888"},cursor:{stroke:"#0094f7",strokeWidth:2,strokeDasharray:"4 4"}}),f.jsx(L4,{type:"monotone",dataKey:"amount",stroke:"#FACC15",strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:"#1A1A1A",stroke:"#0094f7",strokeWidth:2}})]})})})]}),f.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[f.jsxs("div",{className:"ios-card p-6 rounded-[2rem]",children:[f.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),f.jsx("div",{className:"h-[280px]",children:he.length===0?f.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):f.jsx(ps,{width:"100%",height:"100%",children:f.jsxs(DO,{data:he,layout:"vertical",children:[f.jsx(Wy,{strokeDasharray:"3 3",horizontal:!0,vertical:!1,stroke:"#f0f0f0"}),f.jsx(af,{type:"number",axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:12}}),f.jsx(lf,{type:"category",dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#6B7280",fontSize:12},width:100}),f.jsx(Gc,{contentStyle:{backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"}}),f.jsx(t0,{dataKey:"sales",fill:"#000000",radius:[0,8,8,0]})]})})})]}),f.jsxs("div",{className:"ios-card p-6 rounded-[2rem]",children:[f.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),f.jsx("div",{className:"h-[280px]",children:q.length===0?f.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):f.jsx(ps,{width:"100%",height:"100%",children:f.jsxs(RO,{children:[f.jsx(Qy,{data:q,cx:"50%",cy:"50%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",label:({name:M,percent:C})=>`${M} ${(C*100).toFixed(0)}%`,labelLine:!1,children:q.map((M,C)=>f.jsx(qi,{fill:M.color},`cell-${C}`))}),f.jsx(PE,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:M=>f.jsx("span",{style:{color:"#6B7280",fontWeight:500},children:M})})]})})})]})]}),f.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[f.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-[2rem] border-0 bg-white overflow-hidden flex flex-col",children:[f.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]",children:[f.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),f.jsx("div",{className:"relative",children:f.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:x,onChange:M=>w(M.target.value),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),f.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:N?f.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[f.jsx(xj,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):j.filter(M=>{var C,U,ee;return((C=M.order_id)==null?void 0:C.toLowerCase().includes(x.toLowerCase()))||((U=M.item_id)==null?void 0:U.toLowerCase().includes(x.toLowerCase()))||((ee=M.buyer_id)==null?void 0:ee.toLowerCase().includes(x.toLowerCase()))}).length===0?f.jsx("div",{className:"flex items-center justify-center py-20 text-gray-400",children:"暂无订单数据"}):f.jsxs("table",{className:"w-full text-left border-collapse",children:[f.jsx("thead",{children:f.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[f.jsx("th",{className:"px-6 py-4",children:"订单信息"}),f.jsx("th",{className:"px-6 py-4",children:"买家信息"}),f.jsx("th",{className:"px-6 py-4",children:"金额"}),f.jsx("th",{className:"px-6 py-4",children:"状态"}),f.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),f.jsx("tbody",{className:"divide-y divide-gray-50",children:j.filter(M=>{var C,U,ee;return((C=M.order_id)==null?void 0:C.toLowerCase().includes(x.toLowerCase()))||((U=M.item_id)==null?void 0:U.toLowerCase().includes(x.toLowerCase()))||((ee=M.buyer_id)==null?void 0:ee.toLowerCase().includes(x.toLowerCase()))}).map(M=>f.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[f.jsx("td",{className:"px-6 py-4",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:f.jsx(ny,{className:"w-full h-full text-gray-300 p-2"})}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:M.item_title||M.item_id||"未知商品"}),f.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:M.order_id}),f.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",M.quantity||1]})]})]})}),f.jsxs("td",{className:"px-6 py-4",children:[f.jsx("div",{className:"text-sm font-bold text-gray-800",children:M.buyer_id}),M.created_at&&f.jsx("div",{className:"text-xs text-gray-400 mt-1",children:M.created_at})]}),f.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",M.amount||"0.00"]}),f.jsx("td",{className:"px-6 py-4",children:f.jsx(xF,{status:M.status||M.order_status||"unknown"})}),f.jsx("td",{className:"px-6 py-4 text-right",children:f.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${M.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:f.jsx(YO,{className:"w-4 h-4"})})})]},M.order_id))})]})})]}),f.jsxs("div",{className:"ios-card p-6 rounded-[2rem] bg-white",children:[f.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),W.length===0?f.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"h-[300px] relative",children:f.jsx(ps,{width:"100%",height:"100%",children:f.jsxs(RO,{children:[f.jsx(Qy,{data:W,cx:"50%",cy:"50%",innerRadius:60,outerRadius:100,paddingAngle:2,dataKey:"value",label:({name:M,percent:C})=>`${M} ${(C*100).toFixed(0)}%`,children:W.map((M,C)=>f.jsx(qi,{fill:M.color||T[C%T.length]},`cell-${C}`))}),f.jsx(Gc,{contentStyle:{backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"},formatter:M=>`¥${M.toLocaleString()}`})]})})}),f.jsx("div",{className:"space-y-3 mt-4",children:W.map(M=>f.jsxs("div",{className:"flex justify-between items-center text-sm",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:M.color||T[W.indexOf(M)%T.length]}}),f.jsx("span",{className:"text-gray-600 font-medium",children:M.name})]}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs("span",{className:"font-bold text-gray-900",children:["¥",M.value.toLocaleString()]}),f.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[M.percentage,"%"]})]})]},M.name))})]})]})]})]})},bF=()=>{const[e,t]=b.useState([]),[r,n]=b.useState(!0),[l,s]=b.useState(!1),[c,d]=b.useState(""),[h,m]=b.useState("pending"),[p,y]=b.useState(""),[x,w]=b.useState(""),[j,_]=b.useState(""),[N,A]=b.useState(null),[O,P]=b.useState(null),[k,z]=b.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1}),[T,R]=b.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[$,Z]=b.useState(!1),X=async()=>{try{const M=await lD();t(C=>C.map(U=>{const ee=M[U.id];return ee?{...U,runtime_state:ee.state,runtime_message:ee.message||"",runtime_connected:ee.connected,runtime_updated_at:ee.updated_at}:U}))}catch(M){console.error("Failed to load account runtime statuses:",M)}},L=async()=>{n(!0);try{const M=await d0();let C={};try{C=await vD()}catch(ee){console.error("Failed to load AI settings:",ee)}const U=M.map(ee=>{var le,me,pe,be,Me;return{...ee,ai_enabled:((le=C[ee.id])==null?void 0:le.ai_enabled)??!1,max_discount_percent:((me=C[ee.id])==null?void 0:me.max_discount_percent)??10,max_discount_amount:((pe=C[ee.id])==null?void 0:pe.max_discount_amount)??100,max_bargain_rounds:((be=C[ee.id])==null?void 0:be.max_bargain_rounds)??3,custom_prompts:((Me=C[ee.id])==null?void 0:Me.custom_prompts)??""}});t(U),window.setTimeout(X,0)}catch(M){console.error("Failed to load accounts:",M)}finally{n(!1)}};b.useEffect(()=>{L();const M=window.setInterval(X,1e4);return()=>window.clearInterval(M)},[]);const K=M=>{if(!M.enabled||M.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(M.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"}}},se=async(M,C)=>{await uD(M,!C),L()},ce=async M=>{confirm("确认删除该账号吗?")&&(await cD(M),L())},he=M=>{P(M),z({remark:M.remark||M.note||"",cookie:M.cookie||M.value||"",auto_confirm:M.auto_confirm||!1,pause_duration:M.pause_duration||0,username:M.username||"",login_password:M.login_password||"",show_browser:M.show_browser||!1,showLoginPassword:!1}),A("edit")},q=async M=>{P(M),Z(!0);try{const C=await qD(M.id);R({ai_enabled:C.ai_enabled??!1,max_discount_percent:C.max_discount_percent??10,max_discount_amount:C.max_discount_amount??100,max_bargain_rounds:C.max_bargain_rounds??3,custom_prompts:C.custom_prompts??""})}catch(C){console.error("Failed to load AI settings:",C)}finally{Z(!1)}A("ai-settings")},W=async()=>{if(O){Z(!0);try{const M=[];k.remark!==(O.remark||O.note||"")&&M.push(fD(O.id,k.remark)),k.cookie&&k.cookie!==(O.cookie||O.value||"")&&M.push(mD(O.id,k.cookie)),k.auto_confirm!==O.auto_confirm&&M.push(dD(O.id,k.auto_confirm)),k.pause_duration!==(O.pause_duration||0)&&M.push(hD(O.id,k.pause_duration)),(k.username!==(O.username||"")||k.login_password!==(O.login_password||"")||k.show_browser!==(O.show_browser||!1))&&M.push(pD(O.id,{username:k.username,login_password:k.login_password,show_browser:k.show_browser})),await Promise.all(M),A(null),L()}catch(M){console.error("更新账号失败:",M),alert("更新失败,请重试")}finally{Z(!1)}}},ue=async()=>{if(O){Z(!0);try{await UD(O.id,T),A(null),L()}catch(M){console.error("更新AI设置失败:",M),alert("更新失败,请重试")}finally{Z(!1)}}},te=async()=>{s(!0),m("loading");try{const M=await oD();if(M.success&&M.qr_code_url&&M.session_id){d(M.qr_code_url),_(M.session_id),m("waiting");const C=setInterval(async()=>{const U=await sD(M.session_id);if(U.status==="success"){if(clearInterval(C),m("success"),U.cookies&&U.unb)try{await aD(U.unb,U.cookies)}catch(ee){console.error("保存扫码账号失败",ee)}setTimeout(()=>{s(!1),L()},1e3)}else U.status==="scanned"?m("waiting"):U.status==="expired"||U.status==="cancelled"||U.status==="error"||U.status==="not_found"?(clearInterval(C),m("error")):U.status==="verification_required"&&(m("verification"),y(U.verification_url||""),U.verification_screenshot&&w(U.verification_screenshot))},2e3)}}catch{m("error")}};return r?f.jsx("div",{className:"p-20 flex justify-center",children:f.jsx(Wa,{className:"w-8 h-8 text-[#0094f7] animate-spin"})}):f.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[f.jsxs("div",{className:"flex justify-between items-end",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),f.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。"})]}),f.jsxs("button",{onClick:te,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[f.jsx(Aj,{className:"w-5 h-5"}),"扫码添加新账号"]})]}),f.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[e.map(M=>{const C=K(M),U=M.runtime_state==="auth_expired"||M.runtime_state==="verification_required";return f.jsxs("div",{className:"ios-card p-6 rounded-[2rem] flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300",children:[f.jsxs("div",{className:"flex items-center gap-5 sm:gap-8 min-w-0",children:[f.jsxs("div",{className:"relative",children:[M.avatar_url?f.jsx("img",{src:M.avatar_url,alt:M.nickname||"账号头像",className:"w-20 h-20 rounded-3xl object-cover shadow-md ring-4 ring-white bg-gray-100"}):f.jsx("div",{className:"w-20 h-20 rounded-3xl bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:f.jsx(iy,{className:"w-9 h-9"})}),f.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${C.dot}`,children:M.runtime_state==="online"&&f.jsx(Zc,{className:"w-3 h-3 text-white"})})]}),f.jsxs("div",{className:"min-w-0",children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-1",children:[f.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:M.nickname||M.remark||`账号 ${M.id.substring(0,6)}...`}),f.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${C.badge}`,children:C.label}),M.ai_enabled&&f.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:[f.jsx(ra,{className:"w-3 h-3"})," AI"]}),M.profile_error&&f.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:M.profile_error,children:[f.jsx(wj,{className:"w-3 h-3"})," 资料未同步"]})]}),f.jsx("p",{className:"text-sm text-gray-500 font-medium mb-3",children:M.remark||M.note||"暂无备注"}),M.runtime_message&&M.runtime_state!=="online"&&M.runtime_state!=="disabled"&&f.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${U?"text-red-700":"text-amber-700"}`,children:[f.jsx(wj,{className:"w-4 h-4 flex-shrink-0"}),f.jsx("span",{children:M.runtime_message}),U&&f.jsxs("button",{type:"button",onClick:te,className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[f.jsx(Aj,{className:"w-3.5 h-3.5"})," 重新扫码登录"]})]}),f.jsxs("div",{className:"flex gap-2",children:[M.auto_confirm&&f.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[f.jsx(Fa,{className:"w-3 h-3"})," 自动回复"]}),M.pause_duration>0&&f.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[f.jsx(jj,{className:"w-3 h-3"})," 暂停",M.pause_duration,"分钟"]})]})]})]}),f.jsxs("div",{className:"flex items-center gap-3 self-end lg:self-auto flex-shrink-0",children:[f.jsx("button",{onClick:()=>he(M),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:f.jsx(Qc,{className:"w-5 h-5"})}),f.jsx("button",{onClick:()=>q(M),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:f.jsx(ra,{className:"w-5 h-5"})}),f.jsx("button",{onClick:()=>se(M.id,M.enabled),className:`p-3 rounded-xl transition-colors ${M.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:M.enabled?"停用账号":"启用账号",children:f.jsx(ay,{className:"w-5 h-5"})}),f.jsx("button",{onClick:()=>ce(M.id),className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500",children:f.jsx(ei,{className:"w-5 h-5"})})]})]},M.id)}),e.length===0&&f.jsxs("div",{className:"ios-card p-12 text-center",children:[f.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:f.jsx(iy,{className:"w-10 h-10 text-gray-400"})}),f.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),f.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]})]}),l&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container relative",style:{maxWidth:"24rem"},children:[f.jsx("button",{onClick:()=>s(!1),className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:f.jsx(gr,{className:"w-5 h-5 text-gray-600"})}),f.jsx("div",{className:"modal-body",children:f.jsxs("div",{className:"text-center",children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:"扫码登录"}),f.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:"请打开闲鱼APP扫描下方二维码"}),f.jsxs("div",{className:"w-64 h-64 bg-[#F7F8FA] rounded-[2rem] mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-8 relative",children:[h==="loading"&&f.jsx(Wa,{className:"w-10 h-10 text-[#0094f7] animate-spin"}),h==="waiting"&&f.jsx("img",{src:c,alt:"QR Code",className:"w-full h-full p-2"}),h==="success"&&f.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[f.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:f.jsx(Zc,{className:"w-8 h-8"})}),f.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),h==="error"&&f.jsxs("div",{className:"flex flex-col items-center",children:[f.jsx("span",{className:"text-red-500 font-bold mb-2",children:"获取失败"}),f.jsxs("button",{onClick:te,className:"text-xs bg-gray-200 px-3 py-1 rounded-full flex items-center gap-1 hover:bg-gray-300",children:[f.jsx(la,{className:"w-3 h-3"})," 重试"]})]}),h==="verification"&&f.jsxs("div",{className:"flex flex-col items-center px-4",children:[f.jsx("span",{className:"font-bold text-gray-900 mb-2",children:"需要安全验证"}),f.jsx("span",{className:"text-xs text-gray-500 mb-3 text-center",children:"程序已在后台打开验证页面,请用手机完成验证,验证通过后将自动登录。"}),x?f.jsx("img",{src:x,alt:"验证页面",className:"w-full rounded-xl border mb-2",style:{maxHeight:200,objectFit:"contain"}}):f.jsx("div",{className:"w-full h-32 bg-gray-100 rounded-xl flex items-center justify-center mb-2",children:f.jsx(Wa,{className:"w-6 h-6 animate-spin text-gray-400"})}),f.jsx("span",{className:"text-xs text-gray-400",children:"等待手机验证完成,无需手动操作..."})]})]}),f.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),N==="edit"&&O&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[f.jsxs("div",{className:"modal-header",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),f.jsx("p",{className:"text-sm text-gray-500 mt-1",children:O.nickname||O.remark||O.id})]}),f.jsx("button",{onClick:()=>A(null),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:f.jsx(gr,{className:"w-5 h-5 text-gray-500"})})]}),f.jsxs("div",{className:"modal-body space-y-6",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),f.jsx("input",{type:"text",value:O.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),f.jsx("input",{type:"text",value:k.remark,onChange:M=>z({...k,remark:M.target.value}),placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),f.jsx("textarea",{value:k.cookie,onChange:M=>z({...k,cookie:M.target.value}),placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),f.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",k.cookie.length," 字符"]})]}),f.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[f.jsxs("div",{children:[f.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[f.jsx(Zc,{className:"w-4 h-4 text-green-500"}),"自动确认收货"]}),f.jsx("div",{className:"text-xs text-gray-500",children:"自动点击确认收货按钮"})]}),f.jsx("button",{type:"button",onClick:()=>z({...k,auto_confirm:!k.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${k.auto_confirm?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${k.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),f.jsxs("div",{children:[f.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[f.jsx(jj,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),f.jsx("input",{type:"number",value:k.pause_duration,onChange:M=>z({...k,pause_duration:parseInt(M.target.value)||0}),placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"})]}),f.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[f.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[f.jsx(ry,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),f.jsx("input",{type:"text",value:k.username,onChange:M=>z({...k,username:M.target.value}),placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),f.jsxs("div",{className:"relative",children:[f.jsx("input",{type:k.showLoginPassword?"text":"password",value:k.login_password,onChange:M=>z({...k,login_password:M.target.value}),placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),f.jsx("button",{type:"button",onClick:()=>z({...k,showLoginPassword:!k.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:k.showLoginPassword?f.jsx(Ns,{className:"w-5 h-5"}):f.jsx(Xl,{className:"w-5 h-5"})})]})]}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),f.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),f.jsx("button",{type:"button",onClick:()=>z({...k,show_browser:!k.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${k.show_browser?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${k.show_browser?"translate-x-6":"translate-x-0"}`})})]})]})]})]}),f.jsx("div",{className:"modal-footer",children:f.jsxs("div",{className:"flex gap-3 w-full",children:[f.jsx("button",{onClick:()=>A(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:$,children:"取消"}),f.jsxs("button",{onClick:W,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:$,children:[$?f.jsx(Wa,{className:"w-4 h-4 animate-spin"}):f.jsx(oa,{className:"w-4 h-4"}),$?"保存中...":"保存"]})]})})]})}),document.body),N==="ai-settings"&&O&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[f.jsxs("div",{className:"modal-header",children:[f.jsxs("div",{children:[f.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[f.jsx(ra,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),f.jsx("p",{className:"text-sm text-gray-500 mt-1",children:O.nickname||O.remark||O.id})]}),f.jsx("button",{onClick:()=>A(null),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:f.jsx(gr,{className:"w-5 h-5 text-gray-500"})})]}),f.jsxs("div",{className:"modal-body space-y-6",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[f.jsxs("div",{children:[f.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[f.jsx(ra,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),f.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),f.jsx("button",{type:"button",onClick:()=>R({...T,ai_enabled:!T.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${T.ai_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${T.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),f.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[f.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),f.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),f.jsx("input",{type:"number",value:T.max_discount_percent,onChange:M=>R({...T,max_discount_percent:parseInt(M.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10表示最多降价10%"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),f.jsx("input",{type:"number",value:T.max_discount_amount,onChange:M=>R({...T,max_discount_amount:parseInt(M.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100表示最多降价100元"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),f.jsx("input",{type:"number",value:T.max_bargain_rounds,onChange:M=>R({...T,max_bargain_rounds:parseInt(M.target.value)||1}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),f.jsx("textarea",{value:T.custom_prompts,onChange:M=>R({...T,custom_prompts:M.target.value}),placeholder:`输入自定义的AI回复规则或风格指引... + +例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),f.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[f.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[f.jsx(u0,{className:"w-4 h-4"}),"AI如何工作"]}),f.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[f.jsx("li",{children:"• 自动识别买家的砍价请求"}),f.jsx("li",{children:"• 根据设定的策略智能回复"}),f.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),f.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),f.jsx("div",{className:"modal-footer",children:f.jsxs("div",{className:"flex gap-3 w-full",children:[f.jsx("button",{onClick:()=>A(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:$,children:"取消"}),f.jsxs("button",{onClick:ue,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:$,children:[$?f.jsx(Wa,{className:"w-4 h-4 animate-spin"}):f.jsx(oa,{className:"w-4 h-4"}),$?"保存中...":"保存"]})]})})]})}),document.body)]})},IO=({status:e})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600"},r={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return f.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[e]||t.cancelled}`,children:r[e]||e})},wF=()=>{const[e,t]=b.useState([]),[r,n]=b.useState([]),[l,s]=b.useState([]),[c,d]=b.useState({}),[h,m]=b.useState("all"),[p,y]=b.useState(""),[x,w]=b.useState(1),[j,_]=b.useState(1),[N,A]=b.useState(!1),[O,P]=b.useState(!1),[k,z]=b.useState(!1),[T,R]=b.useState(!1),[$,Z]=b.useState(null),[X,L]=b.useState(null),[K,se]=b.useState({}),[ce,he]=b.useState(!1),[q,W]=b.useState(""),[ue,te]=b.useState(!1),[M,C]=b.useState(null),[U,ee]=b.useState(null),[le,me]=b.useState(null),[pe,be]=b.useState(null),Me=D=>{if(!p.trim())return D;const oe=p.toLowerCase().trim();return D.filter(fe=>{var Pe,Sr,pn,fi,Rn,vn;return((Pe=fe.order_id)==null?void 0:Pe.toLowerCase().includes(oe))||((Sr=fe.item_id)==null?void 0:Sr.toLowerCase().includes(oe))||((pn=fe.buyer_id)==null?void 0:pn.toLowerCase().includes(oe))||((fi=fe.item_title)==null?void 0:fi.toLowerCase().includes(oe))||((Rn=fe.receiver_name)==null?void 0:Rn.toLowerCase().includes(oe))||((vn=fe.receiver_phone)==null?void 0:vn.toLowerCase().includes(oe))})},J=async()=>{A(!0);try{if(p.trim()){let D=[],oe=1,fe=!0;for(;fe;){const Pe=await Cj(void 0,h,oe,100);D=[...D,...Pe.data],fe=oe{t(Me(r))},[r,p]);const we=(D,oe)=>{if(oe&&oe.trim())return oe;if(c[D])return c[D];const fe=l.find(Pe=>{if(oe&&Pe.item_title){const Sr=oe.toLowerCase(),pn=Pe.item_title.toLowerCase();return pn.includes(Sr)||Sr.includes(pn)}return!1});return fe!=null&&fe.item_title?fe.item_title:"未知商品"},Oe=D=>{const oe={};D.forEach(fe=>{fe.item_id&&(oe[fe.item_id]=fe.item_title||fe.item_id)}),d(oe)};b.useEffect(()=>{J(),id().then(D=>{s(D),Oe(D)}).catch(D=>{console.error("加载商品列表失败:",D)})},[h,x,p]);const ie=async()=>{A(!0);try{const D=await xD();await J(),D!=null&&D.message&&alert(D.message)}catch(D){console.error("同步订单失败:",D),alert((D==null?void 0:D.message)||"同步失败,请重试")}finally{A(!1)}},Ie=D=>{W(D),C(null),he(!0)},_e=async D=>{var oe;te(!0),C(null);try{const fe=await wD([q],D),Pe=(oe=fe==null?void 0:fe.results)==null?void 0:oe[0];Pe!=null&&Pe.success?(C({success:!0,message:Pe.message}),J()):C({success:!1,message:(Pe==null?void 0:Pe.message)||"发货失败"})}catch(fe){C({success:!1,message:(fe==null?void 0:fe.message)||"请求失败"})}finally{te(!1)}},ct=D=>{Z(D),P(!0)},ft=D=>{L({...D}),z(!0)},ht=async()=>{if(!(!X||!X.order_id))try{const D={};X.status!==void 0&&(D.order_status=X.status),X.buyer_id!==void 0&&(D.buyer_id=X.buyer_id),X.amount!==void 0&&(D.amount=X.amount),X.receiver_name!==void 0&&(D.receiver_name=X.receiver_name),X.receiver_phone!==void 0&&(D.receiver_phone=X.receiver_phone),X.receiver_address!==void 0&&(D.receiver_address=X.receiver_address),X.item_id!==void 0&&(D.item_id=X.item_id),X.quantity!==void 0&&(D.quantity=X.quantity),await yD(X.order_id,D),z(!1),L(null),J()}catch(D){console.error("更新订单失败:",D),alert("更新失败,请重试")}},nn=async()=>{if(U)try{const D=new FormData;D.append("file",U),await jD(D),R(!1),ee(null),J(),alert("订单导入成功")}catch(D){alert((D==null?void 0:D.message)||"导入失败,请检查文件格式")}},Pn=async D=>{me(D);try{const oe=await bD(D);oe.success?await J():alert(oe.message||"同步失败")}catch(oe){console.error("同步订单失败:",oe),alert((oe==null?void 0:oe.message)||"同步失败,请重试")}finally{me(null)}},zn=async D=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){be(D);try{await gD(D),n(oe=>oe.filter(fe=>fe.order_id!==D))}catch(oe){console.error("删除订单失败:",oe),alert((oe==null?void 0:oe.message)||"删除失败,请重试"),await J()}finally{be(null)}}};return f.jsxs("div",{className:"space-y-6 animate-fade-in",children:[f.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),f.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("button",{onClick:J,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:f.jsx(la,{className:`w-5 h-5 ${N?"animate-spin":""}`})}),f.jsxs("button",{onClick:()=>R(!0),className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[f.jsx(Hi,{className:"w-4 h-4"}),"插入订单"]}),f.jsxs("button",{onClick:ie,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[f.jsx(Cs,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),f.jsxs("div",{className:"ios-card rounded-[2rem] overflow-hidden shadow-lg border-0 bg-white",children:[f.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-[#FAFAFA]",children:[f.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:[{k:"all",v:"全部"},{k:"shipped",v:"已发货"},{k:"pending_ship",v:"待发货"},{k:"cancelled",v:"已取消"},{k:"refunding",v:"其他"}].map(D=>f.jsx("button",{onClick:()=>{m(D.k),w(1),y("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${h===D.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:D.v},D.k))}),f.jsxs("div",{className:"relative w-full md:w-auto group",children:[f.jsx(RT,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors"}),f.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:D=>{y(D.target.value),w(1)},className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]}),f.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:f.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[f.jsx("thead",{children:f.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[f.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),f.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),f.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),f.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),f.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),f.jsx("tbody",{className:"divide-y divide-gray-50",children:e.map(D=>f.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[f.jsx("td",{className:"px-6 py-5",children:f.jsxs("div",{className:"flex items-center gap-5",children:[f.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:D.item_image?f.jsx("img",{src:D.item_image,alt:"",className:"w-full h-full object-cover"}):f.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:f.jsx(ny,{})})}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:we(D.item_id,D.item_title)}),f.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",D.order_id]}),f.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",D.quantity," • ",D.created_at]})]})]})}),f.jsx("td",{className:"px-6 py-5",children:f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),f.jsx("div",{className:"text-sm font-bold text-gray-800",children:D.buyer_id}),D.receiver_name&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),f.jsx("div",{className:"text-xs text-gray-600",children:D.receiver_name})]}),D.receiver_phone&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),f.jsx("div",{className:"text-xs text-gray-600 font-mono",children:D.receiver_phone})]}),D.receiver_address&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),f.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:D.receiver_address})]})]})}),f.jsxs("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",D.amount]}),f.jsx("td",{className:"px-6 py-5",children:f.jsx(IO,{status:D.status})}),f.jsxs("td",{className:"px-6 py-5 text-right",children:[D.status==="pending_ship"&&f.jsx("button",{onClick:()=>Ie(D.order_id),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),f.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${D.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:f.jsx(YO,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>ct(D),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:f.jsx(Xl,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>ft(D),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:f.jsx(f0,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>Pn(D.order_id),disabled:le===D.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:f.jsx(la,{className:`w-4 h-4 ${le===D.order_id?"animate-spin":""}`})}),f.jsx("button",{onClick:()=>zn(D.order_id),disabled:pe===D.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:f.jsx(ei,{className:"w-4 h-4"})})]})]},D.id))})]})}),f.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[f.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",x," 页 / 共 ",j," 页"]}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{disabled:x<=1,onClick:()=>w(D=>D-1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:f.jsx(FM,{className:"w-5 h-5"})}),f.jsx("button",{disabled:x>=j,onClick:()=>w(D=>D+1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:f.jsx(QM,{className:"w-5 h-5"})})]})]})]}),O&&$&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",children:[f.jsx("div",{className:"modal-header",children:f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),f.jsx("button",{onClick:()=>P(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:f.jsx(gr,{className:"w-5 h-5 text-gray-600"})})]})}),f.jsxs("div",{className:"modal-body space-y-6",children:[f.jsxs("div",{className:"space-y-4",children:[f.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),f.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),f.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:$.order_id})]}),f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),f.jsx(IO,{status:$.status})]}),f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),f.jsxs("div",{className:"text-lg font-extrabold text-gray-900",children:["¥",$.amount]})]}),f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),f.jsx("div",{className:"font-bold text-gray-900",children:$.quantity})]}),f.jsxs("div",{className:"col-span-2",children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),f.jsx("div",{className:"text-sm font-medium text-gray-700",children:$.created_at})]})]})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),f.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[$.item_image&&f.jsx("img",{src:$.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),f.jsxs("div",{className:"flex-1",children:[f.jsx("div",{className:"font-bold text-gray-900 mb-1",children:we($.item_id,$.item_title)}),f.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",$.item_id]}),$.item_price&&f.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",$.item_price]})]})]})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),f.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),f.jsx("div",{className:"font-bold text-gray-900",children:$.buyer_id})]}),$.receiver_name&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),f.jsx("div",{className:"font-medium text-gray-700",children:$.receiver_name})]}),$.receiver_phone&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),f.jsx("div",{className:"font-mono text-sm text-gray-700",children:$.receiver_phone})]}),$.receiver_address&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),f.jsx("div",{className:"text-sm text-gray-700",children:$.receiver_address})]})]})]})]}),f.jsx("div",{className:"modal-footer",children:f.jsxs("div",{className:"flex gap-3 w-full",children:[f.jsx("button",{onClick:()=>P(!1),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),$.status==="pending_ship"&&f.jsx("button",{onClick:()=>{P(!1),Ie($.order_id)},className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),T&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",children:[f.jsx("div",{className:"modal-header",children:f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),f.jsx("button",{onClick:()=>R(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:f.jsx(gr,{className:"w-5 h-5 text-gray-600"})})]})}),f.jsxs("div",{className:"modal-body space-y-5",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),f.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:D=>{var oe;return ee(((oe=D.target.files)==null?void 0:oe[0])||null)},className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),f.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),U&&f.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(XT,{className:"w-4 h-4 text-blue-600"}),f.jsx("span",{className:"text-sm font-medium text-blue-900",children:U.name})]})})]}),f.jsx("div",{className:"modal-footer",children:f.jsxs("div",{className:"flex gap-3 w-full",children:[f.jsx("button",{onClick:()=>R(!1),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),f.jsx("button",{onClick:nn,disabled:!U,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:"导入订单"})]})})]})}),document.body),ce&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[f.jsx("div",{className:"modal-header",children:f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),f.jsx("button",{onClick:()=>{he(!1),C(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:f.jsx(gr,{className:"w-5 h-5 text-gray-600"})})]})}),f.jsxs("div",{className:"modal-body space-y-4",children:[f.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),f.jsx("button",{onClick:()=>_e("status_only"),disabled:ue,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:f.jsx(Cs,{className:"w-5 h-5 text-blue-600"})}),f.jsxs("div",{children:[f.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),f.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),f.jsx("button",{onClick:()=>_e("full_delivery"),disabled:ue,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-[#0094f7] hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:f.jsx(ny,{className:"w-5 h-5 text-blue-700"})}),f.jsxs("div",{children:[f.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),f.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),ue&&f.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[f.jsx(la,{className:"w-4 h-4 animate-spin text-gray-500"}),f.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),M&&f.jsxs("div",{className:`p-3 rounded-xl text-sm ${M.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[M.success?"✓ ":"✗ ",M.message]})]}),f.jsx("div",{className:"modal-footer",children:f.jsx("button",{onClick:()=>{he(!1),C(null)},className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:M!=null&&M.success?"完成":"取消"})})]})}),document.body),k&&X&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",children:[f.jsx("div",{className:"modal-header",children:f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),f.jsx("button",{onClick:()=>z(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:f.jsx(gr,{className:"w-5 h-5 text-gray-600"})})]})}),f.jsxs("div",{className:"modal-body space-y-5",children:[f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),f.jsx("input",{type:"text",value:X.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),f.jsxs("select",{value:X.status,onChange:D=>L({...X,status:D.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[f.jsx("option",{value:"processing",children:"处理中"}),f.jsx("option",{value:"pending_ship",children:"待发货"}),f.jsx("option",{value:"shipped",children:"已发货"}),f.jsx("option",{value:"completed",children:"已完成"}),f.jsx("option",{value:"cancelled",children:"已取消"}),f.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),f.jsx("input",{type:"text",value:X.buyer_id,onChange:D=>L({...X,buyer_id:D.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),f.jsx("input",{type:"number",value:X.amount,onChange:D=>L({...X,amount:parseFloat(D.target.value)}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),f.jsx("input",{type:"text",value:X.receiver_name||"",onChange:D=>L({...X,receiver_name:D.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),f.jsx("input",{type:"text",value:X.receiver_phone||"",onChange:D=>L({...X,receiver_phone:D.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),f.jsx("textarea",{value:X.receiver_address||"",onChange:D=>L({...X,receiver_address:D.target.value}),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),f.jsx("input",{type:"text",value:X.item_title||"",onChange:D=>L({...X,item_title:D.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),f.jsx("div",{className:"modal-footer",children:f.jsxs("div",{className:"flex gap-3 w-full",children:[f.jsx("button",{onClick:()=>z(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),f.jsxs("button",{onClick:ht,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[f.jsx(oa,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},$O=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),jF=()=>{const[e,t]=b.useState([]),[r,n]=b.useState(!1),[l,s]=b.useState(!1),[c,d]=b.useState(null),[h,m]=b.useState({}),[p,y]=b.useState($O);b.useEffect(()=>{Gl().then(t)},[]);const x=({type:O})=>{switch(O){case"text":return f.jsx(Sj,{className:"w-5 h-5 text-blue-500"});case"image":return f.jsx(Nj,{className:"w-5 h-5 text-purple-500"});case"api":return f.jsx(_j,{className:"w-5 h-5 text-blue-500"});default:return f.jsx(ty,{className:"w-5 h-5 text-gray-500"})}},w=O=>{var P,k,z,T,R;d(O),m({id:O.id,name:O.name||"",type:O.type||"text",api_url:((P=O.api_config)==null?void 0:P.url)||"",api_method:((k=O.api_config)==null?void 0:k.method)||"GET",api_timeout:((z=O.api_config)==null?void 0:z.timeout)||10,api_headers:((T=O.api_config)==null?void 0:T.headers)||"",api_params:((R=O.api_config)==null?void 0:R.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}),n(!0)},j=async()=>{var O,P,k,z,T,R,$,Z;if(c){if(!((O=h.name)!=null&&O.trim())){alert("请输入卡密名称");return}if(!h.type){alert("请选择卡密类型");return}try{const X={name:h.name.trim(),type:h.type,description:(P=h.description)==null?void 0:P.trim(),delay_seconds:h.delay_seconds||0,enabled:h.enabled??!0};h.type==="api"?X.api_config={url:(k=h.api_url)==null?void 0:k.trim(),method:h.api_method,timeout:h.api_timeout||10,headers:((z=h.api_headers)==null?void 0:z.trim())||void 0,params:((T=h.api_params)==null?void 0:T.trim())||void 0}:h.type==="text"?X.text_content=((R=h.text_content)==null?void 0:R.trim())||"":h.type==="data"?X.data_content=(($=h.data_content)==null?void 0:$.trim())||"":h.type==="image"&&(X.image_url=((Z=h.image_url)==null?void 0:Z.trim())||""),await Mj(c.id,X),n(!1),Gl().then(t)}catch(X){console.error("更新卡密失败:",X),alert("更新失败,请重试")}}},_=async O=>{if(confirm("确认删除该卡密吗?"))try{await AD(O),Gl().then(t)}catch(P){console.error("删除卡密失败:",P),alert("删除失败,请重试")}},N=async()=>{if(!p.name.trim()){alert("请输入卡密名称");return}if(!p.content.trim()){alert(p.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const O={name:p.name.trim(),type:p.type,description:p.description.trim(),enabled:p.enabled,delay_seconds:p.delay_seconds};p.type==="text"&&(O.text_content=p.content.trim()),p.type==="data"&&(O.data_content=p.content.trim()),p.type==="image"&&(O.image_url=p.content.trim()),p.type==="api"&&(O.api_config={url:p.content.trim(),method:p.api_method,timeout:p.api_timeout,headers:p.api_headers.trim()||void 0,params:p.api_params.trim()||void 0}),await OD(O),s(!1),y($O()),Gl().then(t)}catch(O){console.error("添加卡密失败:",O),alert("添加失败,请重试")}},A=async O=>{try{await Mj(O.id,{...O,enabled:!O.enabled}),Gl().then(t)}catch(P){console.error("切换状态失败:",P)}};return f.jsxs("div",{className:"space-y-6 animate-fade-in",children:[f.jsxs("div",{className:"flex justify-between items-center",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"卡密库存"}),f.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"管理自动发货的卡密、链接或图片资源。"})]}),f.jsxs("button",{onClick:()=>s(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[f.jsx(Hi,{className:"w-5 h-5"}),"添加新卡密"]})]}),f.jsxs("div",{className:"ios-card rounded-[2rem] overflow-hidden shadow-lg border-0 bg-white",children:[f.jsx("div",{className:"overflow-x-auto",children:f.jsxs("table",{className:"w-full text-left border-collapse",children:[f.jsx("thead",{children:f.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[f.jsx("th",{className:"px-8 py-5 w-[15%]",children:"卡密名称"}),f.jsx("th",{className:"px-6 py-5 w-[12%]",children:"类型"}),f.jsx("th",{className:"px-6 py-5 w-[25%]",children:"内容/库存"}),f.jsx("th",{className:"px-6 py-5 w-[20%]",children:"描述"}),f.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),f.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),f.jsx("tbody",{className:"divide-y divide-gray-50",children:e.map(O=>{let P="";return O.type==="data"&&O.data_content?P=`库存: ${O.data_content.split(` +`).filter(z=>z.trim()).length} 条`:O.type==="text"&&O.text_content?P=O.text_content.substring(0,20)+(O.text_content.length>20?"...":""):O.type==="api"&&O.api_config?P=O.api_config.url:O.type==="image"&&O.image_url&&(P="图片链接"),f.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[f.jsx("td",{className:"px-8 py-5",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:f.jsx(x,{type:O.type})}),f.jsx("span",{className:"font-bold text-gray-900",children:O.name})]})}),f.jsx("td",{className:"px-6 py-5",children:f.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${O.type==="text"?"bg-blue-50 text-blue-600":O.type==="data"?"bg-purple-50 text-purple-600":O.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:O.type==="text"?"文本":O.type==="data"?"批量":O.type==="api"?"API":"图片"})}),f.jsx("td",{className:"px-6 py-5",children:f.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:P,children:P})}),f.jsx("td",{className:"px-6 py-5",children:f.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:O.description||"-",children:O.description||"-"})}),f.jsx("td",{className:"px-6 py-5",children:f.jsx("button",{onClick:()=>A(O),className:`w-12 h-8 rounded-full relative transition-colors ${O.enabled?"bg-green-500":"bg-gray-300"}`,children:f.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${O.enabled?"left-5":"left-1"}`})})}),f.jsx("td",{className:"px-6 py-5",children:f.jsxs("div",{className:"flex items-center justify-end gap-2",children:[f.jsx("button",{onClick:()=>w(O),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:f.jsx(f0,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>_(O.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:f.jsx(ei,{className:"w-5 h-5"})})]})})]},O.id)})})]})}),e.length===0&&f.jsxs("div",{className:"py-20 text-center text-gray-400",children:[f.jsx(GO,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),f.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),r&&c&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",children:[f.jsxs("div",{className:"modal-header",children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),f.jsx("button",{onClick:()=>n(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:f.jsx(gr,{className:"w-5 h-5 text-gray-500"})})]}),f.jsx("div",{className:"modal-body",children:f.jsxs("div",{className:"space-y-5",children:[f.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",f.jsx("span",{className:"text-red-500",children:"*"})]}),f.jsx("input",{type:"text",value:h.name||"",onChange:O=>m({...h,name:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),f.jsxs("select",{value:h.type||"text",onChange:O=>m({...h,type:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[f.jsx("option",{value:"",children:"请选择类型"}),f.jsx("option",{value:"text",children:"固定文字"}),f.jsx("option",{value:"data",children:"批量数据"}),f.jsx("option",{value:"api",children:"API接口"}),f.jsx("option",{value:"image",children:"图片"})]})]})]}),h.type==="api"&&f.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[f.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),f.jsx("input",{type:"url",value:h.api_url||"",onChange:O=>m({...h,api_url:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),f.jsxs("select",{value:h.api_method||"GET",onChange:O=>m({...h,api_method:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[f.jsx("option",{value:"GET",children:"GET"}),f.jsx("option",{value:"POST",children:"POST"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),f.jsx("input",{type:"number",value:h.api_timeout||10,onChange:O=>m({...h,api_timeout:parseInt(O.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),f.jsx("textarea",{value:h.api_headers||"",onChange:O=>m({...h,api_headers:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"Authorization": "Bearer token"}'})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),f.jsx("textarea",{value:h.api_params||"",onChange:O=>m({...h,api_params:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm",placeholder:'{"type": "card", "count": 1}'})]})]}),h.type==="text"&&f.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[f.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),f.jsx("textarea",{value:h.text_content||"",onChange:O=>m({...h,text_content:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),h.type==="data"&&f.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[f.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),f.jsx("textarea",{value:h.data_content||"",onChange:O=>m({...h,data_content:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个: +卡号1:密码1 +卡号2:密码2 +或者 +兑换码1 +兑换码2`}),f.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),f.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",f.jsx("span",{className:"font-bold text-blue-600",children:h.data_content?h.data_content.split(` +`).filter(O=>O.trim()).length:0})," 条"]})]})]}),h.type==="image"&&f.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[f.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),f.jsx("input",{type:"url",value:h.image_url||"",onChange:O=>m({...h,image_url:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),f.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),h.image_url&&f.jsxs("div",{className:"mt-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),f.jsx("img",{src:h.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:O=>{O.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("input",{type:"number",value:h.delay_seconds||0,onChange:O=>m({...h,delay_seconds:parseInt(O.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),f.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),f.jsxs("div",{children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),f.jsx("textarea",{value:h.description||"",onChange:O=>m({...h,description:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),f.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[f.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),f.jsx("button",{type:"button",onClick:()=>m({...h,enabled:!h.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${h.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${h.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),f.jsx("div",{className:"modal-footer",children:f.jsxs("div",{className:"flex gap-3 w-full",children:[f.jsx("button",{onClick:()=>n(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),f.jsxs("button",{onClick:j,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[f.jsx(oa,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),l&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[f.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),f.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),f.jsx("button",{onClick:()=>s(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:f.jsx(gr,{className:"w-5 h-5 text-gray-500"})})]}),f.jsx("div",{className:"modal-body",children:f.jsxs("div",{className:"space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),f.jsx("input",{type:"text",value:p.name,onChange:O=>y({...p,name:O.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),f.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[f.jsxs("button",{type:"button",onClick:()=>y({...p,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${p.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[f.jsx(ty,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),f.jsxs("button",{type:"button",onClick:()=>y({...p,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${p.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[f.jsx(Sj,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),f.jsxs("button",{type:"button",onClick:()=>y({...p,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${p.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[f.jsx(Nj,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]}),f.jsxs("button",{type:"button",onClick:()=>y({...p,type:"api",content:""}),className:`p-3 rounded-xl font-bold transition-all ${p.type==="api"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[f.jsx(_j,{className:"w-5 h-5 mx-auto mb-1"}),"API"]})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:p.type==="data"?"库存内容(一行一个)":p.type==="text"?"固定回复内容":p.type==="image"?"图片 URL":"API 地址"}),p.type==="api"?f.jsx("input",{type:"url",value:p.content,onChange:O=>y({...p,content:O.target.value}),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):p.type==="image"?f.jsx("input",{type:"url",value:p.content,onChange:O=>y({...p,content:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):f.jsx("textarea",{value:p.content,onChange:O=>y({...p,content:O.target.value}),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${p.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:p.type==="data"?`CODE-123456 +CODE-789012 +...`:"请输入每次发货时发送的固定文字"}),p.type==="data"&&f.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",f.jsx("span",{className:"font-bold text-[#0094f7]",children:p.content.split(` +`).filter(O=>O.trim()).length})," 条"]})]}),p.type==="api"&&f.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[f.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),f.jsxs("select",{value:p.api_method,onChange:O=>y({...p,api_method:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[f.jsx("option",{value:"GET",children:"GET"}),f.jsx("option",{value:"POST",children:"POST"})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),f.jsx("input",{type:"number",min:"1",max:"60",value:p.api_timeout,onChange:O=>y({...p,api_timeout:parseInt(O.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),f.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),f.jsx("textarea",{value:p.api_headers,onChange:O=>y({...p,api_headers:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),f.jsx("textarea",{value:p.api_params,onChange:O=>y({...p,api_params:O.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),f.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),f.jsx("input",{value:p.description,onChange:O=>y({...p,description:O.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),f.jsx("input",{type:"number",value:p.delay_seconds,onChange:O=>y({...p,delay_seconds:parseInt(O.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),f.jsx("div",{className:"modal-footer",children:f.jsxs("div",{className:"flex gap-3 w-full",children:[f.jsx("button",{onClick:()=>s(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),f.jsxs("button",{onClick:N,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[f.jsx(Hi,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body)]})},_F=()=>{const[e,t]=b.useState([]),[r,n]=b.useState([]),[l,s]=b.useState(""),[c,d]=b.useState(!1),[h,m]=b.useState(!1),[p,y]=b.useState(!1),[x,w]=b.useState(null),[j,_]=b.useState({}),[N,A]=b.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:"",is_multi_spec:!1,is_multi_qty_ship:!1}),O=async()=>{const L=await id();t(L)};b.useEffect(()=>{d0().then(n),O().catch(L=>{console.error("加载商品失败:",L)})},[]);const P=async()=>{if(!l)return alert("请先选择账号");d(!0);try{const L=await ED(l);await O(),alert((L==null?void 0:L.message)||"商品同步完成")}catch(L){console.error("同步商品失败:",L),alert((L==null?void 0:L.message)||"同步失败,请重试")}finally{d(!1)}},k=L=>{w(L),_({...L}),m(!0)},z=async()=>{if(x)try{await MD(x.cookie_id,x.item_id,{item_title:j.item_title||"",item_description:j.item_description||"",item_category:j.item_category||"",item_price:j.item_price||"",item_detail:j.item_detail||x.item_detail||"",is_multi_spec:!!j.is_multi_spec,multi_quantity_delivery:!!(j.is_multi_qty_ship??j.multi_quantity_delivery)}),await O(),m(!1),w(null)}catch(L){console.error("更新商品失败:",L),alert("更新失败,请重试")}},T=async L=>{if(confirm(`确认删除商品"${L.item_title}"吗?`))try{await CD(L.cookie_id,L.item_id),t(K=>K.filter(se=>!(se.cookie_id===L.cookie_id&&se.item_id===L.item_id)))}catch(K){console.error("删除商品失败:",K),alert("删除失败,请重试")}},R=async()=>{try{if(!N.cookie_id||!N.item_id){alert("请选择账号并填写商品ID");return}await kD(N.cookie_id,{item_id:N.item_id,item_title:N.item_title,item_price:N.item_price,item_detail:N.item_image?JSON.stringify({item_image:N.item_image}):"",is_multi_spec:N.is_multi_spec,is_multi_qty_ship:N.is_multi_qty_ship}),await O(),y(!1),A({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:"",is_multi_spec:!1,is_multi_qty_ship:!1})}catch(L){console.error("添加商品失败:",L),alert("添加失败,请重试")}},$=async L=>{const K=!L.is_multi_spec;t(se=>se.map(ce=>ce.cookie_id===L.cookie_id&&ce.item_id===L.item_id?{...ce,is_multi_spec:K}:ce));try{await TD(L.cookie_id,L.item_id,K)}catch(se){console.error("切换状态失败:",se),await O()}},Z=async L=>{const K=!L.is_multi_qty_ship;t(se=>se.map(ce=>ce.cookie_id===L.cookie_id&&ce.item_id===L.item_id?{...ce,is_multi_qty_ship:K,multi_quantity_delivery:K}:ce));try{await DD(L.cookie_id,L.item_id,K)}catch(se){console.error("切换状态失败:",se),await O()}},X=()=>{A(L=>({...L,cookie_id:l||L.cookie_id})),y(!0)};return f.jsxs("div",{className:"space-y-6 animate-fade-in",children:[f.jsxs("div",{className:"flex justify-between items-center",children:[f.jsxs("div",{children:[f.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),f.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),f.jsxs("div",{className:"flex gap-3",children:[f.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:l,onChange:L=>s(L.target.value),children:[f.jsx("option",{value:"",children:"选择账号以同步"}),r.map(L=>f.jsx("option",{value:L.id,children:L.nickname},L.id))]}),f.jsxs("button",{onClick:P,disabled:c||!l,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[f.jsx(la,{className:`w-4 h-4 ${c?"animate-spin":""}`}),"同步商品"]}),f.jsxs("button",{onClick:X,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[f.jsx(Hi,{className:"w-4 h-4"}),"添加商品"]})]})]}),f.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[e.map(L=>f.jsxs("div",{className:"ios-card p-4 rounded-3xl hover:shadow-lg transition-all group relative",children:[f.jsxs("div",{className:"absolute top-3 right-3 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[f.jsx("button",{onClick:()=>k(L),className:"p-2 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:f.jsx(f0,{className:"w-4 h-4"})}),f.jsx("button",{onClick:()=>T(L),className:"p-2 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:f.jsx(ei,{className:"w-4 h-4"})})]}),f.jsxs("div",{className:"aspect-square bg-gray-100 rounded-2xl mb-4 overflow-hidden relative",children:[L.item_image?f.jsx("img",{src:L.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):f.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:f.jsx(KO,{className:"w-10 h-10"})}),f.jsxs("div",{className:"absolute top-2 left-2 bg-black/50 backdrop-blur-md text-white text-xs font-bold px-2 py-1 rounded-lg",children:["¥",L.item_price]})]}),f.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-sm mb-2 h-10",children:L.item_title}),f.jsx("div",{className:"flex justify-between items-center text-xs text-gray-500 mb-2",children:f.jsxs("span",{className:"bg-gray-100 px-2 py-1 rounded-md truncate max-w-[100px]",children:["ID: ",L.item_id]})}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{onClick:()=>$(L),className:`flex-1 text-xs font-bold px-2 py-1.5 rounded-lg transition-colors ${L.is_multi_spec?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:"多规格"}),f.jsx("button",{onClick:()=>Z(L),className:`flex-1 text-xs font-bold px-2 py-1.5 rounded-lg transition-colors ${L.is_multi_qty_ship?"bg-green-100 text-green-700":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:"多数量发货"})]})]},`${L.cookie_id}-${L.item_id}`)),e.length===0&&f.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[f.jsx(XO,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),"暂无商品数据,请选择账号进行同步"]})]}),h&&x&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[f.jsxs("div",{className:"modal-header flex items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),f.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",x.item_id]})]}),f.jsx("button",{onClick:()=>m(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:f.jsx(gr,{className:"w-5 h-5 text-gray-500"})})]}),f.jsxs("div",{className:"modal-body space-y-4",children:[f.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:j.item_title||"",onChange:L=>_({...j,item_title:L.target.value})}),f.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:j.item_price||"",onChange:L=>_({...j,item_price:L.target.value})}),f.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:j.item_category||"",onChange:L=>_({...j,item_category:L.target.value})}),f.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:j.item_description||"",onChange:L=>_({...j,item_description:L.target.value})}),f.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[f.jsxs("label",{className:"flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700",children:[f.jsx("input",{type:"checkbox",checked:!!j.is_multi_spec,onChange:L=>_({...j,is_multi_spec:L.target.checked})}),"多规格"]}),f.jsxs("label",{className:"flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700",children:[f.jsx("input",{type:"checkbox",checked:!!(j.is_multi_qty_ship??j.multi_quantity_delivery),onChange:L=>_({...j,is_multi_qty_ship:L.target.checked})}),"多数量发货"]})]})]}),f.jsx("div",{className:"modal-footer",children:f.jsxs("button",{onClick:z,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[f.jsx(oa,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),p&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[f.jsxs("div",{className:"modal-header flex items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),f.jsx("button",{onClick:()=>y(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:f.jsx(gr,{className:"w-5 h-5 text-gray-500"})})]}),f.jsxs("div",{className:"modal-body space-y-5",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),f.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:N.cookie_id,onChange:L=>A({...N,cookie_id:L.target.value}),children:[f.jsx("option",{value:"",children:"选择账号"}),r.map(L=>f.jsx("option",{value:L.id,children:L.nickname||L.remark||L.id},L.id))]})]}),f.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),f.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:N.item_id,onChange:L=>A({...N,item_id:L.target.value})})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),f.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:N.item_price,onChange:L=>A({...N,item_price:L.target.value})})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),f.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:N.item_title,onChange:L=>A({...N,item_title:L.target.value})})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),f.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:N.item_image,onChange:L=>A({...N,item_image:L.target.value})})]}),f.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[f.jsxs("label",{className:"flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700",children:[f.jsx("input",{type:"checkbox",checked:N.is_multi_spec,onChange:L=>A({...N,is_multi_spec:L.target.checked})}),"多规格"]}),f.jsxs("label",{className:"flex items-center gap-2 p-3 bg-gray-50 rounded-xl text-sm font-bold text-gray-700",children:[f.jsx("input",{type:"checkbox",checked:N.is_multi_qty_ship,onChange:L=>A({...N,is_multi_qty_ship:L.target.checked})}),"多数量发货"]})]})]}),f.jsx("div",{className:"modal-footer",children:f.jsxs("button",{onClick:R,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[f.jsx(Hi,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body)]})},BO="https://dashscope.aliyuncs.com/compatible-mode/v1",SF=()=>{const[e,t]=b.useState(null),[r,n]=b.useState(!1),[l,s]=b.useState(!1),[c,d]=b.useState([]),[h,m]=b.useState(!1),[p,y]=b.useState(""),[x,w]=b.useState(!1),j=b.useRef(null),[_,N]=b.useState(!1),[A,O]=b.useState(!1),[P,k]=b.useState(!1),[z,T]=b.useState(!1),[R,$]=b.useState(!1),[Z,X]=b.useState(null),[L,K]=b.useState({new_username:"",current_password:"",new_password:"",confirm_password:""});b.useEffect(()=>{ce(),ZO().then(te=>{te.username&&K(M=>({...M,new_username:te.username||""}))}).catch(()=>{})},[]),b.useEffect(()=>{const te=M=>{var C;(C=j.current)!=null&&C.contains(M.target)||w(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[]);const se=async(te,M=!1)=>{const C=te||e,U=(C==null?void 0:C.ai_api_url)||(C==null?void 0:C.ai_base_url)||BO;m(!0),y("");try{const ee=await HD(U,(C==null?void 0:C.ai_api_key)||"");d(ee),w(M&&ee.length>0),!(C!=null&&C.ai_model)&&ee.length>0&&t(le=>le&&{...le,ai_model:ee[0]})}catch(ee){d([]),w(!1),y(ee.message||"读取模型失败")}finally{m(!1)}},ce=()=>{n(!0),$D().then(te=>{t(te),se(te)}).finally(()=>n(!1))},he=async()=>{if(e){s(!0);try{await BD(e),alert("系统配置已保存")}catch(te){alert("保存失败:"+te.message)}finally{s(!1)}}},q=async te=>{te.preventDefault(),X(null);const M=L.new_username.trim();if(M.length<3){X({type:"error",text:"用户名至少需要 3 个字符"});return}if(!L.current_password){X({type:"error",text:"请输入当前密码确认身份"});return}if(L.new_password&&L.new_password.length<8){X({type:"error",text:"新密码至少需要 8 个字符"});return}if(L.new_password!==L.confirm_password){X({type:"error",text:"两次输入的新密码不一致"});return}$(!0);try{const C=await nD({current_password:L.current_password,new_username:M,new_password:L.new_password||void 0});if(!C.success){X({type:"error",text:C.message||"登录凭据更新失败"});return}X({type:"success",text:C.message||"登录凭据已更新"}),window.setTimeout(()=>window.location.reload(),1400)}catch(C){X({type:"error",text:C.message||"登录凭据更新失败"})}finally{$(!1)}};if(!e)return f.jsx("div",{className:"p-8 text-center text-gray-400",children:"加载配置中..."});const W=e.ai_model||"",ue=c;return f.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:f.jsx(u0,{className:"w-6 h-6 text-gray-600"})}),f.jsxs("div",{children:[f.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),f.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),f.jsxs("button",{onClick:ce,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[f.jsx(la,{className:"w-4 h-4"}),"刷新"]})]}),f.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[f.jsxs("div",{className:"space-y-8",children:[f.jsxs("section",{className:"space-y-4",children:[f.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[f.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:f.jsx(nT,{className:"w-4 h-4"})}),"基础设置"]}),f.jsxs("div",{className:"ios-card rounded-[2rem] p-6 bg-white space-y-4",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[f.jsxs("div",{children:[f.jsx("div",{className:"font-bold text-gray-900",children:"允许用户注册"}),f.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"开启后允许新用户注册账号"})]}),f.jsx("button",{onClick:()=>t({...e,registration_enabled:!e.registration_enabled}),className:`w-14 h-8 rounded-full transition-all relative ${e.registration_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("div",{className:`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${e.registration_enabled?"left-7":"left-1"}`})})]}),f.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[f.jsxs("div",{children:[f.jsx("div",{className:"font-bold text-gray-900",children:"显示默认登录信息"}),f.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"登录页面显示默认账号密码提示"})]}),f.jsx("button",{onClick:()=>t({...e,show_default_login_info:!e.show_default_login_info}),className:`w-14 h-8 rounded-full transition-all relative ${e.show_default_login_info?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("div",{className:`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${e.show_default_login_info?"left-7":"left-1"}`})})]}),f.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[f.jsxs("div",{children:[f.jsx("div",{className:"font-bold text-gray-900",children:"登录滑动验证码"}),f.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"开启后账号密码登录需要完成滑动验证"})]}),f.jsx("button",{onClick:()=>t({...e,login_captcha_enabled:!e.login_captcha_enabled}),className:`w-14 h-8 rounded-full transition-all relative ${e.login_captcha_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("div",{className:`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${e.login_captcha_enabled?"left-7":"left-1"}`})})]}),f.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[f.jsxs("div",{children:[f.jsx("div",{className:"font-bold text-gray-900",children:"启用商品自动同步"}),f.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"定时自动获取商品信息到本地数据库"})]}),f.jsx("button",{onClick:()=>t({...e,item_sync_enabled:!e.item_sync_enabled}),className:`w-14 h-8 rounded-full transition-all relative ${e.item_sync_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:f.jsx("div",{className:`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${e.item_sync_enabled?"left-7":"left-1"}`})})]}),f.jsxs("div",{className:"space-y-3 px-4",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"商品同步间隔(分钟)"}),f.jsx("input",{type:"number",value:Math.round((e.item_sync_interval||600)/60),onChange:te=>{const M=parseInt(te.target.value)||10;t({...e,item_sync_interval:M*60})},className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"1440"}),f.jsx("p",{className:"text-xs text-gray-500",children:"建议:10-60分钟"})]}),f.jsxs("div",{className:"space-y-3 px-4",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"每次最多同步页数"}),f.jsx("input",{type:"number",value:e.item_sync_max_pages||5,onChange:te=>t({...e,item_sync_max_pages:parseInt(te.target.value)||5}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"50"}),f.jsx("p",{className:"text-xs text-gray-500",children:"每页20个商品"})]})]})]}),f.jsxs("section",{className:"space-y-4",children:[f.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[f.jsx("div",{className:"p-1.5 rounded-lg bg-[#0094f7] text-white",children:f.jsx(c0,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),f.jsxs("div",{className:"ios-card rounded-[2rem] p-6 bg-white space-y-6",children:[f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),f.jsx("input",{type:"text",value:e.ai_api_url||BO,onChange:te=>t({...e,ai_api_url:te.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),f.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),f.jsxs("div",{className:"relative",children:[f.jsx("input",{type:_?"text":"password",value:e.ai_api_key||"",onChange:te=>t({...e,ai_api_key:te.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:"sk-..."}),f.jsx("button",{type:"button",onClick:()=>N(!_),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:_?f.jsx(Ns,{className:"w-4 h-4"}):f.jsx(Xl,{className:"w-4 h-4"})})]})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),f.jsxs("div",{ref:j,className:"relative flex flex-col sm:flex-row gap-2",children:[f.jsxs("div",{className:"relative flex-1",children:[f.jsx("input",{value:W,onFocus:()=>c.length>0&&w(!0),onChange:te=>{t({...e,ai_model:te.target.value}),c.length>0&&w(!0)},onKeyDown:te=>{te.key==="Escape"&&w(!1),te.key==="ArrowDown"&&c.length>0&&w(!0)},className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),f.jsx("button",{type:"button",onClick:()=>c.length>0&&w(te=>!te),disabled:c.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:f.jsx(VM,{className:`w-4 h-4 transition-transform ${x?"rotate-180":""}`})}),x&&f.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:ue.length>0?ue.map(te=>f.jsxs("button",{type:"button",onClick:()=>{t({...e,ai_model:te}),w(!1)},className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-[#0094f7] flex items-center justify-between gap-3",children:[f.jsx("span",{className:"truncate",children:te}),te===W&&f.jsx(Zc,{className:"w-4 h-4 shrink-0 text-[#0094f7]"})]},te)):f.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),f.jsxs("button",{type:"button",onClick:()=>se(void 0,!0),disabled:h,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[f.jsx(la,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"读取模型"]})]}),p?f.jsx("p",{className:"text-xs text-red-500",children:p}):f.jsx("p",{className:"text-xs text-gray-500",children:c.length>0?`已从当前 API 地址读取到 ${c.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"默认自动回复内容"}),f.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl min-h-[100px] text-sm resize-none",value:e.default_reply||"",onChange:te=>t({...e,default_reply:te.target.value}),placeholder:"设置默认的自动回复内容..."})]}),f.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[f.jsx("strong",{children:"常见 AI 服务:"}),f.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[f.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),f.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),f.jsxs("div",{className:"space-y-8",children:[f.jsxs("section",{className:"space-y-4",children:[f.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[f.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:f.jsx(Oj,{className:"w-4 h-4"})}),"登录凭据"]}),f.jsxs("form",{onSubmit:q,className:"ios-card rounded-[2rem] p-6 bg-white space-y-5",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),f.jsxs("div",{className:"relative",children:[f.jsx(ZT,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),f.jsx("input",{type:"text",value:L.new_username,onChange:te=>K({...L,new_username:te.target.value}),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),f.jsxs("div",{className:"relative",children:[f.jsx("input",{type:P?"text":"password",value:L.current_password,onChange:te=>K({...L,current_password:te.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),f.jsx("button",{type:"button",onClick:()=>k(!P),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:P?"隐藏密码":"显示密码",children:P?f.jsx(Ns,{className:"w-4 h-4"}):f.jsx(Xl,{className:"w-4 h-4"})})]})]}),f.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),f.jsxs("div",{className:"relative",children:[f.jsx("input",{type:z?"text":"password",value:L.new_password,onChange:te=>K({...L,new_password:te.target.value}),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),f.jsx("button",{type:"button",onClick:()=>T(!z),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:z?"隐藏密码":"显示密码",children:z?f.jsx(Ns,{className:"w-4 h-4"}):f.jsx(Xl,{className:"w-4 h-4"})})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),f.jsx("input",{type:z?"text":"password",value:L.confirm_password,onChange:te=>K({...L,confirm_password:te.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),Z&&f.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${Z.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[f.jsx(VO,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),f.jsx("span",{children:Z.text})]}),f.jsxs("button",{type:"submit",disabled:R||!L.new_username||!L.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[f.jsx(Oj,{className:"w-4 h-4"}),R?"正在更新...":"更新登录凭据"]})]})]}),f.jsxs("section",{className:"space-y-4",children:[f.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[f.jsx("div",{className:"p-1.5 rounded-lg bg-blue-100 text-blue-600",children:f.jsx(_T,{className:"w-4 h-4"})}),"SMTP 邮件配置"]}),f.jsxs("div",{className:"ios-card rounded-[2rem] p-6 bg-white space-y-6",children:[f.jsx("p",{className:"text-sm text-gray-500",children:"配置SMTP服务器用于发送注册验证码等邮件通知"}),f.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP服务器"}),f.jsx("input",{type:"text",value:e.smtp_server||"",onChange:te=>t({...e,smtp_server:te.target.value}),placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP端口"}),f.jsx("input",{type:"number",value:e.smtp_port||587,onChange:te=>t({...e,smtp_port:parseInt(te.target.value)}),placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),f.jsx("input",{type:"email",value:e.smtp_user||"",onChange:te=>t({...e,smtp_user:te.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码/授权码"}),f.jsxs("div",{className:"relative",children:[f.jsx("input",{type:A?"text":"password",value:e.smtp_password||"",onChange:te=>t({...e,smtp_password:te.target.value}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),f.jsx("button",{type:"button",onClick:()=>O(!A),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:A?f.jsx(Ns,{className:"w-4 h-4"}):f.jsx(Xl,{className:"w-4 h-4"})})]}),f.jsx("p",{className:"text-xs text-gray-500",children:"QQ邮箱需要使用授权码"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),f.jsx("input",{type:"text",value:e.smtp_from||"",onChange:te=>t({...e,smtp_from:te.target.value}),placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]})]})]})]}),f.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:f.jsxs("button",{onClick:he,disabled:l,className:"ios-btn-primary px-10 py-5 rounded-[2rem] text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[f.jsx(oa,{className:"w-6 h-6"}),l?"保存中...":"保存所有配置"]})})]})},Yl=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0}),NF=()=>{const[e,t]=b.useState([]),[r,n]=b.useState(""),[l,s]=b.useState("reply"),[c,d]=b.useState([]),[h,m]=b.useState(!1),[p,y]=b.useState(null),[x,w]=b.useState({keyword:"",reply_content:""}),[j,_]=b.useState([]),[N,A]=b.useState([]),[O,P]=b.useState([]),[k,z]=b.useState(!1),[T,R]=b.useState(null),[$,Z]=b.useState({cookie_id:"",item_id:"",keyword:"",description:"",enabled:!0,variants:[Yl()]}),[X,L]=b.useState({}),[K,se]=b.useState(!1),[ce,he]=b.useState(null),[q,W]=b.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),[ue,te]=b.useState(!1);b.useEffect(()=>{d0().then(D=>{t(D),D&&D.length>0&&!r&&n(D[0].id)})},[]),b.useEffect(()=>{r&&(le(),C(),U(),ee(),M())},[r]);const M=async()=>{try{const D=await KD();L(D)}catch(D){console.error("加载默认回复失败",D)}},C=async()=>{try{const D=await PD();_(D)}catch(D){console.error("加载发货规则失败",D)}},U=async()=>{try{const D=await Gl();A(D)}catch(D){console.error("加载卡券失败",D)}},ee=async()=>{try{P(await id())}catch(D){console.error("加载商品失败",D)}},le=async()=>{if(r){te(!0);try{const D=await RD(r);d(D)}catch(D){console.error("加载关键词失败",D)}finally{te(!1)}}},me=()=>{if(l==="reply")y(null),w({keyword:"",reply_content:""}),m(!0);else if(l==="delivery")R(null),Z({cookie_id:r,item_id:"",keyword:"",description:"",enabled:!0,variants:[Yl()]}),z(!0);else{if(!r)return;pe(r)}},pe=async D=>{try{const oe=await YD(D);he(oe),W({cookie_id:D,enabled:oe.enabled,reply_content:oe.reply_content,reply_once:oe.reply_once,reply_image_url:oe.reply_image_url||""}),se(!0)}catch(oe){console.error("加载默认回复失败",oe),he(null),W({cookie_id:D,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""}),se(!0)}},be=D=>{l==="reply"&&(y(D),w({keyword:D.keyword,reply_content:D.reply_content}),m(!0))},Me=D=>{var oe;R(D),Z({cookie_id:D.cookie_id||r,item_id:D.item_id||"",keyword:D.item_keyword,description:D.name,enabled:D.enabled,variants:(oe=D.variants)!=null&&oe.length?D.variants.map(fe=>({...fe})):[{...Yl(),card_id:D.card_group_id}]}),z(!0)},J=async()=>{if(!r){alert("请先选择账号");return}if(!x.keyword.trim()||!x.reply_content.trim()){alert("请填写关键词和回复内容");return}try{await LD({id:p==null?void 0:p.id,keyword:x.keyword,reply_content:x.reply_content,match_type:"exact",enabled:!0},r),m(!1),le(),alert("保存成功!")}catch(D){alert("保存失败:"+D.message)}},we=async()=>{if(!$.cookie_id||!$.item_id){alert("请选择需要自动发货的商品");return}const D=O.find(fe=>fe.cookie_id===$.cookie_id&&fe.item_id===$.item_id),oe=!!(D!=null&&D.is_multi_spec);if($.variants.length===0||$.variants.some(fe=>!fe.card_id)){alert("请为每条映射选择卡密库存");return}if(oe&&$.variants.some(fe=>!fe.spec_name.trim()||!fe.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}try{await Tj({id:T==null?void 0:T.id,cookie_id:$.cookie_id,item_id:$.item_id,item_keyword:$.keyword,card_group_id:$.variants[0].card_id,name:$.description,priority:$.variants[0].delivery_count,enabled:$.enabled,variants:$.variants.map(fe=>({...fe,spec_name:oe?fe.spec_name.trim():"",spec_value:oe?fe.spec_value.trim():""}))}),z(!1),C(),alert("保存成功!")}catch(fe){alert("保存失败:"+fe.message)}},Oe=async D=>{if(!(!r||!confirm("确认删除该关键词吗?")))try{await ID(D,r),le(),alert("删除成功!")}catch(oe){alert("删除失败:"+oe.message)}},ie=async D=>{if(confirm("确认删除该发货规则吗?"))try{await zD(D),C(),alert("删除成功!")}catch(oe){alert("删除失败:"+oe.message)}},Ie=async D=>{try{await Tj({...D,enabled:!D.enabled}),C()}catch(oe){alert("操作失败:"+oe.message)}},_e=O.find(D=>D.cookie_id===$.cookie_id&&D.item_id===$.item_id),ct=O.filter(D=>D.cookie_id===($.cookie_id||r)),ft=D=>{const oe=O.find(fe=>fe.cookie_id===($.cookie_id||r)&&fe.item_id===D);Z({...$,cookie_id:(oe==null?void 0:oe.cookie_id)||r,item_id:D,keyword:(oe==null?void 0:oe.item_title)||D,variants:[Yl()]})},ht=(D,oe)=>{Z({...$,variants:$.variants.map((fe,Pe)=>Pe===D?{...fe,...oe}:fe)})},nn=async()=>{if(!q.cookie_id){alert("请先选择账号");return}try{await GD(q.cookie_id,{enabled:q.enabled,reply_content:q.reply_content,reply_once:q.reply_once,reply_image_url:q.reply_image_url}),se(!1),M(),alert("保存成功!")}catch(D){alert("保存失败:"+D.message)}},Pn=async D=>{if(confirm("确认删除该默认回复吗?"))try{await VD(D),M(),alert("删除成功!")}catch(oe){alert("删除失败:"+oe.message)}},zn=async D=>{if(confirm("确认清空该账号的回复记录吗?清空后可以重新对所有对话使用默认回复。"))try{await XD(D),alert("清空成功!")}catch(oe){alert("清空失败:"+oe.message)}};return f.jsxs("div",{className:"space-y-8 animate-fade-in",children:[f.jsx("div",{className:"flex justify-between items-end",children:f.jsxs("div",{children:[f.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),f.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置关键词回复、商品发货和账号默认回复"})]})}),f.jsx("div",{className:"flex justify-center",children:f.jsxs("div",{className:"inline-flex items-center bg-gradient-to-br from-gray-100 to-gray-200 p-2 rounded-3xl shadow-xl gap-1",children:[f.jsxs("button",{onClick:()=>s("reply"),className:`flex items-center gap-2 px-6 py-3.5 rounded-2xl font-bold text-base transition-all duration-300 ${l==="reply"?"bg-gradient-to-r from-[#0094f7] to-[#0071e3] text-white shadow-lg":"text-gray-500 hover:text-gray-700 hover:bg-white/50"}`,children:[f.jsx(Fa,{className:"w-5 h-5 shrink-0"}),f.jsx("span",{children:"关键词回复"}),f.jsx("span",{className:`ml-1 px-2.5 py-0.5 rounded-full text-xs font-semibold tabular-nums ${l==="reply"?"bg-white/25 text-white":"bg-gray-200 text-gray-600"}`,children:c.length})]}),f.jsxs("button",{onClick:()=>s("delivery"),className:`flex items-center gap-2 px-6 py-3.5 rounded-2xl font-bold text-base transition-all duration-300 ${l==="delivery"?"bg-gradient-to-r from-[#0094f7] to-[#0071e3] text-white shadow-lg":"text-gray-500 hover:text-gray-700 hover:bg-white/50"}`,children:[f.jsx(Cs,{className:"w-5 h-5 shrink-0"}),f.jsx("span",{children:"商品发货"}),f.jsx("span",{className:`ml-1 px-2.5 py-0.5 rounded-full text-xs font-semibold tabular-nums ${l==="delivery"?"bg-white/25 text-white":"bg-gray-200 text-gray-600"}`,children:j.length})]}),f.jsxs("button",{onClick:()=>s("default"),className:`flex items-center gap-2 px-6 py-3.5 rounded-2xl font-bold text-base transition-all duration-300 ${l==="default"?"bg-gradient-to-r from-[#0094f7] to-[#0071e3] text-white shadow-lg":"text-gray-500 hover:text-gray-700 hover:bg-white/50"}`,children:[f.jsx(ra,{className:"w-5 h-5 shrink-0"}),f.jsx("span",{children:"账号默认回复"}),f.jsx("span",{className:`ml-1 px-2.5 py-0.5 rounded-full text-xs font-semibold tabular-nums ${l==="default"?"bg-white/25 text-white":"bg-gray-200 text-gray-600"}`,children:Object.values(X).filter(D=>D.enabled).length})]})]})}),f.jsx("div",{className:"bg-white rounded-3xl shadow-xl p-6",children:f.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-4 w-full sm:w-auto",children:[f.jsx("label",{className:"text-sm font-bold text-gray-700 whitespace-nowrap",children:"选择账号"}),f.jsxs("select",{className:"flex-1 sm:w-64 ios-input px-5 py-3 rounded-2xl font-medium border-2 border-gray-200 focus:border-[#0094f7] focus:ring-4 focus:ring-[#0094f7]/20 transition-all",value:r,onChange:D=>n(D.target.value),children:[f.jsx("option",{value:"",children:"请选择账号"}),e.map(D=>f.jsx("option",{value:D.id,children:D.nickname},D.id))]})]}),f.jsxs("div",{className:"flex items-center gap-3 w-full sm:w-auto",children:[f.jsxs("button",{onClick:()=>{l==="reply"?le():l==="delivery"?C():M()},className:"flex-1 sm:flex-none flex items-center justify-center gap-2 px-6 py-3 rounded-2xl font-bold bg-gradient-to-br from-gray-100 to-gray-200 hover:from-gray-200 hover:to-gray-300 transition-all shadow-lg",children:[f.jsx(la,{className:"w-5 h-5"}),"刷新"]}),f.jsxs("button",{onClick:me,disabled:!r,className:"flex-1 sm:flex-none flex items-center justify-center gap-2 px-8 py-3 rounded-2xl font-bold bg-gradient-to-r from-[#0094f7] to-[#0071e3] hover:from-[#0071e3] hover:to-[#0071e3] text-white shadow-xl hover:shadow-2xl hover:scale-105 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:[f.jsx(Hi,{className:"w-5 h-5"}),l==="reply"?"添加关键词":l==="delivery"?"添加发货规则":"编辑默认回复"]})]})]})}),r?l==="reply"?ue?f.jsx("div",{className:"py-24 flex justify-center",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(Wa,{className:"w-16 h-16 text-[#0094f7] animate-spin"}),f.jsx("p",{className:"text-gray-500 font-medium",children:"加载中..."})]})}):f.jsxs("div",{className:"space-y-4",children:[c.map((D,oe)=>f.jsxs("div",{className:"group relative bg-gradient-to-br from-white to-gray-50 rounded-3xl p-6 shadow-lg hover:shadow-2xl transition-all duration-300 border-2 border-transparent hover:border-[#0094f7]/30 overflow-hidden",children:[f.jsx("div",{className:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-[#0094f7]/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 group-hover:scale-150 transition-transform duration-500"}),f.jsxs("div",{className:"relative flex items-center gap-6",children:[f.jsx("div",{className:"flex-shrink-0",children:f.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-[#287efe] to-[#0094f7] rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 group-hover:rotate-12 transition-all duration-300",children:f.jsx(ry,{className:"w-8 h-8 text-blue-800"})})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[f.jsx("h3",{className:"text-xl font-black text-gray-900",children:D.keyword}),f.jsx("span",{className:"px-3 py-1.5 rounded-xl bg-gradient-to-r from-green-400 to-green-500 text-white text-xs font-bold shadow-md",children:"精确匹配"})]}),f.jsxs("p",{className:"text-gray-600 bg-white/70 backdrop-blur-sm rounded-2xl px-4 py-3 line-clamp-2 shadow-inner border border-gray-100",children:["💬 ",D.reply_content||"无回复内容"]})]}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsx("button",{onClick:()=>be(D),className:"p-3.5 bg-gradient-to-br from-blue-50 to-blue-100 text-blue-600 rounded-2xl hover:from-blue-100 hover:to-blue-200 transition-all shadow-md hover:shadow-lg hover:scale-110",title:"编辑",children:f.jsx(Qc,{className:"w-5 h-5"})}),f.jsx("button",{onClick:()=>Oe(D.id),className:"p-3.5 bg-gradient-to-br from-red-50 to-red-100 text-red-500 rounded-2xl hover:from-red-100 hover:to-red-200 transition-all shadow-md hover:shadow-lg hover:scale-110",title:"删除",children:f.jsx(ei,{className:"w-5 h-5"})})]})]})]},D.id)),c.length===0&&f.jsxs("div",{className:"py-24 text-center bg-gradient-to-br from-white to-gray-50 rounded-[2.5rem] border-3 border-dashed border-gray-300 shadow-xl",children:[f.jsx("div",{className:"w-24 h-24 bg-gradient-to-br from-[#0094f7]/20 to-[#0071e3]/20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-inner",children:f.jsx(Fa,{className:"w-12 h-12 text-[#0094f7]"})}),f.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-2",children:"暂无关键词"}),f.jsx("p",{className:"text-gray-500 text-lg",children:"点击右上角添加新的关键词规则"})]})]}):l==="delivery"?f.jsxs("div",{className:"space-y-4",children:[j.filter(D=>!D.cookie_id||D.cookie_id===r).map(D=>f.jsxs("div",{className:`group relative bg-gradient-to-br ${D.enabled?"from-white to-blue-50/30":"from-gray-100 to-gray-150"} rounded-3xl p-6 shadow-lg hover:shadow-2xl transition-all duration-300 border-2 ${D.enabled?"border-transparent hover:border-blue-400/30":"border-gray-200"} overflow-hidden`,children:[D.enabled&&f.jsx("div",{className:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-blue-400/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 group-hover:scale-150 transition-transform duration-500"}),f.jsxs("div",{className:"relative flex items-center gap-6",children:[f.jsx("div",{className:"flex-shrink-0",children:f.jsx("div",{className:`w-16 h-16 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 transition-all duration-300 ${D.enabled?"bg-gradient-to-br from-blue-400 to-blue-500 group-hover:rotate-12":"bg-gradient-to-br from-gray-300 to-gray-400"}`,children:f.jsx(Cs,{className:"w-8 h-8 text-white"})})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[f.jsx("h3",{className:"text-xl font-black text-gray-900",children:D.item_title||D.item_keyword}),f.jsx("span",{className:`px-3 py-1.5 rounded-xl text-xs font-bold shadow-md ${D.enabled?"bg-gradient-to-r from-green-400 to-green-500 text-white":"bg-gradient-to-r from-gray-400 to-gray-500 text-white"}`,children:D.enabled?"已启用":"已禁用"})]}),f.jsx("div",{className:"flex flex-wrap gap-2",children:(D.variants||[]).map((oe,fe)=>f.jsxs("span",{className:"text-xs bg-white border border-gray-200 text-gray-700 px-3 py-1.5 rounded-lg font-bold",children:[oe.spec_value?`${oe.spec_name}: ${oe.spec_value} → `:"默认 → ",oe.card_name||`卡密 ${oe.card_id}`]},oe.id||fe))}),D.name&&f.jsx("p",{className:"text-sm text-gray-500 mt-2",children:D.name})]}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsx("button",{onClick:()=>Ie(D),className:`p-3.5 rounded-2xl transition-all shadow-md hover:shadow-lg hover:scale-110 ${D.enabled?"bg-gradient-to-br from-blue-50 to-blue-100 text-blue-600 hover:from-blue-100 hover:to-blue-200":"bg-gradient-to-br from-green-50 to-green-100 text-green-600 hover:from-green-100 hover:to-green-200"}`,title:D.enabled?"禁用":"启用",children:D.enabled?f.jsx(kT,{className:"w-5 h-5"}):f.jsx(ay,{className:"w-5 h-5"})}),f.jsx("button",{onClick:()=>Me(D),className:"p-3.5 bg-gradient-to-br from-blue-50 to-blue-100 text-blue-600 rounded-2xl hover:from-blue-100 hover:to-blue-200 transition-all shadow-md hover:shadow-lg hover:scale-110",title:"编辑",children:f.jsx(Qc,{className:"w-5 h-5"})}),f.jsx("button",{onClick:()=>ie(D.id),className:"p-3.5 bg-gradient-to-br from-red-50 to-red-100 text-red-500 rounded-2xl hover:from-red-100 hover:to-red-200 transition-all shadow-md hover:shadow-lg hover:scale-110",title:"删除",children:f.jsx(ei,{className:"w-5 h-5"})})]})]})]},D.id)),j.filter(D=>!D.cookie_id||D.cookie_id===r).length===0&&f.jsxs("div",{className:"py-24 text-center bg-gradient-to-br from-white to-gray-50 rounded-[2.5rem] border-3 border-dashed border-gray-300 shadow-xl",children:[f.jsx("div",{className:"w-24 h-24 bg-gradient-to-br from-blue-400/20 to-blue-500/20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-inner",children:f.jsx(Cs,{className:"w-12 h-12 text-blue-400"})}),f.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-2",children:"暂无发货规则"}),f.jsx("p",{className:"text-gray-500 text-lg",children:"点击右上角添加新的发货规则"})]})]}):l==="default"?f.jsxs("div",{className:"space-y-4",children:[e.map(D=>{const oe=X[D.id],fe=oe&&oe.enabled;return f.jsxs("div",{className:`group relative bg-gradient-to-br ${fe?"from-white to-purple-50/30":"from-gray-100 to-gray-150"} rounded-3xl p-6 shadow-lg hover:shadow-2xl transition-all duration-300 border-2 ${fe?"border-transparent hover:border-purple-400/30":"border-gray-200"} overflow-hidden`,children:[fe&&f.jsx("div",{className:"absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-purple-400/10 to-transparent rounded-full -translate-y-1/2 translate-x-1/2 group-hover:scale-150 transition-transform duration-500"}),f.jsxs("div",{className:"relative flex items-center gap-6",children:[f.jsx("div",{className:"flex-shrink-0",children:f.jsx("div",{className:`w-16 h-16 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 transition-all duration-300 ${fe?"bg-gradient-to-br from-purple-400 to-purple-500 group-hover:rotate-12":"bg-gradient-to-br from-gray-300 to-gray-400"}`,children:f.jsx(ra,{className:"w-8 h-8 text-white"})})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[f.jsx("h3",{className:"text-xl font-black text-gray-900",children:D.nickname}),f.jsx("span",{className:`px-3 py-1.5 rounded-xl text-xs font-bold shadow-md ${fe?"bg-gradient-to-r from-green-400 to-green-500 text-white":"bg-gradient-to-r from-gray-400 to-gray-500 text-white"}`,children:fe?"已启用":"未设置"}),(oe==null?void 0:oe.reply_once)&&f.jsx("span",{className:"px-3 py-1.5 rounded-xl bg-purple-100 text-purple-700 text-xs font-bold shadow-md",children:"只回复一次"})]}),fe&&f.jsxs("p",{className:"text-gray-600 bg-white/70 backdrop-blur-sm rounded-2xl px-4 py-3 line-clamp-2 shadow-inner border border-gray-100",children:["💬 ",oe.reply_content||"无回复内容"]})]}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsx("button",{onClick:()=>pe(D.id),className:"p-3.5 bg-gradient-to-br from-purple-50 to-purple-100 text-purple-600 rounded-2xl hover:from-purple-100 hover:to-purple-200 transition-all shadow-md hover:shadow-lg hover:scale-110",title:"编辑",children:f.jsx(Qc,{className:"w-5 h-5"})}),fe&&f.jsxs(f.Fragment,{children:[f.jsx("button",{onClick:()=>zn(D.id),className:"p-3.5 bg-gradient-to-br from-blue-50 to-blue-100 text-blue-600 rounded-2xl hover:from-blue-100 hover:to-blue-200 transition-all shadow-md hover:shadow-lg hover:scale-110",title:"清空回复记录",children:f.jsx(la,{className:"w-5 h-5"})}),f.jsx("button",{onClick:()=>Pn(D.id),className:"p-3.5 bg-gradient-to-br from-red-50 to-red-100 text-red-500 rounded-2xl hover:from-red-100 hover:to-red-200 transition-all shadow-md hover:shadow-lg hover:scale-110",title:"删除",children:f.jsx(ei,{className:"w-5 h-5"})})]})]})]})]},D.id)}),e.length===0&&f.jsxs("div",{className:"py-24 text-center bg-gradient-to-br from-white to-gray-50 rounded-[2.5rem] border-3 border-dashed border-gray-300 shadow-xl",children:[f.jsx("div",{className:"w-24 h-24 bg-gradient-to-br from-purple-400/20 to-purple-500/20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-inner",children:f.jsx(ra,{className:"w-12 h-12 text-purple-400"})}),f.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-2",children:"暂无账号"}),f.jsx("p",{className:"text-gray-500 text-lg",children:"请先添加账号"})]})]}):null:f.jsxs("div",{className:"py-24 text-center bg-gradient-to-br from-white to-gray-50 rounded-[2.5rem] border-3 border-dashed border-gray-300 shadow-xl",children:[f.jsx("div",{className:"w-24 h-24 bg-gradient-to-br from-[#0094f7]/20 to-[#0071e3]/20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-inner",children:f.jsx(Fa,{className:"w-12 h-12 text-[#0094f7]"})}),f.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-2",children:"请选择账号"}),f.jsx("p",{className:"text-gray-500 text-lg",children:"选择一个账号以管理其关键词规则"})]}),h&&Jt.createPortal(f.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in",children:f.jsxs("div",{className:"bg-white rounded-[2.5rem] shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-hidden animate-scale-in",children:[f.jsx("div",{className:"bg-gradient-to-r from-[#0094f7] to-[#0071e3] p-8",children:f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsx("div",{className:"w-14 h-14 bg-white/30 backdrop-blur-sm rounded-2xl flex items-center justify-center",children:f.jsx(Fa,{className:"w-7 h-7 text-gray-900"})}),f.jsx("h3",{className:"text-3xl font-black text-gray-900",children:p?"编辑关键词":"添加关键词"})]}),f.jsx("button",{onClick:()=>m(!1),className:"p-3 bg-white/30 backdrop-blur-sm rounded-2xl hover:bg-white/40 transition-colors",children:f.jsx(gr,{className:"w-6 h-6 text-gray-900"})})]})}),f.jsxs("div",{className:"p-8 space-y-6 overflow-y-auto max-h-[60vh]",children:[f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-2 text-sm font-black text-gray-900 mb-3",children:[f.jsx(ry,{className:"w-5 h-5 text-[#0094f7]"}),"触发关键词"]}),f.jsx("input",{type:"text",value:x.keyword,onChange:D=>w({...x,keyword:D.target.value}),placeholder:"例如:价格、包邮、怎么样",className:"w-full px-6 py-4 rounded-2xl font-medium border-2 border-gray-200 focus:border-[#0094f7] focus:ring-4 focus:ring-[#0094f7]/20 transition-all bg-gray-50"}),f.jsx("p",{className:"text-sm text-gray-500 mt-2 ml-1",children:"💡 买家消息中包含此关键词时自动回复"})]}),f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-2 text-sm font-black text-gray-900 mb-3",children:[f.jsx(Fa,{className:"w-5 h-5 text-[#0094f7]"}),"回复内容"]}),f.jsx("textarea",{value:x.reply_content,onChange:D=>w({...x,reply_content:D.target.value}),placeholder:"输入自动回复的内容...",rows:6,className:"w-full px-6 py-4 rounded-2xl font-medium border-2 border-gray-200 focus:border-[#0094f7] focus:ring-4 focus:ring-[#0094f7]/20 transition-all bg-gray-50 resize-none"}),f.jsx("p",{className:"text-sm text-gray-500 mt-2 ml-1",children:"💬 支持换行,系统将自动发送此内容给买家"})]})]}),f.jsx("div",{className:"p-8 bg-gray-50 border-t border-gray-100",children:f.jsxs("div",{className:"flex gap-4",children:[f.jsx("button",{onClick:()=>m(!1),className:"flex-1 px-8 py-4 rounded-2xl font-bold bg-white border-2 border-gray-200 hover:bg-gray-50 hover:border-gray-300 text-gray-700 transition-all shadow-lg hover:shadow-xl",children:"取消"}),f.jsxs("button",{onClick:J,className:"flex-1 px-8 py-4 rounded-2xl font-bold bg-gradient-to-r from-[#0094f7] to-[#0071e3] hover:from-[#0071e3] hover:to-[#0071e3] text-white shadow-xl hover:shadow-2xl hover:scale-105 transition-all flex items-center justify-center gap-2",children:[f.jsx(oa,{className:"w-5 h-5"}),"保存关键词"]})]})})]})}),document.body),k&&Jt.createPortal(f.jsx("div",{className:"modal-overlay-centered",children:f.jsxs("div",{className:"modal-container",style:{maxWidth:"920px"},children:[f.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[f.jsxs("div",{children:[f.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:T?"编辑商品发货规则":"添加商品发货规则"}),f.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"按订单真实规格选择对应的卡密库存"})]}),f.jsx("button",{onClick:()=>z(!1),className:"p-2 rounded-xl hover:bg-gray-100",title:"关闭",children:f.jsx(gr,{className:"w-5 h-5 text-gray-500"})})]}),f.jsxs("div",{className:"modal-body space-y-6",children:[f.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"闲鱼账号"}),f.jsx("select",{value:$.cookie_id,onChange:D=>Z({...$,cookie_id:D.target.value,item_id:"",keyword:"",variants:[Yl()]}),className:"w-full ios-input px-4 py-3 rounded-xl",children:e.map(D=>f.jsx("option",{value:D.id,children:D.nickname||D.remark||D.id},D.id))})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"关联商品"}),f.jsxs("select",{value:$.item_id,onChange:D=>ft(D.target.value),className:"w-full ios-input px-4 py-3 rounded-xl",children:[f.jsx("option",{value:"",children:"请选择已同步商品"}),ct.map(D=>f.jsx("option",{value:D.item_id,children:D.item_title||D.item_id},`${D.cookie_id}-${D.item_id}`))]})]})]}),_e&&f.jsxs("div",{className:"flex items-center justify-between gap-4 border-y border-gray-100 py-4",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"font-bold text-gray-900 truncate",children:_e.item_title||_e.item_id}),f.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:_e.item_id})]}),f.jsx("span",{className:`flex-shrink-0 px-3 py-1.5 rounded-lg text-xs font-bold ${_e.is_multi_spec?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-600"}`,children:_e.is_multi_spec?"多规格商品":"普通商品"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between gap-4",children:[f.jsxs("div",{children:[f.jsxs("h4",{className:"font-extrabold text-gray-900 flex items-center gap-2",children:[f.jsx(hT,{className:"w-4 h-4 text-[#0094f7]"}),"规格与库存映射"]}),f.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"规格名称和值必须与订单详情完全一致"})]}),(_e==null?void 0:_e.is_multi_spec)&&f.jsxs("button",{type:"button",onClick:()=>Z({...$,variants:[...$.variants,Yl()]}),className:"inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-gray-900 text-white text-xs font-bold hover:bg-black",children:[f.jsx(Hi,{className:"w-3.5 h-3.5"})," 添加规格"]})]}),$.variants.map((D,oe)=>f.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[1fr_1fr_1.4fr_90px_40px] gap-3 items-end border border-gray-200 rounded-xl p-4",children:[_e!=null&&_e.is_multi_spec?f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-xs font-bold text-gray-600",children:"规格名称"}),f.jsx("input",{value:D.spec_name,onChange:fe=>ht(oe,{spec_name:fe.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-xs font-bold text-gray-600",children:"规格值"}),f.jsx("input",{value:D.spec_value,onChange:fe=>ht(oe,{spec_value:fe.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}):f.jsxs("div",{className:"md:col-span-2 space-y-2",children:[f.jsx("label",{className:"block text-xs font-bold text-gray-600",children:"匹配方式"}),f.jsx("div",{className:"h-[42px] flex items-center text-sm text-gray-600 bg-gray-50 px-3 rounded-lg",children:"默认库存"})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-xs font-bold text-gray-600",children:"卡密库存"}),f.jsxs("select",{value:D.card_id||"",onChange:fe=>ht(oe,{card_id:Number(fe.target.value)}),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[f.jsx("option",{value:"",children:"请选择卡密"}),N.filter(fe=>fe.enabled).map(fe=>f.jsx("option",{value:fe.id,children:fe.name},fe.id))]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-xs font-bold text-gray-600",children:"每单数量"}),f.jsx("input",{type:"number",min:"1",max:"100",value:D.delivery_count,onChange:fe=>ht(oe,{delivery_count:Math.max(1,Number(fe.target.value)||1)}),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),f.jsx("button",{type:"button",disabled:$.variants.length===1,onClick:()=>Z({...$,variants:$.variants.filter((fe,Pe)=>Pe!==oe)}),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除规格",children:f.jsx(ei,{className:"w-4 h-4"})})]},D.id||oe))]}),f.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[1fr_auto] gap-4 items-end",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"规则备注"}),f.jsx("input",{value:$.description,onChange:D=>Z({...$,description:D.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"方便识别这条规则(可选)"})]}),f.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[f.jsx("input",{type:"checkbox",checked:$.enabled,onChange:D=>Z({...$,enabled:D.target.checked}),className:"w-4 h-4 rounded"}),"启用规则"]})]})]}),f.jsxs("div",{className:"modal-footer flex gap-3",children:[f.jsx("button",{onClick:()=>z(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),f.jsxs("button",{onClick:we,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[f.jsx(oa,{className:"w-4 h-4"}),"保存发货规则"]})]})]})}),document.body),K&&Jt.createPortal(f.jsx("div",{className:"fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in",children:f.jsxs("div",{className:"bg-white rounded-[2.5rem] shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-hidden animate-scale-in",children:[f.jsx("div",{className:"bg-gradient-to-r from-purple-400 to-purple-500 p-8",children:f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsx("div",{className:"w-14 h-14 bg-white/30 backdrop-blur-sm rounded-2xl flex items-center justify-center",children:f.jsx(ra,{className:"w-7 h-7 text-white"})}),f.jsx("h3",{className:"text-3xl font-black text-white",children:"账号默认回复"})]}),f.jsx("button",{onClick:()=>se(!1),className:"p-3 bg-white/30 backdrop-blur-sm rounded-2xl hover:bg-white/40 transition-colors",children:f.jsx(gr,{className:"w-6 h-6 text-white"})})]})}),f.jsxs("div",{className:"p-8 space-y-6 overflow-y-auto max-h-[60vh]",children:[f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-2 text-sm font-black text-gray-900 mb-3",children:[f.jsx(ra,{className:"w-5 h-5 text-purple-500"}),"账号"]}),f.jsxs("select",{value:q.cookie_id,onChange:D=>W({...q,cookie_id:D.target.value}),className:"w-full px-6 py-4 rounded-2xl font-medium border-2 border-gray-200 focus:border-purple-400 focus:ring-4 focus:ring-purple-400/20 transition-all bg-gray-50",children:[f.jsx("option",{value:"",children:"请选择账号"}),e.map(D=>f.jsx("option",{value:D.id,children:D.nickname},D.id))]}),f.jsx("p",{className:"text-sm text-gray-500 mt-2 ml-1",children:"🤖 为此账号设置默认回复内容"})]}),f.jsxs("div",{className:"flex items-center justify-between p-5 bg-gradient-to-r from-purple-50 to-purple-100/50 rounded-2xl border-2 border-purple-200",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(ay,{className:"w-6 h-6 text-purple-500"}),f.jsx("span",{className:"text-base font-black text-gray-900",children:"启用默认回复"})]}),f.jsx("button",{type:"button",onClick:()=>W({...q,enabled:!q.enabled}),className:`relative inline-flex h-7 w-14 items-center rounded-full transition-all duration-300 ${q.enabled?"bg-purple-500":"bg-gray-300"}`,children:f.jsx("span",{className:`inline-block h-5 w-5 transform rounded-full bg-white shadow-lg transition-transform duration-300 ${q.enabled?"translate-x-8":"translate-x-1"}`})})]}),f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-2 text-sm font-black text-gray-900 mb-3",children:[f.jsx(Fa,{className:"w-5 h-5 text-purple-500"}),"回复内容"]}),f.jsx("textarea",{value:q.reply_content,onChange:D=>W({...q,reply_content:D.target.value}),placeholder:"输入默认回复的内容...",rows:6,className:"w-full px-6 py-4 rounded-2xl font-medium border-2 border-gray-200 focus:border-purple-400 focus:ring-4 focus:ring-purple-400/20 transition-all bg-gray-50 resize-none"}),f.jsx("p",{className:"text-sm text-gray-500 mt-2 ml-1",children:"💬 当没有匹配的关键词时,系统将自动发送此内容"})]}),f.jsxs("div",{className:"flex items-center justify-between p-5 bg-gradient-to-r from-blue-50 to-blue-100/50 rounded-2xl border-2 border-blue-200",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("span",{className:"text-base font-black text-gray-900",children:"🔁 只回复一次"}),f.jsx("span",{className:"text-xs text-gray-500",children:"启用后,每个对话只使用一次默认回复"})]}),f.jsx("button",{type:"button",onClick:()=>W({...q,reply_once:!q.reply_once}),className:`relative inline-flex h-7 w-14 items-center rounded-full transition-all duration-300 ${q.reply_once?"bg-blue-500":"bg-gray-300"}`,children:f.jsx("span",{className:`inline-block h-5 w-5 transform rounded-full bg-white shadow-lg transition-transform duration-300 ${q.reply_once?"translate-x-8":"translate-x-1"}`})})]}),f.jsxs("div",{children:[f.jsxs("label",{className:"flex items-center gap-2 text-sm font-black text-gray-900 mb-3",children:[f.jsx(c0,{className:"w-5 h-5 text-purple-500"}),"回复图片URL(可选)"]}),f.jsx("input",{type:"text",value:q.reply_image_url,onChange:D=>W({...q,reply_image_url:D.target.value}),placeholder:"https://example.com/image.jpg",className:"w-full px-6 py-4 rounded-2xl font-medium border-2 border-gray-200 focus:border-purple-400 focus:ring-4 focus:ring-purple-400/20 transition-all bg-gray-50"}),f.jsx("p",{className:"text-sm text-gray-500 mt-2 ml-1",children:"🖼️ 可选:添加图片URL一起发送"})]})]}),f.jsx("div",{className:"p-8 bg-gray-50 border-t border-gray-100",children:f.jsxs("div",{className:"flex gap-4",children:[f.jsx("button",{onClick:()=>se(!1),className:"flex-1 px-8 py-4 rounded-2xl font-bold bg-white border-2 border-gray-200 hover:bg-gray-50 hover:border-gray-300 text-gray-700 transition-all shadow-lg hover:shadow-xl",children:"取消"}),f.jsxs("button",{onClick:nn,className:"flex-1 px-8 py-4 rounded-2xl font-bold bg-gradient-to-r from-purple-400 to-purple-500 hover:from-purple-500 hover:to-purple-600 text-white shadow-xl hover:shadow-2xl hover:scale-105 transition-all flex items-center justify-center gap-2",children:[f.jsx(oa,{className:"w-5 h-5"}),"保存默认回复"]})]})})]})}),document.body)]})},OF=()=>{const[e,t]=b.useState(!1),[r,n]=b.useState("dashboard"),[l,s]=b.useState(!0),[c,d]=b.useState(!1),[h,m]=b.useState(""),[p,y]=b.useState(""),[x,w]=b.useState(!1),[j,_]=b.useState("");b.useEffect(()=>{ZO().then(P=>{if((P==null?void 0:P.initialized)===!1){d(!0),t(!1);return}d(!1),P!=null&&P.authenticated&&t(!0)}).catch(()=>t(!1)).finally(()=>s(!1));const O=()=>t(!1);return window.addEventListener("auth:logout",O),()=>window.removeEventListener("auth:logout",O)},[]);const N=async O=>{O.preventDefault(),w(!0),_("");try{const P=await rD({username:h,password:p});P.success?t(!0):_(P.message||"登录失败")}catch(P){const k=P instanceof Error?P.message:String(P);_(k||"登录失败")}finally{w(!1)}};if(l)return f.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f5f5f7]",children:f.jsx(Wa,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});if(c)return f.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[f.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),f.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),f.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-[3rem] shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[f.jsxs("div",{className:"text-center mb-8",children:[f.jsx("div",{className:"w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 p-4",style:{filter:"drop-shadow(0 8px 20px rgba(0,148,247,0.3))"},children:f.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),f.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"系统尚未初始化"}),f.jsx("p",{className:"text-gray-600 font-medium",children:"为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。"})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"p-4 rounded-2xl bg-gray-50 border border-gray-100",children:[f.jsx("div",{className:"text-sm font-bold text-gray-900 mb-2",children:"请在服务器上执行:"}),f.jsx("pre",{className:"text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto",children:"python3 init_admin.py"}),f.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"完成后刷新页面即可进入登录。"})]}),f.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group",children:["我已初始化,刷新 ",f.jsx(bj,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})]}),f.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:f.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!e)return f.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[f.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),f.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),f.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-[3rem] shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[f.jsxs("div",{className:"text-center mb-10",children:[f.jsx("div",{className:"w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 cursor-pointer group p-4",style:{filter:"drop-shadow(0 8px 20px rgba(0,148,247,0.3))"},children:f.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full group-hover:scale-110 transition-transform"})}),f.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),f.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),f.jsxs("form",{onSubmit:N,className:"space-y-5",children:[f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"relative group",children:[f.jsx(iy,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),f.jsx("input",{type:"text",placeholder:"管理员账号",value:h,onChange:O=>m(O.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),f.jsxs("div",{className:"relative group",children:[f.jsx(xT,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),f.jsx("input",{type:"password",placeholder:"密码",value:p,onChange:O=>y(O.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),j&&f.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[f.jsx(VO,{className:"w-4 h-4"})," ",j]}),f.jsx("button",{type:"submit",disabled:x,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:x?f.jsx(Wa,{className:"w-5 h-5 animate-spin"}):f.jsxs(f.Fragment,{children:["立即登录 ",f.jsx(bj,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),f.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:f.jsx("div",{className:"mt-6 text-center",children:f.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const A=()=>{switch(r){case"dashboard":return f.jsx(LO,{});case"accounts":return f.jsx(bF,{});case"orders":return f.jsx(wF,{});case"cards":return f.jsx(jF,{});case"items":return f.jsx(_F,{});case"keywords":return f.jsx(NF,{});case"settings":return f.jsx(SF,{});default:return f.jsx(LO,{})}};return f.jsxs("div",{className:"flex min-h-screen bg-[#F4F5F7] text-[#111]",children:[f.jsx(eD,{activeTab:r,setActiveTab:n,onLogout:()=>{t(!1)}}),f.jsxs("main",{className:"flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth",children:[f.jsx("div",{className:"fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"}),f.jsx("div",{className:"max-w-[1400px] mx-auto pb-10",children:A()})]})]})},i5=document.getElementById("root");if(!i5)throw new Error("Could not find root element to mount to");const AF=zM.createRoot(i5);AF.render(f.jsx(qO.StrictMode,{children:f.jsx(OF,{})})); diff --git a/internal/webui/static/favicon.svg b/internal/webui/static/favicon.svg new file mode 100644 index 0000000..6a4dcb0 --- /dev/null +++ b/internal/webui/static/favicon.svg @@ -0,0 +1,8 @@ + + + Ydisks + + + + + \ No newline at end of file diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html new file mode 100644 index 0000000..864a47b --- /dev/null +++ b/internal/webui/static/index.html @@ -0,0 +1,15 @@ + + + + + + + Ydisks闲鱼助手 - 自动发货与管家系统 + + + + + +
+ + diff --git a/internal/webui/static/squircle.svg b/internal/webui/static/squircle.svg new file mode 100644 index 0000000..fd7cd09 --- /dev/null +++ b/internal/webui/static/squircle.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/internal/webui/static/xianyu_js_version_2.js b/internal/webui/static/xianyu_js_version_2.js new file mode 100644 index 0000000..d6af25f --- /dev/null +++ b/internal/webui/static/xianyu_js_version_2.js @@ -0,0 +1,568 @@ +const crypto = require('crypto') + +const generate_mid = () => { + return "" + Math.floor(1e3 * Math.random()) + new Date().getTime() + " 0" +} + +const generate_uuid = () => { + return "-" + Date.now() + "1" +} + +const generate_device_id = (user_id) => { + for (var ee, et = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""), en = [], eo = Math.random, ei = 0; ei < 36; ei++) + 8 === ei || 13 === ei || 18 === ei || 23 === ei ? en[ei] = "-" : 14 === ei ? en[ei] = "4" : (ee = 0 | 16 * eo(), + en[ei] = et[19 === ei ? 3 & ee | 8 : ee]); + return en.join("") + "-" + user_id +} + + +const generate_sign = (t, token, data) => { + const j = t + const h = 34839810 + const msg = token + "&" + j + "&" + h + "&" + data + const md5 = crypto.createHash('md5') + md5.update(msg) + return md5.digest('hex') +} +eM = new TextDecoder("utf-8"); +eL = null +var sv = Array(4096); + +function sg() { + var ee, et = eI[aG++]; + if (!(et >= 160) || !(et < 192)) + return aG--, + sy(a5()); + if (et -= 160, + aX >= aG) + return eR.slice(aG - aq, (aG += et) - aq); + if (!(0 == aX && eO < 180)) + return se(et); + var en = (et << 5 ^ (et > 1 ? eZ.getUint16(aG) : et > 0 ? eI[aG] : 0)) & 4095 + , eo = sv[en] + , ei = aG + , ec = aG + et - 3 + , eu = 0; + if (eo && eo.bytes == et) { + for (; ei < ec;) { + if ((ee = eZ.getUint32(ei)) != eo[eu++]) { + ei = 1879048192; + break + } + ei += 4 + } + for (ec += 3; ei < ec;) + if ((ee = eI[ei++]) != eo[eu++]) { + ei = 1879048192; + break + } + if (ei === ec) + return aG = ei, + eo.string; + ec -= 3, + ei = aG + } + for (eo = [], + sv[en] = eo, + eo.bytes = et; ei < ec;) + ee = eZ.getUint32(ei), + eo.push(ee), + ei += 4; + for (ec += 3; ei < ec;) + ee = eI[ei++], + eo.push(ee); + var ed = et < 16 ? su(et) : sl(et); + return null != ed ? eo.string = ed : eo.string = se(et) +} + +function sy(ee) { + if ("string" == typeof ee) + return ee; + if ("number" == typeof ee || "boolean" == typeof ee || "bigint" == typeof ee) + return ee.toString(); + if (null == ee) + return ee + ""; + throw Error("Invalid property type for record", typeof ee) +} + +r9 = function (ee) { + return atob(rW(ee)) +} +rW = function (ee) { + return ee.replace(/[^A-Za-z0-9\+\/]/g, "") +} +aW = { + "useRecords": false, + "mapsAsObjects": true +} +aJ = false +eP = [] + +function a3(ee) { + if (!aW.trusted && !aJ) { + var et, en, eo = eP.sharedLength || 0; + eo < eP.length && (eP.length = eo) + } + if (aW.randomAccessStructure && eI[aG] < 64 && eI[aG] >= 32 && ej ? (et = ej(eI, aG, eO, aW), + eI = null, + !(ee && ee.lazy) && et && (et = et.toJSON()), + aG = eO) : et = a5(), + eD && (aG = eD.postBundlePosition, + eD = null), + aJ && (eP.restoreStructures = null), + aG == eO) + eP && eP.restoreStructures && a4(), + eP = null, + eI = null, + eL && (eL = null); + else if (aG > eO) + throw Error("Unexpected end of MessagePack data"); + else if (!aJ) { + try { + en = JSON.stringify(et, function (ee, et) { + return "bigint" == typeof et ? "".concat(et, "n") : et + }).slice(0, 100) + } catch (ee) { + en = "(JSON view not available " + ee + ")" + } + throw Error("Data read, but end of buffer not reached " + en) + } + return et + +} + +function so(ee) { + if (ee < 16 && (et = su(ee))) + return et; + if (ee > 64 && eM) + return eM.decode(eI.subarray(aG, aG += ee)); + var et, en = aG + ee, eo = []; + for (et = ""; aG < en;) { + var ei = eI[aG++]; + if ((128 & ei) === 0) + eo.push(ei); + else if ((224 & ei) === 192) { + var ec = 63 & eI[aG++]; + eo.push((31 & ei) << 6 | ec) + } else if ((240 & ei) === 224) { + var eu = 63 & eI[aG++] + , ed = 63 & eI[aG++]; + eo.push((31 & ei) << 12 | eu << 6 | ed) + } else if ((248 & ei) === 240) { + var ef = (7 & ei) << 18 | (63 & eI[aG++]) << 12 | (63 & eI[aG++]) << 6 | 63 & eI[aG++]; + ef > 65535 && (ef -= 65536, + eo.push(ef >>> 10 & 1023 | 55296), + ef = 56320 | 1023 & ef), + eo.push(ef) + } else + eo.push(ei); + eo.length >= 4096 && (et += sc.apply(String, eo), + eo.length = 0) + } + return eo.length > 0 && (et += sc.apply(String, eo)), + et +} + +se = so; +var sc = String.fromCharCode; + +function sl(ee) { + for (var et = aG, en = Array(ee), eo = 0; eo < ee; eo++) { + var ei = eI[aG++]; + if ((128 & ei) > 0) { + aG = et; + return + } + en[eo] = ei + } + return sc.apply(String, en) +} + +function su(ee) { + if (ee < 4) { + if (ee < 2) { + if (0 === ee) + return ""; + var et = eI[aG++]; + if ((128 & et) > 1) { + aG -= 1; + return + } + return sc(et) + } + var en = eI[aG++] + , eo = eI[aG++]; + if ((128 & en) > 0 || (128 & eo) > 0) { + aG -= 2; + return + } + if (ee < 3) + return sc(en, eo); + var ei = eI[aG++]; + if ((128 & ei) > 0) { + aG -= 3; + return + } + return sc(en, eo, ei) + } + var ec = eI[aG++] + , eu = eI[aG++] + , ed = eI[aG++] + , ef = eI[aG++]; + if ((128 & ec) > 0 || (128 & eu) > 0 || (128 & ed) > 0 || (128 & ef) > 0) { + aG -= 4; + return + } + if (ee < 6) { + if (4 === ee) + return sc(ec, eu, ed, ef); + var ep = eI[aG++]; + if ((128 & ep) > 0) { + aG -= 5; + return + } + return sc(ec, eu, ed, ef, ep) + } + if (ee < 8) { + var em = eI[aG++] + , eh = eI[aG++]; + if ((128 & em) > 0 || (128 & eh) > 0) { + aG -= 6; + return + } + if (ee < 7) + return sc(ec, eu, ed, ef, em, eh); + var ev = eI[aG++]; + if ((128 & ev) > 0) { + aG -= 7; + return + } + return sc(ec, eu, ed, ef, em, eh, ev) + } + var eg = eI[aG++] + , eC = eI[aG++] + , eS = eI[aG++] + , ew = eI[aG++]; + if ((128 & eg) > 0 || (128 & eC) > 0 || (128 & eS) > 0 || (128 & ew) > 0) { + aG -= 8; + return + } + if (ee < 10) { + if (8 === ee) + return sc(ec, eu, ed, ef, eg, eC, eS, ew); + var eE = eI[aG++]; + if ((128 & eE) > 0) { + aG -= 9; + return + } + return sc(ec, eu, ed, ef, eg, eC, eS, ew, eE) + } + if (ee < 12) { + var ek = eI[aG++] + , e_ = eI[aG++]; + if ((128 & ek) > 0 || (128 & e_) > 0) { + aG -= 10; + return + } + if (ee < 11) + return sc(ec, eu, ed, ef, eg, eC, eS, ew, ek, e_); + var eT = eI[aG++]; + if ((128 & eT) > 0) { + aG -= 11; + return + } + return sc(ec, eu, ed, ef, eg, eC, eS, ew, ek, e_, eT) + } + var eN = eI[aG++] + , eM = eI[aG++] + , eO = eI[aG++] + , eP = eI[aG++]; + if ((128 & eN) > 0 || (128 & eM) > 0 || (128 & eO) > 0 || (128 & eP) > 0) { + aG -= 12; + return + } + if (ee < 14) { + if (12 === ee) + return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP); + var eR = eI[aG++]; + if ((128 & eR) > 0) { + aG -= 13; + return + } + return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP, eR) + } + var eD = eI[aG++] + , eL = eI[aG++]; + if ((128 & eD) > 0 || (128 & eL) > 0) { + aG -= 14; + return + } + if (ee < 15) + return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP, eD, eL); + var eZ = eI[aG++]; + if ((128 & eZ) > 0) { + aG -= 15; + return + } + return sc(ec, eu, ed, ef, eg, eC, eS, ew, eN, eM, eO, eP, eD, eL, eZ) +} + +function ss(ee) { + if (aW.mapsAsObjects) { + for (var et = {}, en = 0; en < ee; en++) { + var eo = sg(); + "__proto__" === eo && (eo = "__proto_"), + et[eo] = a5() + } + return et + } + for (var ei = new Map, ec = 0; ec < ee; ec++) + ei.set(a5(), a5()); + return ei +} + +function a5() { + var ee, et = eI[aG++]; + if (et < 160) { + if (et < 128) { + if (et < 64) + return et; + var en = eP[63 & et] || aW.getStructures && a9()[63 & et]; + return en ? (en.read || (en.read = a8(en, 63 & et)), + en.read()) : et + } + if (et < 144) { + if (et -= 128, + aW.mapsAsObjects) { + for (var eo = {}, ei = 0; ei < et; ei++) { + var ec = sg(); + "__proto__" === ec && (ec = "__proto_"), + eo[ec] = a5() + } + return eo + } + for (var eu = new Map, ed = 0; ed < et; ed++) + eu.set(a5(), a5()); + return eu + } + for (var ef = Array(et -= 144), ep = 0; ep < et; ep++) + ef[ep] = a5(); + return aW.freezeData ? Object.freeze(ef) : ef + } + if (et < 192) { + var em = et - 160; + if (aX >= aG) + return eR.slice(aG - aq, (aG += em) - aq); + if (0 == aX && eO < 140) { + var eh = em < 16 ? su(em) : sl(em); + if (null != eh) + return eh + } + return se(em) + } + switch (et) { + case 192: + return null; + case 193: + if (eD) { + if ((ee = a5()) > 0) + return eD[1].slice(eD.position1, eD.position1 += ee); + return eD[0].slice(eD.position0, eD.position0 -= ee) + } + return aY; + case 194: + return !1; + case 195: + return !0; + case 196: + if (void 0 === (ee = eI[aG++])) + throw Error("Unexpected end of buffer"); + return sm(ee); + case 197: + return ee = eZ.getUint16(aG), + aG += 2, + sm(ee); + case 198: + return ee = eZ.getUint32(aG), + aG += 4, + sm(ee); + case 199: + return sh(eI[aG++]); + case 200: + return ee = eZ.getUint16(aG), + aG += 2, + sh(ee); + case 201: + return ee = eZ.getUint32(aG), + aG += 4, + sh(ee); + case 202: + if (ee = eZ.getFloat32(aG), + aW.useFloat32 > 2) { + var ev = sT[(127 & eI[aG]) << 1 | eI[aG + 1] >> 7]; + return aG += 4, + (ev * ee + (ee > 0 ? .5 : -.5) >> 0) / ev + } + return aG += 4, + ee; + case 203: + return ee = eZ.getFloat64(aG), + aG += 8, + ee; + case 204: + return eI[aG++]; + case 205: + return ee = eZ.getUint16(aG), + aG += 2, + ee; + case 206: + return ee = eZ.getUint32(aG), + aG += 4, + ee; + case 207: + return "number" === aW.int64AsType ? ee = 4294967296 * eZ.getUint32(aG) + eZ.getUint32(aG + 4) : "string" === aW.int64AsType ? ee = eZ.getBigUint64(aG).toString() : "auto" === aW.int64AsType ? (ee = eZ.getBigUint64(aG)) <= BigInt(2) << BigInt(52) && (ee = Number(ee)) : ee = eZ.getBigUint64(aG), + aG += 8, + ee; + case 208: + return eZ.getInt8(aG++); + case 209: + return ee = eZ.getInt16(aG), + aG += 2, + ee; + case 210: + return ee = eZ.getInt32(aG), + aG += 4, + ee; + case 211: + return "number" === aW.int64AsType ? ee = 4294967296 * eZ.getInt32(aG) + eZ.getUint32(aG + 4) : "string" === aW.int64AsType ? ee = eZ.getBigInt64(aG).toString() : "auto" === aW.int64AsType ? (ee = eZ.getBigInt64(aG)) >= BigInt(-2) << BigInt(52) && ee <= BigInt(2) << BigInt(52) && (ee = Number(ee)) : ee = eZ.getBigInt64(aG), + aG += 8, + ee; + case 212: + if (114 == (ee = eI[aG++])) + return sC(63 & eI[aG++]); + var eg = aK[ee]; + if (eg) { + if (eg.read) + return aG++, + eg.read(a5()); + if (eg.noBuffer) + return aG++, + eg(); + return eg(eI.subarray(aG, ++aG)) + } + throw Error("Unknown extension " + ee); + case 213: + if (114 == (ee = eI[aG])) + return aG++, + sC(63 & eI[aG++], eI[aG++]); + return sh(2); + case 214: + return sh(4); + case 215: + return sh(8); + case 216: + return sh(16); + case 217: + if (ee = eI[aG++], + aX >= aG) + return eR.slice(aG - aq, (aG += ee) - aq); + return st(ee); + case 218: + if (ee = eZ.getUint16(aG), + aG += 2, + aX >= aG) + return eR.slice(aG - aq, (aG += ee) - aq); + return sn(ee); + case 219: + if (ee = eZ.getUint32(aG), + aG += 4, + aX >= aG) + return eR.slice(aG - aq, (aG += ee) - aq); + return sr(ee); + case 220: + return ee = eZ.getUint16(aG), + aG += 2, + si(ee); + case 221: + return ee = eZ.getUint32(aG), + aG += 4, + si(ee); + case 222: + return ee = eZ.getUint16(aG), + aG += 2, + ss(ee); + case 223: + return ee = eZ.getUint32(aG), + aG += 4, + ss(ee); + default: + if (et >= 224) + return et - 256; + if (void 0 === et) { + var eC = Error("Unexpected end of MessagePack data"); + throw eC.incomplete = !0, + eC + } + throw Error("Unknown MessagePack token " + et) + } +} + +sn = so +var a6 = /^[a-zA-Z_$][a-zA-Z\d_$]*$/; +const decrypt = (ee) => { + for (var et, en, eo = r9(ee), ei = eo.length, ec = new Uint8Array(ei), eu = 0; eu < ei; eu++) { + var ed = eo.charCodeAt(eu); + ec[eu] = ed + } + en = {} + et = ec; + et.buffer || et.constructor !== ArrayBuffer || (et = "undefined" != typeof Buffer ? Buffer.from(et) : new Uint8Array(et)), + "object" == typeof en ? (eO = en.end || et.length, + aG = en.start || 0) : (aG = 0, + eO = en > -1 ? en : et.length), + aX = 0, + eR = null, + eD = null, + eI = et; + eM = new TextDecoder("utf-8"); + eL = null + + eP = []; + eZ = et.dataView || (et.dataView = new DataView(et.buffer, et.byteOffset, et.byteLength)) + res = a3(en) + // ec = ecc; + // rA = 0; + // rB = 0; + // ed = []; + // eu = ec.length; + // rj = { + // "useRecords": false, + // "mapsAsObjects": true + // } + // // ei 是 TextDecoder + // ei = new TextDecoder("utf-8"); + // eh = new DataView(ec.buffer, ec.byteOffset, ec.byteLength); + // ec.dataView = eh; + // let res = rK() + const replacer = (key, value) => { + if (typeof value === 'bigint') { + return value.toString(); + } + return value; + }; + + res = JSON.stringify(res, replacer); + return res; +} + + +// console.log(generate_mid()) +// console.log(generate_uuid()) +// console.log(generate_device_id()) +// console.log(generate_sign('5f65b00f83994987e334f97360d69557', '{"sessionTypes":"1,19"}')) +// let msg = "ggGLAYEBtTIyMDI2NDA5MTgwNzlAZ29vZmlzaAKzNDc4MTI4NzAwMDBAZ29vZmlzaAOxMzQwMjM5MTQ3MjUwMy5QTjQEAAXPAAABlYW04bIGggFlA4UBoAKjMTExA6AEAQXaADR7ImF0VXNlcnMiOltdLCJjb250ZW50VHlwZSI6MSwidGV4dCI6eyJ0ZXh0IjoiMTExIn19BwIIAQkACoupX3BsYXRmb3Jtp2FuZHJvaWSmYml6VGFn2gBBeyJzb3VyY2VJZCI6IlM6MSIsIm1lc3NhZ2VJZCI6ImYzNjkwMmVmZjQ1NDQ1YmRiMmQxYjBmZDE2OGY4MjY0In2sZGV0YWlsTm90aWNlozExMadleHRKc29u2gBLeyJxdWlja1JlcGx5IjoiMSIsIm1lc3NhZ2VJZCI6ImYzNjkwMmVmZjQ1NDQ1YmRiMmQxYjBmZDE2OGY4MjY0IiwidGFnIjoidSJ9r3JlbWluZGVyQ29udGVudKMxMTGucmVtaW5kZXJOb3RpY2W15Y+R5p2l5LiA5p2h5paw5raI5oGvrXJlbWluZGVyVGl0bGWmc2hh5L+uq3JlbWluZGVyVXJs2gCbZmxlYW1hcmtldDovL21lc3NhZ2VfY2hhdD9pdGVtSWQ9ODk3NzQyNzQ4MDExJnBlZXJVc2VySWQ9MjIwMjY0MDkxODA3OSZwZWVyVXNlck5pY2s9dCoqKjEmc2lkPTQ3ODEyODcwMDAwJm1lc3NhZ2VJZD1mMzY5MDJlZmY0NTQ0NWJkYjJkMWIwZmQxNjhmODI2NCZhZHY9bm+sc2VuZGVyVXNlcklkrTIwMjY0MDkxODA3Oy5zZW5kZXJVc2VyVHlwYaEwq3Nlc3Npb25UeXBloTGqdXBkYXRlSGVhZKR0cnVl"; +// +// msg = "ggGLAYEBsjMxNDk2MzcwNjNAZ29vZmlzaAKzNDc5ODMzODkwOTZAZ29vZmlzaAOxMzQxNjU2NTI3NDU0Mi5QTjQEAAXPAAABlbKji20GggFlA4UBoAK6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl0DoAQaBdoEKnsiY29udGVudFR5cGUiOjI2LCJkeENhcmQiOnsiaXRlbSI6eyJtYWluIjp7ImNsaWNrUGFyYW0iOnsiYXJnMSI6Ik1zZ0NhcmQiLCJhcmdzIjp7InNvdXJjZSI6ImltIiwidGFza19pZCI6IjNleFFKSE9UbVBVMSIsIm1zZ19pZCI6ImNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczIn19LCJleENvbnRlbnQiOnsiYmdDb2xvciI6IiNGRkZGRkYiLCJidXR0b24iOnsiYmdDb2xvciI6IiNGRkU2MEYiLCJib3JkZXJDb2xvciI6IiNGRkU2MEYiLCJjbGlja1BhcmFtIjp7ImFyZzEiOiJNc2dDYXJkQWN0aW9uIiwiYXJncyI6eyJzb3VyY2UiOiJpbSIsInRhc2tfaWQiOiIzZXhRSkhPVG1QVTEiLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9fSwiZm9udENvbG9yIjoiIzMzMzMzMyIsInRhcmdldFVybCI6ImZsZWFtYXJrZXQ6Ly9hZGp1c3RfcHJpY2U/Zmx1dHRlcj10cnVlJmJpek9yZGVySWQ9MjUwMzY4ODEyNjM1NjYzNjM3MCIsInRleHQiOiLkv67mlLnku7fmoLwifSwiZGVzYyI6Iuivt+WPjOaWueayn+mAmuWPiuaXtuehruiupOS7t+agvCIsImRlc2NDb2xvciI6IiNBM0EzQTMiLCJ0aXRsZSI6IuaIkeW3suaLjeS4i++8jOW+heS7mOasviIsInVwZ3JhZGUiOnsidGFyZ2V0VXJsIjoiaHR0cHM6Ly9oNS5tLmdvb2Zpc2guY29tL2FwcC9pZGxlRmlzaC1GMmUvZm0tZG93bmxvYWQvaG9tZS5odG1sP25vUmVkcmllY3Q9dHJ1ZSZjYW5CYWNrPXRydWUmY2hlY2tWZXJzaW9uPXRydWUiLCJ2ZXJzaW9uIjoiNy43LjkwIn19LCJ0YXJnZXRVcmwiOiJmbGVhbWFya2V0Oi8vb3JkZXJfZGV0YWlsP2lkPTI1MDM2ODgxMjYzNTY2MzYzNzAmcm9sZT1zZWxsZXIifX0sInRlbXBsYXRlIjp7Im5hbWUiOiJpZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZCIsInVybCI6Imh0dHBzOi8vZGluYW1pY3guYWxpYmFiYXVzZXJjb250ZW50LmNvbS9wdWIvaWRsZWZpc2hfbWVzc2FnZV90cmFkZV9jaGF0X2NhcmQvMTY2NzIyMjA1Mjc2Ny9pZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZC56aXAiLCJ2ZXJzaW9uIjoiMTY2NzIyMjA1Mjc2NyJ9fX0HAQgBCQAK3gAQpmJpelRhZ9oAe3sic291cmNlSWQiOiJDMkM6M2V4UUpIT1RtUFUxIiwidGFza05hbWUiOiLlt7Lmi43kuItf5pyq5LuY5qy+X+WNluWutiIsIm1hdGVyaWFsSWQiOiIzZXhRSkhPVG1QVTEiLCJ0YXNrSWQiOiIzZXhRSkhPVG1QVTEifbFjbG9zZVB1c2hSZWNlaXZlcqVmYWxzZbFjbG9zZVVucmVhZE51bWJlcqVmYWxzZaxkZXRhaWxOb3RpY2W6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2nZXh0SnNvbtoBr3sibXNnQXJncyI6eyJ0YXNrX2lkIjoiM2V4UUpIT1RtUFUxIiwic291cmNlIjoiaW0iLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9LCJxdWlja1JlcGx5IjoiMSIsIm1zZ0FyZzEiOiJNc2dDYXJkIiwidXBkYXRlS2V5IjoiNDc5ODMzODkwOTY6MjUwMzY4ODEyNjM1NjYzNjM3MDoxX25vdF9wYXlfc2VsbGVyIiwibWVzc2FnZUlkIjoiY2M4YmMyZGY3YzkzNGRmMDg2ZTA1NjdjYjY5ZjE1NzMiLCJtdWx0aUNoYW5uZWwiOnsiaHVhd2VpIjoiRVhQUkVTUyIsInhpYW9taSI6IjEwODAwMCIsIm9wcG8iOiJFWFBSRVNTIiwiaG9ub3IiOiJOT1JNQUwiLCJhZ29vIjoicHJvZHVjdCIsInZpdm8iOiJPUkRFUiJ9LCJjb250ZW50VHlwZSI6IjI2IiwiY29ycmVsYXRpb25Hcm91cElkIjoiM2V4UUpIT1RtUFUxX0ZGcjRHT1NuOE9RbyJ9qHJlY2VpdmVyrTIyMDI2NDA5MTgwNzmrcmVkUmVtaW5kZXKy562J5b6F5Lmw5a625LuY5qy+sHJlZFJlbWluZGVyU3R5bGWhMa9yZW1pbmRlckNvbnRlbnS6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2ucmVtaW5kZXJOb3RpY2W75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+rXJlbWluZGVyVGl0bGW75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+q3JlbWluZGVyVXJs2gCbZmxlYW1hcmtldDovL21lc3NhZ2VfY2hhdD9pdGVtSWQ9OTAwMDUyNjQ0Mjc3JnBlZXJVc2VySWQ9MzE0OTYzNzA2MyZwZWVyVXNlck5pY2s955S3KioqeSZzaWQ9NDc5ODMzODkwOTYmbWVzc2FnZUlkPWNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczJmFkdj1ub6xzZW5kZXJVc2VySWSqMzE0OTYzNzA2M65zZW5kZXJVc2VyVHlwZaEwq3Nlc3Npb25UeXBloTGqdXBkYXRlSGVhZKR0cnVl" +// msg = "hAGzNDc5ODMzODkwOTZAZ29vZmlzaAIBA4KrcmVkUmVtaW5kZXKy562J5b6F5Lmw5a625LuY5qy+sHJlZFJlbWluZGVyU3R5bGWhMQTPAAABlbMlNng=" +// res = decrypt(msg); +// console.log(res); diff --git a/internal/webui/static/ydisks-logo.svg b/internal/webui/static/ydisks-logo.svg new file mode 100755 index 0000000..52916f8 --- /dev/null +++ b/internal/webui/static/ydisks-logo.svg @@ -0,0 +1,10 @@ + + + 单独LOGO + + + + + \ No newline at end of file diff --git a/internal/webui/webui.go b/internal/webui/webui.go new file mode 100644 index 0000000..b672cbf --- /dev/null +++ b/internal/webui/webui.go @@ -0,0 +1,14 @@ +package webui + +import ( + "embed" + "io/fs" +) + +//go:embed static/* +var files embed.FS + +// Static returns the embedded built frontend rooted at static/. +func Static() (fs.FS, error) { + return fs.Sub(files, "static") +} diff --git a/internal/xianyu/mtop/client.go b/internal/xianyu/mtop/client.go new file mode 100644 index 0000000..17413f6 --- /dev/null +++ b/internal/xianyu/mtop/client.go @@ -0,0 +1,970 @@ +// Package mtop 实现闲鱼 mtop H5 API 客户端,移植自 Python 端 refresh_token()。 +// 关键:签名只覆盖 (t, token, data_val),与 URL query 参数无关;token 取自 cookie _m_h5_tk 前半段。 +package mtop + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "xianyu-go/internal/xianyu" + "xianyu-go/internal/xianyu/protocol" +) + +// WS 注册用的 appKey(注意与签名用的 protocol.SignAppKey=34839810 不同)。 +const RegAppKey = "444e9908a51d1cb236a27862abc769c9" + +// TokenAPI 取 access token 的端点。 +const TokenAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.login.token/1.0/" + +// ConsignAPI 是虚拟商品确认发货端点。 +const ConsignAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.logistic.consign.dummy/1.0/" + +// OrderDetailAPI 是卖家订单详情端点。 +const OrderDetailAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.trade.order.detail/1.0/" + +// UserPageNavAPI 是 PC 站当前登录账号资料端点。 +const UserPageNavAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.user.page.nav/1.0/" + +// ItemListAPI 是卖家商品列表端点。 +const ItemListAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.xyh.item.list/1.0/" + +const ( + MTopRetryGap = time.Second + ItemPageGap = time.Second +) + +// Client 是 mtop API 客户端。零值可用;HTTP 超时默认 30s。 +type Client struct { + HTTPClient *http.Client + TokenURL string + ConsignURL string + OrderDetailURL string +} + +// RefreshResult 是刷新 token 的结果。 +type RefreshResult struct { + AccessToken string // 用于 WS /reg 注册 + UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同) +} + +// UserProfileResult 是 mtop.idle.web.user.page.nav 返回的当前账号资料。 +type UserProfileResult struct { + Nickname string + DisplayNick string + AvatarURL string + UpdatedCookies string +} + +// ItemListResult 是卖家商品列表结果。 +type ItemListResult struct { + Items []ItemListItem + PageNumber int + PageSize int + CurrentCount int + TotalCount int + TotalPages int + SavedCountHint int + UpdatedCookies string +} + +// ItemListItem 是 mtop.idle.web.xyh.item.list 的核心商品信息。 +type ItemListItem struct { + ID string + Title string + Price string + PriceText string + CategoryID string + DetailURL string + WebURL string + PicURL string + ItemDetail string + AuctionType string + ItemStatus int +} + +// OrderDetailResult 是订单详情接口中自动发货需要的字段。 +type OrderDetailResult struct { + Quantity string + SpecName string + SpecValue string + OrderStatus string + Amount string + UpdatedCookies string +} + +// FetchOrderDetail 获取订单真实成交价、数量、状态和规格;token 过期时自动重签重试。 +func (c *Client) FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, error) { + currentCookies := cookiesStr + var lastRet []string + for attempt := 0; attempt < 4; attempt++ { + previousCookies := currentCookies + result, ret, updated, err := c.fetchOrderDetailOnce(ctx, currentCookies, orderID) + if err != nil { + return nil, err + } + lastRet = ret + if updated != "" { + currentCookies = updated + } + if result != nil { + result.UpdatedCookies = currentCookies + return result, nil + } + if !isTokenExpiredRet(ret) { + return nil, fmt.Errorf("订单详情接口返回非成功: ret=%v", ret) + } + if attempt == 3 { + break + } + if currentCookies == previousCookies { + refreshed, refreshErr := c.RefreshTokenContext(ctx, currentCookies) + if refreshErr != nil { + return nil, fmt.Errorf("订单详情 token 刷新失败: %w", refreshErr) + } + currentCookies = refreshed.UpdatedCookies + } + if err := sleepCtx(ctx, MTopRetryGap); err != nil { + return nil, err + } + } + return nil, fmt.Errorf("订单详情 token 重试失败: ret=%v", lastRet) +} + +func (c *Client) fetchOrderDetailOnce(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, []string, string, error) { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + cookies := protocol.TransCookies(cookiesStr) + t := strconv.FormatInt(time.Now().UnixMilli(), 10) + dataVal := `{"tid":"` + orderID + `"}` + sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal) + endpoint := c.OrderDetailURL + if endpoint == "" { + endpoint = OrderDetailAPI + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildOrderDetailQuery(t, sign), strings.NewReader("data="+url.QueryEscape(dataVal))) + if err != nil { + return nil, nil, cookiesStr, err + } + setCommonHeaders(req, cookiesStr) + resp, err := hc.Do(req) + if err != nil { + return nil, nil, cookiesStr, fmt.Errorf("订单详情请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, nil, cookiesStr, err + } + updated := mergeSetCookie(cookiesStr, cookies, resp) + var decoded struct { + Ret []string `json:"ret"` + Data map[string]any `json:"data"` + } + if err := json.Unmarshal(raw, &decoded); err != nil { + return nil, nil, updated, fmt.Errorf("解析订单详情响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + } + if !hasMTopSuccess(decoded.Ret) { + return nil, decoded.Ret, updated, nil + } + result := &OrderDetailResult{Quantity: "1"} + if utArgs, ok := decoded.Data["utArgs"].(map[string]any); ok { + result.OrderStatus = mtopString(utArgs["orderStatus"]) + } + components, _ := decoded.Data["components"].([]any) + for _, component := range components { + cm, _ := component.(map[string]any) + if cm["render"] != "orderInfoVO" { + continue + } + componentData, _ := cm["data"].(map[string]any) + if itemInfo, ok := componentData["itemInfo"].(map[string]any); ok { + if value := mtopString(itemInfo["buyAmount"]); value != "" { + result.Quantity = value + } + result.SpecName = mtopString(itemInfo["specName"]) + result.SpecValue = mtopString(itemInfo["specValue"]) + } + if priceInfo, ok := componentData["priceInfo"].(map[string]any); ok { + if amount, ok := priceInfo["amount"].(map[string]any); ok { + result.Amount = mtopString(amount["value"]) + } + } + } + return result, decoded.Ret, updated, nil +} + +// FetchUserProfile 获取当前 cookie 对应账号的实时昵称和头像。 +func (c *Client) FetchUserProfile(ctx context.Context, cookiesStr string) (*UserProfileResult, error) { + currentCookies := cookiesStr + var lastRet []string + for attempt := 0; attempt < 4; attempt++ { + res, ret, updatedCookies, err := c.fetchUserProfileOnce(ctx, currentCookies) + if err != nil { + return nil, err + } + lastRet = ret + if res != nil { + return res, nil + } + if !isTokenExpiredRet(ret) { + return nil, fmt.Errorf("账号资料接口返回非成功: ret=%v", ret) + } + if updatedCookies != "" && updatedCookies != currentCookies { + currentCookies = updatedCookies + if err := sleepCtx(ctx, MTopRetryGap); err != nil { + return nil, err + } + continue + } + if err := sleepCtx(ctx, MTopRetryGap); err != nil { + return nil, err + } + refreshed, err := c.RefreshToken(currentCookies) + if err != nil { + return nil, fmt.Errorf("刷新 mtop token 失败: %w", err) + } + currentCookies = refreshed.UpdatedCookies + } + return nil, fmt.Errorf("账号资料接口 token 重试失败: ret=%v", lastRet) +} + +func (c *Client) fetchUserProfileOnce(ctx context.Context, cookiesStr string) (*UserProfileResult, []string, string, error) { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + + cookies := protocol.TransCookies(cookiesStr) + dataVal := "{}" + t := strconv.FormatInt(time.Now().UnixMilli(), 10) + sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal) + query := buildUserPageNavQuery(t, sign) + body := "data=" + url.QueryEscape(dataVal) + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, UserPageNavAPI+"?"+query, strings.NewReader(body)) + if err != nil { + return nil, nil, cookiesStr, err + } + setCommonHeaders(req, cookiesStr) + + resp, err := hc.Do(req) + if err != nil { + return nil, nil, cookiesStr, fmt.Errorf("账号资料请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, nil, cookiesStr, err + } + updated := mergeSetCookie(cookiesStr, cookies, resp) + + var decoded struct { + Ret []string `json:"ret"` + Data map[string]any `json:"data"` + } + if err := json.Unmarshal(raw, &decoded); err != nil { + return nil, nil, updated, fmt.Errorf("解析账号资料响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + } + if !hasMTopSuccess(decoded.Ret) { + return nil, decoded.Ret, updated, nil + } + + profile := parseUserProfile(decoded.Data) + profile.UpdatedCookies = updated + return profile, decoded.Ret, updated, nil +} + +// Consign 调用 mtop.taobao.idle.logistic.consign.dummy 确认发货(虚拟发货)。 +// data_val 形如 {"orderId":"...","tradeText":"","picList":[],"newUnconsign":true}。 +// 返回成功标志、响应 ret 列表、可能更新后的 cookie。 +// 移植自 secure_confirm_decrypted.auto_confirm。 +func (c *Client) Consign(cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) { + return c.ConsignContext(context.Background(), cookiesStr, orderID) +} + +// ConsignContext 确认发货;签名 token 过期时使用响应下发的新 Cookie 重签并重试。 +func (c *Client) ConsignContext(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) { + currentCookies := cookiesStr + var lastRet []string + for attempt := 0; attempt < 4; attempt++ { + previousCookies := currentCookies + ok, ret, updated, requestErr := c.consignOnce(ctx, currentCookies, orderID) + if requestErr != nil { + return false, ret, currentCookies, requestErr + } + lastRet = ret + if updated != "" { + currentCookies = updated + } + if ok { + return true, ret, currentCookies, nil + } + if !isTokenExpiredRet(ret) { + return false, ret, currentCookies, nil + } + if attempt == 3 { + break + } + + // MTop 通常会在 token 过期响应中通过 Set-Cookie 下发新签名 token。 + // 若没有下发,则主动调用 token API 尝试刷新一次。 + if currentCookies == previousCookies { + refreshed, refreshErr := c.RefreshTokenContext(ctx, currentCookies) + if refreshErr != nil { + return false, ret, currentCookies, fmt.Errorf("consign token 过期且刷新失败: %w", refreshErr) + } + if refreshed.UpdatedCookies != "" { + currentCookies = refreshed.UpdatedCookies + } + } + if err := sleepCtx(ctx, MTopRetryGap); err != nil { + return false, ret, currentCookies, err + } + } + return false, lastRet, currentCookies, nil +} + +func (c *Client) consignOnce(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + cookies := protocol.TransCookies(cookiesStr) + token := protocol.SignToken(cookiesStr) + t := strconv.FormatInt(time.Now().UnixMilli(), 10) + dataVal := `{"orderId":"` + orderID + `", "tradeText":"","picList":[],"newUnconsign":true}` + sign := protocol.GenerateSign(t, token, dataVal) + + query := buildConsignQuery(t, sign) + body := "data=" + url.QueryEscape(dataVal) + consignURL := c.ConsignURL + if consignURL == "" { + consignURL = ConsignAPI + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + consignURL+"?"+query, + strings.NewReader(body)) + if err != nil { + return false, nil, cookiesStr, err + } + setCommonHeaders(req, cookiesStr) + resp, err := hc.Do(req) + if err != nil { + return false, nil, cookiesStr, fmt.Errorf("consign 请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return false, nil, cookiesStr, err + } + updated := mergeSetCookie(cookiesStr, cookies, resp) + var res struct { + Ret []string `json:"ret"` + } + if err := json.Unmarshal(raw, &res); err != nil { + return false, nil, updated, fmt.Errorf("解析 consign 响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + } + for _, r := range res.Ret { + if strings.Contains(r, "SUCCESS::调用成功") { + return true, res.Ret, updated, nil + } + } + return false, res.Ret, updated, nil +} + +// FetchItemsPage 获取指定页卖家在售商品列表。 +func (c *Client) FetchItemsPage(ctx context.Context, cookiesStr string, pageNumber, pageSize int) (*ItemListResult, error) { + if pageNumber < 1 { + pageNumber = 1 + } + if pageSize < 1 { + pageSize = 20 + } + currentCookies := cookiesStr + var lastRet []string + for attempt := 0; attempt < 4; attempt++ { + res, ret, updatedCookies, err := c.fetchItemsPageOnce(ctx, currentCookies, pageNumber, pageSize) + if err != nil { + return nil, err + } + lastRet = ret + if res != nil { + return res, nil + } + if !isTokenExpiredRet(ret) { + return nil, fmt.Errorf("商品列表接口返回非成功: ret=%v", ret) + } + if updatedCookies != "" && updatedCookies != currentCookies { + currentCookies = updatedCookies + if err := sleepCtx(ctx, MTopRetryGap); err != nil { + return nil, err + } + continue + } + if err := sleepCtx(ctx, MTopRetryGap); err != nil { + return nil, err + } + refreshed, err := c.RefreshToken(currentCookies) + if err != nil { + return nil, fmt.Errorf("刷新 mtop token 失败: %w", err) + } + currentCookies = refreshed.UpdatedCookies + } + return nil, fmt.Errorf("商品列表接口 token 重试失败: ret=%v", lastRet) +} + +func (c *Client) fetchItemsPageOnce(ctx context.Context, cookiesStr string, pageNumber, pageSize int) (*ItemListResult, []string, string, error) { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + cookies := protocol.TransCookies(cookiesStr) + userID := cookies["unb"] + if userID == "" { + return nil, nil, cookiesStr, fmt.Errorf("cookie 缺少 unb 字段,无法获取商品列表") + } + + data := map[string]any{ + "needGroupInfo": false, + "pageNumber": pageNumber, + "pageSize": pageSize, + "groupName": "在售", + "groupId": "58877261", + "defaultGroup": true, + "userId": userID, + } + rawData, _ := json.Marshal(data) + dataVal := string(rawData) + t := strconv.FormatInt(time.Now().UnixMilli(), 10) + sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal) + query := buildItemListQuery(t, sign) + body := "data=" + url.QueryEscape(dataVal) + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, ItemListAPI+"?"+query, strings.NewReader(body)) + if err != nil { + return nil, nil, cookiesStr, err + } + setCommonHeaders(req, cookiesStr) + resp, err := hc.Do(req) + if err != nil { + return nil, nil, cookiesStr, fmt.Errorf("商品列表请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, nil, cookiesStr, err + } + updated := mergeSetCookie(cookiesStr, cookies, resp) + + var decoded struct { + Ret []string `json:"ret"` + Data map[string]any `json:"data"` + } + if err := json.Unmarshal(raw, &decoded); err != nil { + return nil, nil, updated, fmt.Errorf("解析商品列表响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + } + if !hasMTopSuccess(decoded.Ret) { + return nil, decoded.Ret, updated, nil + } + + items := parseItemList(decoded.Data) + return &ItemListResult{ + Items: items, + PageNumber: pageNumber, + PageSize: pageSize, + CurrentCount: len(items), + SavedCountHint: len(items), + UpdatedCookies: updated, + }, decoded.Ret, updated, nil +} + +// FetchAllItems 自动分页获取卖家全部在售商品。maxPages <= 0 表示不限页。 +func (c *Client) FetchAllItems(ctx context.Context, cookiesStr string, pageSize, maxPages int) (*ItemListResult, error) { + if pageSize <= 0 { + pageSize = 20 + } + currentCookies := cookiesStr + page := 1 + var all []ItemListItem + for { + if maxPages > 0 && page > maxPages { + break + } + res, err := c.FetchItemsPage(ctx, currentCookies, page, pageSize) + if err != nil { + return nil, err + } + currentCookies = res.UpdatedCookies + all = append(all, res.Items...) + if len(res.Items) < pageSize { + break + } + page++ + if err := sleepCtx(ctx, ItemPageGap); err != nil { + return nil, err + } + } + return &ItemListResult{ + Items: all, + PageNumber: 1, + PageSize: pageSize, + CurrentCount: len(all), + TotalCount: len(all), + TotalPages: page, + SavedCountHint: len(all), + UpdatedCookies: currentCookies, + }, nil +} + +func buildItemListQuery(t, sign string) string { + parts := [][2]string{ + {"jsv", "2.7.2"}, + {"appKey", protocol.SignAppKey}, + {"t", t}, + {"sign", sign}, + {"v", "1.0"}, + {"type", "originaljson"}, + {"accountSite", "xianyu"}, + {"dataType", "json"}, + {"timeout", "20000"}, + {"api", "mtop.idle.web.xyh.item.list"}, + {"sessionOption", "AutoLoginOnly"}, + {"spm_cnt", "a21ybx.im.0.0"}, + {"spm_pre", "a21ybx.collection.menu.1.272b5141NafCNK"}, + } + var b strings.Builder + for i, p := range parts { + if i > 0 { + b.WriteByte('&') + } + b.WriteString(p[0]) + b.WriteByte('=') + b.WriteString(url.QueryEscape(p[1])) + } + return b.String() +} + +func buildUserPageNavQuery(t, sign string) string { + parts := [][2]string{ + {"jsv", "2.7.2"}, + {"appKey", protocol.SignAppKey}, + {"t", t}, + {"sign", sign}, + {"v", "1.0"}, + {"type", "originaljson"}, + {"accountSite", "xianyu"}, + {"dataType", "json"}, + {"timeout", "20000"}, + {"api", "mtop.idle.web.user.page.nav"}, + {"sessionOption", "AutoLoginOnly"}, + {"ecode", "0"}, + {"spm_cnt", "a21ybx.home.0.0"}, + } + var b strings.Builder + for i, p := range parts { + if i > 0 { + b.WriteByte('&') + } + b.WriteString(p[0]) + b.WriteByte('=') + b.WriteString(url.QueryEscape(p[1])) + } + return b.String() +} + +func buildOrderDetailQuery(t, sign string) string { + return "jsv=2.7.2&appKey=" + protocol.SignAppKey + + "&t=" + t + "&sign=" + sign + + "&v=1.0&type=originaljson&accountSite=xianyu&dataType=json&timeout=20000" + + "&api=mtop.idle.web.trade.order.detail&sessionOption=AutoLoginOnly&valueType=string" +} + +func parseUserProfile(data map[string]any) *UserProfileResult { + module, _ := data["module"].(map[string]any) + base, _ := module["base"].(map[string]any) + if base == nil { + return &UserProfileResult{} + } + nickname := strings.TrimSpace(mtopString(base["displayName"])) + displayNick := strings.TrimSpace(mtopString(base["displayNick"])) + if nickname == "" { + nickname = displayNick + } + return &UserProfileResult{ + Nickname: nickname, + DisplayNick: displayNick, + AvatarURL: strings.TrimSpace(mtopString(base["avatar"])), + } +} + +func parseItemList(data map[string]any) []ItemListItem { + cardList, _ := data["cardList"].([]any) + items := make([]ItemListItem, 0, len(cardList)) + for _, rawCard := range cardList { + card, ok := rawCard.(map[string]any) + if !ok { + continue + } + cardData, _ := card["cardData"].(map[string]any) + if cardData == nil { + continue + } + detailParams, _ := cardData["detailParams"].(map[string]any) + itemID := mtopString(detailParams["itemId"]) + if itemID == "" { + itemID = mtopString(cardData["id"]) + } + if itemID == "" || strings.HasPrefix(itemID, "auto_") { + continue + } + priceInfo, _ := cardData["priceInfo"].(map[string]any) + price := mtopString(priceInfo["price"]) + priceText := mtopString(priceInfo["preText"]) + price + picInfo, _ := cardData["picInfo"].(map[string]any) + picURL := mtopString(picInfo["picUrl"]) + detailURL := mtopString(cardData["detailUrl"]) + detail := map[string]any{ + "title": mtopString(cardData["title"]), + "price": price, + "price_text": priceText, + "category_id": mtopString(cardData["categoryId"]), + "auction_type": mtopString(cardData["auctionType"]), + "item_status": mtopInt(cardData["itemStatus"]), + "detail_url": detailURL, + "web_url": "https://www.goofish.com/item?id=" + itemID, + "pic_info": picInfo, + "detail_params": detailParams, + "track_params": cardData["trackParams"], + "item_label_data": cardData["itemLabelDataVO"], + "card_type": mtopInt(card["cardType"]), + } + detailJSON, _ := json.Marshal(detail) + items = append(items, ItemListItem{ + ID: itemID, + Title: mtopString(cardData["title"]), + Price: price, + PriceText: priceText, + CategoryID: mtopString(cardData["categoryId"]), + DetailURL: detailURL, + WebURL: "https://www.goofish.com/item?id=" + itemID, + PicURL: picURL, + ItemDetail: string(detailJSON), + AuctionType: mtopString(cardData["auctionType"]), + ItemStatus: mtopInt(cardData["itemStatus"]), + }) + } + return items +} + +func hasMTopSuccess(ret []string) bool { + for _, r := range ret { + if strings.Contains(r, "SUCCESS::调用成功") { + return true + } + } + return false +} + +func isTokenExpiredRet(ret []string) bool { + for _, r := range ret { + lower := strings.ToLower(r) + if strings.Contains(lower, "token") || strings.Contains(r, "FAIL_SYS_TOKEN_EXOIRED") || strings.Contains(r, "FAIL_SYS_TOKEN_EXPIRED") { + return true + } + } + return false +} + +func mtopString(v any) string { + switch x := v.(type) { + case string: + return x + case float64: + return strconv.FormatInt(int64(x), 10) + case int: + return strconv.Itoa(x) + case json.Number: + return x.String() + default: + return "" + } +} + +func mtopInt(v any) int { + switch x := v.(type) { + case float64: + return int(x) + case int: + return x + case string: + n, _ := strconv.Atoi(x) + return n + case json.Number: + n, _ := strconv.Atoi(x.String()) + return n + default: + return 0 + } +} + +func buildConsignQuery(t, sign string) string { + parts := [][2]string{ + {"jsv", "2.7.2"}, + {"appKey", protocol.SignAppKey}, + {"t", t}, + {"sign", sign}, + {"v", "1.0"}, + {"type", "originaljson"}, + {"accountSite", "xianyu"}, + {"dataType", "json"}, + {"timeout", "20000"}, + {"api", "mtop.taobao.idle.logistic.consign.dummy"}, + {"sessionOption", "AutoLoginOnly"}, + } + var b strings.Builder + for i, p := range parts { + if i > 0 { + b.WriteByte('&') + } + b.WriteString(p[0]) + b.WriteByte('=') + b.WriteString(p[1]) + } + return b.String() +} + +// RefreshToken 调用 mtop.taobao.idlemessage.pc.login.token 获取 accessToken。 +// 遇到 mtop 签名 token 过期时,仅在响应下发了新 Cookie 后低频重试一次。 +func (c *Client) RefreshToken(cookiesStr string) (*RefreshResult, error) { + return c.RefreshTokenContext(context.Background(), cookiesStr) +} + +// RefreshTokenContext 是支持取消的 RefreshToken 版本。 +func (c *Client) RefreshTokenContext(ctx context.Context, cookiesStr string) (*RefreshResult, error) { + return c.RefreshTokenWithDeviceIDContext(ctx, cookiesStr, "") +} + +// RefreshTokenWithDeviceIDContext 使用指定 deviceId 获取 accessToken。 +// 闲鱼 IM token 和 WS /reg 的 did 是绑定校验关系:token 请求里的 deviceId +// 必须与 /reg.headers.did 完全一致,否则 /reg 会返回 +// "device id or appkey is not equal"。 +func (c *Client) RefreshTokenWithDeviceIDContext(ctx context.Context, cookiesStr, deviceID string) (*RefreshResult, error) { + currentCookies := cookiesStr + for attempt := 0; attempt < 2; attempt++ { + accessToken, ret, updatedCookies, status, err := c.refreshTokenOnce(ctx, currentCookies, deviceID) + if err != nil { + return &RefreshResult{UpdatedCookies: currentCookies}, err + } + if accessToken != "" { + return &RefreshResult{AccessToken: accessToken, UpdatedCookies: updatedCookies}, nil + } + if !isTokenExpiredRet(ret) { + return &RefreshResult{UpdatedCookies: updatedCookies}, fmt.Errorf("token API 返回非成功: ret=%v (status=%d)", ret, status) + } + // 没有新 Cookie 时继续请求只会重复失败,也会增加风控风险。 + if updatedCookies == "" || updatedCookies == currentCookies || attempt == 1 { + return &RefreshResult{UpdatedCookies: updatedCookies}, fmt.Errorf("token API 登录凭证已失效: ret=%v (status=%d)", ret, status) + } + currentCookies = updatedCookies + if err := sleepCtx(ctx, MTopRetryGap); err != nil { + return &RefreshResult{UpdatedCookies: currentCookies}, err + } + } + return &RefreshResult{UpdatedCookies: currentCookies}, fmt.Errorf("token API 登录凭证已失效") +} + +func (c *Client) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string) (string, []string, string, int, error) { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + + cookies := protocol.TransCookies(cookiesStr) + myid := cookies["unb"] + if myid == "" { + return "", nil, cookiesStr, 0, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId") + } + if strings.TrimSpace(deviceID) == "" { + deviceID = protocol.GenerateDeviceID(myid) + } + token := protocol.SignToken(cookiesStr) + + t := strconv.FormatInt(time.Now().UnixMilli(), 10) + dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"` + deviceID + `"}` + + // query 参数(值按 Python 端原样构造;签名不覆盖 query,故编码细节不影响验签)。 + query := buildTokenQuery(t, protocol.GenerateSign(t, token, dataVal)) + + body := "data=" + url.QueryEscape(dataVal) + + tokenURL := c.TokenURL + if tokenURL == "" { + tokenURL = TokenAPI + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL+"?"+query, strings.NewReader(body)) + if err != nil { + return "", nil, cookiesStr, 0, err + } + setCommonHeaders(req, cookiesStr) + + resp, err := hc.Do(req) + if err != nil { + return "", nil, cookiesStr, 0, fmt.Errorf("token API 请求失败: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return "", nil, cookiesStr, resp.StatusCode, err + } + // 即使业务返回 token 过期,也要保留响应下发的新签名 Cookie。 + updated := mergeSetCookie(cookiesStr, cookies, resp) + + var res struct { + Ret []string `json:"ret"` + Data struct { + AccessToken string `json:"accessToken"` + } `json:"data"` + } + if err := json.Unmarshal(raw, &res); err != nil { + return "", nil, updated, resp.StatusCode, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + } + + ok := false + for _, r := range res.Ret { + if strings.Contains(r, "SUCCESS::调用成功") { + ok = true + break + } + } + if !ok { + return "", res.Ret, updated, resp.StatusCode, nil + } + if res.Data.AccessToken == "" { + return "", res.Ret, updated, resp.StatusCode, fmt.Errorf("token API 成功但 accessToken 为空 (body=%s)", truncate(string(raw), 300)) + } + return res.Data.AccessToken, res.Ret, updated, resp.StatusCode, nil +} + +// buildTokenQuery 构造 token API 的 query string,参数顺序与 Python 端一致。 +// 值按原样拼接(dangerouslySetWindvaneParams 已是单次编码),不做二次编码。 +func buildTokenQuery(t, sign string) string { + parts := [][2]string{ + {"jsv", "2.7.2"}, + {"appKey", protocol.SignAppKey}, + {"t", t}, + {"sign", sign}, + {"v", "1.0"}, + {"type", "originaljson"}, + {"accountSite", "xianyu"}, + {"dataType", "json"}, + {"timeout", "20000"}, + {"api", "mtop.taobao.idlemessage.pc.login.token"}, + {"sessionOption", "AutoLoginOnly"}, + {"dangerouslySetWindvaneParams", "%5Bobject%20Object%5D"}, + {"smToken", "token"}, + {"queryToken", "sm"}, + {"sm", "sm"}, + {"spm_cnt", "a21ybx.im.0.0"}, + {"spm_pre", "a21ybx.home.sidebar.1.4c053da6vYwnmf"}, + {"log_id", "4c053da6vYwnmf"}, + } + var b strings.Builder + for i, p := range parts { + if i > 0 { + b.WriteByte('&') + } + b.WriteString(p[0]) + b.WriteByte('=') + b.WriteString(p[1]) + } + return b.String() +} + +func setCommonHeaders(req *http.Request, cookiesStr string) { + h := req.Header + h.Set("accept", "application/json") + h.Set("accept-language", "zh-CN,zh;q=0.9,en;q=0.8") + h.Set("cache-control", "no-cache") + h.Set("content-type", "application/x-www-form-urlencoded") + h.Set("pragma", "no-cache") + h.Set("priority", "u=1, i") + h.Set("sec-ch-ua", xianyu.SecChUA) + h.Set("sec-ch-ua-mobile", "?0") + h.Set("sec-ch-ua-platform", `"Windows"`) + h.Set("sec-fetch-dest", "empty") + h.Set("sec-fetch-mode", "cors") + h.Set("sec-fetch-site", "same-site") + h.Set("user-agent", xianyu.BrowserUA) + h.Set("referer", "https://www.goofish.com/") + h.Set("origin", "https://www.goofish.com") + h.Set("cookie", cookiesStr) +} + +// mergeSetCookie 把响应的 Set-Cookie 合并回 cookie 字符串。 +func mergeSetCookie(orig string, current map[string]string, resp *http.Response) string { + setCookies := resp.Header["Set-Cookie"] + if len(setCookies) == 0 { + return orig + } + changed := false + for _, sc := range setCookies { + // Set-Cookie: name=value; Path=/; ... + pair := sc + if i := strings.Index(pair, ";"); i >= 0 { + pair = pair[:i] + } + if eq := strings.Index(pair, "="); eq >= 0 { + name := strings.TrimSpace(pair[:eq]) + val := strings.TrimSpace(pair[eq+1:]) + if name != "" { + current[name] = val + changed = true + } + } + } + if !changed { + return orig + } + var b strings.Builder + first := true + for k, v := range current { + if !first { + b.WriteString("; ") + } + first = false + b.WriteString(k) + b.WriteByte('=') + b.WriteString(v) + } + return b.String() +} + +func truncate(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + "..." +} + +func sleepCtx(ctx context.Context, d time.Duration) error { + if d <= 0 { + return nil + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} diff --git a/internal/xianyu/mtop/client_test.go b/internal/xianyu/mtop/client_test.go new file mode 100644 index 0000000..5f2f91e --- /dev/null +++ b/internal/xianyu/mtop/client_test.go @@ -0,0 +1,129 @@ +package mtop + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestRefreshTokenRetriesOnceWithUpdatedCookie(t *testing.T) { + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempt := requests.Add(1) + if attempt == 1 { + http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_999", Path: "/"}) + fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`) + return + } + if !strings.Contains(r.Header.Get("Cookie"), "_m_h5_tk=newtoken_999") { + t.Errorf("第二次请求未携带更新后的 Cookie: %s", r.Header.Get("Cookie")) + } + fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"access-1"}}`) + })) + defer server.Close() + + client := &Client{HTTPClient: server.Client(), TokenURL: server.URL + "/"} + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + result, err := client.RefreshTokenContext(ctx, "unb=123; _m_h5_tk=oldtoken_1;") + if err != nil { + t.Fatalf("RefreshTokenContext: %v", err) + } + if result.AccessToken != "access-1" { + t.Fatalf("AccessToken=%q", result.AccessToken) + } + if requests.Load() != 2 { + t.Fatalf("请求次数=%d want 2", requests.Load()) + } +} + +func TestRefreshTokenDoesNotRetryWithoutUpdatedCookie(t *testing.T) { + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`) + })) + defer server.Close() + + client := &Client{HTTPClient: server.Client(), TokenURL: server.URL + "/"} + _, err := client.RefreshTokenContext(context.Background(), "unb=123; _m_h5_tk=oldtoken_1;") + if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") { + t.Fatalf("err=%v", err) + } + if requests.Load() != 1 { + t.Fatalf("请求次数=%d want 1", requests.Load()) + } +} + +func TestConsignRetriesWithUpdatedTokenCookie(t *testing.T) { + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + attempt := requests.Add(1) + if attempt == 1 { + http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "newtoken_999", Path: "/"}) + fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`) + return + } + if !strings.Contains(r.Header.Get("Cookie"), "_m_h5_tk=newtoken_999") { + t.Errorf("重试未携带更新后的 Cookie: %s", r.Header.Get("Cookie")) + } + fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"]}`) + })) + defer server.Close() + + client := &Client{HTTPClient: server.Client(), ConsignURL: server.URL + "/"} + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + ok, ret, updated, err := client.ConsignContext(ctx, "unb=123; _m_h5_tk=oldtoken_1;", "order-1") + if err != nil { + t.Fatalf("ConsignContext: %v", err) + } + if !ok || len(ret) == 0 || !strings.Contains(ret[0], "SUCCESS") { + t.Fatalf("ok=%v ret=%v", ok, ret) + } + if !strings.Contains(updated, "_m_h5_tk=newtoken_999") { + t.Fatalf("updatedCookies=%q", updated) + } + if requests.Load() != 2 { + t.Fatalf("请求次数=%d want 2", requests.Load()) + } +} + +func TestConsignDoesNotRetryNonTokenFailure(t *testing.T) { + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + fmt.Fprint(w, `{"ret":["FAIL_BIZ_ORDER_STATUS_ERROR::订单状态错误"]}`) + })) + defer server.Close() + + client := &Client{HTTPClient: server.Client(), ConsignURL: server.URL + "/"} + ok, ret, _, err := client.ConsignContext(context.Background(), "unb=123; _m_h5_tk=token_1;", "order-1") + if err != nil || ok || len(ret) == 0 { + t.Fatalf("ok=%v ret=%v err=%v", ok, ret, err) + } + if requests.Load() != 1 { + t.Fatalf("请求次数=%d want 1", requests.Load()) + } +} + +func TestFetchOrderDetailParsesPaidAmountAndQuantity(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"3"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2"},"priceInfo":{"amount":{"value":"12.50"}}}}]}}`) + })) + defer server.Close() + + client := &Client{HTTPClient: server.Client(), OrderDetailURL: server.URL + "/"} + result, err := client.FetchOrderDetail(context.Background(), "unb=123; _m_h5_tk=token_1;", "order-1") + if err != nil { + t.Fatalf("FetchOrderDetail: %v", err) + } + if result.Amount != "12.50" || result.Quantity != "2" || result.OrderStatus != "3" { + t.Fatalf("result=%+v", result) + } +} diff --git a/internal/xianyu/mtop/publish.go b/internal/xianyu/mtop/publish.go new file mode 100644 index 0000000..26c8bc5 --- /dev/null +++ b/internal/xianyu/mtop/publish.go @@ -0,0 +1,597 @@ +package mtop + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "image" + _ "image/gif" + _ "image/jpeg" + _ "image/png" + "io" + "mime/multipart" + "net/http" + "net/textproto" + "net/url" + "path/filepath" + "strconv" + "strings" + "time" + + "xianyu-go/internal/xianyu/protocol" +) + +const ( + UploadMediaAPI = "https://stream-upload.goofish.com/api/upload.api" + PublishItemAPI = "https://h5api.m.goofish.com/h5/mtop.idle.pc.idleitem.publish/1.0/" + RecommendItemAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.kgraph.property.recommend/2.0/" + DefaultLocationAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.local.poi.get/1.0/" +) + +type PublishErrorCode string + +const ( + PublishErrorUnknown PublishErrorCode = "publish_failed" + PublishErrorTokenExpired PublishErrorCode = "auth_expired" + PublishErrorStockPermissionMissing PublishErrorCode = "stock_permission_missing" +) + +type PublishError struct { + Code PublishErrorCode + Ret []string + Body string +} + +func (e *PublishError) Error() string { + if len(e.Ret) > 0 { + return strings.Join(e.Ret, "; ") + } + if e.Body != "" { + return truncate(e.Body, 240) + } + return string(e.Code) +} + +type PublishImage struct { + Filename string + ContentType string + Data []byte +} + +type PublishItemRequest struct { + Title string + Description string + PriceCents int64 + OriginalPriceCents int64 + Quantity int + PostageMode string + PostageCents int64 + Images []PublishImage +} + +type PublishItemResult struct { + ItemID string + ItemURL string + Title string + PriceText string + CategoryID string + CategoryName string + ImageURL string + Quantity int + RawData map[string]any + UpdatedCookies string +} + +type uploadedImage struct { + URL string + Width int + Height int +} + +func (c *Client) PublishItem(ctx context.Context, cookiesStr string, req PublishItemRequest) (*PublishItemResult, error) { + if strings.TrimSpace(req.Title) == "" { + return nil, errors.New("商品标题不能为空") + } + if strings.TrimSpace(req.Description) == "" { + req.Description = req.Title + } + if req.PriceCents <= 0 { + return nil, errors.New("商品价格必须大于 0") + } + if req.Quantity <= 0 { + return nil, errors.New("库存数量必须大于 0") + } + if len(req.Images) == 0 { + return nil, errors.New("至少上传 1 张商品图片") + } + if len(req.Images) > 9 { + return nil, errors.New("商品图片最多 9 张") + } + currentCookies := cookiesStr + uploaded := make([]uploadedImage, 0, len(req.Images)) + for _, img := range req.Images { + res, updated, err := c.uploadPublishImage(ctx, currentCookies, img) + if err != nil { + return nil, err + } + if updated != "" { + currentCookies = updated + } + uploaded = append(uploaded, res) + } + category, updated, err := c.recommendPublishCategory(ctx, currentCookies, req.Title, req.Description, uploaded) + if err != nil { + return nil, err + } + if updated != "" { + currentCookies = updated + } + location, updated, err := c.defaultPublishLocation(ctx, currentCookies) + if err != nil { + return nil, err + } + if updated != "" { + currentCookies = updated + } + return c.publishItemOnce(ctx, currentCookies, req, uploaded, category, location) +} + +func (c *Client) uploadPublishImage(ctx context.Context, cookiesStr string, img PublishImage) (uploadedImage, string, error) { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 60 * time.Second} + } + if img.ContentType == "" { + img.ContentType = "application/octet-stream" + } + if img.Filename == "" { + img.Filename = "image" + } + var body bytes.Buffer + mw := multipart.NewWriter(&body) + header := make(textproto.MIMEHeader) + header.Set("Content-Disposition", fmt.Sprintf("form-data; name=\"file\"; filename=\"%s\"", escapeMultipartFilename(filepath.Base(img.Filename)))) + header.Set("Content-Type", img.ContentType) + part, err := mw.CreatePart(header) + if err != nil { + return uploadedImage{}, cookiesStr, err + } + if _, err := part.Write(img.Data); err != nil { + return uploadedImage{}, cookiesStr, err + } + if err := mw.Close(); err != nil { + return uploadedImage{}, cookiesStr, err + } + u, _ := url.Parse(UploadMediaAPI) + q := u.Query() + q.Set("floderId", "0") + q.Set("appkey", "xy_chat") + q.Set("_input_charset", "utf-8") + u.RawQuery = q.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), &body) + if err != nil { + return uploadedImage{}, cookiesStr, err + } + req.Header.Set("content-type", mw.FormDataContentType()) + setBrowserHeaders(req, cookiesStr) + req.Header.Set("accept", "*/*") + resp, err := hc.Do(req) + if err != nil { + return uploadedImage{}, cookiesStr, fmt.Errorf("上传商品图片失败: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return uploadedImage{}, cookiesStr, err + } + updated := mergeSetCookie(cookiesStr, protocol.TransCookies(cookiesStr), resp) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return uploadedImage{}, updated, fmt.Errorf("上传商品图片失败: http=%d body=%s", resp.StatusCode, truncate(string(raw), 240)) + } + var decoded map[string]any + if err := json.Unmarshal(raw, &decoded); err != nil { + return uploadedImage{}, updated, fmt.Errorf("解析图片上传响应失败: %w (body=%s)", err, truncate(string(raw), 240)) + } + obj := mapFromAny(decoded["object"]) + if obj == nil { + obj = mapFromAny(decoded["data"]) + } + imageURL := mtopString(obj["url"]) + if imageURL == "" { + imageURL = mtopString(decoded["url"]) + } + if imageURL == "" { + return uploadedImage{}, updated, fmt.Errorf("图片上传响应缺少 url: %s", truncate(string(raw), 240)) + } + width, height := parsePix(mtopString(obj["pix"])) + if width == 0 || height == 0 { + if cfg, _, err := image.DecodeConfig(bytes.NewReader(img.Data)); err == nil { + width, height = cfg.Width, cfg.Height + } + } + if width == 0 { + width = 800 + } + if height == 0 { + height = 800 + } + return uploadedImage{URL: imageURL, Width: width, Height: height}, updated, nil +} + +func (c *Client) recommendPublishCategory(ctx context.Context, cookiesStr, title, desc string, images []uploadedImage) (map[string]any, string, error) { + imageInfos := make([]any, 0, len(images)) + for i, img := range images { + imageInfos = append(imageInfos, publishImagePayload(img, i == 0)) + } + data := map[string]any{ + "title": title, + "lockCpv": false, + "multiSKU": false, + "publishScene": "mainPublish", + "scene": "newPublishChoice", + "description": desc, + "imageInfos": imageInfos, + "uniqueCode": strconv.FormatInt(time.Now().UnixMicro(), 10), + } + decoded, updated, err := c.callMTop(ctx, cookiesStr, RecommendItemAPI, "mtop.taobao.idle.kgraph.property.recommend", "2.0", "a21ybx.publish.0.0", "a21ybx.item.sidebar.1.67321598K9Vgx8", "67321598K9Vgx8", data) + if err != nil { + return nil, updated, err + } + if !hasMTopSuccess(retFromDecoded(decoded)) { + return nil, updated, classifyPublishError(retFromDecoded(decoded), decoded) + } + dataMap := mapFromAny(decoded["data"]) + if dataMap == nil { + return nil, updated, fmt.Errorf("类目推荐响应缺少 data") + } + cat := mapFromAny(dataMap["categoryPredictResult"]) + if cat == nil || mtopString(cat["catId"]) == "" { + return nil, updated, fmt.Errorf("未能自动识别商品类目,请调整标题或图片后重试") + } + return dataMap, updated, nil +} + +func (c *Client) defaultPublishLocation(ctx context.Context, cookiesStr string) (map[string]any, string, error) { + data := map[string]any{"longitude": 118.78248347393424, "latitude": 31.91629189813543} + decoded, updated, err := c.callMTop(ctx, cookiesStr, DefaultLocationAPI, "mtop.taobao.idle.local.poi.get", "1.0", "a21ybx.publish.0.0", "a21ybx.item.sidebar.1.38262218ame5nr", "38262218ame5nr", data) + if err != nil { + return nil, updated, err + } + if !hasMTopSuccess(retFromDecoded(decoded)) { + return nil, updated, classifyPublishError(retFromDecoded(decoded), decoded) + } + dataMap := mapFromAny(decoded["data"]) + addresses, _ := dataMap["commonAddresses"].([]any) + if len(addresses) == 0 { + return nil, updated, fmt.Errorf("账号缺少默认发货地址/定位信息,无法发布商品") + } + loc := mapFromAny(addresses[0]) + if loc == nil { + return nil, updated, fmt.Errorf("默认地址格式异常,无法发布商品") + } + return loc, updated, nil +} + +func (c *Client) publishItemOnce(ctx context.Context, cookiesStr string, req PublishItemRequest, images []uploadedImage, category, location map[string]any) (*PublishItemResult, error) { + imagePayloads := make([]any, 0, len(images)) + for i, img := range images { + imagePayloads = append(imagePayloads, publishImagePayload(img, i == 0)) + } + cat := mapFromAny(category["categoryPredictResult"]) + data := map[string]any{ + "freebies": false, + "itemTypeStr": "b", + "quantity": strconv.Itoa(req.Quantity), + "simpleItem": "true", + "imageInfoDOList": imagePayloads, + "itemTextDTO": map[string]any{"desc": req.Description, "title": req.Title, "titleDescSeparate": false}, + "itemLabelExtList": publishLabels(category), + "itemPriceDTO": publishPriceDTO(req), + "userRightsProtocols": []any{map[string]any{ + "enable": false, "serviceCode": "SKILL_PLAY_NO_MIND", + }}, + "itemPostFeeDTO": postageDTO(req), + "itemAddrDTO": map[string]any{ + "area": location["area"], + "city": location["city"], + "divisionId": location["divisionId"], + "gps": fmt.Sprintf("%s,%s", mtopString(location["longitude"]), mtopString(location["latitude"])), + "poiId": location["poiId"], + "poiName": location["poi"], + "prov": location["prov"], + }, + "defaultPrice": false, + "itemCatDTO": map[string]any{ + "catId": mtopString(cat["catId"]), + "catName": mtopString(cat["catName"]), + "channelCatId": mtopString(cat["channelCatId"]), + "tbCatId": mtopString(cat["tbCatId"]), + }, + "uniqueCode": strconv.FormatInt(time.Now().UnixMicro(), 10), + "sourceId": "pcMainPublish", + "bizcode": "pcMainPublish", + "publishScene": "pcMainPublish", + } + decoded, updated, err := c.callMTop(ctx, cookiesStr, PublishItemAPI, "mtop.idle.pc.idleitem.publish", "1.0", "a21ybx.publish.0.0", "a21ybx.home.sidebar.1.46413da6EPl7v5", "46413da6EPl7v5", data) + if err != nil { + return nil, err + } + ret := retFromDecoded(decoded) + if !hasMTopSuccess(ret) { + return nil, classifyPublishError(ret, decoded) + } + dataMap := mapFromAny(decoded["data"]) + itemID := findStringDeep(dataMap, "itemId", "item_id", "id", "itemID") + if itemID == "" { + itemID = findStringDeep(decoded, "itemId", "item_id", "itemID") + } + result := &PublishItemResult{ + ItemID: itemID, + Title: req.Title, + PriceText: centsText(req.PriceCents), + CategoryID: mtopString(cat["catId"]), + CategoryName: mtopString(cat["catName"]), + ImageURL: images[0].URL, + Quantity: req.Quantity, + RawData: dataMap, + UpdatedCookies: updated, + } + if itemID != "" { + result.ItemURL = "https://www.goofish.com/item?id=" + itemID + } + return result, nil +} + +func (c *Client) callMTop(ctx context.Context, cookiesStr, endpoint, api, version, spmCnt, spmPre, logID string, data any) (map[string]any, string, error) { + hc := c.HTTPClient + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + cookies := protocol.TransCookies(cookiesStr) + rawData, _ := json.Marshal(data) + dataVal := string(rawData) + t := strconv.FormatInt(time.Now().UnixMilli(), 10) + sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal) + query := buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID) + body := "data=" + url.QueryEscape(dataVal) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+query, strings.NewReader(body)) + if err != nil { + return nil, cookiesStr, err + } + setCommonHeaders(req, cookiesStr) + resp, err := hc.Do(req) + if err != nil { + return nil, cookiesStr, fmt.Errorf("%s 请求失败: %w", api, err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + if err != nil { + return nil, cookiesStr, err + } + updated := mergeSetCookie(cookiesStr, cookies, resp) + var decoded map[string]any + if err := json.Unmarshal(raw, &decoded); err != nil { + return nil, updated, fmt.Errorf("解析 %s 响应失败: %w (body=%s)", api, err, truncate(string(raw), 300)) + } + return decoded, updated, nil +} + +func buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID string) string { + parts := [][2]string{ + {"jsv", "2.7.2"}, + {"appKey", protocol.SignAppKey}, + {"t", t}, + {"sign", sign}, + {"v", version}, + {"type", "originaljson"}, + {"accountSite", "xianyu"}, + {"dataType", "json"}, + {"timeout", "20000"}, + {"api", api}, + {"sessionOption", "AutoLoginOnly"}, + {"spm_cnt", spmCnt}, + {"spm_pre", spmPre}, + {"log_id", logID}, + } + var b strings.Builder + for i, p := range parts { + if i > 0 { + b.WriteByte('&') + } + b.WriteString(p[0]) + b.WriteByte('=') + b.WriteString(url.QueryEscape(p[1])) + } + return b.String() +} + +func setBrowserHeaders(req *http.Request, cookiesStr string) { + req.Header.Set("accept-language", "zh-CN,zh;q=0.9,en;q=0.8") + req.Header.Set("cache-control", "no-cache") + req.Header.Set("pragma", "no-cache") + req.Header.Set("origin", "https://www.goofish.com") + req.Header.Set("referer", "https://www.goofish.com/") + req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36") + req.Header.Set("cookie", cookiesStr) +} + +func publishImagePayload(img uploadedImage, major bool) map[string]any { + return map[string]any{ + "extraInfo": map[string]any{"isH": "false", "isT": "false", "raw": "false"}, + "isQrCode": false, + "url": img.URL, + "heightSize": img.Height, + "widthSize": img.Width, + "major": major, + "type": 0, + "status": "done", + } +} + +func publishPriceDTO(req PublishItemRequest) map[string]any { + out := map[string]any{"priceInCent": strconv.FormatInt(req.PriceCents, 10)} + if req.OriginalPriceCents > 0 { + out["origPriceInCent"] = strconv.FormatInt(req.OriginalPriceCents, 10) + } + return out +} + +func postageDTO(req PublishItemRequest) map[string]any { + out := map[string]any{"canFreeShipping": false, "supportFreight": false, "onlyTakeSelf": false} + switch req.PostageMode { + case "free", "": + out["canFreeShipping"] = true + out["supportFreight"] = true + case "distance": + out["supportFreight"] = true + out["templateId"] = "-100" + case "fixed": + out["supportFreight"] = true + out["postPriceInCent"] = strconv.FormatInt(req.PostageCents, 10) + out["templateId"] = "0" + case "none": + out["templateId"] = "0" + default: + out["canFreeShipping"] = true + out["supportFreight"] = true + } + return out +} + +func publishLabels(category map[string]any) []any { + cards, _ := category["cardList"].([]any) + out := []any{} + for _, rawCard := range cards { + card := mapFromAny(rawCard) + cardData := mapFromAny(card["cardData"]) + if cardData == nil { + continue + } + values, _ := cardData["valuesList"].([]any) + for _, rawValue := range values { + value := mapFromAny(rawValue) + clicked, _ := value["isClicked"].(bool) + if !clicked { + continue + } + propertyID := mtopString(cardData["propertyId"]) + propertyName := mtopString(cardData["propertyName"]) + channelCatID := mtopString(value["channelCatId"]) + catName := mtopString(value["catName"]) + out = append(out, map[string]any{ + "channelCateName": catName, + "valueId": nil, + "channelCateId": channelCatID, + "valueName": nil, + "tbCatId": mtopString(value["tbCatId"]), + "subPropertyId": nil, + "labelType": "common", + "subValueId": nil, + "labelId": nil, + "propertyName": propertyName, + "isUserClick": "1", + "isUserCancel": nil, + "from": "newPublishChoice", + "propertyId": propertyID, + "labelFrom": "newPublish", + "text": catName, + "properties": propertyID + "##" + propertyName + ":" + channelCatID + "##" + catName, + }) + break + } + } + return out +} + +func classifyPublishError(ret []string, decoded map[string]any) error { + bodyBytes, _ := json.Marshal(decoded) + body := string(bodyBytes) + joined := strings.ToLower(strings.Join(append(ret, body), " ")) + if isTokenExpiredRet(ret) || strings.Contains(joined, "login") || strings.Contains(joined, "session") { + return &PublishError{Code: PublishErrorTokenExpired, Ret: ret, Body: body} + } + stockTerms := []string{"库存", "数量", "多库存", "多件", "quantity", "stock", "inventory"} + permissionTerms := []string{"权限", "未开通", "不支持", "没有", "无法", "permission", "forbidden", "not allow", "not support"} + if containsAny(joined, stockTerms) && containsAny(joined, permissionTerms) { + return &PublishError{Code: PublishErrorStockPermissionMissing, Ret: ret, Body: body} + } + return &PublishError{Code: PublishErrorUnknown, Ret: ret, Body: body} +} + +func containsAny(s string, terms []string) bool { + for _, term := range terms { + if strings.Contains(s, strings.ToLower(term)) { + return true + } + } + return false +} + +func retFromDecoded(decoded map[string]any) []string { + raw, _ := decoded["ret"].([]any) + out := make([]string, 0, len(raw)) + for _, r := range raw { + out = append(out, mtopString(r)) + } + return out +} + +func mapFromAny(v any) map[string]any { + if m, ok := v.(map[string]any); ok { + return m + } + return nil +} + +func parsePix(pix string) (int, int) { + parts := strings.Split(pix, "x") + if len(parts) != 2 { + return 0, 0 + } + w, _ := strconv.Atoi(parts[0]) + h, _ := strconv.Atoi(parts[1]) + return w, h +} + +func findStringDeep(v any, keys ...string) string { + keySet := map[string]struct{}{} + for _, k := range keys { + keySet[k] = struct{}{} + } + var walk func(any) string + walk = func(cur any) string { + switch x := cur.(type) { + case map[string]any: + for k, v := range x { + if _, ok := keySet[k]; ok { + if s := mtopString(v); s != "" { + return s + } + } + } + for _, v := range x { + if s := walk(v); s != "" { + return s + } + } + case []any: + for _, v := range x { + if s := walk(v); s != "" { + return s + } + } + } + return "" + } + return walk(v) +} + +func centsText(cents int64) string { + return strconv.FormatFloat(float64(cents)/100, 'f', 2, 64) +} + +func escapeMultipartFilename(s string) string { + return strings.NewReplacer("\\", "\\\\", "\"", "\\\"").Replace(s) +} diff --git a/internal/xianyu/protocol/cookies.go b/internal/xianyu/protocol/cookies.go new file mode 100644 index 0000000..06a549a --- /dev/null +++ b/internal/xianyu/protocol/cookies.go @@ -0,0 +1,37 @@ +// Package protocol 移植自 Python 端 utils/xianyu_utils.py 的协议原语: +// cookie 解析、mtop 签名、设备/消息 ID 生成、消息解密(base64 + MessagePack)。 +// +// 这些算法与 Python 实现逐字节对齐,并通过 golden 测试(用真实抓包样本对比)锁定。 +package protocol + +import "strings" + +// TransCookies 将 "k1=v1; k2=v2" 形式的 cookie 字符串解析为 map。 +// 对应 Python trans_cookies(cookies_str)。 +func TransCookies(cookiesStr string) map[string]string { + cookies := make(map[string]string) + if cookiesStr == "" { + return cookies + } + for _, part := range strings.Split(cookiesStr, "; ") { + if eq := strings.Index(part, "="); eq >= 0 { + k := part[:eq] + v := part[eq+1:] + cookies[k] = v + } + } + return cookies +} + +// SignToken 从 cookie 字符串中提取 _m_h5_tk 的前半段,作为 mtop API 签名用的 token。 +// _m_h5_tk 形如 "_",取 "_" 前的部分。 +func SignToken(cookiesStr string) string { + v := TransCookies(cookiesStr)["_m_h5_tk"] + if v == "" { + return "" + } + if i := strings.Index(v, "_"); i >= 0 { + return v[:i] + } + return v +} diff --git a/internal/xianyu/protocol/decrypt.go b/internal/xianyu/protocol/decrypt.go new file mode 100644 index 0000000..d9a5b6f --- /dev/null +++ b/internal/xianyu/protocol/decrypt.go @@ -0,0 +1,104 @@ +package protocol + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "strconv" + "strings" +) + +// Decrypt 解密闲鱼 WS 同步包载荷:base64 解码 → MessagePack 解码 → 归一化为 JSON 字符串。 +// 对应 Python decrypt(data)。归一化规则与 Python json.dumps(default=bytes→utf-8) 一致: +// - map 的键统一转为字符串(整数键 → 数字字符串,与 Python json 行为一致) +// - []byte(msgpack bin)→ UTF-8 字符串(忽略无效字节) +// - 其余类型原样保留 +func Decrypt(data string) (string, error) { + // 清理非 ASCII(与 Python 一致:utf-8 编码后按 ascii 忽略解码)。 + data = stripNonASCII(data) + + // base64 解码,必要时补 padding。 + decoded, err := base64.StdEncoding.DecodeString(data) + if err != nil { + if pad := len(data) % 4; pad != 0 { + decoded, err = base64.StdEncoding.DecodeString(data + strings.Repeat("=", 4-pad)) + } + if err != nil { + return "", fmt.Errorf("解密失败: base64 解码: %w", err) + } + } + + d := &msgpackDecoder{data: decoded} + val, err := d.decodeValue() + if err != nil { + return "", fmt.Errorf("解密失败: %w", err) + } + + normalized := normalizeForJSON(val) + b, err := json.Marshal(normalized) + if err != nil { + return "", fmt.Errorf("解密失败: JSON 序列化: %w", err) + } + return string(b), nil +} + +// stripNonASCII 模拟 Python data.encode('utf-8','ignore').decode('ascii','ignore')。 +func stripNonASCII(s string) string { + var b strings.Builder + b.Grow(len(s)) + for _, r := range s { + if r < 0x80 { + b.WriteRune(r) + } + } + return b.String() +} + +// normalizeForJSON 把 msgpack 解码出的任意结构转为 json.Marshal 友好的结构, +// 并复刻 Python json.dumps 的键/字节处理。 +func normalizeForJSON(v any) any { + switch x := v.(type) { + case map[any]any: + m := make(map[string]any, len(x)) + for k, val := range x { + m[keyToString(k)] = normalizeForJSON(val) + } + return m + case []any: + out := make([]any, len(x)) + for i, e := range x { + out[i] = normalizeForJSON(e) + } + return out + case []byte: + // Python default 序列化器:bytes.decode('utf-8','ignore') + return strings.ToValidUTF8(string(x), "") + default: + return v + } +} + +// keyToString 复刻 Python json 对非字符串键的转换。 +func keyToString(k any) string { + switch x := k.(type) { + case string: + return x + case int64: + return strconv.FormatInt(x, 10) + case uint64: + return strconv.FormatUint(x, 10) + case bool: + if x { + return "true" + } + return "false" + case nil: + return "null" + case float64: + return strconv.FormatFloat(x, 'g', -1, 64) + case []byte: + return strings.ToValidUTF8(string(x), "") + default: + return fmt.Sprintf("%v", k) + } +} diff --git a/internal/xianyu/protocol/golden_test.go b/internal/xianyu/protocol/golden_test.go new file mode 100644 index 0000000..7000e60 --- /dev/null +++ b/internal/xianyu/protocol/golden_test.go @@ -0,0 +1,62 @@ +package protocol + +import ( + _ "embed" + "encoding/json" + "reflect" + "strings" + "testing" +) + +//go:embed testdata/sample.b64 +var sampleB64 string + +//go:embed testdata/expected_decrypt.json +var expectedDecrypt string + +// TestGenerateSign_Golden 与 Python hashlib.md5 结果逐字节对比。 +func TestGenerateSign_Golden(t *testing.T) { + got := GenerateSign("1700000000000", "abc_token", `{"appKey":"x"}`) + want := "497ff18ef9c6d4792ba5aeef0e99929a" + if got != want { + t.Fatalf("sign mismatch:\n got %s\nwant %s", got, want) + } +} + +// TestDecrypt_Golden 用真实抓包样本对比 Python decrypt 的输出。 +// 比较方式:两侧都按 JSON 解析(UseNumber 保留整数精度),reflect.DeepEqual 结构相等。 +func TestDecrypt_Golden(t *testing.T) { + got, err := Decrypt(strings.TrimSpace(sampleB64)) + if err != nil { + t.Fatalf("Decrypt failed: %v", err) + } + gotV := mustParseJSONUseNumber(t, got) + wantV := mustParseJSONUseNumber(t, strings.TrimSpace(expectedDecrypt)) + if !reflect.DeepEqual(gotV, wantV) { + gj, _ := json.MarshalIndent(gotV, "", " ") + wj, _ := json.MarshalIndent(wantV, "", " ") + t.Fatalf("decrypt mismatch:\n--- got ---\n%s\n--- want ---\n%s", gj, wj) + } +} + +func mustParseJSONUseNumber(t *testing.T, s string) any { + t.Helper() + dec := json.NewDecoder(strings.NewReader(s)) + dec.UseNumber() + var v any + if err := dec.Decode(&v); err != nil { + t.Fatalf("parse json: %v", err) + } + return v +} + +// TestTransCookies 基本解析。 +func TestTransCookies(t *testing.T) { + c := TransCookies("a=1; b=2; _m_h5_tk=tokenpart_123") + if c["a"] != "1" || c["b"] != "2" { + t.Fatalf("unexpected: %v", c) + } + if got := SignToken("a=1; _m_h5_tk=tokenpart_123"); got != "tokenpart" { + t.Fatalf("SignToken = %q, want tokenpart", got) + } +} diff --git a/internal/xianyu/protocol/msgpack.go b/internal/xianyu/protocol/msgpack.go new file mode 100644 index 0000000..df99cd5 --- /dev/null +++ b/internal/xianyu/protocol/msgpack.go @@ -0,0 +1,218 @@ +package protocol + +import ( + "encoding/binary" + "fmt" + "math" +) + +// msgpackDecoder 是 Python MessagePackDecoder 的逐格式移植。 +// 解码结果类型:int64/uint64/float64/string/bool/nil/[]byte/[]any/map[any]any。 +// 与 Python 实现一致:bin → []byte,map 键保留原类型(整数键为 int64)。 +type msgpackDecoder struct { + data []byte + pos int +} + +func (d *msgpackDecoder) readByte() (byte, error) { + if d.pos >= len(d.data) { + return 0, fmt.Errorf("msgpack: unexpected end of data") + } + b := d.data[d.pos] + d.pos++ + return b, nil +} + +func (d *msgpackDecoder) readBytes(n int) ([]byte, error) { + if d.pos+n > len(d.data) { + return nil, fmt.Errorf("msgpack: unexpected end of data") + } + r := d.data[d.pos : d.pos+n] + d.pos += n + return r, nil +} + +func (d *msgpackDecoder) decodeValue() (any, error) { + fb, err := d.readByte() + if err != nil { + return nil, err + } + switch { + // positive fixint + case fb <= 0x7f: + return int64(fb), nil + // fixmap + case fb >= 0x80 && fb <= 0x8f: + return d.decodeMap(int(fb & 0x0f)) + // fixarray + case fb >= 0x90 && fb <= 0x9f: + return d.decodeArray(int(fb & 0x0f)) + // fixstr + case fb >= 0xa0 && fb <= 0xbf: + return d.readString(int(fb & 0x1f)) + } + switch fb { + case 0xc0: + return nil, nil + case 0xc2: + return false, nil + case 0xc3: + return true, nil + case 0xc4: // bin 8 + n, err := d.readByte() + if err != nil { + return nil, err + } + return d.readBytes(int(n)) + case 0xc5: // bin 16 + b, err := d.readBytes(2) + if err != nil { + return nil, err + } + return d.readBytes(int(binary.BigEndian.Uint16(b))) + case 0xc6: // bin 32 + b, err := d.readBytes(4) + if err != nil { + return nil, err + } + return d.readBytes(int(binary.BigEndian.Uint32(b))) + case 0xca: // float 32 + b, err := d.readBytes(4) + if err != nil { + return nil, err + } + bits := binary.BigEndian.Uint32(b) + return float64(math.Float32frombits(bits)), nil + case 0xcb: // float 64 + b, err := d.readBytes(8) + if err != nil { + return nil, err + } + return math.Float64frombits(binary.BigEndian.Uint64(b)), nil + case 0xcc: // uint 8 + n, err := d.readByte() + return uint64(n), err + case 0xcd: // uint 16 + b, err := d.readBytes(2) + if err != nil { + return nil, err + } + return uint64(binary.BigEndian.Uint16(b)), nil + case 0xce: // uint 32 + b, err := d.readBytes(4) + if err != nil { + return nil, err + } + return uint64(binary.BigEndian.Uint32(b)), nil + case 0xcf: // uint 64 + b, err := d.readBytes(8) + if err != nil { + return nil, err + } + return binary.BigEndian.Uint64(b), nil + case 0xd0: // int 8 + n, err := d.readByte() + return int64(int8(n)), err + case 0xd1: // int 16 + b, err := d.readBytes(2) + if err != nil { + return nil, err + } + return int64(int16(binary.BigEndian.Uint16(b))), nil + case 0xd2: // int 32 + b, err := d.readBytes(4) + if err != nil { + return nil, err + } + return int64(int32(binary.BigEndian.Uint32(b))), nil + case 0xd3: // int 64 + b, err := d.readBytes(8) + if err != nil { + return nil, err + } + return int64(binary.BigEndian.Uint64(b)), nil + case 0xd9: // str 8 + n, err := d.readByte() + if err != nil { + return nil, err + } + return d.readString(int(n)) + case 0xda: // str 16 + b, err := d.readBytes(2) + if err != nil { + return nil, err + } + return d.readString(int(binary.BigEndian.Uint16(b))) + case 0xdb: // str 32 + b, err := d.readBytes(4) + if err != nil { + return nil, err + } + return d.readString(int(binary.BigEndian.Uint32(b))) + case 0xdc: // array 16 + b, err := d.readBytes(2) + if err != nil { + return nil, err + } + return d.decodeArray(int(binary.BigEndian.Uint16(b))) + case 0xdd: // array 32 + b, err := d.readBytes(4) + if err != nil { + return nil, err + } + return d.decodeArray(int(binary.BigEndian.Uint32(b))) + case 0xde: // map 16 + b, err := d.readBytes(2) + if err != nil { + return nil, err + } + return d.decodeMap(int(binary.BigEndian.Uint16(b))) + case 0xdf: // map 32 + b, err := d.readBytes(4) + if err != nil { + return nil, err + } + return d.decodeMap(int(binary.BigEndian.Uint32(b))) + } + // negative fixint + if fb >= 0xe0 { + return int64(int8(fb)), nil + } + return nil, fmt.Errorf("msgpack: unknown format byte 0x%02x", fb) +} + +func (d *msgpackDecoder) readString(n int) (string, error) { + b, err := d.readBytes(n) + if err != nil { + return "", err + } + return string(b), nil // UTF-8,与 Python .decode('utf-8') 一致 +} + +func (d *msgpackDecoder) decodeArray(n int) (any, error) { + arr := make([]any, n) + for i := 0; i < n; i++ { + v, err := d.decodeValue() + if err != nil { + return nil, err + } + arr[i] = v + } + return arr, nil +} + +func (d *msgpackDecoder) decodeMap(n int) (any, error) { + m := make(map[any]any, n) + for i := 0; i < n; i++ { + k, err := d.decodeValue() + if err != nil { + return nil, err + } + v, err := d.decodeValue() + if err != nil { + return nil, err + } + m[k] = v + } + return m, nil +} diff --git a/internal/xianyu/protocol/sign.go b/internal/xianyu/protocol/sign.go new file mode 100644 index 0000000..c2bbe77 --- /dev/null +++ b/internal/xianyu/protocol/sign.go @@ -0,0 +1,56 @@ +package protocol + +import ( + "crypto/md5" + "encoding/hex" + "fmt" + "math/rand" + "time" +) + +// mtop 签名使用的 appKey(与 WS 注册用的 APP_CONFIG.app_key 不同)。 +const SignAppKey = "34839810" + +// GenerateSign 生成 mtop API 签名:MD5(token + "&" + t + "&" + appKey + "&" + data)。 +// 对应 Python generate_sign(t, token, data)。 +func GenerateSign(t, token, data string) string { + msg := token + "&" + t + "&" + SignAppKey + "&" + data + sum := md5.Sum([]byte(msg)) + return hex.EncodeToString(sum[:]) +} + +// GenerateMid 生成消息 ID,形如 "<0-999随机><毫秒时间戳> 0"。 +// 对应 Python generate_mid()。非密码学用途,用 math/rand 即可。 +func GenerateMid() string { + randomPart := rand.Intn(1000) + ts := time.Now().UnixMilli() + return fmt.Sprintf("%d%d 0", randomPart, ts) +} + +// GenerateUUID 生成 UUID,形如 "-<毫秒时间戳>1"。 +// 对应 Python generate_uuid()。 +func GenerateUUID() string { + return fmt.Sprintf("-%d1", time.Now().UnixMilli()) +} + +const deviceIDChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + +// GenerateDeviceID 生成设备 ID:36 位 UUID 格式(位置 8/13/18/23 为 "-",14 为 "4", +// 19 取 (rand&0x3)|0x8),末尾追加 "-"。 +// 对应 Python generate_device_id(user_id)。 +func GenerateDeviceID(userID string) string { + result := make([]byte, 36) + for i := 0; i < 36; i++ { + switch { + case i == 8 || i == 13 || i == 18 || i == 23: + result[i] = '-' + case i == 14: + result[i] = '4' + case i == 19: + result[i] = deviceIDChars[(rand.Intn(16)&0x3)|0x8] + default: + result[i] = deviceIDChars[rand.Intn(16)] + } + } + return string(result) + "-" + userID +} diff --git a/internal/xianyu/protocol/testdata/expected_decrypt.json b/internal/xianyu/protocol/testdata/expected_decrypt.json new file mode 100644 index 0000000..545f9d1 --- /dev/null +++ b/internal/xianyu/protocol/testdata/expected_decrypt.json @@ -0,0 +1 @@ +{"1": {"1": {"1": "3149637063@goofish"}, "2": "47983389096@goofish", "3": "3416565274542.PNM", "4": 0, "5": 1742458817389, "6": {"1": 101, "3": {"1": "", "2": "[我已拍下,待付款]", "3": "", "4": 26, "5": "{\"contentType\":26,\"dxCard\":{\"item\":{\"main\":{\"clickParam\":{\"arg1\":\"MsgCard\",\"args\":{\"source\":\"im\",\"task_id\":\"3exQJHOTmPU1\",\"msg_id\":\"cc8bc2df7c934df086e0567cb69f1573\"}},\"exContent\":{\"bgColor\":\"#FFFFFF\",\"button\":{\"bgColor\":\"#FFE60F\",\"borderColor\":\"#FFE60F\",\"clickParam\":{\"arg1\":\"MsgCardAction\",\"args\":{\"source\":\"im\",\"task_id\":\"3exQJHOTmPU1\",\"msg_id\":\"cc8bc2df7c934df086e0567cb69f1573\"}},\"fontColor\":\"#333333\",\"targetUrl\":\"fleamarket://adjust_price?flutter=true&bizOrderId=2503688126356636370\",\"text\":\"修改价格\"},\"desc\":\"请双方沟通及时确认价格\",\"descColor\":\"#A3A3A3\",\"title\":\"我已拍下,待付款\",\"upgrade\":{\"targetUrl\":\"https://h5.m.goofish.com/app/idleFish-F2e/fm-downlaod/home.html?noRedriect=true&canBack=true&checkVersion=true\",\"version\":\"7.7.90\"}},\"targetUrl\":\"fleamarket://order_detail?id=2503688126356636370&role=seller\"}},\"template\":{\"name\":\"idlefish_message_trade_chat_card\",\"url\":\"https://dinamicx.alibabausercontent.com/pub/idlefish_message_trade_chat_card/1667222052767/idlefish_message_trade_chat_card.zip\",\"version\":\"1667222052767\"}}}"}}, "7": 1, "8": 1, "9": 0, "10": {"bizTag": "{\"sourceId\":\"C2C:3exQJHOTmPU1\",\"taskName\":\"已拍下_未付款_卖家\",\"materialId\":\"3exQJHOTmPU1\",\"taskId\":\"3exQJHOTmPU1\"}", "closePushReceiver": "false", "closeUnreadNumber": "false", "detailNotice": "[我已拍下,待付款]", "extJson": "{\"msgArgs\":{\"task_id\":\"3exQJHOTmPU1\",\"source\":\"im\",\"msg_id\":\"cc8bc2df7c934df086e0567cb69f1573\"},\"quickReply\":\"1\",\"msgArg1\":\"MsgCard\",\"updateKey\":\"47983389096:2503688126356636370:1_not_pay_seller\",\"messageId\":\"cc8bc2df7c934df086e0567cb69f1573\",\"multiChannel\":{\"huawei\":\"EXPRESS\",\"xiaomi\":\"108000\",\"oppo\":\"EXPRESS\",\"honor\":\"NORMAL\",\"agoo\":\"product\",\"vivo\":\"ORDER\"},\"contentType\":\"26\",\"correlationGroupId\":\"3exQJHOTmPU1_FFr4GOSn8OQo\"}", "receiver": "2202640918079", "redReminder": "等待买家付款", "redReminderStyle": "1", "reminderContent": "[我已拍下,待付款]", "reminderNotice": "买家已拍下,待付款", "reminderTitle": "买家已拍下,待付款", "reminderUrl": "fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063&peerUserNick=男***y&sid=47983389096&messageId=cc8bc2df7c934df086e0567cb69f1573&adv=no", "senderUserId": "3149637063", "senderUserType": "0", "sessionType": "1", "updateHead": "true"}, "12": 1}, "3": {"needPush": "true"}} diff --git a/internal/xianyu/protocol/testdata/sample.b64 b/internal/xianyu/protocol/testdata/sample.b64 new file mode 100644 index 0000000..874f75e --- /dev/null +++ b/internal/xianyu/protocol/testdata/sample.b64 @@ -0,0 +1 @@ +ggGLAYEBsjMxNDk2MzcwNjNAZ29vZmlzaAKzNDc5ODMzODkwOTZAZ29vZmlzaAOxMzQxNjU2NTI3NDU0Mi5QTk0EAAXPAAABlbKji20GggFlA4UBoAK6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl0DoAQaBdoEKnsiY29udGVudFR5cGUiOjI2LCJkeENhcmQiOnsiaXRlbSI6eyJtYWluIjp7ImNsaWNrUGFyYW0iOnsiYXJnMSI6Ik1zZ0NhcmQiLCJhcmdzIjp7InNvdXJjZSI6ImltIiwidGFza19pZCI6IjNleFFKSE9UbVBVMSIsIm1zZ19pZCI6ImNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczIn19LCJleENvbnRlbnQiOnsiYmdDb2xvciI6IiNGRkZGRkYiLCJidXR0b24iOnsiYmdDb2xvciI6IiNGRkU2MEYiLCJib3JkZXJDb2xvciI6IiNGRkU2MEYiLCJjbGlja1BhcmFtIjp7ImFyZzEiOiJNc2dDYXJkQWN0aW9uIiwiYXJncyI6eyJzb3VyY2UiOiJpbSIsInRhc2tfaWQiOiIzZXhRSkhPVG1QVTEiLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9fSwiZm9udENvbG9yIjoiIzMzMzMzMyIsInRhcmdldFVybCI6ImZsZWFtYXJrZXQ6Ly9hZGp1c3RfcHJpY2U/Zmx1dHRlcj10cnVlJmJpek9yZGVySWQ9MjUwMzY4ODEyNjM1NjYzNjM3MCIsInRleHQiOiLkv67mlLnku7fmoLwifSwiZGVzYyI6Iuivt+WPjOaWueayn+mAmuWPiuaXtuehruiupOS7t+agvCIsImRlc2NDb2xvciI6IiNBM0EzQTMiLCJ0aXRsZSI6IuaIkeW3suaLjeS4i++8jOW+heS7mOasviIsInVwZ3JhZGUiOnsidGFyZ2V0VXJsIjoiaHR0cHM6Ly9oNS5tLmdvb2Zpc2guY29tL2FwcC9pZGxlRmlzaC1GMmUvZm0tZG93bmxhb2QvaG9tZS5odG1sP25vUmVkcmllY3Q9dHJ1ZSZjYW5CYWNrPXRydWUmY2hlY2tWZXJzaW9uPXRydWUiLCJ2ZXJzaW9uIjoiNy43LjkwIn19LCJ0YXJnZXRVcmwiOiJmbGVhbWFya2V0Oi8vb3JkZXJfZGV0YWlsP2lkPTI1MDM2ODgxMjYzNTY2MzYzNzAmcm9sZT1zZWxsZXIifX0sInRlbXBsYXRlIjp7Im5hbWUiOiJpZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZCIsInVybCI6Imh0dHBzOi8vZGluYW1pY3guYWxpYmFiYXVzZXJjb250ZW50LmNvbS9wdWIvaWRsZWZpc2hfbWVzc2FnZV90cmFkZV9jaGF0X2NhcmQvMTY2NzIyMjA1Mjc2Ny9pZGxlZmlzaF9tZXNzYWdlX3RyYWRlX2NoYXRfY2FyZC56aXAiLCJ2ZXJzaW9uIjoiMTY2NzIyMjA1Mjc2NyJ9fX0HAQgBCQAK3gAQpmJpelRhZ9oAe3sic291cmNlSWQiOiJDMkM6M2V4UUpIT1RtUFUxIiwidGFza05hbWUiOiLlt7Lmi43kuItf5pyq5LuY5qy+X+WNluWutiIsIm1hdGVyaWFsSWQiOiIzZXhRSkhPVG1QVTEiLCJ0YXNrSWQiOiIzZXhRSkhPVG1QVTEifbFjbG9zZVB1c2hSZWNlaXZlcqVmYWxzZbFjbG9zZVVucmVhZE51bWJlcqVmYWxzZaxkZXRhaWxOb3RpY2W6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2nZXh0SnNvbtoBr3sibXNnQXJncyI6eyJ0YXNrX2lkIjoiM2V4UUpIT1RtUFUxIiwic291cmNlIjoiaW0iLCJtc2dfaWQiOiJjYzhiYzJkZjdjOTM0ZGYwODZlMDU2N2NiNjlmMTU3MyJ9LCJxdWlja1JlcGx5IjoiMSIsIm1zZ0FyZzEiOiJNc2dDYXJkIiwidXBkYXRlS2V5IjoiNDc5ODMzODkwOTY6MjUwMzY4ODEyNjM1NjYzNjM3MDoxX25vdF9wYXlfc2VsbGVyIiwibWVzc2FnZUlkIjoiY2M4YmMyZGY3YzkzNGRmMDg2ZTA1NjdjYjY5ZjE1NzMiLCJtdWx0aUNoYW5uZWwiOnsiaHVhd2VpIjoiRVhQUkVTUyIsInhpYW9taSI6IjEwODAwMCIsIm9wcG8iOiJFWFBSRVNTIiwiaG9ub3IiOiJOT1JNQUwiLCJhZ29vIjoicHJvZHVjdCIsInZpdm8iOiJPUkRFUiJ9LCJjb250ZW50VHlwZSI6IjI2IiwiY29ycmVsYXRpb25Hcm91cElkIjoiM2V4UUpIT1RtUFUxX0ZGcjRHT1NuOE9RbyJ9qHJlY2VpdmVyrTIyMDI2NDA5MTgwNzmrcmVkUmVtaW5kZXKy562J5b6F5Lmw5a625LuY5qy+sHJlZFJlbWluZGVyU3R5bGWhMa9yZW1pbmRlckNvbnRlbnS6W+aIkeW3suaLjeS4i++8jOW+heS7mOasvl2ucmVtaW5kZXJOb3RpY2W75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+rXJlbWluZGVyVGl0bGW75Lmw5a625bey5ouN5LiL77yM5b6F5LuY5qy+q3JlbWluZGVyVXJs2gCaZmxlYW1hcmtldDovL21lc3NhZ2VfY2hhdD9pdGVtSWQ9OTAwMDUyNjQ0Mjc3JnBlZXJVc2VySWQ9MzE0OTYzNzA2MyZwZWVyVXNlck5pY2s955S3KioqeSZzaWQ9NDc5ODMzODkwOTYmbWVzc2FnZUlkPWNjOGJjMmRmN2M5MzRkZjA4NmUwNTY3Y2I2OWYxNTczJmFkdj1ub6xzZW5kZXJVc2VySWSqMzE0OTYzNzA2M65zZW5kZXJVc2VyVHlwZaEwq3Nlc3Npb25UeXBloTGqdXBkYXRlSGVhZKR0cnVlDAEDgahuZWVkUHVzaKR0cnVl diff --git a/internal/xianyu/qrlogin/client.go b/internal/xianyu/qrlogin/client.go new file mode 100644 index 0000000..b7fa40e --- /dev/null +++ b/internal/xianyu/qrlogin/client.go @@ -0,0 +1,657 @@ +// Package qrlogin 实现闲鱼扫码登录;风控验证场景可通过浏览器提取真实 cookie。 +// 移植自 Python utils/qr_login.py 的 QRLoginManager。 +package qrlogin + +import ( + "bytes" + "context" + "crypto/md5" + rand "crypto/rand" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + "time" + + qrcode "github.com/skip2/go-qrcode" + + "xianyu-go/internal/logsafe" + "xianyu-go/internal/xianyu" +) + +const ( + host = "https://passport.goofish.com" + apiMiniLogin = host + "/mini_login.htm" + apiGenerateQR = host + "/newlogin/qrcode/generate.do" + apiScanStatus = host + "/newlogin/qrcode/query.do" + apiH5TK = "https://h5api.m.goofish.com/h5/mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get/1.0/" + appKey = "34839810" +) + +var qrVerifyTargetURL = "https://www.goofish.com/im" + +var qrHeaders = map[string]string{ + "User-Agent": xianyu.BrowserUA, + "Accept": "application/json, text/plain, */*", + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Connection": "keep-alive", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "same-origin", + "Referer": "https://passport.goofish.com/", + "Origin": "https://passport.goofish.com", +} + +// Session 一个扫码登录会话。 +type Session struct { + SessionID string `json:"session_id"` + Status string `json:"status"` // waiting/scanned/success/expired/cancelled/verification_required + QRCodeURL string `json:"qr_code_url"` + qrContent string + cookies map[string]string + unb string + createdTime time.Time + expireTime time.Duration + params map[string]string + verificationURL string + verificationScreenshot string // 最新截图 data URL,前端轮询时显示 +} + +func (s *Session) isExpired() bool { + return time.Since(s.createdTime) > s.expireTime +} + +// SidecarRefresher 由外部注入的浏览器刷新函数。 +// tmpCookies: 扫码临时 cookie;verificationURL: Chromium 打开后持有 session 等待验证。 +// onScreenshot: 每次截图时回调(data:image/png;base64,...),前端实时显示验证页画面。 +type SidecarRefresher func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error) + +// Manager 扫码登录管理器。 +type Manager struct { + mu sync.Mutex + sessions map[string]*Session + httpc *http.Client + logger *slog.Logger + sidecar SidecarRefresher // 可选:风控验证后用浏览器提取真实 cookie +} + +// SetSidecarRefresher 注入 sidecar 刷新函数(风控验证场景必需)。 +func (m *Manager) SetSidecarRefresher(f SidecarRefresher) { + m.sidecar = f +} + +// NewManager 构造。 +func NewManager(logger *slog.Logger) *Manager { + if logger == nil { + logger = slog.Default() + } + return &Manager{ + sessions: make(map[string]*Session), + httpc: &http.Client{Timeout: 60 * time.Second}, + logger: logger, + } +} + +// GenerateQRCode 生成扫码登录二维码。返回 session_id + qr_code_url(base64 data URL)。 +func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error) { + sessionID = randomUUID() + sess := &Session{ + SessionID: sessionID, + Status: "waiting", + cookies: make(map[string]string), + createdTime: time.Now(), + expireTime: 5 * time.Minute, + params: make(map[string]string), + } + + // 1. 获取 m_h5_tk。 + if err := m.getMH5TK(ctx, sess); err != nil { + return "", "", fmt.Errorf("获取 m_h5_tk 失败: %w", err) + } + + // 2. 获取登录参数。 + loginParams, err := m.getLoginParams(ctx, sess) + if err != nil { + return "", "", fmt.Errorf("获取登录参数失败: %w", err) + } + + // 3. 生成二维码。 + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiGenerateQR, nil) + q := req.URL.Query() + for k, v := range loginParams { + q.Set(k, v) + } + req.URL.RawQuery = q.Encode() + m.setHeaders(req) + + resp, err := m.httpc.Do(req) + if err != nil { + return "", "", fmt.Errorf("请求二维码接口失败: %w", err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + + var result struct { + Content struct { + Success bool `json:"success"` + Data struct { + T any `json:"t"` + Ck string `json:"ck"` + CodeContent string `json:"codeContent"` + } `json:"data"` + } `json:"content"` + } + if err := json.Unmarshal(body, &result); err != nil { + return "", "", fmt.Errorf("解析二维码响应失败: %w (body=%s)", err, truncate(string(body), 300)) + } + if !result.Content.Success { + return "", "", fmt.Errorf("获取登录二维码失败 (body=%s)", truncate(string(body), 300)) + } + + // t 是毫秒时间戳数字,必须转成纯数字字符串(不能用科学计数法)。 + var tStr string + switch tv := result.Content.Data.T.(type) { + case float64: + tStr = strconv.FormatInt(int64(tv), 10) + case string: + tStr = tv + default: + tStr = fmt.Sprintf("%d", tv) + } + sess.params["t"] = tStr + sess.params["ck"] = result.Content.Data.Ck + sess.qrContent = result.Content.Data.CodeContent + + // 4. 生成二维码图片 base64。 + png, err := qrcode.New(result.Content.Data.CodeContent, qrcode.Low) + if err != nil { + return "", "", fmt.Errorf("生成二维码失败: %w", err) + } + png.DisableBorder = false + pngBytes, _ := png.PNG(256) + pngBytes64 := base64.StdEncoding.EncodeToString(pngBytes) + qrCodeURL = "data:image/png;base64," + pngBytes64 + + sess.QRCodeURL = qrCodeURL + + m.mu.Lock() + m.sessions[sessionID] = sess + m.mu.Unlock() + + // 5. 后台轮询扫码状态。 + go m.monitorQRStatus(context.Background(), sessionID) + + m.logger.Info("二维码生成成功", "session_id", sessionID) + return sessionID, qrCodeURL, nil +} + +// GetSessionStatus 查询扫码状态。 +func (m *Manager) GetSessionStatus(sessionID string) map[string]any { + m.mu.Lock() + sess, ok := m.sessions[sessionID] + m.mu.Unlock() + if !ok { + return map[string]any{"status": "not_found"} + } + if sess.isExpired() && sess.Status != "success" { + sess.Status = "expired" + } + result := map[string]any{ + "status": sess.Status, + "session_id": sessionID, + } + if sess.Status == "verification_required" && sess.verificationURL != "" { + result["verification_url"] = sess.verificationURL + result["message"] = "账号被风控,需要手机验证" + if sess.verificationScreenshot != "" { + result["verification_screenshot"] = sess.verificationScreenshot + } + } + if sess.Status == "success" && sess.cookies != nil && sess.unb != "" { + result["cookies"] = cookieMarshal(sess.cookies) + result["unb"] = sess.unb + } + return result +} + +// CleanupExpired 清理过期会话。 +func (m *Manager) CleanupExpired() { + m.mu.Lock() + defer m.mu.Unlock() + for id, s := range m.sessions { + if s.isExpired() && s.Status != "success" { + delete(m.sessions, id) + m.logger.Info("清理过期扫码会话", "session_id", id) + } + } +} + +// monitorQRStatus 后台轮询扫码状态(移植自 Python _monitor_qr_status)。 +func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) { + m.mu.Lock() + sess := m.sessions[sessionID] + m.mu.Unlock() + if sess == nil { + return + } + + maxWait := 5 * time.Minute + start := time.Now() + + for time.Since(start) < maxWait { + select { + case <-ctx.Done(): + return + default: + } + + m.mu.Lock() + if _, ok := m.sessions[sessionID]; !ok { + m.mu.Unlock() + return + } + m.mu.Unlock() + + resp, err := m.pollQRCodeStatus(ctx, sess) + if err != nil { + m.logger.Error("轮询扫码状态异常", "err", err) + time.Sleep(2 * time.Second) + continue + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + + var qrResult struct { + Content struct { + Data struct { + QRCodeStatus string `json:"qrCodeStatus"` + IframeRedirect bool `json:"iframeRedirect"` + IframeRedirectURL string `json:"iframeRedirectUrl"` + } `json:"data"` + } `json:"content"` + } + json.Unmarshal(body, &qrResult) + + status := qrResult.Content.Data.QRCodeStatus + switch status { + case "CONFIRMED": + if qrResult.Content.Data.IframeRedirect { + // 风控验证:记录状态和 URL,提取响应 cookie(临时 cookie), + // 验证完成后用这些临时 cookie 访问 goofish.com/im 换真实 cookie。 + if sess.Status != "verification_required" { + sess.Status = "verification_required" + sess.verificationURL = qrResult.Content.Data.IframeRedirectURL + for _, c := range resp.Cookies() { + sess.cookies[c.Name] = c.Value + } + m.logger.Warn("扫码登录需要风控验证,立即启动浏览器等待验证", "session_id", sessionID, "verification_url", logsafe.URL(sess.verificationURL), "tmp_cookie_count", len(sess.cookies)) + + // 关键:必须在检测到风控时立即启动浏览器,带临时 cookie 打开验证页面。 + // 用户在手机完成验证后,服务端回调打到这个 Chromium 页面(redirect 到 ivCheckLogin.htm), + // Chromium 才能拿到授权 session,再访问 /im 得到 unb。 + // 不能等用户点按钮——那时验证已绑定到用户浏览器 session,与此 Chromium 无关。 + if m.sidecar != nil { + sidecarFn := m.sidecar + cookieStr := cookieMarshal(sess.cookies) + verURL := sess.verificationURL + go func() { + onScreenshot := func(dataURL string) { + m.mu.Lock() + if s, ok := m.sessions[sessionID]; ok { + s.verificationScreenshot = dataURL + } + m.mu.Unlock() + } + realCookies, unb, err := sidecarFn(context.Background(), cookieStr, verURL, onScreenshot) + m.mu.Lock() + defer m.mu.Unlock() + s, ok := m.sessions[sessionID] + if !ok { + return + } + if err != nil { + m.logger.Error("浏览器等待验证失败", "err", err) + return + } + s.cookies = parseCookieStr(realCookies) + s.unb = unb + s.Status = "success" + m.logger.Info("浏览器验证成功,已自动完成登录", "session_id", sessionID, "account_hash", logsafe.ID(unb)) + }() + } + } + time.Sleep(800 * time.Millisecond) + continue + } + sess.Status = "success" + for _, c := range resp.Cookies() { + sess.cookies[c.Name] = c.Value + if c.Name == "unb" { + sess.unb = c.Value + } + } + m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb)) + return + case "NEW": + // 未扫码,继续 + case "EXPIRED": + // 验证中的 EXPIRED 是正常的(验证通过后二维码 session 结束), + // 保持 verification_required 状态,等用户点"我已完成验证"。 + if sess.Status != "verification_required" { + sess.Status = "expired" + m.logger.Info("二维码已过期", "session_id", sessionID) + return + } + m.logger.Info("验证中收到 EXPIRED,保持验证状态", "session_id", sessionID) + time.Sleep(2 * time.Second) + continue + case "SCANED": + if sess.Status == "waiting" { + sess.Status = "scanned" + m.logger.Info("二维码已扫描,等待确认", "session_id", sessionID) + } + default: + sess.Status = "cancelled" + m.logger.Info("用户取消登录", "session_id", sessionID) + return + } + time.Sleep(800 * time.Millisecond) + } + + // 超时 + if sess.Status != "success" && sess.Status != "expired" && sess.Status != "cancelled" { + sess.Status = "expired" + } +} + +// CompleteVerification 用户完成风控验证后调用:先用扫码临时 cookie 访问 goofish.com/im, +// 必要时再使用浏览器提取真实 cookie(含 unb)。 +// 移植自 Python refresh_cookies_from_qr_login 的核心,并保留浏览器兜底。 +func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) { + m.mu.Lock() + sess, ok := m.sessions[sessionID] + m.mu.Unlock() + if !ok { + return "", "", fmt.Errorf("会话不存在") + } + if len(sess.cookies) == 0 { + return "", "", fmt.Errorf("无扫码临时 cookie") + } + + m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(sess.cookies)) + + // 用带 cookie jar 的 client,访问 goofish.com/im 触发真实 cookie 下发。 + jarClient := &http.Client{Timeout: 30 * time.Second} + targetURL := qrVerifyTargetURL + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil) + m.setHeaders(req) + req.Header.Set("Cookie", cookieMarshal(sess.cookies)) + // im 页面 referer + req.Header.Set("Referer", "https://www.goofish.com/") + + resp, err := jarClient.Do(req) + if err != nil { + if m.sidecar == nil { + return "", "", fmt.Errorf("访问 goofish.com/im 失败: %w", err) + } + m.logger.Warn("纯 HTTP 访问 goofish.com/im 失败,改用 sidecar 提取", "session_id", sessionID, "err", err) + } else { + defer resp.Body.Close() + io.Copy(io.Discard, resp.Body) + + // 收集 Set-Cookie。 + for _, c := range resp.Cookies() { + sess.cookies[c.Name] = c.Value + if c.Name == "unb" { + sess.unb = c.Value + } + } + } + + // 如果还没 unb 且没有 sidecar,再访问 mtop token API 触发(有时需要额外请求)。 + // 有 sidecar 时直接走浏览器路径,避免在风控场景中重复纯 HTTP 请求。 + if sess.unb == "" && m.sidecar == nil { + m.logger.Info("首次访问未拿到 unb,尝试 mtop token API", "session_id", sessionID) + if err := m.getMH5TK(ctx, sess); err != nil { + m.logger.Warn("mtop token API 失败", "err", err) + } + } + + m.logger.Info("验证完成,提取 cookie", "session_id", sessionID, "cookie_count", len(sess.cookies), "has_unb", sess.unb != "") + if sess.unb != "" { + sess.Status = "success" + m.logger.Info("纯 HTTP 提取 cookie 成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb)) + return cookieMarshal(sess.cookies), sess.unb, nil + } + + // 纯 HTTP 拿不到 unb(闲鱼真实 cookie 由页面 JS 异步下发), + // 风控验证后的 cookie 提取必须依赖 sidecar(playwright 浏览器)。 + if m.sidecar == nil { + return "", "", fmt.Errorf("风控验证后的 cookie 提取需要浏览器支持(请勿使用 -no-browser 启动)") + } + + m.logger.Info("纯 HTTP 未拿到 unb,调用 sidecar 浏览器提取", "session_id", sessionID) + realCookies, sidecarUNB, err := m.sidecar(ctx, cookieMarshal(sess.cookies), sess.verificationURL, nil) + if err != nil { + m.logger.Error("sidecar 提取失败", "err", err) + return "", "", fmt.Errorf("浏览器提取 cookie 失败: %w", err) + } + parsedCookies := parseCookieStr(realCookies) + if len(parsedCookies) == 0 { + return "", "", fmt.Errorf("浏览器提取 cookie 失败: sidecar 未返回有效 cookie") + } + sess.cookies = parsedCookies + sess.unb = sidecarUNB + if sess.unb == "" { + sess.unb = sess.cookies["unb"] + } + if sess.unb == "" { + return "", "", fmt.Errorf("验证后仍未获取到 unb,可能验证未完成或临时 cookie 已失效") + } + m.logger.Info("sidecar 提取成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb), "cookie_count", len(sess.cookies)) + + sess.Status = "success" + return cookieMarshal(sess.cookies), sess.unb, nil +} + +// parseCookieStr 把 "k=v; k2=v2" 解析回 map。 +func parseCookieStr(s string) map[string]string { + m := make(map[string]string) + for _, part := range strings.Split(s, "; ") { + if eq := strings.Index(part, "="); eq >= 0 { + m[part[:eq]] = part[eq+1:] + } + } + return m +} + +// getMH5TK 获取 m_h5_tk(移植自 Python _get_mh5tk)。 +func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error { + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiH5TK, nil) + m.setHeaders(req) + + resp, err := m.httpc.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + io.Copy(io.Discard, resp.Body) + + // 合并 Set-Cookie。 + for _, c := range resp.Cookies() { + sess.cookies[c.Name] = c.Value + } + + mH5TK := sess.cookies["_m_h5_tk"] + token := "" + if parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 { + token = parts[0] + } + + t := strconv.FormatInt(time.Now().UnixMilli(), 10) + dataStr := `{"bizScene":"home"}` + signInput := token + "&" + t + "&" + appKey + "&" + dataStr + sign := md5hex(signInput) + + params := url.Values{} + params.Set("jsv", "2.7.2") + params.Set("appKey", appKey) + params.Set("t", t) + params.Set("sign", sign) + params.Set("v", "1.0") + params.Set("type", "originaljson") + params.Set("dataType", "json") + params.Set("timeout", "20000") + params.Set("api", "mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get") + params.Set("data", dataStr) + + req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiH5TK+"?"+params.Encode(), nil) + m.setHeaders(req2) + req2.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + resp2, err := m.httpc.Do(req2) + if err != nil { + return err + } + defer resp2.Body.Close() + io.Copy(io.Discard, resp2.Body) + + // 更新 cookie。 + for _, c := range resp2.Cookies() { + sess.cookies[c.Name] = c.Value + } + return nil +} + +// getLoginParams 获取登录表单参数(移植自 Python _get_login_params)。 +func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string]string, error) { + params := url.Values{} + params.Set("lang", "zh_cn") + params.Set("appName", "xianyu") + params.Set("appEntrance", "web") + params.Set("styleType", "vertical") + params.Set("bizParams", "") + params.Set("notLoadSsoView", "false") + params.Set("notKeepLogin", "false") + params.Set("isMobile", "false") + params.Set("qrCodeFirst", "false") + params.Set("stie", "77") + params.Set("rnd", fmt.Sprintf("%f", randFloat())) + + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, apiMiniLogin+"?"+params.Encode(), nil) + m.setHeaders(req) + + // 带上已有 cookie。 + cookieStr := cookieMarshal(sess.cookies) + if cookieStr != "" { + req.Header.Set("Cookie", cookieStr) + } + + resp, err := m.httpc.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + + // 调试:打印响应状态和 body 前 200 字符 + + // 从 HTML 里提取 window.viewData = {...}; + re := regexp.MustCompile(`window\.viewData\s*=\s*(\{.*?\});`) + match := re.FindSubmatch(body) + if match == nil { + return nil, fmt.Errorf("获取登录参数失败:未找到 viewData") + } + + var viewData struct { + LoginFormData map[string]any `json:"loginFormData"` + } + if err := json.Unmarshal(match[1], &viewData); err != nil { + return nil, fmt.Errorf("解析 viewData 失败: %w", err) + } + if viewData.LoginFormData == nil { + return nil, fmt.Errorf("loginFormData 为空") + } + // 把所有值转为字符串(有些是 bool/number)。 + strParams := make(map[string]string, len(viewData.LoginFormData)) + for k, v := range viewData.LoginFormData { + strParams[k] = fmt.Sprintf("%v", v) + } + strParams["umidTag"] = "SERVER" + sess.params = strParams + return strParams, nil +} + +// pollQRCodeStatus 轮询二维码状态。 +func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Response, error) { + form := url.Values{} + for k, v := range sess.params { + form.Set(k, v) + } + + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiScanStatus, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + m.setHeaders(req) + cookieStr := cookieMarshal(sess.cookies) + if cookieStr != "" { + req.Header.Set("Cookie", cookieStr) + } + + return m.httpc.Do(req) +} + +func (m *Manager) setHeaders(req *http.Request) { + for k, v := range qrHeaders { + req.Header.Set(k, v) + } +} + +// ---- 工具函数 ---- + +func md5hex(s string) string { + h := md5.Sum([]byte(s)) + return hex.EncodeToString(h[:]) +} + +func cookieMarshal(cookies map[string]string) string { + parts := make([]string, 0, len(cookies)) + for k, v := range cookies { + parts = append(parts, k+"="+v) + } + return strings.Join(parts, "; ") +} + +func randomUUID() string { + b := make([]byte, 16) + if _, err := io.ReadFull(randReader, b); err != nil { + // 降级到时间种子(极少见) + for i := range b { + b[i] = byte(time.Now().UnixNano() >> (i * 8)) + } + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", + b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) +} + +var randReader io.Reader = rand.Reader +var randFloat = func() float64 { return float64(time.Now().UnixNano()%1e9) / 1e9 } + +func truncate(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + "..." +} + +// 包级别引用,避免 import 报错。 +var _ = bytes.NewReader diff --git a/internal/xianyu/qrlogin/client_test.go b/internal/xianyu/qrlogin/client_test.go new file mode 100644 index 0000000..16de838 --- /dev/null +++ b/internal/xianyu/qrlogin/client_test.go @@ -0,0 +1,95 @@ +package qrlogin + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestCompleteVerificationRequiresSidecarWhenHTTPMissingUNB(t *testing.T) { + m := NewManager(nil) + m.sessions["s1"] = testVerificationSession() + oldTarget := qrVerifyTargetURL + qrVerifyTargetURL = newEmptyCookieServer(t) + defer func() { qrVerifyTargetURL = oldTarget }() + + _, _, err := m.CompleteVerification(context.Background(), "s1") + if err == nil || !strings.Contains(err.Error(), "需要浏览器支持") { + t.Fatalf("错误异常: %v", err) + } +} + +func TestCompleteVerificationSidecarSuccess(t *testing.T) { + m := NewManager(nil) + m.sessions["s1"] = testVerificationSession() + m.SetSidecarRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) { + if !strings.Contains(tmpCookies, "tmp=1") { + t.Fatalf("sidecar 收到临时 cookie 异常: %q", tmpCookies) + } + return "unb=999; cookie2=abc", "999", nil + }) + oldTarget := qrVerifyTargetURL + qrVerifyTargetURL = newEmptyCookieServer(t) + defer func() { qrVerifyTargetURL = oldTarget }() + + cookies, unb, err := m.CompleteVerification(context.Background(), "s1") + if err != nil { + t.Fatalf("CompleteVerification: %v", err) + } + if unb != "999" || !strings.Contains(cookies, "unb=999") { + t.Fatalf("返回异常: cookies=%q unb=%q", cookies, unb) + } + if m.sessions["s1"].Status != "success" { + t.Fatalf("状态异常: %s", m.sessions["s1"].Status) + } +} + +func TestCompleteVerificationSidecarUNBFromCookieMap(t *testing.T) { + m := NewManager(nil) + m.sessions["s1"] = testVerificationSession() + m.SetSidecarRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) { + return "unb=888; cookie2=abc", "", nil + }) + oldTarget := qrVerifyTargetURL + qrVerifyTargetURL = newEmptyCookieServer(t) + defer func() { qrVerifyTargetURL = oldTarget }() + + _, unb, err := m.CompleteVerification(context.Background(), "s1") + if err != nil { + t.Fatalf("CompleteVerification: %v", err) + } + if unb != "888" { + t.Fatalf("应从 cookie map 提取 unb,got %q", unb) + } +} + +func TestCompleteVerificationMissingSession(t *testing.T) { + m := NewManager(nil) + _, _, err := m.CompleteVerification(context.Background(), "missing") + if err == nil || !strings.Contains(err.Error(), "会话不存在") { + t.Fatalf("错误异常: %v", err) + } +} + +func testVerificationSession() *Session { + return &Session{ + SessionID: "s1", + Status: "verification_required", + cookies: map[string]string{"tmp": "1"}, + createdTime: time.Now(), + expireTime: 5 * time.Minute, + } +} + +func newEmptyCookieServer(t *testing.T) string { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok")) + })) + t.Cleanup(srv.Close) + return srv.URL +} diff --git a/internal/xianyu/ua.go b/internal/xianyu/ua.go new file mode 100644 index 0000000..ac50bf9 --- /dev/null +++ b/internal/xianyu/ua.go @@ -0,0 +1,27 @@ +// Package xianyu 的公共常量:UA 统一管理。 +// +// 真实浏览器的所有出站请求(HTTP mtop + WS 握手 + /reg 注册消息)UA 必须完全一致, +// 否则版本号自相矛盾会被风控识别为伪造。这里集中定义,三处引用同一常量,杜绝不一致。 +// +// 版本号选择原则:用主流稳定版区间,避免太新(显得伪造)或太旧(显得异常)。 +// Chrome/138 是 Python 原项目实测可跑通的版本之一。 +package xianyu + +// ChromeVer 统一的 Chrome 版本号,所有 UA 引用此常量。 +// 必须与 playwright-go 实际下载的 Chromium 版本对齐。 +// playwright-go v0.5700.1 → Playwright v1.57.0 → Chromium 143.0.7499.4 +const ChromeVer = "143.0.7499.4" + +// ChromeMajor Chrome 主版本号(sec-ch-ua 用),从 ChromeVer 派生。 +const ChromeMajor = "143" + +// BrowserUA 标准 Chrome 浏览器 UA(HTTP mtop / WS 握手共用)。 +const BrowserUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + ChromeVer + " Safari/537.36" + +// RegUA WS /reg 注册消息用的 UA:浏览器 UA + 闲鱼网页客户端标识(DingTalk/DingWeb)。 +// DingTalk 后缀是闲鱼网页真实客户端标识,必须保留;其 Chrome 版本与 BrowserUA 一致。 +const RegUA = BrowserUA + " DingTalk(2.1.5) OS(Windows/10) Browser(Chrome/" + ChromeVer + ") DingWeb/2.1.5 IMPaaS DingWeb/2.1.5" + +// SecChUA sec-ch-ua 请求头值,主版本号与 ChromeMajor 一致。 +// 真实浏览器 sec-ch-ua 的版本号必须与 UA 的 Chrome 主版本号匹配,否则矛盾。 +const SecChUA = `"Not;A=Brand";v="99", "Google Chrome";v="` + ChromeMajor + `", "Chromium";v="` + ChromeMajor + `"` diff --git a/internal/xianyu/ua_test.go b/internal/xianyu/ua_test.go new file mode 100644 index 0000000..54726fa --- /dev/null +++ b/internal/xianyu/ua_test.go @@ -0,0 +1,38 @@ +package xianyu + +import ( + "strings" + "testing" +) + +// TestUAConsistency 保证所有出站请求的 Chrome 版本号完全一致。 +// 这是反风控的关键:真实浏览器 HTTP 请求、WS 握手、/reg 注册消息的 UA 必须同版本号, +// sec-ch-ua 的主版本也必须匹配。任何一处不一致都是伪造特征。 +func TestUAConsistency(t *testing.T) { + // 1. BrowserUA 含 ChromeVer。 + if !strings.Contains(BrowserUA, "Chrome/"+ChromeVer) { + t.Errorf("BrowserUA 未含 Chrome/%s: %s", ChromeVer, BrowserUA) + } + + // 2. RegUA 必须以 BrowserUA 开头(同一浏览器 UA + DingTalk 后缀)。 + if !strings.HasPrefix(RegUA, BrowserUA) { + t.Errorf("RegUA 必须以 BrowserUA 开头(保证 Chrome 版本一致)\n RegUA: %s\n BrowserUA: %s", RegUA, BrowserUA) + } + // RegUA 的 Browser(Chrome/x) 后缀版本也要一致。 + if !strings.Contains(RegUA, "Browser(Chrome/"+ChromeVer+")") { + t.Errorf("RegUA 的 Browser(Chrome/x) 版本与 ChromeVer 不一致: %s", RegUA) + } + + // 3. SecChUA 的主版本号必须等于 ChromeMajor。 + if !strings.Contains(SecChUA, `"Google Chrome";v="`+ChromeMajor+`"`) { + t.Errorf("SecChUA 的 Google Chrome 版本与 ChromeMajor 不一致: %s", SecChUA) + } + if !strings.Contains(SecChUA, `"Chromium";v="`+ChromeMajor+`"`) { + t.Errorf("SecChUA 的 Chromium 版本与 ChromeMajor 不一致: %s", SecChUA) + } + + // 4. ChromeMajor 必须是 ChromeVer 的主版本号前缀。 + if !strings.HasPrefix(ChromeVer, ChromeMajor+".") { + t.Errorf("ChromeMajor(%s) 应是 ChromeVer(%s) 的主版本前缀", ChromeMajor, ChromeVer) + } +} diff --git a/internal/xianyu/ws/client.go b/internal/xianyu/ws/client.go new file mode 100644 index 0000000..f3d5dcb --- /dev/null +++ b/internal/xianyu/ws/client.go @@ -0,0 +1,408 @@ +// Package ws 实现闲鱼 WebSocket 连接生命周期:握手、/reg 注册、心跳、ACK、消息解密。 +// 移植自 Python XianyuAutoAsync.py 的 main/init/send_heartbeat/handle_message。 +package ws + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "strings" + "sync" + "time" + + "github.com/coder/websocket" + + "xianyu-go/internal/xianyu" + "xianyu-go/internal/xianyu/protocol" +) + +// WSURL 闲鱼 IM WebSocket 地址。 +const WSURL = "wss://wss-goofish.dingtalk.com/" + +// regUA WS /reg 注册消息用的 UA(含闲鱼网页客户端 DingTalk 标识)。 +// 引用 xianyu.RegUA 保证与 HTTP 请求的 Chrome 版本号一致。 +var regUA = xianyu.RegUA + +// RegAppKey WS /reg 用的 app-key。 +const RegAppKey = "444e9908a51d1cb236a27862abc769c9" + +// Config 单账号 WS 连接所需的最小配置。 +type Config struct { + CookieStr string // 完整 cookie 字符串 + DeviceID string // generate_device_id(myid) + AccessToken string // mtop token API 返回的 accessToken + Recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) +} + +// Conn 包装一条已注册的 WebSocket 连接。 +type Conn struct { + ws *websocket.Conn + cfg Config + logger *slog.Logger + sendMu sync.Mutex + recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) +} + +// SetRecorder 设置帧记录器。 +func (c *Conn) SetRecorder(rec func(direction, rawText, parsedJSON, parseStatus, errMsg string)) { + c.recorder = rec +} + +// Dial 建立并注册 WS 连接:握手 → /reg → /r/SyncStatus/ackDiff。 +func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) { + if logger == nil { + logger = slog.Default() + } + // 握手头:Cookie + 浏览器指纹(Origin/Host 由 dialer 据 URL 自动设置,这里显式覆盖)。 + hdr := http.Header{} + hdr.Set("Accept-Encoding", "gzip, deflate, br, zstd") + hdr.Set("Accept-Language", "zh-CN,zh;q=0.9") + hdr.Set("Cache-Control", "no-cache") + hdr.Set("Pragma", "no-cache") + hdr.Set("User-Agent", xianyu.BrowserUA) + hdr.Set("Origin", "https://www.goofish.com") + hdr.Set("Cookie", cfg.CookieStr) + + logger.Info("正在连接闲鱼 WebSocket", "url", WSURL) + c, _, err := websocket.Dial(ctx, WSURL, &websocket.DialOptions{HTTPHeader: hdr}) + if err != nil { + return nil, fmt.Errorf("WS dial: %w", err) + } + // 闲鱼消息多为文本 JSON。 + c.SetReadLimit(8 << 20) // 8 MiB,宽松上限 + + conn := &Conn{ws: c, cfg: cfg, logger: logger, recorder: cfg.Recorder} + if err := conn.register(ctx); err != nil { + c.CloseNow() + return nil, err + } + return conn, nil +} + +// register 发送 /reg 与 ackDiff。 +func (c *Conn) register(ctx context.Context) error { + reg := map[string]any{ + "lwp": "/reg", + "headers": map[string]any{ + "cache-header": "app-key token ua wv", + "app-key": RegAppKey, + "token": c.cfg.AccessToken, + "ua": regUA, + "dt": "j", + "wv": "im:3,au:3,sy:6", + "sync": "0,0;0;0;", + "did": c.cfg.DeviceID, + "mid": protocol.GenerateMid(), + }, + } + if err := c.sendJSON(ctx, reg); err != nil { + return fmt.Errorf("发送 /reg 失败: %w", err) + } + + // Python 端在 /reg 后 sleep 1s 再发 ackDiff,这里用 1s 等待。 + select { + case <-time.After(time.Second): + case <-ctx.Done(): + return ctx.Err() + } + + now := time.Now().UnixMilli() + ackDiff := map[string]any{ + "lwp": "/r/SyncStatus/ackDiff", + "headers": map[string]any{"mid": protocol.GenerateMid()}, + "body": []any{ + map[string]any{ + "pipeline": "sync", + "tooLong2Tag": "PNM,1", + "channel": "sync", + "topic": "sync", + "highPts": 0, + "pts": now * 1000, + "seq": 0, + "timestamp": now, + }, + }, + } + if err := c.sendJSON(ctx, ackDiff); err != nil { + return fmt.Errorf("发送 ackDiff 失败: %w", err) + } + c.logger.Info("WS 注册完成") + return nil +} + +// HeartbeatLoop 周期性发送应用层心跳 {"lwp":"/!"},直到 ctx 取消或连续失败 maxFailures 次。 +func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error { + const maxFailures = 3 + consecutive := 0 + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + } + hb := map[string]any{ + "lwp": "/!", + "headers": map[string]any{"mid": protocol.GenerateMid()}, + } + // 2s 超时保护。 + sendCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + err := c.sendJSON(sendCtx, hb) + cancel() + if err != nil { + consecutive++ + c.logger.Error("心跳发送失败", "err", err, "consecutive", consecutive) + if consecutive >= maxFailures { + return fmt.Errorf("心跳连续失败 %d 次", maxFailures) + } + continue + } + consecutive = 0 + } +} + +// ReceiveLoop 阻塞读取消息:回 ACK,对同步包解密并回调 handler。 +// 非 JSON / 非同步包消息仅记录后跳过。返回 ctx 错误或致命读取错误。 +func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[string]any)) error { + for { + msgType, data, err := c.ws.Read(ctx) + if err != nil { + return fmt.Errorf("WS read: %w", err) + } + _ = msgType + rawText := string(data) + var raw map[string]any + if err := json.Unmarshal(data, &raw); err != nil { + if c.recorder != nil { + c.recorder("in", rawText, "", "non_json", err.Error()) + } + c.logger.Debug("非 JSON 消息,跳过", "err", err) + continue + } + if c.recorder != nil { + if b, e := json.Marshal(raw); e == nil { + c.recorder("in", rawText, string(b), "json", "") + } else { + c.recorder("in", rawText, "", "json", e.Error()) + } + } + + // 心跳响应等直接跳过。 + if code, ok := raw["code"]; ok && code != nil { + c.logger.Debug("收到响应", "code", code) + } + + // 先回 ACK(与 Python handle_message 一致)。 + c.sendACK(ctx, raw) + + // 仅处理同步包:body.syncPushPackage.data[0].data + syncData, ok := extractSyncPayload(raw) + if !ok { + if c.recorder != nil { + c.recorder("in", rawText, "", "skip_non_sync", "") + } + continue + } + decoded, err := decodeSyncData(syncData) + if err != nil { + if c.recorder != nil { + c.recorder("in", rawText, "", "decrypt_failed", err.Error()) + } + c.logger.Error("消息解密失败", "err", err) + continue + } + if c.recorder != nil { + if b, e := json.Marshal(decoded); e == nil { + c.recorder("in", rawText, string(b), "decrypted", "") + } + } + if onMessage != nil { + onMessage(decoded) + } + } +} + +// sendACK 回复 {"code":200, headers:{mid,sid,...}},失败静默(与 Python except: pass 一致)。 +func (c *Conn) sendACK(ctx context.Context, msg map[string]any) { + headers, _ := msg["headers"].(map[string]any) + ack := map[string]any{ + "code": 200, + "headers": map[string]any{ + "mid": ackVal(headers, "mid", protocol.GenerateMid()), + "sid": ackVal(headers, "sid", ""), + }, + } + ackHeaders := ack["headers"].(map[string]any) + for _, k := range []string{"app-key", "ua", "dt"} { + if v, ok := headers[k]; ok && v != nil { + ackHeaders[k] = v + } + } + // ACK 失败不阻塞主循环。 + ackCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + _ = c.sendJSON(ackCtx, ack) + cancel() +} + +// ackVal 取 header 中的 key,缺失或为 nil 时返回 fallback。 +func ackVal(headers map[string]any, key string, fallback any) any { + if v, ok := headers[key]; ok && v != nil { + return v + } + return fallback +} + +// extractSyncPayload 取出 body.syncPushPackage.data[0].data(字符串)。 +func extractSyncPayload(msg map[string]any) (string, bool) { + body, _ := msg["body"].(map[string]any) + if body == nil { + return "", false + } + pkg, _ := body["syncPushPackage"].(map[string]any) + if pkg == nil { + return "", false + } + arr, _ := pkg["data"].([]any) + if len(arr) == 0 { + return "", false + } + first, _ := arr[0].(map[string]any) + if first == nil { + return "", false + } + d, ok := first["data"].(string) + return d, ok && d != "" +} + +// decodeSyncData 先尝试 base64+JSON(未加密系统消息),失败则 base64+msgpack 解密。 +func decodeSyncData(data string) (map[string]any, error) { + // 1) 先按 Python:base64 解码 → 尝试 JSON + if dec, err := base64.StdEncoding.DecodeString(data); err == nil { + var parsed map[string]any + if jsonErr := json.Unmarshal(dec, &parsed); jsonErr == nil { + return parsed, nil + } + } + // 2) JSON 解析失败 → msgpack 解密 + out, err := protocol.Decrypt(data) + if err != nil { + return nil, err + } + var parsed map[string]any + if err := json.Unmarshal([]byte(out), &parsed); err != nil { + return nil, fmt.Errorf("解密后非 JSON: %w", err) + } + return parsed, nil +} + +// sendJSON 发送一条 JSON 文本帧。 +func (c *Conn) sendJSON(ctx context.Context, v any) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + if c.recorder != nil { + c.recorder("out", string(b), string(b), "json", "") + } + c.sendMu.Lock() + defer c.sendMu.Unlock() + return c.ws.Write(ctx, websocket.MessageText, b) +} + +// SendText 发送一条闲鱼聊天文本消息。 +func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error { + content := map[string]any{ + "contentType": 1, + "text": map[string]any{ + "text": text, + }, + } + return c.sendChatContent(ctx, myID, cid, toID, content) +} + +// SendImage 发送一条闲鱼聊天图片消息。imageURL 应为闲鱼可访问的 CDN/公网 URL。 +func (c *Conn) SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error { + if width <= 0 { + width = 800 + } + if height <= 0 { + height = 600 + } + content := map[string]any{ + "contentType": 2, + "image": map[string]any{ + "pics": []map[string]any{{ + "height": height, + "type": 0, + "url": imageURL, + "width": width, + }}, + }, + } + return c.sendChatContent(ctx, myID, cid, toID, content) +} + +func (c *Conn) sendChatContent(ctx context.Context, myID, cid, toID string, content any) error { + myID = stripGoofish(myID) + cid = stripGoofish(cid) + toID = stripGoofish(toID) + if myID == "" || cid == "" || toID == "" { + return fmt.Errorf("发送消息缺少必要参数: myID=%q cid=%q toID=%q", myID, cid, toID) + } + raw, err := json.Marshal(content) + if err != nil { + return err + } + encoded := base64.StdEncoding.EncodeToString(raw) + msg := map[string]any{ + "lwp": "/r/MessageSend/sendByReceiverScope", + "headers": map[string]any{ + "mid": protocol.GenerateMid(), + }, + "body": []any{ + map[string]any{ + "uuid": protocol.GenerateUUID(), + "cid": cid + "@goofish", + "conversationType": 1, + "content": map[string]any{ + "contentType": 101, + "custom": map[string]any{ + "type": 1, + "data": encoded, + }, + }, + "redPointPolicy": 0, + "extension": map[string]any{ + "extJson": "{}", + }, + "ctx": map[string]any{ + "appVersion": "1.0", + "platform": "web", + }, + "mtags": map[string]any{}, + "msgReadStatusSetting": 1, + }, + map[string]any{ + "actualReceivers": []string{ + toID + "@goofish", + myID + "@goofish", + }, + }, + }, + } + return c.sendJSON(ctx, msg) +} + +func stripGoofish(s string) string { + s = strings.TrimSpace(s) + return strings.TrimSuffix(s, "@goofish") +} + +// Close 关闭连接。 +func (c *Conn) Close() error { + return c.ws.Close(websocket.StatusNormalClosure, "bye") +}