修复前后端逻辑并完善多数据库测试

统一仪表盘、AI 回复、卡密、扫码和通知等前后端行为,补齐并发与失败恢复测试。新增 MySQL 8.4、PostgreSQL 17 持久化 Docker 功能测试和 SQLite 脱敏播种工具。
This commit is contained in:
Christ committed 2026-07-10 14:39:13 +08:00
1 parent 45f895d0c4
commit 2f20a54f30
79 files changed
+2684 -2598

No files matched your search

+1
View File
@@ -5,6 +5,7 @@
/init-admin
*.exe
*.test
!/Dockerfile.test
*.out
# Runtime data
+5 -1
View File
@@ -22,7 +22,9 @@ COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=frontend /src/internal/webui/static ./internal/webui/static
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server \
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
FROM debian:13-slim AS runtime
ENV TZ=Asia/Shanghai
@@ -43,6 +45,8 @@ RUN apt-get update \
tzdata \
&& rm -rf /var/lib/apt/lists/*
COPY --from=backend /out/xianyu-server /app/xianyu-server
COPY --from=backend /out/xianyu-dbseed /app/xianyu-dbseed
COPY --from=backend /out/xianyu-dbverify /app/xianyu-dbverify
COPY --from=playwright-driver /ms-playwright-go /ms-playwright-go
RUN mkdir -p /app/data /app/browser_data
EXPOSE 8080
+31
View File
@@ -0,0 +1,31 @@
# syntax=docker/dockerfile:1.7
FROM node:22-trixie AS frontend-assets
WORKDIR /src/frontend
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
FROM golang:1.26-trixie AS go-test
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=frontend-assets /src/internal/webui/static ./internal/webui/static
CMD ["go", "test", "-race", "-timeout=20m", "./..."]
FROM golangci/golangci-lint:v2.12.2 AS go-lint
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=frontend-assets /src/internal/webui/static ./internal/webui/static
CMD ["golangci-lint", "run", "./..."]
FROM node:22-trixie AS frontend-test
WORKDIR /src/frontend
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ ./
CMD ["sh", "-c", "npm test && npm run build"]
+1 -1
View File
@@ -43,7 +43,7 @@ tidy:
## frontend: 安装依赖并构建前端到 internal/webui/static/
frontend:
cd frontend && npm install && npm run build
cd frontend && npm ci && npm run build
## check: 本地提交前全套检查(fmt + vet + lint + test)
check: fmt vet lint test
+20
View File
@@ -192,3 +192,23 @@ TEST_MYSQL_URL="mysql://root:pass@tcp(host:3306)/db" \
TEST_POSTGRES_URL="postgres://user:pass@host:5432/db" \
go test ./internal/db -run TestMultiDB -v
```
完整 Docker 功能回归(前端测试/构建、vet、lint、Go `-race`、三库迁移、
MySQL 8.4 与 PostgreSQL 17 API 功能及重启持久化):
```bash
./scripts/docker-full-test.sh
```
测试编排使用命名卷 `mysql8_data`、`postgres17_data` 和 `sqlite_seed`。
本地 `data/xianyu_data.db` 只会抽取少量商品、订单和卡密元数据,写入外置库前会替换
Cookie、买家 ID 和卡密内容。测试应用分别监听 `18081`(MySQL)与 `18082`
(PostgreSQL),测试账号为 `docker_fixture / docker_fixture_password`。
保留数据库并停止容器:
```bash
docker compose -f docker-compose.functional.yml down
```
只有明确需要清空测试数据时才追加 `-v` 删除命名卷。
+242
View File
@@ -0,0 +1,242 @@
// dbseed 从本地 SQLite 抽取少量业务数据,脱敏后写入目标 MySQL/Postgres。
// 它只用于 Docker 功能测试:不会复制真实 Cookie、买家 ID 或卡密内容。
package main
import (
"context"
"crypto/sha256"
"database/sql"
"errors"
"flag"
"fmt"
"os"
"strings"
"time"
"xianyu-go/internal/db"
)
type seedOptions struct {
Username string
Password string
Limit int
}
type seedResult struct {
Items int
Orders int
Cards int
}
func main() {
sourcePath := flag.String("source", "/seed/xianyu_data.db", "源 SQLite 文件")
targetURL := flag.String("target", "", "目标数据库 URL")
username := flag.String("username", "docker_fixture", "测试登录用户名")
password := flag.String("password", "docker_fixture_password", "测试登录密码")
limit := flag.Int("limit", 20, "每类最多抽取条数")
flag.Parse()
if strings.TrimSpace(*targetURL) == "" {
fmt.Fprintln(os.Stderr, "必须提供 -target")
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
source, err := sql.Open("sqlite", "file:"+*sourcePath+"?mode=ro&_pragma=busy_timeout(10000)")
if err != nil {
fatalf("打开源 SQLite: %v", err)
}
defer source.Close()
if err := source.PingContext(ctx); err != nil {
fatalf("连接源 SQLite: %v", err)
}
targetDB, dialect, err := db.Open(ctx, *targetURL)
if err != nil {
fatalf("打开目标数据库: %v", err)
}
defer targetDB.Close()
result, err := seedFromSQLite(ctx, source, db.NewStore(targetDB, dialect), seedOptions{
Username: *username,
Password: *password,
Limit: *limit,
})
if err != nil {
fatalf("导入测试数据: %v", err)
}
fmt.Printf("数据库种子完成:items=%d orders=%d cards=%d user=%s\n", result.Items, result.Orders, result.Cards, *username)
}
func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, options seedOptions) (seedResult, error) {
if options.Limit <= 0 || options.Limit > 100 {
options.Limit = 20
}
if options.Username == "" || options.Password == "" {
return seedResult{}, fmt.Errorf("测试用户名和密码不能为空")
}
user, err := prepareFixtureUser(ctx, target, options)
if err != nil {
return seedResult{}, err
}
const accountID = "docker-fixture-account"
if err := target.Cookies.Save(ctx, accountID, "unb=docker-fixture; _m_h5_tk=fixture_1;", user.ID); err != nil {
return seedResult{}, err
}
if err := target.Cookies.SetStatusWithReason(ctx, accountID, false, "Docker 脱敏测试账号"); err != nil {
return seedResult{}, err
}
result := seedResult{}
itemMap, count, err := seedItems(ctx, source, target, accountID, options.Limit)
if err != nil {
return result, err
}
result.Items = count
result.Orders, err = seedOrders(ctx, source, target, accountID, itemMap, options.Limit)
if err != nil {
return result, err
}
result.Cards, err = seedCards(ctx, source, target, user.ID, options.Limit)
return result, err
}
func prepareFixtureUser(ctx context.Context, target *db.Store, options seedOptions) (*db.User, error) {
user, err := target.Users.GetByUsername(ctx, options.Username)
if errors.Is(err, db.ErrNotFound) {
created, createErr := target.Users.Create(ctx, options.Username, options.Username+"@docker.test", options.Password)
if createErr != nil {
return nil, fmt.Errorf("创建测试用户: %w", createErr)
}
if !created {
return nil, fmt.Errorf("创建测试用户失败:用户名或邮箱已存在")
}
return target.Users.GetByUsername(ctx, options.Username)
}
if err != nil {
return nil, fmt.Errorf("查询测试用户: %w", err)
}
// 测试用户可能来自持久卷中的上一次执行。先移除其自动化规则,释放
// card_id 的 RESTRICT 外键,再清理账号数据和卡密,保留用户主键并重置密码。
for _, query := range []string{
`DELETE FROM automation_rules WHERE user_id=?`,
`DELETE FROM cookies WHERE user_id=?`,
`DELETE FROM cards WHERE user_id=?`,
} {
if _, err := target.DB.ExecContext(ctx, query, user.ID); err != nil {
return nil, fmt.Errorf("清理上次测试数据: %w", err)
}
}
updated, err := target.Users.UpdatePassword(ctx, options.Username, options.Password)
if err != nil || !updated {
return nil, fmt.Errorf("重置测试用户密码: updated=%v err=%v", updated, err)
}
if _, err := target.DB.ExecContext(ctx, `UPDATE users SET is_active=1,is_admin=0 WHERE id=?`, user.ID); err != nil {
return nil, fmt.Errorf("重置测试用户状态: %w", err)
}
return target.Users.GetByUsername(ctx, options.Username)
}
func seedItems(ctx context.Context, source *sql.DB, target *db.Store, accountID string, limit int) (map[string]string, int, error) {
rows, err := source.QueryContext(ctx, `SELECT item_id,COALESCE(item_title,''),COALESCE(item_description,''),
COALESCE(item_category,''),COALESCE(item_price,'') FROM item_info ORDER BY updated_at DESC LIMIT ?`, limit)
if err != nil {
return nil, 0, err
}
defer rows.Close()
mapping := make(map[string]string)
count := 0
for rows.Next() {
var sourceID, title, description, category, price string
if err := rows.Scan(&sourceID, &title, &description, &category, &price); err != nil {
return nil, count, err
}
fixtureID := fmt.Sprintf("docker-item-%03d", count+1)
if err := target.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: accountID, ItemID: fixtureID, ItemTitle: fallback(title, "SQLite 测试商品"),
ItemDescription: description, ItemCategory: category, ItemPrice: price,
}); err != nil {
return nil, count, err
}
mapping[sourceID] = fixtureID
count++
}
return mapping, count, rows.Err()
}
func seedOrders(ctx context.Context, source *sql.DB, target *db.Store, accountID string, items map[string]string, limit int) (int, error) {
rows, err := source.QueryContext(ctx, `SELECT order_id,COALESCE(item_id,''),COALESCE(quantity,'1'),
COALESCE(amount,'0'),COALESCE(order_status,'unknown'),COALESCE(spec_name,''),COALESCE(spec_value,'')
FROM orders ORDER BY updated_at DESC LIMIT ?`, limit*4)
if err != nil {
return 0, err
}
defer rows.Close()
count := 0
for rows.Next() && count < limit {
var sourceOrderID, sourceItemID, quantity, amount, status, specName, specValue string
if err := rows.Scan(&sourceOrderID, &sourceItemID, &quantity, &amount, &status, &specName, &specValue); err != nil {
return count, err
}
itemID, ok := items[sourceItemID]
if !ok {
continue
}
if err := target.Orders.Upsert(ctx, "docker-order-"+shortHash(sourceOrderID), db.OrderUpsertOpts{
CookieID: accountID, ItemID: itemID, BuyerID: "docker-buyer", Quantity: quantity,
Amount: amount, OrderStatus: status, SpecName: specName, SpecValue: specValue,
}); err != nil {
return count, err
}
count++
}
return count, rows.Err()
}
func seedCards(ctx context.Context, source *sql.DB, target *db.Store, userID int64, limit int) (int, error) {
rows, err := source.QueryContext(ctx, `SELECT COALESCE(name,''),type,COALESCE(delay_seconds,0)
FROM cards ORDER BY updated_at DESC LIMIT ?`, limit)
if err != nil {
return 0, err
}
defer rows.Close()
count := 0
for rows.Next() {
var name, cardType string
var delay int
if err := rows.Scan(&name, &cardType, &delay); err != nil {
return count, err
}
card := &db.CardFull{
Name: fmt.Sprintf("[Docker测试] %s %d", fallback(name, "SQLite 卡密"), count+1),
Type: "text", TextContent: "Docker 脱敏测试发货内容", Enabled: true,
Description: "从本地 SQLite 元数据生成,不包含真实卡密", DelaySeconds: delay, UserID: userID,
}
if cardType == "data" {
card.Type = "data"
card.DataContent = fmt.Sprintf("DOCKER-FIXTURE-%03d-A\nDOCKER-FIXTURE-%03d-B", count+1, count+1)
}
if _, err := target.Cards.Create(ctx, card); err != nil {
return count, err
}
count++
}
return count, rows.Err()
}
func shortHash(value string) string {
sum := sha256.Sum256([]byte(value))
return fmt.Sprintf("%x", sum[:6])
}
func fallback(value, defaultValue string) string {
if strings.TrimSpace(value) == "" {
return defaultValue
}
return value
}
func fatalf(format string, args ...any) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(1)
}
+61
View File
@@ -0,0 +1,61 @@
package main
import (
"context"
"path/filepath"
"strings"
"testing"
"xianyu-go/internal/db"
)
func TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets(t *testing.T) {
ctx := context.Background()
sourceDB, sourceDialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "source.db"))
if err != nil {
t.Fatal(err)
}
defer sourceDB.Close()
source := db.NewStore(sourceDB, sourceDialect)
source.Users.Create(ctx, "source", "[email protected]", "pw")
user, _ := source.Users.GetByUsername(ctx, "source")
source.Cookies.Save(ctx, "real-account", "unb=real-secret; _m_h5_tk=secret;", user.ID)
source.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: "real-account", ItemID: "real-item", ItemTitle: "真实商品", ItemPrice: "19.90"})
source.Orders.Upsert(ctx, "real-order", db.OrderUpsertOpts{CookieID: "real-account", ItemID: "real-item", BuyerID: "real-buyer", Amount: "19.90", OrderStatus: "completed"})
source.Cards.Create(ctx, &db.CardFull{Name: "真实卡密", Type: "data", DataContent: "SECRET-CODE", Enabled: true, UserID: user.ID})
targetDB, targetDialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "target.db"))
if err != nil {
t.Fatal(err)
}
defer targetDB.Close()
target := db.NewStore(targetDB, targetDialect)
result, err := seedFromSQLite(ctx, sourceDB, target, seedOptions{Username: "fixture", Password: "fixture-password", Limit: 10})
if err != nil {
t.Fatal(err)
}
if result.Items != 1 || result.Orders != 1 || result.Cards != 1 {
t.Fatalf("result=%+v", result)
}
cookie, _ := target.Cookies.GetValue(ctx, "docker-fixture-account")
if strings.Contains(cookie, "real-secret") || strings.Contains(cookie, "secret") {
t.Fatalf("source cookie leaked: %q", cookie)
}
fixtureUser, _ := target.Users.GetByUsername(ctx, "fixture")
cards, _ := target.Cards.AllForUser(ctx, fixtureUser.ID)
if len(cards) != 1 || strings.Contains(cards[0].DataContent, "SECRET-CODE") {
t.Fatalf("source card secret leaked: %+v", cards)
}
second, err := seedFromSQLite(ctx, sourceDB, target, seedOptions{Username: "fixture", Password: "fixture-password", Limit: 10})
if err != nil {
t.Fatalf("second idempotent seed: %v", err)
}
if second != result {
t.Fatalf("second seed result=%+v want %+v", second, result)
}
cards, _ = target.Cards.AllForUser(ctx, fixtureUser.ID)
if len(cards) != 1 {
t.Fatalf("second seed should replace fixture cards, got %d", len(cards))
}
}
+194
View File
@@ -0,0 +1,194 @@
name: xianyu-functional
x-mysql-url: &mysql-url mysql://root:xianyu_root_password@tcp(mysql:3306)/xianyu?parseTime=true&loc=Local
x-postgres-url: &postgres-url postgres://xianyu:xianyu_postgres_password@postgres:5432/xianyu?sslmode=disable
services:
mysql:
image: mysql:8.4
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: xianyu_root_password
MYSQL_DATABASE: xianyu
MYSQL_USER: xianyu
MYSQL_PASSWORD: xianyu_mysql_password
TZ: Asia/Shanghai
command: ["--character-set-server=utf8mb4", "--collation-server=utf8mb4_0900_ai_ci"]
ports:
- "13306:3306"
volumes:
- mysql8_data:/var/lib/mysql
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$${MYSQL_ROOT_PASSWORD} --silent"]
interval: 5s
timeout: 5s
retries: 30
postgres:
image: postgres:17
restart: unless-stopped
environment:
POSTGRES_DB: xianyu
POSTGRES_USER: xianyu
POSTGRES_PASSWORD: xianyu_postgres_password
TZ: Asia/Shanghai
ports:
- "15432:5432"
volumes:
- postgres17_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 30
sqlite-seed-copy:
image: alpine:3.22
restart: "no"
volumes:
- ./data:/source:ro
- sqlite_seed:/seed
command:
- /bin/sh
- -ec
- |
rm -f /seed/xianyu_data.db /seed/xianyu_data.db-wal /seed/xianyu_data.db-shm
cp /source/xianyu_data.db /seed/xianyu_data.db
test ! -f /source/xianyu_data.db-wal || cp /source/xianyu_data.db-wal /seed/xianyu_data.db-wal
test ! -f /source/xianyu_data.db-shm || cp /source/xianyu_data.db-shm /seed/xianyu_data.db-shm
seed-mysql:
image: xianyu-go:functional
build:
context: .
dockerfile: Dockerfile.debian13
restart: "no"
depends_on:
mysql:
condition: service_healthy
sqlite-seed-copy:
condition: service_completed_successfully
volumes:
- sqlite_seed:/seed:ro
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *mysql-url, "-limit", "20"]
seed-postgres:
image: xianyu-go:functional
restart: "no"
depends_on:
postgres:
condition: service_healthy
sqlite-seed-copy:
condition: service_completed_successfully
volumes:
- sqlite_seed:/seed:ro
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *postgres-url, "-limit", "20"]
app-mysql:
image: xianyu-go:functional
restart: unless-stopped
depends_on:
seed-mysql:
condition: service_completed_successfully
environment:
DATABASE_URL: *mysql-url
TZ: Asia/Shanghai
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
ports:
- "18081:8080"
volumes:
- app_mysql_data:/app/data
healthcheck:
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
interval: 5s
timeout: 5s
retries: 30
app-postgres:
image: xianyu-go:functional
restart: unless-stopped
depends_on:
seed-postgres:
condition: service_completed_successfully
environment:
DATABASE_URL: *postgres-url
TZ: Asia/Shanghai
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
ports:
- "18082:8080"
volumes:
- app_postgres_data:/app/data
healthcheck:
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
interval: 5s
timeout: 5s
retries: 30
go-test:
build:
context: .
dockerfile: Dockerfile.test
target: go-test
depends_on:
mysql:
condition: service_healthy
postgres:
condition: service_healthy
environment:
TEST_MYSQL_URL: *mysql-url
TEST_POSTGRES_URL: *postgres-url
command: ["go", "test", "-race", "-timeout=20m", "./..."]
go-vet:
build:
context: .
dockerfile: Dockerfile.test
target: go-test
command: ["go", "vet", "./..."]
go-lint:
build:
context: .
dockerfile: Dockerfile.test
target: go-lint
command: ["golangci-lint", "run", "./..."]
frontend-test:
build:
context: .
dockerfile: Dockerfile.test
target: frontend-test
command: ["sh", "-c", "npm test && npm run build"]
dbverify-mysql:
image: xianyu-go:functional
depends_on:
mysql:
condition: service_healthy
command: ["/app/xianyu-dbverify", *mysql-url]
dbverify-postgres:
image: xianyu-go:functional
depends_on:
postgres:
condition: service_healthy
command: ["/app/xianyu-dbverify", *postgres-url]
functional-test:
image: curlimages/curl:8.16.0
restart: "no"
depends_on:
app-mysql:
condition: service_healthy
app-postgres:
condition: service_healthy
volumes:
- ./scripts/docker-functional-test.sh:/tests/docker-functional-test.sh:ro
entrypoint: ["/bin/sh", "/tests/docker-functional-test.sh"]
volumes:
mysql8_data:
postgres17_data:
sqlite_seed:
app_mysql_data:
app_postgres_data:
+79 -45
View File
@@ -4,7 +4,6 @@ import { AccountDetail, AIReplySettings, NotificationChannel } from '../types';
import {
getAccountDetails,
getAccountRuntimeStatuses,
addAccount,
updateAccountStatus,
deleteAccount,
generateQRLogin,
@@ -29,6 +28,7 @@ import {
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink, Bell
} from 'lucide-react';
import { buildAccountLoginInfoUpdate } from './accountEdit';
import { shouldSaveNotificationBindings } from './accountBindings';
import { createQRLoginPoller } from './qrPolling';
type ModalType = 'edit' | 'ai-settings' | null;
@@ -52,6 +52,10 @@ const AccountList: React.FC = () => {
// 通知渠道绑定(编辑弹窗用)
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
const [selectedChannelIds, setSelectedChannelIds] = useState<number[]>([]);
const [bindingsLoaded, setBindingsLoaded] = useState(false);
const [bindingsLoading, setBindingsLoading] = useState(false);
const [bindingsDirty, setBindingsDirty] = useState(false);
const [bindingsLoadError, setBindingsLoadError] = useState('');
// 编辑表单状态
const [editForm, setEditForm] = useState({
@@ -223,6 +227,31 @@ const AccountList: React.FC = () => {
}
};
const loadNotificationBindings = async (accountId: string) => {
setBindingsLoading(true);
setBindingsLoaded(false);
setBindingsDirty(false);
setBindingsLoadError('');
const [channelsResult, bindingsResult] = await Promise.allSettled([
getNotificationChannels(),
getAccountBindings(accountId),
]);
if (channelsResult.status === 'fulfilled') {
setNotifChannels(channelsResult.value.data || []);
} else {
setNotifChannels([]);
setBindingsLoadError('通知渠道列表加载失败,请重试');
}
if (bindingsResult.status === 'fulfilled') {
setSelectedChannelIds(bindingsResult.value || []);
setBindingsLoaded(true);
} else {
setSelectedChannelIds([]);
setBindingsLoadError('通知绑定加载失败;本次保存不会修改现有绑定');
}
setBindingsLoading(false);
};
const openEditModal = async (account: AccountDetail) => {
setEditingAccount(account);
setEditForm({
@@ -237,19 +266,7 @@ const AccountList: React.FC = () => {
clear_password: false,
});
setActiveModal('edit');
// 并行加载通知渠道列表 + 当前账号已绑定渠道
try {
const [chRes, bindings] = await Promise.all([
getNotificationChannels(),
getAccountBindings(account.id).catch(() => [] as number[]),
]);
setNotifChannels(chRes.data || []);
setSelectedChannelIds(bindings || []);
} catch (e) {
console.error('加载通知渠道绑定失败', e);
setNotifChannels([]);
setSelectedChannelIds([]);
}
await loadNotificationBindings(account.id);
};
const openAIModal = async (account: AccountDetail) => {
@@ -305,8 +322,10 @@ const AccountList: React.FC = () => {
promises.push(updateAccountLoginInfo(editingAccount.id, loginInfo));
}
// 更新通知渠道绑定(覆盖式,总是提交以支持解绑)
promises.push(setAccountBindings(editingAccount.id, selectedChannelIds));
// 只有成功加载且用户确实改动后才覆盖,避免加载失败被误解释成解绑全部。
if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) {
promises.push(setAccountBindings(editingAccount.id, selectedChannelIds));
}
await Promise.all(promises);
setActiveModal(null);
@@ -335,22 +354,17 @@ const AccountList: React.FC = () => {
}
};
const persistQRLoginResult = async (cookies: string, unb?: string, target?: AccountDetail | null) => {
if (target) {
if (unb && unb !== target.id) {
const ok = confirm(`扫码返回的账号ID是 ${unb},当前要重新授权的是 ${target.id}。确认用本次扫码结果覆盖当前账号授权吗?`);
if (!ok) {
throw new Error('已取消覆盖当前账号授权');
}
}
await updateAccountCookie(target.id, cookies, 'qr_scan');
return target.id;
const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null) => {
let res = await completeQRVerification(sessionId, target?.id);
if (res.requires_confirmation) {
const confirmed = confirm(`扫码返回的账号ID是 ${res.scanned_account_id || '未知'},确认覆盖 ${target?.id || '当前账号'} 的授权吗?`);
if (!confirmed) return '';
res = await completeQRVerification(sessionId, target?.id, true);
}
if (!unb) {
throw new Error('扫码结果缺少账号ID,无法添加账号');
if (!res.success || !res.account_id) {
throw new Error(res.message || '保存扫码授权失败');
}
await addAccount(unb, cookies, 'qr_scan');
return unb;
return res.account_id;
};
const startQRLogin = async (target?: AccountDetail) => {
@@ -373,17 +387,19 @@ const AccountList: React.FC = () => {
setQrStatus('waiting');
qrPollerRef.current?.start(res.session_id, checkQRLoginStatus, {
onSuccess: async (statusRes) => {
setQrStatus('success');
if (statusRes.cookies && statusRes.unb) {
try {
await persistQRLoginResult(statusRes.cookies, statusRes.unb, targetAccount);
} catch (e) {
console.error('保存扫码授权失败', e);
onSuccess: async () => {
try {
const accountId = await completeAndPersistQRSession(res.session_id, targetAccount);
if (!accountId) {
setQrStatus('error');
return;
}
} catch (e) {
console.error('保存扫码授权失败', e);
setQrStatus('error');
return;
}
setQrStatus('success');
scheduleQRModalClose();
},
onScanned: () => {
@@ -418,15 +434,13 @@ const AccountList: React.FC = () => {
if (!qrSessionId) return;
setQrStatus('loading');
try {
const res = await completeQRVerification(qrSessionId);
if (res.success && res.cookies && res.unb) {
const accountId = await completeAndPersistQRSession(qrSessionId, qrReauthTarget);
if (accountId) {
stopQRPolling();
await persistQRLoginResult(res.cookies, res.unb, qrReauthTarget);
setQrStatus('success');
scheduleQRModalClose();
} else {
setQrStatus('verification');
alert('验证未完成:' + (res.message || '可能验证尚未通过,请先在验证页面完成验证'));
}
} catch (e) {
setQrStatus('verification');
@@ -665,7 +679,15 @@ const AccountList: React.FC = () => {
<Loader2 className="w-6 h-6 animate-spin text-gray-400" />
</div>
)}
<span className="text-xs text-gray-400">等待手机验证完成,无需点击确认。</span>
{verificationUrl && (
<a href={verificationUrl} target="_blank" rel="noopener noreferrer" className="mt-2 text-sm font-bold text-[#0094f7] flex items-center gap-1">
<ExternalLink className="w-4 h-4" />打开安全验证页面
</a>
)}
<button type="button" onClick={handleCompleteVerification} className="mt-3 ios-btn-primary px-4 py-2 rounded-xl text-sm font-bold">
我已完成验证
</button>
<span className="text-xs text-gray-400 mt-2">验证完成后点击确认,系统会提取并保存登录状态。</span>
</div>
)}
</div>
@@ -841,13 +863,22 @@ const AccountList: React.FC = () => {
</div>
{/* 通知渠道绑定 */}
{notifChannels.length > 0 && (
{(notifChannels.length > 0 || bindingsLoading || bindingsLoadError) && (
<div className="border-t border-gray-200 pt-6">
<h3 className="text-lg font-bold text-gray-900 mb-1 flex items-center gap-2">
<Bell className="w-5 h-5 text-blue-500" />
通知渠道绑定
</h3>
<p className="text-xs text-gray-500 mb-4">勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道</p>
{bindingsLoading && (
<div className="flex items-center gap-2 text-sm text-gray-500"><Loader2 className="w-4 h-4 animate-spin" />正在加载通知绑定</div>
)}
{bindingsLoadError && !bindingsLoading && (
<div className="mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3">
<span>{bindingsLoadError}</span>
<button type="button" className="font-bold whitespace-nowrap" onClick={() => loadNotificationBindings(editingAccount.id)}>重试</button>
</div>
)}
<div className="space-y-2">
{notifChannels.map(ch => {
const checked = selectedChannelIds.includes(Number(ch.id));
@@ -859,10 +890,13 @@ const AccountList: React.FC = () => {
<button
type="button"
onClick={() => {
if (!bindingsLoaded) return;
setSelectedChannelIds(prev =>
checked ? prev.filter(id => id !== Number(ch.id)) : [...prev, Number(ch.id)]
);
setBindingsDirty(true);
}}
disabled={!bindingsLoaded}
className={`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${
checked ? 'bg-[#0094f7] border-[#0094f7]' : 'bg-white border-gray-300'
}`}
@@ -964,7 +998,7 @@ const AccountList: React.FC = () => {
min="0"
max="100"
/>
<p className="text-xs text-gray-500 mt-1">例如:10表示最多降价10%</p>
<p className="text-xs text-gray-500 mt-1">例如:10 表示最多降价 10%;设为 0 表示不允许降价</p>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">最大折扣金额 (元)</label>
@@ -975,7 +1009,7 @@ const AccountList: React.FC = () => {
className="w-full ios-input px-4 py-3 rounded-xl"
min="0"
/>
<p className="text-xs text-gray-500 mt-1">例如:100表示最多降价100元</p>
<p className="text-xs text-gray-500 mt-1">例如:100 表示最多降价 100 元;设为 0 表示不允许降价</p>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">最大砍价轮次</label>
+2 -10
View File
@@ -453,7 +453,7 @@ const CardList: React.FC = () => {
<option value="">请选择类型</option>
<option value="text">固定文字</option>
<option value="data">批量数据</option>
<option value="api">API接口</option>
{selectedCard?.type === 'api' && <option value="api">API接口(仅保留现有配置)</option>}
<option value="image">图片</option>
</select>
</div>
@@ -687,7 +687,7 @@ const CardList: React.FC = () => {
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-700 mb-2">类型</label>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'data', content: '' })}
@@ -712,14 +712,6 @@ const CardList: React.FC = () => {
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
图片
</button>
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'api', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'api' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600'}`}
>
<Code className="w-5 h-5 mx-auto mb-1" />
API
</button>
</div>
</div>
+45 -117
View File
@@ -1,6 +1,7 @@
import React, { useEffect, useState } from 'react';
import { AdminStats, OrderAnalytics, Order, OrderStatus, Item } from '../types';
import { getAdminStats, getOrderAnalytics, getValidOrders, getItems } from '../services/api';
import { DashboardStats, OrderAnalytics, Order, OrderStatus, Item } from '../types';
import { getDashboardStats, getOrderAnalytics, getValidOrders, getItems } from '../services/api';
import { getDateRange, getPreviousDateRange, TimeRange } from '../dateRange';
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts';
@@ -49,11 +50,10 @@ const StatCard: React.FC<{ title: string; value: string | number; icon: React.El
</div>
);
type TimeRange = 'today' | 'yesterday' | '3days' | '7days' | '30days' | 'custom';
const Dashboard: React.FC = () => {
const [stats, setStats] = useState<AdminStats | null>(null);
const [stats, setStats] = useState<DashboardStats | null>(null);
const [analytics, setAnalytics] = useState<OrderAnalytics | null>(null);
const [loadError, setLoadError] = useState('');
const [timeRange, setTimeRange] = useState<TimeRange>('7days');
const [customStartDate, setCustomStartDate] = useState('');
const [customEndDate, setCustomEndDate] = useState('');
@@ -71,122 +71,28 @@ const Dashboard: React.FC = () => {
// 颜色配置
const COLORS = ['#0094f7', '#3B82F6', '#10B981', '#F59E0B', '#8B5CF6'];
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
const formatLocalDate = (date: Date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const getDatesForRange = (range: TimeRange) => {
const now = new Date();
const endDate = formatLocalDate(now);
let startDate = endDate;
if (range === 'yesterday') {
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayStr = formatLocalDate(yesterday);
return { startDate: yesterdayStr, endDate: yesterdayStr };
}
if (range === '3days') {
const threeDaysAgo = new Date(now);
threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
startDate = formatLocalDate(threeDaysAgo);
} else if (range === '7days') {
const sevenDaysAgo = new Date(now);
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
startDate = formatLocalDate(sevenDaysAgo);
} else if (range === '30days') {
const thirtyDaysAgo = new Date(now);
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
startDate = formatLocalDate(thirtyDaysAgo);
} else if (range === 'custom' && customStartDate && customEndDate) {
return { startDate: customStartDate, endDate: customEndDate };
} else if (range === 'custom') {
const sevenDaysAgo = new Date(now);
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
startDate = formatLocalDate(sevenDaysAgo);
}
return { startDate, endDate };
};
const loadValidOrders = (range: TimeRange) => {
const { startDate, endDate } = getDatesForRange(range);
const { startDate, endDate } = getDateRange(range, new Date(), customStartDate, customEndDate);
setOrdersLoading(true);
getValidOrders({ start_date: startDate, end_date: endDate })
.then(setValidOrders)
.catch(console.error)
.catch(error => setLoadError(error instanceof Error ? error.message : '订单加载失败'))
.finally(() => setOrdersLoading(false));
};
const loadAnalytics = (range: TimeRange) => {
const now = new Date();
const { startDate, endDate } = getDatesForRange(range);
const currentRange = getDateRange(range, new Date(), customStartDate, customEndDate);
const { startDate, endDate } = currentRange;
const params = { start_date: startDate, end_date: endDate };
// 同时获取上一个周期的数据用于趋势对比
const previousParams = getPreviousPeriodParams(range, now);
if (previousParams) {
getOrderAnalytics(previousParams).then(setPreviousAnalytics).catch(console.error);
}
const previous = getPreviousDateRange(currentRange);
getOrderAnalytics({ start_date: previous.startDate, end_date: previous.endDate })
.then(setPreviousAnalytics)
.catch(error => setLoadError(error instanceof Error ? error.message : '历史统计加载失败'));
getOrderAnalytics(params).then(setAnalytics).catch(console.error);
};
// 获取上一个时间段的参数
const getPreviousPeriodParams = (range: TimeRange, now: Date) => {
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
switch (range) {
case 'today':
// 今天对比昨天
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
const yYear = yesterday.getFullYear();
const yMonth = String(yesterday.getMonth() + 1).padStart(2, '0');
const yDay = String(yesterday.getDate()).padStart(2, '0');
return {
start_date: `${yYear}-${yMonth}-${yDay}`,
end_date: `${yYear}-${yMonth}-${yDay}`
};
case 'yesterday':
// 昨天对比前天
const dayBefore = new Date(now);
dayBefore.setDate(dayBefore.getDate() - 2);
const dbYear = dayBefore.getFullYear();
const dbMonth = String(dayBefore.getMonth() + 1).padStart(2, '0');
const dbDay = String(dayBefore.getDate()).padStart(2, '0');
return {
start_date: `${dbYear}-${dbMonth}-${dbDay}`,
end_date: `${dbYear}-${dbMonth}-${dbDay}`
};
case '7days':
// 7天对比上一个7天
const prev7DaysEnd = new Date(now);
prev7DaysEnd.setDate(prev7DaysEnd.getDate() - 7);
const prev7DaysStart = new Date(prev7DaysEnd);
prev7DaysStart.setDate(prev7DaysStart.getDate() - 7);
return {
start_date: `${prev7DaysStart.getFullYear()}-${String(prev7DaysStart.getMonth() + 1).padStart(2, '0')}-${String(prev7DaysStart.getDate()).padStart(2, '0')}`,
end_date: `${prev7DaysEnd.getFullYear()}-${String(prev7DaysEnd.getMonth() + 1).padStart(2, '0')}-${String(prev7DaysEnd.getDate()).padStart(2, '0')}`
};
case '30days':
// 30天对比上一个30天
const prev30DaysEnd = new Date(now);
prev30DaysEnd.setDate(prev30DaysEnd.getDate() - 30);
const prev30DaysStart = new Date(prev30DaysEnd);
prev30DaysStart.setDate(prev30DaysStart.getDate() - 30);
return {
start_date: `${prev30DaysStart.getFullYear()}-${String(prev30DaysStart.getMonth() + 1).padStart(2, '0')}-${String(prev30DaysStart.getDate()).padStart(2, '0')}`,
end_date: `${prev30DaysEnd.getFullYear()}-${String(prev30DaysEnd.getMonth() + 1).padStart(2, '0')}-${String(prev30DaysEnd.getDate()).padStart(2, '0')}`
};
default:
return null;
}
getOrderAnalytics(params)
.then(setAnalytics)
.catch(error => setLoadError(error instanceof Error ? error.message : '统计加载失败'));
};
// 计算趋势百分比
@@ -206,9 +112,7 @@ const Dashboard: React.FC = () => {
};
useEffect(() => {
getAdminStats().then(setStats).catch(console.error);
loadAnalytics(timeRange);
// 获取商品列表
getDashboardStats().then(setStats).catch(error => setLoadError(error instanceof Error ? error.message : '概览加载失败'));
getItems().then(items => {
setItems(items);
// 建立 item_id 到 item_title 的映射
@@ -217,7 +121,12 @@ const Dashboard: React.FC = () => {
nameMap[item.item_id] = item.item_title || item.item_id;
});
setItemNames(nameMap);
}).catch(console.error);
}).catch(error => setLoadError(error instanceof Error ? error.message : '商品加载失败'));
}, []);
useEffect(() => {
setLoadError('');
loadAnalytics(timeRange);
}, [timeRange]);
// 加载订单列表
@@ -225,6 +134,15 @@ const Dashboard: React.FC = () => {
loadValidOrders(timeRange);
}, [timeRange]);
if (loadError && (!stats || !analytics)) {
return (
<div className="p-8 flex flex-col items-center gap-3 text-red-600">
<AlertCircle className="w-8 h-8" />
<span>{loadError}</span>
<button type="button" className="ios-btn-primary px-4 py-2 rounded-xl" onClick={() => window.location.reload()}>重新加载</button>
</div>
);
}
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-[#0094f7]" /></div>;
const chartData = analytics.daily_stats?.map(d => ({
@@ -296,7 +214,12 @@ const Dashboard: React.FC = () => {
{ key: 'custom' as TimeRange, label: '自定义' },
];
const selectedRangeLabel = timeRangeOptions.find(option => option.key === timeRange)?.label || '所选范围';
const currentRangeDates = getDatesForRange(timeRange);
let currentRangeDates;
try {
currentRangeDates = getDateRange(timeRange, new Date(), customStartDate, customEndDate);
} catch {
currentRangeDates = { startDate: customStartDate, endDate: customEndDate };
}
const normalizedSearchTerm = searchTerm.trim().toLowerCase();
const filteredValidOrders = validOrders.filter((order) =>
order.order_id?.toLowerCase().includes(normalizedSearchTerm) ||
@@ -352,8 +275,13 @@ const Dashboard: React.FC = () => {
/>
<button
onClick={() => {
loadAnalytics('custom');
loadValidOrders('custom');
try {
setLoadError('');
loadAnalytics('custom');
loadValidOrders('custom');
} catch (error) {
setLoadError(error instanceof Error ? error.message : '日期范围无效');
}
}}
className="px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors"
>
+19 -5
View File
@@ -14,6 +14,7 @@ import {
Bell, Plus, Edit2, Trash2, X, Send, RefreshCw, Loader2,
Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save,
} from 'lucide-react';
import { normalizeSMTPSettings } from '../smtpSettings';
type ChannelTypeMeta = {
label: string;
@@ -211,7 +212,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
const loadSmtp = async () => {
try {
const s = await getSystemSettings();
setSmtp(s || {});
setSmtp(normalizeSMTPSettings(s || {}));
} catch (e) {
console.error('加载 SMTP 配置失败', e);
}
@@ -225,7 +226,8 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
smtp_port: smtp.smtp_port || 587,
smtp_user: smtp.smtp_user || '',
smtp_password: smtp.smtp_password || '',
smtp_from: smtp.smtp_from || '',
smtp_from_name: smtp.smtp_from_name || '',
smtp_from_address: smtp.smtp_from_address || smtp.smtp_user || '',
});
showToast('success', 'SMTP 配置已保存');
} catch (e: any) {
@@ -517,15 +519,27 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
<p className="text-xs text-gray-500">QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)</p>
</div>
<div className="space-y-2">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
<input
type="text"
value={smtp.smtp_from || ''}
onChange={e => setSmtp({ ...smtp, smtp_from: e.target.value })}
value={smtp.smtp_from_name || ''}
onChange={e => setSmtp({ ...smtp, smtp_from_name: e.target.value })}
placeholder="闲鱼自动回复系统"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件邮箱地址</label>
<input
type="email"
value={smtp.smtp_from_address || smtp.smtp_user || ''}
onChange={e => setSmtp({ ...smtp, smtp_from_address: e.target.value })}
placeholder="[email protected]"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
</div>
<button
+26 -1
View File
@@ -110,6 +110,8 @@ const emptyVariant = (): ShippingVariant => ({
card_id: 0,
delivery_count: 1,
enabled: true,
delay_override: false,
delay_seconds: 0,
});
const parseJSONObject = (raw?: string): Record<string, any> => {
@@ -1146,7 +1148,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
className="w-full ios-input px-3 py-2.5 rounded-lg"
>
<option value="">请选择卡密库存</option>
{cards.filter(card => card.enabled).map(card => (
{cards.filter(card => card.enabled && card.type !== 'api').map(card => (
<option key={card.id} value={card.id}>{card.name}</option>
))}
</select>
@@ -1162,6 +1164,29 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
className="w-full ios-input px-3 py-2.5 rounded-lg"
/>
</div>
<div className="md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2">
<label className="flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer">
<input
type="checkbox"
checked={variant.delay_override === true}
onChange={event => updateVariant(index, { delay_override: event.target.checked })}
className="accent-[#0094f7]"
/>
覆盖卡密默认延时
</label>
{variant.delay_override && (
<input
type="number"
min="0"
max="86400"
value={variant.delay_seconds || 0}
onChange={event => updateVariant(index, { delay_seconds: Math.max(0, Number(event.target.value) || 0) })}
className="w-28 ios-input px-2 py-1.5 rounded-lg text-xs"
aria-label="动作延时秒数"
/>
)}
<span className="text-xs text-gray-500">{variant.delay_override ? `本动作延时 ${variant.delay_seconds || 0} 秒` : '使用卡密默认延时'}</span>
</div>
<button
type="button"
disabled={displayVariants.length === 1}
+2
View File
@@ -28,6 +28,8 @@ const SETTINGS_SAVE_OMIT_KEYS = new Set([
'smtp_user',
'smtp_password',
'smtp_from',
'smtp_from_name',
'smtp_from_address',
'registration_enabled',
'show_default_login_info',
'login_captcha_enabled',
@@ -0,0 +1,16 @@
import { describe, expect, test } from 'vitest';
import { shouldSaveNotificationBindings } from './accountBindings';
describe('notification binding save guard', () => {
test('does not overwrite bindings when loading failed', () => {
expect(shouldSaveNotificationBindings(false, true)).toBe(false);
});
test('does not write unchanged bindings', () => {
expect(shouldSaveNotificationBindings(true, false)).toBe(false);
});
test('writes an explicitly changed, successfully loaded selection', () => {
expect(shouldSaveNotificationBindings(true, true)).toBe(true);
});
});
+1
View File
@@ -0,0 +1 @@
export const shouldSaveNotificationBindings = (loaded: boolean, dirty: boolean): boolean => loaded && dirty;
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, test } from 'vitest';
import { getDateRange, getPreviousDateRange } from './dateRange';
describe('date ranges', () => {
const now = new Date('2026-07-10T12:00:00');
test.each([
['3days', '2026-07-08'],
['7days', '2026-07-04'],
['30days', '2026-06-11'],
] as const)('%s includes exactly the requested number of days', (range, startDate) => {
expect(getDateRange(range, now)).toEqual({ startDate, endDate: '2026-07-10' });
});
test('previous range has the same length without overlap', () => {
const current = getDateRange('7days', now);
expect(getPreviousDateRange(current)).toEqual({ startDate: '2026-06-27', endDate: '2026-07-03' });
});
test('works across year boundaries', () => {
expect(getDateRange('3days', new Date('2026-01-01T12:00:00'))).toEqual({
startDate: '2025-12-30',
endDate: '2026-01-01',
});
});
test('rejects reversed custom dates', () => {
expect(() => getDateRange('custom', now, '2026-07-11', '2026-07-10')).toThrow('开始日期不能晚于结束日期');
});
});
+52
View File
@@ -0,0 +1,52 @@
export type TimeRange = 'today' | 'yesterday' | '3days' | '7days' | '30days' | 'custom';
export type DateRange = {
startDate: string;
endDate: string;
};
export const formatLocalDate = (date: Date): string => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const addDays = (date: Date, days: number): Date => {
const next = new Date(date);
next.setHours(12, 0, 0, 0);
next.setDate(next.getDate() + days);
return next;
};
const rangeEndingAt = (end: Date, days: number): DateRange => ({
startDate: formatLocalDate(addDays(end, -(days - 1))),
endDate: formatLocalDate(end),
});
export const getDateRange = (
range: TimeRange,
now = new Date(),
customStartDate = '',
customEndDate = '',
): DateRange => {
if (range === 'custom' && customStartDate && customEndDate) {
if (customStartDate > customEndDate) {
throw new Error('开始日期不能晚于结束日期');
}
return { startDate: customStartDate, endDate: customEndDate };
}
if (range === 'yesterday') {
return rangeEndingAt(addDays(now, -1), 1);
}
const days = range === '3days' ? 3 : range === '30days' ? 30 : range === 'today' ? 1 : 7;
return rangeEndingAt(now, days);
};
export const getPreviousDateRange = (current: DateRange): DateRange => {
const start = new Date(`${current.startDate}T12:00:00`);
const end = new Date(`${current.endDate}T12:00:00`);
const dayCount = Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1;
const previousEnd = addDays(start, -1);
return rangeEndingAt(previousEnd, dayCount);
};
-2146
View File
File diff suppressed because it is too large. Load diff
+28
View File
@@ -41,6 +41,34 @@ describe('request helpers', () => {
await expect(get('/bad')).rejects.toThrow('bad request');
});
test('notifies the app when an authenticated request returns 401', async () => {
const events = new EventTarget();
const listener = vi.fn();
events.addEventListener('auth:logout', listener);
vi.stubGlobal('window', events);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {
status: 401,
headers: { 'content-type': 'application/json' },
})));
await expect(get('/private')).rejects.toThrow();
expect(listener).toHaveBeenCalledOnce();
});
test('does not notify logout for a failed login request', async () => {
const events = new EventTarget();
const listener = vi.fn();
events.addEventListener('auth:logout', listener);
vi.stubGlobal('window', events);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', {
status: 401,
headers: { 'content-type': 'application/json' },
})));
await expect(post('/login', {}, { skipAuthLogout: true })).rejects.toThrow();
expect(listener).not.toHaveBeenCalled();
});
test('posts FormData without forcing a content type', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }));
vi.stubGlobal('fetch', fetchMock);
+15 -1
View File
@@ -7,6 +7,18 @@ type JsonValue = unknown;
type RequestOptions = {
params?: QueryParams;
body?: JsonValue;
skipAuthLogout?: boolean;
};
let authLogoutPending = false;
const notifyAuthExpired = () => {
if (authLogoutPending || typeof window === 'undefined') return;
authLogoutPending = true;
window.dispatchEvent(new Event('auth:logout'));
queueMicrotask(() => {
authLogoutPending = false;
});
};
const buildQueryString = (params?: QueryParams): string => {
@@ -37,6 +49,7 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
const isJson = contentType.includes('application/json');
if (!res.ok) {
if (res.status === 401 && !options.skipAuthLogout) notifyAuthExpired();
// 尽量返回后端的detail/message,避免吞错
const payload = isJson ? await res.json().catch(() => undefined) : await res.text().catch(() => undefined);
const detail = typeof payload === 'string' ? payload : (payload?.detail || payload?.message || payload?.msg);
@@ -52,7 +65,7 @@ const request = async <T>(method: RequestMethod, url: string, options: RequestOp
};
export const get = async <T>(url: string, params?: QueryParams): Promise<T> => request<T>('GET', url, { params });
export const post = async <T>(url: string, body?: JsonValue): Promise<T> => request<T>('POST', url, { body });
export const post = async <T>(url: string, body?: JsonValue, options?: { skipAuthLogout?: boolean }): Promise<T> => request<T>('POST', url, { body, ...options });
export const put = async <T>(url: string, body?: JsonValue): Promise<T> => request<T>('PUT', url, { body });
export const del = async <T>(url: string, params?: QueryParams): Promise<T> => request<T>('DELETE', url, { params });
@@ -68,6 +81,7 @@ export const postForm = async <T>(url: string, body: FormData): Promise<T> => {
const payload = isJson ? await res.json().catch(() => undefined) : await res.text().catch(() => undefined);
if (!res.ok) {
if (res.status === 401) notifyAuthExpired();
const detail = typeof payload === 'string' ? payload : (payload?.detail || payload?.message || payload?.msg);
const err = new Error(detail || ('请求失败: ' + res.status)) as Error & { payload?: unknown };
err.payload = payload;
+8
View File
@@ -136,4 +136,12 @@ describe('frontend navigation routing', () => {
expect(itemList).toContain('URL.revokeObjectURL(preview.url)');
expect(itemList).not.toContain('src={URL.createObjectURL(file)}');
});
test('QR verification exposes both the external verification link and completion action', () => {
const accounts = readFrontendFile('components/AccountList.tsx');
expect(accounts).toContain('href={verificationUrl}');
expect(accounts).toContain('rel="noopener noreferrer"');
expect(accounts).toContain('onClick={handleCompleteVerification}');
expect(accounts).toContain('我已完成验证');
});
});
+16 -2
View File
@@ -3,6 +3,7 @@ import {
addAccount,
cancelPasswordLogin,
checkPasswordLoginStatus,
completeQRVerification,
createNotificationChannel,
getAccountDetails,
getItems,
@@ -46,6 +47,16 @@ test('getValidOrders accepts wrapped responses', async () => {
expect(result).toEqual([expect.objectContaining({ id: 'o2', status: 'completed', quantity: 3 })]);
});
test('completeQRVerification sends target account and mismatch confirmation', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, account_id: 'acc1' }));
vi.stubGlobal('fetch', fetchMock);
await completeQRVerification('session-1', 'acc1', true);
expect(fetchMock).toHaveBeenCalledWith('/qr-login/complete-verification/session-1', expect.objectContaining({
method: 'POST',
body: JSON.stringify({ target_account_id: 'acc1', confirm_mismatch: true }),
}));
});
test('getItems normalizes multi-spec flags from backend values', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{
cookie_id: 'cookie-1',
@@ -414,6 +425,8 @@ test('updateShippingRule posts every matching card action before confirm shipmen
card_id: 9,
delivery_count: 2,
enabled: true,
delay_override: true,
delay_seconds: 0,
},
],
});
@@ -437,8 +450,9 @@ test('updateShippingRule posts every matching card action before confirm shipmen
sort_order: 3,
}),
]);
expect(JSON.parse(body.actions[0].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天' });
expect(JSON.parse(body.actions[1].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天' });
expect(JSON.parse(body.actions[0].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天', delay_override: false });
expect(JSON.parse(body.actions[1].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天', delay_override: true });
expect(body.actions[1].delay_seconds).toBe(0);
});
test('updateShippingRule posts review request text action without card requirement', async () => {
+29 -5
View File
@@ -1,7 +1,7 @@
import { get, post, put, del, postForm } from '../request';
import {
LoginResponse, AccountDetail, Order, PaginatedResponse,
AdminStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction,
NotificationChannel, NotificationEventType
} from '../types';
@@ -17,7 +17,7 @@ const normalizeSettings = (settings: Record<string, any>): SystemSettings => {
// Auth
export const login = async (data: { username?: string; password?: string; email?: string; verification_code?: string }): Promise<LoginResponse> => {
return post('/login', data);
return post('/login', data, { skipAuthLogout: true });
};
export const verifySession = async (): Promise<{ authenticated: boolean; initialized?: boolean; user_id?: number; username?: string; is_admin?: boolean }> => {
@@ -102,8 +102,21 @@ export const checkQRLoginStatus = async (sessionId: string): Promise<any> => {
return get(`/qr-login/check/${sessionId}`);
};
export const completeQRVerification = async (sessionId: string): Promise<{ success: boolean; cookies?: string; unb?: string; message?: string }> => {
return post(`/qr-login/complete-verification/${sessionId}`, {});
export const completeQRVerification = async (
sessionId: string,
targetAccountId?: string,
confirmMismatch = false,
): Promise<{
success: boolean;
account_id?: string;
scanned_account_id?: string;
requires_confirmation?: boolean;
message?: string;
}> => {
return post(`/qr-login/complete-verification/${sessionId}`, {
target_account_id: targetAccountId || '',
confirm_mismatch: confirmMismatch,
});
};
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<any> => {
@@ -283,6 +296,10 @@ export const getAdminStats = async (): Promise<AdminStats> => {
return get('/admin/stats');
};
export const getDashboardStats = async (): Promise<DashboardStats> => {
return get('/dashboard/stats');
};
export const getOrderAnalytics = async (daysOrParams: number | {start_date: string; end_date: string} = 7): Promise<OrderAnalytics> => {
let params: {start_date: string; end_date: string};
@@ -502,6 +519,8 @@ export const getShippingRules = async (): Promise<ShippingRule[]> => {
card_name: action.card_name || '',
delivery_count: Number(action.delivery_count || 1),
enabled: action.enabled !== false,
delay_override: cfg.delay_override === true,
delay_seconds: Number(action.delay_seconds || 0),
config_json: action.config_json || '{}',
};
}),
@@ -541,7 +560,12 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<a
delivery_count: variant.delivery_count || 1,
enabled: variant.enabled !== false,
sort_order: index + 1,
config_json: JSON.stringify({ spec_name: variant.spec_name || '', spec_value: variant.spec_value || '' }),
delay_seconds: variant.delay_seconds || 0,
config_json: JSON.stringify({
spec_name: variant.spec_name || '',
spec_value: variant.spec_value || '',
delay_override: variant.delay_override === true,
}),
}))
: (rule.actions && rule.actions.length > 0 ? rule.actions : [{
action_type: 'send_card' as const,
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, test } from 'vitest';
import { normalizeSMTPSettings } from './smtpSettings';
describe('normalizeSMTPSettings', () => {
test('migrates a legacy sender email as the envelope address', () => {
expect(normalizeSMTPSettings({ smtp_from: '[email protected]', smtp_user: '[email protected]' })).toMatchObject({
smtp_from_name: '',
smtp_from_address: '[email protected]',
});
});
test('migrates a legacy display name and falls back to the SMTP user address', () => {
expect(normalizeSMTPSettings({ smtp_from: '闲鱼助手', smtp_user: '[email protected]' })).toMatchObject({
smtp_from_name: '闲鱼助手',
smtp_from_address: '[email protected]',
});
});
test('preserves explicit split sender fields', () => {
expect(normalizeSMTPSettings({
smtp_from: '[email protected]',
smtp_from_name: '新名称',
smtp_from_address: '[email protected]',
})).toMatchObject({
smtp_from_name: '新名称',
smtp_from_address: '[email protected]',
});
});
});
+9
View File
@@ -0,0 +1,9 @@
export const normalizeSMTPSettings = (settings: Record<string, any>): Record<string, any> => {
const legacyFrom = String(settings.smtp_from || '').trim();
const legacyIsAddress = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(legacyFrom);
return {
...settings,
smtp_from_name: settings.smtp_from_name || (legacyIsAddress ? '' : legacyFrom),
smtp_from_address: settings.smtp_from_address || (legacyIsAddress ? legacyFrom : settings.smtp_user || ''),
};
};
+10
View File
@@ -175,6 +175,8 @@ export interface ShippingVariant {
card_type?: Card['type'];
delivery_count: number;
enabled: boolean;
delay_override?: boolean;
delay_seconds?: number;
config_json?: string;
}
@@ -199,6 +201,14 @@ export interface AdminStats {
total_orders: number;
}
export interface DashboardStats {
total_cookies: number;
active_cookies: number;
total_cards: number;
total_keywords: number;
total_orders: number;
}
export interface OrderAnalytics {
revenue_stats: {
total_amount: number;
+9 -8
View File
@@ -89,8 +89,6 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
return nil
}
}
m.mu.Unlock()
acc := engine.New(engine.Config{
CookieID: cookieID,
CookieStr: cookieValue,
@@ -105,16 +103,17 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
cancel: cancel,
done: make(chan struct{}),
}
m.mu.Lock()
m.accounts[cookieID] = ma
m.mu.Unlock()
m.logger.Info("启动账号", "account", cookieID)
go func() {
defer close(ma.done)
ma.err = acc.Run(accCtx)
m.logger.Info("账号运行结束", "account", cookieID, "err", ma.err)
err := acc.Run(accCtx)
m.mu.Lock()
ma.err = err
m.mu.Unlock()
close(ma.done)
m.logger.Info("账号运行结束", "account", cookieID, "err", err)
}()
return nil
}
@@ -131,7 +130,9 @@ func (m *Manager) Stop(cookieID string) {
ma.cancel()
<-ma.done
m.mu.Lock()
delete(m.accounts, cookieID)
if current := m.accounts[cookieID]; current == ma {
delete(m.accounts, cookieID)
}
m.mu.Unlock()
m.logger.Info("账号已停止", "account", cookieID)
}
+40 -4
View File
@@ -3,19 +3,20 @@ package account
import (
"context"
"path/filepath"
"sync"
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
)
type noopHandler struct{}
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
// TestManagerStartStop 验证从 DB 加载账号、启停和 GetInstance。
@@ -73,6 +74,41 @@ func TestManagerStartStop(t *testing.T) {
}
}
func TestManagerConcurrentStartCreatesSingleManagedInstance(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "test.db")
database, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatal(err)
}
defer database.Close()
store := db.NewStore(database, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "[email protected]", "pw")
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
store.Cookies.Save(context.Background(), "same", "unb=1; _m_h5_tk=t_1;", admin.ID)
mgr := NewManager(store, noopHandler{}, nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := mgr.Start(ctx, "same", "unb=1; _m_h5_tk=t_1;"); err != nil {
t.Errorf("Start: %v", err)
}
}()
}
wg.Wait()
mgr.mu.Lock()
count := len(mgr.accounts)
mgr.mu.Unlock()
if count != 1 {
t.Fatalf("managed instances=%d want 1", count)
}
mgr.Stop("same")
}
// TestManagerStopAll 验证 StopAll 停止所有运行中的账号,用于进程优雅退出。
func TestManagerStopAll(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "test.db")
+10 -8
View File
@@ -160,12 +160,12 @@ func classifyAccountAlertEvent(title, body string) string {
}
// OnTokenCaptchaVerification 处理 token 刷新触发的闲鱼滑块风控。
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL string) (string, bool) {
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL string) (*mtop.RefreshResult, bool) {
br, ok := a.browser.(browserTokenCaptchaRecoverer)
if a.browser == nil || !ok {
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
"token 风控验证无法自动处理", "浏览器自动化未启用,无法自动完成 token 滑块验证。")
return "", false
return nil, false
}
start := time.Now()
@@ -188,7 +188,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
if a.store == nil || a.store.Cookies == nil {
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
"token 风控验证无法保存", "账号存储未初始化,无法保存验证后的 Cookie。")
return "", false
return nil, false
}
if d, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && d != nil {
@@ -196,6 +196,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
metadataJSON = d.MetadataJSON
}
freshAccessToken := ""
provider := func(runCtx context.Context, currentCookies string) (string, bool, string, error) {
if a.captchaReq == nil {
return "", false, "", nil
@@ -208,6 +209,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
if err != nil || res == nil {
return "", false, "", err
}
freshAccessToken = res.AccessToken
return res.VerificationURL, res.TokenOK, res.UpdatedCookies, nil
}
@@ -225,10 +227,10 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
}
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
"token 风控验证失败", err.Error())
return "", false
return nil, false
}
if strings.TrimSpace(newCookies) == "" {
return "", false
return nil, false
}
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, cookierefresh.MetadataWithoutSnapshot(metadataJSON), time.Now().Unix()); err != nil {
a.logger.Warn("保存 token 风控恢复 Cookie 失败", "account", cookieID, "err", err)
@@ -241,7 +243,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
DurationMS: time.Since(start).Milliseconds(),
})
}
return "", false
return nil, false
}
if a.store.Tokens != nil {
_ = a.store.Tokens.Clear(ctx, cookieID)
@@ -255,8 +257,8 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
})
}
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelInfo,
"token 风控验证已自动恢复", "系统已完成滑块验证并更新 x5sec,正在重新获取 token。")
return newCookies, true
"token 风控验证已自动恢复", "系统已完成验证并更新登录凭证。")
return &mtop.RefreshResult{AccessToken: freshAccessToken, UpdatedCookies: newCookies}, true
}
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
+8 -3
View File
@@ -175,6 +175,8 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
req := &fakeCaptchaRequester{result: &mtop.FreshCaptchaResult{
VerificationURL: "https://fresh.example/captcha",
UpdatedCookies: "unb=1; _m_h5_tk=fresh;",
AccessToken: "fresh-access-token",
TokenOK: true,
}}
notifier := &fakeNotifier{}
a := New(store, nil, nil)
@@ -182,12 +184,15 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
a.SetTokenCaptchaRequester(req)
a.SetNotifier(notifier)
newCookies, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; _m_h5_tk=tk;", "https://old.example/captcha")
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; _m_h5_tk=tk;", "https://old.example/captcha")
if !ok {
t.Fatal("token captcha recovery should succeed")
}
if !strings.Contains(newCookies, "x5sec=ok") {
t.Fatalf("returned cookies should contain x5sec: %q", newCookies)
if result == nil || !strings.Contains(result.UpdatedCookies, "x5sec=ok") {
t.Fatalf("returned cookies should contain x5sec: %+v", result)
}
if result.AccessToken != "fresh-access-token" {
t.Fatalf("fresh access token was dropped: %+v", result)
}
if fb.tokenCaptchaCalls != 1 || fb.tokenCaptchaURL != "https://old.example/captcha" {
t.Fatalf("browser captcha call mismatch: calls=%d url=%q", fb.tokenCaptchaCalls, fb.tokenCaptchaURL)
+26 -2
View File
@@ -297,14 +297,38 @@ func (c *Center) executeActionWithDelay(ctx context.Context, task Task, action d
if !action.Enabled {
return 0, nil
}
if action.DelaySeconds > 0 {
if err := sleepCtx(ctx, time.Duration(action.DelaySeconds)*time.Second); err != nil {
delaySeconds, err := c.actionDelaySeconds(ctx, action)
if err != nil {
return 0, err
}
if delaySeconds > 0 {
if err := sleepCtx(ctx, time.Duration(delaySeconds)*time.Second); err != nil {
return 0, err
}
}
return c.executeAction(ctx, task, action)
}
// actionDelaySeconds 统一卡密默认延时和动作覆盖语义。旧动作没有
// delay_override 字段时自动使用卡密上的默认延时。
func (c *Center) actionDelaySeconds(ctx context.Context, action db.AutomationAction) (int, error) {
if action.ActionType != ActionSendCard || action.CardID <= 0 {
return action.DelaySeconds, nil
}
var cfg struct {
DelayOverride bool `json:"delay_override"`
}
_ = json.Unmarshal([]byte(action.ConfigJSON), &cfg)
if cfg.DelayOverride {
return action.DelaySeconds, nil
}
card, err := c.store.Cards.Get(ctx, action.CardID)
if err != nil {
return 0, err
}
return card.DelaySeconds, nil
}
func (c *Center) prepareTask(ctx context.Context, task Task) (Task, error) {
if task.OrderID == "" {
return task, nil
+27
View File
@@ -56,6 +56,33 @@ func newAutomationTestStore(t *testing.T) (*db.Store, func()) {
return store, func() { _ = database.Close() }
}
func TestActionDelayUsesCardDefaultUnlessOverridden(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
admin, _ := store.Users.GetByUsername(ctx, "admin")
cardID, err := store.Cards.Create(ctx, &db.CardFull{
Name: "delayed", Type: "text", TextContent: "x", Enabled: true, DelaySeconds: 15, UserID: admin.ID,
})
if err != nil {
t.Fatal(err)
}
center := New(store, nil, nil)
got, err := center.actionDelaySeconds(ctx, db.AutomationAction{
ActionType: ActionSendCard, CardID: cardID, DelaySeconds: 0, ConfigJSON: `{}`,
})
if err != nil || got != 15 {
t.Fatalf("default delay=%d err=%v want 15", got, err)
}
got, err = center.actionDelaySeconds(ctx, db.AutomationAction{
ActionType: ActionSendCard, CardID: cardID, DelaySeconds: 0, ConfigJSON: `{"delay_override":true}`,
})
if err != nil || got != 0 {
t.Fatalf("override delay=%d err=%v want 0", got, err)
}
}
func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
+76
View File
@@ -6,6 +6,14 @@ import (
"errors"
)
// AIConversationMessage 是一个账号会话中的 AI 对话消息。
type AIConversationMessage struct {
Role string
Content string
Intent string
BargainCount int
}
// AIReplySettings 对应 ai_reply_settings 表。
type AIReplySettings struct {
CookieID string `json:"cookie_id"`
@@ -50,3 +58,71 @@ func (a *AIReply) Get(ctx context.Context, cookieID string) (*AIReplySettings, e
}
return &s, nil
}
// ConversationHistory 返回最近的会话消息,结果按时间正序排列。
func (a *AIReply) ConversationHistory(ctx context.Context, cookieID, chatID, itemID string, limit int) ([]AIConversationMessage, error) {
if limit <= 0 || limit > 20 {
limit = 10
}
rows, err := a.DB.QueryContext(ctx, `
SELECT role, content, COALESCE(intent,''), COALESCE(bargain_count,0)
FROM ai_conversations
WHERE cookie_id=? AND chat_id=? AND item_id=?
ORDER BY id DESC LIMIT ?`, cookieID, chatID, itemID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var reversed []AIConversationMessage
for rows.Next() {
var message AIConversationMessage
if err := rows.Scan(&message.Role, &message.Content, &message.Intent, &message.BargainCount); err != nil {
return nil, err
}
reversed = append(reversed, message)
}
if err := rows.Err(); err != nil {
return nil, err
}
result := make([]AIConversationMessage, len(reversed))
for i := range reversed {
result[len(reversed)-1-i] = reversed[i]
}
return result, nil
}
// CurrentBargainCount 返回会话目前的砍价轮次。
func (a *AIReply) CurrentBargainCount(ctx context.Context, cookieID, chatID, itemID string) (int, error) {
var count int
err := a.DB.QueryRowContext(ctx, `
SELECT COALESCE(MAX(bargain_count),0) FROM ai_conversations
WHERE cookie_id=? AND chat_id=? AND item_id=?`, cookieID, chatID, itemID).Scan(&count)
return count, err
}
// AddConversation 追加一条会话消息。
func (a *AIReply) AddConversation(ctx context.Context, cookieID, chatID, userID, itemID string, message AIConversationMessage) error {
_, err := a.DB.ExecContext(ctx, `
INSERT INTO ai_conversations (cookie_id,chat_id,user_id,item_id,role,content,intent,bargain_count)
VALUES (?,?,?,?,?,?,?,?)`, cookieID, chatID, userID, itemID, message.Role, message.Content, message.Intent, message.BargainCount)
return err
}
// AddConversationExchange 原子保存一轮用户消息与 AI 回复,避免上游调用失败时
// 留下半轮历史并错误消耗砍价轮次。
func (a *AIReply) AddConversationExchange(ctx context.Context, cookieID, chatID, userID, itemID string, userMessage, assistantMessage AIConversationMessage) error {
tx, err := a.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
query := `INSERT INTO ai_conversations
(cookie_id,chat_id,user_id,item_id,role,content,intent,bargain_count)
VALUES (?,?,?,?,?,?,?,?)`
for _, message := range []AIConversationMessage{userMessage, assistantMessage} {
if _, err := tx.ExecContext(ctx, query, cookieID, chatID, userID, itemID, message.Role, message.Content, message.Intent, message.BargainCount); err != nil {
return err
}
}
return tx.Commit()
}
+14 -3
View File
@@ -34,6 +34,9 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
{"keywords", "item_id"},
{"item_info", "multi_quantity_delivery"},
{"default_replies", "reply_once"},
{"default_reply_records", "status"},
{"default_reply_records", "text_sent"},
{"default_reply_records", "image_sent"},
{"users", "is_admin"},
{"sessions", "session_id"},
{"notification_channels", "user_id"},
@@ -105,7 +108,7 @@ func columnExists(t *testing.T, db *sql.DB, table, col string) bool {
return false
}
func TestMigration14DownUpSQLite(t *testing.T) {
func TestLatestMigrationsDownUpSQLite(t *testing.T) {
tmp := t.TempDir()
dbPath := filepath.Join(tmp, "rollback.db")
ctx := context.Background()
@@ -119,8 +122,11 @@ func TestMigration14DownUpSQLite(t *testing.T) {
t.Fatalf("goose dialect: %v", err)
}
goose.SetBaseFS(migrationsFS)
if err := goose.Down(d, "migrations/sqlite"); err != nil {
t.Fatalf("down latest migration: %v", err)
// 依次回滚 16(回复投递状态)、15(AI 索引)、14(通知/日志),再整体升级。
for i := 0; i < 3; i++ {
if err := goose.Down(d, "migrations/sqlite"); err != nil {
t.Fatalf("down migration #%d: %v", i+1, err)
}
}
if columnExists(t, d, "notification_channels", "event_types") {
t.Fatal("event_types should be removed after migration 14 down")
@@ -128,6 +134,9 @@ func TestMigration14DownUpSQLite(t *testing.T) {
if tableExists(t, d, "risk_control_logs") {
t.Fatal("risk_control_logs should be removed after migration 14 down")
}
if columnExists(t, d, "default_reply_records", "status") {
t.Fatal("default_reply_records.status should be removed after migration 16 down")
}
if err := goose.Up(d, "migrations/sqlite"); err != nil {
t.Fatalf("up after down: %v", err)
@@ -142,6 +151,8 @@ func TestMigration14DownUpSQLite(t *testing.T) {
{"scheduled_login_renew_log", "updated_cookie_count"},
{"scheduled_api_cookie_renew_log", "request_count"},
{"risk_control_logs", "processing_status"},
{"default_reply_records", "status"},
{"default_reply_records", "text_sent"},
} {
if !columnExists(t, d, c.table, c.col) {
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
@@ -0,0 +1,30 @@
-- +goose Up
-- MySQL may use the composite scope index to satisfy the cookie_id foreign key.
-- Keep a dedicated leading-column index so the scope index remains removable
-- during a Goose rollback.
DROP PROCEDURE IF EXISTS add_ai_conversations_cookie_index;
-- +goose StatementBegin
CREATE PROCEDURE add_ai_conversations_cookie_index()
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'ai_conversations'
AND INDEX_NAME = 'idx_ai_conversations_cookie_id'
) THEN
CREATE INDEX idx_ai_conversations_cookie_id
ON ai_conversations(cookie_id);
END IF;
END;
-- +goose StatementEnd
CALL add_ai_conversations_cookie_index();
DROP PROCEDURE add_ai_conversations_cookie_index;
CREATE INDEX idx_ai_conversations_scope
ON ai_conversations(cookie_id, chat_id, item_id, id);
-- +goose Down
DROP INDEX idx_ai_conversations_scope ON ai_conversations;
-- Intentionally retain idx_ai_conversations_cookie_id: the cookie_id foreign key
-- requires an index even after this feature migration is rolled back.
@@ -0,0 +1,15 @@
-- +goose Up
ALTER TABLE default_reply_records
ADD COLUMN status VARCHAR(16) NOT NULL DEFAULT 'sent',
ADD COLUMN text_sent INTEGER NOT NULL DEFAULT 1,
ADD COLUMN image_sent INTEGER NOT NULL DEFAULT 1,
ADD COLUMN last_error TEXT NULL,
ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-- +goose Down
ALTER TABLE default_reply_records
DROP COLUMN status,
DROP COLUMN text_sent,
DROP COLUMN image_sent,
DROP COLUMN last_error,
DROP COLUMN updated_at;
@@ -0,0 +1,6 @@
-- +goose Up
CREATE INDEX IF NOT EXISTS idx_ai_conversations_scope
ON ai_conversations(cookie_id, chat_id, item_id, id);
-- +goose Down
DROP INDEX IF EXISTS idx_ai_conversations_scope;
@@ -0,0 +1,13 @@
-- +goose Up
ALTER TABLE default_reply_records ADD COLUMN status TEXT NOT NULL DEFAULT 'sent';
ALTER TABLE default_reply_records ADD COLUMN text_sent INTEGER NOT NULL DEFAULT 1;
ALTER TABLE default_reply_records ADD COLUMN image_sent INTEGER NOT NULL DEFAULT 1;
ALTER TABLE default_reply_records ADD COLUMN last_error TEXT NOT NULL DEFAULT '';
ALTER TABLE default_reply_records ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-- +goose Down
ALTER TABLE default_reply_records DROP COLUMN updated_at;
ALTER TABLE default_reply_records DROP COLUMN last_error;
ALTER TABLE default_reply_records DROP COLUMN image_sent;
ALTER TABLE default_reply_records DROP COLUMN text_sent;
ALTER TABLE default_reply_records DROP COLUMN status;
@@ -0,0 +1,6 @@
-- +goose Up
CREATE INDEX IF NOT EXISTS idx_ai_conversations_scope
ON ai_conversations(cookie_id, chat_id, item_id, id);
-- +goose Down
DROP INDEX IF EXISTS idx_ai_conversations_scope;
@@ -0,0 +1,20 @@
-- +goose Up
ALTER TABLE default_reply_records ADD COLUMN status TEXT NOT NULL DEFAULT 'sent';
ALTER TABLE default_reply_records ADD COLUMN text_sent INTEGER NOT NULL DEFAULT 1;
ALTER TABLE default_reply_records ADD COLUMN image_sent INTEGER NOT NULL DEFAULT 1;
ALTER TABLE default_reply_records ADD COLUMN last_error TEXT NOT NULL DEFAULT '';
ALTER TABLE default_reply_records ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
-- +goose Down
CREATE TABLE default_reply_records_legacy (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
replied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(cookie_id, chat_id),
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
INSERT INTO default_reply_records_legacy (id,cookie_id,chat_id,replied_at)
SELECT id,cookie_id,chat_id,replied_at FROM default_reply_records;
DROP TABLE default_reply_records;
ALTER TABLE default_reply_records_legacy RENAME TO default_reply_records;
+10 -3
View File
@@ -444,7 +444,7 @@ func TestMultiDB_Notifications(t *testing.T) {
}
}
func TestMultiDB_Migration14DownUp(t *testing.T) {
func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
for _, tg := range allTestTargets(t) {
t.Run(tg.name, func(t *testing.T) {
defer tg.cleanup()
@@ -453,8 +453,10 @@ func TestMultiDB_Migration14DownUp(t *testing.T) {
t.Fatalf("set goose dialect: %v", err)
}
goose.SetBaseFS(migrationsFS)
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
t.Fatalf("migration 14 down: %v", err)
for i := 0; i < 3; i++ {
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
t.Fatalf("migration down #%d: %v", i+1, err)
}
}
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "notification_channels", "event_types") {
t.Fatal("notification_channels.event_types should be removed after down")
@@ -462,6 +464,9 @@ func TestMultiDB_Migration14DownUp(t *testing.T) {
if tableExistsForDialect(t, tg.store.DB, tg.dialect, "risk_control_logs") {
t.Fatal("risk_control_logs should be removed after down")
}
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "default_reply_records", "status") {
t.Fatal("default_reply_records.status should be removed after down")
}
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
t.Fatalf("migration up after down: %v", err)
@@ -476,6 +481,8 @@ func TestMultiDB_Migration14DownUp(t *testing.T) {
{"scheduled_login_renew_log", "updated_cookie_count"},
{"scheduled_api_cookie_renew_log", "request_count"},
{"risk_control_logs", "processing_status"},
{"default_reply_records", "status"},
{"default_reply_records", "text_sent"},
} {
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)
+86 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
"time"
)
// Keyword 对应 keywords 表。
@@ -23,6 +24,13 @@ type DefaultReply struct {
ReplyOnce bool
}
// DefaultReplyRecord 记录 reply_once 消息各部分的投递状态。
type DefaultReplyRecord struct {
Status string
TextSent bool
ImageSent bool
}
// ItemReply 对应 item_replay 表(指定商品回复)。
type ItemReply struct {
ItemID string
@@ -87,11 +95,88 @@ func (d *DefaultReplies) Get(ctx context.Context, cookieID string) (*DefaultRepl
func (d *DefaultReplies) HasRecord(ctx context.Context, cookieID, chatID string) bool {
var n int
err := d.DB.QueryRowContext(ctx,
`SELECT 1 FROM default_reply_records WHERE cookie_id=? AND chat_id=? LIMIT 1`,
`SELECT 1 FROM default_reply_records WHERE cookie_id=? AND chat_id=? AND status='sent' LIMIT 1`,
cookieID, chatID).Scan(&n)
return err == nil
}
// ClaimRecord 原子领取一次默认回复投递。新记录初始化为 pending;失败记录允许继续
// 投递尚未成功的部分;pending/sent 记录会阻止并发重复发送。
func (d *DefaultReplies) ClaimRecord(ctx context.Context, cookieID, chatID string, needsText, needsImage bool) (DefaultReplyRecord, bool, error) {
query := dialectInsertIgnorePrefix(d.Dialect) + ` INTO default_reply_records
(cookie_id,chat_id,status,text_sent,image_sent,last_error,updated_at)
VALUES (?,?, 'pending', ?, ?, '', CURRENT_TIMESTAMP)` + dialectInsertIgnore(d.Dialect, []string{"cookie_id", "chat_id"})
res, err := d.DB.ExecContext(ctx, query, cookieID, chatID, boolToInt(!needsText), boolToInt(!needsImage))
if err != nil {
return DefaultReplyRecord{}, false, err
}
if affected, _ := res.RowsAffected(); affected > 0 {
return DefaultReplyRecord{Status: "pending", TextSent: !needsText, ImageSent: !needsImage}, true, nil
}
record, err := d.Record(ctx, cookieID, chatID)
if err != nil {
return DefaultReplyRecord{}, false, err
}
if record.Status == "sent" {
return record, false, nil
}
// pending 是发送任务的短租约。进程崩溃或强制退出后,过期租约必须可被
// 新实例接管,否则该会话会永久失去默认回复。
leaseExpiredBefore := time.Now().Add(-5 * time.Minute)
res, err = d.DB.ExecContext(ctx, `UPDATE default_reply_records
SET status='pending',last_error='',updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND chat_id=?
AND (status='failed' OR (status='pending' AND updated_at<?))`,
cookieID, chatID, leaseExpiredBefore)
if err != nil {
return DefaultReplyRecord{}, false, err
}
affected, _ := res.RowsAffected()
return record, affected > 0, nil
}
// Record 查询一次默认回复的投递状态。
func (d *DefaultReplies) Record(ctx context.Context, cookieID, chatID string) (DefaultReplyRecord, error) {
var record DefaultReplyRecord
var textSent, imageSent int
err := d.DB.QueryRowContext(ctx, `SELECT status,text_sent,image_sent
FROM default_reply_records WHERE cookie_id=? AND chat_id=?`, cookieID, chatID).
Scan(&record.Status, &textSent, &imageSent)
record.TextSent = textSent != 0
record.ImageSent = imageSent != 0
return record, err
}
// MarkPartSent 标记图片或文字已经成功投递。
func (d *DefaultReplies) MarkPartSent(ctx context.Context, cookieID, chatID, part string) error {
column := ""
switch part {
case "text":
column = "text_sent"
case "image":
column = "image_sent"
default:
return errors.New("未知默认回复部分")
}
_, err := d.DB.ExecContext(ctx, `UPDATE default_reply_records SET `+column+`=1,updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND chat_id=?`, cookieID, chatID)
return err
}
func (d *DefaultReplies) MarkRecordFailed(ctx context.Context, cookieID, chatID, message string) error {
_, err := d.DB.ExecContext(ctx, `UPDATE default_reply_records
SET status='failed',last_error=?,updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND chat_id=?`, message, cookieID, chatID)
return err
}
func (d *DefaultReplies) MarkRecordSent(ctx context.Context, cookieID, chatID string) error {
_, err := d.DB.ExecContext(ctx, `UPDATE default_reply_records
SET status='sent',last_error='',replied_at=CURRENT_TIMESTAMP,updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND chat_id=?`, cookieID, chatID)
return err
}
// AddRecord 记录已回复(reply_once 防重复)。
func (d *DefaultReplies) AddRecord(ctx context.Context, cookieID, chatID string) error {
_, err := d.DB.ExecContext(ctx,
+47
View File
@@ -0,0 +1,47 @@
package db
import (
"context"
"path/filepath"
"testing"
"time"
)
func TestDefaultReplyClaimReclaimsExpiredPendingLease(t *testing.T) {
ctx := context.Background()
database, dialect, err := Open(ctx, filepath.Join(t.TempDir(), "reply-state.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
defer database.Close()
store := NewStore(database, dialect)
result, err := database.ExecContext(ctx, `INSERT INTO users (username,email,password_hash) VALUES (?,?,?)`, "reply-test", "[email protected]", "hash")
if err != nil {
t.Fatalf("insert user: %v", err)
}
userID, err := result.LastInsertId()
if err != nil {
t.Fatalf("LastInsertId: %v", err)
}
if err := store.Cookies.Save(ctx, "cookie-1", "unb=1", userID); err != nil {
t.Fatalf("save cookie: %v", err)
}
initial, claimed, err := store.DefaultReps.ClaimRecord(ctx, "cookie-1", "chat-1", true, true)
if err != nil || !claimed || initial.Status != "pending" {
t.Fatalf("initial claim: record=%+v claimed=%v err=%v", initial, claimed, err)
}
if _, claimed, err = store.DefaultReps.ClaimRecord(ctx, "cookie-1", "chat-1", true, true); err != nil || claimed {
t.Fatalf("active pending lease must not be claimed: claimed=%v err=%v", claimed, err)
}
_, err = database.ExecContext(ctx, `UPDATE default_reply_records SET updated_at=? WHERE cookie_id=? AND chat_id=?`, time.Now().Add(-10*time.Minute), "cookie-1", "chat-1")
if err != nil {
t.Fatalf("expire lease: %v", err)
}
reclaimed, claimed, err := store.DefaultReps.ClaimRecord(ctx, "cookie-1", "chat-1", true, true)
if err != nil || !claimed || reclaimed.Status != "pending" {
t.Fatalf("expired pending lease should be reclaimed: record=%+v claimed=%v err=%v", reclaimed, claimed, err)
}
}
+66 -15
View File
@@ -91,7 +91,7 @@ type accountEventHandler interface {
}
type tokenCaptchaHandler interface {
OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL string) (newCookies string, ok bool)
OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL string) (*mtop.RefreshResult, bool)
}
// ChatMessage 防抖后投递给业务层的一条聊天消息。
@@ -173,6 +173,13 @@ type Account struct {
// 消息处理信号量
sem chan struct{}
// 业务任务生命周期。Stop 先禁止新增任务并取消 runtimeCtx,再等待已进入
// 自动化/回复链的任务退出。
taskMu sync.Mutex
taskWG sync.WaitGroup
runtimeCtx context.Context
accepting bool
reply *ReplyService
}
@@ -262,6 +269,7 @@ func New(cfg Config) *Account {
processed: make(map[string]time.Time),
debounceTimers: make(map[string]*debounceEntry),
sem: make(chan struct{}, MessageSemaphoreSize),
accepting: true,
runtimeState: RuntimeStarting,
runtimeMessage: "正在启动账号服务",
runtimeUpdatedAt: time.Now(),
@@ -276,9 +284,14 @@ func New(cfg Config) *Account {
// 调用方应在独立 goroutine 中运行;Stop 可优雅停止。
func (a *Account) Run(parent context.Context) error {
ctx, cancel := context.WithCancel(parent)
defer cancel()
a.mu.Lock()
a.stopFn = cancel
a.mu.Unlock()
a.taskMu.Lock()
a.runtimeCtx = ctx
a.accepting = true
a.taskMu.Unlock()
// 复用 DB 缓存的 device_id(跨进程重启稳定),避免每次重启换新设备 ID 触发风控。
a.ensureDeviceIDCached(ctx)
@@ -499,16 +512,22 @@ func (a *Account) Run(parent context.Context) error {
// Stop 优雅停止。
func (a *Account) Stop() {
a.mu.Lock()
defer a.mu.Unlock()
if a.stopped {
a.mu.Unlock()
return
}
a.stopped = true
a.runtimeState = RuntimeStopped
a.runtimeMessage = "账号服务已停止"
a.runtimeUpdatedAt = time.Now()
if a.stopFn != nil {
a.stopFn()
cancel := a.stopFn
a.mu.Unlock()
a.taskMu.Lock()
a.accepting = false
a.taskMu.Unlock()
if cancel != nil {
cancel()
}
// 取消所有防抖定时器。
a.debounceMu.Lock()
@@ -519,6 +538,34 @@ func (a *Account) Stop() {
}
a.debounceTimers = make(map[string]*debounceEntry)
a.debounceMu.Unlock()
done := make(chan struct{})
go func() {
a.taskWG.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(10 * time.Second):
a.logger.Warn("等待账号业务任务退出超时")
}
}
func (a *Account) beginTask() (context.Context, bool) {
a.taskMu.Lock()
defer a.taskMu.Unlock()
if !a.accepting {
return nil, false
}
ctx := a.runtimeCtx
if ctx == nil {
ctx = context.Background()
}
if ctx.Err() != nil {
return nil, false
}
a.taskWG.Add(1)
return ctx, true
}
// handleMaxFailures 连续失败达上限:尝试密码登录刷新;失败则返回 err 触发上层重启实例。
@@ -814,9 +861,13 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
}
res, err := a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
if err != nil && mtop.IsRiskVerificationErr(err) {
if recoveredCookies, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, err); ok {
cookieStr = recoveredCookies
res, err = a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
if recovered, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, err); ok {
cookieStr = recovered.UpdatedCookies
if recovered.AccessToken != "" {
res, err = recovered, nil
} else {
res, err = a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
}
}
}
if res != nil && res.UpdatedCookies != "" && res.UpdatedCookies != cookieStr {
@@ -844,25 +895,25 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
return res.AccessToken, cookieStr, nil
}
func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr string, err error) (string, bool) {
func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr string, err error) (*mtop.RefreshResult, bool) {
h, ok := a.handler.(tokenCaptchaHandler)
if !ok {
return "", false
return nil, false
}
var riskErr *mtop.RiskVerificationError
if !errors.As(err, &riskErr) || strings.TrimSpace(riskErr.VerificationURL) == "" {
return "", false
return nil, false
}
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求滑块验证",
"token 刷新触发闲鱼风控验证,系统将尝试自动完成滑块并合并 x5sec。")
newCookies, ok := h.OnTokenCaptchaVerification(ctx, a.CookieID, cookieStr, riskErr.VerificationURL)
if !ok || strings.TrimSpace(newCookies) == "" {
return "", false
result, ok := h.OnTokenCaptchaVerification(ctx, a.CookieID, cookieStr, riskErr.VerificationURL)
if !ok || result == nil || strings.TrimSpace(result.UpdatedCookies) == "" {
return nil, false
}
a.replaceCookieStr(newCookies)
a.replaceCookieStr(result.UpdatedCookies)
a.clearTokenCache(ctx)
a.setRuntimeState(RuntimeConnecting, "token 风控验证已处理,正在重新获取登录凭证")
return newCookies, true
return result, true
}
// acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控
+38
View File
@@ -4,15 +4,53 @@ import (
"context"
"errors"
"fmt"
"strings"
"sync/atomic"
"testing"
"time"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
type riskCountingMTop struct {
fakeRunMtop
calls int
}
func (m *riskCountingMTop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
m.calls++
return nil, &mtop.RiskVerificationError{Ret: []string{"FAIL_SYS_USER_VALIDATE"}, VerificationURL: "https://verify.example"}
}
type tokenRecoveredHandler struct{ recordingHandler }
func (h *tokenRecoveredHandler) OnTokenCaptchaVerification(context.Context, string, string, string) (*mtop.RefreshResult, bool) {
return &mtop.RefreshResult{AccessToken: "recovered-token", UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, true
}
func TestRefreshTokenUsesRecoveredAccessTokenWithoutSecondRequest(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
client := &riskCountingMTop{}
acc.mtop = client
acc.handler = &tokenRecoveredHandler{}
token, cookies, err := acc.refreshToken(context.Background())
if err != nil {
t.Fatal(err)
}
if token != "recovered-token" || !strings.Contains(cookies, "recovered") {
t.Fatalf("token=%q cookies=%q", token, cookies)
}
if client.calls != 1 {
t.Fatalf("refresh calls=%d want 1", client.calls)
}
}
// TestStop_IdempotentAndClearsTimers Stop 重复调用幂等;调用后防抖定时器被清空。
func TestStop_IdempotentAndClearsTimers(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
+124 -24
View File
@@ -1,6 +1,5 @@
// ai.go AI 回复实现(优先级3)。调用 OpenAI 兼容 chat completions 接口。
// 使用商品信息和自定义提示词生成回复。
// 砍价/对话历史追踪(bargain_count、ai_conversations)留后续完善,本实现为单轮无状态回复。
// 使用商品信息、对话历史和确定性的价格边界生成回复。
package engine
@@ -8,6 +7,7 @@ import (
"context"
"fmt"
"log/slog"
"math"
"regexp"
"strconv"
"strings"
@@ -56,9 +56,23 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
return nil, nil
}
// 取商品信息构造 system prompt。
// 取商品信息和当前会话状态构造 system prompt。
itemTitle, itemPrice, itemDesc := a.itemInfo(ctx, m.ItemID)
systemPrompt := buildSystemPrompt(cfg.CustomPrompts, itemTitle, itemPrice, itemDesc, cfg.MaxDiscountPercent, cfg.MaxDiscountAmount)
history, bargainCount, isBargain, err := a.conversationContext(ctx, m)
if err != nil {
return nil, fmt.Errorf("读取 AI 对话历史失败: %w", err)
}
if isBargain {
bargainCount++
}
withinBargainLimit := !isBargain || bargainCount <= cfg.MaxBargainRounds
systemPrompt := buildSystemPrompt(
cfg.CustomPrompts, itemTitle, itemPrice, itemDesc,
cfg.MaxDiscountPercent, cfg.MaxDiscountAmount, cfg.MaxBargainRounds, bargainCount,
)
if !withinBargainLimit {
systemPrompt += "\n当前买家已经超过最大砍价轮次。不得继续降价,只能礼貌说明价格不再优惠。"
}
// 调 OpenAI 兼容接口。
clientCfg := openai.DefaultConfig(aiCfg.APIKey)
@@ -67,12 +81,19 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
}
client := openai.NewClientWithConfig(clientCfg)
messages := []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem, Content: systemPrompt}}
for _, message := range history {
role := openai.ChatMessageRoleUser
if message.Role == "assistant" {
role = openai.ChatMessageRoleAssistant
}
messages = append(messages, openai.ChatCompletionMessage{Role: role, Content: truncateAIContent(message.Content)})
}
messages = append(messages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser, Content: m.Text})
resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
Model: aiCfg.Model,
Messages: []openai.ChatCompletionMessage{
{Role: openai.ChatMessageRoleSystem, Content: systemPrompt},
{Role: openai.ChatMessageRoleUser, Content: m.Text},
},
Model: aiCfg.Model,
Messages: messages,
Temperature: 0.7,
})
if err != nil {
@@ -85,9 +106,43 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if reply == "" {
return nil, nil
}
minimumPrice := minimumAllowedPrice(itemPrice, cfg.MaxDiscountPercent, cfg.MaxDiscountAmount, withinBargainLimit)
if offered, unsafe := unsafeOfferedPrice(reply, minimumPrice); unsafe {
a.logger.Warn("AI 报价超过折扣边界,使用安全回复", "offered", offered, "minimum", minimumPrice)
if minimumPrice >= itemPrice || !withinBargainLimit {
reply = "抱歉,当前价格已经是最低价,暂时不能再优惠了。"
} else {
reply = fmt.Sprintf("可以优惠的最低价格是 %.2f 元,低于这个价格暂时无法成交。", minimumPrice)
}
}
if m.ChatID != "" && m.ItemID != "" {
intent := "chat"
if isBargain {
intent = "bargain"
}
if err := a.store.AIReply.AddConversationExchange(ctx, a.cookieID, m.ChatID, m.SenderUserID, m.ItemID,
db.AIConversationMessage{Role: "user", Content: m.Text, Intent: intent, BargainCount: bargainCount},
db.AIConversationMessage{Role: "assistant", Content: reply, Intent: "reply", BargainCount: bargainCount},
); err != nil {
return nil, fmt.Errorf("保存 AI 对话失败: %w", err)
}
}
return &ReplyResult{Text: reply}, nil
}
func (a *AIReplierImpl) conversationContext(ctx context.Context, m ChatMessage) ([]db.AIConversationMessage, int, bool, error) {
isBargain := bargainMessageRe.MatchString(strings.ToLower(m.Text))
if m.ChatID == "" || m.ItemID == "" {
return nil, 0, isBargain, nil
}
history, err := a.store.AIReply.ConversationHistory(ctx, a.cookieID, m.ChatID, m.ItemID, 10)
if err != nil {
return nil, 0, isBargain, err
}
count, err := a.store.AIReply.CurrentBargainCount(ctx, a.cookieID, m.ChatID, m.ItemID)
return history, count, isBargain, err
}
type globalAIConfig struct {
APIKey string
BaseURL string
@@ -140,7 +195,10 @@ func (a *AIReplierImpl) itemInfo(ctx context.Context, itemID string) (title stri
title = "未知商品"
}
price = parsePrice(it.ItemPrice)
desc = it.ItemDetail
desc = it.ItemDescription
if desc == "" {
desc = it.ItemDetail
}
if desc == "" {
desc = "暂无商品描述"
}
@@ -148,18 +206,17 @@ func (a *AIReplierImpl) itemInfo(ctx context.Context, itemID string) (title stri
}
// buildSystemPrompt 构造 system 提示词。
// 优先用自定义 prompt,否则用默认模板(含商品信息)。
func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemDesc string, maxDiscountPercent, maxDiscountAmount int) string {
// 自定义 prompt 只替换业务文案,价格和轮次安全约束始终由后端追加。
func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemDesc string, maxDiscountPercent, maxDiscountAmount, maxBargainRounds, bargainCount int) string {
var base string
if strings.TrimSpace(customPrompts) != "" {
return strings.ReplaceAll(customPrompts, "{item_title}", itemTitle)
}
if maxDiscountPercent <= 0 {
maxDiscountPercent = 10
}
if maxDiscountAmount <= 0 {
maxDiscountAmount = 100
}
return fmt.Sprintf(`你是闲鱼卖家的自动回复助手。请根据商品信息友好地回复买家。
base = strings.NewReplacer(
"{item_title}", itemTitle,
"{item_price}", fmt.Sprintf("%.2f", itemPrice),
"{item_description}", itemDesc,
).Replace(customPrompts)
} else {
base = fmt.Sprintf(`你是闲鱼卖家的自动回复助手。请根据商品信息友好地回复买家。
商品信息:
- 标题:%s
@@ -169,12 +226,55 @@ func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemD
要求:
1. 语气友好自然,像真人卖家
2. 回答简洁,不要过长
3. 涉及价格让步时,最多优惠 %.0f%% 或 %.0f 元
4. 不要编造商品没有的功能
5. 直接回复内容,不要加引号或解释`, itemTitle, itemPrice, itemDesc, float64(maxDiscountPercent), float64(maxDiscountAmount))
3. 不要编造商品没有的功能
4. 直接回复内容,不要加引号或解释`, itemTitle, itemPrice, itemDesc)
}
return base + fmt.Sprintf(`
不可覆盖的价格安全规则:
- 原价 %.2f 元;最多优惠 %d%%,且最多优惠 %d 元;两个上限必须同时满足。
- 任一优惠上限为 0 时不得降价。
- 当前砍价轮次 %d,最多允许 %d 轮。
- 回复报价必须带“元”,不得给出低于允许最低价的价格。`, itemPrice, maxDiscountPercent, maxDiscountAmount, bargainCount, maxBargainRounds)
}
var priceRe = regexp.MustCompile(`[^\d.]`)
var bargainMessageRe = regexp.MustCompile(`(?i)(便宜|优惠|少点|最低|砍价|降价|打折|能不能.*(?:元|块)|\d+(?:\.\d+)?\s*(?:元|块).*(?:卖|行|可以))`)
var offeredPriceRe = regexp.MustCompile(`(\d+(?:\.\d+)?)\s*(?:元|块)`)
func minimumAllowedPrice(price float64, maxDiscountPercent, maxDiscountAmount int, allowDiscount bool) float64 {
if price <= 0 {
return 0
}
if !allowDiscount || maxDiscountPercent <= 0 || maxDiscountAmount <= 0 {
return price
}
byPercent := price * (1 - float64(maxDiscountPercent)/100)
byAmount := price - float64(maxDiscountAmount)
return math.Max(0, math.Max(byPercent, byAmount))
}
func unsafeOfferedPrice(reply string, minimum float64) (float64, bool) {
if minimum <= 0 {
return 0, false
}
for _, match := range offeredPriceRe.FindAllStringSubmatch(reply, -1) {
value, err := strconv.ParseFloat(match[1], 64)
if err == nil && value+0.0001 < minimum {
return value, true
}
}
return 0, false
}
func truncateAIContent(content string) string {
const maxRunes = 2000
runes := []rune(content)
if len(runes) <= maxRunes {
return content
}
return string(runes[:maxRunes])
}
// parsePrice 移除非数字字符后转换为 float。
func parsePrice(s string) float64 {
+71 -12
View File
@@ -12,30 +12,47 @@ import (
"xianyu-go/internal/db"
)
// TestBuildSystemPrompt 自定义 prompt 替换 {item_title};默认模板含商品信息与折扣上限。
// TestBuildSystemPrompt 自定义 prompt 替换变量,且始终追加价格与轮次安全约束。
func TestBuildSystemPrompt(t *testing.T) {
// 自定义 prompt 优先,仅替换 {item_title}。
got := buildSystemPrompt("你是卖{item_title}的客服", "iPhone", 0, "", 0, 0)
if got != "你是卖iPhone的客服" {
got := buildSystemPrompt("你是卖{item_title}的客服,价格{item_price}", "iPhone", 100, "手机", 0, 0, 3, 1)
if !strings.Contains(got, "你是卖iPhone的客服,价格100.00") {
t.Fatalf("自定义 prompt 替换: got %q", got)
}
if !strings.Contains(got, "任一优惠上限为 0 时不得降价") || !strings.Contains(got, "当前砍价轮次 1") {
t.Fatalf("自定义 prompt 缺少安全约束: %q", got)
}
// 默认模板:折扣上限 <=0 时兜底 10% / 100 元。
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 0, 0)
// 0 必须保留为不允许优惠,不能静默改成默认值。
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 0, 0, 3, 0)
if !strings.Contains(got, "标题:会员卡") || !strings.Contains(got, "价格:9.90 元") {
t.Fatalf("默认模板缺商品信息: %q", got)
}
if !strings.Contains(got, "最多优惠 10% 或 100 元") {
t.Fatalf("默认折扣上限未兜底: %q", got)
if !strings.Contains(got, "最多优惠 0%") || !strings.Contains(got, "最多优惠 0 元") {
t.Fatalf("零折扣配置被改写: %q", got)
}
// 显式折扣上限。
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 20, 50)
if !strings.Contains(got, "最多优惠 20% 或 50 元") {
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 20, 50, 4, 2)
if !strings.Contains(got, "最多优惠 20%") || !strings.Contains(got, "最多优惠 50 元") {
t.Fatalf("显式折扣上限: %q", got)
}
}
func TestMinimumAllowedPriceAndUnsafeOffer(t *testing.T) {
if got := minimumAllowedPrice(100, 10, 20, true); got != 90 {
t.Fatalf("minimum=%v want 90", got)
}
if got := minimumAllowedPrice(100, 0, 20, true); got != 100 {
t.Fatalf("zero percent minimum=%v want 100", got)
}
if _, unsafe := unsafeOfferedPrice("最低可以 89 元", 90); !unsafe {
t.Fatal("低于最低价的报价应被拦截")
}
if _, unsafe := unsafeOfferedPrice("最低可以 90 元", 90); unsafe {
t.Fatal("边界报价应允许")
}
}
// newAIStore 构造一个带 admin + cookie 的测试 store,供 AIReplier 使用。
func newAIStore(t *testing.T) (*db.Store, func()) {
t.Helper()
@@ -127,6 +144,10 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) {
if res != nil {
t.Fatalf("失败时不应返回结果: %+v", res)
}
history, historyErr := s.AIReply.ConversationHistory(ctx, "cid", "chat1", "item1", 10)
if historyErr != nil || len(history) != 0 {
t.Fatalf("上游失败不应写入半轮历史: history=%+v err=%v", history, historyErr)
}
}
// TestAIReply_EmptyChoicesReturnsNil 成功响应但无 choices → nil(不报错)。
@@ -210,9 +231,47 @@ func TestAIReplierItemInfo(t *testing.T) {
}
// 插入商品。
s.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_price, item_detail) VALUES ('cid','item1','会员卡','9.90','月卡服务')`)
s.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_price, item_description, item_detail) VALUES ('cid','item1','会员卡','9.90','用户编辑描述','原始详情')`)
title, price, desc = a.itemInfo(ctx, "item1")
if title != "会员卡" || price != 9.9 || desc != "月卡服务" {
if title != "会员卡" || price != 9.9 || desc != "用户编辑描述" {
t.Fatalf("真实商品: title=%q price=%v desc=%q", title, price, desc)
}
}
func TestAIReplyTracksBargainRoundsAndBlocksUnsafePrice(t *testing.T) {
s, cleanup := newAIStore(t)
defer cleanup()
ctx := context.Background()
srv := mockOpenAIServer(t, 0, "可以,80 元成交")
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings
(cookie_id,ai_enabled,max_discount_percent,max_discount_amount,max_bargain_rounds,custom_prompts)
VALUES ('cid',1,10,20,1,'')`)
s.DB.ExecContext(ctx, `INSERT INTO item_info
(cookie_id,item_id,item_title,item_price,item_description) VALUES ('cid','item1','商品','100','描述')`)
s.Settings.Set(ctx, "ai_api_key", "sk-test")
s.Settings.Set(ctx, "ai_api_url", srv.URL)
a := NewAIReplier("cid", s, nil)
first, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
if err != nil {
t.Fatal(err)
}
if first == nil || !strings.Contains(first.Text, "90.00 元") {
t.Fatalf("越界报价应替换成安全价格: %+v", first)
}
second, err := a.Reply(ctx, chatMsg("再便宜一点", "item1", "chat1"))
if err != nil {
t.Fatal(err)
}
if second == nil || !strings.Contains(second.Text, "已经是最低价") {
t.Fatalf("超过最大轮次应拒绝继续降价: %+v", second)
}
count, err := s.AIReply.CurrentBargainCount(ctx, "cid", "chat1", "item1")
if err != nil || count != 2 {
t.Fatalf("bargain count=%d err=%v want 2", count, err)
}
history, err := s.AIReply.ConversationHistory(ctx, "cid", "chat1", "item1", 10)
if err != nil || len(history) != 4 {
t.Fatalf("history len=%d err=%v", len(history), err)
}
}
+19 -4
View File
@@ -13,6 +13,10 @@ import (
// dispatch 是 ws.ReceiveLoop 的回调,对每条解密后的消息做:
// 标记消息接收时间 → 提取消息 ID 去重 → 信号量限并发 → 分类(聊天/系统)→ 防抖投递。
func (a *Account) dispatch(decrypted map[string]any) {
ctx, ok := a.beginTask()
if !ok {
return
}
a.mu.Lock()
a.lastMsgReceived = time.Now()
a.mu.Unlock()
@@ -21,22 +25,28 @@ func (a *Account) dispatch(decrypted map[string]any) {
select {
case a.sem <- struct{}{}:
default:
a.taskWG.Done()
a.logger.Warn("消息处理并发达上限,丢弃消息", "limit", MessageSemaphoreSize)
return
}
go func() {
defer a.taskWG.Done()
defer func() { <-a.sem }()
a.handleMessage(decrypted)
a.handleMessageContext(ctx, decrypted)
}()
}
// handleMessage 分类并投递消息。
func (a *Account) handleMessage(decrypted map[string]any) {
a.handleMessageContext(context.Background(), decrypted)
}
func (a *Account) handleMessageContext(ctx context.Context, decrypted map[string]any) {
// 第一优先级:系统卡片和平台通知进入自动化中心。
// 这里不判断具体业务,只做“平台事件”事实解析;系统消息永远不进入 AI 回复范围。
if task := automation.ExtractTaskFromWS(a.CookieID, a.currentCookieStr(), decrypted); task != nil {
if a.handler != nil {
if err := a.handler.HandleSystemEvent(context.Background(), *task); err != nil {
if err := a.handler.HandleSystemEvent(ctx, *task); err != nil {
a.logger.Error("处理系统自动化事件失败", "err", err, "trigger", task.TriggerType)
}
}
@@ -137,14 +147,19 @@ func (a *Account) scheduleDebouncedReply(chat ChatMessage) {
delete(a.debounceTimers, chat.ChatID)
lastMsg := cur.lastMsg
a.debounceMu.Unlock()
ctx, ok := a.beginTask()
if !ok {
return
}
defer a.taskWG.Done()
if a.reply != nil {
if err := a.reply.Handle(context.Background(), lastMsg); err != nil {
if err := a.reply.Handle(ctx, lastMsg); err != nil {
a.logger.Error("处理自动回复失败", "err", err, "chat_id", chat.ChatID)
}
}
if a.handler != nil {
if err := a.handler.HandleChatMessage(context.Background(), lastMsg); err != nil {
if err := a.handler.HandleChatMessage(ctx, lastMsg); err != nil {
a.logger.Error("处理聊天消息失败", "err", err, "chat_id", chat.ChatID)
}
}
+51
View File
@@ -286,6 +286,57 @@ func TestScheduleDebouncedReply_StopClearsTimers(t *testing.T) {
}
}
type cancelAwareHandler struct {
started chan struct{}
canceled chan struct{}
}
func (h *cancelAwareHandler) HandleChatMessage(ctx context.Context, _ ChatMessage) error {
close(h.started)
<-ctx.Done()
close(h.canceled)
return ctx.Err()
}
func (h *cancelAwareHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
func (h *cancelAwareHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
func (h *cancelAwareHandler) OnAccountAlert(context.Context, string, string, string, string) {}
func TestStopCancelsInFlightReplyHandler(t *testing.T) {
handler := &cancelAwareHandler{started: make(chan struct{}), canceled: make(chan struct{})}
acc := New(Config{CookieID: "cid", CookieStr: "unb=1", Handler: handler})
acc.reply = nil
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
acc.mu.Lock()
acc.stopFn = cancel
acc.mu.Unlock()
acc.taskMu.Lock()
acc.runtimeCtx = ctx
acc.taskMu.Unlock()
acc.scheduleDebouncedReply(ChatMessage{ChatID: "cancel-chat", SenderUserID: "buyer", Text: "hi"})
select {
case <-handler.started:
case <-time.After(MessageDebounceDelay + time.Second):
t.Fatal("handler did not start")
}
done := make(chan struct{})
go func() {
acc.Stop()
close(done)
}()
select {
case <-handler.canceled:
case <-time.After(time.Second):
t.Fatal("in-flight handler context was not canceled")
}
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("Stop did not wait for handler exit")
}
}
// TestCleanupDedupLocked_ExpiredRemoved 过期消息 ID 被清理。
func TestCleanupDedupLocked_ExpiredRemoved(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
+53 -23
View File
@@ -8,6 +8,7 @@ package engine
import (
"context"
"fmt"
"log/slog"
"strings"
@@ -16,10 +17,11 @@ import (
// ReplyResult 回复结果。
type ReplyResult struct {
Text string // 文本回复(可空)
ImageURL string // 图片回复(可空)
Source string // 回复来源:API/关键词/AI/默认
Skip bool // true 表示匹配到空回复,不发送任何内容
Text string // 文本回复(可空)
ImageURL string // 图片回复(可空)
Source string // 回复来源:API/关键词/AI/默认
Skip bool // true 表示匹配到空回复,不发送任何内容
ReplyOnce bool // 仅默认回复使用,发送状态由 Handle 持久化
}
// APIReplier 外部 API 回复(优先级1)。返回 nil 表示无回复。
@@ -71,23 +73,64 @@ func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error {
if res == nil || res.Skip {
return nil
}
// 发送:图片优先,文本随后。
// 发送:图片优先,文本随后。reply_once 使用持久化分段状态,失败时只重试
// 尚未成功的部分。
if r.sender == nil {
return nil
}
if res.ImageURL != "" {
if err := r.sender.SendImage(ctx, m.ChatID, m.SenderUserID, res.ImageURL, 0); err != nil {
r.logger.Error("发送回复图片失败", "err", err)
record := db.DefaultReplyRecord{}
if res.ReplyOnce && m.ChatID != "" {
var claimed bool
var err error
record, claimed, err = r.store.DefaultReps.ClaimRecord(ctx, r.cookieID, m.ChatID, res.Text != "", res.ImageURL != "")
if err != nil {
return fmt.Errorf("领取默认回复发送任务: %w", err)
}
if !claimed {
return nil
}
}
if res.Text != "" {
if res.ImageURL != "" && !record.ImageSent {
if err := r.sender.SendImage(ctx, m.ChatID, m.SenderUserID, res.ImageURL, 0); err != nil {
r.logger.Error("发送回复图片失败", "err", err)
r.markReplyFailure(ctx, res, m, err)
return err
}
if res.ReplyOnce && m.ChatID != "" {
if err := r.store.DefaultReps.MarkPartSent(ctx, r.cookieID, m.ChatID, "image"); err != nil {
r.markReplyFailure(ctx, res, m, err)
return err
}
}
}
if res.Text != "" && !record.TextSent {
if err := r.sender.SendText(ctx, m.ChatID, m.SenderUserID, res.Text); err != nil {
r.logger.Error("发送回复文本失败", "err", err)
r.markReplyFailure(ctx, res, m, err)
return err
}
if res.ReplyOnce && m.ChatID != "" {
if err := r.store.DefaultReps.MarkPartSent(ctx, r.cookieID, m.ChatID, "text"); err != nil {
r.markReplyFailure(ctx, res, m, err)
return err
}
}
}
if res.ReplyOnce && m.ChatID != "" {
if err := r.store.DefaultReps.MarkRecordSent(ctx, r.cookieID, m.ChatID); err != nil {
r.markReplyFailure(ctx, res, m, err)
return err
}
}
return nil
}
func (r *ReplyService) markReplyFailure(ctx context.Context, res *ReplyResult, m ChatMessage, sendErr error) {
if res.ReplyOnce && m.ChatID != "" {
_ = r.store.DefaultReps.MarkRecordFailed(ctx, r.cookieID, m.ChatID, sendErr.Error())
}
}
// resolve 按优先级确定回复内容(不发送)。
func (r *ReplyService) resolve(ctx context.Context, m ChatMessage) *ReplyResult {
// 优先级1:API 回复。
@@ -170,24 +213,11 @@ func (r *ReplyService) defaultReply(ctx context.Context, m ChatMessage) *ReplyRe
if err != nil || dr == nil || !dr.Enabled {
return nil
}
// reply_once:已回复过则跳过。
if dr.ReplyOnce && m.ChatID != "" {
if r.store.DefaultReps.HasRecord(ctx, r.cookieID, m.ChatID) {
r.logger.Info("chat_id 已用过默认回复,跳过(reply_once)", "chat_id", m.ChatID)
return nil
}
}
// 文字和图片都为空 → 空回复标记。
if strings.TrimSpace(dr.ReplyContent) == "" && strings.TrimSpace(dr.ReplyImageURL) == "" {
return &ReplyResult{Skip: true, Source: "默认"}
}
// 记录已回复。
if dr.ReplyOnce && m.ChatID != "" {
if err := r.store.DefaultReps.AddRecord(ctx, r.cookieID, m.ChatID); err != nil {
r.logger.Error("记录默认回复失败", "cookie_id", r.cookieID, "chat_id", m.ChatID, "err", err)
}
}
res := &ReplyResult{Source: "默认"}
res := &ReplyResult{Source: "默认", ReplyOnce: dr.ReplyOnce}
if strings.TrimSpace(dr.ReplyContent) != "" {
res.Text = formatReply(dr.ReplyContent, m)
}
+51 -7
View File
@@ -34,8 +34,10 @@ func (f *fakeAIReplier) Reply(_ context.Context, _ ChatMessage) (*ReplyResult, e
// recordingSender 记录发送的文本/图片,用于断言回复投递。
type recordingSender struct {
texts []textSent
images []imageSent
texts []textSent
images []imageSent
textErr error
imageErr error
}
type textSent struct {
@@ -48,15 +50,57 @@ type imageSent struct {
}
func (r *recordingSender) SendText(_ context.Context, chatID, toUserID, text string) error {
if r.textErr != nil {
return r.textErr
}
r.texts = append(r.texts, textSent{chatID, toUserID, text})
return nil
}
func (r *recordingSender) SendImage(_ context.Context, chatID, toUserID, url string, cardID int64) error {
if r.imageErr != nil {
return r.imageErr
}
r.images = append(r.images, imageSent{chatID, toUserID, url, cardID})
return nil
}
func TestReplyOnceRetriesOnlyFailedParts(t *testing.T) {
s, cleanup := newReplyStore(t)
defer cleanup()
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies
(cookie_id,enabled,reply_content,reply_image_url,reply_once)
VALUES ('cid',1,'文字','http://img/retry.png',1)`)
textFailure := errors.New("text failed")
firstSender := &recordingSender{textErr: textFailure}
service := NewReplyService("cid", s, firstSender, nil, nil, nil)
if err := service.Handle(ctx, chatMsg("在吗", "", "chat-retry")); !errors.Is(err, textFailure) {
t.Fatalf("first error=%v want text failure", err)
}
if len(firstSender.images) != 1 || len(firstSender.texts) != 0 {
t.Fatalf("first delivery images=%+v texts=%+v", firstSender.images, firstSender.texts)
}
record, err := s.DefaultReps.Record(ctx, "cid", "chat-retry")
if err != nil || record.Status != "failed" || !record.ImageSent || record.TextSent {
t.Fatalf("failed record=%+v err=%v", record, err)
}
secondSender := &recordingSender{}
service = NewReplyService("cid", s, secondSender, nil, nil, nil)
if err := service.Handle(ctx, chatMsg("再问", "", "chat-retry")); err != nil {
t.Fatal(err)
}
if len(secondSender.images) != 0 || len(secondSender.texts) != 1 {
t.Fatalf("retry should send text only: images=%+v texts=%+v", secondSender.images, secondSender.texts)
}
record, err = s.DefaultReps.Record(ctx, "cid", "chat-retry")
if err != nil || record.Status != "sent" || !record.ImageSent || !record.TextSent {
t.Fatalf("sent record=%+v err=%v", record, err)
}
}
// TestReply_APIPriorityAndError API 回复命中时优先级最高;API 报错时降级到关键词。
func TestReply_APIPriorityAndError(t *testing.T) {
s, cleanup := newReplyStore(t)
@@ -160,10 +204,10 @@ func TestReply_HandleSendsImageThenText(t *testing.T) {
// TestParseMessageIDFromJSON bizTag/extJson 中提取 messageId。
func TestParseMessageIDFromJSON(t *testing.T) {
cases := map[string]string{
`{"messageId":"abc123"}`: "abc123",
`{"sourceId":"x"}`: "",
`not json`: "",
`{}`: "",
`{"messageId":"abc123"}`: "abc123",
`{"sourceId":"x"}`: "",
`not json`: "",
`{}`: "",
}
for in, want := range cases {
if got := parseMessageIDFromJSON(in); got != want {
@@ -177,7 +221,7 @@ func TestExtractMessageID(t *testing.T) {
if got := extractMessageID(map[string]any{
"1": map[string]any{
"10": map[string]any{
"bizTag": `{"messageId":"biz-id"}`,
"bizTag": `{"messageId":"biz-id"}`,
"extJson": `{"messageId":"ext-id"}`,
},
},
+16 -18
View File
@@ -103,21 +103,19 @@ func TestDefaultReply_ReplyOnce(t *testing.T) {
ctx := context.Background()
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认问候',1)`)
r := NewReplyService("cid", s, nil, nil, nil, nil)
// 首次:应回复。
res1 := r.resolve(ctx, chatMsg("在吗", "item1", "chatX"))
if res1 == nil || res1.Text != "默认问候" {
t.Fatalf("首次应回复,got %+v", res1)
sender := &recordingSender{}
r := NewReplyService("cid", s, sender, nil, nil, nil)
if err := r.Handle(ctx, chatMsg("在吗", "item1", "chatX")); err != nil {
t.Fatal(err)
}
// 第二次同 chat_id:reply_once 应跳过。
res2 := r.resolve(ctx, chatMsg("还在吗", "item1", "chatX"))
if res2 != nil {
t.Fatalf("reply_once 应跳过第二次,got %+v", res2)
if err := r.Handle(ctx, chatMsg("还在吗", "item1", "chatX")); err != nil {
t.Fatal(err)
}
// 不同 chat_id:应回复。
res3 := r.resolve(ctx, chatMsg("在吗", "item1", "chatY"))
if res3 == nil || res3.Text != "默认问候" {
t.Fatalf("不同 chat_id 应回复,got %+v", res3)
if err := r.Handle(ctx, chatMsg("在吗", "item1", "chatY")); err != nil {
t.Fatal(err)
}
if len(sender.texts) != 2 || sender.texts[0].text != "默认问候" || sender.texts[1].chatID != "chatY" {
t.Fatalf("reply_once 发送记录异常: %+v", sender.texts)
}
}
@@ -155,11 +153,11 @@ func TestFormatReply(t *testing.T) {
// TestParsePrice 价格解析。
func TestParsePrice(t *testing.T) {
cases := map[string]float64{
"¥99.5": 99.5,
"100元": 100,
"": 0,
"abc": 0,
"12.34": 12.34,
"¥99.5": 99.5,
"100元": 100,
"": 0,
"abc": 0,
"12.34": 12.34,
}
for in, want := range cases {
if got := parsePrice(in); got != want {
+112 -14
View File
@@ -14,7 +14,9 @@ import (
"io"
"log/slog"
"net/http"
"net/mail"
"net/smtp"
"net/url"
"strconv"
"strings"
"time"
@@ -348,7 +350,15 @@ func (n *Notifier) sendDingTalk(cfg map[string]any, message string) error {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(stringToSign))
sign := base64.StdEncoding.EncodeToString(h.Sum(nil))
webhook += "&timestamp=" + ts + "&sign=" + sign
parsed, err := url.Parse(webhook)
if err != nil {
return fmt.Errorf("钉钉 webhook 地址无效: %w", err)
}
query := parsed.Query()
query.Set("timestamp", ts)
query.Set("sign", sign)
parsed.RawQuery = query.Encode()
webhook = parsed.String()
}
payload := map[string]any{
"msgtype": "markdown",
@@ -463,11 +473,10 @@ func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
if botToken == "" || chatID == "" {
return fmt.Errorf("telegram bot_token/chat_id 不完整")
}
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
return n.postJSON(url, map[string]any{
"chat_id": chatID,
"text": message,
"parse_mode": "HTML",
endpoint := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)
return n.postJSON(endpoint, map[string]any{
"chat_id": chatID,
"text": message,
})
}
@@ -478,26 +487,57 @@ func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
port := n.configOrSetting(ctx, cfg, "smtp_port", "587")
user := n.configOrSetting(ctx, cfg, "smtp_user", "")
pass := n.configOrSetting(ctx, cfg, "smtp_password", "")
from := n.configOrSetting(ctx, cfg, "smtp_from", "")
fromAddress := n.configOrSetting(ctx, cfg, "smtp_from_address", "")
fromName := n.configOrSetting(ctx, cfg, "smtp_from_name", "")
legacyFrom := n.configOrSetting(ctx, cfg, "smtp_from", "")
to := strOr(cfg, "to_email", strOr(cfg, "email", ""))
if server == "" || user == "" || to == "" {
return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱")
}
if from == "" {
from = user
if legacyFrom != "" {
if parsed, err := mail.ParseAddress(legacyFrom); err == nil && strings.Contains(parsed.Address, "@") {
if fromAddress == "" {
fromAddress = parsed.Address
}
if fromName == "" {
fromName = parsed.Name
}
} else if fromName == "" {
fromName = legacyFrom
}
}
if fromAddress == "" {
fromAddress = user
}
from, err := mail.ParseAddress(fromAddress)
if err != nil || !strings.Contains(from.Address, "@") {
return fmt.Errorf("发件邮箱地址无效")
}
recipient, err := mail.ParseAddress(to)
if err != nil || !strings.Contains(recipient.Address, "@") {
return fmt.Errorf("收件邮箱地址无效")
}
from.Name = fromName
fromHeader := from.Address
if from.Name != "" {
fromHeader = from.String()
}
toHeader := recipient.Address
if recipient.Name != "" {
toHeader = recipient.String()
}
addr := server + ":" + port
auth := smtp.PlainAuth("", user, pass, server)
msg := strings.Join([]string{
"From: " + from,
"To: " + to,
"From: " + fromHeader,
"To: " + toHeader,
"Subject: =?UTF-8?B?" + base64.StdEncoding.EncodeToString([]byte("闲鱼自动发货通知")) + "?=",
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"",
message,
}, "\r\n")
return smtp.SendMail(addr, auth, from, []string{to}, []byte(msg))
return smtp.SendMail(addr, auth, from.Address, []string{recipient.Address}, []byte(msg))
}
func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
@@ -518,20 +558,78 @@ func (n *Notifier) postJSON(url string, payload any) error {
if err != nil {
return err
}
resp, err := n.httpc.Post(url, "application/json", bytes.NewReader(body))
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := n.httpc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return err
}
if resp.StatusCode >= 300 {
return fmt.Errorf("状态码 %d", resp.StatusCode)
}
if err := notificationBusinessError(responseBody); err != nil {
return err
}
return nil
}
func notificationBusinessError(body []byte) error {
if len(bytes.TrimSpace(body)) == 0 {
return nil
}
var payload map[string]any
if json.Unmarshal(body, &payload) != nil {
return nil
}
message := strings.TrimSpace(firstMapString(payload, "errmsg", "msg", "message", "description"))
if code, ok := mapNumber(payload, "errcode"); ok && code != 0 {
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
}
if code, ok := mapNumber(payload, "StatusCode"); ok && code != 0 {
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
}
if code, ok := mapNumber(payload, "code"); ok && code != 0 && code != 200 {
return fmt.Errorf("通知渠道返回错误 %.0f: %s", code, message)
}
if okValue, exists := payload["ok"].(bool); exists && !okValue {
return fmt.Errorf("通知渠道返回失败: %s", message)
}
return nil
}
func mapNumber(payload map[string]any, key string) (float64, bool) {
value, ok := payload[key]
if !ok {
return 0, false
}
switch typed := value.(type) {
case float64:
return typed, true
case string:
number, err := strconv.ParseFloat(typed, 64)
return number, err == nil
default:
return 0, false
}
}
func firstMapString(payload map[string]any, keys ...string) string {
for _, key := range keys {
if value, ok := payload[key].(string); ok && value != "" {
return value
}
}
return "未知错误"
}
// strOr 从 map 取字符串,缺失返回 fallback。
func strOr(m map[string]any, key, fallback string) string {
if v, ok := m[key]; ok {
+33 -1
View File
@@ -304,9 +304,24 @@ func TestSendTelegram_Success(t *testing.T) {
if gotPath != wantPath {
t.Errorf("path=%s want %s", gotPath, wantPath)
}
if got["chat_id"] != "123" || got["text"] != "TG消息" || got["parse_mode"] != "HTML" {
if got["chat_id"] != "123" || got["text"] != "TG消息" {
t.Errorf("telegram payload: %v", got)
}
if _, ok := got["parse_mode"]; ok {
t.Errorf("动态文本不应启用未转义的 HTML 模式: %v", got)
}
}
func TestPostJSONRejectsBusinessErrors(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"errcode":310000,"errmsg":"signature invalid"}`))
}))
defer srv.Close()
n := New("cid", nil, nil)
if err := n.sendDingTalk(map[string]any{"webhook_url": srv.URL}, "x"); err == nil || !strings.Contains(err.Error(), "signature invalid") {
t.Fatalf("business error=%v", err)
}
}
func TestSendTelegram_MissingConfig(t *testing.T) {
@@ -505,6 +520,23 @@ func TestSendEmail_DefaultFrom(t *testing.T) {
}
}
func TestSendEmail_SeparatesDisplayNameAndEnvelopeAddress(t *testing.T) {
addr, received := fakeSMTPServer(t)
host, port, _ := strings.Cut(addr, ":")
n := New("cid", nil, nil)
cfg := map[string]any{
"smtp_server": host, "smtp_port": port, "smtp_user": "[email protected]", "smtp_password": "pw",
"smtp_from_name": "闲鱼自动回复系统", "smtp_from_address": "[email protected]", "to_email": "[email protected]",
}
if err := n.sendEmail(cfg, "x"); err != nil {
t.Fatal(err)
}
body := received.String()
if !strings.Contains(body, "[email protected]") || !strings.Contains(body, "From: =?utf-8?") {
t.Fatalf("smtp envelope/header mismatch: %s", body)
}
}
func TestSendEmail_UsesSystemSMTPFallback(t *testing.T) {
addr, received := fakeSMTPServer(t)
host, port, _ := strings.Cut(addr, ":")
+51
View File
@@ -11,10 +11,61 @@ import (
// mountAnalyticsReal 订单分析端点(仪表盘 BI 报表用)。
func (s *Server) mountAnalyticsReal(r chi.Router) {
r.Get("/dashboard/stats", s.dashboardStats)
r.Get("/analytics/orders", s.orderAnalytics)
r.Get("/analytics/orders/valid", s.validOrders)
}
// dashboardStats 返回当前登录用户的数据概览。管理员全局统计仍由 /admin/stats 提供,
// 避免普通用户访问管理员接口,也避免把全局资源数和用户自己的订单收益混在一起。
func (s *Server) dashboardStats(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未登录")
return
}
counts := map[string]int64{
"total_cookies": 0,
"active_cookies": 0,
"total_cards": 0,
"total_keywords": 0,
"total_orders": 0,
}
queries := []struct {
key string
query string
}{
{"total_cookies", `SELECT COUNT(*) FROM cookies WHERE user_id=?`},
{"total_cards", `SELECT COUNT(*) FROM cards WHERE user_id=?`},
{"total_keywords", `SELECT COUNT(*) FROM keywords k WHERE EXISTS (
SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`},
{"total_orders", `SELECT COUNT(*) FROM orders o WHERE EXISTS (
SELECT 1 FROM cookies c WHERE c.id=o.cookie_id AND c.user_id=?)`},
}
for _, item := range queries {
var count int64
if err := s.Store.DB.QueryRowContext(r.Context(), item.query, sess.UserID).Scan(&count); err != nil {
writeErr(w, http.StatusInternalServerError, "统计数据失败")
return
}
counts[item.key] = count
}
var activeCookies int64
if err := s.Store.DB.QueryRowContext(r.Context(), `
SELECT COUNT(*) FROM cookies c
WHERE c.user_id=?
AND NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0)
`, sess.UserID).Scan(&activeCookies); err != nil {
writeErr(w, http.StatusInternalServerError, "统计活跃账号失败")
return
}
counts["active_cookies"] = activeCookies
writeJSON(w, http.StatusOK, counts)
}
// 有效订单状态只统计以下几种。
var validOrderStatuses = []string{"pending_ship", "shipped", "completed"}
@@ -69,3 +69,60 @@ func TestValidOrdersMatchesAnalyticsScope(t *testing.T) {
t.Fatalf("状态字段异常: %+v", order)
}
}
func TestDashboardStatsAreAvailableAndScopedToCurrentUser(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "member", "[email protected]", "pw"); err != nil || !ok {
t.Fatalf("create member: ok=%v err=%v", ok, err)
}
member, err := store.Users.GetByUsername(ctx, "member")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(ctx, "member-acc", "unb=456", member.ID); err != nil {
t.Fatal(err)
}
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,user_id) VALUES ('member-card','text',?)`, member.ID)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply) VALUES ('member-acc','hi','hello')`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,cookie_id,order_status) VALUES ('member-order','member-acc','completed')`)
// 管理员资源不能进入 member 的统计。
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,user_id) VALUES ('admin-card','text',1)`)
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,cookie_id,order_status) VALUES ('admin-order','acc1','completed')`)
h := srv.Router()
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"member","password":"pw"}`))
loginRec := httptest.NewRecorder()
h.ServeHTTP(loginRec, loginReq)
if loginRec.Code != http.StatusOK || len(loginRec.Result().Cookies()) == 0 {
t.Fatalf("login status=%d body=%s", loginRec.Code, loginRec.Body.String())
}
req := httptest.NewRequest(http.MethodGet, "/dashboard/stats", nil)
req.AddCookie(loginRec.Result().Cookies()[0])
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var stats map[string]int64
if err := json.Unmarshal(rec.Body.Bytes(), &stats); err != nil {
t.Fatal(err)
}
for _, key := range []string{"total_cookies", "active_cookies", "total_cards", "total_keywords", "total_orders"} {
if stats[key] != 1 {
t.Fatalf("%s=%d want 1; stats=%+v", key, stats[key], stats)
}
}
adminReq := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
adminReq.AddCookie(loginRec.Result().Cookies()[0])
adminRec := httptest.NewRecorder()
h.ServeHTTP(adminRec, adminReq)
if adminRec.Code != http.StatusForbidden {
t.Fatalf("member admin stats status=%d want 403", adminRec.Code)
}
}
+29 -8
View File
@@ -127,6 +127,27 @@ func TestAutomationRuleBadActionType(t *testing.T) {
}
}
func TestAutomationRuleRejectsAPICard(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
cardID, err := store.Cards.Create(context.Background(), &db.CardFull{
Name: "旧 API 卡密", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: 1,
})
if err != nil {
t.Fatal(err)
}
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "API 卡密暂不支持") {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
}
// TestAutomationRuleSendCardMissingCardID send_card 缺 card_id 400。
func TestAutomationRuleSendCardMissingCardID(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -249,7 +270,7 @@ func TestDefaultAutomationRuleName(t *testing.T) {
automation.TriggerOrderPaid: "付款后自动发货",
automation.TriggerBuyerReviewed: "评价后发送赠品",
automation.TriggerReviewMissingTimeout: "超时未评价求评价",
"bogus": "自动化规则",
"bogus": "自动化规则",
}
for trigger, want := range cases {
got := defaultAutomationRuleName(trigger, "")
@@ -265,13 +286,13 @@ func TestDefaultAutomationRuleName(t *testing.T) {
// TestIsJSONObject isJSONObject 表驱动。
func TestIsJSONObject(t *testing.T) {
cases := map[string]bool{
`{}`: true,
`{"a":1}`: true,
`null`: true, // null 能 unmarshal 为 map(nil),函数判定为对象
`[]`: false,
`"str"`: false,
`invalid`: false,
``: false,
`{}`: true,
`{"a":1}`: true,
`null`: true, // null 能 unmarshal 为 map(nil),函数判定为对象
`[]`: false,
`"str"`: false,
`invalid`: false,
``: false,
}
for in, want := range cases {
if got := isJSONObject(in); got != want {
+8 -1
View File
@@ -181,9 +181,13 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
if act.CardID <= 0 {
return db.AutomationRuleInput{}, errStr("发送卡密动作必须选择卡密组")
}
if !s.cardOwnedByUser(r.Context(), userID, act.CardID) {
card, cardErr := s.Store.Cards.Get(r.Context(), act.CardID)
if cardErr != nil || card.UserID != userID {
return db.AutomationRuleInput{}, errStr("卡密组不存在或不属于当前用户")
}
if card.Type == "api" {
return db.AutomationRuleInput{}, errStr("API 卡密暂不支持自动发货,请选择文本、批量数据或图片卡密")
}
case automation.ActionSendText:
if strings.TrimSpace(act.MessageTemplate) == "" {
return db.AutomationRuleInput{}, errStr("发送文本动作必须填写文案")
@@ -194,6 +198,9 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
if act.DeliveryCount <= 0 {
act.DeliveryCount = 1
}
if act.DelaySeconds < 0 || act.DelaySeconds > 86400 {
return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 86400 秒之间")
}
if act.ConfigJSON == "" {
act.ConfigJSON = "{}"
}
+14 -7
View File
@@ -76,25 +76,34 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
continue
}
switch cardType {
case "text", "data", "image", "api":
case "text", "data", "image":
case "api":
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "API 卡密暂不支持自动发货,不能新建"})
failed++
continue
default:
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "类型必须为 text/data/image/api"})
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "类型必须为 text/data/image"})
failed++
continue
}
// content 按类型映射;api 类型允许 content 为空(用 description 等另行说明时)
if cardType != "api" && strings.TrimSpace(content) == "" {
if strings.TrimSpace(content) == "" {
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "缺少内容"})
failed++
continue
}
delaySeconds := atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0)
if delaySeconds < 0 || delaySeconds > 86400 {
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 86400 秒之间"})
failed++
continue
}
cf := &db.CardFull{
Name: name,
Type: cardType,
Description: firstImportString(m, "description", "描述"),
Enabled: true,
DelaySeconds: atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0),
DelaySeconds: delaySeconds,
IsMultiSpec: parseLooseBool(firstImportString(m, "is_multi_spec", "多规格")),
SpecName: firstImportString(m, "spec_name", "规格名"),
SpecValue: firstImportString(m, "spec_value", "规格值"),
@@ -110,8 +119,6 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
cf.DataContent = content
case "image":
cf.ImageURL = content
case "api":
cf.APIConfig = content
}
id, err := s.Store.Cards.Create(r.Context(), cf)
+16
View File
@@ -53,6 +53,10 @@ func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
return
}
cf.UserID = sess.UserID
if cf.Type == "api" {
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建")
return
}
id, err := s.Store.Cards.Create(r.Context(), cf)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建失败")
@@ -76,6 +80,10 @@ func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if cf.Type == "api" && existing.Type != "api" {
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能转换为该类型")
return
}
cf.ID = id
cf.UserID = existing.UserID
if err := s.Store.Cards.Update(r.Context(), cf); err != nil {
@@ -122,6 +130,14 @@ func decodeCard(r *http.Request) (*db.CardFull, error) {
if req.Name == "" || req.Type == "" {
return nil, errStr("名称和类型不能为空")
}
switch req.Type {
case "text", "data", "image", "api":
default:
return nil, errStr("类型必须为 text、data、image 或 api")
}
if req.DelaySeconds < 0 || req.DelaySeconds > 86400 {
return nil, errStr("延时发货必须在 0 到 86400 秒之间")
}
return &db.CardFull{
Name: req.Name, Type: req.Type, APIConfig: req.APIConfig, TextContent: req.TextContent,
DataContent: req.DataContent, ImageURL: req.ImageURL, Description: req.Description,
+21
View File
@@ -236,6 +236,27 @@ func TestAIReplySettings(t *testing.T) {
}
}
func TestAIReplySettingsRejectInvalidBargainLimits(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
for _, body := range []string{
`{"ai_enabled":true,"max_discount_percent":101,"max_discount_amount":1,"max_bargain_rounds":1}`,
`{"ai_enabled":true,"max_discount_percent":1,"max_discount_amount":-1,"max_bargain_rounds":1}`,
`{"ai_enabled":true,"max_discount_percent":1,"max_discount_amount":1,"max_bargain_rounds":0}`,
} {
req := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("body=%s status=%d want 400", body, rec.Code)
}
}
}
func TestParseOpenAIModels(t *testing.T) {
models, err := parseOpenAIModels([]byte(`{"data":[{"id":"qwen-plus"},{"id":"qwen-max"},{"name":"fallback-name"}]}`))
if err != nil {
+21
View File
@@ -69,6 +69,27 @@ func TestCardEndpointsErrorBranches(t *testing.T) {
}
}
func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
for _, body := range []string{
`{"name":"API 卡密","type":"api","enabled":true}`,
`{"name":"非法类型","type":"unknown","enabled":true}`,
`{"name":"延时错误","type":"text","text_content":"x","delay_seconds":86401,"enabled":true}`,
} {
req := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("body=%s status=%d want 400", body, rec.Code)
}
}
}
// TestProtectedEndpointsRequireAuth 受保护端点未登录应 401。
func TestProtectedEndpointsRequireAuth(t *testing.T) {
srv, _, cleanup := newTestServer(t)
+4 -1
View File
@@ -56,7 +56,7 @@ func TestBatchCreateCards(t *testing.T) {
h := srv.Router()
cookie := loginHelper(t, h)
csv := "name,type,content\n卡A,text,内容A\n卡B,text,内容B\n"
csv := "name,type,content,delay_seconds\n卡A,text,内容A,0\n卡B,text,内容B,5\nAPI卡,api,https://example.com,0\n延时异常,text,内容,-1\n"
body := &bytes.Buffer{}
mw := multipart.NewWriter(body)
fw, _ := mw.CreateFormFile("file", "cards.csv")
@@ -76,6 +76,9 @@ func TestBatchCreateCards(t *testing.T) {
if res["created"].(float64) != 2 {
t.Fatalf("应创建 2 个,got %+v", res)
}
if res["failed"].(float64) != 2 {
t.Fatalf("API 卡和非法延时应拒绝,got %+v", res)
}
// 缺文件 → 400。
req2 := httptest.NewRequest(http.MethodPost, "/cards/batch", &bytes.Buffer{})
+39 -4
View File
@@ -100,6 +100,25 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
})
return
}
var req struct {
TargetAccountID string `json:"target_account_id"`
ConfirmMismatch bool `json:"confirm_mismatch"`
}
if r.Body != nil && r.ContentLength != 0 {
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
}
req.TargetAccountID = strings.TrimSpace(req.TargetAccountID)
if req.TargetAccountID != "" && req.TargetAccountID != unb && !req.ConfirmMismatch {
writeJSON(w, http.StatusOK, map[string]any{
"success": false, "requires_confirmation": true,
"scanned_account_id": unb,
"message": "扫码账号与待重新授权账号不一致,需要确认后才能覆盖",
})
return
}
resp := map[string]any{
"success": true,
"cookies": cookies,
@@ -107,11 +126,11 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
}
sess := auth.SessionFromContext(r.Context())
if sess != nil {
persisted, persistErr := s.persistQRLoginSuccess(r.Context(), sess.UserID, sessionID, map[string]any{
persisted, persistErr := s.persistQRLoginSuccessFor(r.Context(), sess.UserID, sessionID, map[string]any{
"status": "success",
"cookies": cookies,
"unb": unb,
})
}, req.TargetAccountID)
if persistErr != nil {
if s.Logger != nil {
s.Logger.Warn("保存扫码验证结果失败", "session_id", sessionID, "err", persistErr)
@@ -128,6 +147,10 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
}
func (s *Server) persistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any) (qrLoginPersistence, error) {
return s.persistQRLoginSuccessFor(ctx, userID, sessionID, result, "")
}
func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
s.qrMu.Lock()
defer s.qrMu.Unlock()
if s.qrPersisted == nil {
@@ -137,10 +160,22 @@ func (s *Server) persistQRLoginSuccess(ctx context.Context, userID int64, sessio
return persisted, nil
}
cookies := qrString(result, "cookies")
accountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
if cookies == "" || accountID == "" {
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
if cookies == "" || scannedAccountID == "" {
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
}
accountID := strings.TrimSpace(targetAccountID)
if accountID == "" {
accountID = scannedAccountID
} else {
target, err := s.Store.Cookies.GetDetails(ctx, accountID)
if err != nil {
return qrLoginPersistence{}, errors.New("待重新授权账号不存在")
}
if target.UserID != userID {
return qrLoginPersistence{}, errors.New("待重新授权账号不属于当前用户")
}
}
_, err := s.Store.Cookies.GetDetails(ctx, accountID)
isNew := errors.Is(err, db.ErrNotFound)
+46
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
@@ -193,6 +194,51 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
}
}
func TestCompleteQRVerificationRequiresConfirmationForDifferentTarget(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{
completeCookies: "unb=scanned-other; _m_h5_tk=qr-fresh;",
completeUNB: "scanned-other",
}
h := srv.Router()
cookie := loginHelper(t, h)
request := func(confirm bool) map[string]any {
body := fmt.Sprintf(`{"target_account_id":"acc1","confirm_mismatch":%t}`, confirm)
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/s-mismatch", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var result map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
first := request(false)
if first["requires_confirmation"] != true || first["success"] != false {
t.Fatalf("first response=%+v", first)
}
original, _ := store.Cookies.GetValue(context.Background(), "acc1")
if strings.Contains(original, "qr-fresh") {
t.Fatal("mismatched account must not be overwritten before confirmation")
}
second := request(true)
if second["success"] != true || second["account_id"] != "acc1" {
t.Fatalf("confirmed response=%+v", second)
}
updated, _ := store.Cookies.GetValue(context.Background(), "acc1")
if !strings.Contains(updated, "qr-fresh") {
t.Fatalf("target account was not updated: %q", updated)
}
}
// TestKeywordsListAndDelete 关键字列表与删除(覆盖 listKeywords / listKeywordsWithItemID / listKeywordsWithType)。
func TestKeywordsListAndDelete(t *testing.T) {
srv, _, cleanup := newTestServer(t)
+12
View File
@@ -166,6 +166,18 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
return
}
if req.MaxDiscountPercent < 0 || req.MaxDiscountPercent > 100 {
writeErr(w, http.StatusBadRequest, "最大折扣比例必须在 0 到 100 之间")
return
}
if req.MaxDiscountAmount < 0 {
writeErr(w, http.StatusBadRequest, "最大折扣金额不能小于 0")
return
}
if req.MaxBargainRounds < 1 || req.MaxBargainRounds > 10 {
writeErr(w, http.StatusBadRequest, "最大砍价轮次必须在 1 到 10 之间")
return
}
_, err := s.Store.DB.ExecContext(r.Context(),
`INSERT INTO ai_reply_settings
(cookie_id, ai_enabled, max_discount_percent, max_discount_amount,
@@ -343,4 +343,4 @@ import{r as s}from"./react-vendor-DZnRGM0-.js";/**
*
* 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:"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"}]],T0=e("zap",A1);export{E1 as $,H1 as A,S1 as B,G1 as C,J1 as D,X1 as E,t0 as F,W1 as G,y0 as H,o0 as I,a0 as J,h0 as K,n0 as L,v0 as M,O1 as N,T1 as O,x0 as P,w0 as Q,$0 as R,z0 as S,V0 as T,B0 as U,Z1 as V,d0 as W,R0 as X,L1 as Y,T0 as Z,Q1 as _,V1 as a,r0 as a0,U0 as a1,q0 as a2,_0 as a3,I1 as a4,c0 as a5,s0 as a6,b0 as a7,l0 as a8,D0 as a9,i0 as aa,C0 as b,j0 as c,p0 as d,A0 as e,M0 as f,k0 as g,E0 as h,U1 as i,P1 as j,R1 as k,K1 as l,g0 as m,u0 as n,L0 as o,Y1 as p,e0 as q,N0 as r,m0 as s,P0 as t,f0 as u,H0 as v,B1 as w,D1 as x,S0 as y,F1 as z};
*/const A1=[["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"}]],T0=e("zap",A1);export{E1 as $,H1 as A,S1 as B,G1 as C,J1 as D,X1 as E,t0 as F,y0 as G,a0 as H,o0 as I,W1 as J,h0 as K,n0 as L,v0 as M,O1 as N,T1 as O,x0 as P,w0 as Q,$0 as R,z0 as S,V0 as T,B0 as U,Z1 as V,d0 as W,R0 as X,L1 as Y,T0 as Z,Q1 as _,V1 as a,r0 as a0,U0 as a1,q0 as a2,_0 as a3,I1 as a4,c0 as a5,s0 as a6,b0 as a7,l0 as a8,D0 as a9,i0 as aa,C0 as b,j0 as c,p0 as d,R1 as e,A0 as f,M0 as g,k0 as h,E0 as i,U1 as j,P1 as k,K1 as l,g0 as m,u0 as n,L0 as o,Y1 as p,e0 as q,N0 as r,m0 as s,P0 as t,f0 as u,H0 as v,B1 as w,D1 as x,S0 as y,F1 as z};
@@ -1,19 +0,0 @@
import{j as e,r as d,b as he,c as bt,d as yt}from"./react-vendor-DZnRGM0-.js";import{L as ft,U as Ks,S as Gs,C as us,B as Xs,Z as hs,a as Be,b as ys,c as Zs,d as jt,A as ws,D as Nt,e as _s,P as Hs,f as Xe,E as et,T as vt,g as ke,Q as is,h as gs,i as Ae,j as qe,k as ls,l as ks,R as Se,m as st,n as wt,o as De,X as pe,K as _t,p as Ge,q as ze,r as Le,s as Pe,t as Ss,u as kt,v as Ue,w as St,x as Ct,y as Ke,z as $t,F as Cs,I as $s,G as Is,H as It,J as At,M as os,N as Ze,O as tt,V as Dt,W as Pt,Y as bs,_ as Lt,$ as Ft,a0 as As,a1 as Et,a2 as at,a3 as as,a4 as lt,a5 as Rt,a6 as Ot,a7 as fs,a8 as rt,a9 as Tt,aa as Mt}from"./icons-vendor-BmeuAUrP.js";import{R as He,B as qt,X as Ds,Y as Ps,T as ds,a as Bt,C as cs,A as zt,b as Ut,c as Wt,P as Ls,d as Fs,L as Jt}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const g of document.querySelectorAll('link[rel="modulepreload"]'))h(g);new MutationObserver(g=>{for(const p of g)if(p.type==="childList")for(const k of p.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&h(k)}).observe(document,{childList:!0,subtree:!0});function l(g){const p={};return g.integrity&&(p.integrity=g.integrity),g.referrerPolicy&&(p.referrerPolicy=g.referrerPolicy),g.crossOrigin==="use-credentials"?p.credentials="include":g.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function h(g){if(g.ep)return;g.ep=!0;const p=l(g);fetch(g.href,p)}})();const Vt=({activeTab:s,isAdmin:a=!1,onNavigate:l,onLogout:h})=>{const g=[{id:"dashboard",icon:ft,label:"仪表盘"},{id:"accounts",icon:Ks,label:"账号管理"},{id:"orders",icon:Gs,label:"订单管理"},{id:"cards",icon:us,label:"卡密库存"},{id:"items",icon:Xs,label:"商品列表"},{id:"rules",icon:hs,label:"自动化规则"},{id:"notifications",icon:Be,label:"通知设置"},...a?[{id:"settings",icon:ys,label:"系统与AI"}]:[]];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:g.map(p=>{const k=p.icon,_=s===p.id;return e.jsxs("button",{onClick:()=>l(p.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${_?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(k,{className:`w-5 h-5 transition-colors ${_?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:p.label}),_&&e.jsx(Zs,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},p.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:h,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(jt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Qt=s=>{if(!s)return"";const a=new URLSearchParams;for(const[h,g]of Object.entries(s))g!=null&&a.set(h,String(g));const l=a.toString();return l?`?${l}`:""},ns=async(s,a,l={})=>{const h=Qt(l.params),g=`${a}${h}`,p=await fetch(g,{method:s,credentials:"include",headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)}),_=(p.headers.get("content-type")||"").includes("application/json");if(!p.ok){const u=_?await p.json().catch(()=>{}):await p.text().catch(()=>{}),q=typeof u=="string"?u:(u==null?void 0:u.detail)||(u==null?void 0:u.message)||(u==null?void 0:u.msg);throw new Error(q||`请求失败: ${p.status}`)}return _?await p.json():await p.text()},me=async(s,a)=>ns("GET",s,{params:a}),de=async(s,a)=>ns("POST",s,{body:a}),Ne=async(s,a)=>ns("PUT",s,{body:a}),Oe=async(s,a)=>ns("DELETE",s,{params:a}),js=async(s,a)=>{const l=await fetch(s,{method:"POST",credentials:"include",body:a}),p=(l.headers.get("content-type")||"").includes("application/json")?await l.json().catch(()=>{}):await l.text().catch(()=>{});if(!l.ok){const k=typeof p=="string"?p:(p==null?void 0:p.detail)||(p==null?void 0:p.message)||(p==null?void 0:p.msg),_=new Error(k||"请求失败: "+l.staLine 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(ys,{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:()=>F(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:P,children:"取消"}),e.jsxs("button",{onClick:Ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:P,children:[P?e.jsx(ke,{className:"w-4 h-4 animate-spin"}):e.jsx(Le,{className:"w-4 h-4"}),P?"保存中...":"保存"]})]})})]})}),document.body)]})},zs=({status:s})=>{const a={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"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[s]||a.cancelled}`,children:l[s]||s})},al=()=>{const[s,a]=d.useState([]),[l,h]=d.useState([]),[g,p]=d.useState([]),[k,_]=d.useState({}),[u,q]=d.useState("all"),[b,Y]=d.useState(""),[te,B]=d.useState(1),[Q,T]=d.useState(1),[Z,H]=d.useState(!1),[E,X]=d.useState(!1),[ee,I]=d.useState(!1),[J,U]=d.useState(!1),[v,F]=d.useState(null),[o,C]=d.useState(null),[re,K]=d.useState({}),[z,S]=d.useState(!1),[A,W]=d.useState(""),[m,x]=d.useState(!1),[P,N]=d.useState(null),[se,D]=d.useState(null),[i,R]=d.useState(null),[ne,ae]=d.useState(null),c=t=>{if(!b.trim())return t;const y=b.toLowerCase().trim();return t.filter($=>{var O,oe,r,L,ie,$e;return((O=$.order_id)==null?void 0:O.toLowerCase().includes(y))||((oe=$.item_id)==null?void 0:oe.toLowerCase().includes(y))||((r=$.buyer_id)==null?void 0:r.toLowerCase().includes(y))||((L=$.item_title)==null?void 0:L.toLowerCase().includes(y))||((ie=$.receiver_name)==null?void 0:ie.toLowerCase().includes(y))||(($e=$.receiver_phone)==null?void 0:$e.toLowerCase().includes(y))})},f=async()=>{H(!0);try{if(b.trim()){let t=[],y=1,$=!0;for(;$;){const O=await Rs(void 0,u,y,100);t=[...t,...O.data],$=y<O.total_pages,y++}h(t),a(c(t)),T(1)}else{const t=await Rs(void 0,u,te,20);h(t.data),a(c(t.data)),T(t.total_pages)}}catch(t){console.error("加载订单失败:",t)}finally{H(!1)}};d.useEffect(()=>{a(c(l))},[l,b]);const V=(t,y)=>{if(y&&y.trim())return y;if(k[t])return k[t];const $=g.find(O=>{if(y&&O.item_title){const oe=y.toLowerCase(),r=O.item_title.toLowerCase();return r.includes(oe)||oe.includes(r)}return!1});return $!=null&&$.item_title?$.item_title:"未知商品"},le=t=>{const y={};t.forEach($=>{$.item_id&&(y[$.item_id]=$.item_title||$.item_id)}),_(y)};d.useEffect(()=>{f(),We().then(t=>{p(t),le(t)}).catch(t=>{console.error("加载商品列表失败:",t)})},[u,te,b]);const M=async()=>{H(!0);try{const t=await pa();await f(),t!=null&&t.message&&alert(t.message)}catch(t){console.error("同步订单失败:",t),alert((t==null?void 0:t.message)||"同步失败,请重试")}finally{H(!1)}},ge=t=>{W(t),N(null),S(!0)},ve=async t=>{var y;x(!0),N(null);try{const $=await ha([A],t),O=(y=$==null?void 0:$.results)==null?void 0:y[0];O!=null&&O.success?(N({success:!0,message:O.message}),f()):N({success:!1,message:(O==null?void 0:O.message)||"发货失败"})}catch($){N({success:!1,message:($==null?void 0:$.message)||"请求失败"})}finally{x(!1)}},be=t=>{F(t),X(!0)},_e=t=>{C({...t}),I(!0)},Ce=async()=>{if(!(!o||!o.order_id))try{const t={};o.status!==void 0&&(t.order_status=o.status),o.buyer_id!==void 0&&(t.buyer_id=o.buyer_id),o.amount!==void 0&&(t.amount=o.amount),o.receiver_name!==void 0&&(t.receiver_name=o.receiver_name),o.receiver_phone!==void 0&&(t.receiver_phone=o.receiver_phone),o.receiver_address!==void 0&&(t.receiver_address=o.receiver_address),o.item_id!==void 0&&(t.item_id=o.item_id),o.quantity!==void 0&&(t.quantity=o.quantity),await xa(o.order_id,t),I(!1),C(null),f()}catch(t){console.error("更新订单失败:",t),alert("更新失败,请重试")}},we=async()=>{if(se)try{const t=new FormData;t.append("file",se),await ga(t),U(!1),D(null),f(),alert("订单导入成功")}catch(t){alert((t==null?void 0:t.message)||"导入失败,请检查文件格式")}},ye=async t=>{R(t);tr Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(V=>V.map(le=>`"${String(le).replace(/"/g,'""')}"`).join(",")).join(`
`),ae=new Blob(["\uFEFF"+ne],{type:"text/csv;charset=utf-8"}),c=URL.createObjectURL(ae),f=document.createElement("a");f.href=c,f.download="卡密组批量导入模板.csv",document.body.appendChild(f),f.click(),f.remove(),URL.revokeObjectURL(c)},N=async()=>{if(Z){I(!0),X(null);try{const i=await va(Z);if(X(i),i.created>0){const R=await Ie();a(R)}}catch(i){X({error:(i==null?void 0:i.message)||"上传失败"})}finally{I(!1)}}},se=async()=>{if(!(!J||!v.trim())){I(!0),C(null);try{const i=await wa(J,v);C({added:i.added}),F("");const R=await Ie();a(R)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{I(!1)}}},D=()=>{var i;T("create"),H(null),X(null),U((i=x[0])!=null&&i.id?String(x[0].id):""),F(""),C(null),B(!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:D,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(Ke,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>p(!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(Pe,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),e.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),e.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),e.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),e.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(i=>{let R="";return i.type==="data"&&i.data_content?R=`库存: ${i.data_content.split(`
`).filter(ae=>ae.trim()).length} 条`:i.type==="text"&&i.text_content?R=i.text_content.substring(0,20)+(i.text_content.length>20?"...":""):i.type==="api"&&i.api_config?R=i.api_config.url:i.type==="image"&&i.image_url&&(R="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-8 py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:e.jsx(re,{type:i.type})}),e.jsx("span",{className:"font-bold text-gray-900",children:i.name})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("button",{onClick:()=>m(i.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[i.id,e.jsx($t,{className:"w-3.5 h-3.5"})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs 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-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:R,children:R})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("button",{onClick:()=>W(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-6 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>K(i),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(Ue,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>S(i.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx(De,{className:"w-5 h-5"})})]})})]},i.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Hs,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),l&&k&&he.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:()=>h(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(pe,{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:u.name||"",onChange:i=>q({...u,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:u.type||"text",onChange:i=>q({...u,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:"批量数据"}),e.jsx("option",{value:"api",children:"API接口"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),u.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:u.api_url||"",onChange:i=>q({...u,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.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:u.api_method||"GET",onChange:i=>q({...u,api_method:i.target.value}),className:"w-full ios-input px-4 pyLine 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:u.data_content?u.data_content.split(`
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),u.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:u.image_url||"",onChange:i=>q({...u,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 地址"})]}),u.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:u.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:u.delay_seconds||0,onChange:i=>q({...u,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:u.description||"",onChange:i=>q({...u,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:()=>q({...u,enabled:!u.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${u.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 ${u.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:()=>h(!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:z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),g&&he.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:()=>p(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(pe,{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:b.name,onChange:i=>Y({...b,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-4 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(us,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Cs,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Y({...b,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),b.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:b.content.split(`
`).filter(i=>i.trim()).length})," 条"]})]}),b.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:b.api_method,onChange:i=>Y({...b,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:b.api_timeout,onChange:i=>Y({...b,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:b.api_headers,onChange:i=>Y({...b,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:b.api_params,onChange:i=>Y({...b,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:b.description,onChange:i=>Y({...b,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:b.delay_seconds,onChange:i=>Y({...b,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:()=>p(!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:A,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),te&&he.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:()=>B(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(pe,{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:()=>T("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 ${Q==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(It,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>T("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 ${Q==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ke,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),Q==="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/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:P,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:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),o&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",o.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:()=>B(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),Q==="create"?e.jsxs("button",{onClick:N,disabled:!Z||ee,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[ee?e.jsx(ke,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),ee?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:se,disabled:!J||!v.trim()||ee||x.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[ee?e.jsx(ke,{className:"w-4 h-4 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4"}),ee?"处理中...":"追加卡密"]})]})]})}),document.body)]})},rl=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},nl=({onConfigureDelivery:s})=>{const[a,l]=d.useState([]),[h,g]=d.useState([]),[p,k]=d.useState([]),[_,u]=d.useState(""),[q,b]=d.useState(!1),[Y,te]=d.useState(!1),[B,Q]=d.useState(!1),[T,Z]=d.useState(!1),[H,E]=d.useState(!1),[X,ee]=d.useState(!1),[I,J]=d.useState(!1),[U,v]=d.useState("upload"),[F,o]=d.useState(null),[C,re]=d.useState(null),[K,z]=d.useState(null),[S,A]=d.useState(null),[W,m]=d.useState(null),[x,P]=d.useState({}),[N,se]=d.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[D,i]=d.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[R,ne]=d.useState([]);d.useEffect(()=>{if(!X||D.images.length===0){ne([]);return}const r=D.images.map((L,ie)=>({key:L.name+ie,url:URL.createObjectURL(L)}));return ne(r),()=>{r.forEach(L=>URL.revokeObjectURL(L.url))}},[X,D.images]);const ae=async()=>{const r=await We();l(r)},c=async()=>{g(await rs())};d.useEffect(()=>{Promise.all([Ns(),We(),rs()]).then(([r,L,ie])=>{k(r),l(L),g(ie)}).catch(r=>console.error("加载商品配置失败:",r))},[]),d.useEffect(()=>{if(!I||!(S!=null&&S.id)||S.status!=="running")return;const r=window.setInterval(async()=>{try{const L=await es(S.id);A(L),L.status!=="running"&&(v("done"),await ae(),await c())}catch(L){console.error("刷新批量铺货进度失败:",L)}},3e3);return()=>window.clearInterval(r)},[I,S==null?void 0:S.id,S==null?void 0:S.status]);const f=async()=>{if(!_)return alert("请先选择账号");b(!0);try{const r=await _a(_);await ae(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{b(!1)}},V=r=>{m(r),P({...r}),Z(!0)},le=async()=>{if(W)try{await Pa(W.cookie_id,W.item_id,{item_title:x.item_title||"",item_description:x.item_description||"",item_category:x.item_category||"",item_price:x.item_price||"",item_detail:x.item_detail||W.item_detail||""}),await ae(),await c(),Z(!1),m(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},M=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await ka(r.cookie_id,r.item_id),l(L=>L.filter(ie=>!(ie.cookie_id===r.cookie_id&&ie.item_id===r.item_id)))}catch(L){console.error("删除商品失败:",L),alert("删除失败,请重试")}},ge=async()=>{try{if(!N.cookie_id||!N.item_id){alert("请选择账号并填写商品ID");return}await Sa(N.cookie_id,{item_id:N.item_id,item_title:N.item_title,item_price:N.item_price,item_detail:N.item_image?JSON.stringify({item_image:N.item_image}):""}),await ae(),E(!1),se({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},ve=async()=>{if(!D.cookie_id)return alert("请选择发布账号");if(!D.title.trim())return alert("请填写商品标题");if(!D.price.trim())return alert("请填写商品价格");if(!D.quantity||Number(D.quantity)<=0)return alert("库存数量必须大于 0");if(D.images.length===0)return alert("至少上传 1 张商品图片");if(D.postage_mode==="fixed"&&!D.postage.trim())return alert("请填写一口价邮费");te(!0);try{const r=await Ca(D);if(await ae(),ee(!1),i({cookie_id:_||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),r!=null&&r.item_id){const L={id:r.item_id,cookie_id:D.cookie_id,item_id:r.item_id,item_title:r.item_title||D.title,item_price:r.item_price||D.price,item_image:r.item_image};s(L),alert("商品发布成功,ID: "+r.item_id+",已为 Line truncated
`),$e=new Blob(["\uFEFF"+ie],{type:"text/csv;charset=utf-8"}),Je=URL.createObjectURL($e),Fe=document.createElement("a");Fe.href=Je,Fe.download="批量铺货模板.csv",document.body.appendChild(Fe),Fe.click(),Fe.remove(),URL.revokeObjectURL(Je)},t=()=>{se(r=>({...r,cookie_id:_||r.cookie_id})),E(!0)},y=()=>{i(r=>({...r,cookie_id:_||r.cookie_id})),ee(!0)},$=r=>h.filter(L=>L.cookie_id===r.cookie_id&&L.item_id===r.item_id),O=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},oe=r=>{switch(r){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"}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex justify-between items-center",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 gap-3",children:[e.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:_,onChange:r=>u(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),p.map(r=>e.jsx("option",{value:r.id,children:r.nickname},r.id))]}),e.jsxs("button",{onClick:f,disabled:q||!_,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(Se,{className:`w-4 h-4 ${q?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:t,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(Pe,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:y,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(os,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:be,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(Ze,{className:"w-4 h-4"}),"批量铺货"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[a.map(r=>{const L=$(r),ie=L.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>V(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(Ue,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>M(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(De,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[r.item_image?e.jsx("img",{src:r.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Xs,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:rl(r.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:r.item_title}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",r.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${ie?"text-emerald-600":"text-amber-600"}`,children:[ie?e.jsx(tt,{className:"w-3 h-3"}):e.jsx(Dt,{className:"w-3 h-3"}),ie?`${L.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(r),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${ie?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`Line 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}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{rigLine truncated
@@ -0,0 +1,19 @@
import{j as e,r as o,b as ge,c as vt,d as wt}from"./react-vendor-DZnRGM0-.js";import{L as _t,U as et,S as st,C as gs,B as tt,Z as bs,a as ze,b as Ns,c as at,d as kt,e as Xe,A as Is,D as Ct,f as As,P as lt,g as Ze,E as vs,T as St,h as je,Q as is,i as ys,j as Ae,k as Be,l as $s,R as _e,m as rt,n as It,o as $e,X as pe,K as At,p as Ye,q as Ue,r as Pe,s as Le,t as Ls,u as $t,v as We,w as Lt,x as Pt,y as Ge,z as Et,F as Ps,I as Es,G as Dt,H as Ft,J as Rt,M as os,N as He,O as nt,V as Tt,W as Ot,Y as fs,_ as Mt,$ as qt,a0 as Ds,a1 as Bt,a2 as it,a3 as ls,a4 as ot,a5 as zt,a6 as Ut,a7 as ws,a8 as dt,a9 as Wt,aa as Vt}from"./icons-vendor-6fuKcPoR.js";import{R as es,B as Jt,X as Fs,Y as Rs,T as ds,a as Qt,C as cs,A as Kt,b as Gt,c as Yt,P as Ts,d as Os,L as Xt}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 y of document.querySelectorAll('link[rel="modulepreload"]'))h(y);new MutationObserver(y=>{for(const u of y)if(u.type==="childList")for(const _ of u.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&h(_)}).observe(document,{childList:!0,subtree:!0});function l(y){const u={};return y.integrity&&(u.integrity=y.integrity),y.referrerPolicy&&(u.referrerPolicy=y.referrerPolicy),y.crossOrigin==="use-credentials"?u.credentials="include":y.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function h(y){if(y.ep)return;y.ep=!0;const u=l(y);fetch(y.href,u)}})();const Zt=({activeTab:s,isAdmin:t=!1,onNavigate:l,onLogout:h})=>{const y=[{id:"dashboard",icon:_t,label:"仪表盘"},{id:"accounts",icon:et,label:"账号管理"},{id:"orders",icon:st,label:"订单管理"},{id:"cards",icon:gs,label:"卡密库存"},{id:"items",icon:tt,label:"商品列表"},{id:"rules",icon:bs,label:"自动化规则"},{id:"notifications",icon:ze,label:"通知设置"},...t?[{id:"settings",icon:Ns,label:"系统与AI"}]:[]];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:y.map(u=>{const _=u.icon,k=s===u.id;return e.jsxs("button",{onClick:()=>l(u.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${k?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(_,{className:`w-5 h-5 transition-colors ${k?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:u.label}),k&&e.jsx(at,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},u.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:h,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(kt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})};let xs=!1;const ct=()=>{xs||typeof window>"u"||(xs=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{xs=!1}))},Ht=s=>{if(!s)return"";const t=new URLSearchParams;for(const[h,y]of Object.entries(s))y!=null&&t.set(h,String(y));const l=t.toString();return l?`?${l}`:""},ns=async(s,t,l={})=>{const h=Ht(l.params),y=`${t}${h}`,u=await fetch(y,{method:s,credentials:"include",headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)}),k=(u.headers.get("content-type")||"").includes("application/json");if(!u.ok){u.status===401&&!l.skipAuthLogout&&ct();const g=k?await u.json().catch(()=>{}):await u.text().catch(()=>{}),q=typeof g=="string"?g:(g==null?void 0:g.detail)||(g==null?void 0:g.message)||(g==null?void 0:g.msg);throw new Error(q||`请求失败: ${u.status}`)}return k?await u.json():await u.text()},me=async(s,t)=>ns("GET",s,{params:t}),xe=async(s,t,l)=>ns("POST",s,{body:t,...l}),ye=async(s,t)=>ns("PUT",s,{body:t}),Oe=async(s,t)=>ns("DELETE",s,{params:t}),_s=async(s,t)=>{const l=await fetch(s,{method:"POST",credentials:"include",body:t}),u=(l.headers.get("content-type")||"").includes("application/json")?await l.json().catch(()=>{}):awaitLine 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(Ns,{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:()=>P(null),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:w,children:"取消"}),e.jsxs("button",{onClick:n,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:w,children:[w?e.jsx(je,{className:"w-4 h-4 animate-spin"}):e.jsx(Pe,{className:"w-4 h-4"}),w?"保存中...":"保存"]})]})})]})}),document.body)]})},Qs=({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"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},xl=()=>{const[s,t]=o.useState([]),[l,h]=o.useState([]),[y,u]=o.useState([]),[_,k]=o.useState({}),[g,q]=o.useState("all"),[f,Q]=o.useState(""),[se,R]=o.useState(1),[U,D]=o.useState(1),[Y,ee]=o.useState(!1),[E,K]=o.useState(!1),[re,A]=o.useState(!1),[B,V]=o.useState(!1),[N,P]=o.useState(null),[i,S]=o.useState(null),[X,J]=o.useState({}),[W,C]=o.useState(!1),[le,H]=o.useState(""),[b,x]=o.useState(!1),[O,v]=o.useState(null),[Z,I]=o.useState(null),[r,$]=o.useState(null),[z,d]=o.useState(null),w=m=>{if(!f.trim())return m;const T=f.toLowerCase().trim();return m.filter(G=>{var ne,we,n,L,te,Ce;return((ne=G.order_id)==null?void 0:ne.toLowerCase().includes(T))||((we=G.item_id)==null?void 0:we.toLowerCase().includes(T))||((n=G.buyer_id)==null?void 0:n.toLowerCase().includes(T))||((L=G.item_title)==null?void 0:L.toLowerCase().includes(T))||((te=G.receiver_name)==null?void 0:te.toLowerCase().includes(T))||((Ce=G.receiver_phone)==null?void 0:Ce.toLowerCase().includes(T))})},M=async()=>{ee(!0);try{if(f.trim()){let m=[],T=1,G=!0;for(;G;){const ne=await qs(void 0,g,T,100);m=[...m,...ne.data],G=T<ne.total_pages,T++}h(m),t(w(m)),D(1)}else{const m=await qs(void 0,g,se,20);h(m.data),t(w(m.data)),D(m.total_pages)}}catch(m){console.error("加载订单失败:",m)}finally{ee(!1)}};o.useEffect(()=>{t(w(l))},[l,f]);const ae=(m,T)=>{if(T&&T.trim())return T;if(_[m])return _[m];const G=y.find(ne=>{if(T&&ne.item_title){const we=T.toLowerCase(),n=ne.item_title.toLowerCase();return n.includes(we)||we.includes(n)}return!1});return G!=null&&G.item_title?G.item_title:"未知商品"},de=m=>{const T={};m.forEach(G=>{G.item_id&&(T[G.item_id]=G.item_title||G.item_id)}),k(T)};o.useEffect(()=>{M(),Ve().then(m=>{u(m),de(m)}).catch(m=>{console.error("加载商品列表失败:",m)})},[g,se,f]);const ce=async()=>{ee(!0);try{const m=await fa();await M(),m!=null&&m.message&&alert(m.message)}catch(m){console.error("同步订单失败:",m),alert((m==null?void 0:m.message)||"同步失败,请重试")}finally{ee(!1)}},be=m=>{H(m),v(null),C(!0)},Ee=async m=>{var T;x(!0),v(null);try{const G=await Na([le],m),ne=(T=G==null?void 0:G.results)==null?void 0:T[0];ne!=null&&ne.success?(v({success:!0,message:ne.message}),M()):v({success:!1,message:(ne==null?void 0:ne.message)||"发货失败"})}catch(G){v({success:!1,message:(G==null?void 0:G.message)||"请求失败"})}finally{x(!1)}},fe=m=>{P(m),K(!0)},Ne=m=>{S({...m}),A(!0)},ve=async()=>{if(!(!i||!i.order_id))try{const m={};i.status!==void 0&&(m.order_status=i.status),i.buyer_id!==void 0&&(m.buyer_id=i.buyer_id),i.amount!==void 0&&(m.amount=i.amount),i.receiver_name!==void 0&&(m.receiver_name=i.receiver_name),i.receiver_phone!==void 0&&(m.receiver_phone=i.receiver_phone),i.receiver_address!==void 0&&(m.receiver_address=i.receiver_address),i.item_id!==void 0&&(m.item_id=i.item_id),i.quantity!==void 0&&(m.quantity=i.quantity),await ba(i.order_id,m),A(!1),S(null),M()}catch(m){console.error("更新订单失败:",m),alert("更新失败,请重试")}},De=async()=>{if(Z)try{const m=new FormData;m.append("file",Z),await va(m),V(!1),I(null),M(),alert("订单导入成功")}catch(m){alert((m==null?void 0:m.message)||"导入失败,请检查文件格式")}},Fe= Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(ae=>ae.map(de=>`"${String(de).replace(/"/g,'""')}"`).join(",")).join(`
`),d=new Blob(["\uFEFF"+z],{type:"text/csv;charset=utf-8"}),w=URL.createObjectURL(d),M=document.createElement("a");M.href=w,M.download="卡密组批量导入模板.csv",document.body.appendChild(M),M.click(),M.remove(),URL.revokeObjectURL(w)},v=async()=>{if(Y){A(!0),K(null);try{const r=await Ia(Y);if(K(r),r.created>0){const $=await Ie();t($)}}catch(r){K({error:(r==null?void 0:r.message)||"上传失败"})}finally{A(!1)}}},Z=async()=>{if(!(!B||!N.trim())){A(!0),S(null);try{const r=await Aa(B,N);S({added:r.added}),P("");const $=await Ie();t($)}catch(r){alert("追加失败:"+((r==null?void 0:r.message)||"未知错误"))}finally{A(!1)}}},I=()=>{var r;D("create"),ee(null),K(null),V((r=x[0])!=null&&r.id?String(x[0].id):""),P(""),S(null),R(!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:I,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(Ge,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>u(!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(Le,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),e.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),e.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),e.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),e.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(r=>{let $="";return r.type==="data"&&r.data_content?$=`库存: ${r.data_content.split(`
`).filter(d=>d.trim()).length} 条`:r.type==="text"&&r.text_content?$=r.text_content.substring(0,20)+(r.text_content.length>20?"...":""):r.type==="api"&&r.api_config?$=r.api_config.url:r.type==="image"&&r.image_url&&($="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-8 py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:e.jsx(X,{type:r.type})}),e.jsx("span",{className:"font-bold text-gray-900",children:r.name})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("button",{onClick:()=>b(r.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[r.id,e.jsx(Et,{className:"w-3.5 h-3.5"})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${r.type==="text"?"bg-blue-50 text-blue-600":r.type==="data"?"bg-purple-50 text-purple-600":r.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:r.type==="text"?"文本":r.type==="data"?"批量":r.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:$,children:$})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:r.description||"-",children:r.description||"-"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("button",{onClick:()=>H(r),className:`w-12 h-8 rounded-full relative transition-colors ${r.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 ${r.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>J(r),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(We,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>C(r.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx($e,{className:"w-5 h-5"})})]})})]},r.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(lt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),l&&_&&ge.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:()=>h(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(pe,{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:r=>q({...g,name:r.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:r=>q({...g,type:r.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:"批量数据"}),(_==null?void 0:_.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:r=>q({...g,api_url:r.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:g.api_method||"GET",onChange:r=>q({...g,api_meLine 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(r=>r.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:r=>q({...g,image_url:r.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:r=>{r.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:r=>q({...g,delay_seconds:parseInt(r.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:r=>q({...g,description:r.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:()=>q({...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:()=>h(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:W,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Pe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&ge.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:()=>u(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(pe,{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:f.name,onChange:r=>Q({...f,name:r.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:()=>Q({...f,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(gs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ps,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),f.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:f.content.split(`
`).filter(r=>r.trim()).length})," 条"]})]}),f.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:f.api_method,onChange:r=>Q({...f,api_method:r.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:f.api_timeout,onChange:r=>Q({...f,api_timeout:parseInt(r.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:f.api_headers,onChange:r=>Q({...f,api_headers:r.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:f.api_params,onChange:r=>Q({...f,api_params:r.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:f.description,onChange:r=>Q({...f,description:r.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:f.delay_seconds,onChange:r=>Q({...f,delay_seconds:parseInt(r.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:()=>u(!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:le,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Le,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),se&&ge.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:()=>R(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(pe,{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:()=>D("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 ${U==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>D("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 ${U==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ge,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),U==="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/api;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:O,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:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),i&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",i.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:()=>R(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),U==="create"?e.jsxs("button",{onClick:v,disabled:!Y||re,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[re?e.jsx(je,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),re?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Z,disabled:!B||!N.trim()||re||x.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[re?e.jsx(je,{className:"w-4 h-4 animate-spin"}):e.jsx(Le,{className:"w-4 h-4"}),re?"处理中...":"追加卡密"]})]})]})}),document.body)]})},ul=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},pl=({onConfigureDelivery:s})=>{const[t,l]=o.useState([]),[h,y]=o.useState([]),[u,_]=o.useState([]),[k,g]=o.useState(""),[q,f]=o.useState(!1),[Q,se]=o.useState(!1),[R,U]=o.useState(!1),[D,Y]=o.useState(!1),[ee,E]=o.useState(!1),[K,re]=o.useState(!1),[A,B]=o.useState(!1),[V,N]=o.useState("upload"),[P,i]=o.useState(null),[S,X]=o.useState(null),[J,W]=o.useState(null),[C,le]=o.useState(null),[H,b]=o.useState(null),[x,O]=o.useState({}),[v,Z]=o.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[I,r]=o.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[$,z]=o.useState([]);o.useEffect(()=>{if(!K||I.images.length===0){z([]);return}const n=I.images.map((L,te)=>({key:L.name+te,url:URL.createObjectURL(L)}));return z(n),()=>{n.forEach(L=>URL.revokeObjectURL(L.url))}},[K,I.images]);const d=async()=>{const n=await Ve();l(n)},w=async()=>{y(await rs())};o.useEffect(()=>{Promise.all([ks(),Ve(),rs()]).then(([n,L,te])=>{_(n),l(L),y(te)}).catch(n=>console.error("加载商品配置失败:",n))},[]),o.useEffect(()=>{if(!A||!(C!=null&&C.id)||C.status!=="running")return;const n=window.setInterval(async()=>{try{const L=await ss(C.id);le(L),L.status!=="running"&&(N("done"),await d(),await w())}catch(L){console.error("刷新批量铺货进度失败:",L)}},3e3);return()=>window.clearInterval(n)},[A,C==null?void 0:C.id,C==null?void 0:C.status]);const M=async()=>{if(!k)return alert("请先选择账号");f(!0);try{const n=await $a(k);await d(),alert((n==null?void 0:n.message)||"商品同步完成")}catch(n){console.error("同步商品失败:",n),alert((n==null?void 0:n.message)||"同步失败,请重试")}finally{f(!1)}},ae=n=>{b(n),O({...n}),Y(!0)},de=async()=>{if(H)try{await Oa(H.cookie_id,H.item_id,{item_title:x.item_title||"",item_description:x.item_description||"",item_category:x.item_category||"",item_price:x.item_price||"",item_detail:x.item_detail||H.item_detail||""}),await d(),await w(),Y(!1),b(null)}catch(n){console.error("更新商品失败:",n),alert("更新失败,请重试")}},ce=async n=>{if(confirm(`确认删除商品"${n.item_title}"吗?`))try{await La(n.cookie_id,n.item_id),l(L=>L.filter(te=>!(te.cookie_id===n.cookie_id&&te.item_id===n.item_id)))}catch(L){console.error("删除商品失败:",L),alert("删除失败,请重试")}},be=async()=>{try{if(!v.cookie_id||!v.item_id){alert("请选择账号并填写商品ID");return}await Pa(v.cookie_id,{item_id:v.item_id,item_title:v.item_title,item_price:v.item_price,item_detail:v.item_image?JSON.stringify({item_image:v.item_image}):""}),await d(),E(!1),Z({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(n){console.error("添加商品失败:",n),alert("添加失败,请重试")}},Ee=async()=>{if(!I.cookie_id)return alert("请选择发布账号");if(!I.title.trim())return alert("请填写商品标题");if(!I.price.trim())return alert("请填写商品价格");if(!I.quantity||Number(I.quantity)<=0)return alert("库存数量必须大于 0");if(I.images.length===0)return alert("至少上传 1 张商品图片");if(I.postage_mode==="fixed"&&!I.postage.trim())return alert("请填写一口价邮费");se(!0);try{const n=await Ea(I);if(await d(),re(!1),r({cookie_id:k||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),n!=null&&n.item_id){const L={id:n.item_id,cookie_id:I.cookie_id,item_id:n.item_id,item_title:n.item_title||I.title,item_price:n.item_price||I.price,item_image:n.item_image};s(L),alert("商品发布成功,ID: "+n.item_id+",已为你打开 Line truncated
`),Ce=new Blob(["\uFEFF"+te],{type:"text/csv;charset=utf-8"}),Se=URL.createObjectURL(Ce),c=document.createElement("a");c.href=Se,c.download="批量铺货模板.csv",document.body.appendChild(c),c.click(),c.remove(),URL.revokeObjectURL(Se)},m=()=>{Z(n=>({...n,cookie_id:k||n.cookie_id})),E(!0)},T=()=>{r(n=>({...n,cookie_id:k||n.cookie_id})),re(!0)},G=n=>h.filter(L=>L.cookie_id===n.cookie_id&&L.item_id===n.item_id),ne=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},we=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"}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex justify-between items-center",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 gap-3",children:[e.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:k,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),u.map(n=>e.jsx("option",{value:n.id,children:n.nickname},n.id))]}),e.jsxs("button",{onClick:M,disabled:q||!k,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(_e,{className:`w-4 h-4 ${q?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:m,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(Le,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:T,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(os,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:fe,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(He,{className:"w-4 h-4"}),"批量铺货"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[t.map(n=>{const L=G(n),te=L.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>ae(n),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(We,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>ce(n),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx($e,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[n.item_image?e.jsx("img",{src:n.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(tt,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:ul(n.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:n.item_title}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",n.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${te?"text-emerald-600":"text-amber-600"}`,children:[te?e.jsx(nt,{className:"w-3 h-3"}):e.jsx(Tt,{className:"w-3 h-3"}),te?`${L.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(n),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${te?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`,chi 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}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{rigLine truncated
+3 -3
View File
@@ -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-BcWGTs2i.js"></script>
<script type="module" crossorigin src="/static/assets/index-CaW5oMkx.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BmeuAUrP.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-6fuKcPoR.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-D71nKbMO.css">
<link rel="stylesheet" crossorigin href="/static/assets/index-CK7Gki1b.css">
</head>
<body>
<div id="root"></div>
+148 -40
View File
@@ -53,6 +53,7 @@ var qrHeaders = map[string]string{
// Session 一个扫码登录会话。
type Session struct {
mu sync.RWMutex
SessionID string `json:"session_id"`
Status string `json:"status"` // waiting/scanned/success/expired/cancelled/verification_required
QRCodeURL string `json:"qr_code_url"`
@@ -69,9 +70,34 @@ type Session struct {
}
func (s *Session) isExpired() bool {
s.mu.RLock()
defer s.mu.RUnlock()
return time.Since(s.createdTime) > s.expireTime
}
type sessionSnapshot struct {
status string
cookies map[string]string
unb string
params map[string]string
verificationURL string
verificationScreenshot string
faceQRURL string
expireTime time.Duration
createdTime time.Time
}
func (s *Session) snapshot() sessionSnapshot {
s.mu.RLock()
defer s.mu.RUnlock()
return sessionSnapshot{
status: s.Status, cookies: cloneCookieMap(s.cookies), unb: s.unb,
params: cloneCookieMap(s.params), verificationURL: s.verificationURL,
verificationScreenshot: s.verificationScreenshot, faceQRURL: s.faceQRURL,
expireTime: s.expireTime, createdTime: s.createdTime,
}
}
// BrowserRefresher 由外部注入的浏览器刷新函数。
// tmpCookies: 扫码临时 cookie;verificationURL: Chromium 打开后持有 session 等待验证。
// onScreenshot: 每次截图时回调(data:image/png;base64,...),前端实时显示验证页画面。
@@ -88,9 +114,17 @@ type Manager struct {
// SetBrowserRefresher 注入浏览器刷新函数(风控验证场景必需)。
func (m *Manager) SetBrowserRefresher(f BrowserRefresher) {
m.mu.Lock()
defer m.mu.Unlock()
m.browser = f
}
func (m *Manager) browserRefresher() BrowserRefresher {
m.mu.Lock()
defer m.mu.Unlock()
return m.browser
}
// NewManager 构造。
func NewManager(logger *slog.Logger) *Manager {
if logger == nil {
@@ -198,7 +232,7 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
// 5. 扫码会话独立于生成二维码的 HTTP 请求,但受会话有效期约束。
// #nosec G118 -- 后台任务必须跨越原请求,且由超时上下文保证退出。
go func() {
monitorCtx, cancel := context.WithTimeout(context.Background(), sess.expireTime)
monitorCtx, cancel := context.WithTimeout(context.Background(), sess.snapshot().expireTime)
defer cancel()
m.monitorQRStatus(monitorCtx, sessionID)
}()
@@ -215,27 +249,34 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
if !ok {
return map[string]any{"status": "not_found"}
}
if sess.isExpired() && sess.Status != "success" {
sess.mu.Lock()
if time.Since(sess.createdTime) > sess.expireTime && sess.Status != "success" {
sess.Status = "expired"
}
snapshot := sessionSnapshot{
status: sess.Status, cookies: cloneCookieMap(sess.cookies), unb: sess.unb,
verificationURL: sess.verificationURL, verificationScreenshot: sess.verificationScreenshot,
faceQRURL: sess.faceQRURL,
}
sess.mu.Unlock()
result := map[string]any{
"status": sess.Status,
"status": snapshot.status,
"session_id": sessionID,
}
if sess.Status == "verification_required" && sess.verificationURL != "" {
result["verification_url"] = sess.verificationURL
if snapshot.status == "verification_required" && snapshot.verificationURL != "" {
result["verification_url"] = snapshot.verificationURL
result["message"] = "账号被风控,需要手机验证"
if sess.faceQRURL != "" {
result["face_qr_url"] = sess.faceQRURL
if snapshot.faceQRURL != "" {
result["face_qr_url"] = snapshot.faceQRURL
result["message"] = "需要人脸验证,请使用手机闲鱼扫描二维码"
}
if sess.verificationScreenshot != "" {
result["verification_screenshot"] = sess.verificationScreenshot
if snapshot.verificationScreenshot != "" {
result["verification_screenshot"] = snapshot.verificationScreenshot
}
}
if sess.Status == "success" && sess.cookies != nil && sess.unb != "" {
result["cookies"] = cookieMarshal(sess.cookies)
result["unb"] = sess.unb
if snapshot.status == "success" && snapshot.cookies != nil && snapshot.unb != "" {
result["cookies"] = cookieMarshal(snapshot.cookies)
result["unb"] = snapshot.unb
}
return result
}
@@ -269,13 +310,18 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
resp, err := m.pollQRCodeStatus(ctx, sess)
if err != nil {
m.logger.Error("轮询扫码状态异常", "err", err)
time.Sleep(2 * time.Second)
if !waitQRRetry(ctx, 2*time.Second) {
return
}
continue
}
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
closeErr := resp.Body.Close()
if readErr != nil || closeErr != nil {
m.logger.Warn("读取扫码状态响应失败", "read_err", readErr, "close_err", closeErr)
if !waitQRRetry(ctx, 800*time.Millisecond) {
return
}
continue
}
@@ -290,6 +336,9 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
}
if err := json.Unmarshal(body, &qrResult); err != nil {
m.logger.Warn("解析扫码状态响应失败", "err", err)
if !waitQRRetry(ctx, 800*time.Millisecond) {
return
}
continue
}
@@ -299,6 +348,11 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
if qrResult.Content.Data.IframeRedirect {
// 风控验证:记录状态和 URL,提取响应 cookie(临时 cookie),
// 验证完成后用这些临时 cookie 访问 goofish.com/im 换真实 cookie。
sess.mu.Lock()
if sess.Status == "success" {
sess.mu.Unlock()
return
}
if sess.Status != "verification_required" {
sess.Status = "verification_required"
sess.verificationURL = qrResult.Content.Data.IframeRedirectURL
@@ -309,22 +363,29 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
// 扫码 5 分钟窗口在用户扫人脸二维码时把会话误标为 expired。
sess.createdTime = time.Now()
sess.expireTime = 5 * time.Minute
m.logger.Warn("扫码登录需要风控验证,启动 API 人脸验证链路", "session_id", sessionID, "verification_url", logsafe.URL(sess.verificationURL), "tmp_cookie_count", len(sess.cookies))
verURL := sess.verificationURL
expireTime := sess.expireTime
cookieCount := len(sess.cookies)
sess.mu.Unlock()
m.logger.Warn("扫码登录需要风控验证,启动 API 人脸验证链路", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
// #nosec G118 -- 风控验证必须跨越轮询请求,且由超时上下文保证退出。
go func() {
verifyCtx, cancel := context.WithTimeout(context.Background(), sess.expireTime)
verifyCtx, cancel := context.WithTimeout(context.Background(), expireTime)
defer cancel()
if err := m.runFaceVerification(verifyCtx, sessionID, verURL); err != nil {
m.logger.Error("API 人脸验证链路失败", "session_id", sessionID, "err", err)
m.fallbackBrowserVerification(verifyCtx, sessionID, verURL)
}
}()
} else {
sess.mu.Unlock()
}
if !waitQRRetry(ctx, 800*time.Millisecond) {
return
}
time.Sleep(800 * time.Millisecond)
continue
}
sess.mu.Lock()
sess.Status = "success"
for _, c := range resp.Cookies() {
sess.cookies[c.Name] = c.Value
@@ -332,7 +393,9 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
sess.unb = c.Value
}
}
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb))
unb := sess.unb
sess.mu.Unlock()
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb))
return
case "NEW":
// 未扫码,继续
@@ -340,40 +403,61 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
// 浏览器自动验证可能已把状态置为 success:二维码 session 结束是
// 验证通过后的正常现象,此时绝不能把 success 覆盖回 expired,
// 否则前端轮询会错过自动完成的登录、不存 cookie、不重启账号。
m.mu.Lock()
sess.mu.Lock()
curStatus := sess.Status
if curStatus == "success" {
m.mu.Unlock()
sess.mu.Unlock()
m.logger.Info("验证已自动完成,二维码 session 结束", "session_id", sessionID)
return
}
if curStatus != "verification_required" {
sess.Status = "expired"
m.mu.Unlock()
sess.mu.Unlock()
m.logger.Info("二维码已过期", "session_id", sessionID)
return
}
m.mu.Unlock()
sess.mu.Unlock()
m.logger.Info("验证中收到 EXPIRED,保持验证状态", "session_id", sessionID)
time.Sleep(2 * time.Second)
if !waitQRRetry(ctx, 2*time.Second) {
return
}
continue
case "SCANED":
sess.mu.Lock()
if sess.Status == "waiting" {
sess.Status = "scanned"
m.logger.Info("二维码已扫描,等待确认", "session_id", sessionID)
}
sess.mu.Unlock()
default:
sess.mu.Lock()
sess.Status = "cancelled"
sess.mu.Unlock()
m.logger.Info("用户取消登录", "session_id", sessionID)
return
}
time.Sleep(800 * time.Millisecond)
if !waitQRRetry(ctx, 800*time.Millisecond) {
return
}
}
// 超时
sess.mu.Lock()
if sess.Status != "success" && sess.Status != "expired" && sess.Status != "cancelled" {
sess.Status = "expired"
}
sess.mu.Unlock()
}
func waitQRRetry(ctx context.Context, delay time.Duration) bool {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
// CompleteVerification 用户完成风控验证后调用:先用扫码临时 cookie 访问 goofish.com/im,
@@ -385,24 +469,29 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
if !ok {
return "", "", fmt.Errorf("会话不存在")
}
if len(sess.cookies) == 0 {
state := sess.snapshot()
if len(state.cookies) == 0 {
return "", "", fmt.Errorf("无扫码临时 cookie")
}
if state.status == "success" && state.unb != "" {
return cookieMarshal(state.cookies), state.unb, nil
}
browser := m.browserRefresher()
m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(sess.cookies))
m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(state.cookies))
// 用带 cookie jar 的 client,访问 goofish.com/im 触发真实 cookie 下发。
jarClient := &http.Client{Timeout: 30 * time.Second}
targetURL := qrVerifyTargetURL
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
m.setHeaders(req)
req.Header.Set("Cookie", cookieMarshal(sess.cookies))
req.Header.Set("Cookie", cookieMarshal(state.cookies))
// im 页面 referer
req.Header.Set("Referer", "https://www.goofish.com/")
resp, err := jarClient.Do(req)
if err != nil {
if m.browser == nil {
if browser == nil {
return "", "", fmt.Errorf("访问 goofish.com/im 失败: %w", err)
}
m.logger.Warn("纯 HTTP 访问 goofish.com/im 失败,改用浏览器提取", "session_id", sessionID, "err", err)
@@ -413,38 +502,44 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
}
// 收集 Set-Cookie。
sess.mu.Lock()
for _, c := range resp.Cookies() {
sess.cookies[c.Name] = c.Value
if c.Name == "unb" {
sess.unb = c.Value
}
}
sess.mu.Unlock()
}
// 如果还没 unb 且没有浏览器刷新器,再访问 mtop token API 触发(有时需要额外请求)。
// 有浏览器刷新器时直接走浏览器路径,避免在风控场景中重复纯 HTTP 请求。
if sess.unb == "" && m.browser == nil {
state = sess.snapshot()
if state.unb == "" && browser == nil {
m.logger.Info("首次访问未拿到 unb,尝试 mtop token API", "session_id", sessionID)
if err := m.getMH5TK(ctx, sess); err != nil {
m.logger.Warn("mtop token API 失败", "err", err)
}
}
m.logger.Info("验证完成,提取 cookie", "session_id", sessionID, "cookie_count", len(sess.cookies), "has_unb", sess.unb != "")
if sess.unb != "" {
state = sess.snapshot()
m.logger.Info("验证完成,提取 cookie", "session_id", sessionID, "cookie_count", len(state.cookies), "has_unb", state.unb != "")
if state.unb != "" {
sess.mu.Lock()
sess.Status = "success"
m.logger.Info("纯 HTTP 提取 cookie 成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb))
return cookieMarshal(sess.cookies), sess.unb, nil
sess.mu.Unlock()
m.logger.Info("纯 HTTP 提取 cookie 成功", "session_id", sessionID, "account_hash", logsafe.ID(state.unb))
return cookieMarshal(state.cookies), state.unb, nil
}
// 纯 HTTP 拿不到 unb(闲鱼真实 cookie 由页面 JS 异步下发),
// 风控验证后的 cookie 提取必须依赖浏览器。
if m.browser == nil {
if browser == nil {
return "", "", fmt.Errorf("风控验证后的 cookie 提取需要浏览器支持(请勿使用 -no-browser 启动)")
}
m.logger.Info("纯 HTTP 未拿到 unb,调用浏览器提取", "session_id", sessionID)
realCookies, browserUNB, err := m.browser(ctx, cookieMarshal(sess.cookies), sess.verificationURL, nil)
realCookies, browserUNB, err := browser(ctx, cookieMarshal(state.cookies), state.verificationURL, nil)
if err != nil {
m.logger.Error("浏览器提取失败", "err", err)
return "", "", fmt.Errorf("浏览器提取 cookie 失败: %w", err)
@@ -453,18 +548,22 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
if len(parsedCookies) == 0 {
return "", "", fmt.Errorf("浏览器提取 cookie 失败: 未返回有效 cookie")
}
sess.mu.Lock()
sess.cookies = parsedCookies
sess.unb = browserUNB
if sess.unb == "" {
sess.unb = sess.cookies["unb"]
}
if sess.unb == "" {
sess.mu.Unlock()
return "", "", fmt.Errorf("验证后仍未获取到 unb,可能验证未完成或临时 cookie 已失效")
}
m.logger.Info("浏览器提取成功", "session_id", sessionID, "account_hash", logsafe.ID(sess.unb), "cookie_count", len(sess.cookies))
sess.Status = "success"
return cookieMarshal(sess.cookies), sess.unb, nil
finalCookies := cloneCookieMap(sess.cookies)
finalUNB := sess.unb
sess.mu.Unlock()
m.logger.Info("浏览器提取成功", "session_id", sessionID, "account_hash", logsafe.ID(finalUNB), "cookie_count", len(finalCookies))
return cookieMarshal(finalCookies), finalUNB, nil
}
// parseCookieStr 把 "k=v; k2=v2" 解析回 map。
@@ -493,11 +592,13 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
}
// 合并 Set-Cookie。
sess.mu.Lock()
for _, c := range resp.Cookies() {
sess.cookies[c.Name] = c.Value
}
mH5TK := sess.cookies["_m_h5_tk"]
sess.mu.Unlock()
token := ""
if parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 {
token = parts[0]
@@ -534,9 +635,11 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
}
// 更新 cookie。
sess.mu.Lock()
for _, c := range resp2.Cookies() {
sess.cookies[c.Name] = c.Value
}
sess.mu.Unlock()
return nil
}
@@ -559,7 +662,9 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
m.setHeaders(req)
// 带上已有 cookie。
sess.mu.RLock()
cookieStr := cookieMarshal(sess.cookies)
sess.mu.RUnlock()
if cookieStr != "" {
req.Header.Set("Cookie", cookieStr)
}
@@ -598,21 +703,24 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
strParams[k] = fmt.Sprintf("%v", v)
}
strParams["umidTag"] = "SERVER"
sess.mu.Lock()
sess.params = strParams
sess.mu.Unlock()
return strParams, nil
}
// pollQRCodeStatus 轮询二维码状态。
func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Response, error) {
form := url.Values{}
for k, v := range sess.params {
state := sess.snapshot()
for k, v := range state.params {
form.Set(k, v)
}
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiScanStatus, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
m.setHeaders(req)
cookieStr := cookieMarshal(sess.cookies)
cookieStr := cookieMarshal(state.cookies)
if cookieStr != "" {
req.Header.Set("Cookie", cookieStr)
}
+45
View File
@@ -3,12 +3,14 @@ package qrlogin
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
)
@@ -23,6 +25,35 @@ func TestReadQRBodyRejectsOversizedResponse(t *testing.T) {
}
}
func TestSessionStatusConcurrentSnapshot(t *testing.T) {
m := NewManager(nil)
sess := testVerificationSession()
m.sessions["s1"] = sess
var wg sync.WaitGroup
for worker := 0; worker < 8; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
for i := 0; i < 500; i++ {
if worker%2 == 0 {
sess.mu.Lock()
sess.verificationScreenshot = fmt.Sprintf("shot-%d-%d", worker, i)
sess.faceQRURL = fmt.Sprintf("qr-%d-%d", worker, i)
sess.Status = "verification_required"
sess.mu.Unlock()
} else {
status := m.GetSessionStatus("s1")
if status["status"] == "not_found" {
t.Error("existing session reported not_found")
return
}
}
}
}(worker)
}
wg.Wait()
}
func TestCompleteVerificationRequiresBrowserWhenHTTPMissingUNB(t *testing.T) {
m := NewManager(nil)
m.sessions["s1"] = testVerificationSession()
@@ -36,6 +67,20 @@ func TestCompleteVerificationRequiresBrowserWhenHTTPMissingUNB(t *testing.T) {
}
}
func TestCompleteVerificationReturnsCompletedSessionWithoutAnotherRequest(t *testing.T) {
m := NewManager(nil)
sess := testVerificationSession()
sess.Status = "success"
sess.unb = "completed-account"
sess.cookies["unb"] = sess.unb
m.sessions["s1"] = sess
cookies, unb, err := m.CompleteVerification(context.Background(), "s1")
if err != nil || unb != "completed-account" || !strings.Contains(cookies, "unb=completed-account") {
t.Fatalf("completed session: cookies=%q unb=%q err=%v", cookies, unb, err)
}
}
func TestCompleteVerificationBrowserSuccess(t *testing.T) {
m := NewManager(nil)
m.sessions["s1"] = testVerificationSession()
+18 -16
View File
@@ -248,9 +248,9 @@ func TestGenerateQRCodeSuccess(t *testing.T) {
"content": map[string]any{
"success": true,
"data": map[string]any{
"t": 1717000000000,
"ck": "ck_value",
"codeContent": "https://login/qr?token=xyz",
"t": 1717000000000,
"ck": "ck_value",
"codeContent": "https://login/qr?token=xyz",
},
},
}
@@ -665,27 +665,24 @@ func TestMonitorQRStatusVerificationRequiredTriggersBrowser(t *testing.T) {
// 等待浏览器 goroutine 完成。
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
m.mu.Lock()
st := sess.Status
m.mu.Unlock()
st := sess.snapshot().status
if st == "success" {
break
}
time.Sleep(50 * time.Millisecond)
}
m.mu.Lock()
defer m.mu.Unlock()
if browserCalled.Load() == 0 {
t.Fatal("浏览器刷新器未被调用")
if browserCalled.Load() != 1 {
t.Fatalf("浏览器刷新器应只调用一次,got %d", browserCalled.Load())
}
if sess.Status != "success" {
t.Fatalf("状态异常: %s", sess.Status)
state := sess.snapshot()
if state.status != "success" {
t.Fatalf("状态异常: %s", state.status)
}
if sess.unb != "777" {
t.Fatalf("unb 异常: %q", sess.unb)
if state.unb != "777" {
t.Fatalf("unb 异常: %q", state.unb)
}
if sess.verificationScreenshot != "data:image/png;base64,shot" {
t.Fatalf("screenshot 未保存: %q", sess.verificationScreenshot)
if state.verificationScreenshot != "data:image/png;base64,shot" {
t.Fatalf("screenshot 未保存: %q", state.verificationScreenshot)
}
}
@@ -704,7 +701,9 @@ func TestMonitorQRStatusMissingSession(t *testing.T) {
func TestMonitorQRStatusInvalidJSONBody(t *testing.T) {
hc := &handlerChain{}
var requests atomic.Int64
hc.handle("/newlogin/qrcode/query.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
_, _ = w.Write([]byte(`not-json`))
}))
m, _, _ := newStubbedManager(t, hc)
@@ -720,6 +719,9 @@ func TestMonitorQRStatusInvalidJSONBody(t *testing.T) {
if sess.Status != "waiting" {
t.Fatalf("解析失败期间不应改状态: %s", sess.Status)
}
if requests.Load() > 2 {
t.Fatalf("解析失败不应无间隔忙轮询,requests=%d", requests.Load())
}
}
func TestMonitorQRStatusCtxCancelled(t *testing.T) {
+25 -13
View File
@@ -31,8 +31,8 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
m.mu.Unlock()
return fmt.Errorf("会话不存在")
}
initialCookies := cloneCookieMap(sess.cookies)
m.mu.Unlock()
initialCookies := sess.snapshot().cookies
if len(initialCookies) == 0 {
return fmt.Errorf("无扫码临时 cookie")
}
@@ -69,12 +69,15 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
}
m.mu.Lock()
if s := m.sessions[sessionID]; s != nil {
s := m.sessions[sessionID]
m.mu.Unlock()
if s != nil {
s.mu.Lock()
s.faceQRContent = faceContent
s.faceQRURL = faceQRURL
s.Status = "verification_required"
s.mu.Unlock()
}
m.mu.Unlock()
m.logger.Info("人脸验证二维码已生成,等待用户手机扫码", "session_id", sessionID)
ivCheckURL, err := m.waitFaceVerification(ctx, client, sessionID, htoken)
@@ -96,12 +99,15 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
}
m.mu.Lock()
if s := m.sessions[sessionID]; s != nil {
s = m.sessions[sessionID]
m.mu.Unlock()
if s != nil {
s.mu.Lock()
s.cookies = finalCookies
s.unb = finalCookies["unb"]
s.Status = "success"
s.mu.Unlock()
}
m.mu.Unlock()
m.logger.Info("人脸验证登录成功", "session_id", sessionID, "account_hash", logsafe.ID(finalCookies["unb"]))
return nil
}
@@ -109,7 +115,8 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
// fallbackBrowserVerification 保留旧浏览器验证作为协议变化时的兜底。
// 主路径不再截图展示,只有 API 链路失败且浏览器可用时才尝试。
func (m *Manager) fallbackBrowserVerification(ctx context.Context, sessionID, verificationURL string) {
if m.browser == nil {
browser := m.browserRefresher()
if browser == nil {
return
}
m.mu.Lock()
@@ -118,20 +125,23 @@ func (m *Manager) fallbackBrowserVerification(ctx context.Context, sessionID, ve
m.mu.Unlock()
return
}
cookieStr := cookieMarshal(sess.cookies)
m.mu.Unlock()
cookieStr := cookieMarshal(sess.snapshot().cookies)
onScreenshot := func(dataURL string) {
m.mu.Lock()
if s, ok := m.sessions[sessionID]; ok {
s.verificationScreenshot = dataURL
}
s, ok := m.sessions[sessionID]
m.mu.Unlock()
if ok {
s.mu.Lock()
s.verificationScreenshot = dataURL
s.mu.Unlock()
}
}
realCookies, unb, err := m.browser(ctx, cookieStr, verificationURL, onScreenshot)
realCookies, unb, err := browser(ctx, cookieStr, verificationURL, onScreenshot)
m.mu.Lock()
defer m.mu.Unlock()
s, ok := m.sessions[sessionID]
m.mu.Unlock()
if !ok {
return
}
@@ -139,6 +149,8 @@ func (m *Manager) fallbackBrowserVerification(ctx context.Context, sessionID, ve
m.logger.Error("浏览器验证兜底失败", "session_id", sessionID, "err", err)
return
}
s.mu.Lock()
defer s.mu.Unlock()
s.cookies = parseCookieStr(realCookies)
s.unb = unb
if s.unb == "" {
@@ -191,8 +203,8 @@ func (m *Manager) waitFaceVerification(ctx context.Context, client *http.Client,
for {
m.mu.Lock()
sess := m.sessions[sessionID]
expired := sess == nil || sess.isExpired()
m.mu.Unlock()
expired := sess == nil || sess.isExpired()
if expired {
return "", fmt.Errorf("人脸验证超时或会话已过期")
}
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
set -eu
compose="docker compose -f docker-compose.functional.yml"
$compose up -d --build mysql postgres
$compose build seed-mysql frontend-test go-vet go-lint go-test
$compose run --rm frontend-test
$compose run --rm go-vet
$compose run --rm go-lint
$compose run --rm go-test
$compose run --rm dbverify-mysql
$compose run --rm dbverify-postgres
$compose up -d --build app-mysql app-postgres
$compose run --rm --no-deps functional-test
mysql_before="$($compose exec -T mysql mysql -uroot -pxianyu_root_password -Nse "SELECT CONCAT((SELECT COUNT(*) FROM xianyu.users WHERE username='docker_fixture'), ':', (SELECT COUNT(*) FROM xianyu.cards c JOIN xianyu.users u ON u.id=c.user_id WHERE u.username='docker_fixture'), ':', (SELECT COUNT(*) FROM xianyu.orders o JOIN xianyu.cookies c ON c.id=o.cookie_id JOIN xianyu.users u ON u.id=c.user_id WHERE u.username='docker_fixture'))")"
postgres_before="$($compose exec -T postgres psql -U xianyu -d xianyu -Atc "SELECT (SELECT COUNT(*) FROM users WHERE username='docker_fixture') || ':' || (SELECT COUNT(*) FROM cards c JOIN users u ON u.id=c.user_id WHERE u.username='docker_fixture') || ':' || (SELECT COUNT(*) FROM orders o JOIN cookies c ON c.id=o.cookie_id JOIN users u ON u.id=c.user_id WHERE u.username='docker_fixture')")"
$compose restart mysql postgres
$compose up -d --wait mysql postgres
$compose restart app-mysql app-postgres
$compose up -d --wait --no-deps app-mysql app-postgres
mysql_after="$($compose exec -T mysql mysql -uroot -pxianyu_root_password -Nse "SELECT CONCAT((SELECT COUNT(*) FROM xianyu.users WHERE username='docker_fixture'), ':', (SELECT COUNT(*) FROM xianyu.cards c JOIN xianyu.users u ON u.id=c.user_id WHERE u.username='docker_fixture'), ':', (SELECT COUNT(*) FROM xianyu.orders o JOIN xianyu.cookies c ON c.id=o.cookie_id JOIN xianyu.users u ON u.id=c.user_id WHERE u.username='docker_fixture'))")"
postgres_after="$($compose exec -T postgres psql -U xianyu -d xianyu -Atc "SELECT (SELECT COUNT(*) FROM users WHERE username='docker_fixture') || ':' || (SELECT COUNT(*) FROM cards c JOIN users u ON u.id=c.user_id WHERE u.username='docker_fixture') || ':' || (SELECT COUNT(*) FROM orders o JOIN cookies c ON c.id=o.cookie_id JOIN users u ON u.id=c.user_id WHERE u.username='docker_fixture')")"
test "${mysql_before%%:*}" = "1"
test "${postgres_before%%:*}" = "1"
test "$mysql_after" = "$mysql_before"
test "$postgres_after" = "$postgres_before"
$compose run --rm --no-deps functional-test
printf 'MySQL 8 and PostgreSQL 17 persistent-volume tests passed\n'
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
test_instance() {
name="$1"
base_url="$2"
cookie_file="/tmp/${name}.cookies"
curl -fsS "${base_url}/health" | grep -q '"status":"ok"'
curl -fsS -c "$cookie_file" -H 'Content-Type: application/json' \
-d '{"username":"docker_fixture","password":"docker_fixture_password"}' \
"${base_url}/login" | grep -q '"success":true'
curl -fsS -b "$cookie_file" "${base_url}/dashboard/stats" | grep -q '"total_cookies":1'
curl -fsS -b "$cookie_file" "${base_url}/analytics/orders" | grep -q '"revenue_stats"'
curl -fsS -b "$cookie_file" "${base_url}/cards" | grep -q '\[Docker测试\]'
admin_status="$(curl -sS -o /tmp/${name}-admin.json -w '%{http_code}' -b "$cookie_file" "${base_url}/admin/stats")"
test "$admin_status" = "403"
printf '%s functional test passed\n' "$name"
}
test_instance mysql http://app-mysql:8080
test_instance postgres http://app-postgres:8080