merge: integrate phase1 chat and account automation
This commit is contained in:
commit
0de1ec7635
72 files changed
+5475
-284
No files matched your search
@@ -310,7 +310,7 @@ LocalAI 或兼容网关。只有在明确了解数据流向时才应向外部 AI
|
||||
GitHub Actions 会将同一标签发布为多架构镜像:
|
||||
|
||||
```text
|
||||
ghcr.io/christ9038/ydisks-xianyu-helper:dev
|
||||
ghcr.io/christ9038/ydisks-xianyu-helper:latest
|
||||
├── linux/amd64
|
||||
└── linux/arm64
|
||||
```
|
||||
@@ -322,10 +322,13 @@ ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
|
||||
|
||||
| Git 引用 | 镜像标签 |
|
||||
| --- | --- |
|
||||
| `dev` 分支 | `dev`、`sha-<完整提交号>` |
|
||||
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
|
||||
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
|
||||
|
||||
当前 Docker 发布工作流只在 `main` 分支推送和发布镜像;`dev` 分支不会自动生成
|
||||
GHCR 标签。开发分支如需验证镜像,请在本地使用源码构建 Compose 文件,或手动运行
|
||||
对应的构建流程。
|
||||
|
||||
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
|
||||
|
||||
### Compose 服务
|
||||
|
||||
+36
-28
@@ -7,8 +7,10 @@ package main
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
@@ -32,66 +34,72 @@ func main() {
|
||||
resolved = *dbPath
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
if err := run(context.Background(), resolved, bufio.NewReader(os.Stdin), os.Stdout); err != nil {
|
||||
fatalf("初始化管理员失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// run 执行一次初始化流程。把数据库、输入和输出显式注入后,CLI 的核心行为
|
||||
// 可以在临时数据库中回归测试,而不会调用 os.Exit 或污染用户数据。
|
||||
func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writer) error {
|
||||
database, dialect, err := db.Open(ctx, resolved)
|
||||
if err != nil {
|
||||
fatalf("打开数据库失败: %v", err)
|
||||
return fmt.Errorf("打开数据库失败: %w", err)
|
||||
}
|
||||
defer database.Close()
|
||||
store := db.NewStore(database, dialect)
|
||||
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
existing, err := store.Users.GetAdmin(ctx)
|
||||
if err != nil && !isNotFound(err) {
|
||||
fatalf("查询 admin 失败: %v", err)
|
||||
return fmt.Errorf("查询 admin 失败: %w", err)
|
||||
}
|
||||
|
||||
if existing != nil {
|
||||
fmt.Printf("管理员用户 %s 已存在\n", existing.Username)
|
||||
fmt.Print("是否重置管理员密码?(y/N): ")
|
||||
fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username)
|
||||
fmt.Fprint(out, "是否重置管理员密码?(y/N): ")
|
||||
ans, _ := reader.ReadString('\n')
|
||||
if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") {
|
||||
fmt.Println("跳过初始化")
|
||||
return
|
||||
fmt.Fprintln(out, "跳过初始化")
|
||||
return nil
|
||||
}
|
||||
pw := promptPasswordTwice(reader)
|
||||
pw := promptPasswordTwice(reader, out)
|
||||
if _, err := auth.InitAdmin(ctx, store, "", pw); err != nil {
|
||||
fatalf("重置 admin 密码失败: %v", err)
|
||||
return fmt.Errorf("重置 admin 密码失败: %w", err)
|
||||
}
|
||||
fmt.Printf("重置完成:已更新 %s 的密码\n", existing.Username)
|
||||
return
|
||||
fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Println("=== 初始化管理员账号(CLI)===")
|
||||
fmt.Print("请输入管理员邮箱: ")
|
||||
fmt.Fprintln(out, "=== 初始化管理员账号(CLI)===")
|
||||
fmt.Fprint(out, "请输入管理员邮箱: ")
|
||||
email, _ := reader.ReadString('\n')
|
||||
email = strings.TrimSpace(email)
|
||||
if email == "" {
|
||||
fatalf("邮箱不能为空")
|
||||
return errors.New("邮箱不能为空")
|
||||
}
|
||||
pw := promptPasswordTwice(reader)
|
||||
pw := promptPasswordTwice(reader, out)
|
||||
|
||||
created, err := auth.InitAdmin(ctx, store, email, pw)
|
||||
if err != nil {
|
||||
fatalf("创建 admin 用户失败:%v", err)
|
||||
return fmt.Errorf("创建 admin 用户失败:%w", err)
|
||||
}
|
||||
if created {
|
||||
fmt.Println("初始化完成:已创建 admin 用户")
|
||||
fmt.Fprintln(out, "初始化完成:已创建 admin 用户")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// promptPasswordTwice 两次输入密码(不回显)并校验一致性。
|
||||
func promptPasswordTwice(reader *bufio.Reader) string {
|
||||
func promptPasswordTwice(reader *bufio.Reader, out io.Writer) string {
|
||||
for {
|
||||
p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ")
|
||||
p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out)
|
||||
if p1 == "" {
|
||||
fmt.Println("密码不能为空")
|
||||
fmt.Fprintln(out, "密码不能为空")
|
||||
continue
|
||||
}
|
||||
p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ")
|
||||
p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out)
|
||||
if p1 != p2 {
|
||||
fmt.Println("两次输入不一致,请重试")
|
||||
fmt.Fprintln(out, "两次输入不一致,请重试")
|
||||
continue
|
||||
}
|
||||
return p1
|
||||
@@ -100,11 +108,11 @@ func promptPasswordTwice(reader *bufio.Reader) string {
|
||||
|
||||
// readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道),
|
||||
// 共用同一 bufio.Reader 避免缓冲吞掉后续输入。
|
||||
func readPasswordNoEcho(reader *bufio.Reader, prompt string) string {
|
||||
fmt.Print(prompt)
|
||||
func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) string {
|
||||
fmt.Fprint(out, prompt)
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
b, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Println()
|
||||
fmt.Fprintln(out)
|
||||
if err != nil {
|
||||
fatalf("读取密码失败: %v", err)
|
||||
}
|
||||
@@ -116,7 +124,7 @@ func readPasswordNoEcho(reader *bufio.Reader, prompt string) string {
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool { return err == db.ErrNotFound }
|
||||
func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) }
|
||||
|
||||
func fatalf(format string, a ...any) {
|
||||
fmt.Fprintf(os.Stderr, format+"\n", a...)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"flag"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
func TestRunCreatesAdminInTemporaryDatabase(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||
var out bytes.Buffer
|
||||
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nsecret\nsecret\n")), &out)
|
||||
if err != nil {
|
||||
t.Fatalf("run create: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "初始化完成") {
|
||||
t.Fatalf("missing create confirmation: %s", out.String())
|
||||
}
|
||||
d, dialect, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
admin, err := db.NewStore(d, dialect).Users.GetAdmin(context.Background())
|
||||
if err != nil || admin == nil || admin.Email != "admin@example.com" {
|
||||
t.Fatalf("admin=%+v err=%v", admin, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunExistingAdminCanSkipReset(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||
input := "admin@example.com\nsecret\nsecret\n"
|
||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("n\n")), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "跳过初始化") {
|
||||
t.Fatalf("missing skip confirmation: %s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunExistingAdminResetsPasswordAfterMismatchRetry(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nold\nold\n")), &bytes.Buffer{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := "y\nnew\nnot-the-same\nnew\nnew\n"
|
||||
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, dialect, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
store := db.NewStore(d, dialect)
|
||||
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "old"); ok {
|
||||
t.Fatal("old password should be invalid")
|
||||
}
|
||||
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "new"); !ok {
|
||||
t.Fatal("new password should be valid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRejectsEmptyEmail(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
|
||||
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("\n")), &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "邮箱不能为空") {
|
||||
t.Fatalf("err=%v, want empty email error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMainCLIEntrypointUsesDatabaseFlag(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "main.db")
|
||||
stdin, writer, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldArgs, oldStdin, oldEnv, oldCommandLine := os.Args, os.Stdin, os.Getenv("DATABASE_URL"), flag.CommandLine
|
||||
defer func() {
|
||||
os.Args, os.Stdin, flag.CommandLine = oldArgs, oldStdin, oldCommandLine
|
||||
_ = os.Setenv("DATABASE_URL", oldEnv)
|
||||
_ = stdin.Close()
|
||||
}()
|
||||
os.Args = []string{"init-admin", "-db", dbPath}
|
||||
os.Stdin = stdin
|
||||
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
|
||||
flag.CommandLine.SetOutput(io.Discard)
|
||||
_ = os.Unsetenv("DATABASE_URL")
|
||||
go func() {
|
||||
_, _ = writer.Write([]byte("admin@example.com\nmain-secret\nmain-secret\n"))
|
||||
_ = writer.Close()
|
||||
}()
|
||||
main()
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/logging"
|
||||
"xianyu-go/internal/notify"
|
||||
@@ -149,6 +150,8 @@ func main() {
|
||||
}
|
||||
var mgr *account.Manager
|
||||
ap := adapter.New(store, bm, logger)
|
||||
chatService := chat.New(store)
|
||||
ap.SetChatService(chatService)
|
||||
mgr = account.NewManager(store, ap, logger)
|
||||
autoCenter := automation.New(store, mgr, logger)
|
||||
autoCenter.SetOrderDetailFetcher(ap)
|
||||
@@ -167,6 +170,7 @@ func main() {
|
||||
|
||||
// 3) HTTP 服务。
|
||||
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
srv.SetChatService(chatService)
|
||||
srv.StartPublishBatchRecovery(ctx)
|
||||
if err := srv.Run(ctx); err != nil {
|
||||
logger.Error("HTTP 服务退出", "err", err)
|
||||
|
||||
+13
-2
@@ -8,6 +8,8 @@ import ItemList from './components/ItemList';
|
||||
import Settings from './components/Settings';
|
||||
import Rules from './components/Rules';
|
||||
import Notifications from './components/Notifications';
|
||||
import Chat from './components/Chat';
|
||||
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
|
||||
import { YdisksBrandIcon } from './components/YdisksLogo';
|
||||
import { login, logout, verifySession } from './services/api';
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
@@ -24,6 +26,7 @@ interface DeliveryRuleTarget {
|
||||
const ROUTES: Record<string, string> = {
|
||||
'/app/dashboard': 'dashboard',
|
||||
'/app/accounts': 'accounts',
|
||||
'/app/chat': 'chat',
|
||||
'/app/orders': 'orders',
|
||||
'/app/cards': 'cards',
|
||||
'/app/items': 'items',
|
||||
@@ -50,6 +53,7 @@ const App: React.FC = () => {
|
||||
const [loginLoading, setLoginLoading] = useState(false);
|
||||
const [loginError, setLoginError] = useState('');
|
||||
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>();
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
|
||||
|
||||
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
|
||||
const navigate = (tab: string) => {
|
||||
@@ -266,6 +270,7 @@ const App: React.FC = () => {
|
||||
switch (activeTab) {
|
||||
case 'dashboard': return <Dashboard />;
|
||||
case 'accounts': return <AccountList />;
|
||||
case 'chat': return <Chat />;
|
||||
case 'orders': return <OrderList />;
|
||||
case 'cards': return <CardList />;
|
||||
case 'items': return <ItemList onConfigureDelivery={(item) => {
|
||||
@@ -287,15 +292,21 @@ const App: React.FC = () => {
|
||||
<Sidebar
|
||||
activeTab={activeTab}
|
||||
isAdmin={isAdmin}
|
||||
collapsed={sidebarCollapsed}
|
||||
onToggleCollapsed={() => setSidebarCollapsed(current => {
|
||||
const next = !current;
|
||||
writeSidebarCollapsed(next);
|
||||
return next;
|
||||
})}
|
||||
onNavigate={navigate}
|
||||
onLogout={handleLogout}
|
||||
/>
|
||||
|
||||
<main className="flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth">
|
||||
<main className={`h-screen flex-1 overflow-y-auto scroll-smooth transition-[margin] duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
|
||||
{/* Subtle background decoration */}
|
||||
<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"></div>
|
||||
|
||||
<div className="max-w-[1400px] mx-auto pb-10">
|
||||
<div className={`${activeTab === 'chat' ? 'mx-auto max-w-[1680px]' : 'mx-auto max-w-[1400px] pb-10'}`}>
|
||||
{renderContent()}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { renderXianyuText, xianyuEmojis } from './chatEmojis';
|
||||
|
||||
describe('official Xianyu emoji mapping', () => {
|
||||
test('contains the complete official panel in official order', () => {
|
||||
expect(xianyuEmojis).toHaveLength(126);
|
||||
expect(xianyuEmojis[0][0]).toBe('尊嘟假嘟');
|
||||
expect(xianyuEmojis.at(-1)?.[0]).toBe('爱心');
|
||||
expect(new Set(xianyuEmojis.map(([name]) => name)).size).toBe(126);
|
||||
});
|
||||
|
||||
test('uses official CDN assets and renders bracket codes inline', () => {
|
||||
for (const [, url] of xianyuEmojis) {
|
||||
expect(url).toMatch(/^https:\/\/img\.alicdn\.com\//);
|
||||
}
|
||||
const html = renderToStaticMarkup(<>{renderXianyuText('你好[捂脸哭][送花]')}</>);
|
||||
expect(html).toContain('你好');
|
||||
expect(html).toContain('alt="[捂脸哭]"');
|
||||
expect(html).toContain('alt="[送花]"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,516 @@
|
||||
import React from 'react';
|
||||
|
||||
export const xianyuEmojis = [
|
||||
[
|
||||
"尊嘟假嘟",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"鸡哔你",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"谁懂啊",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吗喽",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"功德+1",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"city不city啊",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"激推",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"微笑",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"龇牙",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"流泪",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"尴尬",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"撇嘴",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"破涕为笑",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"捂脸哭",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"害羞",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"感动",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"滴泪",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"暗中观察",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"偷笑",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"ok",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"送花",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"大哭",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"色",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"惊慌",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"惊讶",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"得意",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"睡",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"不好意思",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"托腮",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"发怒",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"难过",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"调皮",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"愉快",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"白眼",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拒绝",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"期待",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"困",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"流汗",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"憨笑",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"耶",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"奋斗",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"咒骂",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"疑问",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"嘘",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"晕",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"开心到模糊",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"衰",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"委屈",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"再见",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"鼓掌",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吐",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"坏笑",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"抠鼻",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"叹气",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"无聊",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"思考",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"呆",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"哇哦",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"飞吻",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"好喜欢",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拜托",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"真棒",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"流鼻血",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"费解",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"秃头",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"嘿哈",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吃土",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"机智",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"举杯",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"握手",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"挥手",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"yeah",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"666",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"棒",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"爱你",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"比心",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"感谢",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拍手",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拉钩",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"没钱",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"小刀",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"不刀",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"同出",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"递钱",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"数钱",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"打call",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"号外",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"包邮",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"求赞",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"非主流",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吃瓜",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"种草",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"佛系",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"超便宜",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拥抱",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"摊手",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"举手",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"蹲",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"跪了",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拜",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"排",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"旺财",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"招财猫",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"酸了",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"鸭鸭",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"方了",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"白菜",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"桃子",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"打包",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"沙发",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"南",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"盯",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"hot",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"new",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"cool",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"1",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"可",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"搬砖",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"菜狗",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"开心面具",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"快递",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"裂开",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"啤酒",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"瑞思拜",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"小丑",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"爱心",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
]
|
||||
] as const;
|
||||
|
||||
export const emojiURL = (url: string) => url;
|
||||
const emojiLookup = new Map<string, string>(xianyuEmojis.map(([name, url]) => [name, url]));
|
||||
|
||||
export const renderXianyuText = (text: string) => text.split(/(\[[^\]]+\])/g).map((part, index) => {
|
||||
const url = part.startsWith('[') ? emojiLookup.get(part.slice(1, -1)) : undefined;
|
||||
return url ? <img key={index} src={url} alt={part} title={part} className="mx-0.5 inline-block h-7 w-7 align-middle" /> : <React.Fragment key={index}>{part}</React.Fragment>;
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8');
|
||||
|
||||
describe('online chat UI contract', () => {
|
||||
test('uses account tabs above a two-column buyer/chat layout', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
expect(chat).toContain('role="tablist"');
|
||||
expect(chat).toContain('grid-cols-[320px_minmax(0,1fr)]');
|
||||
expect(chat).toContain('min-h-0 min-w-0 flex-col overflow-hidden');
|
||||
expect(chat).not.toContain('grid-cols-[320px_minmax(0,1fr)_');
|
||||
expect(chat).toContain('activeAccountID');
|
||||
expect(chat).toContain('activeChatID');
|
||||
});
|
||||
|
||||
test('uses neutral user labels instead of assuming buyer role', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
expect(chat).toContain('用户 ID:');
|
||||
expect(chat).not.toContain('买家 ID:');
|
||||
expect(chat).not.toContain('选择一个买家');
|
||||
});
|
||||
|
||||
test('frontend connects only to the application chat websocket', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
expect(chat).toContain('/api/chat/ws');
|
||||
expect(chat).not.toContain('wss-goofish.dingtalk.com');
|
||||
});
|
||||
|
||||
test('renders peer/self identity and verified media capabilities', () => {
|
||||
const chat = source('components/Chat.tsx');
|
||||
expect(chat).toContain('selectedSession.buyer_avatar_url');
|
||||
expect(chat).toContain('activeAccount?.avatar_url');
|
||||
expect(chat).toContain("message.message_type === 'image'");
|
||||
expect(chat).toContain("message.message_type === 'video'");
|
||||
expect(chat).toContain('sendChatImage');
|
||||
});
|
||||
|
||||
test('sidebar exposes collapse control and chat primary navigation', () => {
|
||||
const sidebar = source('components/Sidebar.tsx');
|
||||
expect(sidebar).toContain("id: 'chat'");
|
||||
expect(sidebar).toContain('onToggleCollapsed');
|
||||
expect(sidebar).toContain('collapsed ? \'w-16\' : \'w-64\'');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
import React, { useState } from 'react';
|
||||
import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react';
|
||||
import { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../types';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from '../services/api';
|
||||
|
||||
interface Props {
|
||||
account: AccountDetail;
|
||||
onClose: () => void;
|
||||
onSaved: (settings: AccountTaskSettings) => void;
|
||||
}
|
||||
|
||||
const Toggle: React.FC<{checked: boolean; onChange: () => void; label: string}> = ({ checked, onChange, label }) => (
|
||||
<button type="button" aria-label={label} aria-pressed={checked} onClick={onChange}
|
||||
className={`relative h-8 w-14 shrink-0 rounded-full transition-colors ${checked ? 'bg-sky-500' : 'bg-slate-300'}`}>
|
||||
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${checked ? 'translate-x-6' : ''}`} />
|
||||
</button>
|
||||
);
|
||||
|
||||
const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved }) => {
|
||||
const [form, setForm] = useState<AccountTaskSettings>({
|
||||
account_id: account.id,
|
||||
auto_rate_enabled: account.auto_rate_enabled === true,
|
||||
rate_content: account.rate_content || '不错的买家,交易愉快',
|
||||
auto_polish_enabled: account.auto_polish_enabled === true,
|
||||
polish_time: account.polish_time || '03:00',
|
||||
last_rate_scan_at: account.last_rate_scan_at,
|
||||
last_polish_date: account.last_polish_date,
|
||||
last_polish_at: account.last_polish_at,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [running, setRunning] = useState<'' | 'auto_rate' | 'auto_polish'>('');
|
||||
const [error, setError] = useState('');
|
||||
const [summary, setSummary] = useState<AccountTaskSummary | null>(null);
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
const stored = await updateAccountTaskSettings(account.id, form);
|
||||
setForm(stored);
|
||||
onSaved(stored);
|
||||
} catch (saveError) {
|
||||
setError(saveError instanceof Error ? saveError.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const run = async (taskType: 'auto_rate' | 'auto_polish') => {
|
||||
setRunning(taskType);
|
||||
setError('');
|
||||
setSummary(null);
|
||||
try {
|
||||
await updateAccountTaskSettings(account.id, form);
|
||||
const result = await runAccountTask(account.id, taskType);
|
||||
const stored = await getAccountTaskSettings(account.id);
|
||||
setSummary(result.summary);
|
||||
setForm(stored);
|
||||
onSaved(stored);
|
||||
} catch (runError) {
|
||||
setError(runError instanceof Error ? runError.message : '任务执行失败');
|
||||
} finally {
|
||||
setRunning('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal-overlay-centered">
|
||||
<div className="modal-container" style={{ maxWidth: '640px' }} role="dialog" aria-modal="true" aria-labelledby="account-task-title">
|
||||
<div className="modal-header">
|
||||
<div>
|
||||
<h3 id="account-task-title" className="text-2xl font-extrabold text-slate-950">账号自动任务</h3>
|
||||
<p className="mt-1 text-sm text-slate-500">{account.nickname || account.remark || account.id}</p>
|
||||
</div>
|
||||
<button type="button" onClick={onClose} className="rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700" aria-label="关闭">
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="modal-body space-y-5">
|
||||
<section className="rounded-2xl border border-slate-200 bg-white p-5">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><MessageSquareQuote className="h-5 w-5" /></div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h4 className="font-black text-slate-900">自动评价</h4>
|
||||
<p className="mt-1 text-xs leading-5 text-slate-500">持续扫描待评价订单,按订单执行;不是每日任务。</p>
|
||||
</div>
|
||||
<Toggle checked={form.auto_rate_enabled} onChange={() => setForm(current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" />
|
||||
</div>
|
||||
<label className="mt-4 block text-xs font-extrabold text-slate-600">统一好评文案</label>
|
||||
<textarea aria-label="统一好评文案" value={form.rate_content} maxLength={500} onChange={event => setForm(current => ({ ...current, rate_content: event.target.value }))}
|
||||
className="mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
|
||||
<div className="mt-3 flex items-center justify-between gap-3">
|
||||
<span className="text-xs text-slate-400">最近扫描:{form.last_rate_scan_at ? new Date(form.last_rate_scan_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</span>
|
||||
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_rate')}
|
||||
className="flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50">
|
||||
{running === 'auto_rate' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}立即评价
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-slate-200 bg-white p-5">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600"><Sparkles className="h-5 w-5" /></div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h4 className="font-black text-slate-900">每日自动擦亮</h4>
|
||||
<p className="mt-1 text-xs leading-5 text-slate-500">每个账号每天最多执行一次,按北京时间判断。</p>
|
||||
</div>
|
||||
<Toggle checked={form.auto_polish_enabled} onChange={() => setForm(current => ({ ...current, auto_polish_enabled: !current.auto_polish_enabled }))} label="每日自动擦亮" />
|
||||
</div>
|
||||
<div className="mt-4 flex items-end justify-between gap-4">
|
||||
<label className="block">
|
||||
<span className="text-xs font-extrabold text-slate-600">每日执行时间</span>
|
||||
<input type="time" value={form.polish_time} onChange={event => setForm(current => ({ ...current, polish_time: event.target.value }))}
|
||||
className="mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400" />
|
||||
</label>
|
||||
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_polish')}
|
||||
className="flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50">
|
||||
{running === 'auto_polish' ? <Loader2 className="h-4 w-4 animate-spin" /> : <CalendarClock className="h-4 w-4" />}立即擦亮
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-3 text-xs text-slate-400">上次完成:{form.last_polish_at ? new Date(form.last_polish_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{summary && (
|
||||
<div className="rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900">
|
||||
本次发现 {summary.found} 项,成功 {summary.success},失败 {summary.failed},跳过 {summary.skipped}。{summary.message || ''}
|
||||
</div>
|
||||
)}
|
||||
{error && <div className="rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">{error}</div>}
|
||||
</div>
|
||||
|
||||
<div className="modal-footer">
|
||||
<div className="flex w-full gap-3">
|
||||
<button type="button" onClick={onClose} disabled={saving || running !== ''}
|
||||
className="flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50">关闭</button>
|
||||
<button type="button" onClick={() => void save()} disabled={saving || running !== '' || (form.auto_rate_enabled && !form.rate_content.trim())}
|
||||
className="ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50">
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}保存
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AccountAutomationModal;
|
||||
@@ -27,7 +27,7 @@ import { shouldUpdateAccountPause } from './accountPause';
|
||||
import {
|
||||
Plus, Power, Edit2, Trash2, QrCode, X, Check, Loader2,
|
||||
RefreshCw, Save, User, Clock, MessageCircle,
|
||||
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell
|
||||
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell, CalendarClock, Sparkles
|
||||
} from 'lucide-react';
|
||||
import { buildAccountLoginInfoUpdate } from './accountEdit';
|
||||
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||
@@ -35,6 +35,7 @@ import { mergeAccountRuntimeStatuses } from './accountRuntimeState';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
import AccountAutomationModal from './AccountAutomationModal';
|
||||
|
||||
type ModalType = 'edit' | 'ai-settings' | null;
|
||||
|
||||
@@ -54,6 +55,7 @@ const AccountList: React.FC = () => {
|
||||
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
|
||||
const [activeModal, setActiveModal] = useState<ModalType>(null);
|
||||
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
|
||||
const [taskAccount, setTaskAccount] = useState<AccountDetail | null>(null);
|
||||
const [longLogin, setLongLogin] = useState({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
|
||||
// 通知渠道绑定(编辑弹窗用)
|
||||
@@ -726,8 +728,8 @@ const AccountList: React.FC = () => {
|
||||
const runtime = runtimePresentation(account);
|
||||
const requiresLogin = account.runtime_state === 'auth_expired' || account.runtime_state === 'verification_required';
|
||||
return (
|
||||
<div key={account.id} className="ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300">
|
||||
<div className="flex items-center gap-5 sm:gap-8 min-w-0">
|
||||
<div key={account.id} className="ios-card rounded-xl p-6 group transition-all duration-300 hover:border-[#0094f7]">
|
||||
<div className="flex min-w-0 items-start gap-5 sm:gap-8">
|
||||
<div className="relative">
|
||||
{account.avatar_url ? (
|
||||
<img
|
||||
@@ -744,8 +746,8 @@ const AccountList: React.FC = () => {
|
||||
{account.runtime_state === 'online' && <Check className="w-3 h-3 text-white" />}
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-3 mb-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2.5 mb-1">
|
||||
<h3 className="text-xl font-extrabold text-gray-900 break-words">{account.nickname || account.remark || `账号 ${account.id.substring(0,6)}...`}</h3>
|
||||
<span className={`px-2.5 py-0.5 rounded-lg text-xs font-bold ${runtime.badge}`}>{runtime.label}</span>
|
||||
{account.ai_enabled && (
|
||||
@@ -753,6 +755,17 @@ const AccountList: React.FC = () => {
|
||||
<Bot className="w-3 h-3" /> AI
|
||||
</span>
|
||||
)}
|
||||
{account.auto_rate_enabled && (
|
||||
<span className="flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700">
|
||||
<MessageCircle className="h-3 w-3" /> 自动评价
|
||||
</span>
|
||||
)}
|
||||
{account.auto_polish_enabled && (
|
||||
<span className="flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700">
|
||||
<Sparkles className="h-3 w-3" /> 每日擦亮
|
||||
</span>
|
||||
)}
|
||||
{account.auto_confirm && <span className="flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700"><Check className="h-3 w-3" /> 自动确认发货</span>}
|
||||
{account.profile_error && (
|
||||
<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"
|
||||
@@ -762,10 +775,11 @@ const AccountList: React.FC = () => {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 font-medium mb-3 space-y-1">
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-4">
|
||||
<div className="text-sm font-medium text-gray-500">
|
||||
<p>{account.remark || account.note || '暂无备注'}</p>
|
||||
<p className="font-mono text-xs text-gray-400">ID: {account.id}</p>
|
||||
</div>
|
||||
</div>
|
||||
{account.runtime_message && account.runtime_state !== 'online' && account.runtime_state !== 'disabled' && (
|
||||
<div className={`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${requiresLogin ? 'text-red-700' : 'text-amber-700'}`}>
|
||||
<AlertCircle className="w-4 h-4 flex-shrink-0" />
|
||||
@@ -781,13 +795,8 @@ const AccountList: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
{account.auto_confirm && <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"><Check className="w-3 h-3"/> 自动确认发货</span>}
|
||||
{account.paused && <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"><Clock className="w-3 h-3"/> 暂停处理中</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 self-end lg:self-auto flex-shrink-0">
|
||||
{account.paused && <span className="flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700"><Clock className="h-3 w-3" /> 暂停处理中</span>}
|
||||
<div className="mt-3 flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
onClick={() => handleRefreshProfile(account)}
|
||||
disabled={refreshingProfileId === account.id}
|
||||
@@ -817,6 +826,13 @@ const AccountList: React.FC = () => {
|
||||
>
|
||||
<Bot className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTaskAccount(account)}
|
||||
className="p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600"
|
||||
title="自动评价与每日擦亮"
|
||||
>
|
||||
<CalendarClock className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleToggle(account.id, account.enabled)}
|
||||
className={`p-3 rounded-xl transition-colors ${account.enabled ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-100'}`}
|
||||
@@ -834,8 +850,11 @@ const AccountList: React.FC = () => {
|
||||
? <Loader2 className="w-5 h-5 animate-spin" />
|
||||
: <Trash2 className="w-5 h-5" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)})}
|
||||
|
||||
{accounts.length === 0 && (
|
||||
@@ -855,6 +874,26 @@ const AccountList: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{taskAccount && createPortal(
|
||||
<AccountAutomationModal
|
||||
account={taskAccount}
|
||||
onClose={() => setTaskAccount(null)}
|
||||
onSaved={settings => {
|
||||
setAccounts(current => current.map(account => account.id === taskAccount.id ? {
|
||||
...account,
|
||||
auto_rate_enabled: settings.auto_rate_enabled,
|
||||
rate_content: settings.rate_content,
|
||||
auto_polish_enabled: settings.auto_polish_enabled,
|
||||
polish_time: settings.polish_time,
|
||||
last_rate_scan_at: settings.last_rate_scan_at,
|
||||
last_polish_date: settings.last_polish_date,
|
||||
last_polish_at: settings.last_polish_at,
|
||||
} : account));
|
||||
}}
|
||||
/>,
|
||||
document.body
|
||||
)}
|
||||
|
||||
{/* 删除账号确认弹窗 */}
|
||||
{deleteDialogAccount && createPortal(
|
||||
<div className="modal-overlay-centered" role="presentation">
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
|
||||
Search, Send, Smile, UserRound, Wifi, WifiOff,
|
||||
} from 'lucide-react';
|
||||
import { AccountDetail, ChatMessage, ChatSession } from '../types';
|
||||
import {
|
||||
getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions,
|
||||
markChatRead, sendChatImage, sendChatMessage,
|
||||
} from '../services/api';
|
||||
import { emojiURL, renderXianyuText, xianyuEmojis } from '../chatEmojis';
|
||||
|
||||
type SessionsByAccount = Record<string, ChatSession[]>;
|
||||
|
||||
const accountStorageKey = 'ydisks.chat.account.v1';
|
||||
|
||||
const formatClock = (value: number): string => {
|
||||
if (!value) return '';
|
||||
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
|
||||
const today = new Date();
|
||||
if (date.toDateString() === today.toDateString()) {
|
||||
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
|
||||
}
|
||||
return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
|
||||
};
|
||||
|
||||
const messageTime = (value: number): string => {
|
||||
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
|
||||
return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
|
||||
};
|
||||
|
||||
const Chat: React.FC = () => {
|
||||
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
|
||||
const [activeAccountID, setActiveAccountID] = useState('');
|
||||
const [sessionsByAccount, setSessionsByAccount] = useState<SessionsByAccount>({});
|
||||
const [activeChatID, setActiveChatID] = useState('');
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
const [unreadOnly, setUnreadOnly] = useState(false);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [messagesLoading, setMessagesLoading] = useState(false);
|
||||
const [olderLoading, setOlderLoading] = useState(false);
|
||||
const [hasOlder, setHasOlder] = useState(false);
|
||||
const [historyCursor, setHistoryCursor] = useState<number | undefined>();
|
||||
const [contactCursors, setContactCursors] = useState<Record<string, number | undefined>>({});
|
||||
const [hasMoreContacts, setHasMoreContacts] = useState<Record<string, boolean>>({});
|
||||
const [contactsLoading, setContactsLoading] = useState(false);
|
||||
const [emojiOpen, setEmojiOpen] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [liveState, setLiveState] = useState<'connecting' | 'online' | 'offline'>('connecting');
|
||||
const activeAccountRef = useRef('');
|
||||
const activeChatRef = useRef('');
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const imageInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const refreshedAccountsRef = useRef(new Set<string>());
|
||||
|
||||
useEffect(() => { activeAccountRef.current = activeAccountID; }, [activeAccountID]);
|
||||
useEffect(() => { activeChatRef.current = activeChatID; }, [activeChatID]);
|
||||
|
||||
const reloadSessions = async (accountID: string) => {
|
||||
const page = await getChatSessionPage(accountID, undefined, undefined, true);
|
||||
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
|
||||
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
|
||||
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
|
||||
return page.sessions;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [details, statuses] = await Promise.all([getAccountDetails(), getAccountRuntimeStatuses()]);
|
||||
const withRuntime = details.map(account => ({
|
||||
...account,
|
||||
runtime_state: statuses[account.id]?.state || (account.enabled ? 'connecting' : 'disabled'),
|
||||
runtime_connected: statuses[account.id]?.connected === true,
|
||||
}));
|
||||
const enabled = withRuntime.filter(account => account.enabled);
|
||||
const sessionPages = await Promise.all(enabled.map(async account => [account.id, await getChatSessionPage(account.id)] as const));
|
||||
if (cancelled) return;
|
||||
setAccounts(enabled);
|
||||
setSessionsByAccount(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.sessions])));
|
||||
setContactCursors(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.next_cursor])));
|
||||
setHasMoreContacts(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.has_more])));
|
||||
const stored = window.localStorage.getItem(accountStorageKey) || '';
|
||||
const first = enabled.some(account => account.id === stored) ? stored : enabled[0]?.id || '';
|
||||
setActiveAccountID(first);
|
||||
} catch (loadError) {
|
||||
if (!cancelled) setError(loadError instanceof Error ? loadError.message : '加载聊天数据失败');
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
};
|
||||
void load();
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
let timer = 0;
|
||||
let controller: AbortController | null = null;
|
||||
const poll = async () => {
|
||||
controller = new AbortController();
|
||||
try {
|
||||
const statuses = await getAccountRuntimeStatuses({ signal: controller.signal, timeoutMs: 10_000 });
|
||||
if (!disposed) {
|
||||
setAccounts(current => current.map(account => ({
|
||||
...account,
|
||||
runtime_state: statuses[account.id]?.state || account.runtime_state,
|
||||
runtime_connected: statuses[account.id]?.connected ?? account.runtime_connected,
|
||||
})));
|
||||
}
|
||||
} catch {
|
||||
// The app WebSocket has its own visible state; a transient status poll
|
||||
// failure does not invalidate the loaded conversations.
|
||||
} finally {
|
||||
if (!disposed) timer = window.setTimeout(poll, 3_000);
|
||||
}
|
||||
};
|
||||
timer = window.setTimeout(poll, 3_000);
|
||||
return () => {
|
||||
disposed = true;
|
||||
window.clearTimeout(timer);
|
||||
controller?.abort();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeAccountID) return;
|
||||
window.localStorage.setItem(accountStorageKey, activeAccountID);
|
||||
const sessions = sessionsByAccount[activeAccountID] || [];
|
||||
setActiveChatID(current => sessions.some(session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
|
||||
}, [activeAccountID, sessionsByAccount]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return;
|
||||
refreshedAccountsRef.current.add(activeAccountID);
|
||||
void reloadSessions(activeAccountID).catch(loadError => {
|
||||
setError(loadError instanceof Error ? loadError.message : '同步会话失败');
|
||||
});
|
||||
}, [activeAccountID]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeAccountID || !activeChatID) {
|
||||
setMessages([]);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setMessagesLoading(true);
|
||||
void Promise.all([
|
||||
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
|
||||
markChatRead(activeAccountID, activeChatID),
|
||||
]).then(([page]) => {
|
||||
setMessages(page.messages);
|
||||
setHasOlder(page.has_more);
|
||||
setHistoryCursor(page.next_cursor);
|
||||
if (page.session) {
|
||||
setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === page.session?.chat_id ? page.session! : session) }));
|
||||
}
|
||||
setSessionsByAccount(current => ({
|
||||
...current,
|
||||
[activeAccountID]: (current[activeAccountID] || []).map(session =>
|
||||
session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session),
|
||||
}));
|
||||
}).catch(loadError => {
|
||||
if (!controller.signal.aborted) setError(loadError instanceof Error ? loadError.message : '加载消息失败');
|
||||
}).finally(() => {
|
||||
if (!controller.signal.aborted) setMessagesLoading(false);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [activeAccountID, activeChatID]);
|
||||
|
||||
const loadOlderMessages = async () => {
|
||||
if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return;
|
||||
const container = scrollRef.current;
|
||||
const previousHeight = container?.scrollHeight || 0;
|
||||
setOlderLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const oldestID = messages[0]?.id;
|
||||
const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID);
|
||||
setMessages(current => {
|
||||
const keys = new Set(current.map(message => message.message_key));
|
||||
return [...page.messages.filter(message => !keys.has(message.message_key)), ...current];
|
||||
});
|
||||
setHasOlder(page.has_more);
|
||||
setHistoryCursor(page.next_cursor);
|
||||
requestAnimationFrame(() => {
|
||||
if (container) container.scrollTop += container.scrollHeight - previousHeight;
|
||||
});
|
||||
} catch (loadError) {
|
||||
setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
|
||||
} finally {
|
||||
setOlderLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
let reconnectTimer = 0;
|
||||
let retry = 0;
|
||||
let socket: WebSocket | null = null;
|
||||
const connect = () => {
|
||||
if (disposed) return;
|
||||
setLiveState('connecting');
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
socket = new WebSocket(`${protocol}//${window.location.host}/api/chat/ws`);
|
||||
socket.onopen = () => { retry = 0; setLiveState('online'); };
|
||||
socket.onmessage = event => {
|
||||
try {
|
||||
const payload = JSON.parse(event.data);
|
||||
const message = payload.message as ChatMessage | undefined;
|
||||
if (!message) return;
|
||||
const accountID = message.account_id;
|
||||
setSessionsByAccount(current => {
|
||||
const rows = current[accountID] || [];
|
||||
const found = rows.some(row => row.chat_id === message.chat_id);
|
||||
if (!found) {
|
||||
void reloadSessions(accountID);
|
||||
return current;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[accountID]: rows.map(row => row.chat_id === message.chat_id ? {
|
||||
...row,
|
||||
last_message: message.content,
|
||||
last_message_at: message.sent_at,
|
||||
unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id)
|
||||
? row.unread_count + 1 : row.unread_count,
|
||||
} : row).sort((a, b) => b.last_message_at - a.last_message_at),
|
||||
};
|
||||
});
|
||||
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
|
||||
setMessages(current => {
|
||||
const index = current.findIndex(item => item.message_key === message.message_key);
|
||||
if (index >= 0) return current.map((item, i) => i === index ? message : item);
|
||||
return [...current, message];
|
||||
});
|
||||
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed non-chat frames and recover from authoritative REST state.
|
||||
}
|
||||
};
|
||||
socket.onclose = () => {
|
||||
if (disposed) return;
|
||||
setLiveState('offline');
|
||||
const delay = Math.min(15_000, 1_000 * 2 ** Math.min(retry++, 4));
|
||||
reconnectTimer = window.setTimeout(connect, delay);
|
||||
};
|
||||
socket.onerror = () => socket?.close();
|
||||
};
|
||||
connect();
|
||||
return () => {
|
||||
disposed = true;
|
||||
window.clearTimeout(reconnectTimer);
|
||||
socket?.close();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const container = scrollRef.current;
|
||||
if (container) container.scrollTop = container.scrollHeight;
|
||||
}, [activeAccountID, activeChatID, messagesLoading]);
|
||||
|
||||
const activeAccount = accounts.find(account => account.id === activeAccountID);
|
||||
const activeSessions = sessionsByAccount[activeAccountID] || [];
|
||||
const selectedSession = activeSessions.find(session => session.chat_id === activeChatID);
|
||||
const filteredSessions = useMemo(() => {
|
||||
const keyword = search.trim().toLowerCase();
|
||||
return activeSessions.filter(session => {
|
||||
if (unreadOnly && session.unread_count <= 0) return false;
|
||||
if (!keyword) return true;
|
||||
return [session.buyer_name, session.buyer_id, session.item_title, session.last_message]
|
||||
.some(value => (value || '').toLowerCase().includes(keyword));
|
||||
});
|
||||
}, [activeSessions, search, unreadOnly]);
|
||||
|
||||
const unreadForAccount = (accountID: string) =>
|
||||
(sessionsByAccount[accountID] || []).reduce((sum, session) => sum + session.unread_count, 0);
|
||||
|
||||
const loadMoreContacts = async () => {
|
||||
if (!activeAccountID || contactsLoading || !hasMoreContacts[activeAccountID]) return;
|
||||
setContactsLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const page = await getChatSessionPage(activeAccountID, contactCursors[activeAccountID], undefined, true);
|
||||
setSessionsByAccount(current => ({ ...current, [activeAccountID]: page.sessions }));
|
||||
setContactCursors(current => ({ ...current, [activeAccountID]: page.next_cursor }));
|
||||
setHasMoreContacts(current => ({ ...current, [activeAccountID]: page.has_more }));
|
||||
} catch (loadError) {
|
||||
setError(loadError instanceof Error ? loadError.message : '加载历史联系人失败');
|
||||
} finally { setContactsLoading(false); }
|
||||
};
|
||||
|
||||
const handleSend = async () => {
|
||||
const text = draft.trim();
|
||||
if (!text || !selectedSession || !activeAccountID || sending) return;
|
||||
setSending(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await sendChatMessage({
|
||||
account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id,
|
||||
buyer_name: selectedSession.buyer_name, item_id: selectedSession.item_id,
|
||||
item_title: selectedSession.item_title, text,
|
||||
});
|
||||
setDraft('');
|
||||
setMessages(current => current.some(item => item.message_key === result.message.message_key)
|
||||
? current.map(item => item.message_key === result.message.message_key ? result.message : item)
|
||||
: [...current, result.message]);
|
||||
} catch (sendError) {
|
||||
setError(sendError instanceof Error ? sendError.message : '消息发送失败');
|
||||
void getChatMessages(activeAccountID, selectedSession.chat_id).then(setMessages);
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImage = async (file?: File) => {
|
||||
if (!file || !selectedSession || !activeAccountID || sending) return;
|
||||
setSending(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await sendChatImage({
|
||||
account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id,
|
||||
buyer_name: selectedSession.buyer_name, buyer_avatar_url: selectedSession.buyer_avatar_url,
|
||||
item_id: selectedSession.item_id, item_title: selectedSession.item_title, image: file,
|
||||
});
|
||||
setMessages(current => current.some(item => item.message_key === result.message.message_key)
|
||||
? current.map(item => item.message_key === result.message.message_key ? result.message : item)
|
||||
: [...current, result.message]);
|
||||
} catch (sendError) {
|
||||
setError(sendError instanceof Error ? sendError.message : '图片发送失败');
|
||||
} finally {
|
||||
setSending(false);
|
||||
if (imageInputRef.current) imageInputRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="flex h-[calc(100vh-4rem)] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-sky-500" /></div>;
|
||||
|
||||
return (
|
||||
<section className="flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-[0_16px_45px_rgba(15,23,42,0.06)]">
|
||||
<header className="border-b border-slate-200 bg-slate-50/70 px-5 pt-4">
|
||||
<div className="mb-3 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-xl font-black tracking-tight text-slate-950">在线聊天</h2>
|
||||
<p className="mt-0.5 text-xs font-medium text-slate-500">复用账号实时连接,消息按账号完全隔离</p>
|
||||
</div>
|
||||
<div className={`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${liveState === 'online' ? 'bg-emerald-50 text-emerald-700' : liveState === 'connecting' ? 'bg-amber-50 text-amber-700' : 'bg-red-50 text-red-700'}`}>
|
||||
{liveState === 'online' ? <Wifi className="h-3.5 w-3.5" /> : <WifiOff className="h-3.5 w-3.5" />}
|
||||
{liveState === 'online' ? '实时同步中' : liveState === 'connecting' ? '正在连接' : '连接已断开'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-1 overflow-x-auto pb-0" role="tablist" aria-label="聊天账号">
|
||||
{accounts.map(account => {
|
||||
const active = account.id === activeAccountID;
|
||||
const unread = unreadForAccount(account.id);
|
||||
const online = account.runtime_state === 'online';
|
||||
return (
|
||||
<button key={account.id} type="button" role="tab" aria-selected={active} onClick={() => setActiveAccountID(account.id)}
|
||||
className={`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${active ? 'border-sky-500 text-sky-700' : 'border-transparent text-slate-500 hover:text-slate-900'}`}>
|
||||
<span className={`h-2 w-2 rounded-full ${online ? 'bg-emerald-500' : 'bg-slate-300'}`} />
|
||||
<span className="max-w-36 truncate">{account.nickname || account.remark || account.id}</span>
|
||||
{unread > 0 && <span className="min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white">{unread > 99 ? '99+' : unread}</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{accounts.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center text-center">
|
||||
<MessageCircleMore className="h-12 w-12 text-slate-300" />
|
||||
<h3 className="mt-4 font-black text-slate-800">暂无启用账号</h3>
|
||||
<p className="mt-1 text-sm text-slate-500">先在账号管理中启用账号,聊天会话会自动出现。</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]">
|
||||
<aside className="flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40">
|
||||
<div className="space-y-3 border-b border-slate-200 p-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
|
||||
<input value={search} onChange={event => setSearch(event.target.value)} placeholder="搜索用户、商品或消息"
|
||||
className="h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<button type="button" onClick={() => setUnreadOnly(value => !value)}
|
||||
className={`rounded-lg px-2.5 py-1.5 text-xs font-bold ${unreadOnly ? 'bg-sky-100 text-sky-700' : 'text-slate-500 hover:bg-slate-100'}`}>
|
||||
{unreadOnly ? '只看未读' : '全部会话'}
|
||||
</button>
|
||||
<button type="button" title="刷新会话" onClick={() => void reloadSessions(activeAccountID)} className="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
{filteredSessions.map(session => (
|
||||
<button key={session.chat_id} type="button" onClick={() => setActiveChatID(session.chat_id)}
|
||||
className={`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-[inset_3px_0_0_#0ea5e9]' : 'hover:bg-white/80'}`}>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500">
|
||||
{session.buyer_avatar_url ? <img src={session.buyer_avatar_url} alt="" className="h-full w-full object-cover" /> : <UserRound className="h-5 w-5" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="truncate text-sm font-extrabold text-slate-900">{session.buyer_name || `用户 ${session.buyer_id}`}</span>
|
||||
<span className="ml-auto shrink-0 text-[10px] font-medium text-slate-400">{formatClock(session.last_message_at)}</span>
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<span className="truncate text-xs text-slate-500">{session.last_message || '暂无消息'}</span>
|
||||
{session.unread_count > 0 && <span className="ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white">{session.unread_count}</span>}
|
||||
</div>
|
||||
{session.item_title && <div className="mt-1.5 truncate text-[10px] font-medium text-sky-700">商品 · {session.item_title}</div>}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
{filteredSessions.length === 0 && <div className="px-6 py-16 text-center text-sm text-slate-400">当前账号暂无匹配会话</div>}
|
||||
{hasMoreContacts[activeAccountID] && !search && !unreadOnly && <div className="flex justify-center p-4">
|
||||
<button type="button" onClick={() => void loadMoreContacts()} disabled={contactsLoading}
|
||||
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
|
||||
{contactsLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{contactsLoading ? '正在加载' : '加载更多历史联系人'}
|
||||
</button>
|
||||
</div>}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="flex min-h-0 min-w-0 flex-col overflow-hidden bg-[#f7f8fa]">
|
||||
{selectedSession ? (
|
||||
<>
|
||||
<div className="flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-black text-slate-950">{selectedSession.buyer_name || selectedSession.buyer_id}</div>
|
||||
<div className="mt-0.5 truncate text-xs text-slate-500">用户 ID:{selectedSession.buyer_id}</div>
|
||||
</div>
|
||||
<span className={`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${activeAccount?.runtime_state === 'online' ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500'}`}>
|
||||
{activeAccount?.runtime_state === 'online' ? '账号在线' : '账号离线'}
|
||||
</span>
|
||||
</div>
|
||||
<div ref={scrollRef} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
|
||||
{messagesLoading ? <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-sky-500" /></div> : <>
|
||||
{hasOlder && <div className="flex justify-center pb-1">
|
||||
<button type="button" onClick={() => void loadOlderMessages()} disabled={olderLoading}
|
||||
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
|
||||
{olderLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{olderLoading ? '正在加载' : '加载更早消息'}
|
||||
</button>
|
||||
</div>}
|
||||
{messages.map(message => {
|
||||
const outgoing = message.direction === 'outgoing';
|
||||
return (
|
||||
<div key={message.message_key} className={`flex items-end gap-2.5 ${outgoing ? 'justify-end' : 'justify-start'}`}>
|
||||
{!outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white">
|
||||
{selectedSession.buyer_avatar_url ? <img src={selectedSession.buyer_avatar_url} alt={selectedSession.buyer_name || '用户'} className="h-full w-full object-cover" /> : <UserRound className="m-2 h-5 w-5 text-slate-500" />}
|
||||
</div>}
|
||||
<div className={`max-w-[72%] ${outgoing ? 'items-end' : 'items-start'} flex flex-col`}>
|
||||
<div className={`mb-1 px-1 text-[10px] font-semibold text-slate-400`}>{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}</div>
|
||||
{message.message_type === 'image' ? (
|
||||
<a href={message.content} target="_blank" rel="noreferrer" className={`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${outgoing ? 'rounded-br-md border-sky-200' : 'rounded-bl-md border-slate-200'}`}>
|
||||
<img src={message.content} alt="聊天图片" className="max-h-80 max-w-full rounded-xl object-contain" />
|
||||
</a>
|
||||
) : message.message_type === 'video' ? (
|
||||
<video src={message.content} controls preload="metadata" className="max-h-80 max-w-full rounded-2xl bg-black" />
|
||||
) : (
|
||||
<div className={`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${outgoing ? 'rounded-br-md bg-sky-500 text-white' : 'rounded-bl-md border border-slate-200 bg-white text-slate-800'}`}>{renderXianyuText(message.content)}</div>
|
||||
)}
|
||||
<div className="mt-1 flex items-center gap-1 text-[10px] text-slate-400">
|
||||
{messageTime(message.sent_at)}
|
||||
{outgoing && (message.status === 'failed' ? <AlertCircle className="h-3 w-3 text-red-500" /> : message.status === 'sent' ? <CheckCheck className="h-3 w-3 text-sky-500" /> : <Check className="h-3 w-3" />)}
|
||||
</div>
|
||||
</div>
|
||||
{outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white">
|
||||
{activeAccount?.avatar_url ? <img src={activeAccount.avatar_url} alt="我" className="h-full w-full object-cover" /> : <UserRound className="m-2 h-5 w-5 text-sky-600" />}
|
||||
</div>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>}
|
||||
</div>
|
||||
{error && <div className="border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700">{error}</div>}
|
||||
<div className="relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-[0_-8px_24px_rgba(15,23,42,0.04)]">
|
||||
<div className="mb-2 flex items-center gap-1">
|
||||
<div className="relative">
|
||||
<button type="button" onClick={() => setEmojiOpen(value => !value)} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="闲鱼表情"><Smile className="h-5 w-5" /></button>
|
||||
{emojiOpen && <div className="absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl">
|
||||
<div className="mb-2 text-xs font-bold text-slate-500">全部表情</div>
|
||||
<div className="grid max-h-72 grid-cols-8 gap-1 overflow-y-auto">
|
||||
{xianyuEmojis.map(([name,file]) => <button key={name} type="button" title={`[${name}]`} onClick={() => { setDraft(value => value + `[${name}]`); setEmojiOpen(false); }} className="flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100"><img src={emojiURL(file)} alt={`[${name}]`} className="h-8 w-8 object-contain" /></button>)}
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
<input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={event => void handleImage(event.target.files?.[0])} />
|
||||
<button type="button" onClick={() => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'}
|
||||
className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
|
||||
</div>
|
||||
<div className="flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100">
|
||||
<textarea value={draft} onChange={event => setDraft(event.target.value)} rows={2} maxLength={2000}
|
||||
onKeyDown={event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void handleSend(); } }}
|
||||
disabled={activeAccount?.runtime_state !== 'online'} placeholder={activeAccount?.runtime_state === 'online' ? '输入消息,Enter 发送,Shift + Enter 换行' : '账号离线,暂时无法发送'}
|
||||
className="max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed" />
|
||||
<button type="button" onClick={() => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'}
|
||||
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
|
||||
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex flex-1 flex-col items-center justify-center text-center">
|
||||
<MessageCircleMore className="h-12 w-12 text-slate-300" />
|
||||
<h3 className="mt-4 font-black text-slate-700">选择一个用户开始聊天</h3>
|
||||
<p className="mt-1 text-sm text-slate-400">该账号的新消息会实时出现在左侧列表。</p>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default Chat;
|
||||
@@ -1,69 +1,95 @@
|
||||
import React from 'react';
|
||||
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, Bell } from 'lucide-react';
|
||||
import {
|
||||
Bell, Box, ChevronLeft, ChevronRight, CreditCard, LayoutDashboard,
|
||||
LogOut, MessageCircleMore, Settings, ShoppingBag, Users, Zap,
|
||||
} from 'lucide-react';
|
||||
import { YdisksBrandIcon } from './YdisksLogo';
|
||||
|
||||
interface SidebarProps {
|
||||
activeTab: string;
|
||||
isAdmin?: boolean;
|
||||
collapsed: boolean;
|
||||
onToggleCollapsed: () => void;
|
||||
onNavigate: (tab: string) => void;
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
const Sidebar: React.FC<SidebarProps> = ({ activeTab, isAdmin = false, onNavigate, onLogout }) => {
|
||||
const Sidebar: React.FC<SidebarProps> = ({
|
||||
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout,
|
||||
}) => {
|
||||
const menuItems = [
|
||||
{ id: 'dashboard', icon: LayoutDashboard, label: '仪表盘' },
|
||||
{ id: 'accounts', icon: Users, label: '账号管理' },
|
||||
{ id: 'orders', icon: ShoppingBag, label: '订单管理' },
|
||||
{ id: 'chat', icon: MessageCircleMore, label: '在线聊天' },
|
||||
{ id: 'cards', icon: CreditCard, label: '卡密库存' },
|
||||
{ id: 'items', icon: Box, label: '商品列表' },
|
||||
{ id: 'orders', icon: ShoppingBag, label: '订单管理' },
|
||||
{ id: 'rules', icon: Zap, label: '自动化规则' },
|
||||
{ id: 'notifications', icon: Bell, label: '通知设置' },
|
||||
...(isAdmin ? [{ id: 'settings', icon: Settings, label: '系统与AI' }] : []),
|
||||
];
|
||||
|
||||
return (
|
||||
<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)]">
|
||||
<div className="p-6">
|
||||
<div className="flex items-center gap-3 mb-12 px-2">
|
||||
<div className="shrink-0">
|
||||
<YdisksBrandIcon sizeClass="w-10 h-10" />
|
||||
<aside className={`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-[4px_0_24px_rgba(15,23,42,0.035)] backdrop-blur-xl transition-[width] duration-300 ${collapsed ? 'w-16' : 'w-64'}`}>
|
||||
<div className={`flex h-20 items-center border-b border-slate-100 ${collapsed ? 'justify-center px-2' : 'gap-3 px-5'}`}>
|
||||
<YdisksBrandIcon sizeClass="h-10 w-10" />
|
||||
{!collapsed && (
|
||||
<div className="min-w-0 leading-tight">
|
||||
<div className="truncate text-base font-black tracking-tight text-slate-950">Ydisks 闲鱼助手</div>
|
||||
<div className="mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600">Operations</div>
|
||||
</div>
|
||||
<h1 className="text-xl font-extrabold tracking-tight text-gray-900">Ydisks闲鱼助手 <span className="text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1">PRO</span></h1>
|
||||
</div>
|
||||
|
||||
<nav className="space-y-2">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = activeTab === item.id;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => onNavigate(item.id)}
|
||||
className={`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${
|
||||
isActive
|
||||
? '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'
|
||||
}`}
|
||||
>
|
||||
<Icon className={`w-5 h-5 transition-colors ${isActive ? 'text-white' : 'text-gray-400 group-hover:text-gray-600'}`} />
|
||||
<span className="text-sm tracking-wide">{item.label}</span>
|
||||
{isActive && <Sparkles className="w-4 h-4 absolute right-3 text-white/30 animate-pulse" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-6 border-t border-gray-50">
|
||||
<button
|
||||
onClick={onLogout}
|
||||
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"
|
||||
<nav className={`flex-1 space-y-1.5 overflow-y-auto py-5 ${collapsed ? 'px-2' : 'px-3'}`} aria-label="主导航">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const active = activeTab === item.id;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
title={collapsed ? item.label : undefined}
|
||||
aria-label={item.label}
|
||||
aria-current={active ? 'page' : undefined}
|
||||
onClick={() => onNavigate(item.id)}
|
||||
className={`group relative flex h-11 w-full items-center rounded-xl transition-colors ${collapsed ? 'justify-center' : 'gap-3 px-3.5'} ${
|
||||
active
|
||||
? 'bg-sky-500 text-white shadow-[0_8px_18px_rgba(14,165,233,0.2)]'
|
||||
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
|
||||
}`}
|
||||
>
|
||||
<Icon className={`h-[19px] w-[19px] shrink-0 ${active ? 'text-white' : 'text-slate-400 group-hover:text-slate-700'}`} />
|
||||
{!collapsed && <span className="truncate text-sm font-bold">{item.label}</span>}
|
||||
{active && !collapsed && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-white/90" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className={`space-y-2 border-t border-slate-100 p-2 ${collapsed ? '' : 'p-3'}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleCollapsed}
|
||||
title={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
|
||||
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
|
||||
>
|
||||
<LogOut className="w-5 h-5" />
|
||||
<span className="text-sm">退出登录</span>
|
||||
{collapsed ? <ChevronRight className="h-5 w-5" /> : <ChevronLeft className="h-5 w-5" />}
|
||||
{!collapsed && <span className="text-sm font-bold">收起侧边栏</span>}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onLogout}
|
||||
title={collapsed ? '退出登录' : undefined}
|
||||
aria-label="退出登录"
|
||||
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
|
||||
>
|
||||
<LogOut className="h-5 w-5" />
|
||||
{!collapsed && <span className="text-sm font-bold">退出登录</span>}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { readSidebarCollapsed, writeSidebarCollapsed } from './sidebarState';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('sidebar persistence', () => {
|
||||
test('defaults to expanded and persists both states', () => {
|
||||
const values = new Map<string, string>();
|
||||
vi.stubGlobal('window', { localStorage: {
|
||||
getItem: (key: string) => values.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => values.set(key, value),
|
||||
}});
|
||||
expect(readSidebarCollapsed()).toBe(false);
|
||||
writeSidebarCollapsed(true);
|
||||
expect(readSidebarCollapsed()).toBe(true);
|
||||
writeSidebarCollapsed(false);
|
||||
expect(readSidebarCollapsed()).toBe(false);
|
||||
});
|
||||
|
||||
test('storage failures safely fall back to expanded', () => {
|
||||
vi.stubGlobal('window', { localStorage: {
|
||||
getItem: () => { throw new Error('blocked'); },
|
||||
setItem: () => { throw new Error('blocked'); },
|
||||
}});
|
||||
expect(readSidebarCollapsed()).toBe(false);
|
||||
expect(() => writeSidebarCollapsed(true)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
const storageKey = 'ydisks.sidebar.v1';
|
||||
|
||||
export const readSidebarCollapsed = (): boolean => {
|
||||
try {
|
||||
return window.localStorage.getItem(storageKey) === 'collapsed';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const writeSidebarCollapsed = (collapsed: boolean): void => {
|
||||
try {
|
||||
window.localStorage.setItem(storageKey, collapsed ? 'collapsed' : 'expanded');
|
||||
} catch {
|
||||
// Storage can be unavailable in hardened browsers; the in-memory state
|
||||
// remains fully functional.
|
||||
}
|
||||
};
|
||||
@@ -33,6 +33,12 @@ import {
|
||||
updateNotificationChannel,
|
||||
updateSystemSettings,
|
||||
updateShippingRule,
|
||||
getChatSessions,
|
||||
getChatMessages,
|
||||
sendChatMessage,
|
||||
markChatRead,
|
||||
updateAccountTaskSettings,
|
||||
runAccountTask,
|
||||
} from './api';
|
||||
|
||||
afterEach(() => {
|
||||
@@ -49,6 +55,36 @@ test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ theme_color: 'blue', renewal_log_retention_days: 15 });
|
||||
});
|
||||
|
||||
test('chat APIs preserve account and conversation scope', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ sessions: [{ account_id: 'a1', chat_id: 'c1' }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ messages: [{ account_id: 'a1', chat_id: 'c1', id: 1 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await getChatSessions('a1');
|
||||
await getChatMessages('a1', 'c1', 9);
|
||||
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' });
|
||||
await markChatRead('a1', 'c1');
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/chat/sessions?account_id=a1');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/chat/messages?account_id=a1&chat_id=c1&before_id=9');
|
||||
expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' });
|
||||
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' });
|
||||
});
|
||||
|
||||
test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateAccountTaskSettings('a1', {
|
||||
account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快',
|
||||
auto_polish_enabled: true, polish_time: '03:00',
|
||||
});
|
||||
await runAccountTask('a1', 'auto_rate');
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/account-tasks/a1');
|
||||
expect(fetchMock.mock.calls[0][1].method).toBe('PUT');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/account-tasks/a1/run');
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ task_type: 'auto_rate' });
|
||||
});
|
||||
|
||||
test('getItemPublishBatches unwraps persisted batch list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType
|
||||
, AccountTaskSettings, AccountTaskSummary, ChatSession, ChatMessage
|
||||
} from '../types';
|
||||
import { formatLocalDate } from '../dateRange';
|
||||
|
||||
@@ -82,9 +83,70 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis
|
||||
avatar_url: accountAvatarURL(item, avatarVersion),
|
||||
profile_error: item.profile_error || '',
|
||||
ai_enabled: false,
|
||||
auto_rate_enabled: item.auto_rate_enabled === true || item.auto_rate_enabled === 1,
|
||||
rate_content: item.rate_content || '不错的买家,交易愉快',
|
||||
auto_polish_enabled: item.auto_polish_enabled === true || item.auto_polish_enabled === 1,
|
||||
polish_time: item.polish_time || '03:00',
|
||||
last_rate_scan_at: Number(item.last_rate_scan_at || 0),
|
||||
last_polish_date: item.last_polish_date || '',
|
||||
last_polish_at: Number(item.last_polish_at || 0),
|
||||
}));
|
||||
};
|
||||
|
||||
export const getAccountTaskSettings = async (id: string): Promise<AccountTaskSettings> =>
|
||||
get(`/api/account-tasks/${id}`);
|
||||
|
||||
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings): Promise<AccountTaskSettings> =>
|
||||
put(`/api/account-tasks/${id}`, settings);
|
||||
|
||||
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish'): Promise<{success: boolean; summary: AccountTaskSummary}> =>
|
||||
post(`/api/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000 });
|
||||
|
||||
export interface ChatSessionPage { sessions: ChatSession[]; has_more: boolean; next_cursor?: number }
|
||||
|
||||
export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise<ChatSessionPage> => {
|
||||
const result = await get<ChatSessionPage>('/api/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined },
|
||||
refresh ? { timeoutMs: 60_000, ...options } : options);
|
||||
return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor };
|
||||
};
|
||||
|
||||
export const getChatSessions = async (accountId: string, options?: RequestControlOptions): Promise<ChatSession[]> =>
|
||||
(await getChatSessionPage(accountId, undefined, options)).sessions;
|
||||
|
||||
export interface ChatMessagePage {
|
||||
messages: ChatMessage[];
|
||||
has_more: boolean;
|
||||
next_cursor?: number;
|
||||
session?: ChatSession;
|
||||
}
|
||||
|
||||
export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessagePage> => {
|
||||
const result = await get<ChatMessagePage>('/api/chat/messages', {
|
||||
account_id: accountId, chat_id: chatId, cursor, before_id: beforeId,
|
||||
}, options);
|
||||
return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session };
|
||||
};
|
||||
|
||||
export const getChatMessages = async (accountId: string, chatId: string, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessage[]> =>
|
||||
(await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages;
|
||||
|
||||
export const sendChatMessage = async (input: {
|
||||
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
|
||||
item_id?: string; item_title?: string; text: string;
|
||||
}): Promise<{message: ChatMessage}> => post('/api/chat/messages', input);
|
||||
|
||||
export const sendChatImage = async (input: {
|
||||
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
|
||||
buyer_avatar_url?: string; item_id?: string; item_title?: string; image: File;
|
||||
}): Promise<{message: ChatMessage}> => {
|
||||
const form = new FormData();
|
||||
Object.entries(input).forEach(([key, value]) => form.append(key, value));
|
||||
return postForm('/api/chat/images', form, { timeoutMs: 120_000 });
|
||||
};
|
||||
|
||||
export const markChatRead = async (accountId: string, chatId: string): Promise<ApiResponse> =>
|
||||
post('/api/chat/read', { account_id: accountId, chat_id: chatId });
|
||||
|
||||
export interface AccountRuntimeStatus {
|
||||
state: NonNullable<AccountDetail['runtime_state']>;
|
||||
message?: string;
|
||||
|
||||
@@ -55,6 +55,61 @@ export interface AccountDetail {
|
||||
max_discount_amount?: number;
|
||||
max_bargain_rounds?: number;
|
||||
custom_prompts?: string;
|
||||
// 账号级计划任务
|
||||
auto_rate_enabled?: boolean;
|
||||
rate_content?: string;
|
||||
auto_polish_enabled?: boolean;
|
||||
polish_time?: string;
|
||||
last_rate_scan_at?: number;
|
||||
last_polish_date?: string;
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
export interface AccountTaskSettings {
|
||||
account_id: string;
|
||||
auto_rate_enabled: boolean;
|
||||
rate_content: string;
|
||||
auto_polish_enabled: boolean;
|
||||
polish_time: string;
|
||||
last_rate_scan_at?: number;
|
||||
last_polish_date?: string;
|
||||
last_polish_at?: number;
|
||||
}
|
||||
|
||||
export interface AccountTaskSummary {
|
||||
task_type: 'auto_rate' | 'auto_polish';
|
||||
found: number;
|
||||
success: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ChatSession {
|
||||
account_id: string;
|
||||
chat_id: string;
|
||||
buyer_id: string;
|
||||
buyer_name: string;
|
||||
buyer_avatar_url?: string;
|
||||
item_id?: string;
|
||||
item_title?: string;
|
||||
last_message: string;
|
||||
last_message_at: number;
|
||||
unread_count: number;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: number;
|
||||
account_id: string;
|
||||
chat_id: string;
|
||||
message_key: string;
|
||||
direction: 'incoming' | 'outgoing';
|
||||
sender_id: string;
|
||||
sender_name: string;
|
||||
message_type: 'text' | 'image' | 'video';
|
||||
content: string;
|
||||
status: 'received' | 'sending' | 'sent' | 'failed';
|
||||
sent_at: number;
|
||||
}
|
||||
|
||||
// Orders
|
||||
|
||||
@@ -12,6 +12,7 @@ export default defineConfig({
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
// 代理其他后端请求
|
||||
'/cookies': {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/renewal"
|
||||
@@ -65,6 +66,7 @@ type Adapter struct {
|
||||
cooldown *renewal.CooldownManager
|
||||
captchaReq tokenCaptchaRequester
|
||||
orderMTop orderDetailClient
|
||||
chat *chat.Service
|
||||
|
||||
orderFetchMu sync.Mutex
|
||||
lastOrderFetch time.Time
|
||||
@@ -126,9 +128,37 @@ func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaR
|
||||
// SetOrderDetailClient 覆盖纯 Go 订单详情客户端,便于测试隔离网络。
|
||||
func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
|
||||
|
||||
// SetChatService installs the user-facing chat side channel. It persists and
|
||||
// broadcasts messages without changing the automatic reply path.
|
||||
func (a *Adapter) SetChatService(service *chat.Service) { a.chat = service }
|
||||
|
||||
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
|
||||
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
|
||||
return nil
|
||||
func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMessage) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// Xianyu echoes messages sent by this account back over the same WS. Those
|
||||
// sends are already captured by HandleOutgoingChatMessage; recording the
|
||||
// echo as incoming would put our own bubble on the buyer side and duplicate it.
|
||||
if strings.TrimSuffix(message.SenderUserID, "@goofish") == strings.TrimSuffix(message.AccountID, "@goofish") {
|
||||
return nil
|
||||
}
|
||||
_, _, err := a.chat.RecordIncoming(ctx, chat.Incoming{
|
||||
AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID,
|
||||
BuyerName: message.SenderName, Text: message.Text, ItemID: message.ItemID, Raw: message.Raw,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// HandleOutgoingChatMessage records successful manual/automatic text sends as
|
||||
// a side channel; it never participates in platform delivery.
|
||||
func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.OutgoingChatMessage) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
_, err := a.chat.RecordOutgoingSent(ctx, db.ChatSession{CookieID: message.AccountID, ChatID: message.ChatID,
|
||||
BuyerID: message.BuyerID}, message.MessageKey, message.Text)
|
||||
return err
|
||||
}
|
||||
|
||||
// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
const (
|
||||
TaskAutoRate = "auto_rate"
|
||||
TaskAutoPolish = "auto_polish"
|
||||
polishItemPageSize = 20
|
||||
polishItemMaxPages = 20
|
||||
)
|
||||
|
||||
type AccountTaskClient interface {
|
||||
FetchPendingRateOrders(ctx context.Context, cookiesStr string, page, pageSize int) (*mtop.PendingRateResult, error)
|
||||
RateBuyer(ctx context.Context, cookiesStr, tradeID, feedback string) (*mtop.AccountTaskResult, error)
|
||||
FetchAllItems(ctx context.Context, cookiesStr string, pageSize, maxPages int) (*mtop.ItemListResult, error)
|
||||
PolishItem(ctx context.Context, cookiesStr, itemID string) (*mtop.AccountTaskResult, error)
|
||||
}
|
||||
|
||||
type AccountTaskSummary struct {
|
||||
TaskType string `json:"task_type"`
|
||||
Found int `json:"found"`
|
||||
Success int `json:"success"`
|
||||
Failed int `json:"failed"`
|
||||
Skipped int `json:"skipped"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Center) RunAccountTask(ctx context.Context, accountID, taskType string) (AccountTaskSummary, error) {
|
||||
allowed, err := c.accountAutomationAllowed(ctx, accountID)
|
||||
if err != nil {
|
||||
return AccountTaskSummary{TaskType: taskType}, err
|
||||
}
|
||||
if !allowed {
|
||||
return AccountTaskSummary{TaskType: taskType}, fmt.Errorf("账号已停用或暂停,无法执行任务")
|
||||
}
|
||||
settings, err := c.store.AccountTasks.Get(ctx, accountID)
|
||||
if err != nil {
|
||||
return AccountTaskSummary{TaskType: taskType}, err
|
||||
}
|
||||
switch taskType {
|
||||
case TaskAutoRate:
|
||||
return c.runAutoRate(ctx, settings)
|
||||
case TaskAutoPolish:
|
||||
return c.runAutoPolish(ctx, settings, beijingNow(), true)
|
||||
default:
|
||||
return AccountTaskSummary{TaskType: taskType}, fmt.Errorf("不支持的账号任务: %s", taskType)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Center) scanAccountTasks(ctx context.Context) {
|
||||
if c.accountTasks == nil || c.store.AccountTasks == nil {
|
||||
return
|
||||
}
|
||||
settings, err := c.store.AccountTasks.Enabled(ctx)
|
||||
if err != nil {
|
||||
c.logger.Warn("扫描账号任务配置失败", "err", err)
|
||||
return
|
||||
}
|
||||
now := beijingNow()
|
||||
for _, setting := range settings {
|
||||
allowed, err := c.accountAutomationAllowed(ctx, setting.CookieID)
|
||||
if err != nil || !allowed {
|
||||
continue
|
||||
}
|
||||
if setting.AutoRateEnabled {
|
||||
if _, err := c.runAutoRate(ctx, setting); err != nil {
|
||||
c.logger.Warn("自动评价扫描失败", "account", setting.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
if setting.AutoPolishEnabled && polishDue(setting, now) {
|
||||
if _, err := c.runAutoPolish(ctx, setting, now, false); err != nil {
|
||||
c.logger.Warn("每日擦亮失败", "account", setting.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Center) runAutoRate(ctx context.Context, settings db.AccountTaskSettings) (AccountTaskSummary, error) {
|
||||
summary := AccountTaskSummary{TaskType: TaskAutoRate}
|
||||
if c.accountTasks == nil {
|
||||
return summary, fmt.Errorf("自动评价客户端未初始化")
|
||||
}
|
||||
cookies, err := c.store.Cookies.GetValue(ctx, settings.CookieID)
|
||||
if err != nil {
|
||||
return summary, err
|
||||
}
|
||||
current := cookies
|
||||
var orders []mtop.PendingRateOrder
|
||||
for page := 1; page <= 20; page++ {
|
||||
pending, err := c.accountTasks.FetchPendingRateOrders(ctx, current, page, 50)
|
||||
if err != nil {
|
||||
return summary, err
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, pending.UpdatedCookies)
|
||||
orders = append(orders, pending.Orders...)
|
||||
if len(pending.Orders) < 50 {
|
||||
break
|
||||
}
|
||||
}
|
||||
summary.Found = len(orders)
|
||||
for _, order := range orders {
|
||||
runKey := "rate:" + settings.CookieID + ":" + order.TradeID
|
||||
claimed, err := c.store.AccountTasks.ClaimRun(ctx, db.AccountTaskRun{RunKey: runKey, CookieID: settings.CookieID,
|
||||
TaskType: TaskAutoRate, TargetID: order.TradeID}, time.Now().UTC().Unix())
|
||||
if err != nil {
|
||||
return summary, err
|
||||
}
|
||||
if !claimed {
|
||||
summary.Skipped++
|
||||
continue
|
||||
}
|
||||
result, rateErr := c.accountTasks.RateBuyer(ctx, current, order.TradeID, settings.RateContent)
|
||||
if rateErr != nil || result == nil || !result.Success {
|
||||
message := errorString(rateErr)
|
||||
if result != nil && result.Message != "" {
|
||||
message = result.Message
|
||||
}
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, message, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
summary.Failed++
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "success", 1, 0, "", 0)
|
||||
summary.Success++
|
||||
}
|
||||
_ = c.store.AccountTasks.MarkRateScan(ctx, settings.CookieID, time.Now().UTC().Unix())
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (c *Center) runAutoPolish(ctx context.Context, settings db.AccountTaskSettings, now time.Time, manual bool) (AccountTaskSummary, error) {
|
||||
summary := AccountTaskSummary{TaskType: TaskAutoPolish}
|
||||
if c.accountTasks == nil {
|
||||
return summary, fmt.Errorf("擦亮客户端未初始化")
|
||||
}
|
||||
date := now.Format("2006-01-02")
|
||||
runKey := "polish:" + settings.CookieID + ":" + date
|
||||
run := db.AccountTaskRun{RunKey: runKey, CookieID: settings.CookieID, TaskType: TaskAutoPolish, RunDate: date}
|
||||
var claimed bool
|
||||
var err error
|
||||
if manual {
|
||||
claimed, err = c.store.AccountTasks.ClaimRunImmediately(ctx, run, time.Now().UTC().Unix())
|
||||
} else {
|
||||
claimed, err = c.store.AccountTasks.ClaimRun(ctx, run, time.Now().UTC().Unix())
|
||||
}
|
||||
if err != nil || !claimed {
|
||||
if !claimed && err == nil {
|
||||
summary.Skipped = 1
|
||||
summary.Message = "今天已经执行过擦亮"
|
||||
}
|
||||
return summary, err
|
||||
}
|
||||
cookies, err := c.store.Cookies.GetValue(ctx, settings.CookieID)
|
||||
if err != nil {
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
return summary, err
|
||||
}
|
||||
items, err := c.accountTasks.FetchAllItems(ctx, cookies, polishItemPageSize, polishItemMaxPages)
|
||||
if err != nil {
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
return summary, err
|
||||
}
|
||||
current := c.persistTaskCookies(ctx, settings.CookieID, cookies, items.UpdatedCookies)
|
||||
summary.Found = len(items.Items)
|
||||
var lastError string
|
||||
for _, item := range items.Items {
|
||||
result, polishErr := c.accountTasks.PolishItem(ctx, current, item.ID)
|
||||
if polishErr != nil || result == nil || !result.Success {
|
||||
summary.Failed++
|
||||
lastError = errorString(polishErr)
|
||||
if result != nil && result.Message != "" {
|
||||
lastError = result.Message
|
||||
}
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
summary.Success++
|
||||
}
|
||||
status, retryAt := "success", int64(0)
|
||||
if summary.Failed > 0 {
|
||||
status, retryAt = "failed", time.Now().UTC().Add(10*time.Minute).Unix()
|
||||
} else {
|
||||
_ = c.store.AccountTasks.MarkPolished(ctx, settings.CookieID, date, time.Now().UTC().Unix())
|
||||
}
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, status, summary.Success, summary.Failed, lastError, retryAt)
|
||||
if summary.Failed > 0 {
|
||||
return summary, fmt.Errorf("%d 个商品擦亮失败: %s", summary.Failed, lastError)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (c *Center) persistTaskCookies(ctx context.Context, accountID, oldValue, newValue string) string {
|
||||
newValue = strings.TrimSpace(newValue)
|
||||
if newValue == "" || newValue == oldValue {
|
||||
return oldValue
|
||||
}
|
||||
if err := c.store.Cookies.UpdateValueExisting(ctx, accountID, newValue); err != nil {
|
||||
c.logger.Warn("保存账号任务响应 Cookie 失败", "account", accountID, "err", err)
|
||||
return oldValue
|
||||
}
|
||||
if c.senders != nil {
|
||||
if sender, ok := c.senders.Sender(accountID); ok && sender != nil {
|
||||
sender.UpdateCookie(newValue)
|
||||
}
|
||||
}
|
||||
return newValue
|
||||
}
|
||||
|
||||
func beijingNow() time.Time {
|
||||
return time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
|
||||
}
|
||||
|
||||
func polishDue(settings db.AccountTaskSettings, now time.Time) bool {
|
||||
if settings.LastPolishDate == now.Format("2006-01-02") {
|
||||
return false
|
||||
}
|
||||
target, err := time.Parse("15:04", settings.PolishTime)
|
||||
if err != nil {
|
||||
target, _ = time.Parse("15:04", "03:00")
|
||||
}
|
||||
return now.Hour() > target.Hour() || now.Hour() == target.Hour() && now.Minute() >= target.Minute()
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
type fakeAccountTaskClient struct {
|
||||
pendingCalls int
|
||||
rateCalls int
|
||||
polishCalls int
|
||||
pending []mtop.PendingRateOrder
|
||||
items []mtop.ItemListItem
|
||||
fetchItemsErr error
|
||||
fetchPageSize int
|
||||
fetchMaxPages int
|
||||
polishErr error
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) FetchPendingRateOrders(context.Context, string, int, int) (*mtop.PendingRateResult, error) {
|
||||
f.pendingCalls++
|
||||
return &mtop.PendingRateResult{Orders: f.pending}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) RateBuyer(context.Context, string, string, string) (*mtop.AccountTaskResult, error) {
|
||||
f.rateCalls++
|
||||
return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) FetchAllItems(_ context.Context, _ string, pageSize, maxPages int) (*mtop.ItemListResult, error) {
|
||||
f.fetchPageSize, f.fetchMaxPages = pageSize, maxPages
|
||||
if f.fetchItemsErr != nil {
|
||||
return nil, f.fetchItemsErr
|
||||
}
|
||||
return &mtop.ItemListResult{Items: f.items}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) PolishItem(context.Context, string, string) (*mtop.AccountTaskResult, error) {
|
||||
f.polishCalls++
|
||||
if f.polishErr != nil {
|
||||
return nil, f.polishErr
|
||||
}
|
||||
return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil
|
||||
}
|
||||
|
||||
func TestAccountTaskRateIsOrderIdempotent(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-1"}, {TradeID: "order-2"}}}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "03:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := center.RunAccountTask(ctx, "cid", TaskAutoRate)
|
||||
if err != nil || first.Success != 2 || client.rateCalls != 2 {
|
||||
t.Fatalf("first=%+v calls=%d err=%v", first, client.rateCalls, err)
|
||||
}
|
||||
second, err := center.RunAccountTask(ctx, "cid", TaskAutoRate)
|
||||
if err != nil || second.Skipped != 2 || client.rateCalls != 2 {
|
||||
t.Fatalf("second=%+v calls=%d err=%v", second, client.rateCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTaskPolishRunsOncePerBeijingDay(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}, {ID: "item-2"}}}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || first.Success != 2 || client.polishCalls != 2 {
|
||||
t.Fatalf("first=%+v calls=%d err=%v", first, client.polishCalls, err)
|
||||
}
|
||||
if client.fetchPageSize != 20 || client.fetchMaxPages != 20 {
|
||||
t.Fatalf("unexpected item pagination: pageSize=%d maxPages=%d", client.fetchPageSize, client.fetchMaxPages)
|
||||
}
|
||||
second, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || second.Skipped != 1 || client.polishCalls != 2 {
|
||||
t.Fatalf("second=%+v calls=%d err=%v", second, client.polishCalls, err)
|
||||
}
|
||||
settings, err := store.AccountTasks.Get(ctx, "cid")
|
||||
if err != nil || settings.LastPolishDate != beijingNow().Format("2006-01-02") {
|
||||
t.Fatalf("settings=%+v err=%v", settings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualPolishReportsItemFailures(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, polishErr: errors.New("both polish APIs failed")}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
summary, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err == nil || summary.Failed != 1 || summary.Success != 0 {
|
||||
t.Fatalf("summary=%+v err=%v", summary, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualPolishCanRetryImmediatelyAfterFailure(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, fetchItemsErr: errors.New("upstream 502")}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish); err == nil {
|
||||
t.Fatal("first polish should expose the upstream failure")
|
||||
}
|
||||
client.fetchItemsErr = nil
|
||||
second, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || second.Success != 1 || second.Skipped != 0 || client.polishCalls != 1 {
|
||||
t.Fatalf("manual retry=%+v calls=%d err=%v", second, client.polishCalls, err)
|
||||
}
|
||||
third, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || third.Skipped != 1 || client.polishCalls != 1 {
|
||||
t.Fatalf("successful day must remain idempotent: summary=%+v calls=%d err=%v", third, client.polishCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolishDueHonorsConfiguredTimeAndDate(t *testing.T) {
|
||||
now := beijingNow()
|
||||
settings := db.AccountTaskSettings{PolishTime: now.Add(2 * time.Hour).Format("15:04")}
|
||||
if polishDue(settings, now) && now.Hour() < 22 {
|
||||
t.Fatal("task must not run before configured time")
|
||||
}
|
||||
settings.PolishTime = "00:00"
|
||||
if !polishDue(settings, now) {
|
||||
t.Fatal("task should be due after midnight")
|
||||
}
|
||||
settings.LastPolishDate = now.Format("2006-01-02")
|
||||
if polishDue(settings, now) {
|
||||
t.Fatal("task must not run twice on the same Beijing date")
|
||||
}
|
||||
}
|
||||
@@ -86,15 +86,16 @@ type Notifier interface {
|
||||
// Center 是统一自动化处理中心。
|
||||
// 它只接收已经分类好的系统事件或计划任务,不处理用户消息;用户消息由 engine 的回复链处理。
|
||||
type Center struct {
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
logger *slog.Logger
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
cardLocks sync.Map
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
accountTasks AccountTaskClient
|
||||
logger *slog.Logger
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
cardLocks sync.Map
|
||||
}
|
||||
|
||||
// New 构造自动化中心。
|
||||
@@ -102,12 +103,16 @@ func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Center{store: store, senders: senders, mtop: mtop.NewClient(), logger: logger.With("subsys", "automation")}
|
||||
client := mtop.NewClient()
|
||||
return &Center{store: store, senders: senders, mtop: client, accountTasks: client, logger: logger.With("subsys", "automation")}
|
||||
}
|
||||
|
||||
// SetMTop 注入 mtop 客户端(确认发货用)。未注入时使用默认 HTTP 实现。
|
||||
func (c *Center) SetMTop(m mtop.Client) { c.mtop = m }
|
||||
|
||||
// SetAccountTaskClient overrides automatic rating/polish transport for tests.
|
||||
func (c *Center) SetAccountTaskClient(client AccountTaskClient) { c.accountTasks = client }
|
||||
|
||||
// SetOrderDetailFetcher 注入订单详情查询能力。
|
||||
func (c *Center) SetOrderDetailFetcher(fetcher OrderDetailFetcher) {
|
||||
c.fetcher = fetcher
|
||||
|
||||
@@ -60,6 +60,7 @@ func (s *Scheduler) Wait() {
|
||||
|
||||
func (s *Scheduler) scan(ctx context.Context) {
|
||||
s.runDeferredTasks(ctx)
|
||||
s.center.scanAccountTasks(ctx)
|
||||
if recovered, err := s.center.store.Automation.RecoverDefinitelyUnsentReviewRuns(ctx); err != nil {
|
||||
s.center.logger.Warn("恢复历史求评价未发送任务失败", "err", err)
|
||||
} else if recovered > 0 {
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
type HistoryPage struct {
|
||||
Messages []db.ChatMessage
|
||||
HasMore bool
|
||||
NextCursor int64
|
||||
}
|
||||
|
||||
type ConversationPage struct {
|
||||
HasMore bool
|
||||
NextCursor int64
|
||||
}
|
||||
|
||||
const xianxiaomiAvatar = "https://img.alicdn.com/imgextra/i2/O1CN01rxBFRr1II3BU0as29_!!6000000000869-2-tps-144-144.png_110x10000.jpg_.webp"
|
||||
|
||||
func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID string, body map[string]any) (ConversationPage, error) {
|
||||
page := ConversationPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
|
||||
items, _ := body["userConvs"].([]any)
|
||||
for _, item := range items {
|
||||
wrapper, _ := item.(map[string]any)
|
||||
conv := wrapper
|
||||
if nested, ok := wrapper["singleChatUserConversation"].(map[string]any); ok {
|
||||
conv = nested
|
||||
}
|
||||
single, _ := conv["singleChatConversation"].(map[string]any)
|
||||
cid := strings.Split(strings.TrimSpace(fmt.Sprint(single["cid"])), "@")[0]
|
||||
if visible, exists := conv["visible"]; exists && int64Value(visible) == 0 {
|
||||
if cid != "" && cid != "<nil>" {
|
||||
_ = s.store.Chats.DeleteSession(ctx, accountID, cid)
|
||||
}
|
||||
continue
|
||||
}
|
||||
first := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairFirst"])), "@")[0]
|
||||
second := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairSecond"])), "@")[0]
|
||||
ext := mapValue(single["extension"])
|
||||
if second == "0" && cleanNilString(ext["extUserId"]) != "1400" {
|
||||
_ = s.store.Chats.DeleteSession(ctx, accountID, cid)
|
||||
continue
|
||||
}
|
||||
peerID := first
|
||||
if first == myID {
|
||||
peerID = second
|
||||
}
|
||||
if peerID == "0" {
|
||||
peerID = cleanNilString(ext["extUserId"])
|
||||
}
|
||||
if cid == "" || cid == "<nil>" || peerID == "" || peerID == "0" || peerID == "<nil>" {
|
||||
continue
|
||||
}
|
||||
lastWrap, _ := conv["lastMessage"].(map[string]any)
|
||||
last, _ := lastWrap["message"].(map[string]any)
|
||||
// reminderTitle belongs to the message presentation layer. Depending on
|
||||
// the message type it may contain a nickname, an order-state prompt, or
|
||||
// another card title. The official web client resolves conversation
|
||||
// identity separately through pc.user.query, so never persist this field
|
||||
// as the session nickname.
|
||||
peerName := ""
|
||||
custom := map[string]any{}
|
||||
if content, ok := last["content"].(map[string]any); ok {
|
||||
custom, _ = content["custom"].(map[string]any)
|
||||
}
|
||||
summary := cleanNilString(custom["summary"])
|
||||
if summary == "" {
|
||||
if encoded := cleanNilString(custom["data"]); encoded != "" {
|
||||
var decoded map[string]any
|
||||
if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil && json.Unmarshal(raw, &decoded) == nil {
|
||||
fallback := ""
|
||||
if textBlock, ok := decoded["text"].(map[string]any); ok {
|
||||
fallback = cleanNilString(textBlock["text"])
|
||||
}
|
||||
_, summary = extractMessageContent(decoded, fallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
if summary == "" {
|
||||
summary = "暂无消息"
|
||||
}
|
||||
avatar := ""
|
||||
if peerID == "1400" {
|
||||
peerName, avatar = "闲小蜜", xianxiaomiAvatar
|
||||
}
|
||||
modifyTime := int64Value(conv["modifyTime"])
|
||||
lastMessageAt := int64Value(last["createAt"])
|
||||
if lastMessageAt <= 0 {
|
||||
lastMessageAt = modifyTime
|
||||
}
|
||||
session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar,
|
||||
ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary,
|
||||
LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))}
|
||||
if err := s.store.Chats.UpsertSession(ctx, session); err != nil {
|
||||
return page, err
|
||||
}
|
||||
if err := s.store.Chats.SyncSessionSummary(ctx, accountID, cid, summary, lastMessageAt, modifyTime, session.UnreadCount); err != nil {
|
||||
return page, err
|
||||
}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
var invalidNicknames = map[string]struct{}{
|
||||
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
|
||||
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
|
||||
"等待您发货": {}, "超时未付款,系统关闭了订单": {}, "邀您填写售后问卷": {},
|
||||
}
|
||||
|
||||
func ValidNickname(value string) bool {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(value, "***") {
|
||||
return false
|
||||
}
|
||||
if _, err := strconv.ParseUint(value, 10, 64); err == nil {
|
||||
return false
|
||||
}
|
||||
trimmed := strings.TrimSuffix(strings.TrimPrefix(value, "["), "]")
|
||||
if _, invalid := invalidNicknames[trimmed]; invalid {
|
||||
return false
|
||||
}
|
||||
return !strings.Contains(value, "发来一条新消息")
|
||||
}
|
||||
|
||||
func cleanNilString(value any) string {
|
||||
text := strings.TrimSpace(fmt.Sprint(value))
|
||||
if text == "<nil>" {
|
||||
return ""
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
type Incoming struct {
|
||||
AccountID string
|
||||
ChatID string
|
||||
BuyerID string
|
||||
BuyerName string
|
||||
Text string
|
||||
ItemID string
|
||||
Raw map[string]any
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
Message *db.ChatMessage `json:"message,omitempty"`
|
||||
Session *db.ChatSession `json:"session,omitempty"`
|
||||
}
|
||||
|
||||
type subscriber struct {
|
||||
accounts map[string]struct{}
|
||||
ch chan Event
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store *db.Store
|
||||
mu sync.RWMutex
|
||||
next uint64
|
||||
subs map[uint64]subscriber
|
||||
}
|
||||
|
||||
func New(store *db.Store) *Service {
|
||||
return &Service{store: store, subs: make(map[uint64]subscriber)}
|
||||
}
|
||||
|
||||
func (s *Service) Subscribe(ctx context.Context, userID int64) (<-chan Event, func(), error) {
|
||||
accounts, err := s.store.Cookies.AllForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
allowed := make(map[string]struct{}, len(accounts))
|
||||
for accountID := range accounts {
|
||||
allowed[accountID] = struct{}{}
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.next++
|
||||
id := s.next
|
||||
ch := make(chan Event, 128)
|
||||
s.subs[id] = subscriber{accounts: allowed, ch: ch}
|
||||
s.mu.Unlock()
|
||||
var once sync.Once
|
||||
cancel := func() {
|
||||
once.Do(func() {
|
||||
s.mu.Lock()
|
||||
if sub, ok := s.subs[id]; ok {
|
||||
delete(s.subs, id)
|
||||
close(sub.ch)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
})
|
||||
}
|
||||
return ch, cancel, nil
|
||||
}
|
||||
|
||||
func (s *Service) Publish(accountID string, event Event) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for _, sub := range s.subs {
|
||||
if _, ok := sub.accounts[accountID]; !ok {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case sub.ch <- event:
|
||||
default:
|
||||
// A slow browser must not block the account receive loop. The client
|
||||
// reconnects and reloads authoritative history when its buffer fills.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMessage, bool, error) {
|
||||
if s == nil || s.store == nil || s.store.Chats == nil {
|
||||
return nil, false, fmt.Errorf("聊天服务未初始化")
|
||||
}
|
||||
sentAt := extractUnixMilli(in.Raw)
|
||||
if sentAt == 0 {
|
||||
sentAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||
if key == "" {
|
||||
raw, _ := json.Marshal(in.Raw)
|
||||
digest := sha256.Sum256([]byte(in.AccountID + "\x00" + in.ChatID + "\x00" + in.BuyerID + "\x00" + in.Text + "\x00" + string(raw)))
|
||||
key = "in-" + hex.EncodeToString(digest[:16])
|
||||
}
|
||||
session := db.ChatSession{CookieID: in.AccountID, ChatID: in.ChatID, BuyerID: in.BuyerID,
|
||||
BuyerName: in.BuyerName, BuyerAvatar: extractString(in.Raw, "avatar", "avatarUrl", "senderAvatar"),
|
||||
ItemID: in.ItemID, ItemTitle: extractString(in.Raw, "itemTitle", "title")}
|
||||
messageType, content := extractMessageContent(in.Raw, in.Text)
|
||||
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
|
||||
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
|
||||
stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, true)
|
||||
if err == nil && inserted {
|
||||
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
return stored, inserted, err
|
||||
}
|
||||
|
||||
// RecordHistoryPage normalizes official IM history and stores it idempotently.
|
||||
func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID string, session db.ChatSession, body map[string]any) (HistoryPage, error) {
|
||||
page := HistoryPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
|
||||
models, _ := body["userMessageModels"].([]any)
|
||||
for i := len(models) - 1; i >= 0; i-- { // official API returns newest first
|
||||
model, _ := models[i].(map[string]any)
|
||||
message, ok := parseHistoryMessage(accountID, chatID, myID, model)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
session.CookieID, session.ChatID = accountID, chatID
|
||||
if message.Direction == "incoming" {
|
||||
if session.BuyerID == "" {
|
||||
session.BuyerID = message.SenderID
|
||||
}
|
||||
}
|
||||
stored, _, err := s.store.Chats.SaveMessage(ctx, session, message, false)
|
||||
if err != nil {
|
||||
return page, err
|
||||
}
|
||||
page.Messages = append(page.Messages, *stored)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func parseHistoryMessage(accountID, chatID, myID string, model map[string]any) (db.ChatMessage, bool) {
|
||||
message, _ := model["message"].(map[string]any)
|
||||
if message == nil {
|
||||
return db.ChatMessage{}, false
|
||||
}
|
||||
extension := mapValue(message["extension"])
|
||||
senderID := strings.Split(strings.TrimSpace(fmt.Sprint(extension["senderUserId"])), "@")[0]
|
||||
senderName := strings.TrimSpace(fmt.Sprint(extension["reminderTitle"]))
|
||||
if senderName == "<nil>" {
|
||||
senderName = ""
|
||||
}
|
||||
key := strings.TrimSpace(fmt.Sprint(message["messageId"]))
|
||||
if key == "" || key == "<nil>" {
|
||||
return db.ChatMessage{}, false
|
||||
}
|
||||
contentMap, _ := message["content"].(map[string]any)
|
||||
custom, _ := contentMap["custom"].(map[string]any)
|
||||
rawContent := map[string]any{}
|
||||
if encoded := strings.TrimSpace(fmt.Sprint(custom["data"])); encoded != "" && encoded != "<nil>" {
|
||||
if decoded, err := base64.StdEncoding.DecodeString(encoded); err == nil {
|
||||
_ = json.Unmarshal(decoded, &rawContent)
|
||||
}
|
||||
}
|
||||
fallback := strings.TrimSpace(fmt.Sprint(custom["summary"]))
|
||||
if fallback == "<nil>" {
|
||||
fallback = ""
|
||||
}
|
||||
if textBlock, ok := rawContent["text"].(map[string]any); ok {
|
||||
if text := strings.TrimSpace(fmt.Sprint(textBlock["text"])); text != "" && text != "<nil>" {
|
||||
fallback = text
|
||||
}
|
||||
}
|
||||
messageType, content := extractMessageContent(rawContent, fallback)
|
||||
if content == "" {
|
||||
content = "[系统消息]"
|
||||
}
|
||||
direction, status := "incoming", "received"
|
||||
if senderID != "" && senderID == strings.TrimSpace(myID) {
|
||||
direction, status = "outgoing", "sent"
|
||||
}
|
||||
return db.ChatMessage{CookieID: accountID, ChatID: chatID, MessageKey: key, Direction: direction,
|
||||
SenderID: senderID, SenderName: senderName, MessageType: messageType, Content: content,
|
||||
Status: status, SentAt: int64Value(message["createAt"])}, true
|
||||
}
|
||||
|
||||
func mapValue(value any) map[string]any {
|
||||
if result, ok := value.(map[string]any); ok {
|
||||
return result
|
||||
}
|
||||
if text, ok := value.(string); ok {
|
||||
var result map[string]any
|
||||
if json.Unmarshal([]byte(text), &result) == nil {
|
||||
return result
|
||||
}
|
||||
}
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
func int64Value(value any) int64 {
|
||||
switch typed := value.(type) {
|
||||
case float64:
|
||||
return int64(typed)
|
||||
case int64:
|
||||
return typed
|
||||
case int:
|
||||
return int64(typed)
|
||||
case json.Number:
|
||||
result, _ := typed.Int64()
|
||||
return result
|
||||
case string:
|
||||
var result int64
|
||||
_, _ = fmt.Sscan(strings.TrimSpace(typed), &result)
|
||||
return result
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func boolValue(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case bool:
|
||||
return typed
|
||||
case float64:
|
||||
return typed == 1
|
||||
case int:
|
||||
return typed == 1
|
||||
case string:
|
||||
return typed == "1" || strings.EqualFold(typed, "true")
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func extractMessageContent(raw map[string]any, fallback string) (string, string) {
|
||||
var inspect func(any) (string, string)
|
||||
inspect = func(value any) (string, string) {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
var nested any
|
||||
if json.Unmarshal([]byte(typed), &nested) == nil {
|
||||
return inspect(nested)
|
||||
}
|
||||
case map[string]any:
|
||||
contentType := strings.TrimSpace(fmt.Sprint(typed["contentType"]))
|
||||
if contentType == "2" {
|
||||
if mediaURL := extractString(typed["image"], "url"); mediaURL != "" {
|
||||
return "image", mediaURL
|
||||
}
|
||||
}
|
||||
if contentType == "4" || typed["video"] != nil {
|
||||
if mediaURL := extractString(typed["video"], "url", "videoUrl", "playUrl"); mediaURL != "" {
|
||||
return "video", mediaURL
|
||||
}
|
||||
}
|
||||
for _, child := range typed {
|
||||
if kind, mediaURL := inspect(child); mediaURL != "" {
|
||||
return kind, mediaURL
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range typed {
|
||||
if kind, mediaURL := inspect(child); mediaURL != "" {
|
||||
return kind, mediaURL
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
if kind, mediaURL := inspect(raw); mediaURL != "" {
|
||||
return kind, mediaURL
|
||||
}
|
||||
return "text", strings.TrimSpace(fallback)
|
||||
}
|
||||
|
||||
func (s *Service) CreateOutgoing(ctx context.Context, session db.ChatSession, text string) (*db.ChatMessage, error) {
|
||||
return s.CreateOutgoingMedia(ctx, session, "text", strings.TrimSpace(text))
|
||||
}
|
||||
|
||||
func (s *Service) CreateOutgoingMedia(ctx context.Context, session db.ChatSession, messageType, content string) (*db.ChatMessage, error) {
|
||||
key := "local-" + randomID()
|
||||
message := db.ChatMessage{MessageKey: key, Direction: "outgoing", SenderID: session.CookieID,
|
||||
SenderName: "我", MessageType: messageType, Content: strings.TrimSpace(content), Status: "sending",
|
||||
SentAt: time.Now().UTC().UnixMilli()}
|
||||
stored, _, err := s.store.Chats.SaveMessage(ctx, session, message, false)
|
||||
if err == nil {
|
||||
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
return stored, err
|
||||
}
|
||||
|
||||
// RecordOutgoingSent captures automatic replies and automation messages. A
|
||||
// supplied key correlates a UI pending message and only updates its status.
|
||||
func (s *Service) RecordOutgoingSent(ctx context.Context, session db.ChatSession, key, text string) (*db.ChatMessage, error) {
|
||||
if strings.TrimSpace(key) != "" {
|
||||
return s.SetOutgoingStatus(ctx, session.CookieID, key, "sent")
|
||||
}
|
||||
message := db.ChatMessage{MessageKey: "sent-" + randomID(), Direction: "outgoing", SenderID: session.CookieID,
|
||||
SenderName: "我", MessageType: "text", Content: strings.TrimSpace(text), Status: "sent",
|
||||
SentAt: time.Now().UTC().UnixMilli()}
|
||||
stored, _, err := s.store.Chats.SaveMessage(ctx, session, message, false)
|
||||
if err == nil {
|
||||
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
return stored, err
|
||||
}
|
||||
|
||||
func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (*db.ChatMessage, error) {
|
||||
message, err := s.store.Chats.UpdateMessageStatus(ctx, accountID, key, status)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
func randomID() string {
|
||||
var value [16]byte
|
||||
if _, err := rand.Read(value[:]); err == nil {
|
||||
return hex.EncodeToString(value[:])
|
||||
}
|
||||
return fmt.Sprintf("%d", time.Now().UTC().UnixNano())
|
||||
}
|
||||
|
||||
func extractString(value any, keys ...string) string {
|
||||
wanted := make(map[string]struct{}, len(keys))
|
||||
for _, key := range keys {
|
||||
wanted[strings.ToLower(key)] = struct{}{}
|
||||
}
|
||||
var walk func(any) string
|
||||
walk = func(v any) string {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range x {
|
||||
if _, ok := wanted[strings.ToLower(key)]; ok {
|
||||
if text := strings.TrimSpace(fmt.Sprint(child)); text != "" && text != "<nil>" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, child := range x {
|
||||
if text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range x {
|
||||
if text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(value)
|
||||
}
|
||||
|
||||
func extractUnixMilli(raw map[string]any) int64 {
|
||||
text := extractString(raw, "sendTime", "timestamp", "time", "createdAt")
|
||||
var value int64
|
||||
_, _ = fmt.Sscan(text, &value)
|
||||
if value > 0 && value < 10_000_000_000 {
|
||||
value *= 1000
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
service := New(store)
|
||||
ctx := context.Background()
|
||||
encoded := func(value string) string { return base64.StdEncoding.EncodeToString([]byte(value)) }
|
||||
body := map[string]any{
|
||||
"hasMore": float64(1), "nextCursor": float64(12345),
|
||||
"userMessageModels": []any{
|
||||
map[string]any{"message": map[string]any{"messageId": "m2", "createAt": float64(2000), "extension": `{"senderUserId":"self@goofish","reminderTitle":"我"}`, "content": map[string]any{"custom": map[string]any{"data": encoded(`{"contentType":2,"image":{"pics":[{"url":"https://img.example/2.jpg"}]}}`)}}}},
|
||||
map[string]any{"message": map[string]any{"messageId": "m1", "createAt": float64(1000), "extension": map[string]any{"senderUserId": "peer@goofish", "reminderTitle": "对方"}, "content": map[string]any{"custom": map[string]any{"data": encoded(`{"contentType":1,"text":{"text":"较早的消息"}}`)}}}},
|
||||
},
|
||||
}
|
||||
session := db.ChatSession{CookieID: "account-1", ChatID: "cid", BuyerID: "peer", BuyerName: "对方"}
|
||||
page, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !page.HasMore || page.NextCursor != 12345 || len(page.Messages) != 2 {
|
||||
t.Fatalf("unexpected page: %+v", page)
|
||||
}
|
||||
if page.Messages[0].Direction != "incoming" || page.Messages[0].Content != "较早的消息" {
|
||||
t.Fatalf("unexpected incoming: %+v", page.Messages[0])
|
||||
}
|
||||
if page.Messages[1].Direction != "outgoing" || page.Messages[1].MessageType != "image" || page.Messages[1].Content != "https://img.example/2.jpg" {
|
||||
t.Fatalf("unexpected outgoing image: %+v", page.Messages[1])
|
||||
}
|
||||
if _, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||
rows, err := store.Chats.ListMessages(ctx, owner.ID, "account-1", "cid", 0, 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("history retry inserted duplicates: %d", len(rows))
|
||||
}
|
||||
_, _, err = store.Chats.SaveMessage(ctx, session, db.ChatMessage{MessageKey: "system-later", Direction: "incoming", SenderID: "peer", SenderName: "快给ta一个评价吧~", MessageType: "text", Content: "快给ta一个评价吧~", Status: "received", SentAt: 3000}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name, err := store.Chats.LatestUnmaskedPeerName(ctx, "account-1", "cid")
|
||||
if err != nil || name != "对方" {
|
||||
t.Fatalf("historical nickname=%q err=%v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
service := New(store)
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":1,"text":{"text":"历史消息"}}`))
|
||||
if err := store.Chats.UpsertSession(context.Background(), db.ChatSession{CookieID: "account-1", ChatID: "history-cid", BuyerID: "peer-9", LastMessage: "错误的新摘要", LastMessageAt: 987654}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := map[string]any{"hasMore": true, "nextCursor": float64(888), "userConvs": []any{
|
||||
map[string]any{"singleChatUserConversation": map[string]any{
|
||||
"singleChatConversation": map[string]any{"cid": "history-cid@goofish", "pairFirst": "self@goofish", "pairSecond": "peer-9@goofish", "extension": `{"itemTitle":"旧商品"}`},
|
||||
"lastMessage": map[string]any{"message": map[string]any{"createAt": float64(123456), "extension": map[string]any{"senderUserId": "peer-9@goofish", "reminderTitle": "历史用户"}, "content": map[string]any{"custom": map[string]any{"data": encoded}}}},
|
||||
"modifyTime": float64(987654), "redPoint": float64(2),
|
||||
}},
|
||||
}}
|
||||
page, err := service.RecordConversationPage(context.Background(), "account-1", "self", body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !page.HasMore || page.NextCursor != 888 {
|
||||
t.Fatalf("unexpected page: %+v", page)
|
||||
}
|
||||
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
||||
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].BuyerID != "peer-9" || rows[0].BuyerName != "" || rows[0].LastMessage != "历史消息" || rows[0].UnreadCount != 2 {
|
||||
t.Fatalf("unexpected historical contact: %+v", rows)
|
||||
}
|
||||
if rows[0].LastMessageAt != 123456 {
|
||||
t.Fatalf("used conversation modifyTime instead of last message createAt: %d", rows[0].LastMessageAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
service := New(store)
|
||||
if err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "hidden", BuyerID: "peer", LastMessage: "暂无消息"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "platform", BuyerID: "900", LastMessage: "暂无消息"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := map[string]any{"userConvs": []any{
|
||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(0), "singleChatConversation": map[string]any{"cid": "hidden@goofish"}}},
|
||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}},
|
||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "modifyTime": float64(123),
|
||||
"singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}},
|
||||
"lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}},
|
||||
}}
|
||||
if _, err := service.RecordConversationPage(ctx, "account-1", "self", body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar {
|
||||
t.Fatalf("unexpected sessions: %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
ghost := db.ChatSession{CookieID: "account-1", ChatID: "ghost", BuyerID: "peer-ghost", LastMessage: "暂无消息", LastMessageAt: 100}
|
||||
if err := store.Chats.UpsertSession(ctx, ghost); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
real := db.ChatSession{CookieID: "account-1", ChatID: "real", BuyerID: "peer-real", LastMessage: "暂无消息", LastMessageAt: 200}
|
||||
if _, _, err := store.Chats.SaveMessage(ctx, real, db.ChatMessage{MessageKey: "real-1", Direction: "incoming", SenderID: "peer-real", SenderName: "真实用户", MessageType: "text", Content: "真实消息", Status: "received", SentAt: 200}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Chats.DeleteEmptySessions(ctx, "account-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].ChatID != "real" {
|
||||
t.Fatalf("unexpected sessions after pruning: %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidNicknameRejectsSystemReminderTitles(t *testing.T) {
|
||||
for _, value := range []string{"", "203591535", "x***3", "快给ta一个评价吧~", "[卖家已发货]", "闲小蜜发来一条新消息"} {
|
||||
if ValidNickname(value) {
|
||||
t.Fatalf("system reminder accepted as nickname: %q", value)
|
||||
}
|
||||
}
|
||||
if !ValidNickname("纽约做手工的石斑") {
|
||||
t.Fatal("real nickname rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncomingMessagePersistsDeduplicatesAndPublishesByOwner(t *testing.T) {
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
owner, _ := store.Users.GetByUsername(ctx, "owner")
|
||||
other, _ := store.Users.GetByUsername(ctx, "other")
|
||||
service := New(store)
|
||||
ownerEvents, cancelOwner, err := service.Subscribe(ctx, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancelOwner()
|
||||
otherEvents, cancelOther, err := service.Subscribe(ctx, other.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancelOther()
|
||||
|
||||
incoming := Incoming{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲",
|
||||
Text: "你好", ItemID: "item-1", Raw: map[string]any{"messageId": "platform-1", "sendTime": int64(1234567890000)}}
|
||||
message, inserted, err := service.RecordIncoming(ctx, incoming)
|
||||
if err != nil || !inserted || message.MessageKey != "platform-1" {
|
||||
t.Fatalf("message=%+v inserted=%v err=%v", message, inserted, err)
|
||||
}
|
||||
if _, inserted, err := service.RecordIncoming(ctx, incoming); err != nil || inserted {
|
||||
t.Fatalf("duplicate inserted=%v err=%v", inserted, err)
|
||||
}
|
||||
select {
|
||||
case event := <-ownerEvents:
|
||||
if event.Type != "message.created" || event.Message.MessageKey != "platform-1" {
|
||||
t.Fatalf("event=%+v", event)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("owner did not receive event")
|
||||
}
|
||||
select {
|
||||
case event := <-otherEvents:
|
||||
t.Fatalf("other owner leaked event: %+v", event)
|
||||
case <-time.After(30 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractMessageContentSupportsImageAndVideo(t *testing.T) {
|
||||
imageRaw := map[string]any{"payload": `{"contentType":2,"image":{"pics":[{"url":"https://cdn/image.jpg"}]}}`}
|
||||
if kind, content := extractMessageContent(imageRaw, "[图片]"); kind != "image" || content != "https://cdn/image.jpg" {
|
||||
t.Fatalf("image kind=%q content=%q", kind, content)
|
||||
}
|
||||
videoRaw := map[string]any{"content": map[string]any{"video": map[string]any{"playUrl": "https://cdn/video.mp4"}}}
|
||||
if kind, content := extractMessageContent(videoRaw, "[视频]"); kind != "video" || content != "https://cdn/video.mp4" {
|
||||
t.Fatalf("video kind=%q content=%q", kind, content)
|
||||
}
|
||||
if kind, content := extractMessageContent(nil, " 你好 "); kind != "text" || content != "你好" {
|
||||
t.Fatalf("text kind=%q content=%q", kind, content)
|
||||
}
|
||||
}
|
||||
|
||||
func chatTestStore(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
database, dialect, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "chat.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := db.NewStore(database, dialect)
|
||||
if ok, err := store.Users.Create(context.Background(), "owner", "owner@example.com", "pw"); err != nil || !ok {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, err := store.Users.Create(context.Background(), "other", "other@example.com", "pw"); err != nil || !ok {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
|
||||
other, _ := store.Users.GetByUsername(context.Background(), "other")
|
||||
if err := store.Cookies.Save(context.Background(), "account-1", "unb=1", owner.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Cookies.Save(context.Background(), "account-2", "unb=2", other.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store, func() { _ = database.Close() }
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AccountTaskSettings struct {
|
||||
CookieID string `json:"account_id"`
|
||||
AutoRateEnabled bool `json:"auto_rate_enabled"`
|
||||
RateContent string `json:"rate_content"`
|
||||
AutoPolishEnabled bool `json:"auto_polish_enabled"`
|
||||
PolishTime string `json:"polish_time"`
|
||||
LastRateScanAt int64 `json:"last_rate_scan_at"`
|
||||
LastPolishDate string `json:"last_polish_date"`
|
||||
LastPolishAt int64 `json:"last_polish_at"`
|
||||
}
|
||||
|
||||
type AccountTaskRun struct {
|
||||
ID int64 `json:"id"`
|
||||
RunKey string `json:"run_key"`
|
||||
CookieID string `json:"account_id"`
|
||||
TaskType string `json:"task_type"`
|
||||
TargetID string `json:"target_id"`
|
||||
RunDate string `json:"run_date"`
|
||||
Status string `json:"status"`
|
||||
SuccessCount int `json:"success_count"`
|
||||
FailedCount int `json:"failed_count"`
|
||||
ErrorMessage string `json:"error_message"`
|
||||
NextRetryAt int64 `json:"next_retry_at"`
|
||||
StartedAt int64 `json:"started_at"`
|
||||
FinishedAt int64 `json:"finished_at"`
|
||||
}
|
||||
|
||||
type AccountTaskStore struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
func defaultAccountTaskSettings(cookieID string) AccountTaskSettings {
|
||||
return AccountTaskSettings{CookieID: cookieID, RateContent: "不错的买家,交易愉快", PolishTime: "03:00"}
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) Get(ctx context.Context, cookieID string) (AccountTaskSettings, error) {
|
||||
result := defaultAccountTaskSettings(cookieID)
|
||||
var rateEnabled, polishEnabled int
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT auto_rate_enabled,rate_content,auto_polish_enabled,polish_time,
|
||||
last_rate_scan_at,last_polish_date,last_polish_at FROM account_task_settings WHERE cookie_id=?`, cookieID).Scan(
|
||||
&rateEnabled, &result.RateContent, &polishEnabled, &result.PolishTime, &result.LastRateScanAt,
|
||||
&result.LastPolishDate, &result.LastPolishAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return result, nil
|
||||
}
|
||||
result.AutoRateEnabled = rateEnabled != 0
|
||||
result.AutoPolishEnabled = polishEnabled != 0
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) Upsert(ctx context.Context, settings AccountTaskSettings) error {
|
||||
settings.RateContent = strings.TrimSpace(settings.RateContent)
|
||||
if settings.RateContent == "" {
|
||||
settings.RateContent = "不错的买家,交易愉快"
|
||||
}
|
||||
if settings.PolishTime == "" {
|
||||
settings.PolishTime = "03:00"
|
||||
}
|
||||
now := time.Now().UTC().Unix()
|
||||
query := `INSERT INTO account_task_settings
|
||||
(cookie_id,auto_rate_enabled,rate_content,auto_polish_enabled,polish_time,last_rate_scan_at,last_polish_date,last_polish_at,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?)` + dialectUpsert(s.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"auto_rate_enabled": "EXCLUDED.auto_rate_enabled", "rate_content": "EXCLUDED.rate_content",
|
||||
"auto_polish_enabled": "EXCLUDED.auto_polish_enabled", "polish_time": "EXCLUDED.polish_time",
|
||||
"updated_at": "EXCLUDED.updated_at",
|
||||
})
|
||||
_, err := s.DB.ExecContext(ctx, query, settings.CookieID, boolInt(settings.AutoRateEnabled), settings.RateContent,
|
||||
boolInt(settings.AutoPolishEnabled), settings.PolishTime, settings.LastRateScanAt, settings.LastPolishDate,
|
||||
settings.LastPolishAt, now, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) Enabled(ctx context.Context) ([]AccountTaskSettings, error) {
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT s.cookie_id,s.auto_rate_enabled,s.rate_content,s.auto_polish_enabled,s.polish_time,
|
||||
s.last_rate_scan_at,s.last_polish_date,s.last_polish_at
|
||||
FROM account_task_settings s JOIN cookies c ON c.id=s.cookie_id
|
||||
WHERE s.auto_rate_enabled=1 OR s.auto_polish_enabled=1 ORDER BY s.cookie_id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []AccountTaskSettings
|
||||
for rows.Next() {
|
||||
var row AccountTaskSettings
|
||||
var rate, polish int
|
||||
if err := rows.Scan(&row.CookieID, &rate, &row.RateContent, &polish, &row.PolishTime,
|
||||
&row.LastRateScanAt, &row.LastPolishDate, &row.LastPolishAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row.AutoRateEnabled, row.AutoPolishEnabled = rate != 0, polish != 0
|
||||
result = append(result, row)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// ClaimRun creates a run or atomically reclaims a due failed run.
|
||||
func (s *AccountTaskStore) ClaimRun(ctx context.Context, run AccountTaskRun, now int64) (bool, error) {
|
||||
return s.claimRun(ctx, run, now, false)
|
||||
}
|
||||
|
||||
// ClaimRunImmediately creates a run or immediately reclaims a failed run. It is
|
||||
// intended for an explicit user retry; scheduled workers should keep using
|
||||
// ClaimRun so repeated platform failures still honor their retry delay.
|
||||
func (s *AccountTaskStore) ClaimRunImmediately(ctx context.Context, run AccountTaskRun, now int64) (bool, error) {
|
||||
return s.claimRun(ctx, run, now, true)
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) claimRun(ctx context.Context, run AccountTaskRun, now int64, immediate bool) (bool, error) {
|
||||
retryCondition := "next_retry_at<=?"
|
||||
args := []any{now, run.RunKey, now}
|
||||
if immediate {
|
||||
retryCondition = "1=1"
|
||||
args = args[:2]
|
||||
}
|
||||
res, err := s.DB.ExecContext(ctx, `UPDATE account_task_runs SET status='running',started_at=?,finished_at=0,error_message=''
|
||||
WHERE run_key=? AND status='failed' AND `+retryCondition, args...)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n > 0 {
|
||||
return true, nil
|
||||
}
|
||||
query := dialectInsertIgnorePrefix(s.Dialect) + ` INTO account_task_runs
|
||||
(run_key,cookie_id,task_type,target_id,run_date,status,success_count,failed_count,error_message,next_retry_at,started_at,finished_at)
|
||||
VALUES(?,?,?,?,?,'running',0,0,'',0,?,0)` + dialectInsertIgnore(s.Dialect, []string{"run_key"})
|
||||
res, err = s.DB.ExecContext(ctx, query, run.RunKey, run.CookieID, run.TaskType, run.TargetID, run.RunDate, now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) FinishRun(ctx context.Context, runKey, status string, success, failed int, message string, nextRetryAt int64) error {
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE account_task_runs SET status=?,success_count=?,failed_count=?,error_message=?,next_retry_at=?,finished_at=? WHERE run_key=?`,
|
||||
status, success, failed, message, nextRetryAt, time.Now().UTC().Unix(), runKey)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) MarkRateScan(ctx context.Context, cookieID string, at int64) error {
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE account_task_settings SET last_rate_scan_at=?,updated_at=? WHERE cookie_id=?`, at, at, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) MarkPolished(ctx context.Context, cookieID, date string, at int64) error {
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE account_task_settings SET last_polish_date=?,last_polish_at=?,updated_at=? WHERE cookie_id=?`, date, at, at, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *AccountTaskStore) RecentRuns(ctx context.Context, cookieID string, limit int) ([]AccountTaskRun, error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT id,run_key,cookie_id,task_type,target_id,run_date,status,success_count,failed_count,
|
||||
error_message,next_retry_at,started_at,finished_at FROM account_task_runs WHERE cookie_id=? ORDER BY id DESC LIMIT ?`, cookieID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []AccountTaskRun
|
||||
for rows.Next() {
|
||||
var row AccountTaskRun
|
||||
if err := rows.Scan(&row.ID, &row.RunKey, &row.CookieID, &row.TaskType, &row.TargetID, &row.RunDate,
|
||||
&row.Status, &row.SuccessCount, &row.FailedCount, &row.ErrorMessage, &row.NextRetryAt,
|
||||
&row.StartedAt, &row.FinishedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, row)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func boolInt(v bool) int {
|
||||
if v {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ChatSession struct {
|
||||
CookieID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
BuyerID string `json:"buyer_id"`
|
||||
BuyerName string `json:"buyer_name"`
|
||||
BuyerAvatar string `json:"buyer_avatar_url"`
|
||||
ItemID string `json:"item_id"`
|
||||
ItemTitle string `json:"item_title"`
|
||||
LastMessage string `json:"last_message"`
|
||||
LastMessageAt int64 `json:"last_message_at"`
|
||||
UnreadCount int `json:"unread_count"`
|
||||
}
|
||||
|
||||
type ChatMessage struct {
|
||||
ID int64 `json:"id"`
|
||||
CookieID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
MessageKey string `json:"message_key"`
|
||||
Direction string `json:"direction"`
|
||||
SenderID string `json:"sender_id"`
|
||||
SenderName string `json:"sender_name"`
|
||||
MessageType string `json:"message_type"`
|
||||
Content string `json:"content"`
|
||||
Status string `json:"status"`
|
||||
SentAt int64 `json:"sent_at"`
|
||||
}
|
||||
|
||||
type ChatStore struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
func (s *ChatStore) UpsertSession(ctx context.Context, session ChatSession) error {
|
||||
now := time.Now().UTC().Unix()
|
||||
prefix := dialectInsertIgnorePrefix(s.Dialect)
|
||||
query := prefix + ` INTO chat_sessions
|
||||
(cookie_id,chat_id,buyer_id,buyer_name,buyer_avatar_url,item_id,item_title,last_message,last_message_at,unread_count,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "chat_id"})
|
||||
if _, err := s.DB.ExecContext(ctx, query, session.CookieID, session.ChatID, session.BuyerID, session.BuyerName,
|
||||
session.BuyerAvatar, session.ItemID, session.ItemTitle, session.LastMessage, session.LastMessageAt,
|
||||
session.UnreadCount, now, now); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET
|
||||
buyer_id=CASE WHEN ?<>'' THEN ? ELSE buyer_id END,
|
||||
buyer_name=CASE WHEN ?<>'' THEN ? ELSE buyer_name END,
|
||||
buyer_avatar_url=CASE WHEN ?<>'' THEN ? ELSE buyer_avatar_url END,
|
||||
item_id=CASE WHEN ?<>'' THEN ? ELSE item_id END,
|
||||
item_title=CASE WHEN ?<>'' THEN ? ELSE item_title END,
|
||||
last_message=CASE WHEN last_message_at<=? THEN ? ELSE last_message END,
|
||||
last_message_at=CASE WHEN last_message_at<=? THEN ? ELSE last_message_at END,
|
||||
unread_count=CASE WHEN ?>unread_count THEN ? ELSE unread_count END,updated_at=?
|
||||
WHERE cookie_id=? AND chat_id=?`, session.BuyerID, session.BuyerID, session.BuyerName, session.BuyerName,
|
||||
session.BuyerAvatar, session.BuyerAvatar, session.ItemID, session.ItemID, session.ItemTitle, session.ItemTitle,
|
||||
session.LastMessageAt, session.LastMessage, session.LastMessageAt, session.LastMessageAt,
|
||||
session.UnreadCount, session.UnreadCount, now, session.CookieID, session.ChatID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *ChatStore) DeleteSession(ctx context.Context, cookieID, chatID string) error {
|
||||
_, err := s.DB.ExecContext(ctx, `DELETE FROM chat_sessions WHERE cookie_id=? AND chat_id=?`, cookieID, chatID)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteEmptySessions removes conversation shells returned by IM pagination
|
||||
// with visible=0 and no lastMessage. Older versions persisted these shells as
|
||||
// "暂无消息", although the official UI never renders them.
|
||||
func (s *ChatStore) DeleteEmptySessions(ctx context.Context, cookieID string) error {
|
||||
_, err := s.DB.ExecContext(ctx, `DELETE FROM chat_sessions
|
||||
WHERE cookie_id=? AND (last_message='' OR last_message='暂无消息')
|
||||
AND NOT EXISTS (SELECT 1 FROM chat_messages m WHERE m.cookie_id=chat_sessions.cookie_id AND m.chat_id=chat_sessions.chat_id)`, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
// SyncSessionSummary applies the authoritative last-message timestamp from the
|
||||
// official conversation response. observedModifyAt guards against overwriting
|
||||
// a genuinely newer live message that arrived after that response was built.
|
||||
func (s *ChatStore) SyncSessionSummary(ctx context.Context, cookieID, chatID, summary string, sentAt, observedModifyAt int64, unread int) error {
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET last_message=?,last_message_at=?,unread_count=?,updated_at=?
|
||||
WHERE cookie_id=? AND chat_id=? AND last_message_at<=?`, summary, sentAt, unread, time.Now().UTC().Unix(),
|
||||
cookieID, chatID, observedModifyAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *ChatStore) UpdateSessionIdentity(ctx context.Context, cookieID, chatID, buyerID, buyerName, avatarURL string) error {
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET
|
||||
buyer_id=CASE WHEN ?<>'' THEN ? ELSE buyer_id END,
|
||||
buyer_name=CASE WHEN ?<>'' THEN ? ELSE buyer_name END,
|
||||
buyer_avatar_url=CASE WHEN ?<>'' THEN ? ELSE buyer_avatar_url END,
|
||||
updated_at=? WHERE cookie_id=? AND chat_id=?`, buyerID, buyerID, buyerName, buyerName,
|
||||
avatarURL, avatarURL, time.Now().UTC().Unix(), cookieID, chatID)
|
||||
return err
|
||||
}
|
||||
|
||||
// LatestUnmaskedPeerName recovers the most recent real nickname observed in
|
||||
// message history. Conversation summaries and profile APIs may return masked
|
||||
// names such as x***3, while older message extensions still contain the nick.
|
||||
func (s *ChatStore) LatestUnmaskedPeerName(ctx context.Context, cookieID, chatID string) (string, error) {
|
||||
var name string
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT sender_name FROM chat_messages
|
||||
WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND sender_name<>'' AND sender_name NOT LIKE '%***%'
|
||||
AND sender_name<>content AND sender_name NOT IN ('交易消息','系统消息','卡片消息','我完成了评价','对方完成了评价',
|
||||
'快给ta一个评价吧~','卖家已发货','买家已付款','买家已确认收货','等待您发货','超时未付款,系统关闭了订单','邀您填写售后问卷')
|
||||
ORDER BY sent_at DESC,id DESC LIMIT 1`, cookieID, chatID).Scan(&name)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", nil
|
||||
}
|
||||
return strings.TrimSpace(name), err
|
||||
}
|
||||
|
||||
// SaveMessage inserts a message idempotently and updates its conversation only
|
||||
// when the message was new. This keeps retries from inflating unread counters.
|
||||
func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, message ChatMessage, unread bool) (*ChatMessage, bool, error) {
|
||||
if s == nil || s.DB == nil {
|
||||
return nil, false, errors.New("聊天存储未初始化")
|
||||
}
|
||||
session.CookieID = strings.TrimSpace(session.CookieID)
|
||||
session.ChatID = strings.TrimSpace(session.ChatID)
|
||||
message.MessageKey = strings.TrimSpace(message.MessageKey)
|
||||
if session.CookieID == "" || session.ChatID == "" || message.MessageKey == "" {
|
||||
return nil, false, errors.New("聊天消息缺少账号、会话或消息键")
|
||||
}
|
||||
if message.SentAt <= 0 {
|
||||
message.SentAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
message.CookieID, message.ChatID = session.CookieID, session.ChatID
|
||||
now := time.Now().UTC().Unix()
|
||||
tx, err := s.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// The composite foreign key on chat_messages requires the session to exist
|
||||
// first. Insert an empty shell without touching an existing conversation.
|
||||
sessionPrefix := dialectInsertIgnorePrefix(s.Dialect)
|
||||
sessionInsert := sessionPrefix + ` INTO chat_sessions
|
||||
(cookie_id,chat_id,buyer_id,buyer_name,buyer_avatar_url,item_id,item_title,last_message,last_message_at,unread_count,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "chat_id"})
|
||||
if _, err := tx.ExecContext(ctx, sessionInsert, session.CookieID, session.ChatID, session.BuyerID,
|
||||
session.BuyerName, session.BuyerAvatar, session.ItemID, session.ItemTitle, "", int64(0), 0, now, now); err != nil {
|
||||
return nil, false, fmt.Errorf("建立聊天会话: %w", err)
|
||||
}
|
||||
|
||||
prefix := dialectInsertIgnorePrefix(s.Dialect)
|
||||
query := prefix + ` INTO chat_messages
|
||||
(cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"})
|
||||
res, err := tx.ExecContext(ctx, query, message.CookieID, message.ChatID, message.MessageKey,
|
||||
message.Direction, message.SenderID, message.SenderName, message.MessageType, message.Content,
|
||||
message.Status, message.SentAt, now)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("保存聊天消息: %w", err)
|
||||
}
|
||||
inserted, _ := res.RowsAffected()
|
||||
if inserted > 0 {
|
||||
unreadDelta := 0
|
||||
if unread {
|
||||
unreadDelta = 1
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE chat_sessions SET buyer_id=?,buyer_name=?,buyer_avatar_url=?,
|
||||
item_id=?,item_title=?,last_message=CASE WHEN last_message_at<=? THEN ? ELSE last_message END,
|
||||
last_message_at=CASE WHEN last_message_at<=? THEN ? ELSE last_message_at END,
|
||||
unread_count=unread_count+?,updated_at=?
|
||||
WHERE cookie_id=? AND chat_id=?`, session.BuyerID, session.BuyerName, session.BuyerAvatar,
|
||||
session.ItemID, session.ItemTitle, message.SentAt, message.Content, message.SentAt, message.SentAt, unreadDelta, now,
|
||||
session.CookieID, session.ChatID); err != nil {
|
||||
return nil, false, fmt.Errorf("更新聊天会话: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
stored, err := s.GetMessageByKey(ctx, message.CookieID, message.MessageKey)
|
||||
return stored, inserted > 0, err
|
||||
}
|
||||
|
||||
func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (*ChatMessage, error) {
|
||||
var m ChatMessage
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at
|
||||
FROM chat_messages WHERE cookie_id=? AND message_key=?`, cookieID, key).Scan(
|
||||
&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, &m.SenderName,
|
||||
&m.MessageType, &m.Content, &m.Status, &m.SentAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return &m, err
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListSessions(ctx context.Context, userID int64, cookieID string, limit int) ([]ChatSession, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 200
|
||||
}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT cs.cookie_id,cs.chat_id,cs.buyer_id,cs.buyer_name,cs.buyer_avatar_url,
|
||||
cs.item_id,cs.item_title,cs.last_message,cs.last_message_at,cs.unread_count
|
||||
FROM chat_sessions cs JOIN cookies c ON c.id=cs.cookie_id
|
||||
WHERE c.user_id=? AND cs.cookie_id=? ORDER BY cs.last_message_at DESC LIMIT ?`, userID, cookieID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []ChatSession
|
||||
for rows.Next() {
|
||||
var row ChatSession
|
||||
if err := rows.Scan(&row.CookieID, &row.ChatID, &row.BuyerID, &row.BuyerName, &row.BuyerAvatar,
|
||||
&row.ItemID, &row.ItemTitle, &row.LastMessage, &row.LastMessageAt, &row.UnreadCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, row)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, chatID string, beforeID int64, limit int) ([]ChatMessage, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.sent_at
|
||||
FROM chat_messages m JOIN cookies c ON c.id=m.cookie_id
|
||||
WHERE c.user_id=? AND m.cookie_id=? AND m.chat_id=?`
|
||||
args := []any{userID, cookieID, chatID}
|
||||
if beforeID > 0 {
|
||||
query += ` AND (m.sent_at < COALESCE((SELECT older.sent_at FROM chat_messages older WHERE older.id=? AND older.cookie_id=?), m.sent_at)
|
||||
OR (m.sent_at = COALESCE((SELECT same.sent_at FROM chat_messages same WHERE same.id=? AND same.cookie_id=?), m.sent_at) AND m.id<?))`
|
||||
args = append(args, beforeID, cookieID, beforeID, cookieID, beforeID)
|
||||
}
|
||||
query += ` ORDER BY m.sent_at DESC,m.id DESC LIMIT ?`
|
||||
args = append(args, limit)
|
||||
rows, err := s.DB.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var result []ChatMessage
|
||||
for rows.Next() {
|
||||
var m ChatMessage
|
||||
if err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID,
|
||||
&m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.SentAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, m)
|
||||
}
|
||||
// API returns chronological order while the query remains index-friendly.
|
||||
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
|
||||
result[i], result[j] = result[j], result[i]
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (s *ChatStore) MarkRead(ctx context.Context, userID int64, cookieID, chatID string) error {
|
||||
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET unread_count=0,updated_at=?
|
||||
WHERE cookie_id=? AND chat_id=? AND EXISTS(SELECT 1 FROM cookies c WHERE c.id=chat_sessions.cookie_id AND c.user_id=?)`,
|
||||
time.Now().UTC().Unix(), cookieID, chatID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*ChatMessage, error) {
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET status=? WHERE cookie_id=? AND message_key=?`, status, cookieID, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetMessageByKey(ctx, cookieID, key)
|
||||
}
|
||||
@@ -125,8 +125,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// 依次回滚 23 到 14,再整体升级。
|
||||
for i := 0; i < 10; i++ {
|
||||
// 依次回滚最新版本到 14,再整体升级。
|
||||
for i := 0; i < 12; i++ {
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -146,6 +146,11 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
if columnExists(t, d, "item_publish_batch_rows", "category_json") {
|
||||
t.Fatal("item_publish_batch_rows.category_json should be removed after migration 23 down")
|
||||
}
|
||||
for _, table := range []string{"account_task_settings", "account_task_runs", "chat_sessions", "chat_messages"} {
|
||||
if tableExists(t, d, table) {
|
||||
t.Fatalf("table should be removed after migration 24 down: %s", table)
|
||||
}
|
||||
}
|
||||
|
||||
if err := goose.Up(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("up after down: %v", err)
|
||||
@@ -164,6 +169,10 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
{"default_reply_records", "text_sent"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
{"account_task_settings", "auto_rate_enabled"},
|
||||
{"account_task_runs", "run_key"},
|
||||
{"chat_sessions", "unread_count"},
|
||||
{"chat_messages", "message_key"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE account_task_settings (
|
||||
cookie_id VARCHAR(191) PRIMARY KEY,
|
||||
auto_rate_enabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||
rate_content TEXT NOT NULL,
|
||||
auto_polish_enabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||
polish_time VARCHAR(5) NOT NULL DEFAULT '03:00',
|
||||
last_rate_scan_at BIGINT NOT NULL DEFAULT 0,
|
||||
last_polish_date VARCHAR(10) NOT NULL DEFAULT '',
|
||||
last_polish_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL,
|
||||
CONSTRAINT fk_account_task_settings_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE account_task_runs (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
run_key VARCHAR(255) NOT NULL UNIQUE,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
task_type VARCHAR(32) NOT NULL,
|
||||
target_id VARCHAR(191) NOT NULL DEFAULT '',
|
||||
run_date VARCHAR(10) NOT NULL DEFAULT '',
|
||||
status VARCHAR(24) NOT NULL,
|
||||
success_count INT NOT NULL DEFAULT 0,
|
||||
failed_count INT NOT NULL DEFAULT 0,
|
||||
error_message TEXT NOT NULL,
|
||||
next_retry_at BIGINT NOT NULL DEFAULT 0,
|
||||
started_at BIGINT NOT NULL,
|
||||
finished_at BIGINT NOT NULL DEFAULT 0,
|
||||
CONSTRAINT fk_account_task_runs_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
INDEX idx_account_task_runs_account_type (cookie_id, task_type, started_at),
|
||||
INDEX idx_account_task_runs_retry (status, next_retry_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE chat_sessions (
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
chat_id VARCHAR(191) NOT NULL,
|
||||
buyer_id VARCHAR(191) NOT NULL DEFAULT '',
|
||||
buyer_name VARCHAR(255) NOT NULL DEFAULT '',
|
||||
buyer_avatar_url TEXT NOT NULL,
|
||||
item_id VARCHAR(191) NOT NULL DEFAULT '',
|
||||
item_title VARCHAR(500) NOT NULL DEFAULT '',
|
||||
last_message TEXT NOT NULL,
|
||||
last_message_at BIGINT NOT NULL DEFAULT 0,
|
||||
unread_count INT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL,
|
||||
PRIMARY KEY (cookie_id, chat_id),
|
||||
CONSTRAINT fk_chat_sessions_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
INDEX idx_chat_sessions_account_recent (cookie_id, last_message_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE chat_messages (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
cookie_id VARCHAR(191) NOT NULL,
|
||||
chat_id VARCHAR(191) NOT NULL,
|
||||
message_key VARCHAR(255) NOT NULL,
|
||||
direction VARCHAR(16) NOT NULL,
|
||||
sender_id VARCHAR(191) NOT NULL DEFAULT '',
|
||||
sender_name VARCHAR(255) NOT NULL DEFAULT '',
|
||||
message_type VARCHAR(24) NOT NULL DEFAULT 'text',
|
||||
content TEXT NOT NULL,
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'received',
|
||||
sent_at BIGINT NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
UNIQUE KEY uq_chat_messages_account_key (cookie_id, message_key),
|
||||
CONSTRAINT fk_chat_messages_session FOREIGN KEY (cookie_id, chat_id) REFERENCES chat_sessions(cookie_id, chat_id) ON DELETE CASCADE,
|
||||
INDEX idx_chat_messages_conversation (cookie_id, chat_id, sent_at, id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS chat_messages;
|
||||
DROP TABLE IF EXISTS chat_sessions;
|
||||
DROP TABLE IF EXISTS account_task_runs;
|
||||
DROP TABLE IF EXISTS account_task_settings;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
UPDATE chat_messages SET direction='outgoing', sender_name='我'
|
||||
WHERE sender_id=cookie_id AND direction='incoming';
|
||||
UPDATE chat_sessions cs SET buyer_id=COALESCE((
|
||||
SELECT m.sender_id FROM chat_messages m
|
||||
WHERE m.cookie_id=cs.cookie_id AND m.chat_id=cs.chat_id
|
||||
AND m.direction='incoming' AND m.sender_id<>cs.cookie_id
|
||||
ORDER BY m.sent_at DESC,m.id DESC LIMIT 1
|
||||
), cs.buyer_id);
|
||||
|
||||
-- +goose Down
|
||||
-- Data repair is intentionally irreversible.
|
||||
@@ -0,0 +1,72 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE account_task_settings (
|
||||
cookie_id TEXT PRIMARY KEY REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
auto_rate_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
rate_content TEXT NOT NULL DEFAULT '不错的买家,交易愉快',
|
||||
auto_polish_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
polish_time VARCHAR(5) NOT NULL DEFAULT '03:00',
|
||||
last_rate_scan_at BIGINT NOT NULL DEFAULT 0,
|
||||
last_polish_date VARCHAR(10) NOT NULL DEFAULT '',
|
||||
last_polish_at BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE account_task_runs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
run_key TEXT NOT NULL UNIQUE,
|
||||
cookie_id TEXT NOT NULL REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
task_type VARCHAR(32) NOT NULL,
|
||||
target_id TEXT NOT NULL DEFAULT '',
|
||||
run_date VARCHAR(10) NOT NULL DEFAULT '',
|
||||
status VARCHAR(24) NOT NULL,
|
||||
success_count INTEGER NOT NULL DEFAULT 0,
|
||||
failed_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
next_retry_at BIGINT NOT NULL DEFAULT 0,
|
||||
started_at BIGINT NOT NULL,
|
||||
finished_at BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX idx_account_task_runs_account_type ON account_task_runs(cookie_id, task_type, started_at DESC);
|
||||
CREATE INDEX idx_account_task_runs_retry ON account_task_runs(status, next_retry_at);
|
||||
|
||||
CREATE TABLE chat_sessions (
|
||||
cookie_id TEXT NOT NULL REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
chat_id TEXT NOT NULL,
|
||||
buyer_id TEXT NOT NULL DEFAULT '',
|
||||
buyer_name TEXT NOT NULL DEFAULT '',
|
||||
buyer_avatar_url TEXT NOT NULL DEFAULT '',
|
||||
item_id TEXT NOT NULL DEFAULT '',
|
||||
item_title TEXT NOT NULL DEFAULT '',
|
||||
last_message TEXT NOT NULL DEFAULT '',
|
||||
last_message_at BIGINT NOT NULL DEFAULT 0,
|
||||
unread_count INTEGER NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL,
|
||||
PRIMARY KEY (cookie_id, chat_id)
|
||||
);
|
||||
CREATE INDEX idx_chat_sessions_account_recent ON chat_sessions(cookie_id, last_message_at DESC);
|
||||
|
||||
CREATE TABLE chat_messages (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
cookie_id TEXT NOT NULL,
|
||||
chat_id TEXT NOT NULL,
|
||||
message_key TEXT NOT NULL,
|
||||
direction VARCHAR(16) NOT NULL,
|
||||
sender_id TEXT NOT NULL DEFAULT '',
|
||||
sender_name TEXT NOT NULL DEFAULT '',
|
||||
message_type VARCHAR(24) NOT NULL DEFAULT 'text',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'received',
|
||||
sent_at BIGINT NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
UNIQUE (cookie_id, message_key),
|
||||
FOREIGN KEY (cookie_id, chat_id) REFERENCES chat_sessions(cookie_id, chat_id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_chat_messages_conversation ON chat_messages(cookie_id, chat_id, sent_at DESC, id DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS chat_messages;
|
||||
DROP TABLE IF EXISTS chat_sessions;
|
||||
DROP TABLE IF EXISTS account_task_runs;
|
||||
DROP TABLE IF EXISTS account_task_settings;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
UPDATE chat_messages SET direction='outgoing', sender_name='我'
|
||||
WHERE sender_id=cookie_id AND direction='incoming';
|
||||
UPDATE chat_sessions cs SET buyer_id=COALESCE((
|
||||
SELECT m.sender_id FROM chat_messages m
|
||||
WHERE m.cookie_id=cs.cookie_id AND m.chat_id=cs.chat_id
|
||||
AND m.direction='incoming' AND m.sender_id<>cs.cookie_id
|
||||
ORDER BY m.sent_at DESC,m.id DESC LIMIT 1
|
||||
), cs.buyer_id);
|
||||
|
||||
-- +goose Down
|
||||
-- Data repair is intentionally irreversible.
|
||||
@@ -0,0 +1,75 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE account_task_settings (
|
||||
cookie_id TEXT PRIMARY KEY,
|
||||
auto_rate_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
rate_content TEXT NOT NULL DEFAULT '不错的买家,交易愉快',
|
||||
auto_polish_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
polish_time TEXT NOT NULL DEFAULT '03:00',
|
||||
last_rate_scan_at INTEGER NOT NULL DEFAULT 0,
|
||||
last_polish_date TEXT NOT NULL DEFAULT '',
|
||||
last_polish_at INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE account_task_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
run_key TEXT NOT NULL UNIQUE,
|
||||
cookie_id TEXT NOT NULL,
|
||||
task_type TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL DEFAULT '',
|
||||
run_date TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL,
|
||||
success_count INTEGER NOT NULL DEFAULT 0,
|
||||
failed_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
next_retry_at INTEGER NOT NULL DEFAULT 0,
|
||||
started_at INTEGER NOT NULL,
|
||||
finished_at INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_account_task_runs_account_type ON account_task_runs(cookie_id, task_type, started_at DESC);
|
||||
CREATE INDEX idx_account_task_runs_retry ON account_task_runs(status, next_retry_at);
|
||||
|
||||
CREATE TABLE chat_sessions (
|
||||
cookie_id TEXT NOT NULL,
|
||||
chat_id TEXT NOT NULL,
|
||||
buyer_id TEXT NOT NULL DEFAULT '',
|
||||
buyer_name TEXT NOT NULL DEFAULT '',
|
||||
buyer_avatar_url TEXT NOT NULL DEFAULT '',
|
||||
item_id TEXT NOT NULL DEFAULT '',
|
||||
item_title TEXT NOT NULL DEFAULT '',
|
||||
last_message TEXT NOT NULL DEFAULT '',
|
||||
last_message_at INTEGER NOT NULL DEFAULT 0,
|
||||
unread_count INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
PRIMARY KEY (cookie_id, chat_id),
|
||||
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_chat_sessions_account_recent ON chat_sessions(cookie_id, last_message_at DESC);
|
||||
|
||||
CREATE TABLE chat_messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
cookie_id TEXT NOT NULL,
|
||||
chat_id TEXT NOT NULL,
|
||||
message_key TEXT NOT NULL,
|
||||
direction TEXT NOT NULL,
|
||||
sender_id TEXT NOT NULL DEFAULT '',
|
||||
sender_name TEXT NOT NULL DEFAULT '',
|
||||
message_type TEXT NOT NULL DEFAULT 'text',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'received',
|
||||
sent_at INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
|
||||
UNIQUE (cookie_id, message_key),
|
||||
FOREIGN KEY (cookie_id, chat_id) REFERENCES chat_sessions(cookie_id, chat_id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_chat_messages_conversation ON chat_messages(cookie_id, chat_id, sent_at DESC, id DESC);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE IF EXISTS chat_messages;
|
||||
DROP TABLE IF EXISTS chat_sessions;
|
||||
DROP TABLE IF EXISTS account_task_runs;
|
||||
DROP TABLE IF EXISTS account_task_settings;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
UPDATE chat_messages SET direction='outgoing', sender_name='我'
|
||||
WHERE sender_id=cookie_id AND direction='incoming';
|
||||
UPDATE chat_sessions SET buyer_id=COALESCE((
|
||||
SELECT m.sender_id FROM chat_messages m
|
||||
WHERE m.cookie_id=chat_sessions.cookie_id AND m.chat_id=chat_sessions.chat_id
|
||||
AND m.direction='incoming' AND m.sender_id<>chat_sessions.cookie_id
|
||||
ORDER BY m.sent_at DESC,m.id DESC LIMIT 1
|
||||
), buyer_id);
|
||||
|
||||
-- +goose Down
|
||||
-- Data repair is intentionally irreversible.
|
||||
+101
-1
@@ -771,7 +771,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
for i := 0; i < 10; i++ {
|
||||
for i := 0; i < 12; i++ {
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration down #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -791,6 +791,11 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "item_publish_batch_rows", "category_json") {
|
||||
t.Fatal("item_publish_batch_rows.category_json should be removed after down")
|
||||
}
|
||||
for _, table := range []string{"account_task_settings", "account_task_runs", "chat_sessions", "chat_messages"} {
|
||||
if tableExistsForDialect(t, tg.store.DB, tg.dialect, table) {
|
||||
t.Fatalf("table should be removed after migration 24 down: %s", table)
|
||||
}
|
||||
}
|
||||
|
||||
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration up after down: %v", err)
|
||||
@@ -811,6 +816,10 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
{"automation_runs", "action_started"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
{"account_task_settings", "auto_rate_enabled"},
|
||||
{"account_task_runs", "run_key"},
|
||||
{"chat_sessions", "unread_count"},
|
||||
{"chat_messages", "message_key"},
|
||||
} {
|
||||
if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
@@ -820,6 +829,97 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiDB_ChatAndAccountTasks(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
ctx := context.Background()
|
||||
s := tg.store
|
||||
suffix := fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
username := tg.name + "_chat_" + suffix
|
||||
if ok, err := s.Users.Create(ctx, username, username+"@e.com", "pw"); err != nil || !ok {
|
||||
t.Fatalf("create user: ok=%v err=%v", ok, err)
|
||||
}
|
||||
user, _ := s.Users.GetByUsername(ctx, username)
|
||||
cookieID := tg.name + "_chat_cookie_" + suffix
|
||||
if err := s.Cookies.Save(ctx, cookieID, "unb=1; _m_h5_tk=token_1", user.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
settings, err := s.AccountTasks.Get(ctx, cookieID)
|
||||
if err != nil || settings.RateContent == "" || settings.PolishTime != "03:00" {
|
||||
t.Fatalf("default settings=%+v err=%v", settings, err)
|
||||
}
|
||||
settings.AutoRateEnabled = true
|
||||
settings.AutoPolishEnabled = true
|
||||
settings.RateContent = "交易愉快"
|
||||
settings.PolishTime = "04:30"
|
||||
if err := s.AccountTasks.Upsert(ctx, settings); err != nil {
|
||||
t.Fatalf("upsert settings: %v", err)
|
||||
}
|
||||
stored, err := s.AccountTasks.Get(ctx, cookieID)
|
||||
if err != nil || !stored.AutoRateEnabled || !stored.AutoPolishEnabled || stored.RateContent != "交易愉快" || stored.PolishTime != "04:30" {
|
||||
t.Fatalf("stored settings=%+v err=%v", stored, err)
|
||||
}
|
||||
enabled, err := s.AccountTasks.Enabled(ctx)
|
||||
if err != nil || len(enabled) != 1 {
|
||||
t.Fatalf("enabled=%+v err=%v", enabled, err)
|
||||
}
|
||||
|
||||
run := AccountTaskRun{RunKey: "rate:" + cookieID + ":order-1", CookieID: cookieID, TaskType: "auto_rate", TargetID: "order-1"}
|
||||
if claimed, err := s.AccountTasks.ClaimRun(ctx, run, 100); err != nil || !claimed {
|
||||
t.Fatalf("first claim=%v err=%v", claimed, err)
|
||||
}
|
||||
if claimed, err := s.AccountTasks.ClaimRun(ctx, run, 100); err != nil || claimed {
|
||||
t.Fatalf("duplicate claim=%v err=%v", claimed, err)
|
||||
}
|
||||
if err := s.AccountTasks.FinishRun(ctx, run.RunKey, "failed", 0, 1, "retry", 200); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claimed, err := s.AccountTasks.ClaimRun(ctx, run, 199); err != nil || claimed {
|
||||
t.Fatalf("early retry claim=%v err=%v", claimed, err)
|
||||
}
|
||||
if claimed, err := s.AccountTasks.ClaimRunImmediately(ctx, run, 199); err != nil || !claimed {
|
||||
t.Fatalf("manual retry claim=%v err=%v", claimed, err)
|
||||
}
|
||||
if err := s.AccountTasks.FinishRun(ctx, run.RunKey, "failed", 0, 1, "retry", 200); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claimed, err := s.AccountTasks.ClaimRun(ctx, run, 200); err != nil || !claimed {
|
||||
t.Fatalf("due retry claim=%v err=%v", claimed, err)
|
||||
}
|
||||
|
||||
session := ChatSession{CookieID: cookieID, ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲", ItemID: "item-1"}
|
||||
incoming := ChatMessage{MessageKey: "platform-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家甲", MessageType: "text", Content: "你好", Status: "received", SentAt: 1000}
|
||||
if _, inserted, err := s.Chats.SaveMessage(ctx, session, incoming, true); err != nil || !inserted {
|
||||
t.Fatalf("save incoming inserted=%v err=%v", inserted, err)
|
||||
}
|
||||
if _, inserted, err := s.Chats.SaveMessage(ctx, session, incoming, true); err != nil || inserted {
|
||||
t.Fatalf("duplicate incoming inserted=%v err=%v", inserted, err)
|
||||
}
|
||||
outgoing := ChatMessage{MessageKey: "local-1", Direction: "outgoing", SenderID: cookieID, SenderName: "我", MessageType: "text", Content: "您好", Status: "sent", SentAt: 2000}
|
||||
if _, inserted, err := s.Chats.SaveMessage(ctx, session, outgoing, false); err != nil || !inserted {
|
||||
t.Fatalf("save outgoing inserted=%v err=%v", inserted, err)
|
||||
}
|
||||
sessions, err := s.Chats.ListSessions(ctx, user.ID, cookieID, 20)
|
||||
if err != nil || len(sessions) != 1 || sessions[0].UnreadCount != 1 || sessions[0].LastMessage != "您好" {
|
||||
t.Fatalf("sessions=%+v err=%v", sessions, err)
|
||||
}
|
||||
messages, err := s.Chats.ListMessages(ctx, user.ID, cookieID, "chat-1", 0, 20)
|
||||
if err != nil || len(messages) != 2 || messages[0].Content != "你好" || messages[1].Content != "您好" {
|
||||
t.Fatalf("messages=%+v err=%v", messages, err)
|
||||
}
|
||||
if err := s.Chats.MarkRead(ctx, user.ID, cookieID, "chat-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sessions, _ = s.Chats.ListSessions(ctx, user.ID, cookieID, 20)
|
||||
if sessions[0].UnreadCount != 0 {
|
||||
t.Fatalf("unread after mark=%d", sessions[0].UnreadCount)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_CardsCreateGet 验证 cards Create + Get 的 NULL 列扫描(含 nullable 字段)。
|
||||
func TestMultiDB_CardsCreateGet(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
|
||||
@@ -28,6 +28,8 @@ type Store struct {
|
||||
Renewal *RenewalStore
|
||||
LoginLogs *AccountLoginLogs
|
||||
RiskLogs *RiskControlLogs
|
||||
Chats *ChatStore
|
||||
AccountTasks *AccountTaskStore
|
||||
|
||||
credentialMu sync.Mutex
|
||||
credentialLocks map[string]*sync.Mutex
|
||||
@@ -58,6 +60,8 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
Renewal: &RenewalStore{DB: db, Dialect: dialect},
|
||||
LoginLogs: &AccountLoginLogs{DB: db},
|
||||
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
|
||||
Chats: &ChatStore{DB: db, Dialect: dialect},
|
||||
AccountTasks: &AccountTaskStore{DB: db, Dialect: dialect},
|
||||
credentialLocks: make(map[string]*sync.Mutex),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ package engine
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@@ -124,6 +125,29 @@ type ChatMessage struct {
|
||||
Raw map[string]any // 解密后的完整消息
|
||||
}
|
||||
|
||||
// OutgoingChatMessage is emitted after the existing account WebSocket has
|
||||
// accepted a text message. It is an observation hook only; persistence errors
|
||||
// never change the delivery result.
|
||||
type OutgoingChatMessage struct {
|
||||
AccountID string
|
||||
ChatID string
|
||||
BuyerID string
|
||||
Text string
|
||||
MessageKey string
|
||||
}
|
||||
|
||||
type outgoingChatHandler interface {
|
||||
HandleOutgoingChatMessage(ctx context.Context, message OutgoingChatMessage) error
|
||||
}
|
||||
|
||||
type outgoingMessageKeyContextKey struct{}
|
||||
|
||||
// WithOutgoingMessageKey correlates a UI-created pending message with the
|
||||
// post-send observer so the same text is not inserted twice.
|
||||
func WithOutgoingMessageKey(ctx context.Context, key string) context.Context {
|
||||
return context.WithValue(ctx, outgoingMessageKeyContextKey{}, strings.TrimSpace(key))
|
||||
}
|
||||
|
||||
// RuntimeStatus 是账号引擎的实时连接状态,不写入数据库。
|
||||
type RuntimeStatus struct {
|
||||
State string `json:"state"`
|
||||
@@ -192,6 +216,7 @@ type Account struct {
|
||||
tokenAcquiredAt time.Time
|
||||
tokenExpiresAt time.Time
|
||||
tokenRefreshAt time.Time
|
||||
tokenFingerprint string // 仅用于诊断,不保存原始 Token
|
||||
|
||||
// 去重
|
||||
dedupMu sync.Mutex
|
||||
@@ -1539,12 +1564,15 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri
|
||||
}
|
||||
now := time.Now()
|
||||
expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now)
|
||||
tokenFP := tokenFingerprint(accessToken)
|
||||
a.mu.Lock()
|
||||
previousTokenFP := a.tokenFingerprint
|
||||
a.tokenFingerprint = tokenFP
|
||||
a.tokenAcquiredAt = now
|
||||
a.tokenExpiresAt = expiresAt
|
||||
a.tokenRefreshAt = refreshAt
|
||||
a.mu.Unlock()
|
||||
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second))
|
||||
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP)
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
@@ -1561,8 +1589,18 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri
|
||||
}
|
||||
}
|
||||
|
||||
// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token,
|
||||
// 同时避免日志泄露可用于 WS 注册的凭证原文。
|
||||
func tokenFingerprint(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return fmt.Sprintf("%x", sum[:6])
|
||||
}
|
||||
|
||||
// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。
|
||||
func (a *Account) clearTokenCache(ctx context.Context) {
|
||||
a.mu.Lock()
|
||||
a.tokenFingerprint = ""
|
||||
a.mu.Unlock()
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
@@ -1737,7 +1775,18 @@ func (a *Account) SendText(ctx context.Context, chatID, toUserID, text string) e
|
||||
}
|
||||
sendCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
return conn.SendText(sendCtx, myID, chatID, toUserID, text)
|
||||
if err := conn.SendText(sendCtx, myID, chatID, toUserID, text); err != nil {
|
||||
return err
|
||||
}
|
||||
if observer, ok := a.handler.(outgoingChatHandler); ok {
|
||||
key, _ := ctx.Value(outgoingMessageKeyContextKey{}).(string)
|
||||
if err := observer.HandleOutgoingChatMessage(ctx, OutgoingChatMessage{
|
||||
AccountID: a.CookieID, ChatID: chatID, BuyerID: toUserID, Text: text, MessageKey: key,
|
||||
}); err != nil {
|
||||
a.logger.Warn("保存出站聊天旁路失败", "account", a.CookieID, "chat_id", chatID, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendImage 通过当前 WebSocket 给买家发送图片消息。当前仅支持可直接访问的 CDN/公网 URL。
|
||||
@@ -1774,6 +1823,39 @@ func (a *Account) currentSenderState() (WSConn, string, error) {
|
||||
return a.conn, myID, nil
|
||||
}
|
||||
|
||||
// FetchChatHistory reuses the account's registered IM connection. Keeping this
|
||||
// optional capability outside WSConn avoids forcing non-chat test transports to
|
||||
// implement history retrieval.
|
||||
func (a *Account) FetchChatHistory(ctx context.Context, chatID string, cursor int64, limit int) (map[string]any, string, error) {
|
||||
conn, myID, err := a.currentSenderState()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
history, ok := conn.(interface {
|
||||
ListUserMessages(context.Context, string, int64, int) (map[string]any, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, "", errors.New("当前 WebSocket 连接不支持聊天历史")
|
||||
}
|
||||
body, err := history.ListUserMessages(ctx, chatID, cursor, limit)
|
||||
return body, myID, err
|
||||
}
|
||||
|
||||
func (a *Account) FetchChatConversations(ctx context.Context, cursor int64, limit int) (map[string]any, string, error) {
|
||||
conn, myID, err := a.currentSenderState()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
fetcher, ok := conn.(interface {
|
||||
ListConversations(context.Context, int64, int) (map[string]any, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, "", errors.New("当前 WebSocket 连接不支持历史会话")
|
||||
}
|
||||
body, err := fetcher.ListConversations(ctx, cursor, limit)
|
||||
return body, myID, err
|
||||
}
|
||||
|
||||
// AutomationReady 报告自动化消息是否可以立即使用当前 WS 连接发送。
|
||||
func (a *Account) AutomationReady() bool {
|
||||
a.mu.Lock()
|
||||
|
||||
@@ -243,6 +243,9 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
}
|
||||
senderUserID, _ := m10["senderUserId"].(string)
|
||||
senderName, _ := m10["senderNick"].(string)
|
||||
if strings.TrimSpace(senderName) == "" {
|
||||
senderName, _ = m10["reminderTitle"].(string)
|
||||
}
|
||||
reminderURL, _ := m10["reminderUrl"].(string)
|
||||
itemID := extractItemID(reminderURL)
|
||||
return &ChatMessage{
|
||||
@@ -263,6 +266,9 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
// - contentType=26:交易卡片,如“我已拍下,待付款”“我发起了退款申请”
|
||||
// 付款待发货卡片已经在 handleMessage 前半段进入 automation.Center,这里不能再进入聊天回复链。
|
||||
func isNonUserChatNotice(m1, m10 map[string]any, reminder string) bool {
|
||||
if sessionType := strings.TrimSpace(toString(m10["sessionType"])); sessionType != "" && sessionType != "1" {
|
||||
return true
|
||||
}
|
||||
contentType := messageContentType(m1, m10)
|
||||
switch contentType {
|
||||
case "14":
|
||||
|
||||
@@ -91,6 +91,17 @@ func TestExtractChatMessage_FiltersContentType14Notice(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractChatMessageUsesReminderTitleAsNickname(t *testing.T) {
|
||||
decrypted := map[string]any{"1": map[string]any{
|
||||
"2": "chat-1@goofish",
|
||||
"10": map[string]any{"reminderContent": "你好", "reminderTitle": "真实昵称", "senderUserId": "buyer-1", "sessionType": "1"},
|
||||
}}
|
||||
chat := extractChatMessage(decrypted, "account-1", "cookie")
|
||||
if chat == nil || chat.SenderName != "真实昵称" {
|
||||
t.Fatalf("chat=%+v", chat)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) {
|
||||
decrypted := mustRefundTradeCard(t)
|
||||
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
)
|
||||
|
||||
type outgoingObserverHandler struct {
|
||||
messages []OutgoingChatMessage
|
||||
}
|
||||
|
||||
func (h *outgoingObserverHandler) HandleChatMessage(context.Context, ChatMessage) error { return nil }
|
||||
func (h *outgoingObserverHandler) HandleSystemEvent(context.Context, automation.Task) error {
|
||||
return nil
|
||||
}
|
||||
func (h *outgoingObserverHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
|
||||
func (h *outgoingObserverHandler) OnAccountAlert(context.Context, string, string, string, string) {}
|
||||
func (h *outgoingObserverHandler) HandleOutgoingChatMessage(_ context.Context, message OutgoingChatMessage) error {
|
||||
h.messages = append(h.messages, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestSendTextEmitsCorrelatedOutgoingObservation(t *testing.T) {
|
||||
handler := &outgoingObserverHandler{}
|
||||
account := New(Config{CookieID: "account-1", CookieStr: "unb=me", Handler: handler})
|
||||
conn := &fakeWSConn{}
|
||||
account.mu.Lock()
|
||||
account.conn = conn
|
||||
account.mu.Unlock()
|
||||
ctx := WithOutgoingMessageKey(context.Background(), "local-1")
|
||||
if err := account.SendText(ctx, "chat-1", "buyer-1", "您好"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(handler.messages) != 1 {
|
||||
t.Fatalf("messages=%+v", handler.messages)
|
||||
}
|
||||
got := handler.messages[0]
|
||||
if got.AccountID != "account-1" || got.ChatID != "chat-1" || got.BuyerID != "buyer-1" || got.Text != "您好" || got.MessageKey != "local-1" {
|
||||
t.Fatalf("observation=%+v", got)
|
||||
}
|
||||
}
|
||||
@@ -282,6 +282,9 @@ func TestIsNonUserChatNotice(t *testing.T) {
|
||||
if isNonUserChatNotice(map[string]any{}, map[string]any{}, "[买家说你好]") {
|
||||
t.Error("普通消息不应判为系统提示")
|
||||
}
|
||||
if !isNonUserChatNotice(map[string]any{}, map[string]any{"sessionType": "24"}, "售后问卷") {
|
||||
t.Error("非真人会话不应进入买家聊天列表")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToStringAndTrimFloatInt 数字/字符串安全转换。
|
||||
|
||||
@@ -76,3 +76,19 @@ func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) {
|
||||
t.Fatal("权威空 Jar 必须与没有快照的历史状态区分")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenFingerprintIsStableNonReversibleDiagnosticID(t *testing.T) {
|
||||
first := tokenFingerprint("access-token-a")
|
||||
if first == "" || len(first) != 12 {
|
||||
t.Fatalf("token fingerprint=%q, want 12 hex chars", first)
|
||||
}
|
||||
if first != tokenFingerprint("access-token-a") {
|
||||
t.Fatal("same token must produce stable fingerprint")
|
||||
}
|
||||
if first == tokenFingerprint("access-token-b") {
|
||||
t.Fatal("different tokens must produce different fingerprints")
|
||||
}
|
||||
if first == "access-token-a" {
|
||||
t.Fatal("fingerprint must not expose the token")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
var accountTaskTimePattern = regexp.MustCompile(`^(?:[01]\d|2[0-3]):[0-5]\d$`)
|
||||
|
||||
func (s *Server) mountAccountTasks(r chi.Router) {
|
||||
r.Get("/api/account-tasks/{cid}", s.getAccountTaskSettings)
|
||||
r.Put("/api/account-tasks/{cid}", s.updateAccountTaskSettings)
|
||||
r.Get("/api/account-tasks/{cid}/runs", s.listAccountTaskRuns)
|
||||
r.Post("/api/account-tasks/{cid}/run", s.runAccountTask)
|
||||
}
|
||||
|
||||
func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
settings, err := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, settings)
|
||||
}
|
||||
|
||||
func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
var input db.AccountTaskSettings
|
||||
if decodeJSON(r, &input) != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
input.CookieID = cid
|
||||
input.RateContent = strings.TrimSpace(input.RateContent)
|
||||
if input.AutoRateEnabled && input.RateContent == "" {
|
||||
writeErr(w, http.StatusBadRequest, "启用自动评价时评价内容不能为空")
|
||||
return
|
||||
}
|
||||
if len([]rune(input.RateContent)) > 500 {
|
||||
writeErr(w, http.StatusBadRequest, "评价内容不能超过 500 个字符")
|
||||
return
|
||||
}
|
||||
if !accountTaskTimePattern.MatchString(input.PolishTime) {
|
||||
writeErr(w, http.StatusBadRequest, "擦亮时间格式必须为 HH:mm")
|
||||
return
|
||||
}
|
||||
if err := s.Store.AccountTasks.Upsert(r.Context(), input); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号任务配置失败")
|
||||
return
|
||||
}
|
||||
stored, _ := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
writeJSON(w, http.StatusOK, stored)
|
||||
}
|
||||
|
||||
func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
runs, err := s.Store.AccountTasks.RecentRuns(r.Context(), cid, parsePositiveInt(r.URL.Query().Get("limit"), 20))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取任务记录失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"runs": runs})
|
||||
}
|
||||
|
||||
func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.ownsAccount(r, cid) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
if s.automation == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "自动化中心未启用")
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
TaskType string `json:"task_type"`
|
||||
}
|
||||
if decodeJSON(r, &input) != nil || (input.TaskType != automation.TaskAutoRate && input.TaskType != automation.TaskAutoPolish) {
|
||||
writeErr(w, http.StatusBadRequest, "不支持的任务类型")
|
||||
return
|
||||
}
|
||||
summary, err := s.automation.RunAccountTask(r.Context(), cid, input.TaskType)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"summary": summary, "error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "summary": summary})
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
service := chat.New(store)
|
||||
srv.SetChatService(service)
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
|
||||
_, _, err := store.Chats.SaveMessage(context.Background(), db.ChatSession{CookieID: "acc1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲"},
|
||||
db.ChatMessage{MessageKey: "platform-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家甲", MessageType: "text", Content: "你好", Status: "received", SentAt: 1000}, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/chat/sessions?account_id=acc1", nil)
|
||||
request.AddCookie(cookie)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "买家甲") {
|
||||
t.Fatalf("sessions status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodGet, "/api/chat/messages?account_id=acc1&chat_id=chat-1", nil)
|
||||
request.AddCookie(cookie)
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "你好") {
|
||||
t.Fatalf("messages status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
|
||||
request = httptest.NewRequest(http.MethodPut, "/api/account-tasks/acc1", strings.NewReader(`{
|
||||
"auto_rate_enabled":true,"rate_content":"交易愉快","auto_polish_enabled":true,"polish_time":"04:30"
|
||||
}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "交易愉快") {
|
||||
t.Fatalf("task settings status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
settings, err := store.AccountTasks.Get(context.Background(), "acc1")
|
||||
if err != nil || !settings.AutoRateEnabled || !settings.AutoPolishEnabled || settings.PolishTime != "04:30" {
|
||||
t.Fatalf("settings=%+v err=%v", settings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
service := chat.New(store)
|
||||
srv.SetChatService(service)
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
httpServer := httptest.NewServer(handler)
|
||||
defer httpServer.Close()
|
||||
|
||||
header := make(http.Header)
|
||||
header.Set("Cookie", cookie.String())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/chat/ws", &websocket.DialOptions{HTTPHeader: header})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
|
||||
var ready map[string]any
|
||||
if err := wsjson.Read(ctx, conn, &ready); err != nil || ready["type"] != "ready" {
|
||||
t.Fatalf("ready=%+v err=%v", ready, err)
|
||||
}
|
||||
if _, _, err := service.RecordIncoming(ctx, chat.Incoming{AccountID: "acc1", ChatID: "chat-live", BuyerID: "buyer",
|
||||
BuyerName: "实时买家", Text: "实时消息", Raw: map[string]any{"messageId": "live-1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var event chat.Event
|
||||
if err := wsjson.Read(ctx, conn, &event); err != nil || event.Type != "message.created" || event.Message.Content != "实时消息" {
|
||||
t.Fatalf("event=%+v err=%v", event, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.SetChatService(chat.New(srv.Store))
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
|
||||
cases := []struct {
|
||||
method, path, body string
|
||||
want int
|
||||
}{
|
||||
{http.MethodGet, "/api/chat/sessions?account_id=missing", "", http.StatusForbidden},
|
||||
{http.MethodGet, "/api/chat/messages?account_id=acc1", "", http.StatusBadRequest},
|
||||
{http.MethodPut, "/api/account-tasks/acc1", `{"auto_rate_enabled":true,"rate_content":"","auto_polish_enabled":false,"polish_time":"03:00"}`, http.StatusBadRequest},
|
||||
{http.MethodPut, "/api/account-tasks/acc1", `{"auto_rate_enabled":false,"rate_content":"x","auto_polish_enabled":true,"polish_time":"25:99"}`, http.StatusBadRequest},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
request := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(cookie)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != tc.want {
|
||||
t.Errorf("%s %s status=%d want=%d body=%s", tc.method, tc.path, recorder.Code, tc.want, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
func (s *Server) mountChat(r chi.Router) {
|
||||
r.Get("/api/chat/sessions", s.listChatSessions)
|
||||
r.Get("/api/chat/messages", s.listChatMessages)
|
||||
r.Post("/api/chat/messages", s.sendChatMessage)
|
||||
r.Post("/api/chat/images", s.sendChatImage)
|
||||
r.Post("/api/chat/read", s.markChatRead)
|
||||
r.Get("/api/chat/ws", s.chatWebSocket)
|
||||
}
|
||||
|
||||
func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
|
||||
if !s.ownsAccount(r, accountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
|
||||
refresh := r.URL.Query().Get("refresh") == "1"
|
||||
var hasMore bool
|
||||
var nextCursor int64
|
||||
if err := s.Store.Chats.DeleteEmptySessions(r.Context(), accountID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "清理无效聊天会话失败")
|
||||
return
|
||||
}
|
||||
if refresh && s.chat != nil && s.Manager != nil {
|
||||
if sender, ok := s.Manager.GetInstance(accountID); ok {
|
||||
if fetcher, ok := sender.(interface {
|
||||
FetchChatConversations(context.Context, int64, int) (map[string]any, string, error)
|
||||
}); ok {
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
body, myID, fetchErr := fetcher.FetchChatConversations(fetchCtx, cursor, 100)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
page, saveErr := s.chat.RecordConversationPage(r.Context(), accountID, myID, body)
|
||||
if saveErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存历史联系人失败")
|
||||
return
|
||||
}
|
||||
hasMore, nextCursor = page.HasMore, page.NextCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rows, err := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, parsePositiveInt(r.URL.Query().Get("limit"), 200))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取聊天会话失败")
|
||||
return
|
||||
}
|
||||
if refresh {
|
||||
if cookieValue, cookieErr := s.Store.Cookies.GetValue(r.Context(), accountID); cookieErr == nil {
|
||||
client, canResolve := s.mtopClient().(interface {
|
||||
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
|
||||
})
|
||||
if !canResolve {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"sessions": rows, "has_more": hasMore, "next_cursor": nextCursor})
|
||||
return
|
||||
}
|
||||
resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
defer resolveCancel()
|
||||
jobs := make(chan int)
|
||||
var workers sync.WaitGroup
|
||||
for worker := 0; worker < 8; worker++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
for index := range jobs {
|
||||
infoCtx, cancel := context.WithTimeout(resolveCtx, 3*time.Second)
|
||||
info, infoErr := client.FetchChatUserInfo(infoCtx, cookieValue, rows[index].ChatID)
|
||||
cancel()
|
||||
if infoErr != nil || info == nil {
|
||||
continue
|
||||
}
|
||||
if nickname := strings.TrimSpace(info.Nickname); nickname != "" {
|
||||
rows[index].BuyerName = nickname
|
||||
}
|
||||
if info.AvatarURL != "" {
|
||||
rows[index].BuyerAvatar = info.AvatarURL
|
||||
}
|
||||
_ = s.Store.Chats.UpdateSessionIdentity(resolveCtx, accountID, rows[index].ChatID,
|
||||
rows[index].BuyerID, rows[index].BuyerName, rows[index].BuyerAvatar)
|
||||
}
|
||||
}()
|
||||
}
|
||||
queue:
|
||||
for index := range rows {
|
||||
if rows[index].BuyerID == "1400" {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case jobs <- index:
|
||||
case <-resolveCtx.Done():
|
||||
break queue
|
||||
}
|
||||
}
|
||||
close(jobs)
|
||||
workers.Wait()
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"sessions": rows, "has_more": hasMore, "next_cursor": nextCursor})
|
||||
}
|
||||
|
||||
func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
|
||||
if err := r.ParseMultipartForm(10 << 20); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
|
||||
return
|
||||
}
|
||||
accountID := strings.TrimSpace(r.FormValue("account_id"))
|
||||
chatID := strings.TrimSpace(r.FormValue("chat_id"))
|
||||
buyerID := strings.TrimSpace(r.FormValue("buyer_id"))
|
||||
if !s.ownsAccount(r, accountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
if chatID == "" || buyerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "会话和买家不能为空")
|
||||
return
|
||||
}
|
||||
file, header, err := r.FormFile("image")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请选择图片")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
if !strings.HasPrefix(strings.ToLower(contentType), "image/") {
|
||||
writeErr(w, http.StatusBadRequest, "只支持图片文件")
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, (10<<20)+1))
|
||||
if err != nil || len(data) == 0 || len(data) > 10<<20 {
|
||||
writeErr(w, http.StatusBadRequest, "图片不能为空且不能超过 10MB")
|
||||
return
|
||||
}
|
||||
sender, ok := s.Manager.GetInstance(accountID)
|
||||
if !ok || sender == nil {
|
||||
writeErr(w, http.StatusConflict, "账号当前离线,无法发送图片")
|
||||
return
|
||||
}
|
||||
cookies, err := s.Store.Cookies.GetValue(r.Context(), accountID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号凭证失败")
|
||||
return
|
||||
}
|
||||
uploader, ok := s.mtopClient().(interface {
|
||||
UploadChatImage(context.Context, string, string, string, []byte) (*mtop.ChatImageUpload, error)
|
||||
})
|
||||
if !ok {
|
||||
writeErr(w, http.StatusServiceUnavailable, "图片上传服务未启用")
|
||||
return
|
||||
}
|
||||
upload, err := uploader.UploadChatImage(r.Context(), cookies, header.Filename, contentType, data)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, "图片上传到闲鱼失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
if upload.UpdatedCookies != "" && upload.UpdatedCookies != cookies {
|
||||
_ = s.Store.Cookies.UpdateValueExisting(r.Context(), accountID, upload.UpdatedCookies)
|
||||
sender.UpdateCookie(upload.UpdatedCookies)
|
||||
}
|
||||
session := db.ChatSession{CookieID: accountID, ChatID: chatID, BuyerID: buyerID,
|
||||
BuyerName: r.FormValue("buyer_name"), BuyerAvatar: r.FormValue("buyer_avatar_url"),
|
||||
ItemID: r.FormValue("item_id"), ItemTitle: r.FormValue("item_title")}
|
||||
message, err := s.chat.CreateOutgoingMedia(r.Context(), session, "image", upload.URL)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存待发送图片失败")
|
||||
return
|
||||
}
|
||||
if err := sender.SendImage(engine.WithOutgoingMessageKey(r.Context(), message.MessageKey), chatID, buyerID, upload.URL, 0); err != nil {
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), accountID, message.MessageKey, "failed")
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "图片发送失败,请重试"})
|
||||
return
|
||||
}
|
||||
sent, err := s.chat.SetOutgoingStatus(r.Context(), accountID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "图片已发送,但状态保存失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"message": sent})
|
||||
}
|
||||
|
||||
func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
accountID := strings.TrimSpace(r.URL.Query().Get("account_id"))
|
||||
chatID := strings.TrimSpace(r.URL.Query().Get("chat_id"))
|
||||
if !s.ownsAccount(r, accountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权访问该账号")
|
||||
return
|
||||
}
|
||||
if chatID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "缺少 chat_id")
|
||||
return
|
||||
}
|
||||
beforeID, _ := strconv.ParseInt(r.URL.Query().Get("before_id"), 10, 64)
|
||||
cursor, _ := strconv.ParseInt(r.URL.Query().Get("cursor"), 10, 64)
|
||||
limit := parsePositiveInt(r.URL.Query().Get("limit"), 50)
|
||||
if s.chat != nil && s.Manager != nil {
|
||||
if sender, ok := s.Manager.GetInstance(accountID); ok {
|
||||
if fetcher, ok := sender.(interface {
|
||||
FetchChatHistory(context.Context, string, int64, int) (map[string]any, string, error)
|
||||
}); ok {
|
||||
fetchCtx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
body, myID, fetchErr := fetcher.FetchChatHistory(fetchCtx, chatID, cursor, limit)
|
||||
cancel()
|
||||
if fetchErr == nil {
|
||||
sessions, _ := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500)
|
||||
var current db.ChatSession
|
||||
for _, candidate := range sessions {
|
||||
if candidate.ChatID == chatID {
|
||||
current = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
page, saveErr := s.chat.RecordHistoryPage(r.Context(), accountID, chatID, myID, current, body)
|
||||
if saveErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存聊天历史失败")
|
||||
return
|
||||
}
|
||||
current = s.resolveSelectedChatIdentity(r.Context(), accountID, current)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"messages": page.Messages, "has_more": page.HasMore, "next_cursor": page.NextCursor, "session": current})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rows, err := s.Store.Chats.ListMessages(r.Context(), sess.UserID, accountID, chatID, beforeID,
|
||||
limit)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取聊天消息失败")
|
||||
return
|
||||
}
|
||||
var current db.ChatSession
|
||||
if sessions, sessionErr := s.Store.Chats.ListSessions(r.Context(), sess.UserID, accountID, 500); sessionErr == nil {
|
||||
for _, candidate := range sessions {
|
||||
if candidate.ChatID == chatID {
|
||||
current = s.resolveSelectedChatIdentity(r.Context(), accountID, candidate)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"messages": rows, "has_more": len(rows) == limit, "session": current})
|
||||
}
|
||||
|
||||
func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID string, session db.ChatSession) db.ChatSession {
|
||||
if session.BuyerID != "1400" {
|
||||
cookies, cookieErr := s.Store.Cookies.GetValue(ctx, accountID)
|
||||
client, supported := s.mtopClient().(interface {
|
||||
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
|
||||
})
|
||||
if cookieErr == nil && supported {
|
||||
resolveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
info, err := client.FetchChatUserInfo(resolveCtx, cookies, session.ChatID)
|
||||
cancel()
|
||||
if err == nil && info != nil {
|
||||
if nickname := strings.TrimSpace(info.Nickname); nickname != "" {
|
||||
session.BuyerName = nickname
|
||||
}
|
||||
if info.AvatarURL != "" {
|
||||
session.BuyerAvatar = info.AvatarURL
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = s.Store.Chats.UpdateSessionIdentity(ctx, accountID, session.ChatID, session.BuyerID, session.BuyerName, session.BuyerAvatar)
|
||||
return session
|
||||
}
|
||||
|
||||
type sendChatMessageRequest struct {
|
||||
AccountID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
BuyerID string `json:"buyer_id"`
|
||||
BuyerName string `json:"buyer_name"`
|
||||
ItemID string `json:"item_id"`
|
||||
ItemTitle string `json:"item_title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil || s.Manager == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
var input sendChatMessageRequest
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
input.AccountID, input.ChatID, input.BuyerID = strings.TrimSpace(input.AccountID), strings.TrimSpace(input.ChatID), strings.TrimSpace(input.BuyerID)
|
||||
input.Text = strings.TrimSpace(input.Text)
|
||||
if !s.ownsAccount(r, input.AccountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
if input.ChatID == "" || input.BuyerID == "" || input.Text == "" {
|
||||
writeErr(w, http.StatusBadRequest, "会话、买家和消息内容不能为空")
|
||||
return
|
||||
}
|
||||
if len([]rune(input.Text)) > 2000 {
|
||||
writeErr(w, http.StatusBadRequest, "消息不能超过 2000 个字符")
|
||||
return
|
||||
}
|
||||
sender, ok := s.Manager.GetInstance(input.AccountID)
|
||||
if !ok || sender == nil {
|
||||
writeErr(w, http.StatusConflict, "账号当前离线,无法发送消息")
|
||||
return
|
||||
}
|
||||
message, err := s.chat.CreateOutgoing(r.Context(), db.ChatSession{CookieID: input.AccountID, ChatID: input.ChatID,
|
||||
BuyerID: input.BuyerID, BuyerName: input.BuyerName, ItemID: input.ItemID, ItemTitle: input.ItemTitle}, input.Text)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存待发送消息失败")
|
||||
return
|
||||
}
|
||||
sendContext := engine.WithOutgoingMessageKey(r.Context(), message.MessageKey)
|
||||
if err := sender.SendText(sendContext, input.ChatID, input.BuyerID, input.Text); err != nil {
|
||||
failed, _ := s.chat.SetOutgoingStatus(context.Background(), input.AccountID, message.MessageKey, "failed")
|
||||
writeJSON(w, http.StatusBadGateway, map[string]any{"message": failed, "error": "发送失败,请重试"})
|
||||
return
|
||||
}
|
||||
sent, err := s.chat.SetOutgoingStatus(r.Context(), input.AccountID, message.MessageKey, "sent")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "消息已发送,但状态保存失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"message": sent})
|
||||
}
|
||||
|
||||
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
AccountID string `json:"account_id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
if decodeJSON(r, &input) != nil || input.ChatID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if !s.ownsAccount(r, input.AccountID) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该账号")
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if err := s.Store.Chats.MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
if s.chat == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
events, unsubscribe, err := s.chat.Subscribe(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "订阅聊天消息失败")
|
||||
return
|
||||
}
|
||||
defer unsubscribe()
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.Close(websocket.StatusNormalClosure, "") }()
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
conn.SetReadLimit(8 << 10)
|
||||
go func() {
|
||||
for {
|
||||
if _, _, readErr := conn.Read(ctx); readErr != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
if err := wsjson.Write(ctx, conn, map[string]any{"type": "ready", "at": time.Now().UTC().UnixMilli()}); err != nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case event, ok := <-events:
|
||||
if !ok || wsjson.Write(ctx, conn, event) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) ownsAccount(r *http.Request, accountID string) bool {
|
||||
if accountID == "" {
|
||||
return false
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
accounts, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
_, ok := accounts[accountID]
|
||||
return ok
|
||||
}
|
||||
|
||||
func parsePositiveInt(raw string, fallback int) int {
|
||||
value, err := strconv.Atoi(raw)
|
||||
if err != nil || value <= 0 {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -381,23 +381,31 @@ func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil || d == nil {
|
||||
continue
|
||||
}
|
||||
tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
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,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"ai_enabled": false,
|
||||
"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,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"ai_enabled": false,
|
||||
"auto_rate_enabled": tasks.AutoRateEnabled,
|
||||
"rate_content": tasks.RateContent,
|
||||
"auto_polish_enabled": tasks.AutoPolishEnabled,
|
||||
"polish_time": tasks.PolishTime,
|
||||
"last_rate_scan_at": tasks.LastRateScanAt,
|
||||
"last_polish_date": tasks.LastPolishDate,
|
||||
"last_polish_at": tasks.LastPolishAt,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
@@ -417,22 +425,30 @@ func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
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,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"has_cookie": true,
|
||||
"id": d.ID,
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), cid),
|
||||
"auto_confirm": d.AutoConfirm,
|
||||
"remark": d.Remark,
|
||||
"pause_duration": d.PauseDuration,
|
||||
"paused_until": d.PausedUntil,
|
||||
"paused": d.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": d.ShowBrowser,
|
||||
"username": d.Username,
|
||||
"nickname": cachedAccountNickname(d),
|
||||
"avatar_url": d.AvatarURL,
|
||||
"login_method": d.LoginMethod,
|
||||
"last_login_at": d.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"has_cookie": true,
|
||||
"auto_rate_enabled": tasks.AutoRateEnabled,
|
||||
"rate_content": tasks.RateContent,
|
||||
"auto_polish_enabled": tasks.AutoPolishEnabled,
|
||||
"polish_time": tasks.PolishTime,
|
||||
"last_rate_scan_at": tasks.LastRateScanAt,
|
||||
"last_polish_date": tasks.LastPolishDate,
|
||||
"last_polish_at": tasks.LastPolishAt,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"xianyu-go/internal/account"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/notify"
|
||||
"xianyu-go/internal/webui"
|
||||
@@ -60,6 +61,7 @@ type Server struct {
|
||||
Manager *account.Manager
|
||||
automation *automation.Center
|
||||
notifier *notify.Notifier
|
||||
chat *chat.Service
|
||||
MTop mtop.Client
|
||||
CookieRenew xrenew.Service
|
||||
QRLogin qrLoginService
|
||||
@@ -85,6 +87,9 @@ type Server struct {
|
||||
loginLimiter *loginFailureLimiter
|
||||
}
|
||||
|
||||
// SetChatService installs the shared chat persistence and live event hub.
|
||||
func (s *Server) SetChatService(service *chat.Service) { s.chat = service }
|
||||
|
||||
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
|
||||
// adapter → manager → automation → notifier → server)。
|
||||
func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
|
||||
@@ -151,6 +156,9 @@ func (s *Server) Router() http.Handler {
|
||||
|
||||
// 账号 cookie
|
||||
s.mountCookies(r)
|
||||
s.mountAccountTasks(r)
|
||||
// 在线聊天(历史 REST + 应用层 WebSocket)
|
||||
s.mountChat(r)
|
||||
// 扫码登录
|
||||
s.mountQRLoginReal(r)
|
||||
// 密码登录
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import{r as d,b as fo,R as Sp}from"./react-vendor-DZnRGM0-.js";import{c as Z,g as Qt,u as cu,w as Ip,a as P,s as Ca,b as Te,t as Ep,p as re,d as Qe,e as q,f as kp,D as G,I as su,r as Xf,E as jp,h as Cp,i as Tp,j as ir,k as dn,l as $p,m as Mp,n as Dp,P as _p}from"./vendor-w5t2K9ux.js";var Np=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"];function vo(e){if(typeof e!="string")return!1;var t=Np;return t.includes(e)}var Lp=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gLine truncated
|
||||
import{r as d,b as fo,R as Sp}from"./react-vendor-C_od1ZSF.js";import{c as Z,g as Qt,u as cu,w as Ip,a as P,s as Ca,b as Te,t as Ep,p as re,d as Qe,e as q,f as kp,D as G,I as su,r as Xf,E as jp,h as Cp,i as Tp,j as ir,k as dn,l as $p,m as Mp,n as Dp,P as _p}from"./vendor-D-Edl3pr.js";var Np=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"];function vo(e){if(typeof e!="string")return!1;var t=Np;return t.includes(e)}var Lp=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gLine truncated
|
||||
A`).concat(i,",").concat(i,",0,1,1,").concat(2*o,",").concat(a,`
|
||||
H`).concat(He,"M").concat(2*o,",").concat(a,`
|
||||
A`).concat(i,",").concat(i,",0,1,1,").concat(o,",").concat(a),className:"recharts-legend-icon"});if(u==="rect")return d.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(He/8,"h").concat(He,"v").concat(He*3/4,"h").concat(-He,"z"),className:"recharts-legend-icon"});if(d.isValidElement(t.legendIcon)){var c=wd({},t);return delete c.legendIcon,d.cloneElement(t.legendIcon,c)}return d.createElement(bd,{fill:l,cx:a,cy:a,size:He,sizeType:"diameter",type:u})}function qy(e){var t=e.payload,r=e.iconSize,n=e.layout,a=e.formatter,i=e.inactiveColor,o=e.iconType,l=e.labelStyle,u={x:0,y:0,width:He,height:He},c={display:n==="horizontal"?"inline-block":"block",marginRight:10},s={display:"inline-block",verticalAlign:"middle",marginRight:4};return t.map((f,v)=>{var h=f.formatter||a,m=Z({"recharts-legend-item":!0,["legend-item-".concat(v)]:!0,inactive:f.inactive});if(f.type==="none")return null;var p=typeof l=="object"?wd({},l):{};p.color=f.inactive?i:p.color||f.color;var y=h?h(f.value,f,v):f.value;return d.createElement("li",Zn({className:m,style:c,key:"legend-item-".concat(v)},hn(e,f,v)),d.createElement(ho,{width:r,height:r,viewBox:u,style:s,"aria-label":"".concat(f.value," legend icon")},d.createElement(Yy,{data:f,iconType:o,inactiveColor:i})),d.createElement("span",{className:"recharts-legend-item-text",style:p},y))})}var Xy=e=>{var t=Ae(e,Vy),r=t.payload,n=t.layout,a=t.align;if(!r||!r.length)return null;var i={padding:0,margin:0,textAlign:n==="horizontal"?a:"left"};return d.createElement("ul",{className:"recharts-default-legend",style:i},d.createElement(qy,Zn({},t,{payload:r})))};function Ad(e,t,r){return t===!0?cu(e,r):typeof t=="function"?cu(e,t):e}var bo=d.createContext(null),Zy=e=>e,ee=()=>{var e=d.useContext(bo);return e?e.store.dispatch:Zy},Fn=()=>{},Qy=()=>Fn,Jy=(e,t)=>e===t;function M(e){var t=d.useContext(bo),r=d.useMemo(()=>t?n=>{if(n!=null)return e(n)}:Fn,[t,e]);return Ip.useSyncExternalStoreWithSelector(t?t.subscription.addNestedSub:Qy,t?t.store.getState:Fn,t?t.store.getState:Fn,r,Jy)}var Pd=e=>e.legend.settings,eg=e=>e.legend.size,tg=e=>e.legend.payload,rg=P([tg,Pd],(e,t)=>{var r=t.itemSorter,n=e.flat(1);return r?Ca(n,r):n});function ng(){return M(rg)}function ag(e,t){return ug(e)||lg(e,t)||og(e,t)||ig()}function ig(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
||||
+118
-73
@@ -1,361 +1,406 @@
|
||||
import{r as s}from"./react-vendor-DZnRGM0-.js";/**
|
||||
import{r as s}from"./react-vendor-C_od1ZSF.js";/**
|
||||
* @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=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),M=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(a,o,c)=>c?c.toUpperCase():o.toLowerCase()),y=t=>{const a=M(t);return a.charAt(0).toUpperCase()+a.slice(1)},k=(...t)=>t.filter((a,o,c)=>!!a&&a.trim()!==""&&c.indexOf(a)===o).join(" ").trim(),v=t=>{for(const a in t)if(a.startsWith("aria-")||a==="role"||a==="title")return!0};/**
|
||||
*/const M=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(a,c,o)=>o?o.toUpperCase():c.toLowerCase()),n=t=>{const a=_(t);return a.charAt(0).toUpperCase()+a.slice(1)},k=(...t)=>t.filter((a,c,o)=>!!a&&a.trim()!==""&&o.indexOf(a)===c).join(" ").trim(),x=t=>{for(const a in t)if(a.startsWith("aria-")||a==="role"||a==="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 x={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"};/**
|
||||
*/var v={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 g=s.forwardRef(({color:t="currentColor",size:a=24,strokeWidth:o=2,absoluteStrokeWidth:c,className:n="",children:h,iconNode:r,...d},i)=>s.createElement("svg",{ref:i,...x,width:a,height:a,stroke:t,strokeWidth:c?Number(o)*24/Number(a):o,className:k("lucide",n),...!h&&!v(d)&&{"aria-hidden":"true"},...d},[...r.map(([p,l])=>s.createElement(p,l)),...Array.isArray(h)?h:[h]]));/**
|
||||
*/const m=s.forwardRef(({color:t="currentColor",size:a=24,strokeWidth:c=2,absoluteStrokeWidth:o,className:y="",children:h,iconNode:p,...d},i)=>s.createElement("svg",{ref:i,...v,width:a,height:a,stroke:t,strokeWidth:o?Number(c)*24/Number(a):c,className:k("lucide",y),...!h&&!x(d)&&{"aria-hidden":"true"},...d},[...p.map(([r,l])=>s.createElement(r,l)),...Array.isArray(h)?h:[h]]));/**
|
||||
* @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 e=(t,a)=>{const o=s.forwardRef(({className:c,...n},h)=>s.createElement(g,{ref:h,iconNode:a,className:k(`lucide-${_(y(t))}`,`lucide-${t}`,c),...n}));return o.displayName=y(t),o};/**
|
||||
*/const e=(t,a)=>{const c=s.forwardRef(({className:o,...y},h)=>s.createElement(m,{ref:h,iconNode:a,className:k(`lucide-${M(n(t))}`,`lucide-${t}`,o),...y}));return c.displayName=n(t),c};/**
|
||||
* @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 m=[["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"}]],P1=e("activity",m);/**
|
||||
*/const g=[["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"}]],I1=e("activity",g);/**
|
||||
* @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 u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],S1=e("arrow-right",u);/**
|
||||
*/const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],O1=e("arrow-right",u);/**
|
||||
* @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 w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],U1=e("bell",w);/**
|
||||
*/const $=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],Z1=e("bell",$);/**
|
||||
* @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 $=[["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"}]],E1=e("bot",$);/**
|
||||
*/const N=[["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"}]],F1=e("bot",N);/**
|
||||
* @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 N=[["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"}]],B1=e("box",N);/**
|
||||
*/const f=[["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"}]],K1=e("box",f);/**
|
||||
* @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 f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],D1=e("check",f);/**
|
||||
*/const w=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],Q1=e("calendar-clock",w);/**
|
||||
* @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 b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],R1=e("chevron-down",b);/**
|
||||
*/const b=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],G1=e("check-check",b);/**
|
||||
* @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 q=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],T1=e("chevron-left",q);/**
|
||||
*/const z=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],J1=e("check",z);/**
|
||||
* @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 z=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Z1=e("chevron-right",z);/**
|
||||
*/const q=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],X1=e("chevron-down",q);/**
|
||||
* @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 A=[["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"}]],F1=e("circle-alert",A);/**
|
||||
*/const C=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Y1=e("chevron-left",C);/**
|
||||
* @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 C=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],I1=e("circle-check",C);/**
|
||||
*/const A=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],e2=e("chevron-right",A);/**
|
||||
* @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 H=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],K1=e("circle-dashed",H);/**
|
||||
*/const j=[["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"}]],a2=e("circle-alert",j);/**
|
||||
* @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 j=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],O1=e("clock-3",j);/**
|
||||
*/const H=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],t2=e("circle-check",H);/**
|
||||
* @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 L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],W1=e("clock",L);/**
|
||||
*/const V=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],c2=e("circle-dashed",V);/**
|
||||
* @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 V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],G1=e("cloud-upload",V);/**
|
||||
*/const L=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],o2=e("clock-3",L);/**
|
||||
* @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 P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q1=e("code",P);/**
|
||||
*/const P=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],h2=e("clock",P);/**
|
||||
* @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 S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],J1=e("copy",S);/**
|
||||
*/const S=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],s2=e("cloud-upload",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 U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],X1=e("credit-card",U);/**
|
||||
*/const U=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],y2=e("code",U);/**
|
||||
* @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 E=[["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"}]],Y1=e("database",E);/**
|
||||
*/const E=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],d2=e("copy",E);/**
|
||||
* @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 B=[["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"}]],e0=e("dollar-sign",B);/**
|
||||
*/const B=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],n2=e("credit-card",B);/**
|
||||
* @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 D=[["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"}]],a0=e("external-link",D);/**
|
||||
*/const D=[["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"}]],k2=e("database",D);/**
|
||||
* @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 R=[["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"}]],t0=e("eye-off",R);/**
|
||||
*/const R=[["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"}]],p2=e("dollar-sign",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 T=[["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"}]],o0=e("eye",T);/**
|
||||
*/const T=[["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"}]],i2=e("external-link",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 Z=[["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:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],c0=e("file-down",Z);/**
|
||||
*/const W=[["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"}]],r2=e("eye-off",W);/**
|
||||
* @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 F=[["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"}]],h0=e("file-text",F);/**
|
||||
*/const I=[["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"}]],l2=e("eye",I);/**
|
||||
* @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 I=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],s0=e("funnel",I);/**
|
||||
*/const O=[["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:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],M2=e("file-down",O);/**
|
||||
* @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 K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],n0=e("gift",K);/**
|
||||
*/const Z=[["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"}]],_2=e("file-text",Z);/**
|
||||
* @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 O=[["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"}]],d0=e("image",O);/**
|
||||
*/const F=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],x2=e("funnel",F);/**
|
||||
* @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 W=[["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"}]],y0=e("key",W);/**
|
||||
*/const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],v2=e("gift",K);/**
|
||||
* @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 G=[["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"}]],k0=e("layers",G);/**
|
||||
*/const Q=[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]],m2=e("image-plus",Q);/**
|
||||
* @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 Q=[["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"}]],r0=e("layout-dashboard",Q);/**
|
||||
*/const G=[["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"}]],g2=e("image",G);/**
|
||||
* @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 J=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],i0=e("link-2",J);/**
|
||||
*/const J=[["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"}]],u2=e("key",J);/**
|
||||
* @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 X=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],p0=e("list-plus",X);/**
|
||||
*/const X=[["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"}]],$2=e("layers",X);/**
|
||||
* @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 Y=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],l0=e("loader-circle",Y);/**
|
||||
*/const Y=[["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"}]],N2=e("layout-dashboard",Y);/**
|
||||
* @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 e1=[["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"}]],_0=e("lock-keyhole",e1);/**
|
||||
*/const e1=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],f2=e("link-2",e1);/**
|
||||
* @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 a1=[["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"}]],M0=e("lock",a1);/**
|
||||
*/const a1=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],w2=e("list-plus",a1);/**
|
||||
* @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 t1=[["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"}]],v0=e("log-out",t1);/**
|
||||
*/const t1=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],b2=e("loader-circle",t1);/**
|
||||
* @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 o1=[["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"}]],x0=e("mail",o1);/**
|
||||
*/const c1=[["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"}]],z2=e("lock-keyhole",c1);/**
|
||||
* @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 c1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],g0=e("message-circle",c1);/**
|
||||
*/const o1=[["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"}]],q2=e("lock",o1);/**
|
||||
* @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 h1=[["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"}]],m0=e("package-check",h1);/**
|
||||
*/const h1=[["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"}]],C2=e("log-out",h1);/**
|
||||
* @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 s1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["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"}]],u0=e("package-plus",s1);/**
|
||||
*/const s1=[["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"}]],A2=e("mail",s1);/**
|
||||
* @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 n1=[["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"}]],w0=e("package",n1);/**
|
||||
*/const y1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]],j2=e("message-circle-more",y1);/**
|
||||
* @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 d1=[["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"}]],$0=e("pen",d1);/**
|
||||
*/const d1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],H2=e("message-circle",d1);/**
|
||||
* @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 y1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],N0=e("plus",y1);/**
|
||||
*/const n1=[["path",{d:"M14 14a2 2 0 0 0 2-2V8h-2",key:"1r06pg"}],["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"}],["path",{d:"M8 14a2 2 0 0 0 2-2V8H8",key:"1jzu5j"}]],V2=e("message-square-quote",n1);/**
|
||||
* @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 k1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],f0=e("power",k1);/**
|
||||
*/const k1=[["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"}]],L2=e("package-check",k1);/**
|
||||
* @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 r1=[["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"}]],b0=e("qr-code",r1);/**
|
||||
*/const p1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["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"}]],P2=e("package-plus",p1);/**
|
||||
* @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 i1=[["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"}]],q0=e("refresh-cw",i1);/**
|
||||
*/const i1=[["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"}]],S2=e("package",i1);/**
|
||||
* @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 p1=[["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"}]],z0=e("save",p1);/**
|
||||
*/const r1=[["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"}]],U2=e("pen",r1);/**
|
||||
* @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 l1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],A0=e("search",l1);/**
|
||||
*/const l1=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],E2=e("play",l1);/**
|
||||
* @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 _1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],C0=e("send",_1);/**
|
||||
*/const M1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],B2=e("plus",M1);/**
|
||||
* @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 M1=[["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"}]],H0=e("settings",M1);/**
|
||||
*/const _1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],D2=e("power",_1);/**
|
||||
* @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 v1=[["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"}]],j0=e("shield-check",v1);/**
|
||||
*/const x1=[["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"}]],R2=e("qr-code",x1);/**
|
||||
* @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 x1=[["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"}]],L0=e("shopping-bag",x1);/**
|
||||
*/const v1=[["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"}]],T2=e("refresh-cw",v1);/**
|
||||
* @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 g1=[["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"}]],V0=e("shopping-cart",g1);/**
|
||||
*/const m1=[["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"}]],W2=e("save",m1);/**
|
||||
* @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 m1=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],P0=e("sliders-horizontal",m1);/**
|
||||
*/const g1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],I2=e("search",g1);/**
|
||||
* @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 u1=[["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"}]],S0=e("sparkles",u1);/**
|
||||
*/const u1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],O2=e("send",u1);/**
|
||||
* @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 w1=[["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"}]],U0=e("square-pen",w1);/**
|
||||
*/const $1=[["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"}]],Z2=e("settings",$1);/**
|
||||
* @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 $1=[["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"}]],E0=e("trash-2",$1);/**
|
||||
*/const N1=[["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"}]],F2=e("shield-check",N1);/**
|
||||
* @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 N1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],B0=e("trending-up",N1);/**
|
||||
*/const f1=[["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"}]],K2=e("shopping-bag",f1);/**
|
||||
* @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 f1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],D0=e("triangle-alert",f1);/**
|
||||
*/const w1=[["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"}]],Q2=e("shopping-cart",w1);/**
|
||||
* @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 b1=[["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"}]],R0=e("truck",b1);/**
|
||||
*/const b1=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],G2=e("sliders-horizontal",b1);/**
|
||||
* @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 q1=[["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"}]],T0=e("upload",q1);/**
|
||||
*/const z1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]],J2=e("smile",z1);/**
|
||||
* @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 z1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Z0=e("user-round",z1);/**
|
||||
*/const q1=[["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"}]],X2=e("sparkles",q1);/**
|
||||
* @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 A1=[["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"}]],F0=e("user",A1);/**
|
||||
*/const C1=[["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"}]],Y2=e("square-pen",C1);/**
|
||||
* @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 C1=[["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"}]],I0=e("users",C1);/**
|
||||
*/const A1=[["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"}]],e0=e("trash-2",A1);/**
|
||||
* @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 H1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],K0=e("webhook",H1);/**
|
||||
*/const j1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],a0=e("trending-up",j1);/**
|
||||
* @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 j1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],O0=e("x",j1);/**
|
||||
*/const H1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],t0=e("triangle-alert",H1);/**
|
||||
* @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 L1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],W0=e("zap",L1);export{i0 as $,P1 as A,B1 as B,X1 as C,e0 as D,a0 as E,P0 as F,J1 as G,h0 as H,d0 as I,p0 as J,y0 as K,r0 as L,c0 as M,Q1 as N,s0 as O,w0 as P,b0 as Q,q0 as R,L0 as S,B0 as T,I0 as U,u0 as V,G1 as W,O0 as X,I1 as Y,W0 as Z,K1 as _,U1 as a,S1 as a0,Y1 as a1,R1 as a2,j0 as a3,_0 as a4,Z0 as a5,g0 as a6,O1 as a7,n0 as a8,k0 as a9,C0 as aa,x0 as ab,K0 as ac,M0 as ad,H0 as b,S0 as c,v0 as d,F1 as e,V0 as f,m0 as g,D0 as h,l0 as i,F0 as j,D1 as k,E1 as l,W1 as m,$0 as n,f0 as o,E0 as p,t0 as q,o0 as r,z0 as s,N0 as t,R0 as u,A0 as v,U0 as w,T1 as x,Z1 as y,T0 as z};
|
||||
*/const V1=[["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"}]],c0=e("truck",V1);/**
|
||||
* @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 L1=[["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"}]],o0=e("upload",L1);/**
|
||||
* @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 P1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],h0=e("user-round",P1);/**
|
||||
* @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 S1=[["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"}]],s0=e("user",S1);/**
|
||||
* @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 U1=[["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"}]],y0=e("users",U1);/**
|
||||
* @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 E1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],d0=e("webhook",E1);/**
|
||||
* @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 B1=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],n0=e("wifi-off",B1);/**
|
||||
* @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 D1=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]],k0=e("wifi",D1);/**
|
||||
* @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 R1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],p0=e("x",R1);/**
|
||||
* @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 T1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],i0=e("zap",T1);export{x2 as $,I1 as A,K1 as B,n2 as C,p2 as D,i2 as E,c0 as F,I2 as G,Y2 as H,o0 as I,G2 as J,u2 as K,N2 as L,j2 as M,d2 as N,_2 as O,S2 as P,R2 as Q,T2 as R,K2 as S,a0 as T,y0 as U,g2 as V,w2 as W,p0 as X,M2 as Y,i0 as Z,y2 as _,Z1 as a,P2 as a0,s2 as a1,t2 as a2,c2 as a3,f2 as a4,O1 as a5,k2 as a6,X1 as a7,F2 as a8,z2 as a9,h0 as aa,o2 as ab,v2 as ac,$2 as ad,O2 as ae,A2 as af,d0 as ag,k0 as ah,n0 as ai,G1 as aj,J2 as ak,m2 as al,q2 as am,Z2 as b,e2 as c,Y1 as d,C2 as e,a2 as f,Q2 as g,L2 as h,t0 as i,b2 as j,V2 as k,E2 as l,X2 as m,Q1 as n,W2 as o,s0 as p,J1 as q,F1 as r,H2 as s,h2 as t,U2 as u,D2 as v,e0 as w,r2 as x,l2 as y,B2 as z};
|
||||
@@ -1,19 +0,0 @@
|
||||
import{j as e,r as n,b as Le,c as ba,d as ya}from"./react-vendor-DZnRGM0-.js";import{L as fa,U as Wt,S as Vt,C as Zs,B as Gt,Z as Xs,a as ys,b as it,c as Jt,d as ja,e as cs,A as gt,D as Na,f as bt,P as Kt,g as Ls,E as Qt,T as va,h as wa,i as $e,Q as Ws,j as ds,k as ss,l as bs,m as yt,R as qe,n as Yt,o as _a,p as Je,X as we,K as ka,q as os,r as rs,s as as,t as ts,u as ft,v as As,w as fs,x as Zt,y as Xt,z as Ss,F as Ht,G as Ca,H as jt,I as Nt,J as Sa,M as La,N as Aa,O as Ia,V as Vs,W as $s,Y as Hs,_ as $a,$ as Ra,a0 as et,a1 as Pa,a2 as Da,a3 as st,a4 as vt,a5 as Ta,a6 as Ms,a7 as ea,a8 as Fa,a9 as Ea,aa as ot,ab as sa,ac as Ma,ad as Oa}from"./icons-vendor-RenKjhri.js";import{R as Rs,B as qa,X as wt,Y as _t,T as Ps,a as Ba,C as Gs,A as za,b as Ua,c as Wa,P as kt,d as Ct,L as Va}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const x of document.querySelectorAll('link[rel="modulepreload"]'))d(x);new MutationObserver(x=>{for(const w of x)if(w.type==="childList")for(const L of w.addedNodes)L.tagName==="LINK"&&L.rel==="modulepreload"&&d(L)}).observe(document,{childList:!0,subtree:!0});function r(x){const w={};return x.integrity&&(w.integrity=x.integrity),x.referrerPolicy&&(w.referrerPolicy=x.referrerPolicy),x.crossOrigin==="use-credentials"?w.credentials="include":x.crossOrigin==="anonymous"?w.credentials="omit":w.credentials="same-origin",w}function d(x){if(x.ep)return;x.ep=!0;const w=r(x);fetch(x.href,w)}})();const Ga=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),tt=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:us,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:c,children:"取消"}),e.jsxs("button",{onClick:Z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:c,children:[c?e.jsx($e,{className:"w-4 h-4 animate-spin"}):e.jsx(as,{className:"w-4 h-4"}),c?"保存中...":"保存"]})]})})]})}),document.body)]})},vr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),wr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],Tt=({status:s})=>{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",unknown:"bg-gray-100 text-gray-500"},r={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:r[s]||s})},_r=()=>{const[s,t]=n.useState([]),[r,d]=n.useState([]),[x,w]=n.useState([]),[L,F]=n.useState({}),[g,D]=n.useState("all"),[y,G]=n.useState(""),[ee,ae]=n.useState(""),[ie,S]=n.useState(""),q=n.useRef(0),[le,J]=n.useState(1),[Y,B]=n.useState(1),[me,oe]=n.useState(!1),[k,E]=n.useState(!1),[U,V]=n.useState(!1),[ue,A]=n.useState(!1),[R,K]=n.useState(null),[I,he]=n.useState(null),[_e,Ne]=n.useState({}),[re,m]=n.useState(!1),[h,z]=n.useState(""),[j,X]=n.useState(!1),[se,ne]=n.useState(null),[ve,$]=n.useState(null),[i,T]=n.useState(null),[b,c]=n.useState(!1),[_,C]=n.useState(null),[M,te]=n.useState(null),H=async()=>{const u=++q.current;oe(!0);try{const P=await yl(y||void 0,g,le,20,ie);if(u!==q.current)return;t(P.data),B(P.total_pages)}catch(P){console.error("加载订单失败:",P)}finally{u===q.current&&oe(!1)}},ce=(u,P,de)=>{if(de&&de.trim())return de;if(L[`${u}:${P}`])return L[`${u}:${P}`];const Ce=r.find(Ye=>{if(de&&Ye.item_title){const Ze=de.toLowerCase(),Xe=Ye.item_title.toLowerCase();return Xe.includes(Ze)||Ze.includes(Xe)}return!1});return Ce!=null&&Ce.item_title?Ce.item_title:"未知商品"},be=u=>{const P={};u.forEach(de=>{de.item_id&&(P[`${de.cookie_id}:${de.item_id}`]=de.item_title||de.item_id)}),F(P)};n.useEffect(()=>{const u=window.setTimeout(()=>{J(1),S(ee.trim())},300);return()=>window.clearTimeout(u)},[ee]),n.useEffect(()=>{H()},[y,g,le,ie]),n.useEffect(()=>{Promise.all([Bs(),js()]).then(([u,P])=>{w(u),d(P),be(P)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const ke=n.useMemo(()=>new Map(x.map(u=>[u.id,u])),[x]),Re=u=>{const P=ke.get(u),de=(P==null?void 0:P.remark)||(P==null?void 0:P.nickname);return de?`${de} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},Ie=u=>{const P=ke.get(u);return(P==null?void 0:P.remark)||(P==null?void 0:P.nickname)||"未命名账号"},Fe=async()=>{oe(!0);try{const u=await Nl(y||void 0,g);await H(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{oe(!1)}},Be=u=>{z(u),ne(null),m(!0)},Ee=async u=>{var P;X(!0),ne(null);try{const de=await wl([h],u),Ce=(P=de==null?void 0:de.results)==null?void 0:P[0];Ce!=null&&Ce.success?(ne({success:!0,message:Ce.message}),H()):ne({success:!1,message:(Ce==null?void 0:Ce.message)||"发货失败"})}catch(de){ne({success:!1,message:(de==null?void 0:de.message)||"请求失败"})}finally{X(!1)}},Ve=u=>{K(u),E(!0)},Me=u=>{he({...u}),V(!0)},Pe=async()=>{if(!(!I||!I.order_id))try{const u={};I.status!==void 0&&(u.order_status=I.status),I.buyer_id!==void 0&&(u.buyer_id=I.buyer_id),I.amount!==void 0&&(u.amount=I.amount),I.receiver_name!==void 0&&(u.receiver_name=I.receiver_name),I.receiver_p
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(M=>M.map(te=>`"${String(te).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),c=new Blob(["\uFEFF"+b],{type:"text/csv;charset=utf-8"}),_=URL.createObjectURL(c),C=document.createElement("a");C.href=_,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(_)},ne=async()=>{if(q){me(!0),Y(null);try{const i=await Il(q);if(Y(i),i.created>0){const T=await es();t(T)}}catch(i){Y({error:(i==null?void 0:i.message)||"上传失败"})}finally{me(!1)}}},ve=async()=>{if(!(!oe||!E.trim())){me(!0),ue(null);try{const i=await $l(oe,E);ue({added:i.added}),U("");const T=await es();t(T)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{me(!1)}}},$=()=>{var i;S("create"),le(null),Y(null),k((i=j[0])!=null&&i.id?String(j[0].id):""),U(""),ue(null),ae(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:$,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Ss,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>w(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(ts,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Ht,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:A,onChange:i=>R(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(As,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:K,onChange:i=>I(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",X.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:X.map(i=>{let T="";return i.type==="data"&&i.data_content?T=`库存: ${i.data_content.split(`
|
||||
`).filter(c=>c.trim()).length} 条`:i.type==="text"&&i.text_content?T=i.text_content:i.type==="api"&&i.api_config?T=i.api_config.url:i.type==="image"&&i.image_url&&(T="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(he,{type:i.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:i.name,children:i.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>z(i.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:i.id}),e.jsx(Ca,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:T,children:T})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>h(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>_e(i),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(fs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>re(i.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},i.id)})})]})}),X.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Kt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),r&&L&&Le.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>d(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:i=>D({...g,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:i=>D({...g,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(L==null?void 0:L.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:i=>D({...g,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxLine truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
|
||||
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:i=>D({...g,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:i=>D({...g,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:i=>D({...g,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>D({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>d(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ne,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(as,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),x&&Le.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>w(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:y.name,onChange:i=>G({...y,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>G({...y,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Zs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>G({...y,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(jt,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>G({...y,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-grayLine truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),y.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:y.content.split(`
|
||||
`).filter(i=>i.trim()).length})," 条"]})]}),y.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:y.api_method,onChange:i=>G({...y,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:y.api_timeout,onChange:i=>G({...y,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:y.api_headers,onChange:i=>G({...y,api_headers:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:y.api_params,onChange:i=>G({...y,api_params:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:y.description,onChange:i=>G({...y,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:y.delay_seconds,onChange:i=>G({...y,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>w(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),ee&&Le.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>ae(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>S("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ie==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Sa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>S("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ie==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ss,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ie==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:se,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 tex
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),V&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",V.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>ae(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ie==="create"?e.jsxs("button",{onClick:ne,disabled:!q||B,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx($e,{className:"w-4 h-4 animate-spin"}):e.jsx(Ss,{className:"w-4 h-4"}),B?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:ve,disabled:!oe||!E.trim()||B||j.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx($e,{className:"w-4 h-4 animate-spin"}):e.jsx(ts,{className:"w-4 h-4"}),B?"处理中...":"追加卡密"]})]})]})}),document.body)]})},Sr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),Lr=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},Ar=({onConfigureDelivery:s})=>{const[t,r]=n.useState([]),[d,x]=n.useState([]),[w,L]=n.useState([]),[F,g]=n.useState(""),[D,y]=n.useState(""),[G,ee]=n.useState(!1),[ae,ie]=n.useState(!1),[S,q]=n.useState(!1),[le,J]=n.useState(!1),[Y,B]=n.useState(!1),[me,oe]=n.useState(!1),[k,E]=n.useState(!1),[U,V]=n.useState("upload"),[ue,A]=n.useState(null),[R,K]=n.useState(null),[I,he]=n.useState(""),[_e,Ne]=n.useState(!1),[re,m]=n.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[h,z]=n.useState(null),[j,X]=n.useState(null),[se,ne]=n.useState(null),ve=n.useRef(!1),[$,i]=n.useState(null),[T,b]=n.useState({}),[c,_]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[C,M]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[te,H]=n.useState([]);n.useEffect(()=>{if(!me||C.images.length===0){H([]);return}const l=C.images.map((N,Z)=>({key:N.name+Z,url:URL.createObjectURL(N)}));return H(l),()=>{l.forEach(N=>URL.revokeObjectURL(N.url))}},[me,C.images]);const ce=async()=>{const l=await js();r(l)},be=async()=>{x(await lt())};n.useEffect(()=>{Promise.all([Bs(),js(),lt(),It(20)]).then(([l,N,Z,We])=>{L(l),r(N),x(Z);const Ge=We.find(De=>["running","canceling"].includes(De.status))||We.find(De=>De.status!=="preview");ne(Ge||null)}).catch(l=>console.error("加载商品配置失败:",l))},[]),n.useEffect(()=>{if(!k||!(j!=null&&j.id)||!["running","canceling"].includes(j.status))return;const l=window.setInterval(async()=>{if(!ve.current){ve.current=!0;try{const N=await hs(j.id);X(N),ne(N),["running","canceling"].includes(N.status)||(V("done"),await ce(),await be())}catch(N){console.error("刷新批量铺货进度失败:",N)}finally{ve.current=!1}}},3e3);return()=>{window.clearInterval(l)}},[k,j==null?void 0:j.id,j==null?void 0:j.status]);const ke=async()=>{if(!F)return alert("请先选择账号");ee(!0);try{const l=await Rl(F);await ce(),alert((l==null?void 0:l.message)||"商品同步完成")}catch(l){console.error("同步商品失败:",l),alert((l==null?void 0:l.message)||"同步失败,请重试")}finally{ee(!1)}},Re=l=>{i(l),b({...l}),J(!0)},Ie=async()=>{if($)try{await zl($.cookie_id,$.item_id,{item_title:T.item_title||"",item_description:T.item_description||"",item_category:T.item_category||"",item_price:T.item_price||"",item_detail:T.item_detail||$.item_detail||""}),await ce(),await be(),J(!1),i(null)}catch(l){console.error("更新商品失败:",l),alert("更新失败,请重试")}},Fe=async l=>{if(confirm(`确认删除商品"${l.item_title}"吗?`))try{await Pl(l.cookie_id,l.item_id),r(N=>N.filter(Z=>!(Z.cookie_id===l.cookie_id&&Z.item_id===l.item_id)))}catch(N){console.error("删除商品失败:",N),alert("删除失败,请重试")}},Be=async()=>{try{if(!c.cookie_id||!c.item_id){alert("请选择账号并填写商品ID");return}await Dl(c.cookie_id,{item_id:c.item_id,item_title:c.item_title,item_price:c.item_price,item_detail:c.item_image?JSON.stringify({item_image:c.item_image}):""}),await ce(),B(!1),_({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(l){console.error("添加商品失败:",l),alert("添加失败,请重试")}},Ee=async()=>{if(!C.cookie_id)return alert("请选择发布账号");if(!C.title.trim())return alert("请填写商品标题");if(!C.price.trim())return alert("请填写商品价格");if(!C.quantity||Number(C.quantity)<=0)return alert("库存数量必须大于 0");if(C.images.length===0)return alert("至少上传 1 张商品图片");if(C.postage_mode==="fixed"&&!C
Line truncated
|
||||
`),We=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),Ge=URL.createObjectURL(We),De=document.createElement("a");De.href=Ge,De.download="批量铺货模板.csv",document.body.appendChild(De),De.click(),De.remove(),URL.revokeObjectURL(Ge)},Ce=()=>{_(l=>({...l,cookie_id:F||l.cookie_id})),B(!0)},Ye=()=>{M(l=>({...l,cookie_id:F||l.cookie_id})),oe(!0)},Ze=l=>d.filter(N=>N.cookie_id===l.cookie_id&&N.item_id===l.item_id).length>0?d.filter(N=>N.cookie_id===l.cookie_id&&N.item_id===l.item_id):d.filter(N=>N.cookie_id===l.cookie_id&&!N.item_id),Xe=l=>{switch(l){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return l||"-"}},ze=l=>{switch(l){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},Ue=n.useMemo(()=>new Map(w.map(l=>[l.id,l])),[w]),xs=n.useMemo(()=>D?t.filter(l=>l.cookie_id===D):t,[D,t]),He=l=>{const N=Ue.get(l),Z=(N==null?void 0:N.remark)||(N==null?void 0:N.nickname);return Z?`${Z} · ${l.slice(0,6)}`:`账号 ${l.slice(0,8)}`},ms=l=>{const N=Ue.get(l);return(N==null?void 0:N.remark)||(N==null?void 0:N.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ia,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:D,onChange:l=>y(l.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),w.map(l=>e.jsx("option",{value:l.id,children:He(l.id)},l.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ds,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:l=>g(l.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),w.map(l=>e.jsx("option",{value:l.id,children:He(l.id)},l.id))]})]})]}),e.jsxs("button",{onClick:ke,disabled:G||!F,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${G?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Ce,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(ts,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ye,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Vs,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Ve(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx($s,{className:"w-4 h-4"}),se&&["running","canceling"].includes(se.status)?"继续批量任务":"批量铺货"]}),se&&!["running","canceling"].includes(se.status)&&e.jsx("button",{onClick:()=>void Pe(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[xs.map(l=>{const N=Ze(l),Z=N.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relat
Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
import{j as e,r,b as Fe,c as aa,d as Ra}from"./react-vendor-C_od1ZSF.js";import{L as $a,U as la,M as ts,C as ss,B as ra,S as na,Z as as,a as yt,b as us,c as hs,d as gs,e as Pa,f as rt,A as ks,D as Da,g as Cs,P as ia,h as At,E as oa,T as Ea,i as Ta,j as Re,X as $e,k as Fa,l as Ma,m as bs,n as ca,o as He,Q as Qt,p as ot,q as Ke,r as ft,s as It,t as Ss,R as Be,u as da,v as qa,w as Qe,K as Ba,x as it,y as lt,z as tt,F as Ls,G as _t,H as jt,I as Ot,J as xa,N as za,O as Os,V as Is,W as Ua,Y as Wa,_ as Va,$ as Ja,a0 as Gt,a1 as Dt,a2 as ls,a3 as Qa,a4 as Ga,a5 as rs,a6 as Ka,a7 as Ha,a8 as ns,a9 as As,aa as zt,ab as ma,ac as Za,ad as Ya,ae as Wt,af as pa,ag as Xa,ah as el,ai as tl,aj as sl,ak as al,al as ll,am as rl}from"./icons-vendor-DjsKcZkz.js";import{R as Et,B as nl,X as Rs,Y as $s,T as Tt,a as il,C as Kt,A as ol,b as cl,c as dl,P as Ps,d as Ds,L as xl}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const x of document.querySelectorAll('link[rel="modulepreload"]'))i(x);new MutationObserver(x=>{for(const v of x)if(v.type==="childList")for(const S of v.addedNodes)S.tagName==="LINK"&&S.rel==="modulepreload"&&i(S)}).observe(document,{childList:!0,subtree:!0});function l(x){const v={};return x.integrity&&(v.integrity=x.integrity),x.referrerPolicy&&(v.referrerPolicy=x.referrerPolicy),x.crossOrigin==="use-credentials"?v.credentials="include":x.crossOrigin==="anonymous"?v.credentials="omit":v.credentials="same-origin",v}function i(x){if(x.ep)return;x.ep=!0;const v=l(x);fetch(x.href,v)}})();const ml=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),is=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.8Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Pt,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:R,children:"取消"}),e.jsxs("button",{onClick:Je,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:R,children:[R?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),R?"保存中...":"保存"]})]})})]})}),document.body)]})},Qr=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(s=>({order_id:String((s==null?void 0:s.order_id)||"unknown"),success:(s==null?void 0:s.success)===!0,message:String((s==null?void 0:s.message)||"")})):[]}),Gr=t=>(t==null?void 0:t.results.filter(s=>!s.success))||[],Qs=({status:t})=>{const s={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",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${s[t]||s.cancelled}`,children:l[t]||t})},Kr=()=>{const[t,s]=r.useState([]),[l,i]=r.useState([]),[x,v]=r.useState([]),[S,$]=r.useState({}),[f,I]=r.useState("all"),[y,J]=r.useState(""),[H,me]=r.useState(""),[ne,N]=r.useState(""),M=r.useRef(0),[ie,G]=r.useState(1),[Z,W]=r.useState(1),[ge,ue]=r.useState(!1),[O,Q]=r.useState(!1),[ce,q]=r.useState(!1),[V,A]=r.useState(!1),[D,ae]=r.useState(null),[E,le]=r.useState(null),[Se,je]=r.useState({}),[pe,u]=r.useState(!1),[b,z]=r.useState(""),[w,Y]=r.useState(!1),[oe,he]=r.useState(null),[Ie,fe]=r.useState(null),[d,k]=r.useState(null),[p,c]=r.useState(!1),[_,R]=r.useState(null),[U,K]=r.useState(null),te=async()=>{const g=++M.current;ue(!0);try{const B=await zl(y||void 0,f,ie,20,ne);if(g!==M.current)return;s(B.data),W(B.total_pages)}catch(B){console.error("加载订单失败:",B)}finally{g===M.current&&ue(!1)}},Ne=(g,B,_e)=>{if(_e&&_e.trim())return _e;if(S[`${g}:${B}`])return S[`${g}:${B}`];const Oe=l.find(Ye=>{if(_e&&Ye.item_title){const st=_e.toLowerCase(),Xe=Ye.item_title.toLowerCase();return Xe.includes(st)||st.includes(Xe)}return!1});return Oe!=null&&Oe.item_title?Oe.item_title:"未知商品"},h=g=>{const B={};g.forEach(_e=>{_e.item_id&&(B[`${_e.cookie_id}:${_e.item_id}`]=_e.item_title||_e.item_id)}),$(B)};r.useEffect(()=>{const g=window.setTimeout(()=>{G(1),N(H.trim())},300);return()=>window.clearTimeout(g)},[H]),r.useEffect(()=>{te()},[y,f,ie,ne]),r.useEffect(()=>{Promise.all([Rt(),Nt()]).then(([g,B])=>{v(g),i(B),h(B)}).catch(g=>{console.error("加载商品列表失败:",g)})},[]);const C=r.useMemo(()=>new Map(x.map(g=>[g.id,g])),[x]),F=g=>{const B=C.get(g),_e=(B==null?void 0:B.remark)||(B==null?void 0:B.nickname);return _e?`${_e} · ${g.slice(0,6)}`:`账号 ${g.slice(0,8)}`},T=g=>{const B=C.get(g);return(B==null?void 0:B.remark)||(B==null?void 0:B.nickname)||"未命名账号"},ve=async()=>{ue(!0);try{const g=await Vl(y||void 0,f);await te(),g!=null&&g.message&&alert(g.message)}catch(g){console.error("同步订单失败:",g),alert((g==null?void 0:g.message)||"同步失败,请重试")}finally{ue(!1)}},Ee=g=>{z(g),he(null),u(!0)},we=async g=>{var B;Y(!0),he(null);try{const _e=await Ql([b],g),Oe=(B=_e==null?void 0:_e.results)==null?void 0:B[0];Oe!=null&&Oe.success?(he({success:!0,message:Oe.message}),te()):he({success:!1,message:(Oe==null?void 0:Oe.message)||"发货失败"})}catch(_e){he({success:!1,message:(_e==null?void 0:_e.message)||"请求失败"})}finally{Y(!1)}},Pe=g=>{ae(g),Q(!0)},de=g=>{le({...g}),q(!0)},Te=async()=>{if(!(!E||!E.order_id))try{const g={};E.status!==void 0&&(g.order_status=E.status),E.buyer_id!==void 0&&(g.buyer_id=E.buyer_id),E.amount!==void 0&&(g.amount=E.amount),E.receiver_name!==void 0&&(g.receiver_name=E.receiver_name),E.receiver_phon
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(U=>U.map(K=>`"${String(K).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),c=new Blob(["\uFEFF"+p],{type:"text/csv;charset=utf-8"}),_=URL.createObjectURL(c),R=document.createElement("a");R.href=_,R.download="卡密组批量导入模板.csv",document.body.appendChild(R),R.click(),R.remove(),URL.revokeObjectURL(_)},he=async()=>{if(M){ge(!0),Z(null);try{const d=await er(M);if(Z(d),d.created>0){const k=await et();s(k)}}catch(d){Z({error:(d==null?void 0:d.message)||"上传失败"})}finally{ge(!1)}}},Ie=async()=>{if(!(!ue||!Q.trim())){ge(!0),V(null);try{const d=await tr(ue,Q);V({added:d.added}),ce("");const k=await et();s(k)}catch(d){alert("追加失败:"+((d==null?void 0:d.message)||"未知错误"))}finally{ge(!1)}}},fe=()=>{var d;N("create"),ie(null),Z(null),O((d=w[0])!=null&&d.id?String(w[0].id):""),ce(""),V(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:fe,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Ot,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>v(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(tt,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(xa,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:A,onChange:d=>D(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:ae,onChange:d=>E(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",Y.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:Y.map(d=>{let k="";return d.type==="data"&&d.data_content?k=`库存: ${d.data_content.split(`
|
||||
`).filter(c=>c.trim()).length} 条`:d.type==="text"&&d.text_content?k=d.text_content:d.type==="api"&&d.api_config?k=d.api_config.url:d.type==="image"&&d.image_url&&(k="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(le,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>z(d.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(za,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:k,children:k})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Se(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(jt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>pe(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Qe,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),Y.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ia,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&S&&Fe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx($e,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:f.name||"",onChange:d=>I({...f,name:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:f.type||"text",onChange:d=>I({...f,type:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(S==null?void 0:S.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),f.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:f.api_url||"",onChange:d=>I({...f,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxLine truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:f.data_content?f.data_content.split(`
|
||||
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),f.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:f.image_url||"",onChange:d=>I({...f,image_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),f.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:f.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:f.delay_seconds||0,onChange:d=>I({...f,delay_seconds:parseInt(d.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:f.description||"",onChange:d=>I({...f,description:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>I({...f,enabled:!f.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${f.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${f.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:je,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),x&&Fe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>v(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx($e,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:y.name,onChange:d=>J({...y,name:d.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(ss,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>J({...y,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${y.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-grayLine truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),y.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:y.content.split(`
|
||||
`).filter(d=>d.trim()).length})," 条"]})]}),y.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:y.api_method,onChange:d=>J({...y,api_method:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:y.api_timeout,onChange:d=>J({...y,api_timeout:parseInt(d.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:y.api_headers,onChange:d=>J({...y,api_headers:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:y.api_params,onChange:d=>J({...y,api_params:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:y.description,onChange:d=>J({...y,description:d.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:y.delay_seconds,onChange:d=>J({...y,delay_seconds:parseInt(d.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>v(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:u,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),H&&Fe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx($e,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>N("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ne==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ua,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>N("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ne==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ot,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ne==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:oe,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),q&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",q.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ne==="create"?e.jsxs("button",{onClick:he,disabled:!M||W,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[W?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(Ot,{className:"w-4 h-4"}),W?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ie,disabled:!ue||!Q.trim()||W||w.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[W?e.jsx(Re,{className:"w-4 h-4 animate-spin"}):e.jsx(tt,{className:"w-4 h-4"}),W?"处理中...":"追加卡密"]})]})]})}),document.body)]})},Yr=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Xr=t=>{const s=String(t||"").trim();return s?/^[¥¥]/.test(s)?s:`¥${s}`:"-"},en=({onConfigureDelivery:t})=>{const[s,l]=r.useState([]),[i,x]=r.useState([]),[v,S]=r.useState([]),[$,f]=r.useState(""),[I,y]=r.useState(""),[J,H]=r.useState(!1),[me,ne]=r.useState(!1),[N,M]=r.useState(!1),[ie,G]=r.useState(!1),[Z,W]=r.useState(!1),[ge,ue]=r.useState(!1),[O,Q]=r.useState(!1),[ce,q]=r.useState("upload"),[V,A]=r.useState(null),[D,ae]=r.useState(null),[E,le]=r.useState(""),[Se,je]=r.useState(!1),[pe,u]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[b,z]=r.useState(null),[w,Y]=r.useState(null),[oe,he]=r.useState(null),Ie=r.useRef(!1),[fe,d]=r.useState(null),[k,p]=r.useState({}),[c,_]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[R,U]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[K,te]=r.useState([]);r.useEffect(()=>{if(!ge||R.images.length===0){te([]);return}const n=R.images.map((L,re)=>({key:L.name+re,url:URL.createObjectURL(L)}));return te(n),()=>{n.forEach(L=>URL.revokeObjectURL(L.url))}},[ge,R.images]);const Ne=async()=>{const n=await Nt();l(n)},h=async()=>{x(await xs())};r.useEffect(()=>{Promise.all([Rt(),Nt(),xs(),Bs(20)]).then(([n,L,re,Ve])=>{S(n),l(L),x(re);const Je=Ve.find(qe=>["running","canceling"].includes(qe.status))||Ve.find(qe=>qe.status!=="preview");he(Je||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!O||!(w!=null&&w.id)||!["running","canceling"].includes(w.status))return;const n=window.setInterval(async()=>{if(!Ie.current){Ie.current=!0;try{const L=await gt(w.id);Y(L),he(L),["running","canceling"].includes(L.status)||(q("done"),await Ne(),await h())}catch(L){console.error("刷新批量铺货进度失败:",L)}finally{Ie.current=!1}}},3e3);return()=>{window.clearInterval(n)}},[O,w==null?void 0:w.id,w==null?void 0:w.status]);const C=async()=>{if(!$)return alert("请先选择账号");H(!0);try{const n=await sr($);await Ne(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{H(!1)}},F=n=>{d(n),p({...n}),G(!0)},T=async()=>{if(fe)try{await mr(fe.cookie_id,fe.item_id,{item_title:k.item_title||"",item_description:k.item_description||"",item_category:k.item_category||"",item_price:k.item_price||"",item_detail:k.item_detail||fe.item_detail||""}),await Ne(),await h(),G(!1),d(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},ve=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await ar(n.cookie_id,n.item_id),l(L=>L.filter(re=>!(re.cookie_id===n.cookie_id&&re.item_id===n.item_id)))}catch(L){console.error("删除商品失败:",L),alert("删除失败,请重试")}},Ee=async()=>{try{if(!c.cookie_id||!c.item_id){alert("请选择账号并填写商品ID");return}await lr(c.cookie_id,{item_id:c.item_id,item_title:c.item_title,item_price:c.item_price,item_detail:c.item_image?JSON.stringify({item_image:c.item_image}):""}),await Ne(),W(!1),_({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},we=async()=>{if(!R.cookie_id)return alert("请选择发布账号");if(!R.title.trim())return alert("请填写商品标题");if(!R.price.trim())return alert("请填写商品价格");if(!R.quantity||Number(R.quantity)<=0)return alert("库存数量必须大于 0");if(R.images.length===0)return alert("至少上传 1 张商品图片");if(R.postage_mode==="fixe
Line truncated
|
||||
`),Ve=new Blob(["\uFEFF"+re],{type:"text/csv;charset=utf-8"}),Je=URL.createObjectURL(Ve),qe=document.createElement("a");qe.href=Je,qe.download="批量铺货模板.csv",document.body.appendChild(qe),qe.click(),qe.remove(),URL.revokeObjectURL(Je)},Oe=()=>{_(n=>({...n,cookie_id:$||n.cookie_id})),W(!0)},Ye=()=>{U(n=>({...n,cookie_id:$||n.cookie_id})),ue(!0)},st=n=>i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id).length>0?i.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id):i.filter(L=>L.cookie_id===n.cookie_id&&!L.item_id),Xe=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ze=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},We=r.useMemo(()=>new Map(v.map(n=>[n.id,n])),[v]),ct=r.useMemo(()=>I?s.filter(n=>n.cookie_id===I):s,[I,s]),Ge=n=>{const L=We.get(n),re=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return re?`${re} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},dt=n=>{const L=We.get(n);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ja,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:n=>y(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),v.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ot,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:$,onChange:n=>f(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),v.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:C,disabled:J||!$,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Be,{className:`w-4 h-4 ${J?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Oe,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(tt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ye,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Gt,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Pe(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Dt,{className:"w-4 h-4"}),oe&&["running","canceling"].includes(oe.status)?"继续批量任务":"批量铺货"]}),oe&&!["running","canceling"].includes(oe.status)&&e.jsx("button",{onClick:()=>void Te(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[ct.map(n=>{const L=st(n),re=L.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group r
Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(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}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{positiLine truncated
|
||||
@@ -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}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-wLine truncated
|
||||
+1
-1
@@ -46,4 +46,4 @@ function ws(M,Sl){for(var W=0;W<Sl.length;W++){const o=Sl[W];if(typeof o!="strin
|
||||
`+i[a].replace(" at new "," at ");return l.displayName&&g.includes("<anonymous>")&&(g=g.replace("<anonymous>",l.displayName)),g}while(1<=a&&0<=e);break}}}finally{Qn=!1,Error.prepareStackTrace=u}return(u=l?l.displayName||l.name:"")?Tu(u):""}function O1(l,t){switch(l.tag){case 26:case 27:case 5:return Tu(l.type);case 16:return Tu("Lazy");case 13:return l.child!==t&&t!==null?Tu("Suspense Fallback"):Tu("Suspense");case 19:return Tu("SuspenseList");case 0:case 15:return jn(l.type,!1);case 11:return jn(l.type.render,!1);case 1:return jn(l.type,!0);case 31:return Tu("Activity");default:return""}}function mi(l){try{var t="",u=null;do t+=O1(l,u),u=l,l=l.return;while(l);return t}catch(a){return`
|
||||
Error generating stack: `+a.message+`
|
||||
`+a.stack}}var Zn=Object.prototype.hasOwnProperty,Vn=M.unstable_scheduleCallback,xn=M.unstable_cancelCallback,M1=M.unstable_shouldYield,D1=M.unstable_requestPaint,$l=M.unstable_now,U1=M.unstable_getCurrentPriorityLevel,si=M.unstable_ImmediatePriority,di=M.unstable_UserBlockingPriority,Te=M.unstable_NormalPriority,r1=M.unstable_LowPriority,hi=M.unstable_IdlePriority,H1=M.log,N1=M.unstable_setDisableYieldValue,Ma=null,Fl=null;function Wt(l){if(typeof H1=="function"&&N1(l),Fl&&typeof Fl.setStrictMode=="function")try{Fl.setStrictMode(Ma,l)}catch{}}var kl=Math.clz32?Math.clz32:q1,p1=Math.log,R1=Math.LN2;function q1(l){return l>>>=0,l===0?32:31-(p1(l)/R1|0)|0}var Ee=256,Ae=262144,_e=4194304;function Eu(l){var t=l&42;if(t!==0)return t;switch(l&-l){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 l&261888;case 262144:case 524288:case 1048576:case 2097152:return l&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return l&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return l}}function Oe(l,t,u){var a=l.pendingLanes;if(a===0)return 0;var e=0,n=l.suspendedLanes,f=l.pingedLanes;l=l.warmLanes;var c=a&134217727;return c!==0?(a=c&~n,a!==0?e=Eu(a):(f&=c,f!==0?e=Eu(f):u||(u=c&~l,u!==0&&(e=Eu(u))))):(c=a&~n,c!==0?e=Eu(c):f!==0?e=Eu(f):u||(u=a&~l,u!==0&&(e=Eu(u)))),e===0?0:t!==0&&t!==e&&(t&n)===0&&(n=e&-e,u=t&-t,n>=u||n===32&&(u&4194048)!==0)?t:e}function Da(l,t){return(l.pendingLanes&~(l.suspendedLanes&~l.pingedLanes)&t)===0}function C1(l,t){switch(l){case 1:case 2:case 4:case 8:case 64:return t+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 t+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 oi(){var l=_e;return _e<<=1,(_e&62914560)===0&&(_e=4194304),l}function Ln(l){for(var t=[],u=0;31>u;u++)t.push(l);return t}function Ua(l,t){l.pendingLanes|=t,t!==268435456&&(l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0)}function Y1(l,t,u,a,e,n){var f=l.pendingLanes;l.pendingLanes=u,l.suspendedLanes=0,l.pingedLanes=0,l.warmLanes=0,l.expiredLanes&=u,l.entangledLanes&=u,l.errorRecoveryDisabledLanes&=u,l.shellSuspendCounter=0;var c=l.entanglements,i=l.expirationTimes,d=l.hiddenUpdates;for(u=f&~u;0<u;){var g=31-kl(u),T=1<<g;c[g]=0,i[g]=-1;var h=d[g];if(h!==null)for(d[g]=null,g=0;g<h.length;g++){var S=h[g];S!==null&&(S.lane&=-536870913)}u&=~T}a!==0&&Si(l,a,0),n!==0&&e===0&&l.tag!==0&&(l.suspendedLanes|=n&~(f&~t))}function Si(l,t,u){l.pendingLanes|=t,l.suspendedLanes&=~t;var a=31-kl(t);l.entangledLanes|=t,l.entanglements[a]=l.entanglements[a]|1073741824|u&261930}function gi(l,t){var u=l.entangledLanes|=t;for(l=l.entanglements;u;){var a=31-kl(u),e=1<<a;e&t|l[a]&t&&(l[a]|=t),u&=~e}}function bi(l,t){var u=t&-t;return u=(u&42)!==0?1:Kn(u),(u&(l.suspendedLanes|t))!==0?0:u}function Kn(l){switch(l){case 2:l=1;break;case 8:l=4;break;case 32:l=16;break;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:case 4194304:case 8388608:case 16777216:case 33554432:l=128;break;case 268435456:l=134217728;break;default:l=0}return l}function Jn(l){return l&=-l,2<l?8<l?(l&134217727)!==0?32:268435456:8:2}function zi(){var l=_.p;return l!==0?l:(l=window.event,l===void 0?32:e1(l.type))}function Ti(l,t){var u=_.p;try{return _.p=l,t()}finally{_.p=u}}var $t=Math.random().toString(36).slice(2),Ml="__reactFiber$"+$t,jl="__reactProps$"+$t,ju="__reactContainer$"+$t,wn="__reactEvents$"+$t,B1="__reactListeners$"+$t,G1="__reactHandles$"+$t,Ei="__reactResources$"+$t,ra="__reactMarker$"+$t;function Wn(l){delete l[Ml],delete l[jl],delete l[wn],delete l[B1],delete l[G1]}function Zu(l){var t=l[Ml];if(t)return t;for(var u=l.parentNode;u;){if(t=u[ju]||u[Ml]){if(u=t.alternate,t.child!==null||u!==null&&u.child!==null)for(l=Vv(l);l!==null;){if(u=l[Ml])return u;l=Vv(l)}return t}l=u,u=l.parentNode}return null}function Vu(l){if(l=l[Ml]||l[ju]){var t=l.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return l}return null}function Ha(l){var t=l.tag;if(t===5||t===26||t===27||t===6)return l.stateNode;throw Error(o(33))}function xu(l){var t=l[Ei];return t||(t=l[Ei]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function Al(l){l[ra]=!0}var Ai=new Set,_i={};function Au(l,t){Lu(l,t),Lu(l+"Capture",t)}function Lu(l,t){for(_i[l]=t,l=0;l<t.length;l++)Ai.add(t[l])}var X1=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u21
Line truncated
|
||||
`).replace(os,"")}function Rv(l,t){return t=pv(t),pv(l)===t}function tl(l,t,u,a,e,n){switch(u){case"children":typeof a=="string"?t==="body"||t==="textarea"&&a===""||Ju(l,a):(typeof a=="number"||typeof a=="bigint")&&t!=="body"&&Ju(l,""+a);break;case"className":De(l,"class",a);break;case"tabIndex":De(l,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":De(l,u,a);break;case"style":Ri(l,a,n);break;case"data":if(t!=="object"){De(l,"data",a);break}case"src":case"href":if(a===""&&(t!=="a"||u!=="href")){l.removeAttribute(u);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(u);break}a=re(""+a),l.setAttribute(u,a);break;case"action":case"formAction":if(typeof a=="function"){l.setAttribute(u,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof n=="function"&&(u==="formAction"?(t!=="input"&&tl(l,t,"name",e.name,e,null),tl(l,t,"formEncType",e.formEncType,e,null),tl(l,t,"formMethod",e.formMethod,e,null),tl(l,t,"formTarget",e.formTarget,e,null)):(tl(l,t,"encType",e.encType,e,null),tl(l,t,"method",e.method,e,null),tl(l,t,"target",e.target,e,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(u);break}a=re(""+a),l.setAttribute(u,a);break;case"onClick":a!=null&&(l.onclick=Nt);break;case"onScroll":a!=null&&j("scroll",l);break;case"onScrollEnd":a!=null&&j("scrollend",l);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(u=a.__html,u!=null){if(e.children!=null)throw Error(o(60));l.innerHTML=u}}break;case"multiple":l.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":l.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){l.removeAttribute("xlink:href");break}u=re(""+a),l.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",u);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,""+a):l.removeAttribute(u);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,""):l.removeAttribute(u);break;case"capture":case"download":a===!0?l.setAttribute(u,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,a):l.removeAttribute(u);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?l.setAttribute(u,a):l.removeAttribute(u);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?l.removeAttribute(u):l.setAttribute(u,a);break;case"popover":j("beforetoggle",l),j("toggle",l),Me(l,"popover",a);break;case"xlinkActuate":Ht(l,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Ht(l,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Ht(l,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Ht(l,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Ht(l,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Ht(l,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Me(l,"is",a);break;case"innerText":case"textContent":break;default:(!(2<u.length)||u[0]!=="o"&&u[0]!=="O"||u[1]!=="n"&&u[1]!=="N")&&(u=x1.get(u)||u,Me(l,u,a))}}function Qc(l,t,u,a,e,n){switch(u){case"style":Ri(l,a,n);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(u=a.__html,u!=null){if(e.children!=null)throw Error(o(60));l.innerHTML=u}}break;case"children":typeof a=="string"?Ju(l,a):(typeof a=="number"||typeof a=="bigint")&&Ju(l,""+a);break;case"onScroll":a!=null&&j("scroll",l);break;case"onScrollEnd":a!=null&&j("scrollend",l);break;case"onClick":a!=null&&(l.onclick=Nt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML"
Line truncated
|
||||
`).replace(os,"")}function Rv(l,t){return t=pv(t),pv(l)===t}function tl(l,t,u,a,e,n){switch(u){case"children":typeof a=="string"?t==="body"||t==="textarea"&&a===""||Ju(l,a):(typeof a=="number"||typeof a=="bigint")&&t!=="body"&&Ju(l,""+a);break;case"className":De(l,"class",a);break;case"tabIndex":De(l,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":De(l,u,a);break;case"style":Ri(l,a,n);break;case"data":if(t!=="object"){De(l,"data",a);break}case"src":case"href":if(a===""&&(t!=="a"||u!=="href")){l.removeAttribute(u);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(u);break}a=re(""+a),l.setAttribute(u,a);break;case"action":case"formAction":if(typeof a=="function"){l.setAttribute(u,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof n=="function"&&(u==="formAction"?(t!=="input"&&tl(l,t,"name",e.name,e,null),tl(l,t,"formEncType",e.formEncType,e,null),tl(l,t,"formMethod",e.formMethod,e,null),tl(l,t,"formTarget",e.formTarget,e,null)):(tl(l,t,"encType",e.encType,e,null),tl(l,t,"method",e.method,e,null),tl(l,t,"target",e.target,e,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){l.removeAttribute(u);break}a=re(""+a),l.setAttribute(u,a);break;case"onClick":a!=null&&(l.onclick=Nt);break;case"onScroll":a!=null&&j("scroll",l);break;case"onScrollEnd":a!=null&&j("scrollend",l);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(u=a.__html,u!=null){if(e.children!=null)throw Error(o(60));l.innerHTML=u}}break;case"multiple":l.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":l.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){l.removeAttribute("xlink:href");break}u=re(""+a),l.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",u);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,""+a):l.removeAttribute(u);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,""):l.removeAttribute(u);break;case"capture":case"download":a===!0?l.setAttribute(u,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?l.setAttribute(u,a):l.removeAttribute(u);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?l.setAttribute(u,a):l.removeAttribute(u);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?l.removeAttribute(u):l.setAttribute(u,a);break;case"popover":j("beforetoggle",l),j("toggle",l),Me(l,"popover",a);break;case"xlinkActuate":Ht(l,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":Ht(l,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":Ht(l,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":Ht(l,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":Ht(l,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":Ht(l,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":Ht(l,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":Me(l,"is",a);break;case"innerText":case"textContent":break;default:(!(2<u.length)||u[0]!=="o"&&u[0]!=="O"||u[1]!=="n"&&u[1]!=="N")&&(u=x1.get(u)||u,Me(l,u,a))}}function Qc(l,t,u,a,e,n){switch(u){case"style":Ri(l,a,n);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(u=a.__html,u!=null){if(e.children!=null)throw Error(o(60));l.innerHTML=u}}break;case"children":typeof a=="string"?Ju(l,a):(typeof a=="number"||typeof a=="bigint")&&Ju(l,""+a);break;case"onScroll":a!=null&&j("scroll",l);break;case"onScrollEnd":a!=null&&j("scrollend",l);break;case"onClick":a!=null&&(l.onclick=Nt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML"
Line truncated
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
var Yn=Object.defineProperty;var Gn=(e,t,r)=>t in e?Yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Oe=(e,t,r)=>Gn(e,typeof t!="symbol"?t+"":t,r);import{a as qt,r as K,g as Xn}from"./react-vendor-DZnRGM0-.js";function qr(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=qr(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function Uo(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=qr(e))&&(n&&(n+=" "),n+=t);return n}function At(e){return e==="__proto__"}function Yr(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Yt(e){var t;return typeof e=="string"||typeof e=="symbol"?e:Object.is((t=e==null?void 0:e.valueOf)==null?void 0:t.call(e),-0)?"-0":String(e)}function Gr(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Gr).join(",");const t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function Gt(e){if(Array.isArray(e))return e.map(Yt);if(typeof e=="symbol")return[e];e=Gr(e);const t=[],r=e.length;if(r===0)return t;let n=0,i="",s="",o=!1;for(e.charCodeAt(0)===46&&t.push("");n<r;){const f=e[n];if(s)f==="\\"&&n+1<r?(n++,i+=e[n]):f===s?s="":i+=f;else if(o)f==='"'||f==="'"?s=f:f==="]"?(o=!1,t.push(i),i=""):i+=f;else if(f==="[")o=!0,i&&(t.push(i),i="");else if(f==="."){i&&(t.push(i),i="");const u=e[n+1];(u===void 0||u===".")&&t.push("")}else i+=f;n++}return i&&t.push(i),t}function Xt(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(At(t))return r;const n=e[t];return n===void 0?Yr(t)?Xt(e,Gt(t),r):r:n}case"number":case"symbol":{typeof t=="number"&&(t=Yt(t));const n=e[t];return n===void 0?r:n}default:{if(Array.isArray(t))return Hn(e,t,r);if(Object.is(t==null?void 0:t.valueOf(),-0)?t="-0":t=String(t),At(t))return r;const n=e[t];return n===void 0?r:n}}}function Hn(e,t,r){if(t.length===0)return r;let n=e;for(let i=0;i<t.length;i++){if(n==null||At(t[i]))return r;n=n[t[i]]}return n===void 0?r:n}function Kn(e,t){const r=new Map;for(let n=0;n<e.length;n++){const i=e[n],s=t(i,n,e);r.has(s)||r.set(s,i)}return Array.from(r.values())}function Zn(e,t){return function(...r){return e.apply(this,r.slice(0,t))}}function Xr(e){return e}function Jn(e){return function(t){return Xt(t,e)}}function Pt(e){return e==null||typeof e!="object"&&typeof e!="function"}function Vn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Qn(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function Ht(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const ei="[object RegExp]",Hr="[object String]",Kr="[object Number]",Zr="[object Boolean]",Jr="[object Arguments]",ti="[object Symbol]",ri="[object Date]",ni="[object Map]",ii="[object Set]",si="[object Array]",oi="[object ArrayBuffer]",fi="[object Object]",ui="[object DataView]",ci="[object Uint8Array]",ai="[object Uint8ClampedArray]",li="[object Uint16Array]",di="[object Uint32Array]",hi="[object Int8Array]",pi="[object Int16Array]",yi="[object Int32Array]",mi="[object Float32Array]",_i="[object Float64Array]",sr=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window||typeof self=="object"&&self||typeof global=="object"&&global||(function(){return this})();function gi(e){return typeof sr.Buffer<"u"&&sr.Buffer.isBuffer(e)}function wi(e,t){return te(e,void 0,e,new Map,t)}function te(e,t,r,n=new Map,i=void 0){const s=i==null?void 0:i(e,t,r,n);if(s!==void 0)return s;if(Pt(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){const o=new Array(e.length);n.set(e,o);for(let f=0;f<e.length;f++)o[f]=te(e[f],f,r,n,i);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){const o=new Map;n.set(e,o);for(const[f,u]of e)o.set(f,te(u,f,r,n,i));return o}if(e instanceof Set){const o=new Set;n.set(e,o);for(const f of e)o.add(te(f,void 0,r,n,i));return o}if(gi(e))return e.subarray();if(Vn(e)){const o=new(Object.getPrototypeOf(e)).constructor(e.length);n.set(e,o);for(let f=0;f<e.length;f++)o[f]=te(e[f],f,r,n,i);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return n.set(e,o),j(o,e,r,n,i),o}if(typeof File<"u"&&e instanceof File){const o=new File([e],e.name,{type:e.type});return n.set(e,o),j(o,e,r,n,i),o}if(typeof Blob<"u"&&e instanceof Blob){const o=new Blob([e],{type:e.type});return n.set(e,o),j(o,e,r,n,i),o}if(e instanceof Error){const o=structuredClone(e);return n.set(e,o),o.message=e.message,o.name=e.name,o.staLine truncated
|
||||
var Yn=Object.defineProperty;var Gn=(e,t,r)=>t in e?Yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Oe=(e,t,r)=>Gn(e,typeof t!="symbol"?t+"":t,r);import{a as qt,r as K,g as Xn}from"./react-vendor-C_od1ZSF.js";function qr(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=qr(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function Uo(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=qr(e))&&(n&&(n+=" "),n+=t);return n}function At(e){return e==="__proto__"}function Yr(e){switch(typeof e){case"number":case"symbol":return!1;case"string":return e.includes(".")||e.includes("[")||e.includes("]")}}function Yt(e){var t;return typeof e=="string"||typeof e=="symbol"?e:Object.is((t=e==null?void 0:e.valueOf)==null?void 0:t.call(e),-0)?"-0":String(e)}function Gr(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Gr).join(",");const t=String(e);return t==="0"&&Object.is(Number(e),-0)?"-0":t}function Gt(e){if(Array.isArray(e))return e.map(Yt);if(typeof e=="symbol")return[e];e=Gr(e);const t=[],r=e.length;if(r===0)return t;let n=0,i="",s="",o=!1;for(e.charCodeAt(0)===46&&t.push("");n<r;){const f=e[n];if(s)f==="\\"&&n+1<r?(n++,i+=e[n]):f===s?s="":i+=f;else if(o)f==='"'||f==="'"?s=f:f==="]"?(o=!1,t.push(i),i=""):i+=f;else if(f==="[")o=!0,i&&(t.push(i),i="");else if(f==="."){i&&(t.push(i),i="");const u=e[n+1];(u===void 0||u===".")&&t.push("")}else i+=f;n++}return i&&t.push(i),t}function Xt(e,t,r){if(e==null)return r;switch(typeof t){case"string":{if(At(t))return r;const n=e[t];return n===void 0?Yr(t)?Xt(e,Gt(t),r):r:n}case"number":case"symbol":{typeof t=="number"&&(t=Yt(t));const n=e[t];return n===void 0?r:n}default:{if(Array.isArray(t))return Hn(e,t,r);if(Object.is(t==null?void 0:t.valueOf(),-0)?t="-0":t=String(t),At(t))return r;const n=e[t];return n===void 0?r:n}}}function Hn(e,t,r){if(t.length===0)return r;let n=e;for(let i=0;i<t.length;i++){if(n==null||At(t[i]))return r;n=n[t[i]]}return n===void 0?r:n}function Kn(e,t){const r=new Map;for(let n=0;n<e.length;n++){const i=e[n],s=t(i,n,e);r.has(s)||r.set(s,i)}return Array.from(r.values())}function Zn(e,t){return function(...r){return e.apply(this,r.slice(0,t))}}function Xr(e){return e}function Jn(e){return function(t){return Xt(t,e)}}function Pt(e){return e==null||typeof e!="object"&&typeof e!="function"}function Vn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Qn(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function Ht(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const ei="[object RegExp]",Hr="[object String]",Kr="[object Number]",Zr="[object Boolean]",Jr="[object Arguments]",ti="[object Symbol]",ri="[object Date]",ni="[object Map]",ii="[object Set]",si="[object Array]",oi="[object ArrayBuffer]",fi="[object Object]",ui="[object DataView]",ci="[object Uint8Array]",ai="[object Uint8ClampedArray]",li="[object Uint16Array]",di="[object Uint32Array]",hi="[object Int8Array]",pi="[object Int16Array]",yi="[object Int32Array]",mi="[object Float32Array]",_i="[object Float64Array]",sr=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window||typeof self=="object"&&self||typeof global=="object"&&global||(function(){return this})();function gi(e){return typeof sr.Buffer<"u"&&sr.Buffer.isBuffer(e)}function wi(e,t){return te(e,void 0,e,new Map,t)}function te(e,t,r,n=new Map,i=void 0){const s=i==null?void 0:i(e,t,r,n);if(s!==void 0)return s;if(Pt(e))return e;if(n.has(e))return n.get(e);if(Array.isArray(e)){const o=new Array(e.length);n.set(e,o);for(let f=0;f<e.length;f++)o[f]=te(e[f],f,r,n,i);return Object.hasOwn(e,"index")&&(o.index=e.index),Object.hasOwn(e,"input")&&(o.input=e.input),o}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const o=new RegExp(e.source,e.flags);return o.lastIndex=e.lastIndex,o}if(e instanceof Map){const o=new Map;n.set(e,o);for(const[f,u]of e)o.set(f,te(u,f,r,n,i));return o}if(e instanceof Set){const o=new Set;n.set(e,o);for(const f of e)o.add(te(f,void 0,r,n,i));return o}if(gi(e))return e.subarray();if(Vn(e)){const o=new(Object.getPrototypeOf(e)).constructor(e.length);n.set(e,o);for(let f=0;f<e.length;f++)o[f]=te(e[f],f,r,n,i);return o}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const o=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return n.set(e,o),j(o,e,r,n,i),o}if(typeof File<"u"&&e instanceof File){const o=new File([e],e.name,{type:e.type});return n.set(e,o),j(o,e,r,n,i),o}if(typeof Blob<"u"&&e instanceof Blob){const o=new Blob([e],{type:e.type});return n.set(e,o),j(o,e,r,n,i),o}if(e instanceof Error){const o=structuredClone(e);return n.set(e,o),o.message=e.message,o.name=e.name,o.staLine truncated
|
||||
* @license React
|
||||
* use-sync-external-store-shim.production.js
|
||||
*
|
||||
@@ -6,12 +6,12 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-2_f0Vmhn.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-RenKjhri.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/vendor-w5t2K9ux.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-B_BfwiL0.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-DMeflf1O.css">
|
||||
<script type="module" crossorigin src="/static/assets/index-BIyp4is6.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-DjsKcZkz.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-BxxJOyEX.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-DtBcYu3b.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
const (
|
||||
RateCreateAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.rate.create/4.0/"
|
||||
PendingRateListAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.merchant.rate.list/1.0/"
|
||||
PolishItemAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.item.polish/1.0/"
|
||||
PolishItemBackupAPI = "https://h5api.m.goofish.com/h5/mtop.idle.item.polish/1.0/"
|
||||
)
|
||||
|
||||
type PendingRateOrder struct {
|
||||
TradeID string `json:"trade_id"`
|
||||
ItemID string `json:"item_id"`
|
||||
}
|
||||
|
||||
type PendingRateResult struct {
|
||||
Orders []PendingRateOrder
|
||||
UpdatedCookies string
|
||||
}
|
||||
|
||||
type AccountTaskResult struct {
|
||||
Success bool
|
||||
Message string
|
||||
UpdatedCookies string
|
||||
}
|
||||
|
||||
func (c *ClientImpl) FetchPendingRateOrders(ctx context.Context, cookiesStr string, page, pageSize int) (*PendingRateResult, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 50
|
||||
}
|
||||
data := map[string]any{"pageNumber": page, "rowsPerPage": pageSize, "queryType": "ORDER",
|
||||
"rateSearchParam": map[string]any{"sellerRateStatus": "5"}}
|
||||
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr, firstNonEmptyURL(c.RateListURL, PendingRateListAPI),
|
||||
"mtop.taobao.idle.merchant.rate.list", "1.0", data, "https://seller.goofish.com/")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
module, _ := decoded.Data["module"].(map[string]any)
|
||||
items, _ := module["items"].([]any)
|
||||
orders := make([]PendingRateOrder, 0, len(items))
|
||||
seen := make(map[string]struct{}, len(items))
|
||||
for _, item := range items {
|
||||
tradeID := findStringField(item, "tradeId", "trade_id", "orderId", "orderNo", "order_no")
|
||||
if tradeID == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[tradeID]; ok {
|
||||
continue
|
||||
}
|
||||
seen[tradeID] = struct{}{}
|
||||
orders = append(orders, PendingRateOrder{TradeID: tradeID,
|
||||
ItemID: findStringField(item, "itemId", "item_id")})
|
||||
}
|
||||
return &PendingRateResult{Orders: orders, UpdatedCookies: updated}, nil
|
||||
}
|
||||
|
||||
func (c *ClientImpl) RateBuyer(ctx context.Context, cookiesStr, tradeID, feedback string) (*AccountTaskResult, error) {
|
||||
feedback = strings.TrimSpace(feedback)
|
||||
if feedback == "" {
|
||||
feedback = "不错的买家,交易愉快"
|
||||
}
|
||||
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr, firstNonEmptyURL(c.RateCreateURL, RateCreateAPI),
|
||||
"mtop.taobao.idle.rate.create", "4.0", map[string]any{
|
||||
"tradeId": tradeID, "rate": 1, "feedback": feedback, "createOrAppend": 0,
|
||||
}, "https://www.goofish.com/")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &AccountTaskResult{Success: true, Message: firstRet(decoded.Ret), UpdatedCookies: updated}, nil
|
||||
}
|
||||
|
||||
func (c *ClientImpl) PolishItem(ctx context.Context, cookiesStr, itemID string) (*AccountTaskResult, error) {
|
||||
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr, firstNonEmptyURL(c.PolishItemURL, PolishItemAPI),
|
||||
"mtop.taobao.idle.item.polish", "2.0", map[string]any{"itemId": itemID}, "https://www.goofish.com/")
|
||||
if err == nil {
|
||||
return &AccountTaskResult{Success: true, Message: firstRet(decoded.Ret), UpdatedCookies: updated}, nil
|
||||
}
|
||||
if duplicatePolishError(err) {
|
||||
return &AccountTaskResult{Success: true, Message: "商品今天已经擦亮", UpdatedCookies: updated}, nil
|
||||
}
|
||||
primaryErr := err
|
||||
if strings.TrimSpace(updated) == "" {
|
||||
updated = cookiesStr
|
||||
}
|
||||
decoded, backupUpdated, backupErr := c.accountTaskRequest(ctx, updated,
|
||||
firstNonEmptyURL(c.PolishItemBackupURL, PolishItemBackupAPI), "mtop.idle.item.polish", "1.0",
|
||||
map[string]any{"itemId": itemID}, "https://www.goofish.com/")
|
||||
if backupErr == nil {
|
||||
return &AccountTaskResult{Success: true, Message: firstRet(decoded.Ret), UpdatedCookies: backupUpdated}, nil
|
||||
}
|
||||
if duplicatePolishError(backupErr) {
|
||||
return &AccountTaskResult{Success: true, Message: "商品今天已经擦亮", UpdatedCookies: backupUpdated}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("擦亮主接口失败: %v;备用接口失败: %w", primaryErr, backupErr)
|
||||
}
|
||||
|
||||
func duplicatePolishError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "IDLEITEM_POLISH_AGAIN") || strings.Contains(msg, "已经擦亮") ||
|
||||
strings.Contains(msg, "POLISH_DUPLICATE") || strings.Contains(msg, "一天只能擦亮一次")
|
||||
}
|
||||
|
||||
type accountTaskResponse struct {
|
||||
Ret []string `json:"ret"`
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
|
||||
func (c *ClientImpl) accountTaskRequest(ctx context.Context, cookiesStr, endpoint, api, version string, data map[string]any, referer string) (*accountTaskResponse, string, error) {
|
||||
current := cookiesStr
|
||||
if session := cookieSessionFromContext(ctx); session != nil {
|
||||
current, _, _ = session.State()
|
||||
}
|
||||
var lastRet []string
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
decoded, updated, err := c.accountTaskRequestOnce(ctx, current, endpoint, api, version, data, referer)
|
||||
if err != nil {
|
||||
return nil, current, err
|
||||
}
|
||||
lastRet = decoded.Ret
|
||||
if hasMTopSuccess(decoded.Ret) {
|
||||
return decoded, updated, nil
|
||||
}
|
||||
if isRiskVerificationRet(decoded.Ret) {
|
||||
return nil, updated, &RiskVerificationError{Ret: decoded.Ret}
|
||||
}
|
||||
if !isTokenExpiredRet(decoded.Ret) {
|
||||
return nil, updated, fmt.Errorf("%s 返回失败: %s", api, firstRet(decoded.Ret))
|
||||
}
|
||||
current = updated
|
||||
if current == cookiesStr {
|
||||
refreshed, refreshErr := c.RefreshTokenContext(ctx, current)
|
||||
if refreshErr != nil {
|
||||
return nil, current, fmt.Errorf("刷新 mtop token: %w", refreshErr)
|
||||
}
|
||||
current = refreshed.UpdatedCookies
|
||||
}
|
||||
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
|
||||
return nil, current, err
|
||||
}
|
||||
}
|
||||
return nil, current, fmt.Errorf("%s token 重试失败: %s", api, firstRet(lastRet))
|
||||
}
|
||||
|
||||
func (c *ClientImpl) accountTaskRequestOnce(ctx context.Context, cookiesStr, endpoint, api, version string, data map[string]any, referer string) (*accountTaskResponse, string, error) {
|
||||
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, referer, endpoint)
|
||||
token := protocol.SignToken(signingCookies)
|
||||
if token == "" {
|
||||
return nil, cookiesStr, fmt.Errorf("cookie 缺少 _m_h5_tk,无法调用 %s", api)
|
||||
}
|
||||
rawData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, cookiesStr, err
|
||||
}
|
||||
dataVal := string(rawData)
|
||||
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
sign := protocol.GenerateSign(t, token, dataVal)
|
||||
query := url.Values{}
|
||||
query.Set("jsv", "2.7.2")
|
||||
query.Set("appKey", protocol.SignAppKey)
|
||||
query.Set("t", t)
|
||||
query.Set("sign", sign)
|
||||
query.Set("v", version)
|
||||
responseType := "originaljson"
|
||||
if api == "mtop.taobao.idle.merchant.rate.list" {
|
||||
responseType = "json"
|
||||
query.Set("valueType", "string")
|
||||
}
|
||||
query.Set("type", responseType)
|
||||
query.Set("accountSite", "xianyu")
|
||||
query.Set("dataType", "json")
|
||||
query.Set("timeout", "20000")
|
||||
query.Set("api", api)
|
||||
query.Set("sessionOption", "AutoLoginOnly")
|
||||
if api == "mtop.taobao.idlemessage.pc.user.query" {
|
||||
query.Set("spm_cnt", "a21ybx.im.0.0")
|
||||
query.Set("spm_pre", "a21ybx.home.sidebar.2.4c053da6MpVe1m")
|
||||
query.Set("log_id", "4c053da6MpVe1m")
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+query.Encode(),
|
||||
strings.NewReader("data="+url.QueryEscape(dataVal)))
|
||||
if err != nil {
|
||||
return nil, cookiesStr, err
|
||||
}
|
||||
setCommonHeaders(req, requestCookies)
|
||||
req.Header.Set("Referer", referer)
|
||||
if parsedReferer, parseErr := url.Parse(referer); parseErr == nil && parsedReferer.Scheme != "" && parsedReferer.Host != "" {
|
||||
req.Header.Set("Origin", parsedReferer.Scheme+"://"+parsedReferer.Host)
|
||||
}
|
||||
resp, err := c.httpClientWithTimeout(25 * time.Second).Do(req)
|
||||
if err != nil {
|
||||
return nil, cookiesStr, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
|
||||
raw, err := readMTopBody(resp)
|
||||
if err != nil {
|
||||
return nil, updated, err
|
||||
}
|
||||
var decoded accountTaskResponse
|
||||
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||
return nil, updated, fmt.Errorf("解析 %s 响应: %w", api, err)
|
||||
}
|
||||
return &decoded, updated, nil
|
||||
}
|
||||
|
||||
func firstRet(ret []string) string {
|
||||
if len(ret) == 0 {
|
||||
return "未知响应"
|
||||
}
|
||||
return ret[0]
|
||||
}
|
||||
|
||||
func firstNonEmptyURL(configured, fallback string) string {
|
||||
if strings.TrimSpace(configured) != "" {
|
||||
return configured
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func findStringField(value any, keys ...string) string {
|
||||
wanted := make(map[string]struct{}, len(keys))
|
||||
for _, key := range keys {
|
||||
wanted[key] = struct{}{}
|
||||
}
|
||||
var walk func(any) string
|
||||
walk = func(v any) string {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range x {
|
||||
if _, ok := wanted[key]; ok {
|
||||
if text := mtopString(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, child := range x {
|
||||
if text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range x {
|
||||
if text := walk(child); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return walk(value)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestLivePolishAccount is opt-in because it calls the real Xianyu APIs and
|
||||
// changes the selected account's daily polish state. It never logs credentials.
|
||||
func TestLivePolishAccount(t *testing.T) {
|
||||
if os.Getenv("TEST_XIANYU_LIVE") != "1" {
|
||||
t.Skip("set TEST_XIANYU_LIVE=1 to run against a real account")
|
||||
}
|
||||
dbURL := os.Getenv("TEST_XIANYU_DB_URL")
|
||||
accountID := os.Getenv("TEST_XIANYU_ACCOUNT_ID")
|
||||
if dbURL == "" || accountID == "" {
|
||||
t.Fatal("TEST_XIANYU_DB_URL and TEST_XIANYU_ACCOUNT_ID are required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
database, dialect, err := db.Open(ctx, dbURL)
|
||||
if err != nil {
|
||||
t.Fatalf("open test database: %v", err)
|
||||
}
|
||||
defer database.Close()
|
||||
store := db.NewStore(database, dialect)
|
||||
cookies, err := store.Cookies.GetValue(ctx, accountID)
|
||||
if err != nil {
|
||||
t.Fatalf("read account credentials: %v", err)
|
||||
}
|
||||
client := &ClientImpl{}
|
||||
items, err := client.FetchAllItems(ctx, cookies, 20, 20)
|
||||
if err != nil {
|
||||
t.Fatalf("fetch live items: %v", err)
|
||||
}
|
||||
current := cookies
|
||||
if items.UpdatedCookies != "" {
|
||||
current = items.UpdatedCookies
|
||||
}
|
||||
for _, item := range items.Items {
|
||||
result, polishErr := client.PolishItem(ctx, current, item.ID)
|
||||
if polishErr != nil || result == nil || !result.Success {
|
||||
t.Fatalf("polish item %s: result=%+v err=%v", item.ID, result, polishErr)
|
||||
}
|
||||
if result.UpdatedCookies != "" {
|
||||
current = result.UpdatedCookies
|
||||
}
|
||||
}
|
||||
t.Logf("live polish responses accepted for %d items", len(items.Items))
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAccountTaskEndpointsAndParsing(t *testing.T) {
|
||||
var received map[string]any
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(r.Form.Get("data")), &received); err != nil {
|
||||
t.Fatalf("decode data: %v", err)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Query().Get("api") {
|
||||
case "mtop.taobao.idle.merchant.rate.list":
|
||||
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{"module":{"items":[{"tradeInfo":{"tradeId":"order-1"},"item":{"itemId":"item-1"}},{"orderNo":"order-2","itemId":"item-2"}]}}}`))
|
||||
case "mtop.taobao.idle.rate.create":
|
||||
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{}}`))
|
||||
case "mtop.taobao.idle.item.polish":
|
||||
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{}}`))
|
||||
default:
|
||||
t.Fatalf("unexpected api: %s", r.URL.Query().Get("api"))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := &ClientImpl{HTTPClient: server.Client(), RateListURL: server.URL, RateCreateURL: server.URL, PolishItemURL: server.URL}
|
||||
cookies := "unb=123; _m_h5_tk=token_1"
|
||||
pending, err := client.FetchPendingRateOrders(context.Background(), cookies, 1, 50)
|
||||
if err != nil || len(pending.Orders) != 2 || pending.Orders[0].TradeID != "order-1" || pending.Orders[0].ItemID != "item-1" {
|
||||
t.Fatalf("pending=%+v err=%v", pending, err)
|
||||
}
|
||||
rate, err := client.RateBuyer(context.Background(), cookies, "order-1", "交易愉快")
|
||||
if err != nil || !rate.Success || received["tradeId"] != "order-1" || received["feedback"] != "交易愉快" {
|
||||
t.Fatalf("rate=%+v received=%+v err=%v", rate, received, err)
|
||||
}
|
||||
polish, err := client.PolishItem(context.Background(), cookies, "item-1")
|
||||
if err != nil || !polish.Success || received["itemId"] != "item-1" {
|
||||
t.Fatalf("polish=%+v received=%+v err=%v", polish, received, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTaskRequestUsesSignedForm(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost || r.Header.Get("Cookie") == "" || r.URL.Query().Get("sign") == "" {
|
||||
t.Fatalf("request method=%s cookie=%q query=%v", r.Method, r.Header.Get("Cookie"), r.URL.Query())
|
||||
}
|
||||
body, _ := url.ParseQuery(func() string { _ = r.ParseForm(); return r.Form.Encode() }())
|
||||
if body.Get("data") == "" {
|
||||
t.Fatal("missing data form")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"ret":["FAIL_BIZ_IDLEITEM_POLISH_AGAIN::宝贝已经擦亮过了"],"data":{}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := &ClientImpl{HTTPClient: server.Client(), PolishItemURL: server.URL}
|
||||
result, err := client.PolishItem(context.Background(), "unb=123; _m_h5_tk=token_1", "item-1")
|
||||
if err != nil || !result.Success {
|
||||
t.Fatalf("duplicate polish should be success: result=%+v err=%v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolishItemFallsBackToAlternateAPI(t *testing.T) {
|
||||
var calls []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
api := r.URL.Query().Get("api")
|
||||
calls = append(calls, api)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if api == "mtop.taobao.idle.item.polish" {
|
||||
_, _ = w.Write([]byte(`{"ret":["FAIL_BIZ_FORBIDDEN::主接口暂不可用"],"data":{}}`))
|
||||
return
|
||||
}
|
||||
if api != "mtop.idle.item.polish" || r.URL.Query().Get("v") != "1.0" {
|
||||
t.Fatalf("unexpected backup request: api=%s version=%s", api, r.URL.Query().Get("v"))
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var data map[string]any
|
||||
if err := json.Unmarshal([]byte(r.Form.Get("data")), &data); err != nil || data["itemId"] != "item-1" {
|
||||
t.Fatalf("backup data=%v err=%v", data, err)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := &ClientImpl{HTTPClient: server.Client(), PolishItemURL: server.URL, PolishItemBackupURL: server.URL}
|
||||
result, err := client.PolishItem(context.Background(), "unb=123; _m_h5_tk=token_1", "item-1")
|
||||
if err != nil || result == nil || !result.Success {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
want := []string{"mtop.taobao.idle.item.polish", "mtop.idle.item.polish"}
|
||||
if len(calls) != len(want) || calls[0] != want[0] || calls[1] != want[1] {
|
||||
t.Fatalf("calls=%v want=%v", calls, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const ChatUserQueryAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.user.query/4.0/"
|
||||
|
||||
type ChatUserInfo struct {
|
||||
Nickname string
|
||||
AvatarURL string
|
||||
UpdatedCookies string
|
||||
}
|
||||
|
||||
type ChatImageUpload struct {
|
||||
URL string
|
||||
Width int
|
||||
Height int
|
||||
UpdatedCookies string
|
||||
}
|
||||
|
||||
// FetchChatUserInfo resolves the peer identity for a conversation. Xianyu's
|
||||
// API expects the conversation id as sessionId rather than the user id.
|
||||
func (c *ClientImpl) FetchChatUserInfo(ctx context.Context, cookiesStr, chatID string) (*ChatUserInfo, error) {
|
||||
decoded, updated, err := c.accountTaskRequest(ctx, cookiesStr,
|
||||
firstNonEmptyURL(c.ChatUserQueryURL, ChatUserQueryAPI), "mtop.taobao.idlemessage.pc.user.query", "4.0",
|
||||
map[string]any{"type": 0, "sessionType": 1, "sessionId": strings.TrimSpace(chatID), "isOwner": false},
|
||||
"https://www.goofish.com/")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userInfo, _ := decoded.Data["userInfo"].(map[string]any)
|
||||
if userInfo == nil {
|
||||
return nil, fmt.Errorf("会话用户接口响应缺少 userInfo")
|
||||
}
|
||||
nickname := strings.TrimSpace(mtopString(userInfo["fishNick"]))
|
||||
if nickname == "" {
|
||||
nickname = strings.TrimSpace(mtopString(userInfo["nick"]))
|
||||
}
|
||||
return &ChatUserInfo{Nickname: nickname,
|
||||
AvatarURL: strings.TrimSpace(mtopString(userInfo["logo"])), UpdatedCookies: updated}, nil
|
||||
}
|
||||
|
||||
func (c *ClientImpl) UploadChatImage(ctx context.Context, cookiesStr, filename, contentType string, data []byte) (*ChatImageUpload, error) {
|
||||
uploaded, updated, err := c.uploadPublishImage(ctx, cookiesStr, PublishImage{
|
||||
Filename: filename, ContentType: contentType, Data: data,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ChatImageUpload{URL: uploaded.URL, Width: uploaded.Width, Height: uploaded.Height, UpdatedCookies: updated}, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package mtop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFetchChatUserInfoUsesConversationAndParsesIdentity(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("api") != "mtop.taobao.idlemessage.pc.user.query" || r.URL.Query().Get("v") != "4.0" {
|
||||
t.Fatalf("query=%v", r.URL.Query())
|
||||
}
|
||||
if r.URL.Query().Get("spm_cnt") != "a21ybx.im.0.0" || r.URL.Query().Get("spm_pre") == "" || r.URL.Query().Get("log_id") == "" {
|
||||
t.Fatalf("missing official IM query context: %v", r.URL.Query())
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal([]byte(r.Form.Get("data")), &payload); err != nil || payload["sessionId"] != "chat-1" || payload["isOwner"] != false {
|
||||
t.Fatalf("payload=%v err=%v", payload, err)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{"userInfo":{"fishNick":"闲鱼真实昵称","nick":"x***3","logo":"https://cdn/avatar.jpg"}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := &ClientImpl{HTTPClient: server.Client(), ChatUserQueryURL: server.URL}
|
||||
info, err := client.FetchChatUserInfo(context.Background(), "unb=123; _m_h5_tk=token_1", "chat-1")
|
||||
if err != nil || info.Nickname != "闲鱼真实昵称" || info.AvatarURL != "https://cdn/avatar.jpg" {
|
||||
t.Fatalf("info=%+v err=%v", info, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchChatUserInfoFallsBackToNickWhenFishNickMissing(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"ret":["SUCCESS::调用成功"],"data":{"userInfo":{"nick":"兼容昵称","logo":"https://cdn/fallback.jpg"}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client := &ClientImpl{HTTPClient: server.Client(), ChatUserQueryURL: server.URL}
|
||||
info, err := client.FetchChatUserInfo(context.Background(), "unb=123; _m_h5_tk=token_1", "chat-2")
|
||||
if err != nil || info.Nickname != "兼容昵称" {
|
||||
t.Fatalf("info=%+v err=%v", info, err)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -61,13 +62,72 @@ type Client interface {
|
||||
// ClientImpl 是 Client 接口的 HTTP 实现。零值可用;HTTP 超时默认 30s。
|
||||
// 仍导出 HTTPClient/TokenURL 等字段以便调用方覆盖(如测试注入 RoundTripper)。
|
||||
type ClientImpl struct {
|
||||
HTTPClient *http.Client
|
||||
TokenURL string
|
||||
ConsignURL string
|
||||
OrderDetailURL string
|
||||
SoldOrdersURL string
|
||||
ItemDetailURL string
|
||||
LoginUserURL string
|
||||
HTTPClient *http.Client
|
||||
// Logger 记录 MTOP 请求的安全摘要(不会输出 Cookie、签名或响应正文)。
|
||||
// 未设置时使用 slog.Default,测试可传入丢弃日志的 logger。
|
||||
Logger *slog.Logger
|
||||
TokenURL string
|
||||
ConsignURL string
|
||||
OrderDetailURL string
|
||||
SoldOrdersURL string
|
||||
ItemDetailURL string
|
||||
LoginUserURL string
|
||||
RateCreateURL string
|
||||
RateListURL string
|
||||
PolishItemURL string
|
||||
PolishItemBackupURL string
|
||||
ChatUserQueryURL string
|
||||
}
|
||||
|
||||
// httpClient 返回带统一请求/响应日志的 HTTP 客户端副本。统一放在传输层,
|
||||
// 确保 token、续期、订单、商品和发布等所有 MTOP 调用都具备一致的可观测性。
|
||||
func (c *ClientImpl) httpClient() *http.Client {
|
||||
return c.httpClientWithTimeout(30 * time.Second)
|
||||
}
|
||||
|
||||
func (c *ClientImpl) httpClientWithTimeout(defaultTimeout time.Duration) *http.Client {
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: defaultTimeout}
|
||||
}
|
||||
clone := *hc
|
||||
transport := hc.Transport
|
||||
if transport == nil {
|
||||
transport = http.DefaultTransport
|
||||
}
|
||||
clone.Transport = loggingTransport{base: transport, logger: c.Logger}
|
||||
return &clone
|
||||
}
|
||||
|
||||
type loggingTransport struct {
|
||||
base http.RoundTripper
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
logger := t.logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
started := time.Now()
|
||||
logger.Debug("MTOP 请求开始", "method", req.Method, "path", req.URL.Path)
|
||||
resp, err := t.base.RoundTrip(req)
|
||||
attrs := []any{"method", req.Method, "path", req.URL.Path, "duration", time.Since(started).Round(time.Millisecond)}
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
logger.Debug("MTOP 请求取消", append(attrs, "err", err)...)
|
||||
} else {
|
||||
logger.Warn("MTOP 请求失败", append(attrs, "err", err)...)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
responseAttrs := append(attrs, "status", resp.StatusCode, "content_length", resp.ContentLength)
|
||||
if resp.StatusCode >= http.StatusBadRequest {
|
||||
logger.Warn("MTOP HTTP 响应异常", responseAttrs...)
|
||||
} else {
|
||||
logger.Debug("MTOP 响应收到", responseAttrs...)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// NewClient 构造纯 Go HTTP 的 MTOP 客户端。Chromium 只用于读取本机指纹
|
||||
|
||||
@@ -68,10 +68,7 @@ func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID str
|
||||
}
|
||||
|
||||
func (c *ClientImpl) 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}
|
||||
}
|
||||
hc := c.httpClient()
|
||||
consignURL := c.ConsignURL
|
||||
if consignURL == "" {
|
||||
consignURL = ConsignAPI
|
||||
|
||||
@@ -49,10 +49,7 @@ func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID st
|
||||
req.Header.Set("Origin", "https://www.goofish.com")
|
||||
req.Header.Set("Referer", documentURL)
|
||||
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
hc := c.httpClient()
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("商品详情请求失败: %w", err)
|
||||
|
||||
@@ -59,10 +59,7 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
|
||||
}
|
||||
|
||||
func (c *ClientImpl) 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}
|
||||
}
|
||||
hc := c.httpClient()
|
||||
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", ItemListAPI)
|
||||
cookies := protocol.TransCookies(signingCookies)
|
||||
userID := cookies["unb"]
|
||||
|
||||
@@ -38,10 +38,7 @@ func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr str
|
||||
if session := cookieSessionFromContext(ctx); session != nil {
|
||||
cookiesStr, _, _ = session.State()
|
||||
}
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 20 * time.Second}
|
||||
}
|
||||
hc := c.httpClientWithTimeout(20 * time.Second)
|
||||
loginURL := c.LoginUserURL
|
||||
if loginURL == "" {
|
||||
loginURL = LoginUserAPI
|
||||
|
||||
@@ -66,10 +66,7 @@ func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID s
|
||||
}
|
||||
|
||||
func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, []string, string, error) {
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
hc := c.httpClient()
|
||||
endpoint := c.OrderDetailURL
|
||||
if endpoint == "" {
|
||||
endpoint = OrderDetailAPI
|
||||
|
||||
@@ -208,10 +208,7 @@ func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, k
|
||||
}
|
||||
|
||||
func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string, img PublishImage) (uploadedImage, string, error) {
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 60 * time.Second}
|
||||
}
|
||||
hc := c.httpClientWithTimeout(60 * time.Second)
|
||||
if img.ContentType == "" {
|
||||
img.ContentType = "application/octet-stream"
|
||||
}
|
||||
@@ -495,10 +492,7 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
|
||||
}
|
||||
|
||||
func (c *ClientImpl) 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}
|
||||
}
|
||||
hc := c.httpClient()
|
||||
rawData, _ := json.Marshal(data)
|
||||
dataVal := string(rawData)
|
||||
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", endpoint)
|
||||
|
||||
@@ -88,10 +88,7 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
|
||||
req.Header.Set("Referer", soldOrdersReferer)
|
||||
req.Header.Set("idle_site_biz_code", "COMMONPRO")
|
||||
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
hc := c.httpClient()
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("订单列表请求失败: %w", err)
|
||||
|
||||
@@ -154,10 +154,7 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS
|
||||
}
|
||||
|
||||
func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (string, int64, []string, string, []cookierefresh.BrowserCookie, string, int, bool, bool, error) {
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 20 * time.Second}
|
||||
}
|
||||
hc := c.httpClientWithTimeout(20 * time.Second)
|
||||
|
||||
tokenURL := c.TokenURL
|
||||
if tokenURL == "" {
|
||||
|
||||
@@ -53,10 +53,7 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*
|
||||
}
|
||||
|
||||
func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string) (*UserProfileResult, []string, string, error) {
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
hc := c.httpClient()
|
||||
|
||||
dataVal := "{}"
|
||||
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", UserPageNavAPI)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -232,9 +233,11 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg
|
||||
if result.conn != nil {
|
||||
_ = result.conn.CloseNow()
|
||||
}
|
||||
logger.Warn("闲鱼 WebSocket 握手失败", "url", target, "err", result.err)
|
||||
return nil, fmt.Errorf("WS dial: %w", result.err)
|
||||
}
|
||||
result.conn.SetReadLimit(8 << 20)
|
||||
logger.Info("闲鱼 WebSocket 握手成功", "url", target)
|
||||
return newConn(result.conn, cfg, logger), nil
|
||||
}
|
||||
|
||||
@@ -350,6 +353,8 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
|
||||
headers["mid"] = mid
|
||||
}
|
||||
key := midKey(mid)
|
||||
started := time.Now()
|
||||
c.logger.Debug("WS 请求发送", "path", path, "mid", key)
|
||||
responseCh := make(chan map[string]any, 1)
|
||||
c.pendingMu.Lock()
|
||||
c.pending[key] = responseCh
|
||||
@@ -365,10 +370,13 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
|
||||
frame["body"] = body
|
||||
}
|
||||
if err := c.sendJSON(requestCtx, frame); err != nil {
|
||||
c.logger.Warn("WS 请求发送失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
|
||||
return nil, err
|
||||
}
|
||||
select {
|
||||
case response := <-responseCh:
|
||||
code, _ := responseCode(response["code"])
|
||||
c.logResponse(path, key, code, time.Since(started))
|
||||
return response, nil
|
||||
case <-c.readDone:
|
||||
// readPump always dispatches a decoded response before it can observe the
|
||||
@@ -376,15 +384,93 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
|
||||
// matching browser event ordering (message before close).
|
||||
select {
|
||||
case response := <-responseCh:
|
||||
code, _ := responseCode(response["code"])
|
||||
c.logResponse(path, key, code, time.Since(started))
|
||||
return response, nil
|
||||
default:
|
||||
}
|
||||
return nil, c.connectionReadError()
|
||||
err := c.connectionReadError()
|
||||
c.logger.Warn("WS 请求因连接结束失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
|
||||
return nil, err
|
||||
case <-requestCtx.Done():
|
||||
return nil, requestCtx.Err()
|
||||
err := requestCtx.Err()
|
||||
if errors.Is(err, context.Canceled) {
|
||||
c.logger.Debug("WS 请求取消", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
|
||||
} else {
|
||||
c.logger.Warn("WS 请求超时", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// ListUserMessages retrieves one page of official IM history for a conversation.
|
||||
// The cursor is opaque to callers; zero selects the newest page.
|
||||
func (c *Conn) ListUserMessages(ctx context.Context, cid string, cursor int64, limit int) (map[string]any, error) {
|
||||
cid = strings.TrimSpace(cid)
|
||||
if cid == "" {
|
||||
return nil, errors.New("聊天历史缺少会话 ID")
|
||||
}
|
||||
if !strings.Contains(cid, "@") {
|
||||
cid += "@goofish"
|
||||
}
|
||||
if cursor <= 0 {
|
||||
cursor = 9007199254740991
|
||||
}
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 50
|
||||
}
|
||||
response, err := c.request(ctx, "/r/MessageManager/listUserMessages", nil,
|
||||
[]any{cid, false, cursor, limit, false}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
|
||||
return nil, fmt.Errorf("聊天历史接口返回状态 %d", code)
|
||||
}
|
||||
body, ok := response["body"].(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("聊天历史接口响应缺少 body")
|
||||
}
|
||||
if reason := strings.TrimSpace(fmt.Sprint(body["reason"])); reason != "" && reason != "<nil>" {
|
||||
return nil, fmt.Errorf("聊天历史接口失败: %s", reason)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// ListConversations retrieves one page of the account's official IM contacts.
|
||||
func (c *Conn) ListConversations(ctx context.Context, cursor int64, limit int) (map[string]any, error) {
|
||||
if cursor <= 0 {
|
||||
cursor = 9007199254740991
|
||||
}
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 100
|
||||
}
|
||||
response, err := c.request(ctx, "/r/Conversation/listNewestPagination", nil, []any{cursor, limit}, regResponseTimeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
|
||||
return nil, fmt.Errorf("会话列表接口返回状态 %d", code)
|
||||
}
|
||||
body, ok := response["body"].(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("会话列表接口响应缺少 body")
|
||||
}
|
||||
if reason := strings.TrimSpace(fmt.Sprint(body["reason"])); reason != "" && reason != "<nil>" {
|
||||
return nil, fmt.Errorf("会话列表接口失败: %s", reason)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (c *Conn) logResponse(path, mid string, code int, duration time.Duration) {
|
||||
attrs := []any{"path", path, "mid", mid, "code", code, "duration", duration.Round(time.Millisecond)}
|
||||
if code >= 400 {
|
||||
c.logger.Warn("WS 业务响应异常", attrs...)
|
||||
return
|
||||
}
|
||||
c.logger.Debug("WS 响应收到", attrs...)
|
||||
}
|
||||
|
||||
func (c *Conn) readPump() {
|
||||
defer close(c.readDone)
|
||||
for {
|
||||
|
||||
Reference in new issue
Block a user