Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c742f5e7f | ||
|
|
5f4d199231 | ||
|
|
50d09eb47a | ||
|
|
6e678999fc | ||
|
|
f68c8b8add | ||
|
|
cef2ca92c4 | ||
|
|
090802e25d | ||
|
|
2c6385374a | ||
|
|
d0569fb1ef | ||
|
|
90b6e4f5ce | ||
|
|
9e4e4bcee9 | ||
|
|
8fdc25483f | ||
|
|
b98c4edf68 | ||
|
|
fd30a0d17a | ||
|
|
7fd11106af | ||
|
|
968c66469d | ||
|
|
085c302be6 | ||
|
|
9705402d1d | ||
|
|
adbec2b9b0 | ||
|
|
687e5156af | ||
|
|
051bf6eb68 | ||
|
|
6cd3ff7d60 | ||
|
|
614bae4b2b | ||
|
|
16b2b84fa2 | ||
|
|
0f77607d57 | ||
|
|
c819810b1b | ||
|
|
fccb5eebc8 | ||
|
|
a5a8aa9b8b | ||
|
|
6a9a684e5e |
No files matched your search
+4
-4
@@ -1,5 +1,5 @@
|
||||
# 复制为 .env 后再填写。不要提交包含真实密钥的 .env。
|
||||
COMPOSE_PROJECT_NAME=xianyu
|
||||
COMPOSE_PROJECT_NAME=ydisks-xianyu-helper
|
||||
|
||||
# PostgreSQL 17
|
||||
POSTGRES_IMAGE=postgres:17-trixie
|
||||
@@ -9,8 +9,8 @@ POSTGRES_PASSWORD=请替换为高强度数据库密码
|
||||
# 密码含有特殊字符时,必须先进行 URL 编码。
|
||||
DATABASE_URL=postgres://xianyu:请替换为URL编码后的数据库密码@postgres:5432/xianyu?sslmode=disable
|
||||
|
||||
# 应用
|
||||
XIANYU_IMAGE=xianyu-go:debian13-amd64
|
||||
# 应用:默认 compose.yml 仅拉取 GHCR 镜像,不会在服务器上构建源码。
|
||||
XIANYU_IMAGE=ghcr.io/christ9038/ydisks-xianyu-helper:latest
|
||||
XIANYU_DATA_KEY=请替换为稳定且足够长的随机密钥
|
||||
XIANYU_BIND_ADDRESS=0.0.0.0
|
||||
XIANYU_HTTP_PORT=8080
|
||||
@@ -20,5 +20,5 @@ LOG_LEVEL=info
|
||||
LOG_FORMAT=json
|
||||
BROWSER_HEADLESS=true
|
||||
|
||||
# 仅在执行 init-admin profile 时使用。
|
||||
# 首次 docker compose up -d 时自动创建 admin;后续重启不会重置密码。
|
||||
XIANYU_ADMIN_PASSWORD=请替换为管理员密码
|
||||
@@ -0,0 +1,67 @@
|
||||
name: 构建并发布 Docker 镜像
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
concurrency:
|
||||
group: docker-publish-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: 发布多架构镜像
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 配置 QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: 配置 Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: 登录 GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 生成小写镜像名称
|
||||
id: image
|
||||
shell: bash
|
||||
run: echo "name=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: 生成镜像标签
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ steps.image.outputs.name }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,format=long
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: 构建并推送镜像
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.debian13
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
@@ -0,0 +1,48 @@
|
||||
name: 同步 GitHub Wiki
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
concurrency:
|
||||
group: sync-wiki-main
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: 同步仓库 Wiki 页面
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出主分支文档
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
|
||||
- name: 克隆 GitHub Wiki 仓库
|
||||
env:
|
||||
WIKI_REPOSITORY: https://x-access-token:${{ github.token }}@github.com/Christ9038/Ydisks-Xianyu-Helper.wiki.git
|
||||
run: git clone "$WIKI_REPOSITORY" wiki
|
||||
|
||||
- name: 镜像 Wiki 页面
|
||||
run: rsync -a --delete --exclude='.git' docs/wiki/ wiki/
|
||||
|
||||
- name: 提交并推送 Wiki
|
||||
working-directory: wiki
|
||||
env:
|
||||
GIT_AUTHOR_NAME: github-actions[bot]
|
||||
GIT_AUTHOR_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com
|
||||
GIT_COMMITTER_NAME: github-actions[bot]
|
||||
GIT_COMMITTER_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com
|
||||
run: |
|
||||
git add --all
|
||||
if git diff --cached --quiet; then
|
||||
echo "Wiki 内容没有变化。"
|
||||
exit 0
|
||||
fi
|
||||
git commit -m "docs: 同步项目 Wiki"
|
||||
git push origin HEAD:master
|
||||
@@ -21,7 +21,7 @@ The active application contains:
|
||||
## Common commands
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper
|
||||
|
||||
make build # go build ./cmd/server
|
||||
make test # go test ./...
|
||||
@@ -74,7 +74,7 @@ go test ./internal/db -run TestMultiDB -v
|
||||
Build the frontend:
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper/frontend
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
@@ -2,7 +2,7 @@ FROM golang:1.26-trixie AS go-toolchain
|
||||
|
||||
# 复用生产运行镜像中已经安装并验证过的 Chromium、Node 和 Playwright driver,
|
||||
# 只补 Go 工具链来执行真实浏览器集成测试。
|
||||
FROM xianyu-go:functional
|
||||
FROM ydisks-xianyu-helper:functional
|
||||
ENV PATH=/usr/local/go/bin:${PATH}
|
||||
ENV CGO_ENABLED=0
|
||||
WORKDIR /src
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,4 +1,4 @@
|
||||
# xianyu-go 常用命令入口。详见各 target 注释。
|
||||
# Ydisks-Xianyu-Helper 常用命令入口。详见各 target 注释。
|
||||
|
||||
GO ?= go
|
||||
GOLANGCI_LINT ?= golangci-lint
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
Ydisks闲鱼助手 / Ydisks-Xianyu-Helper
|
||||
Copyright 2026 Christ9038
|
||||
|
||||
This product includes software developed by Christ9038 and is licensed under
|
||||
the Apache License, Version 2.0.
|
||||
@@ -1,264 +1,606 @@
|
||||
# 闲鱼管家
|
||||
# Ydisks闲鱼助手
|
||||
|
||||
这是当前活跃版本:Go 后端 + React 前端。后续功能迭代均在此目录进行:
|
||||

|
||||
|
||||
```text
|
||||
xianyu-go/
|
||||
cmd/
|
||||
server/ 服务入口、依赖装配、管理员非交互初始化
|
||||
init-admin/ 交互式管理员初始化 CLI
|
||||
dbverify/ SQLite/MySQL/Postgres 迁移与 CRUD 验证
|
||||
dbseed/ Docker 功能测试所需的脱敏数据种子工具
|
||||
spike/ debug/tools 构建标签下的协议链路探针
|
||||
internal/
|
||||
account/ 已启用账号监督与生命周期管理
|
||||
adapter/ engine/automation 与浏览器、通知器的接线层
|
||||
auth/ 管理端会话认证与安全 Cookie
|
||||
automation/ 发货、评价赠送、邀评自动化与调度器
|
||||
browser/ Playwright/Chromium 登录、风控验证、订单抓取
|
||||
db/ 三种数据库方言、模型、存储与嵌入式迁移
|
||||
engine/ 单账号运行时、消息处理、回复和发货行为
|
||||
logging/ 进程级结构化日志配置
|
||||
logsafe/ 敏感 ID 与 URL 的日志脱敏
|
||||
netguard/ 出站网络目标校验与 DNS rebinding 防护
|
||||
notify/ 账号告警和通知渠道
|
||||
renewal/ 登录态续期调度与冷却控制
|
||||
server/ chi HTTP API、鉴权和 SPA 服务
|
||||
webui/static/ 前端构建产物,由 Go 二进制嵌入
|
||||
xianyu/ MTOP、WebSocket、扫码登录和协议实现
|
||||
frontend/ 当前活跃 React/Vite 前端源码
|
||||
docs/ 运行、功能与不可变行为规范
|
||||
scripts/ Docker、持久化和功能回归脚本
|
||||
data/ 本地运行数据(不作为源码维护)
|
||||
```
|
||||
基于 Go 与 React 构建的闲鱼多账号管理、消息回复与自动发货系统
|
||||
|
||||
目录职责以根目录 `AGENTS.md` 为准。滑块认证属于冻结逻辑,完整契约见
|
||||
[`docs/slider-captcha-frozen-spec.md`](docs/slider-captcha-frozen-spec.md);没有用户在当前任务中的明确授权,不得修改其实现、测试或任何会间接改变其行为的调用链。
|
||||
[](go.mod)
|
||||
[](frontend/package.json)
|
||||
[](compose.yml)
|
||||
[](https://github.com/Christ9038/Ydisks-Xianyu-Helper/actions/workflows/docker-publish.yml)
|
||||
|
||||
## 数据库支持
|
||||
[功能特性](#功能特性) · [快速开始](#快速开始) · [配置说明](#配置说明) ·
|
||||
[Docker 部署](#docker-部署) · [开发指南](#开发指南) · [开源协议](#开源协议)
|
||||
|
||||
支持三种数据库,由连接 URL 的 scheme 决定:
|
||||
操作手册见仓库内的 [GitHub Wiki 文档](docs/wiki/Home.md):包含数据库选择、账号接入、
|
||||
批量铺货、自动化发货、AI、通知和运维流程。
|
||||
|
||||
| scheme | 说明 |
|
||||
> [!IMPORTANT]
|
||||
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或
|
||||
> 授权关系。请仅在遵守当地法律法规、闲鱼平台规则及账号授权范围的前提下使用。
|
||||
> 使用自动化能力可能触发平台风控,请自行评估风险并妥善保护账号凭证。
|
||||
|
||||
## 项目简介
|
||||
|
||||
Ydisks闲鱼助手是一个面向闲鱼卖家的自托管管理系统。它将账号运行、即时消息、订单、
|
||||
商品、卡密库存、自动化规则、AI 回复和异常通知整合到同一个 Web 管理后台,适合需要
|
||||
同时维护多个闲鱼账号或交付虚拟商品的个人与小型团队。
|
||||
|
||||
项目采用 Go 语言实现闲鱼登录、Cookie 续期、MTOP 请求和 WebSocket 消息链路。
|
||||
扫码登录、人脸验证流程、消息连接、凭证更新和绝大部分业务逻辑均由 Go 客户端完成。
|
||||
使用 Chromium 处理必须依赖浏览器环境的滑块风控。
|
||||
|
||||
### 与 Ydisks 网盘拉新助手协同使用
|
||||
|
||||
如果你通过网盘资料、教程包或数字资源做闲鱼推广,推荐搭配
|
||||
[Ydisks 网盘拉新助手](https://www.ydisks.com) 使用:先为不同商品、渠道或推广账号
|
||||
创建独立短链,再在 Ydisks 控制台查看短链与目标页面的 PV、UV、趋势、排行及渠道/账号报表。
|
||||
这样,Ydisks 负责识别“链接从哪里带来访问与转化线索”,Ydisks闲鱼助手负责承接账号消息、
|
||||
订单和自动发货,帮助你把投放复盘与日常交付放进一套更清晰的运营流程。
|
||||
|
||||
Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名,适用于网盘拉新和推广投放场景;
|
||||
可从 [Ydisks 网盘拉新助手使用文档](https://docs.ydisks.com/guide/quick-start) 开始创建推广链接并查看数据。
|
||||
|
||||
|
||||
### 适用场景
|
||||
|
||||
- 多个闲鱼账号的统一在线状态与消息管理
|
||||
- 数字商品、兑换码、链接或图片内容的自动交付
|
||||
- 付款后发货、评价赠品、超时求评价等自动化流程
|
||||
- 商品与订单同步、单商品发布及支持逐行/默认类目、自动识别和最终兜底的表格批量铺货
|
||||
- 接入 OpenAI 兼容接口实现可控的 AI 客服回复
|
||||
- 账号掉线、风控、续期和发货结果的多渠道通知
|
||||
|
||||
## 功能特性
|
||||
|
||||
| 模块 | 能力 |
|
||||
| --- | --- |
|
||||
| `sqlite://<path>` 或纯路径 | 纯 Go modernc.org/sqlite,WAL + foreign_keys(默认,本地开发) |
|
||||
| `mysql://<dsn>` | go-sql-driver/mysql(生产 / Docker 外置库) |
|
||||
| `postgres://<dsn>` | jackc/pgx(生产 / Docker 外置库) |
|
||||
| 账号管理 | 多账号启停、扫码登录、密码登录、资料刷新、在线状态、登录审计与备注管理 |
|
||||
| 凭证续期 | Cookie/token 定时续期、WebSocket 凭证更新、失效恢复、冷却与失败停用 |
|
||||
| 即时消息 | 闲鱼 WebSocket 长连接、消息收发、关键词回复、默认回复及仅回复一次 |
|
||||
| 自动化中心 | 付款后自动发货、评价后赠品、超时未评价提醒、失败任务恢复与幂等检查点 |
|
||||
| 卡密库存 | 文本、批量卡密和图片三种交付类型,库存追加、批量导入、规格与延迟发送 |
|
||||
| 商品管理 | 商品同步、手工关联、单商品发布、CSV + ZIP 批量铺货、关键词获取默认类目、逐行类目优先、自动识别与“电子资料”最终兜底、任务恢复与结果导出 |
|
||||
| 订单管理 | 订单同步、插入、编辑、平台发货、补发卡密、仅确认发货及异常状态处理 |
|
||||
| AI 回复 | OpenAI 兼容 API、模型发现、自定义提示词、议价轮次和让价范围控制 |
|
||||
| 数据看板 | 活跃账号、订单、营收、库存、商品销量与金额统计 |
|
||||
| 通知告警 | Bark、钉钉、飞书、企业微信、Telegram、邮件和自定义 Webhook |
|
||||
| 数据存储 | SQLite、MySQL、PostgreSQL,内置按方言执行的 Goose 数据库迁移 |
|
||||
| 安全能力 | 管理端会话、敏感字段 AES-256-GCM 加密、日志脱敏和出站地址校验 |
|
||||
| 容器部署 | PostgreSQL 17、健康检查、持久化卷、GHCR amd64/arm64 多架构镜像 |
|
||||
|
||||
迁移用 goose 嵌入式执行,按方言分目录 `internal/db/migrations/{sqlite,mysql,postgres}`。
|
||||
批量铺货的类目优先级为:表格当前行指定类目 > 上传页通过关键词获取的默认类目 > 闲鱼按标题、描述和图片自动识别 > “电子资料”最终兜底。模板类目字段可全部留空;如填写,类目 ID、名称和频道类目 ID 必须同时填写,淘宝类目 ID 按闲鱼响应提供的值填写。
|
||||
|
||||
## 首次运行
|
||||
## 系统架构
|
||||
|
||||
### 1. 安装前端依赖并构建
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
npm install
|
||||
npm run build
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI["React 管理后台"] --> API["Go / chi HTTP API"]
|
||||
API --> Store["SQLite / MySQL / PostgreSQL"]
|
||||
API --> Manager["账号管理器"]
|
||||
Manager --> Engine["单账号运行时"]
|
||||
Engine --> WS["闲鱼 WebSocket"]
|
||||
Engine --> MTOP["闲鱼 MTOP"]
|
||||
Engine --> Automation["自动化中心"]
|
||||
Automation --> Notify["通知渠道"]
|
||||
Engine -. "仅指纹与滑块风控" .-> Chromium["Playwright / Chromium"]
|
||||
```
|
||||
|
||||
构建产物会写入:
|
||||
核心职责划分:
|
||||
|
||||
```text
|
||||
xianyu-go/internal/webui/static/
|
||||
```
|
||||
- `internal/xianyu`:登录协议、Cookie、MTOP、WebSocket 和消息协议
|
||||
- `internal/engine`:单账号生命周期、消息处理、回复与交付行为
|
||||
- `internal/automation`:发货、评价赠品、求评价和任务调度
|
||||
- `internal/browser`:Chromium 指纹读取与滑块验证
|
||||
- `internal/db`:多数据库访问、敏感字段加密和嵌入式迁移
|
||||
- `internal/server`:HTTP API、管理端鉴权和前端静态资源
|
||||
|
||||
### 2. 初始化管理员
|
||||
## 页面预览
|
||||
|
||||

|
||||
|
||||
## 快速开始
|
||||
|
||||
### 方式一:Docker Compose(推荐)
|
||||
|
||||
适用于 Linux x86_64、Linux ARM64 和 Apple Silicon。需要 Docker Engine 或
|
||||
Docker Desktop,并使用 Docker Compose v2。
|
||||
|
||||
Docker 部署会使用容器内 Chromium 的原生 Linux 指纹执行官网静默续期;续期是否成功由闲鱼响应决定,不会因宿主系统是 Linux 而跳过。
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go run ./cmd/init-admin -db data/xianyu_data.db
|
||||
git clone https://github.com/Christ9038/Ydisks-Xianyu-Helper.git
|
||||
cd Ydisks-Xianyu-Helper
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
也可以通过服务入口非交互初始化(适合脚本/Docker):
|
||||
编辑 `.env`,至少修改以下配置:
|
||||
|
||||
```dotenv
|
||||
POSTGRES_DB=xianyu
|
||||
POSTGRES_USER=xianyu
|
||||
POSTGRES_PASSWORD=替换为高强度密码
|
||||
DATABASE_URL=postgres://xianyu:替换为URL编码后的数据库密码@postgres:5432/xianyu?sslmode=disable
|
||||
XIANYU_DATA_KEY=替换为长期固定的随机密钥
|
||||
XIANYU_ADMIN_PASSWORD=替换为管理员密码
|
||||
```
|
||||
|
||||
推荐使用以下命令生成随机值:
|
||||
|
||||
```bash
|
||||
openssl rand -hex 24 # 适合作为 POSTGRES_PASSWORD,连接串无需额外 URL 编码
|
||||
openssl rand -base64 48 # 适合作为 XIANYU_DATA_KEY
|
||||
```
|
||||
|
||||
配置完成后,只需一条命令即可拉取 GHCR 镜像、启动 PostgreSQL,并在首次部署时自动创建
|
||||
管理员:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
浏览器访问 `http://localhost:8080`,使用用户名 `admin` 和 `.env` 中的
|
||||
`XIANYU_ADMIN_PASSWORD` 登录。
|
||||
|
||||
> GHCR 镜像公开时可以匿名拉取。若镜像仍为私有,请先执行
|
||||
> `docker login ghcr.io -u Christ9038`,并使用具有 `read:packages` 权限的
|
||||
> Personal Access Token 登录。
|
||||
|
||||
### 方式二:从源码运行
|
||||
|
||||
环境要求:
|
||||
|
||||
- Go 1.26.4 或兼容版本
|
||||
- Node.js 22 与 npm
|
||||
- Chromium 运行所需的系统依赖
|
||||
- 默认可直接使用 SQLite,无需额外数据库服务
|
||||
|
||||
构建前端:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Christ9038/Ydisks-Xianyu-Helper.git
|
||||
cd Ydisks-Xianyu-Helper
|
||||
npm --prefix frontend ci
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
初始化管理员:
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
go run ./cmd/server \
|
||||
-init-admin \
|
||||
-db data/xianyu_data.db \
|
||||
-admin-password '你的密码'
|
||||
-admin-password '请替换为管理员密码'
|
||||
```
|
||||
|
||||
`-admin-password` 也可用环境变量 `XIANYU_ADMIN_PASSWORD` 传入。
|
||||
|
||||
### 3. 启动服务
|
||||
启动服务:
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
```
|
||||
|
||||
使用 MySQL / Postgres 时改用 `-db-url` 或 `DATABASE_URL`:
|
||||
首次启动会准备 Playwright 运行环境和 Chromium;下载速度取决于当前网络。启动完成后
|
||||
访问 `http://localhost:8080`。
|
||||
|
||||
如当前环境无法安装 Chromium,可以使用 `-no-browser` 启动:
|
||||
|
||||
```bash
|
||||
# MySQL(DSN 需含 multiStatements=true,工具会自动补齐)
|
||||
go run ./cmd/server -db-url "mysql://user:pass@tcp(host:3306)/dbname" -addr :8080
|
||||
|
||||
# Postgres
|
||||
DATABASE_URL="postgres://user:pass@host:5432/dbname?sslmode=disable" go run ./cmd/server -addr :8080
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser
|
||||
```
|
||||
|
||||
浏览器访问:
|
||||
此模式仍可运行管理后台,但浏览器指纹读取和滑块风控处理不可用,不建议用于需要登录
|
||||
和长期运行账号的生产环境。
|
||||
|
||||
## 初次使用
|
||||
|
||||
1. 使用管理员账号登录管理后台。
|
||||
2. 进入“账号管理”,通过闲鱼 App 扫描二维码完成账号授权。
|
||||
3. 如平台触发风控,根据页面提示在手机端完成人脸或安全验证。
|
||||
4. 等待账号状态变为在线,再同步商品和订单。
|
||||
5. 在“卡密库存”创建交付内容。
|
||||
6. 在“自动化规则”将闲鱼商品与卡密、规格和触发条件关联。
|
||||
7. 按需配置关键词回复、默认回复、AI 回复和通知渠道。
|
||||
|
||||
扫码登录是推荐方式。密码登录适合已有明确需求的环境,但更容易触发平台安全校验。
|
||||
无论使用哪种方式,都不要把 Cookie、密码、二维码或人脸验证地址分享给不可信第三方。
|
||||
|
||||
## 配置说明
|
||||
|
||||
配置分为三层:进程环境变量、命令行参数和管理后台设置。数据库连接优先级为:
|
||||
|
||||
```text
|
||||
http://localhost:8080
|
||||
DATABASE_URL > -db-url > -db
|
||||
```
|
||||
|
||||
不传 `-web` 时,Go 会使用 `internal/webui/static` 中的内置前端资源。
|
||||
### 环境变量
|
||||
|
||||
## 开发模式
|
||||
| 变量 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | 空 | 数据库连接 URL;生产环境推荐 PostgreSQL |
|
||||
| `XIANYU_DATA_KEY` | 空 | 敏感字段加密主密钥;生产环境必须固定并备份 |
|
||||
| `XIANYU_ADMIN_PASSWORD` | 空 | 非交互初始化或重置管理员时使用 |
|
||||
| `XIANYU_UPLOAD_DIR` | `data/uploads` | 批量铺货上传文件与临时资源目录 |
|
||||
| `LOG_LEVEL` | 系统设置或 `info` | `debug`、`info`、`warn`、`error` |
|
||||
| `LOG_FORMAT` | 系统设置或 `text` | `text` 或 `json` |
|
||||
| `BROWSER_HEADLESS` | 按账号设置;Docker 为 `true` | 强制启用或关闭无头 Chromium |
|
||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | 自动发现 | 指定系统 Chromium 可执行文件 |
|
||||
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | 源码 `false` / Docker `true` | 跳过下载 |
|
||||
| `TZ` | 系统时区;Docker 为 `Asia/Shanghai` | 容器和日志时区 |
|
||||
|
||||
后端:
|
||||
Docker Compose 还支持:
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `COMPOSE_PROJECT_NAME` | `ydisks-xianyu-helper` | Compose 项目名及命名卷前缀 |
|
||||
| `POSTGRES_IMAGE` | `postgres:17-trixie` | PostgreSQL 镜像 |
|
||||
| `POSTGRES_DB` | 必填 | 数据库名 |
|
||||
| `POSTGRES_USER` | 必填 | 数据库用户 |
|
||||
| `POSTGRES_PASSWORD` | 必填 | 数据库密码 |
|
||||
| `XIANYU_IMAGE` | `ghcr.io/christ9038/ydisks-xianyu-helper:latest` | 应用镜像与标签 |
|
||||
| `XIANYU_BIND_ADDRESS` | `0.0.0.0` | 应用在宿主机上的绑定地址 |
|
||||
| `XIANYU_HTTP_PORT` | `8080` | 应用在宿主机上的端口 |
|
||||
|
||||
默认 `compose.yml` 直接拉取 GHCR 的 `:latest` 多架构镜像;如需固定版本,请将
|
||||
`XIANYU_IMAGE` 改为 `:main`、版本号或 `:sha-<提交号>` 标签。
|
||||
|
||||
`XIANYU_DATA_KEY` 用于加密 Cookie、账号密码、设备令牌、访问令牌、AI/SMTP 密钥和
|
||||
通知凭证。启用后,服务会自动升级历史明文数据。密钥丢失或更换后,已有加密数据将
|
||||
无法解密,因此必须与数据库备份一起保存。
|
||||
|
||||
### 命令行参数
|
||||
|
||||
| 参数 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `-db` | `data/xianyu_data.db` | SQLite 数据库路径 |
|
||||
| `-db-url` | 空 | `sqlite://`、`mysql://` 或 `postgres://` 连接 URL |
|
||||
| `-addr` | `:8080` | HTTP 监听地址 |
|
||||
| `-web` | 内嵌前端 | 外部前端静态资源目录,目录内需包含 `index.html` |
|
||||
| `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 |
|
||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 |
|
||||
| `-log-level` | 环境变量或系统设置 | 覆盖日志等级 |
|
||||
| `-log-format` | 环境变量或系统设置 | 覆盖日志格式 |
|
||||
| `-v` | `false` | 启用调试日志,等价于未显式配置时使用 debug |
|
||||
| `-init-admin` | `false` | 初始化或重置 `admin` 后退出 |
|
||||
| `-ensure-admin` | `false` | 仅在 `admin` 不存在时初始化;已存在时不重置密码 |
|
||||
| `-admin-email` | `admin@example.com` | 初始化管理员邮箱 |
|
||||
| `-admin-password` | 空 | 初始化管理员密码 |
|
||||
|
||||
### 数据库连接示例
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
# SQLite
|
||||
DATABASE_URL="sqlite://data/xianyu_data.db" ./xianyu-server
|
||||
|
||||
# MySQL;应用会强制补齐 multiStatements=true 和 clientFoundRows=true
|
||||
DATABASE_URL="mysql://user:pass@tcp(127.0.0.1:3306)/xianyu" ./xianyu-server
|
||||
|
||||
# PostgreSQL
|
||||
DATABASE_URL="postgres://user:pass@127.0.0.1:5432/xianyu?sslmode=disable" ./xianyu-server
|
||||
```
|
||||
|
||||
前端开发服务器:
|
||||
每次启动都会自动执行对应数据库方言的嵌入式 Goose 迁移。生产数据库升级前仍建议
|
||||
先完成备份。
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
npm run dev
|
||||
```
|
||||
### 管理后台配置
|
||||
|
||||
访问:
|
||||
以下配置通过 Web 管理后台维护并保存在数据库中:
|
||||
|
||||
- **账号设置**:启停状态、备注、通知渠道绑定和单账号 AI 回复策略
|
||||
- **自动化规则**:触发条件、商品、规格、卡密组、发送数量、延迟和后续动作
|
||||
- **回复规则**:关键词、文本或图片回复、默认回复及回复次数限制
|
||||
- **AI 设置**:OpenAI 兼容 API 地址、API Key、模型和全局提示词
|
||||
- **议价策略**:最大折扣比例、最大折扣金额和最多议价轮次
|
||||
- **通知设置**:Bark、钉钉、飞书、企业微信、Telegram、邮件和 Webhook
|
||||
- **日志设置**:日志等级、输出格式和续期日志保留天数
|
||||
- **远程滑块服务**:服务地址、密钥及是否允许传递 Cookie;默认不传递 Cookie
|
||||
- **管理凭据**:管理员用户名、密码和邮箱
|
||||
|
||||
AI Base URL 支持 OpenAI 兼容接口,可连接 OpenAI、通义千问、Ollama、vLLM、
|
||||
LocalAI 或兼容网关。只有在明确了解数据流向时才应向外部 AI 或远程验证服务传递
|
||||
消息内容与账号数据。
|
||||
|
||||
## Docker 部署
|
||||
|
||||
### 镜像与架构
|
||||
|
||||
GitHub Actions 会将同一标签发布为多架构镜像:
|
||||
|
||||
```text
|
||||
http://localhost:3000
|
||||
ghcr.io/christ9038/ydisks-xianyu-helper:dev
|
||||
├── linux/amd64
|
||||
└── linux/arm64
|
||||
```
|
||||
|
||||
Vite 会把 API 请求代理到 `http://localhost:8080`。
|
||||
Docker 会根据宿主机 CPU 自动选择镜像。x86_64 Linux 拉取 amd64,Apple M 系列和
|
||||
ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
|
||||
|
||||
## 编译运行
|
||||
标签规则:
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
go build -o xianyu-server ./cmd/server
|
||||
./xianyu-server -db data/xianyu_data.db -addr :8080
|
||||
```
|
||||
|
||||
如果要使用外部前端目录,也可以传:
|
||||
|
||||
```bash
|
||||
./xianyu-server -db data/xianyu_data.db -addr :8080 -web /path/to/static
|
||||
```
|
||||
|
||||
## 验证数据库(三库冒烟)
|
||||
|
||||
`cmd/dbverify` 在目标库上跑迁移 + 核心 CRUD,确认方言适配正常:
|
||||
|
||||
```bash
|
||||
go run ./cmd/dbverify "sqlite:///tmp/verify.db"
|
||||
go run ./cmd/dbverify "mysql://root:pass@tcp(host:3306)/db?multiStatements=true"
|
||||
go run ./cmd/dbverify "postgres://user:pass@host:5432/db"
|
||||
```
|
||||
|
||||
全部 9 步通过即说明 upsert / 布尔读写 / 自增主键 / NULL 扫描跨三库一致。
|
||||
|
||||
## Docker 部署注意
|
||||
|
||||
仓库提供 `docker-compose.debian13-postgres17.yml`,用于在 x86_64 Linux 上运行
|
||||
Debian 13 应用镜像和 PostgreSQL 17。Compose 明确锁定 `linux/amd64`,即使在 ARM
|
||||
开发机上也会构建并验证 x86_64 镜像。
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# 编辑 .env,至少替换 PostgreSQL 密码、DATABASE_URL 和 XIANYU_DATA_KEY
|
||||
docker compose -f docker-compose.debian13-postgres17.yml build app
|
||||
docker compose -f docker-compose.debian13-postgres17.yml up -d postgres app
|
||||
```
|
||||
|
||||
数据库只在 Compose 内部网络开放,不映射宿主机端口;应用端口由
|
||||
`XIANYU_BIND_ADDRESS` 和 `XIANYU_HTTP_PORT` 控制。PostgreSQL 数据、应用数据和
|
||||
Chromium 持久化配置分别保存在命名卷 `postgres_data`、`app_data` 和
|
||||
`browser_data` 中。
|
||||
|
||||
首次部署后初始化管理员:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.debian13-postgres17.yml --profile init run --rm init-admin
|
||||
```
|
||||
|
||||
检查服务和日志:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.debian13-postgres17.yml ps
|
||||
curl -fsS http://127.0.0.1:8080/health
|
||||
docker compose -f docker-compose.debian13-postgres17.yml logs -f app
|
||||
```
|
||||
|
||||
`.env` 已被 Git 和 Docker 构建上下文忽略。`DATABASE_URL` 必须使用 Compose 服务名
|
||||
`postgres` 作为主机;如果密码包含 `@`、`:`、`/` 等字符,需要在连接串中进行 URL
|
||||
编码。部署到服务器前可用 `openssl rand -base64 48` 生成稳定的
|
||||
`XIANYU_DATA_KEY`,并与数据库卷一同安全备份。
|
||||
|
||||
生产环境建议同时设置稳定且仅由服务进程可读的 `XIANYU_DATA_KEY`。启用后,Cookie、
|
||||
账号登录密码、设备/访问令牌、AI/SMTP 密钥和通知渠道配置会使用 AES-256-GCM 加密
|
||||
后落库;首次启动会自动升级历史明文。该密钥必须随数据卷一同备份,丢失或更换后
|
||||
已有凭证无法解密。
|
||||
|
||||
管理员配置的 OpenAI 兼容 AI Base URL 不限制目标网络,可使用 `0.0.0.0`、loopback、
|
||||
Docker 服务名、RFC1918 私网、Tailscale/CGNAT、IPv6 ULA 或公网地址,便于连接任意部署
|
||||
位置的 Ollama、vLLM、LocalAI 或兼容网关。通知 Webhook、远程图片等非管理员可信目标
|
||||
继续只允许公网地址。
|
||||
|
||||
## 常用参数
|
||||
|
||||
| 参数 | 说明 |
|
||||
| Git 引用 | 镜像标签 |
|
||||
| --- | --- |
|
||||
| `-db` | SQLite 数据库路径,默认 `data/xianyu_data.db`(向后兼容) |
|
||||
| `-db-url` | 数据库连接 URL(`sqlite://` / `mysql://` / `postgres://`),优先级高于 `-db` |
|
||||
| `DATABASE_URL` | 环境变量,优先级最高 |
|
||||
| `XIANYU_DATA_KEY` | 敏感字段加密主密钥;生产环境应固定配置并安全备份 |
|
||||
| `-addr` | HTTP 监听地址,默认 `:8080` |
|
||||
| `-web` | 外部前端静态资源目录;不传则用内置前端 |
|
||||
| `-init-admin` | 初始化或重置管理员后退出 |
|
||||
| `-admin-email` | 初始化管理员邮箱 |
|
||||
| `-admin-password` | 初始化管理员密码(也可用 `XIANYU_ADMIN_PASSWORD` 环境变量) |
|
||||
| `-no-browser` | 禁用内置浏览器自动化(扫码风控/密码登录/订单抓取将不可用) |
|
||||
| `-secure` | HTTPS 模式,Cookie 加 Secure |
|
||||
| `-v` | 调试日志 |
|
||||
| `dev` 分支 | `dev`、`sha-<完整提交号>` |
|
||||
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
|
||||
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
|
||||
|
||||
## 质量门禁与测试
|
||||
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
|
||||
|
||||
项目内置 Makefile 与 golangci-lint 配置:
|
||||
### Compose 服务
|
||||
|
||||
根目录的 [`compose.yml`](compose.yml) 是默认生产部署文件:它只拉取 GHCR 镜像,完全不
|
||||
包含 `build` 配置,因此服务器不需要安装 Go、Node.js 或项目源码构建依赖。完成一次
|
||||
`.env` 配置后,始终使用:
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go
|
||||
make vet # go vet
|
||||
make test # 全部单元测试
|
||||
make lint # golangci-lint(0 issues 基线)
|
||||
make cover # 覆盖率报告
|
||||
make check # vet + lint + test 一键全检
|
||||
make frontend # 构建前端
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
跨三库回归(需 Docker 容器或外置库):
|
||||
它包含两个服务:
|
||||
|
||||
| 服务 | 用途 |
|
||||
| --- | --- |
|
||||
| `postgres` | PostgreSQL 17 数据库,仅在 Compose 内部网络开放 5432 |
|
||||
| `app` | Ydisks闲鱼助手主服务、前端和 Chromium |
|
||||
|
||||
`app` 会在首次启动时自动创建 `admin`;如果管理员已存在,后续 `up`、重启或升级均不会
|
||||
修改其密码。
|
||||
|
||||
`docker-compose.debian13-postgres17.yml` 保留为**源码构建版**,用于本地修改 Dockerfile
|
||||
或需要构建本地镜像的场景;生产服务器无需使用该文件。
|
||||
|
||||
持久化卷:
|
||||
|
||||
| 卷 | 内容 |
|
||||
| --- | --- |
|
||||
| `postgres_data` | PostgreSQL 数据文件 |
|
||||
| `app_data` | 上传文件、批量铺货资源和应用数据 |
|
||||
| `browser_data` | Chromium 持久化配置和验证上下文 |
|
||||
|
||||
### 完整部署步骤
|
||||
|
||||
```bash
|
||||
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
|
||||
git clone https://github.com/Christ9038/Ydisks-Xianyu-Helper.git
|
||||
cd Ydisks-Xianyu-Helper
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
完整 Docker 功能回归(前端测试/构建、vet、lint、Go `-race`、三库迁移、
|
||||
MySQL 8.4 与 PostgreSQL 17 API 功能及重启持久化):
|
||||
完成 `.env` 配置后执行:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
检查运行状态:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
curl -fsS http://127.0.0.1:8080/health
|
||||
docker compose logs --tail=200 app
|
||||
```
|
||||
|
||||
健康接口正常时返回:
|
||||
|
||||
```json
|
||||
{"database":"ok","status":"ok"}
|
||||
```
|
||||
|
||||
### 更新镜像
|
||||
|
||||
```bash
|
||||
docker compose pull app
|
||||
docker compose up -d
|
||||
docker compose logs --tail=100 app
|
||||
```
|
||||
|
||||
更新前请先备份数据库,并确认 `.env` 中的 `XIANYU_DATA_KEY` 未发生变化。
|
||||
|
||||
### 备份 PostgreSQL
|
||||
|
||||
```bash
|
||||
set -a
|
||||
. ./.env
|
||||
set +a
|
||||
|
||||
docker compose exec -T postgres \
|
||||
pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
|
||||
> "xianyu-$(date +%Y%m%d-%H%M%S).sql"
|
||||
```
|
||||
|
||||
恢复前请先停止应用,并在独立环境验证备份文件:
|
||||
|
||||
```bash
|
||||
docker compose stop app
|
||||
docker compose exec -T postgres \
|
||||
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" < xianyu-backup.sql
|
||||
```
|
||||
|
||||
同时备份 `.env` 中的 `XIANYU_DATA_KEY`。不要把包含真实密码和密钥的 `.env` 提交到
|
||||
Git;项目已默认忽略该文件。
|
||||
|
||||
### 停止服务
|
||||
|
||||
```bash
|
||||
# 停止并保留数据卷
|
||||
docker compose down
|
||||
|
||||
# 查看数据卷
|
||||
docker volume ls --filter name=xianyu
|
||||
```
|
||||
|
||||
不要在生产环境随意执行 `down -v`,该参数会删除 Compose 管理的数据库和应用数据卷。
|
||||
|
||||
### HTTPS 与反向代理
|
||||
|
||||
生产环境建议使用 Caddy、Nginx、Traefik 或云负载均衡器终止 TLS,并避免直接向公网
|
||||
暴露管理端口。启用 HTTPS 后,应为应用命令增加 `-secure`,确保管理端会话 Cookie
|
||||
仅通过 HTTPS 发送。例如可创建一个 Compose override:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-secure"]
|
||||
```
|
||||
|
||||
## 开发指南
|
||||
|
||||
### 项目结构
|
||||
|
||||
```text
|
||||
.
|
||||
├── cmd/
|
||||
│ ├── server/ # 主服务与管理员初始化入口
|
||||
│ ├── init-admin/ # 交互式管理员初始化工具
|
||||
│ ├── dbverify/ # 多数据库迁移和 CRUD 验证
|
||||
│ └── dbseed/ # Docker 功能测试数据种子
|
||||
├── internal/
|
||||
│ ├── account/ # 多账号监督与生命周期
|
||||
│ ├── adapter/ # 业务模块接线层
|
||||
│ ├── automation/ # 自动化中心与调度器
|
||||
│ ├── browser/ # Chromium 指纹和滑块验证
|
||||
│ ├── db/ # 数据访问、加密与迁移
|
||||
│ ├── engine/ # 单账号消息和交付运行时
|
||||
│ ├── notify/ # 通知渠道
|
||||
│ ├── renewal/ # 登录态续期调度
|
||||
│ ├── server/ # HTTP API 与 SPA 服务
|
||||
│ └── xianyu/ # MTOP、WebSocket、登录和协议实现
|
||||
├── frontend/ # React、TypeScript、Vite 前端
|
||||
├── docs/ # 专题文档和行为规范
|
||||
├── scripts/ # Docker 与回归测试脚本
|
||||
└── Dockerfile.debian13 # 多阶段生产镜像
|
||||
```
|
||||
|
||||
### 本地开发
|
||||
|
||||
启动后端:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
```
|
||||
|
||||
启动前端开发服务器:
|
||||
|
||||
```bash
|
||||
npm --prefix frontend ci
|
||||
npm --prefix frontend run dev
|
||||
```
|
||||
|
||||
访问 `http://localhost:3000`。Vite 会将 API 请求代理到 `http://localhost:8080`。
|
||||
|
||||
构建嵌入式前端和 Go 二进制:
|
||||
|
||||
```bash
|
||||
make frontend
|
||||
make build
|
||||
```
|
||||
|
||||
### 质量检查
|
||||
|
||||
```bash
|
||||
make fmt # 格式化 Go 代码
|
||||
make vet # go vet
|
||||
make lint # golangci-lint
|
||||
make test # 全部 Go 单元测试
|
||||
make cover # 覆盖率报告
|
||||
make check # fmt + vet + lint + test
|
||||
|
||||
npm --prefix frontend run typecheck
|
||||
npm --prefix frontend test
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
完整 Docker 功能回归会检查前端、Go `-race`、SQLite、MySQL 8.4、PostgreSQL 17、
|
||||
API 功能和容器重启持久化:
|
||||
|
||||
```bash
|
||||
./scripts/docker-full-test.sh
|
||||
```
|
||||
|
||||
测试编排使用命名卷 `mysql8_data`、`postgres17_data` 和 `sqlite_seed`。
|
||||
本地 `data/xianyu_data.db` 只会抽取少量商品、订单和卡密元数据,写入外置库前会替换
|
||||
Cookie、买家 ID 和卡密内容。测试应用分别监听 `28081`(MySQL)与 `28082`
|
||||
(PostgreSQL),测试账号为 `docker_fixture / docker_fixture_password`。
|
||||
测试管理员为 `docker_admin / docker_admin_password`。
|
||||
|
||||
保留数据库并停止容器:
|
||||
验证指定数据库的迁移与核心 CRUD:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.functional.yml down
|
||||
go run ./cmd/dbverify "sqlite:///tmp/xianyu-verify.db"
|
||||
go run ./cmd/dbverify "mysql://root:pass@tcp(127.0.0.1:3306)/xianyu"
|
||||
go run ./cmd/dbverify "postgres://user:pass@127.0.0.1:5432/xianyu"
|
||||
```
|
||||
|
||||
只有明确需要清空测试数据时才追加 `-v` 删除命名卷。
|
||||
## 常见问题
|
||||
|
||||
### 首次部署无法完成管理员初始化
|
||||
|
||||
确认 `.env` 已设置非空的 `XIANYU_ADMIN_PASSWORD`,然后执行:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
源码运行时可执行:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密码'
|
||||
```
|
||||
|
||||
### PostgreSQL 连接失败
|
||||
|
||||
- 确认 `.env` 中 `POSTGRES_DB`、`POSTGRES_USER`、`POSTGRES_PASSWORD` 与
|
||||
`DATABASE_URL` 完全一致。
|
||||
- Compose 内部的数据库主机名必须写 `postgres`,不能写 `localhost`。
|
||||
- 密码包含 `@`、`:`、`/`、`#` 等字符时,需要在 `DATABASE_URL` 中进行 URL 编码。
|
||||
- 使用 `docker compose ... ps` 确认 PostgreSQL 健康检查已通过。
|
||||
|
||||
### Chromium 或 Playwright 初始化失败
|
||||
|
||||
- Docker 部署优先使用项目提供的镜像,镜像已包含 Chromium 和运行依赖。
|
||||
- 源码运行时确认系统允许下载 Playwright 驱动和 Chromium。
|
||||
- 自带 Chromium 时设置 `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`,并按需设置
|
||||
`PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1`。
|
||||
- 容器内需要足够的共享内存与可写的 `browser_data` 卷。
|
||||
|
||||
### 账号掉线或需要安全验证
|
||||
|
||||
- 查看“账号管理”中的状态和续期日志。
|
||||
- 根据页面二维码在闲鱼 App 完成人脸或安全验证。
|
||||
- 检查服务器时间、时区和外网连接是否正常。
|
||||
- 不要同时在多个实例中运行同一个闲鱼账号,避免凭证相互覆盖。
|
||||
|
||||
### 修改 `XIANYU_DATA_KEY` 后无法读取凭证
|
||||
|
||||
这是预期的安全行为。请恢复写入这些数据时使用的原密钥。无法恢复原密钥时,只能重新
|
||||
登录账号并重新录入受保护的密钥;不要通过清空或绕过解密检查继续运行生产数据库。
|
||||
|
||||
## 安全建议
|
||||
|
||||
- 仅通过 HTTPS 暴露管理后台,并限制可信来源访问。
|
||||
- 为管理员、数据库和 GHCR 分别使用不同的高强度密码。
|
||||
- 固定并离线备份 `XIANYU_DATA_KEY`,不要在多套环境之间随意复用。
|
||||
- 不要提交 `.env`、数据库文件、Cookie、二维码、日志或浏览器数据目录。
|
||||
- 定期备份 PostgreSQL,并实际验证恢复流程。
|
||||
- 使用版本或 SHA 镜像标签部署生产环境。
|
||||
- 仅向可信的 AI、SMTP、Webhook 和远程滑块服务发送数据。
|
||||
- 发现账号异常时先停用账号,再检查登录审计和续期日志。
|
||||
|
||||
## 贡献
|
||||
|
||||
欢迎通过 Issue 报告可复现的问题,或通过 Pull Request 提交改进。提交前请:
|
||||
|
||||
1. 将不同主题拆分为独立提交。
|
||||
2. 为协议、数据库和关键业务行为补充测试。
|
||||
3. 运行 `make check` 和前端测试。
|
||||
4. 不要提交真实账号、Cookie、订单、卡密、密钥或其他敏感数据。
|
||||
5. 不要在未说明原因和验证证据的情况下修改风控与滑块行为。
|
||||
|
||||
提交安全问题时,请避免在公开 Issue 中附带真实凭证或用户数据。
|
||||
|
||||
## 开源协议
|
||||
|
||||
本项目采用 [Apache License 2.0](LICENSE) 开源,版权所有 © 2026 Christ9038。
|
||||
|
||||
完整许可条款见 [LICENSE](LICENSE),
|
||||
原项目名称、版权与署名声明见 [NOTICE](NOTICE)。分发原始或衍生作品时,请保留这两个
|
||||
文件中的适用声明,并在修改过的文件中显著标注修改。
|
||||
|
||||
## 免责声明
|
||||
|
||||
本项目仅提供技术研究和自托管管理能力,不保证对闲鱼接口变化、账号风控策略、业务
|
||||
连续性或数据完整性的长期兼容。因使用本项目造成的账号限制、交易纠纷、数据损失或
|
||||
其他直接与间接损失,应由使用者自行承担。请勿将本项目用于垃圾消息、欺诈、未授权
|
||||
访问、规避平台限制或任何违法违规活动。
|
||||
+28
-1
@@ -14,6 +14,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@@ -45,6 +46,7 @@ func main() {
|
||||
logLevel := flag.String("log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置")
|
||||
logFormat := flag.String("log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT")
|
||||
initAdmin := flag.Bool("init-admin", false, "初始化或重置 admin 管理员后退出")
|
||||
ensureAdminOnStart := flag.Bool("ensure-admin", false, "仅在 admin 管理员不存在时初始化;已存在时不修改密码")
|
||||
adminEmail := flag.String("admin-email", "admin@example.com", "初始化 admin 的邮箱")
|
||||
adminPassword := flag.String("admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量")
|
||||
flag.Parse()
|
||||
@@ -119,6 +121,16 @@ func main() {
|
||||
logger.Info("管理员初始化完成", "username", "admin")
|
||||
return
|
||||
}
|
||||
if *ensureAdminOnStart {
|
||||
created, err := ensureAdminIfMissing(ctx, store, *adminEmail, *adminPassword)
|
||||
if err != nil {
|
||||
logger.Error("检查或初始化管理员失败", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if created {
|
||||
logger.Info("管理员初始化完成", "username", "admin")
|
||||
}
|
||||
}
|
||||
|
||||
// 检查系统是否已初始化。
|
||||
if init, _ := store.Users.IsSystemInitialized(ctx); !init {
|
||||
@@ -149,7 +161,7 @@ func main() {
|
||||
logger.Error("启动账号引擎失败", "err", err)
|
||||
}
|
||||
go automation.NewScheduler(autoCenter).Run(ctx)
|
||||
go renewal.NewScheduler(store, mgr, ap, logger).Run(ctx)
|
||||
go renewal.NewScheduler(store, mgr, ap, logger, notifier).Run(ctx)
|
||||
|
||||
// 3) HTTP 服务。
|
||||
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
@@ -184,3 +196,18 @@ func ensureAdmin(ctx context.Context, store *db.Store, email, password string) e
|
||||
_, err := auth.InitAdmin(ctx, store, email, password)
|
||||
return err
|
||||
}
|
||||
|
||||
// ensureAdminIfMissing 只为首次部署创建管理员,避免容器重启重置既有管理员密码。
|
||||
func ensureAdminIfMissing(ctx context.Context, store *db.Store, email, password string) (bool, error) {
|
||||
admin, err := store.Users.GetAdmin(ctx)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
return false, fmt.Errorf("查询 admin 失败: %w", err)
|
||||
}
|
||||
if admin != nil {
|
||||
return false, nil
|
||||
}
|
||||
if err := ensureAdmin(ctx, store, email, password); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, dialect, err := db.Open(ctx, "sqlite://"+filepath.Join(t.TempDir(), "server.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open database: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
store := db.NewStore(database, dialect)
|
||||
|
||||
created, err := ensureAdminIfMissing(ctx, store, "admin@example.com", "first-password")
|
||||
if err != nil || !created {
|
||||
t.Fatalf("first ensure: created=%v err=%v", created, err)
|
||||
}
|
||||
created, err = ensureAdminIfMissing(ctx, store, "admin@example.com", "second-password")
|
||||
if err != nil || created {
|
||||
t.Fatalf("second ensure: created=%v err=%v", created, err)
|
||||
}
|
||||
if _, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "first-password"); err != nil || !ok {
|
||||
t.Fatalf("original password should remain valid: ok=%v err=%v", ok, err)
|
||||
}
|
||||
if _, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "second-password"); err == nil || ok {
|
||||
t.Fatalf("later password must not reset admin: ok=%v err=%v", ok, err)
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
# 默认生产部署:仅拉取 GHCR 多架构镜像,不在服务器上构建源码。
|
||||
x-app-env: &app-env
|
||||
DATABASE_URL: ${DATABASE_URL:?请在 .env 中配置 DATABASE_URL}
|
||||
XIANYU_DATA_KEY: ${XIANYU_DATA_KEY:?请在 .env 中配置 XIANYU_DATA_KEY}
|
||||
XIANYU_ADMIN_PASSWORD: ${XIANYU_ADMIN_PASSWORD:?请在 .env 中配置 XIANYU_ADMIN_PASSWORD}
|
||||
XIANYU_UPLOAD_DIR: ${XIANYU_UPLOAD_DIR:-/app/data/uploads}
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
LOG_FORMAT: ${LOG_FORMAT:-json}
|
||||
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
|
||||
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
|
||||
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/bin/node}
|
||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
|
||||
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH: ${PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH:-/usr/bin/chromium}
|
||||
|
||||
x-app-volumes: &app-volumes
|
||||
- app_data:/app/data
|
||||
- browser_data:/app/browser_data
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: ${POSTGRES_IMAGE:-postgres:17-trixie}
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:?请在 .env 中配置 POSTGRES_DB}
|
||||
POSTGRES_USER: ${POSTGRES_USER:?请在 .env 中配置 POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?请在 .env 中配置 POSTGRES_PASSWORD}
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
expose:
|
||||
- "5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 10s
|
||||
|
||||
app:
|
||||
image: ${XIANYU_IMAGE:-ghcr.io/christ9038/ydisks-xianyu-helper:latest}
|
||||
pull_policy: always
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment: *app-env
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-ensure-admin"]
|
||||
ports:
|
||||
- "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-8080}:8080"
|
||||
volumes: *app-volumes
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
app_data:
|
||||
browser_data:
|
||||
@@ -17,7 +17,6 @@ x-app-volumes: &app-volumes
|
||||
|
||||
services:
|
||||
postgres:
|
||||
platform: linux/amd64
|
||||
image: ${POSTGRES_IMAGE:-postgres:17-trixie}
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
@@ -37,8 +36,7 @@ services:
|
||||
start_period: 10s
|
||||
|
||||
app:
|
||||
platform: linux/amd64
|
||||
image: ${XIANYU_IMAGE:-xianyu-go:debian13-amd64}
|
||||
image: ${XIANYU_IMAGE:-ydisks-xianyu-helper:debian13}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.debian13
|
||||
@@ -59,8 +57,7 @@ services:
|
||||
start_period: 30s
|
||||
|
||||
init-admin:
|
||||
platform: linux/amd64
|
||||
image: ${XIANYU_IMAGE:-xianyu-go:debian13-amd64}
|
||||
image: ${XIANYU_IMAGE:-ydisks-xianyu-helper:debian13}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.debian13
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: xianyu-functional
|
||||
name: ydisks-xianyu-helper-functional
|
||||
|
||||
x-mysql-url: &mysql-url mysql://root:xianyu_root_password@tcp(mysql:3306)/xianyu?parseTime=true&loc=UTC
|
||||
x-postgres-url: &postgres-url postgres://xianyu:xianyu_postgres_password@postgres:5432/xianyu?sslmode=disable&timezone=UTC
|
||||
@@ -65,7 +65,7 @@ services:
|
||||
sqlite3 /seed/xianyu_data.db "PRAGMA quick_check" | grep -qx ok
|
||||
|
||||
seed-mysql:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.debian13
|
||||
@@ -82,7 +82,7 @@ services:
|
||||
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *mysql-url, "-limit", "20"]
|
||||
|
||||
seed-sqlite:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.debian13
|
||||
@@ -98,7 +98,7 @@ services:
|
||||
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", "/app/data/xianyu-functional.db", "-limit", "20"]
|
||||
|
||||
seed-postgres:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
restart: "no"
|
||||
depends_on:
|
||||
postgres:
|
||||
@@ -112,7 +112,7 @@ services:
|
||||
command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *postgres-url, "-limit", "20"]
|
||||
|
||||
app-mysql:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
seed-mysql:
|
||||
@@ -134,7 +134,7 @@ services:
|
||||
retries: 30
|
||||
|
||||
app-sqlite:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
seed-sqlite:
|
||||
@@ -156,7 +156,7 @@ services:
|
||||
retries: 30
|
||||
|
||||
app-postgres:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
seed-postgres:
|
||||
@@ -223,7 +223,7 @@ services:
|
||||
command: ["sh", "-c", "npm run typecheck && npm test && npm run build"]
|
||||
|
||||
dbverify-mysql:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
@@ -232,7 +232,7 @@ services:
|
||||
command: ["/app/xianyu-dbverify", *mysql-url]
|
||||
|
||||
dbverify-sqlite:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
environment:
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
volumes:
|
||||
@@ -240,7 +240,7 @@ services:
|
||||
command: ["/app/xianyu-dbverify", "/app/data/verify.db"]
|
||||
|
||||
dbverify-postgres:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -249,7 +249,7 @@ services:
|
||||
command: ["/app/xianyu-dbverify", *postgres-url]
|
||||
|
||||
functional-test:
|
||||
image: xianyu-go:functional
|
||||
image: ydisks-xianyu-helper:functional
|
||||
restart: "no"
|
||||
depends_on:
|
||||
app-sqlite:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
xianyu.ydisks.com
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="256" height="256" viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">
|
||||
<title>Ydisks闲鱼助手</title>
|
||||
<path d="M256.00,128.00 L255.99,144.91 L255.96,151.91 L255.91,157.28 L255.84,161.81 L255.76,165.79 L255.65,169.38 L255.52,172.68 L255.38,175.75 L255.21,178.63 L255.02,181.34 L254.82,183.91 L254.59,186.36 L254.35,188.71 L254.08,190.96 L253.80,193.12 L253.50,195.20 L253.17,197.21 L252.83,199.15 L252.46,201.03 L252.08,202.86 L251.68,204.63 L251.25,206.34 L250.81,208.01 L250.34,209.63 L249.86,211.21 L249.35,212.75 L248.82,214.24 L248.28,215.70 L247.71,217.12 L247.12,218.51 L246.51,219.86 L245.87,221.18 L245.22,222.46 L244.55,223.72 L243.85,224.94 L243.13,226.13 L242.39,227.30 L241.63,228.43 L240.84,229.54 L240.03,230.62 L239.20,231.68 L238.34,232.70 L237.46,233.71 L236.56,234.68 L235.63,235.63 L234.68,236.56 L233.71,237.46 L232.70,238.34 L231.68,239.20 L230.62,240.03 L229.54,240.84 L228.43,241.63 L227.30,242.39 L226.13,243.13 L224.94,243.85 L223.72,244.55 L222.46,245.22 L221.18,245.87 L219.86,246.51 L218.51,247.12 L217.12,247.71 L215.70,248.28 L214.24,248.82 L212.75,249.35 L211.21,249.86 L209.63,250.34 L208.01,250.81 L206.34,251.25 L204.63,251.68 L202.86,252.08 L201.03,252.46 L199.15,252.83 L197.21,253.17 L195.20,253.50 L193.12,253.80 L190.96,254.08 L188.71,254.35 L186.36,254.59 L183.91,254.82 L181.34,255.02 L178.63,255.21 L175.75,255.38 L172.68,255.52 L169.38,255.65 L165.79,255.76 L161.81,255.84 L157.28,255.91 L151.91,255.96 L144.91,255.99 L128.00,256.00 L111.09,255.99 L104.09,255.96 L98.72,255.91 L94.19,255.84 L90.21,255.76 L86.62,255.65 L83.32,255.52 L80.25,255.38 L77.37,255.21 L74.66,255.02 L72.09,254.82 L69.64,254.59 L67.29,254.35 L65.04,254.08 L62.88,253.80 L60.80,253.50 L58.79,253.17 L56.85,252.83 L54.97,252.46 L53.14,252.08 L51.37,251.68 L49.66,251.25 L47.99,250.81 L46.37,250.34 L44.79,249.86 L43.25,249.35 L41.76,248.82 L40.30,248.28 L38.88,247.71 L37.49,247.12 L36.14,246.51 L34.82,245.87 L33.54,245.22 L32.28,244.55 L31.06,243.85 L29.87,243.13 L28.70,242.39 L27.57,241.63 L26.46,240.84 L25.38,240.03 L24.32,239.20 L23.30,238.34 L22.29,237.46 L21.32,236.56 L20.37,235.63 L19.44,234.68 L18.54,233.71 L17.66,232.70 L16.80,231.68 L15.97,230.62 L15.16,229.54 L14.37,228.43 L13.61,227.30 L12.87,226.13 L12.15,224.94 L11.45,223.72 L10.78,222.46 L10.13,221.18 L9.49,219.86 L8.88,218.51 L8.29,217.12 L7.72,215.70 L7.18,214.24 L6.65,212.75 L6.14,211.21 L5.66,209.63 L5.19,208.01 L4.75,206.34 L4.32,204.63 L3.92,202.86 L3.54,201.03 L3.17,199.15 L2.83,197.21 L2.50,195.20 L2.20,193.12 L1.92,190.96 L1.65,188.71 L1.41,186.36 L1.18,183.91 L0.98,181.34 L0.79,178.63 L0.62,175.75 L0.48,172.68 L0.35,169.38 L0.24,165.79 L0.16,161.81 L0.09,157.28 L0.04,151.91 L0.01,144.91 L0.00,128.00 L0.01,111.09 L0.04,104.09 L0.09,98.72 L0.16,94.19 L0.24,90.21 L0.35,86.62 L0.48,83.32 L0.62,80.25 L0.79,77.37 L0.98,74.66 L1.18,72.09 L1.41,69.64 L1.65,67.29 L1.92,65.04 L2.20,62.88 L2.50,60.80 L2.83,58.79 L3.17,56.85 L3.54,54.97 L3.92,53.14 L4.32,51.37 L4.75,49.66 L5.19,47.99 L5.66,46.37 L6.14,44.79 L6.65,43.25 L7.18,41.76 L7.72,40.30 L8.29,38.88 L8.88,37.49 L9.49,36.14 L10.13,34.82 L10.78,33.54 L11.45,32.28 L12.15,31.06 L12.87,29.87 L13.61,28.70 L14.37,27.57 L15.16,26.46 L15.97,25.38 L16.80,24.32 L17.66,23.30 L18.54,22.29 L19.44,21.32 L20.37,20.37 L21.32,19.44 L22.29,18.54 L23.30,17.66 L24.32,16.80 L25.38,15.97 L26.46,15.16 L27.57,14.37 L28.70,13.61 L29.87,12.87 L31.06,12.15 L32.28,11.45 L33.54,10.78 L34.82,10.13 L36.14,9.49 L37.49,8.88 L38.88,8.29 L40.30,7.72 L41.76,7.18 L43.25,6.65 L44.79,6.14 L46.37,5.66 L47.99,5.19 L49.66,4.75 L51.37,4.32 L53.14,3.92 L54.97,3.54 L56.85,3.17 L58.79,2.83 L60.80,2.50 L62.88,2.20 L65.04,1.92 L67.29,1.65 L69.64,1.41 L72.09,1.18 L74.66,0.98 L77.37,0.79 L80.25,0.62 L83.32,0.48 L86.62,0.35 L90.21,0.24 L94.19,0.16 L98.72,0.09 L104.09,0.04 L111.09,0.01 L128.00,0.00 L144.91,0.01 L151.91,0.04 L157.28,0.09 L161.81,0.16 L165.79,0.24 L169.38,0.35 L172.68,0.48 L175.75,0.62 L178.63,0.79 L181.34,0.98 L183.91,1.18 L186.36,1.41 L188.71,1.65 L190.96,1.92 L193.12,2.20 L195.20,2.50 L197.21,2.83 L199.15,3.17 L201.03,3.54 L202.86,3.92 L204.63,4.32 L206.34,4.75 L208.01,5.19 L209.63,5.66 L211.21,6.14 L212.75,6.65 L214.24,7.18 L215.70,7.72 L217.12,8.29 L218.51,8.88 L219.86,9.49 L221.18,10.13 L222.46,10.78 L223.72,11.45 L224.94,12.15 L226.13,12.87 L227.30,13.61 L228.43,14.37 L229.54,15.16 L230.62,15.97 L231.68,16.80 L232.70,17.66 L233.71,18.54 L234.68,19.44 L235.63,20.37 L236.56,21.32 L237.46,22.29 L238.34,23.30 L239.20,24.32 L240.03,25.38 L240.84,26.46 L241.63,27.57 L242.39,28.70 L243.13,29.87 L243.85,31.06 L244.55,32.28 L245.22,33.54 L245.87,34.82 L246.51,36.14 L247.12,37.49 L247.71,38.88 L248.28,40.30 L248.82,41.76 L249.35,43.25 L249.86,44.79 L250.34,46.37 L250.81,47.99 L251.25,49.66 L251.68,51.37 L252.08,53.14 L252.46,54.97 L252.83,56.85 L253.17,58.79 L253.50,60.80 L253.80,62.88 L254.08,65.04 L254.35,67.29 L254.59,69.64 L254.82,72.09 L255.02,74.66 L255.21,77.37 L255.38,80.25 L255.52,83.32 L255.65,86.62 L255.76,90.21 L255.84,94.19 L255.91,98.72 L255.96,104.09 L255.99,111.09 Z" fill="#0094f7"/>
|
||||
<g transform="translate(0,0)">
|
||||
<path d="M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z" fill="#FFFFFF"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 494 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
+1318
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@
|
||||
|
||||
## 目标
|
||||
|
||||
参考 `zhinianboke/xianyu-auto-reply` 的实现,把当前项目缺少的登录态续期、MTOP 风控识别、扫码人脸验证能力补齐。改造重点是提升账号长期在线能力和风控状态的可恢复性,同时保持 `xianyu-go` 现有单进程架构清晰、可测试、可回滚。
|
||||
参考 `zhinianboke/xianyu-auto-reply` 的实现,把当前项目缺少的登录态续期、MTOP 风控识别、扫码人脸验证能力补齐。改造重点是提升账号长期在线能力和风控状态的可恢复性,同时保持 `Ydisks-Xianyu-Helper` 现有单进程架构清晰、可测试、可回滚。
|
||||
|
||||
## 非目标
|
||||
|
||||
@@ -108,7 +108,7 @@ cd frontend && npm test -- --run && npm run build
|
||||
## 实施记录
|
||||
|
||||
- 已完成扫码人脸验证 API 链路:后端提取 `htoken`、`verify_modes`、人脸二维码内容并轮询 `photoVerify/check.do`,前端优先展示 `face_qr_url`;截图只保留为兜底。
|
||||
- 已完成 Cookie 接口续期服务:`hasLogin.do -> silentHasLogin.do -> setLoginSettings.do` 串行合并 `Set-Cookie`,所有响应读取有大小上限。
|
||||
- 已完成 Cookie 接口续期服务:主动续期使用 `silentHasLogin.do`,长登录设置使用 `setLoginSettings.do`;两者均合并 `Set-Cookie`,所有响应读取有大小上限。续期请求使用运行时 Chromium 原生指纹,Linux Docker 与桌面部署均会实际发起续期请求。
|
||||
- 已完成 MTOP 风控分类:token 过期、session 失效、`FAIL_SYS_USER_VALIDATE`、`RGV587`、`punish/captcha/x5secdata` 等状态被结构化识别。
|
||||
- 已完成运行时恢复顺序:`RefreshToken -> API Renew -> Browser Renew -> PasswordLogin -> 慢重试/人工验证`,Cookie 更新后会清理旧 token 缓存。
|
||||
- 已完成多账号保护:重连退避加入 0-30% 抖动,降低多账号同时重连造成的风控压力。
|
||||
@@ -0,0 +1,46 @@
|
||||
# AI、通知与运维
|
||||
|
||||
## 配置 AI 服务
|
||||
|
||||
系统级连接在“系统与 AI”设置,仅管理员可修改:
|
||||
|
||||
1. 填写 OpenAI 兼容的 API 地址,填到版本根路径即可,例如 `https://api.openai.com/v1` 或通义兼容地址 `https://dashscope.aliyuncs.com/compatible-mode/v1`;不要填 `/chat/completions`。
|
||||
2. 填入 API Key,点击“读取模型”。若服务不支持模型列表,也可手动填模型名。
|
||||
3. 保存系统设置。API Key 会作为敏感字段保存;仍应限制数据库和管理员访问。
|
||||
4. 前往“账号管理”,在目标账号行打开“AI 设置”。
|
||||
5. 打开“启用 AI 自动回复”,配置最大折扣比例、最大降价金额、最大砍价轮次和自定义提示词,保存。
|
||||
6. 使用真实但无风险的砍价对话测试输出;确认金额边界和措辞均符合预期后再开启正式账号。
|
||||
|
||||
AI 用于处理买家的砍价消息。`0` 的最大折扣比例或金额表示不允许对应降价;砍价轮次应设置保守值。提示词应明确产品边界、禁止承诺事项、语气和转人工条件,不应放入 Cookie、密码、完整订单隐私或其他机密。
|
||||
|
||||
## 配置通知
|
||||
|
||||
1. 打开“通知设置”,先按需要配置系统 SMTP(仅邮件渠道需要)。
|
||||
2. 新建通知渠道,选择 Bark、钉钉、飞书、企业微信、Telegram、邮件或自定义 Webhook,并填写该渠道所需地址/令牌。
|
||||
3. 选择接收事件;不选择表示接收全部。可选事件包括掉线、恢复、禁用、安全验证、续期和交易结果。
|
||||
4. 保存后点击“测试通知”,在目标渠道确认收到。
|
||||
5. 回到“账号管理 → 编辑”,把通知渠道绑定到具体账号。仅创建渠道不会自动让账号使用它。
|
||||
|
||||
Webhook 和机器人令牌通常等同于密码。不要贴进截图、Issue 或聊天记录;更换令牌后立即更新渠道并重测。
|
||||
|
||||
## 日常巡检
|
||||
|
||||
每天或每次大促前检查:
|
||||
|
||||
- Dashboard 的在线账号、订单、库存和异常趋势;
|
||||
- 自动化异常/延迟任务是否有待处理项;
|
||||
- 批量卡密库存是否低于安全线;
|
||||
- 最近一次通知是否可达;
|
||||
- 登录续期和安全验证是否需要人工操作。
|
||||
|
||||
## 故障排查顺序
|
||||
|
||||
1. **账号不在线**:检查账号是否被暂停、Cookie 是否失效、是否需要扫码或安全验证;完成后确认恢复通知。
|
||||
2. **未自动发货**:核对订单所属账号、商品/规格匹配、规则启用、卡密库存和自动化异常。先确认是否已经实际发送过内容。
|
||||
3. **AI 无回复**:确认系统 API 地址、Key 和模型可用;再确认该账号 AI 已启用,且消息属于砍价场景。
|
||||
4. **通知未达**:先点击测试通知,再核对事件筛选与账号绑定;邮件还需检查 SMTP 配置。
|
||||
5. **数据库无法连接**:检查 `DATABASE_URL`、网络/TLS、数据库账号权限和服务日志。不要通过删除数据库来“修复”。
|
||||
|
||||
## 备份与恢复
|
||||
|
||||
备份至少包含数据库、`.env`(特别是 `XIANYU_DATA_KEY`)和必要的上传资源。恢复到新机器时先恢复数据库与同一把密钥,再启动服务;若密钥不一致,已加密的 Cookie、AI 和通知配置不可读取。恢复后先禁用高风险自动化,用测试订单逐项确认。
|
||||
@@ -0,0 +1,34 @@
|
||||
# Ydisks闲鱼助手 Wiki
|
||||
|
||||
本 Wiki 面向管理后台操作人员。先完成“部署与数据库”和“账号接入”,再配置库存、商品、自动化与 AI。
|
||||
|
||||
## 推荐上线路径
|
||||
|
||||
1. 选择并启动数据库;生产环境推荐 PostgreSQL。
|
||||
2. 设置并备份 `XIANYU_DATA_KEY`,初始化管理员后登录后台。
|
||||
3. 在“账号管理”扫码接入账号,确认账号为启用且在线状态。
|
||||
4. 在“卡密库存”建立可交付内容。
|
||||
5. 同步已有商品,或通过“商品管理”发布商品。
|
||||
6. 在“自动化规则”建立付款发货、评价赠品或求评价规则。
|
||||
7. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
|
||||
8. 建立通知渠道并绑定到账号;用测试通知验证。
|
||||
9. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
|
||||
|
||||
## 先读这些页面
|
||||
|
||||
- [部署与数据库](部署与数据库)
|
||||
- [账号、库存与商品](账号、库存与商品)
|
||||
- [批量铺货](批量铺货)
|
||||
- [自动化发货与回复](自动化发货与回复)
|
||||
- [AI、通知与运维](AI、通知与运维)
|
||||
|
||||
## 关键安全规则
|
||||
|
||||
- 不要提交 `.env`、数据库备份、Cookie、API Key 或通知 Webhook 地址。
|
||||
- `XIANYU_DATA_KEY` 用于加密 Cookie、密码、AI/SMTP 和通知凭据;换密钥会导致旧数据无法解密。务必和数据库一同离线备份。
|
||||
- 自动化必须先用测试商品、测试卡密和小额订单验证。库存耗尽、账号掉线或风控时,不应假设发货已完成。
|
||||
- 本项目为非官方工具。请确保使用方式符合平台规则、当地法律及账号授权范围。
|
||||
|
||||
## GitHub Wiki 同步
|
||||
|
||||
这些 Markdown 文件位于仓库 `docs/wiki/`,可直接复制到 GitHub Wiki 对应页面;文件名即页面名。`_Sidebar.md` 是 Wiki 导航。仓库内保留副本便于在 Pull Request 中审阅和版本化维护。
|
||||
@@ -0,0 +1,8 @@
|
||||
### Ydisks闲鱼助手
|
||||
|
||||
- [首页](Home)
|
||||
- [部署与数据库](部署与数据库)
|
||||
- [账号、库存与商品](账号、库存与商品)
|
||||
- [批量铺货](批量铺货)
|
||||
- [自动化发货与回复](自动化发货与回复)
|
||||
- [AI、通知与运维](AI、通知与运维)
|
||||
@@ -0,0 +1,62 @@
|
||||
# 批量铺货
|
||||
|
||||
批量铺货会先预检,再启动后台发布任务。它最多一次处理 50 行商品;建议先用 1 行测试资料包验证后再跑正式批次。
|
||||
|
||||
## 1. 准备资料包
|
||||
|
||||
必需文件为 CSV、XLSX 或 TSV 表格;如引用本地图片,再提供 ZIP 图片包。下载“商品管理 → 批量铺货”中的模板可避免表头错误。
|
||||
|
||||
推荐中文表头:
|
||||
|
||||
```text
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
```
|
||||
|
||||
也支持英文表头,但不能与中文混用。每行一个商品;`账号ID` 可留空并在上传页选择默认账号。
|
||||
|
||||
### 必填与格式
|
||||
|
||||
- 标题非空,价格大于 0;库存为正整数,留空默认 1。
|
||||
- 邮费模式为 `free`/`包邮` 或 `fixed`/`固定邮费`;固定邮费时必须填邮费。
|
||||
- 每件商品 1–9 张图片,多个用英文分号 `;` 分隔。可用公开 `https://` URL,或 ZIP 内相对路径。
|
||||
- 上传页的默认类目可以留空。需要指定时,先选择账号,再输入关键词,由闲鱼推荐接口返回完整类目信息。表格的“类目ID + 类目名称 + 频道类目ID”可覆盖当前行;三列必须同时填写。
|
||||
- “淘宝类目ID”按闲鱼推荐响应填写;“电子资料”的值为空,应保持为空。
|
||||
- 本地图片 ZIP 最大 200 MiB,单图最大 10 MiB;表格最大 20 MiB。
|
||||
- CSV 使用 UTF-8,建议带 BOM;不要在表头增加空格。
|
||||
|
||||
### 自动化列
|
||||
|
||||
“付款发货内容”和“评价赠品内容”格式相同:
|
||||
|
||||
```text
|
||||
卡密组ID:每件份数:延迟秒;卡密组ID:每件份数:延迟秒
|
||||
```
|
||||
|
||||
例如 `101:1;102:2:30`:先从组 101 发 1 份,再等待 30 秒从组 102 发 2 份。份数省略时为 1,延迟省略时为 0。卡密组 ID 从“卡密库存”复制。启用值可写“是”、`true`、`1` 或 `on`;不启用写“否”、`false`、`0` 或留空。
|
||||
|
||||
完整字段规范和示例见仓库 [批量铺货资料包准备规格](../批量铺货使用文档.md)。
|
||||
|
||||
## 2. 后台操作
|
||||
|
||||
1. 在“商品管理”点击“批量铺货”。
|
||||
2. 选择默认账号;表格某行未填账号 ID 时会使用它。
|
||||
3. 默认类目可以留空;需要整批固定类目时,输入关键词并点击“获取类目”。
|
||||
4. 选择表格;表格引用本地图片时同时选择 ZIP。
|
||||
5. 点击预检,确认每一行的类目策略正确,再处理账号未授权、卡密组不存在、图片路径不匹配、固定邮费缺失或价格为 0 等错误。
|
||||
6. 所有需发布行确认无误后启动任务;不要关闭正在运行的任务页面。
|
||||
7. 在任务详情查看成功、失败与进行中行。需要时取消任务;正在提交的单件商品可能继续完成。
|
||||
8. 对可重试失败项使用“重试失败”,并下载结果 CSV 留档。
|
||||
|
||||
### 类目选择顺序
|
||||
|
||||
类目优先级为:表格当前行指定类目 > 上传页通过关键词获取的默认类目 > 闲鱼根据商品标题、描述和图片自动识别 > “电子资料”最终兜底。只要用户指定了类目,就不会再由自动识别结果覆盖。接口超时、鉴权失败、风控等错误不会被最终兜底掩盖。
|
||||
|
||||
批量铺货发布的都是虚拟商品,不请求或提交实物发货地址;指定类目只解决商品类型识别,不会改变虚拟发货流程。
|
||||
|
||||
## 3. 常见问题
|
||||
|
||||
- **图片找不到**:ZIP 内路径必须与表格完全一致,使用 `/`,不能以 `/` 开头或包含 `..`。
|
||||
- **未能自动识别类目**:系统会自动使用“电子资料”最终兜底;接口超时、鉴权或风控错误仍会正常提示。
|
||||
- **类目 ID 从哪里取**:在上传页输入关键词获取,无需手工查找或填写底层 ID。
|
||||
- **自动化不生效**:检查卡密组 ID、账号归属、启用列和库存;发布成功后仍应查看自动化规则是否已创建。
|
||||
- **任务中断**:先重新打开批次详情确认状态,避免重复新建整批任务;仅重试失败行。
|
||||
@@ -0,0 +1,47 @@
|
||||
# 自动化发货与回复
|
||||
|
||||
## 自动化的三种触发器
|
||||
|
||||
| 触发器 | 触发时机 | 标准流程 |
|
||||
| --- | --- | --- |
|
||||
| 付款后自动发货 | 收到付款系统卡片 | 匹配商品/规格 → 发送卡密 → 成功后确认发货。 |
|
||||
| 评价后发送赠品 | 收到评价系统卡片 | 匹配商品/规格 → 发送赠品卡密。 |
|
||||
| 超时未评价求评价 | 定时扫描已发货未评价订单 | 到达等待时间 → 发送提醒文案。 |
|
||||
|
||||
系统通知卡片只进入自动化判断;买家普通消息走关键词、默认回复和 AI 规则。
|
||||
|
||||
## 配置付款自动发货
|
||||
|
||||
前提:账号在线、商品已同步、卡密组已建立且有库存。
|
||||
|
||||
1. 进入“自动化规则”,选择“付款后自动发货”,点击新增。
|
||||
2. 设置规则名称,选择目标账号和商品;商品有规格时为每个需要交付的规格建立对应配置。
|
||||
3. 添加“发送卡密”动作,选择卡密库存、每件发送数量与是否启用。
|
||||
4. 如需覆盖卡密组默认延迟,打开延迟覆盖并填写秒数;否则使用卡密组的默认延时。
|
||||
5. 保存并确认规则处于启用状态。
|
||||
6. 用测试订单确认:卡密内容已发送、卡密库存扣减正确、随后才确认发货。
|
||||
|
||||
按购买数量发货:动作中的“每件发送数量”会乘以订单购买数量。不要把每单总量误填为每件数量。
|
||||
|
||||
## 配置评价赠品与求评价
|
||||
|
||||
评价赠品的配置与付款发货相同,但触发器选择“评价后发送赠品”。赠品应使用独立卡密组,便于核对和补货。
|
||||
|
||||
配置求评价:
|
||||
|
||||
1. 新建“超时未评价求评价”规则,选择账号和商品。
|
||||
2. 填写等待时间(发货后多少小时开始检查)、重复间隔及最多提醒次数。
|
||||
3. 填写发送给买家的求评价文案,保存并启用。
|
||||
4. 在测试订单上确认不会提前发送;达到最大次数后不再重复提醒。
|
||||
|
||||
## 异常处理与补发
|
||||
|
||||
“自动化规则”页面的异常区会列出可处理的自动化运行和延迟任务。先查看订单、库存、聊天记录和失败原因,再使用页面的“处理/解决”操作。不要在不确定已发货状态时直接重试,以免重复发卡。
|
||||
|
||||
需要人工补发时,在订单管理中定位订单,确认买家、商品和历史交付记录,再使用手动发货/补发能力。处理后记录原因并检查库存。
|
||||
|
||||
## 关键词与默认回复
|
||||
|
||||
在“自动化规则”的“关键词回复”页:选择账号 → 新增规则 → 填写关键词与文本或图片 URL → 保存。关键词规则用于买家普通消息。
|
||||
|
||||
“账号默认回复”只在关键词和 AI 都未处理该消息时使用。可设置文本、图片 URL 和“同一会话只回复一次”。上线前避免关键词、默认回复和 AI 提示词对同类问题给出互相矛盾的答案。
|
||||
@@ -0,0 +1,45 @@
|
||||
# 账号、库存与商品
|
||||
|
||||
## 1. 接入账号
|
||||
|
||||
1. 进入“账号管理”,选择添加账号/扫码登录。
|
||||
2. 用目标闲鱼账号在官方客户端完成扫码;若出现人脸或安全验证,按页面提示在官方流程中完成。
|
||||
3. 等待后台保存登录信息,确认昵称、账号 ID 和运行状态正常。
|
||||
4. 为账号填写备注,按需开启或暂停账号,并进入编辑页绑定通知渠道。
|
||||
5. 首次接入后同步一次商品;开始自动化前确认账号处于启用状态。
|
||||
|
||||
不要手工向他人发送 Cookie。登录态、指纹和密码等敏感值由系统加密存储,依赖固定的 `XIANYU_DATA_KEY`。
|
||||
|
||||
## 2. 创建卡密库存
|
||||
|
||||
付款自动发货和评价赠品都先依赖卡密库存。进入“卡密库存”后点击“添加新卡密”:
|
||||
|
||||
| 类型 | 适用内容 | 填写方式 |
|
||||
| --- | --- | --- |
|
||||
| 文本 | 固定说明、链接 | 填写文本内容。 |
|
||||
| 批量卡密(`data`) | 一次性兑换码、序列号 | 每行一个卡密;发货会按库存消费。 |
|
||||
| 图片 | 固定图片资源 | 填写公开可访问的图片 URL。 |
|
||||
| API | 外部发码接口 | 填写 URL、GET/POST、超时、请求头和参数;先用无敏感测试数据验证。 |
|
||||
|
||||
通用字段包括名称、描述、启用状态和默认延时秒数。保存后复制“卡密组 ID”;它是自动化规则和批量铺货表格引用库存的唯一标识。
|
||||
|
||||
批量卡密可用“批量导入”创建,也可选择已有 `data` 类型卡密组追加新卡密。上架前检查库存余量;库存不足时应先补货,不要依赖人工补救。
|
||||
|
||||
## 3. 同步或发布商品
|
||||
|
||||
进入“商品管理”:
|
||||
|
||||
- 对已在闲鱼上存在的商品,选择同步全部或按页同步,确认商品归属到正确账号。
|
||||
- 对单个新商品,使用发布入口填写标题、描述、价格、库存、邮费和图片。图片必须可用;提交前复核目标账号。
|
||||
- 批量铺货的默认类目可以留空,也可以通过关键词从闲鱼获取。优先级为逐行类目、页面默认类目、自动识别,最后才使用“电子资料”兜底。
|
||||
- 批量铺货商品按虚拟商品发布,不依赖实物发货地址;类目兜底不会改变付款后的虚拟交付逻辑。
|
||||
- 商品发布成功不等于已开启自动发货。仍需在“自动化规则”中按商品/规格绑定卡密组,或在批量铺货表格中一并声明自动化配置。
|
||||
|
||||
## 4. 上线前检查
|
||||
|
||||
1. 账号在线并已启用。
|
||||
2. 商品已同步或发布成功,价格、库存和图片正确。
|
||||
3. 批量铺货的预检明细已显示正确的类目策略。
|
||||
4. 所需卡密组启用且余量充足。
|
||||
5. 自动化规则准确匹配商品;有规格时逐个规格确认。
|
||||
6. 先用测试订单验证,检查订单列表、自动化异常列表和通知记录。
|
||||
@@ -0,0 +1,84 @@
|
||||
# 部署与数据库
|
||||
|
||||
## 选择数据库
|
||||
|
||||
| 场景 | 建议 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| 本机试用、单人低频使用 | SQLite | 无需额外服务,数据库是一个文件。 |
|
||||
| Docker 生产部署 | PostgreSQL 17 | 默认 Compose 已提供服务、持久化卷和健康检查。 |
|
||||
| 已有 MySQL 运维体系 | MySQL 8+ | 可复用现有备份、监控和权限管理。 |
|
||||
| 多人或长期运行 | PostgreSQL / MySQL | 更适合并发、备份和独立运维。 |
|
||||
|
||||
三种数据库均会在应用启动时自动执行内置迁移。连接优先级是:`DATABASE_URL` > `-db-url` > `-db`。升级生产库前先备份。
|
||||
|
||||
## Docker + PostgreSQL(推荐)
|
||||
|
||||
1. 复制配置:`cp .env.example .env`。
|
||||
2. 编辑 `.env`,至少设置 `POSTGRES_DB`、`POSTGRES_USER`、`POSTGRES_PASSWORD`、`XIANYU_DATA_KEY`、`XIANYU_ADMIN_PASSWORD`。
|
||||
3. 为 `XIANYU_DATA_KEY` 生成一次长期固定的随机值,例如 `openssl rand -base64 48`;不要在后续升级时更换。
|
||||
4. 启动:`docker compose up -d`。
|
||||
5. 查看:`docker compose ps` 和 `docker compose logs -f app`。
|
||||
6. 打开 `http://服务器地址:8080`,用管理员账号登录。若未自动初始化,可按 README 的 `-init-admin` 命令执行。
|
||||
|
||||
默认连接已由 `compose.yml` 注入,不需要手写 PostgreSQL URL。若修改 `COMPOSE_PROJECT_NAME`,新卷名前缀也会变化;已有部署升级时保留原 `.env`,避免误用新空卷。
|
||||
|
||||
Docker 中的自动续期会使用容器内 Chromium 检测到的 Linux 原生浏览器指纹请求闲鱼官网;不会因为宿主系统是 Linux 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
|
||||
|
||||
## SQLite
|
||||
|
||||
适合开发或轻量单机。默认数据库路径为 `data/xianyu_data.db`:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
```
|
||||
|
||||
也可显式指定:
|
||||
|
||||
```bash
|
||||
DATABASE_URL="sqlite://data/xianyu_data.db" ./xianyu-server
|
||||
```
|
||||
|
||||
备份时先停服务,或使用 SQLite 在线备份工具;不要只复制正在写入的 WAL 数据库主文件。恢复时同时恢复数据库和原有 `XIANYU_DATA_KEY`。
|
||||
|
||||
## MySQL
|
||||
|
||||
先创建 UTF-8 数据库和最小权限账号,再为应用提供 URL:
|
||||
|
||||
```bash
|
||||
DATABASE_URL="mysql://user:URL编码后的密码@tcp(db.example:3306)/xianyu" \
|
||||
./xianyu-server -addr :8080
|
||||
```
|
||||
|
||||
应用会补齐所需 MySQL 连接参数。密码中出现 `@`、`:`、`/` 等字符时必须 URL 编码。使用 TLS 的环境请按数据库驱动/基础设施要求配置安全连接,不要把真实密码写进命令历史。
|
||||
|
||||
## PostgreSQL(外部服务)
|
||||
|
||||
```bash
|
||||
DATABASE_URL="postgres://user:URL编码后的密码@db.example:5432/xianyu?sslmode=require" \
|
||||
./xianyu-server -addr :8080
|
||||
```
|
||||
|
||||
仅在受信任的本机网络可考虑 `sslmode=disable`;公网或跨网络部署应使用 TLS。数据库账号只应拥有该应用数据库的必要权限。
|
||||
|
||||
## 初始化、备份和升级
|
||||
|
||||
初始化管理员:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '强密码'
|
||||
```
|
||||
|
||||
已有管理员时,仅确保其存在而不重置密码:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -ensure-admin -admin-password '强密码'
|
||||
```
|
||||
|
||||
PostgreSQL 备份示例:
|
||||
|
||||
```bash
|
||||
docker compose exec -T postgres pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
|
||||
> ydisks-backup.sql
|
||||
```
|
||||
|
||||
升级顺序:备份数据库和 `.env` → 拉取/构建新镜像 → `docker compose up -d` → 查看日志确认迁移成功 → 登录检查账号和自动化任务。若迁移失败,停止继续操作并从备份恢复。
|
||||
+29
-8
@@ -28,13 +28,13 @@
|
||||
表头必须完全一致(大小写敏感、无空格)。**推荐用中文表头**,复制下面这一行:
|
||||
|
||||
```
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
```
|
||||
|
||||
如果用英文表头,对应是:
|
||||
|
||||
```
|
||||
cookie_id,title,description,price,original_price,quantity,postage_mode,postage,images,paid_delivery_enabled,paid_delivery_contents,review_gift_enabled,review_gift_contents,review_request_enabled,review_request_after_hours,review_request_message,review_request_max_attempts
|
||||
cookie_id,title,description,price,original_price,quantity,postage_mode,postage,images,category_id,category_name,channel_category_id,tb_category_id,paid_delivery_enabled,paid_delivery_contents,review_gift_enabled,review_gift_contents,review_request_enabled,review_request_after_hours,review_request_message,review_request_max_attempts
|
||||
```
|
||||
|
||||
> 中英文表头二选一,**不要混用**。每个表头单元格的匹配是精确匹配,多空格、全角半角差异都会导致该列识别失败。
|
||||
@@ -55,6 +55,24 @@ cookie_id,title,description,price,original_price,quantity,postage_mode,postage,i
|
||||
| 邮费 | 条件必填 | 数字。邮费模式为 `fixed` 时必填;`free` 时留空 | `8.00` |
|
||||
| 图片 | 是 | 1–9 张,多个用 `;` 分隔。每项是公网 URL 或图片包内相对路径 | `images/bundle-1.jpg;images/bundle-2.jpg` |
|
||||
|
||||
#### 指定类目字段(可选的逐行默认类目)
|
||||
|
||||
| 列 | 何时填写 | 格式 / 取值 |
|
||||
|---|---|---|
|
||||
| 类目ID | 当前行需要指定默认类目时 | 闲鱼商品类目 ID;必须和“类目名称、频道类目ID”同时填写 |
|
||||
| 类目名称 | 填写了“类目ID”时 | 与类目 ID 对应的准确名称 |
|
||||
| 频道类目ID | 填写了“类目ID”时 | 必须填写闲鱼推荐响应中的准确频道类目 ID |
|
||||
| 淘宝类目ID | 闲鱼响应有值时 | 按原样填写;“电子资料”没有该值,保持为空 |
|
||||
|
||||
上传页面的默认类目可以留空。需要整批固定类目时,选择发布账号后输入关键词,由闲鱼推荐接口返回并保存完整类目信息。系统对每行按以下顺序处理:
|
||||
|
||||
1. 当前行填写了完整类目字段时,优先使用当前行类目。
|
||||
2. 否则,上传页已通过关键词选择默认类目时,使用页面默认类目。
|
||||
3. 前两项均为空时,调用闲鱼接口,根据标题、描述和图片自动识别。
|
||||
4. 闲鱼明确没有识别结果时,最终使用“电子资料”(类目 ID `50023914`、频道类目 ID `202036301`)。
|
||||
|
||||
因此,表格和上传页都不指定类目时,系统会先自动识别,并只在没有匹配结果时使用“电子资料”。接口超时、鉴权失败和风控错误不会被最终兜底掩盖。
|
||||
|
||||
#### 自动化字段(可选,不填或填"否"表示不启用)
|
||||
|
||||
启用值接受:`1` / `true` / `yes` / `y` / `on` / `是` / `开启` / `启用`(不区分大小写)。
|
||||
@@ -152,6 +170,7 @@ sub/product.jpg
|
||||
| 邮费模式 | `free` 或 `fixed`(或 `包邮` / `固定邮费`) |
|
||||
| 邮费 | 邮费模式为 `fixed` 时必填且 ≥ 0 |
|
||||
| 图片 | 1–9 张;本地路径必须在 ZIP 内存在;URL 必须是合法 `http(s)://` |
|
||||
| 指定类目 | 当前行填写了任一类目字段时,“类目ID、类目名称、频道类目ID”必须同时存在;页面默认类目可为空 |
|
||||
| 付款发货 | 启用时:内容列必填至少一条卡密组;卡密组 ID 必须属于上传者;每件份数 > 0;延迟秒 ≥ 0 |
|
||||
| 评价赠品 | 同上 |
|
||||
| 求评价 | 启用时:等待小时 > 0、文案非空、最多次数 > 0 |
|
||||
@@ -178,19 +197,19 @@ sub/product.jpg
|
||||
|
||||
**表格 `商品清单.csv`:**
|
||||
```csv
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,普通商品,仅发布不绑自动化,49.90,,10,fixed,8.00,https://cdn.example.com/p1.jpg,否,,,,否,,,
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,普通商品,仅发布不绑自动化,49.90,,10,fixed,8.00,https://cdn.example.com/p1.jpg,,,,,否,,否,,否,,,
|
||||
```
|
||||
|
||||
无需图片包(用的是 URL)。
|
||||
无需图片包(用的是 URL)。四个逐行类目列可留空;页面默认类目也留空时,系统会自动识别。
|
||||
|
||||
### 7.2 完整自动化 + 本地图片包
|
||||
|
||||
**表格 `商品清单.csv`:**
|
||||
```csv
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,会员组合包自动发货,下单后发送主卡和附赠卡。,19.90,29.90,10,free,,images/bundle-1.jpg;images/bundle-2.jpg,是,101:1;102:1,是,201:1;202:2,是,72,亲,满意的话麻烦给个评价,谢谢~,1
|
||||
2222660684687,单卡直发,拍下自动发卡。,9.90,,50,free,,images/single.jpg,是,101:1,否,,否,,,
|
||||
账号ID,标题,描述,价格,原价,库存,邮费模式,邮费,图片,类目ID,类目名称,频道类目ID,淘宝类目ID,付款发货启用,付款发货内容,评价赠品启用,评价赠品内容,求评价启用,求评价等待小时,求评价文案,求评价最多次数
|
||||
2222660684687,会员组合包自动发货,下单后发送主卡和附赠卡。,19.90,29.90,10,free,,images/bundle-1.jpg;images/bundle-2.jpg,,,,,是,101:1;102:1,是,201:1;202:2,是,72,亲,满意的话麻烦给个评价,谢谢~,1
|
||||
2222660684687,单卡直发,拍下自动发卡。,9.90,,50,free,,images/single.jpg,,,,,是,101:1,否,,否,,,
|
||||
```
|
||||
|
||||
**图片包 `images.zip`:**
|
||||
@@ -215,6 +234,8 @@ images.zip
|
||||
- [ ] 每行标题非空、价格 > 0、库存 > 0
|
||||
- [ ] 邮费模式只填 `free` / `fixed`(或 `包邮` / `固定邮费`);`fixed` 时邮费已填
|
||||
- [ ] 每行图片 1–9 张,多个用 `;` 分隔
|
||||
- [ ] 需要整批固定类目时,已在上传页通过关键词获取默认类目;否则保持为空
|
||||
- [ ] 需要逐行指定类目时,“类目ID、类目名称、频道类目ID”同时填写;淘宝类目 ID 按接口响应填写
|
||||
- [ ] 用本地路径的图片,在 ZIP 内对应路径都能找到
|
||||
- [ ] 用 URL 的图片,链接是 `http(s)://` 且可公开访问
|
||||
- [ ] 启用了付款发货/评价赠品的行,内容列按 §3 格式填写,卡密组 ID 已知(或已标注需运营补填)
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
# 闲鱼管家前端
|
||||
# Ydisks闲鱼助手前端
|
||||
|
||||
React + Vite + TypeScript 单页应用,作为闲鱼管家 Go 后端的管理面板。
|
||||
React + Vite + TypeScript 单页应用,作为 Ydisks闲鱼助手 Go 后端的管理面板。
|
||||
|
||||
## 目录结构
|
||||
|
||||
@@ -19,7 +19,7 @@ frontend/
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend
|
||||
cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper/frontend
|
||||
npm install
|
||||
npm run dev # http://localhost:3000,API 代理到 localhost:8080
|
||||
```
|
||||
|
||||
@@ -43,6 +43,9 @@ const AccountList: React.FC = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [accountSearch, setAccountSearch] = useState('');
|
||||
const [refreshingProfileId, setRefreshingProfileId] = useState<string>('');
|
||||
const [deletingAccountId, setDeletingAccountId] = useState<string>('');
|
||||
const [deleteDialogAccount, setDeleteDialogAccount] = useState<AccountDetail | null>(null);
|
||||
const [deleteError, setDeleteError] = useState('');
|
||||
const [showQRModal, setShowQRModal] = useState(false);
|
||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||
const [qrStatus, setQrStatus] = useState<string>('pending');
|
||||
@@ -260,10 +263,32 @@ const AccountList: React.FC = () => {
|
||||
loadAccounts();
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (confirm('确认删除该账号吗?')) {
|
||||
await deleteAccount(id);
|
||||
loadAccounts();
|
||||
const openDeleteDialog = (account: AccountDetail) => {
|
||||
if (deletingAccountId) return;
|
||||
setDeleteError('');
|
||||
setDeleteDialogAccount(account);
|
||||
};
|
||||
|
||||
const closeDeleteDialog = () => {
|
||||
if (deletingAccountId) return;
|
||||
setDeleteError('');
|
||||
setDeleteDialogAccount(null);
|
||||
};
|
||||
|
||||
const confirmDeleteAccount = async () => {
|
||||
const account = deleteDialogAccount;
|
||||
if (!account || deletingAccountId) return;
|
||||
setDeletingAccountId(account.id);
|
||||
setDeleteError('');
|
||||
try {
|
||||
await deleteAccount(account.id);
|
||||
setAccounts(current => current.filter(item => item.id !== account.id));
|
||||
setDeleteDialogAccount(null);
|
||||
} catch (error: any) {
|
||||
console.error('删除账号失败:', error);
|
||||
setDeleteError(error?.message || '删除账号失败,请稍后重试');
|
||||
} finally {
|
||||
setDeletingAccountId('');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -800,10 +825,14 @@ const AccountList: React.FC = () => {
|
||||
<Power className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(account.id)}
|
||||
className="p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500"
|
||||
onClick={() => openDeleteDialog(account)}
|
||||
disabled={deletingAccountId !== ''}
|
||||
className="p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
title={deletingAccountId === account.id ? '删除中…' : `删除账号 ${account.nickname || account.remark || account.id}`}
|
||||
>
|
||||
<Trash2 className="w-5 h-5" />
|
||||
{deletingAccountId === account.id
|
||||
? <Loader2 className="w-5 h-5 animate-spin" />
|
||||
: <Trash2 className="w-5 h-5" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -826,6 +855,105 @@ const AccountList: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 删除账号确认弹窗 */}
|
||||
{deleteDialogAccount && createPortal(
|
||||
<div className="modal-overlay-centered" role="presentation">
|
||||
<div
|
||||
className="h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-[0_24px_64px_rgba(15,23,42,0.22)]"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="delete-account-title"
|
||||
aria-describedby="delete-account-description"
|
||||
>
|
||||
<div className="relative overflow-hidden border-b border-red-100 bg-gradient-to-br from-red-50 via-white to-orange-50 px-5 py-5">
|
||||
<div className="absolute -right-12 -top-16 h-36 w-36 rounded-full bg-red-200/35 blur-2xl" />
|
||||
<div className="relative flex items-start gap-4">
|
||||
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-red-600 text-white shadow-md shadow-red-200">
|
||||
<Trash2 className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 id="delete-account-title" className="text-lg font-extrabold tracking-tight text-gray-950">
|
||||
删除这个账号?
|
||||
</h3>
|
||||
<p id="delete-account-description" className="mt-1 text-xs leading-5 text-gray-600">
|
||||
删除后,该账号的关联配置也会一并清理,此操作无法撤销。
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={closeDeleteDialog}
|
||||
disabled={deletingAccountId !== ''}
|
||||
className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors hover:bg-white hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
aria-label="关闭删除确认"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-5 py-4">
|
||||
<div className="rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3">
|
||||
<div className="text-sm font-extrabold text-gray-900">
|
||||
{deleteDialogAccount.nickname || deleteDialogAccount.remark || '未命名账号'}
|
||||
</div>
|
||||
{deleteDialogAccount.remark && deleteDialogAccount.nickname && (
|
||||
<div className="mt-1 text-sm text-gray-500">备注:{deleteDialogAccount.remark}</div>
|
||||
)}
|
||||
<div className="mt-1.5 break-all font-mono text-[11px] text-gray-400">ID: {deleteDialogAccount.id}</div>
|
||||
</div>
|
||||
|
||||
{deletingAccountId === deleteDialogAccount.id && (
|
||||
<div
|
||||
className="mt-4 flex items-center gap-3 rounded-xl border border-blue-100 bg-blue-50 px-4 py-3"
|
||||
role="progressbar"
|
||||
aria-label="正在删除账号"
|
||||
>
|
||||
<Loader2 className="h-5 w-5 flex-shrink-0 animate-spin text-[#0094f7]" />
|
||||
<div>
|
||||
<div className="text-sm font-extrabold text-blue-950">正在删除账号</div>
|
||||
<div className="mt-0.5 text-xs text-blue-700">正在清理关联数据,请保持页面打开…</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{deleteError && (
|
||||
<div className="mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3" role="alert">
|
||||
<AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-red-600" />
|
||||
<div>
|
||||
<div className="text-sm font-extrabold text-red-800">删除失败</div>
|
||||
<div className="mt-1 text-xs leading-5 text-red-700">{deleteError}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 border-t border-gray-100 bg-gray-50/70 px-5 py-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={closeDeleteDialog}
|
||||
disabled={deletingAccountId !== ''}
|
||||
className="flex-1 rounded-xl bg-white px-5 py-3 text-sm font-extrabold text-gray-700 ring-1 ring-gray-200 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void confirmDeleteAccount()}
|
||||
disabled={deletingAccountId !== ''}
|
||||
className="flex flex-1 items-center justify-center gap-2 rounded-xl bg-red-600 px-5 py-3 text-sm font-extrabold text-white shadow-lg shadow-red-200 transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:bg-red-400"
|
||||
>
|
||||
{deletingAccountId === deleteDialogAccount.id ? (
|
||||
<><Loader2 className="h-4 w-4 animate-spin" />处理中</>
|
||||
) : (
|
||||
<><Trash2 className="h-4 w-4" />确认删除</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
|
||||
{/* QR Code Modal */}
|
||||
{showQRModal && createPortal(
|
||||
<div className="modal-overlay-centered">
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
syncItemsFromAccount,
|
||||
createItem,
|
||||
publishItem,
|
||||
recommendPublishCategory,
|
||||
previewItemPublishBatch,
|
||||
startItemPublishBatch,
|
||||
getItemPublishBatch,
|
||||
@@ -19,7 +20,7 @@ import {
|
||||
deleteItem,
|
||||
getShippingRules
|
||||
} from '../services/api';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
|
||||
|
||||
interface ItemListProps {
|
||||
onConfigureDelivery: (item: Item) => void;
|
||||
@@ -27,6 +28,13 @@ interface ItemListProps {
|
||||
|
||||
type BatchPhase = 'upload' | 'preview' | 'running' | 'done';
|
||||
|
||||
interface PublishCategory {
|
||||
cat_id: string;
|
||||
cat_name: string;
|
||||
channel_cat_id?: string;
|
||||
tb_cat_id?: string;
|
||||
}
|
||||
|
||||
interface PublishBatchPreviewRow {
|
||||
row_no: number;
|
||||
valid: boolean;
|
||||
@@ -36,6 +44,7 @@ interface PublishBatchPreviewRow {
|
||||
price: string;
|
||||
quantity: number;
|
||||
images: string[];
|
||||
category: PublishCategory;
|
||||
}
|
||||
|
||||
interface PublishBatchDetailRow {
|
||||
@@ -51,6 +60,7 @@ interface PublishBatchDetailRow {
|
||||
error_message: string;
|
||||
failure_kind: string;
|
||||
images?: string[];
|
||||
category: PublishCategory;
|
||||
}
|
||||
|
||||
interface PublishBatchDetail {
|
||||
@@ -88,6 +98,14 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const [batchPhase, setBatchPhase] = useState<BatchPhase>('upload');
|
||||
const [batchFile, setBatchFile] = useState<File | null>(null);
|
||||
const [batchImagesZip, setBatchImagesZip] = useState<File | null>(null);
|
||||
const [batchCategoryKeyword, setBatchCategoryKeyword] = useState('');
|
||||
const [batchCategoryLoading, setBatchCategoryLoading] = useState(false);
|
||||
const [batchFallbackCategory, setBatchFallbackCategory] = useState({
|
||||
catId: '',
|
||||
catName: '',
|
||||
channelCatId: '',
|
||||
tbCatId: '',
|
||||
});
|
||||
const [batchPreview, setBatchPreview] = useState<{
|
||||
preview_id: string;
|
||||
total: number;
|
||||
@@ -319,6 +337,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
setBatchDetail(null);
|
||||
setBatchFile(null);
|
||||
setBatchImagesZip(null);
|
||||
setBatchCategoryKeyword('');
|
||||
setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' });
|
||||
setShowBatchModal(true);
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
@@ -337,6 +357,28 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleRecommendBatchCategory = async () => {
|
||||
const keyword = batchCategoryKeyword.trim();
|
||||
if (!selectedAccount) return alert('请先选择默认发布账号');
|
||||
if (!keyword) return alert('请输入类目关键词');
|
||||
setBatchCategoryLoading(true);
|
||||
try {
|
||||
const result = await recommendPublishCategory(selectedAccount, keyword);
|
||||
const category = result.category;
|
||||
setBatchFallbackCategory({
|
||||
catId: category.cat_id,
|
||||
catName: category.cat_name,
|
||||
channelCatId: category.channel_cat_id,
|
||||
tbCatId: category.tb_cat_id || '',
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('获取推荐类目失败:', error);
|
||||
alert(error?.message || '没有匹配到类目,请换一个更具体的关键词');
|
||||
} finally {
|
||||
setBatchCategoryLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openRecentBatchResult = async () => {
|
||||
if (!recentBatch?.id) return;
|
||||
setBatchLoading(true);
|
||||
@@ -361,6 +403,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
file: batchFile,
|
||||
imagesZip: batchImagesZip,
|
||||
defaultCookieId: selectedAccount,
|
||||
fallbackCategory: batchFallbackCategory,
|
||||
});
|
||||
setBatchPreview(result);
|
||||
setBatchDetail(null);
|
||||
@@ -442,12 +485,13 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
const downloadPublishTemplate = () => {
|
||||
const headers = [
|
||||
'账号ID', '标题', '描述', '价格', '原价', '库存', '邮费模式', '邮费', '图片',
|
||||
'类目ID', '类目名称', '频道类目ID', '淘宝类目ID',
|
||||
'付款发货启用', '付款发货内容', '评价赠品启用', '评价赠品内容',
|
||||
'求评价启用', '求评价等待小时', '求评价文案', '求评价最多次数',
|
||||
];
|
||||
const rows = [
|
||||
['', '会员组合包自动发货', '下单后发送主卡和附赠卡。', '19.90', '29.90', '10', 'free', '', 'images/bundle-1.jpg;images/bundle-2.jpg', '是', '101:1;102:1', '是', '201:1;202:2', '是', '72', '亲,满意的话麻烦给个评价,谢谢~', '1'],
|
||||
['', '普通商品', '仅发布商品,不创建自动化规则。', '49.90', '', '10', 'fixed', '8.00', 'https://example.com/product.jpg', '否', '', '否', '', '否', '', '', ''],
|
||||
['', '会员组合包自动发货', '下单后发送主卡和附赠卡。', '19.90', '29.90', '10', 'free', '', 'images/bundle-1.jpg;images/bundle-2.jpg', '', '', '', '', '是', '101:1;102:1', '是', '201:1;202:2', '是', '72', '亲,满意的话麻烦给个评价,谢谢~', '1'],
|
||||
['', '普通商品', '仅发布商品,不创建自动化规则。', '49.90', '', '10', 'fixed', '8.00', 'https://example.com/product.jpg', '', '', '', '', '否', '', '否', '', '否', '', '', ''],
|
||||
];
|
||||
const csv = [headers, ...rows]
|
||||
.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
|
||||
@@ -915,6 +959,59 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<p className="text-xs text-gray-500">表格中“账号ID”为空时,会使用这里选择的账号。</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-amber-200 bg-amber-50/70 p-4 space-y-3">
|
||||
<div>
|
||||
<div className="text-sm font-extrabold text-gray-900">默认类目 <span className="font-medium text-gray-500">(可为空)</span></div>
|
||||
<p className="mt-1 text-xs leading-5 text-amber-800">填写后优先使用该类目;留空时由闲鱼根据每件商品自动识别。仍无法识别时,系统最终使用“电子资料”兜底。</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<label className="relative flex-1">
|
||||
<span className="sr-only">类目关键词</span>
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
className="w-full ios-input rounded-xl bg-white py-2.5 pl-10 pr-3"
|
||||
placeholder="输入关键词,例如:课程资料、设计素材"
|
||||
value={batchCategoryKeyword}
|
||||
onChange={e => setBatchCategoryKeyword(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
void handleRecommendBatchCategory();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!selectedAccount || !batchCategoryKeyword.trim() || batchCategoryLoading}
|
||||
onClick={() => void handleRecommendBatchCategory()}
|
||||
className="ios-btn-primary flex min-h-[42px] items-center justify-center gap-2 rounded-xl px-4 text-sm font-bold disabled:opacity-50"
|
||||
>
|
||||
<Search className="h-4 w-4" />
|
||||
{batchCategoryLoading ? '匹配中...' : '获取类目'}
|
||||
</button>
|
||||
</div>
|
||||
{batchFallbackCategory.catId ? (
|
||||
<div className="flex min-h-[46px] items-center justify-between gap-3 border-t border-amber-200 pt-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 text-sm font-bold text-gray-900">
|
||||
<CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-600" />
|
||||
<span className="truncate">{batchFallbackCategory.catName}</span>
|
||||
</div>
|
||||
<div className="mt-1 font-mono text-xs text-gray-500">类目 {batchFallbackCategory.catId} · 频道 {batchFallbackCategory.channelCatId}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
title="清除默认类目"
|
||||
onClick={() => setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' })}
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-gray-500 hover:bg-white hover:text-gray-900"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors">
|
||||
<UploadCloud className="w-9 h-9 text-blue-600 mb-3" />
|
||||
@@ -986,6 +1083,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
['邮费模式', '可以留空', '留空表示包邮;包邮填 free,固定邮费填 fixed'],
|
||||
['邮费', '邮费模式填 fixed 时填写', '只填数字,例如 8.00'],
|
||||
['图片', '每个商品都要填', '填写 zip 内图片路径或图片网址;多张图片用英文分号隔开'],
|
||||
['类目ID', '需要指定当前行默认类目时填写', '必须和“类目名称、频道类目ID”同时填写;优先于自动识别'],
|
||||
['类目名称', '填写了“类目ID”时必填', '填写该 ID 对应的准确类目名称'],
|
||||
['频道类目ID', '覆盖类目时必填', '必须填写闲鱼返回的准确频道类目 ID'],
|
||||
['淘宝类目ID', '按闲鱼返回填写', '“电子资料”无淘宝类目 ID,保持为空'],
|
||||
['付款发货启用', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
['付款发货内容', '“付款发货启用”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'],
|
||||
['评价赠品启用', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'],
|
||||
@@ -1033,6 +1134,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<th className="px-4 py-3">状态</th>
|
||||
<th className="px-4 py-3">标题</th>
|
||||
<th className="px-4 py-3">价格/库存</th>
|
||||
<th className="px-4 py-3">类目策略</th>
|
||||
<th className="px-4 py-3">图片</th>
|
||||
<th className="px-4 py-3">问题</th>
|
||||
</tr>
|
||||
@@ -1048,6 +1150,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</td>
|
||||
<td className="px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate">{row.title || '-'}</td>
|
||||
<td className="px-4 py-3 text-gray-600">¥{row.price || '-'} / {row.quantity || 1}</td>
|
||||
<td className="px-4 py-3 text-xs text-gray-600 min-w-[150px]">
|
||||
<div className="font-bold text-gray-800">{row.category?.cat_name || '自动识别'}</div>
|
||||
<div className="font-mono text-gray-400">{row.category?.cat_id || '失败后使用电子资料'}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-600">{row.images?.length || 0} 张</td>
|
||||
<td className="px-4 py-3 text-red-600 text-xs max-w-[280px]">{row.errors?.join(';') || '-'}</td>
|
||||
</tr>
|
||||
@@ -1090,6 +1196,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
<th className="px-4 py-3">行号</th>
|
||||
<th className="px-4 py-3">状态</th>
|
||||
<th className="px-4 py-3">标题</th>
|
||||
<th className="px-4 py-3">类目策略</th>
|
||||
<th className="px-4 py-3">商品ID</th>
|
||||
<th className="px-4 py-3">错误原因</th>
|
||||
</tr>
|
||||
@@ -1104,6 +1211,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate">{row.title}</td>
|
||||
<td className="px-4 py-3 text-xs text-gray-600 min-w-[150px]">
|
||||
<div className="font-bold text-gray-800">{row.category?.cat_name || '自动识别'}</div>
|
||||
<div className="font-mono text-gray-400">{row.category?.cat_id || '失败后使用电子资料'}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs font-mono">
|
||||
{row.item_url ? <a href={row.item_url} target="_blank" rel="noreferrer" className="text-blue-600 hover:underline">{row.item_id}</a> : (row.item_id || '-')}
|
||||
</td>
|
||||
|
||||
@@ -31,7 +31,7 @@ const CHANNEL_TYPES: Record<NotificationChannelType, ChannelTypeMeta> = {
|
||||
fields: [
|
||||
{ key: 'server_url', label: 'Bark 服务器', placeholder: 'https://api.day.app', required: true },
|
||||
{ key: 'device_key', label: 'Device Key', placeholder: '你的 Bark 设备 Key', required: true },
|
||||
{ key: 'title', label: '标题(可选)', placeholder: '闲鱼助手' },
|
||||
{ key: 'title', label: '标题(可选)', placeholder: 'Ydisks闲鱼助手' },
|
||||
{ key: 'sound', label: '铃声(可选)', placeholder: 'default' },
|
||||
{ key: 'group', label: '分组(可选)', placeholder: 'xianyu' },
|
||||
],
|
||||
|
||||
+209
-25
@@ -24,6 +24,7 @@ import {
|
||||
getAutomationIssues,
|
||||
getReplyRules,
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
updateDefaultReply,
|
||||
updateReplyRule,
|
||||
updateShippingRule,
|
||||
@@ -36,6 +37,8 @@ import {
|
||||
AlertCircle,
|
||||
Bot,
|
||||
CheckCircle2,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Clock3,
|
||||
Edit,
|
||||
Gift,
|
||||
@@ -45,7 +48,9 @@ import {
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Save,
|
||||
Search,
|
||||
Send,
|
||||
SlidersHorizontal,
|
||||
Trash2,
|
||||
X,
|
||||
Zap,
|
||||
@@ -54,7 +59,6 @@ import {
|
||||
automationIssueKindLabel,
|
||||
canResolveAutomationIssue,
|
||||
filterAutomationIssues,
|
||||
loadAutomationPageData,
|
||||
} from './automationIssueState';
|
||||
import { commitIfLatest } from './latestRequest';
|
||||
|
||||
@@ -220,6 +224,15 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selectedAccountId, setSelectedAccountId] = useState('');
|
||||
const [automationSearch, setAutomationSearch] = useState('');
|
||||
const [debouncedAutomationSearch, setDebouncedAutomationSearch] = useState('');
|
||||
const [automationTriggerFilter, setAutomationTriggerFilter] = useState<AutomationTriggerType | ''>('');
|
||||
const [automationStatusFilter, setAutomationStatusFilter] = useState<'all' | 'enabled' | 'disabled'>('all');
|
||||
const [automationPage, setAutomationPage] = useState(1);
|
||||
const [automationPageSize, setAutomationPageSize] = useState(10);
|
||||
const [automationTotal, setAutomationTotal] = useState(0);
|
||||
const [automationTotalPages, setAutomationTotalPages] = useState(0);
|
||||
const automationRulesRequest = useRef(0);
|
||||
const replyRulesRequest = useRef(0);
|
||||
const selectedAccountRef = useRef('');
|
||||
selectedAccountRef.current = selectedAccountId;
|
||||
@@ -253,14 +266,28 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
}, []);
|
||||
|
||||
const loadAutomationRules = useCallback(async () => {
|
||||
await loadAutomationPageData({
|
||||
loadRules: getShippingRules,
|
||||
loadIssues: getAutomationIssues,
|
||||
onRules: setAutomationRules,
|
||||
onIssues: setAutomationIssues,
|
||||
onIssuesError: error => console.warn('加载自动化异常列表失败,不阻断规则展示', error),
|
||||
const requestID = ++automationRulesRequest.current;
|
||||
const issuesPromise = getAutomationIssues().catch(error => {
|
||||
console.warn('加载自动化异常列表失败,不阻断规则展示', error);
|
||||
return null;
|
||||
});
|
||||
}, []);
|
||||
const result = await getShippingRulesPage({
|
||||
cookieId: selectedAccountId || undefined,
|
||||
triggerType: automationTriggerFilter,
|
||||
enabled: automationStatusFilter === 'all' ? undefined : automationStatusFilter === 'enabled',
|
||||
search: debouncedAutomationSearch,
|
||||
page: automationPage,
|
||||
pageSize: automationPageSize,
|
||||
});
|
||||
if (requestID !== automationRulesRequest.current) return;
|
||||
setAutomationRules(result.data);
|
||||
setAutomationTotal(result.total);
|
||||
setAutomationTotalPages(result.total_pages);
|
||||
if (result.page !== automationPage) setAutomationPage(result.page);
|
||||
const issues = await issuesPromise;
|
||||
if (requestID !== automationRulesRequest.current) return;
|
||||
if (issues) setAutomationIssues(issues);
|
||||
}, [automationPage, automationPageSize, automationStatusFilter, automationTriggerFilter, debouncedAutomationSearch, selectedAccountId]);
|
||||
|
||||
const loadReplyRules = useCallback(async () => {
|
||||
const cookieID = selectedAccountId;
|
||||
@@ -293,6 +320,14 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
}
|
||||
}, [activeTab, loadAutomationRules, loadDefaultReplies, loadReplyRules]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setAutomationPage(1);
|
||||
setDebouncedAutomationSearch(automationSearch.trim());
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [automationSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadReferenceData().catch(error => console.error('加载规则参考数据失败', error));
|
||||
}, [loadReferenceData]);
|
||||
@@ -328,6 +363,25 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
return grouped;
|
||||
}, [visibleAutomationRules]);
|
||||
|
||||
const automationPageNumbers = useMemo(() => {
|
||||
if (automationTotalPages <= 1) return [];
|
||||
const first = Math.max(1, Math.min(automationPage - 2, automationTotalPages - 4));
|
||||
const last = Math.min(automationTotalPages, first + 4);
|
||||
return Array.from({ length: last - first + 1 }, (_, index) => first + index);
|
||||
}, [automationPage, automationTotalPages]);
|
||||
|
||||
const hasAutomationListFilters = Boolean(
|
||||
automationSearch.trim() || automationTriggerFilter || automationStatusFilter !== 'all',
|
||||
);
|
||||
|
||||
const clearAutomationListFilters = () => {
|
||||
setAutomationSearch('');
|
||||
setDebouncedAutomationSearch('');
|
||||
setAutomationTriggerFilter('');
|
||||
setAutomationStatusFilter('all');
|
||||
setAutomationPage(1);
|
||||
};
|
||||
|
||||
const modalAccountItems = useMemo(() => {
|
||||
const cookieID = editingAutomationRule?.cookie_id || selectedAccountId;
|
||||
return items.filter(item => item.cookie_id === cookieID);
|
||||
@@ -748,15 +802,18 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-fade-in">
|
||||
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
|
||||
<div className="flex flex-col xl:flex-row justify-between xl:items-end gap-4">
|
||||
<div>
|
||||
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">自动化规则</h2>
|
||||
<p className="text-gray-500 mt-2 font-medium">系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。</p>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<div className="flex flex-col sm:flex-row sm:flex-wrap gap-3">
|
||||
<select
|
||||
value={selectedAccountId}
|
||||
onChange={event => setSelectedAccountId(event.target.value)}
|
||||
onChange={event => {
|
||||
setSelectedAccountId(event.target.value);
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input px-4 py-3 rounded-2xl text-sm min-w-64"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
@@ -766,7 +823,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</select>
|
||||
<button
|
||||
onClick={refresh}
|
||||
className="px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 transition-colors"
|
||||
className="px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 whitespace-nowrap transition-colors"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
刷新
|
||||
@@ -774,7 +831,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
<button
|
||||
onClick={activeTab === 'automation' ? () => openNewAutomationRule('order_paid') : activeTab === 'reply' ? handleAddReplyRule : () => void openDefaultReplyModal()}
|
||||
disabled={!selectedAccountId}
|
||||
className="ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
className="ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 whitespace-nowrap disabled:opacity-50"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
{primaryActionLabel}
|
||||
@@ -879,7 +936,10 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm">
|
||||
<h3 className="font-black text-gray-900 mb-4">规则概览</h3>
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<h3 className="font-black text-gray-900">本页规则构成</h3>
|
||||
<span className="text-xs font-bold text-gray-400">共 {automationTotal} 条</span>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{triggerOrder.map(trigger => {
|
||||
const meta = triggerMeta[trigger];
|
||||
@@ -898,15 +958,82 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section className="space-y-4">
|
||||
{visibleAutomationRules.length === 0 ? (
|
||||
<div className="bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center">
|
||||
<Zap className="w-12 h-12 text-gray-300 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-black text-gray-900">还没有自动化规则</h3>
|
||||
<p className="text-gray-500 mt-2">从左侧选择一个模板开始配置。</p>
|
||||
</div>
|
||||
) : (
|
||||
visibleAutomationRules.map(rule => {
|
||||
<section className="space-y-4">
|
||||
<div className="rounded-xl border border-gray-100 bg-[#FAFAFA] p-4 shadow-sm">
|
||||
<div className="flex flex-col gap-3 xl:flex-row xl:items-center">
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="search"
|
||||
aria-label="搜索自动化规则"
|
||||
placeholder="搜索规则名、商品名或商品 ID..."
|
||||
value={automationSearch}
|
||||
onChange={event => {
|
||||
setAutomationSearch(event.target.value);
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative xl:w-52">
|
||||
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
|
||||
<select
|
||||
aria-label="按自动化类型筛选"
|
||||
value={automationTriggerFilter}
|
||||
onChange={event => {
|
||||
setAutomationTriggerFilter(event.target.value as AutomationTriggerType | '');
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm"
|
||||
>
|
||||
<option value="">全部自动化类型</option>
|
||||
{triggerOrder.map(trigger => <option key={trigger} value={trigger}>{triggerMeta[trigger].shortLabel}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<select
|
||||
aria-label="按启用状态筛选"
|
||||
value={automationStatusFilter}
|
||||
onChange={event => {
|
||||
setAutomationStatusFilter(event.target.value as 'all' | 'enabled' | 'disabled');
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input rounded-xl border-none bg-white px-4 py-2.5 text-sm shadow-sm xl:w-36"
|
||||
>
|
||||
<option value="all">全部状态</option>
|
||||
<option value="enabled">已启用</option>
|
||||
<option value="disabled">已禁用</option>
|
||||
</select>
|
||||
{hasAutomationListFilters && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={clearAutomationListFilters}
|
||||
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-100 hover:text-gray-900"
|
||||
title="清除筛选"
|
||||
aria-label="清除筛选"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-3 flex items-center justify-between text-xs font-bold text-gray-400">
|
||||
<span>找到 {automationTotal} 条规则</span>
|
||||
{loading && <span className="inline-flex items-center gap-1.5"><RefreshCw className="h-3.5 w-3.5 animate-spin" />正在更新</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && visibleAutomationRules.length === 0 ? (
|
||||
<div className="flex min-h-56 items-center justify-center rounded-xl border border-gray-100 bg-white text-sm font-bold text-gray-400">
|
||||
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
|
||||
正在加载规则
|
||||
</div>
|
||||
) : visibleAutomationRules.length === 0 ? (
|
||||
<div className="bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center">
|
||||
<Zap className="w-12 h-12 text-gray-300 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-black text-gray-900">{hasAutomationListFilters ? '没有匹配的自动化规则' : '还没有自动化规则'}</h3>
|
||||
<p className="text-gray-500 mt-2">{hasAutomationListFilters ? '调整或清除筛选条件后再试。' : '从左侧选择一个模板开始配置。'}</p>
|
||||
</div>
|
||||
) : (
|
||||
visibleAutomationRules.map(rule => {
|
||||
const meta = triggerMeta[rule.trigger_type];
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
@@ -957,8 +1084,65 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</article>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{automationTotal > 0 && (
|
||||
<div className="flex flex-col gap-3 rounded-xl border border-gray-100 bg-white px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-3 text-sm font-medium text-gray-500">
|
||||
<span>第 {automationPage} / {Math.max(automationTotalPages, 1)} 页</span>
|
||||
<span className="h-4 w-px bg-gray-200" />
|
||||
<label className="flex items-center gap-2">
|
||||
<span className="sr-only">每页显示数量</span>
|
||||
<select
|
||||
value={automationPageSize}
|
||||
onChange={event => {
|
||||
setAutomationPageSize(Number(event.target.value));
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input rounded-lg border-none bg-gray-50 px-2.5 py-2 text-sm"
|
||||
>
|
||||
{[10, 20, 50].map(size => <option key={size} value={size}>{size} 条/页</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={automationPage <= 1 || loading}
|
||||
onClick={() => setAutomationPage(page => Math.max(1, page - 1))}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
aria-label="上一页"
|
||||
title="上一页"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
{automationPageNumbers.map(pageNumber => (
|
||||
<button
|
||||
key={pageNumber}
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => setAutomationPage(pageNumber)}
|
||||
className={`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${pageNumber === automationPage ? 'bg-[#0094f7] text-white' : 'bg-gray-50 text-gray-600 hover:bg-gray-100'} disabled:cursor-not-allowed disabled:opacity-60`}
|
||||
aria-label={`第 ${pageNumber} 页`}
|
||||
aria-current={pageNumber === automationPage ? 'page' : undefined}
|
||||
>
|
||||
{pageNumber}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
disabled={automationPage >= automationTotalPages || loading}
|
||||
onClick={() => setAutomationPage(page => Math.min(automationTotalPages, page + 1))}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg bg-gray-50 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
aria-label="下一页"
|
||||
title="下一页"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "闲鱼自动发货-pro",
|
||||
"name": "ydisks-xianyu-helper",
|
||||
"version": "0.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "闲鱼自动发货-pro",
|
||||
"name": "ydisks-xianyu-helper",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"axios": "^1.13.2",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "闲鱼自动发货-pro",
|
||||
"name": "ydisks-xianyu-helper",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
getOrderAnalytics,
|
||||
getReplyRules,
|
||||
getShippingRules,
|
||||
getShippingRulesPage,
|
||||
getSystemSettings,
|
||||
getValidOrders,
|
||||
logout,
|
||||
@@ -108,6 +109,33 @@ test('getOrders maps unsupported backend statuses to unknown', async () => {
|
||||
expect(result.data[0].status).toBe('unknown');
|
||||
});
|
||||
|
||||
test('getShippingRulesPage sends filters and preserves pagination metadata', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
data: [{ id: 7, name: '付款规则', trigger_type: 'order_paid', enabled: false, actions: [] }],
|
||||
total: 21,
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
total_pages: 2,
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const result = await getShippingRulesPage({
|
||||
cookieId: 'acc1',
|
||||
triggerType: 'order_paid',
|
||||
enabled: false,
|
||||
search: ' 商品 ',
|
||||
page: 2,
|
||||
pageSize: 20,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ total: 21, page: 2, page_size: 20, total_pages: 2 });
|
||||
expect(result.data[0]).toMatchObject({ id: '7', name: '付款规则', enabled: false });
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/automation-rules?page=2&page_size=20&cookie_id=acc1&trigger_type=order_paid&enabled=false&search=%E5%95%86%E5%93%81',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'include' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('getValidOrders accepts wrapped responses', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
|
||||
orders: [{ order_id: 'o2', order_status: 'completed', quantity: '3' }],
|
||||
|
||||
@@ -2,7 +2,7 @@ import { get, post, put, del, postForm, type RequestControlOptions } from '../re
|
||||
import {
|
||||
LoginResponse, AccountDetail, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType
|
||||
} from '../types';
|
||||
import { formatLocalDate } from '../dateRange';
|
||||
@@ -476,15 +476,37 @@ export const publishItem = async (form: {
|
||||
return postForm('/items/publish', body);
|
||||
}
|
||||
|
||||
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<{
|
||||
success: boolean;
|
||||
category: {
|
||||
cat_id: string;
|
||||
cat_name: string;
|
||||
channel_cat_id: string;
|
||||
tb_cat_id?: string;
|
||||
};
|
||||
}> => {
|
||||
return post('/items/publish-categories/recommend', { cookie_id: cookieId, keyword });
|
||||
};
|
||||
|
||||
export const previewItemPublishBatch = async (form: {
|
||||
file: File;
|
||||
imagesZip?: File | null;
|
||||
defaultCookieId?: string;
|
||||
fallbackCategory: {
|
||||
catId: string;
|
||||
catName: string;
|
||||
channelCatId?: string;
|
||||
tbCatId?: string;
|
||||
};
|
||||
}): Promise<any> => {
|
||||
const body = new FormData();
|
||||
body.set('file', form.file);
|
||||
if (form.imagesZip) body.set('images_zip', form.imagesZip);
|
||||
if (form.defaultCookieId) body.set('default_cookie_id', form.defaultCookieId);
|
||||
body.set('fallback_category_id', form.fallbackCategory.catId);
|
||||
body.set('fallback_category_name', form.fallbackCategory.catName);
|
||||
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
return postForm('/items/publish-batches/preview', body);
|
||||
}
|
||||
|
||||
@@ -518,10 +540,7 @@ export const updateItem = async (cookieId: string, itemId: string, data: Partial
|
||||
}
|
||||
|
||||
// Rules - 自动化规则
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
const res = await get<any>('/automation-rules');
|
||||
const rules = Array.isArray(res) ? res : (res.data || res.rules || []);
|
||||
return rules.map((item: any) => ({
|
||||
const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map((item: any) => ({
|
||||
id: String(item.id),
|
||||
name: item.name || '',
|
||||
trigger_type: item.trigger_type || 'order_paid',
|
||||
@@ -565,6 +584,47 @@ export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
export const getShippingRules = async (): Promise<ShippingRule[]> => {
|
||||
const res = await get<any>('/automation-rules');
|
||||
const rules = Array.isArray(res) ? res : (res.data || res.rules || []);
|
||||
return normalizeShippingRules(rules);
|
||||
}
|
||||
|
||||
export interface ShippingRuleListParams {
|
||||
cookieId?: string;
|
||||
triggerType?: AutomationTriggerType | '';
|
||||
enabled?: boolean;
|
||||
search?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export const getShippingRulesPage = async ({
|
||||
cookieId,
|
||||
triggerType,
|
||||
enabled,
|
||||
search,
|
||||
page = 1,
|
||||
pageSize = 10,
|
||||
}: ShippingRuleListParams = {}): Promise<PaginatedResponse<ShippingRule>> => {
|
||||
const res = await get<any>('/automation-rules', {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
cookie_id: cookieId || undefined,
|
||||
trigger_type: triggerType || undefined,
|
||||
enabled,
|
||||
search: search?.trim() || undefined,
|
||||
});
|
||||
const rules = normalizeShippingRules(Array.isArray(res) ? res : (res.data || res.rules || []));
|
||||
return {
|
||||
success: true,
|
||||
data: rules,
|
||||
total: Number(res.total ?? rules.length),
|
||||
page: Number(res.page ?? page),
|
||||
page_size: Number(res.page_size ?? pageSize),
|
||||
total_pages: Number(res.total_pages ?? (rules.length ? 1 : 0)),
|
||||
};
|
||||
}
|
||||
|
||||
const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => {
|
||||
|
||||
+58
-45
@@ -342,6 +342,20 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
if a.orderMTop == nil {
|
||||
return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
|
||||
}
|
||||
detail, err := a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
if err == nil || !mtop.IsSessionExpiredErr(err) {
|
||||
return detail, err
|
||||
}
|
||||
a.logger.Warn("订单详情检测到 Session 过期,开始即时续期", "account", cookieID, "order_id", orderID)
|
||||
if !a.OnPasswordLoginRefresh(ctx, cookieID) {
|
||||
return nil, fmt.Errorf("订单详情 Session 过期且即时续期失败: %w", err)
|
||||
}
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
a.logger.Info("Cookie 即时续期成功,重新请求订单详情", "account", cookieID, "order_id", orderID)
|
||||
return a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
}
|
||||
|
||||
func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID string) (*automation.OrderDetail, error) {
|
||||
|
||||
a.orderFetchMu.Lock()
|
||||
defer a.orderFetchMu.Unlock()
|
||||
@@ -407,6 +421,15 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if a.store == nil || a.store.Automation == nil {
|
||||
return
|
||||
}
|
||||
if err := a.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
a.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func hasCompleteCookieSnapshot(metadata string) bool {
|
||||
_, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
|
||||
return ok
|
||||
@@ -551,7 +574,7 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe
|
||||
// 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
res, err := api.RenewAPIFirst(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
res, err := api.RenewAfterSessionExpired(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
if res != nil {
|
||||
var completeSnapshot []cookierefresh.BrowserCookie
|
||||
if res.CookieSnapshotComplete {
|
||||
@@ -564,9 +587,40 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe
|
||||
return false, saveErr
|
||||
}
|
||||
if res.HasPending() {
|
||||
a.watchPendingProtocolRenew(d.ID, res)
|
||||
// 官网 Promise 超时只记录错误,不把当前登录态判定为失效。
|
||||
return true, nil
|
||||
// 恢复路径不能把“底层请求仍在进行”提前记为成功,否则上层会
|
||||
// 重置失败计数并继续使用未确认的旧凭证。这里等待最终响应;定时
|
||||
// 调度仍使用异步 watcher,不阻塞健康账号。
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
late, waitErr := res.AwaitPending(waitCtx)
|
||||
waitCancel()
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
return false, waitErr
|
||||
}
|
||||
return false, errors.New("协议续期底层响应未返回结果")
|
||||
}
|
||||
var lateSnapshot []cookierefresh.BrowserCookie
|
||||
if late.CookieSnapshotComplete {
|
||||
lateSnapshot = late.CookieSnapshot
|
||||
if lateSnapshot == nil {
|
||||
lateSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if saveErr := save(late.NewCookies, late.SetCookies, lateSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if waitErr != nil {
|
||||
return false, waitErr
|
||||
}
|
||||
if late.Success {
|
||||
a.logger.Info("Go 协议续期迟到响应成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
message := strings.TrimSpace(late.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
}
|
||||
return false, errors.New(message)
|
||||
}
|
||||
if err == nil && res.Success {
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
@@ -576,47 +630,6 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDe
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (a *Adapter) watchPendingProtocolRenew(cookieID string, result *xrenew.Result) {
|
||||
if result == nil || !result.HasPending() || a.store == nil || a.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("等待协议续期底层响应失败", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
unlock := a.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
}
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
return
|
||||
}
|
||||
newCookies, metadata, changed := xrenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if changed {
|
||||
if saveErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
|
||||
return
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
a.logger.Info("已异步接收协议续期迟到 Cookie", "account", cookieID)
|
||||
}
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("协议续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
|
||||
var (
|
||||
_ engine.Handler = (*Adapter)(nil)
|
||||
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -103,6 +105,27 @@ type fakeOrderDetailClient struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
type scriptedOrderDetailClient struct {
|
||||
mu sync.Mutex
|
||||
results []struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
cookies string
|
||||
}
|
||||
}
|
||||
|
||||
func (f *scriptedOrderDetailClient) FetchOrderDetail(_ context.Context, cookies, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if len(f.results) == 0 {
|
||||
return nil, errors.New("unexpected order detail call")
|
||||
}
|
||||
next := f.results[0]
|
||||
f.results = f.results[1:]
|
||||
next.cookies = cookies
|
||||
return next.detail, next.err
|
||||
}
|
||||
|
||||
func (f *fakeOrderDetailClient) FetchOrderDetail(_ context.Context, _, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.calls++
|
||||
return f.detail, f.err
|
||||
@@ -380,6 +403,46 @@ func TestFetchOrderDetail_PersistsFlatGoMTopCookie(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchOrderDetailSessionExpiredRenewsAndRetries(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
oldCookie := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
|
||||
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) + "; havana_lgc2_77=old"
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", oldCookie, `{}`, now.Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Automation.DeferTask(ctx, db.DeferredAutomationTask{TaskKey: "blocked", CookieID: "cid", TriggerType: automation.TriggerOrderPaid, TaskJSON: `{}`, DueAt: now.Add(time.Hour).Unix(), ErrorMessage: "Session过期"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &scriptedOrderDetailClient{results: []struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
cookies string
|
||||
}{
|
||||
{err: errors.New("token API 返回非成功: FAIL_SYS_SESSION_EXPIRED::Session过期")},
|
||||
{detail: &mtop.OrderDetailResult{Quantity: "1", SpecName: "套餐", SpecValue: "续期版", Amount: "9.9"}},
|
||||
}}
|
||||
renewSvc, closeRenew := verifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetOrderDetailClient(client)
|
||||
detail, err := a.FetchOrderDetail(ctx, "cid", "expired-order", "item", "buyer", "")
|
||||
if err != nil || detail == nil || detail.SpecValue != "续期版" {
|
||||
t.Fatalf("detail=%+v err=%v", detail, err)
|
||||
}
|
||||
saved, _ := store.Cookies.GetValue(ctx, "cid")
|
||||
if !strings.Contains(saved, "havana_lgc2_77=verified") {
|
||||
t.Fatalf("renewed cookie not saved: %q", saved)
|
||||
}
|
||||
var dueAt int64
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='blocked'`).Scan(&dueAt); err != nil || dueAt != 0 {
|
||||
t.Fatalf("credential-blocked task not woken: due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew 浏览器未启用时仍先尝试接口轻量续期。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
@@ -403,6 +466,45 @@ func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
body string
|
||||
want bool
|
||||
wantCookie bool
|
||||
}{
|
||||
{name: "late success", body: `{"content":{"data":{"processFinished":true,"resultCode":100}}}`, want: true, wantCookie: true},
|
||||
{name: "late business failure", body: `{"content":{"data":{"processFinished":true,"resultCode":500}}}`, want: false, wantCookie: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
renewal.GlobalCooldown.Reset("cid")
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "late_cookie", Value: "saved", Path: "/"})
|
||||
_, _ = w.Write([]byte(tt.body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(xrenew.Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL,
|
||||
RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond,
|
||||
})
|
||||
if got := a.OnPasswordLoginRefresh(context.Background(), "cid"); got != tt.want {
|
||||
t.Fatalf("pending 最终恢复结果=%v want %v", got, tt.want)
|
||||
}
|
||||
saved, err := store.Cookies.GetValue(context.Background(), "cid")
|
||||
if err != nil || strings.Contains(saved, "late_cookie=saved") != tt.wantCookie {
|
||||
t.Fatalf("迟到 Cookie 保存异常: value=%q err=%v", saved, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
|
||||
@@ -19,8 +19,17 @@ import (
|
||||
var (
|
||||
errAutomationDeferred = errors.New("自动化动作已持久化等待执行")
|
||||
errAutomationNeedsReview = errors.New("自动化动作结果需要人工核对")
|
||||
// ErrMessageNotSent 表示错误发生在调用 WebSocket 发送之前,可以安全重试。
|
||||
// engine 通过 errors.Is 标记“连接尚未就绪”等运行时状态,避免被误判为
|
||||
// 远端可能已经收到消息。
|
||||
ErrMessageNotSent = errors.New("自动化消息确定未发送")
|
||||
)
|
||||
|
||||
type preparationError struct{ err error }
|
||||
|
||||
func (e *preparationError) Error() string { return e.err.Error() }
|
||||
func (e *preparationError) Unwrap() error { return e.err }
|
||||
|
||||
type uncertainActionError struct{ err error }
|
||||
|
||||
func (e *uncertainActionError) Error() string { return e.err.Error() }
|
||||
@@ -50,6 +59,12 @@ type MessageSender interface {
|
||||
UpdateCookie(cookieStr string)
|
||||
}
|
||||
|
||||
// automationReadySender 由能够报告实时连接状态的发送器选择性实现。
|
||||
// 未实现的测试或外部发送器保持向后兼容,视为已经就绪。
|
||||
type automationReadySender interface {
|
||||
AutomationReady() bool
|
||||
}
|
||||
|
||||
// OrderDetailFetcher 查询闲鱼订单详情。自动发货必须先拿到订单规格和购买数量,
|
||||
// 再按规则里的规格映射发货。
|
||||
type OrderDetailFetcher interface {
|
||||
@@ -114,7 +129,9 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
if task.TriggerType == "" || task.AccountID == "" {
|
||||
return false, nil
|
||||
}
|
||||
c.markEventFacts(ctx, task)
|
||||
if err := c.markEventFacts(ctx, task); err != nil {
|
||||
return false, err
|
||||
}
|
||||
paused, until, err := c.store.Cookies.IsPaused(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -161,6 +178,16 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
var firstErr error
|
||||
for _, rule := range rules {
|
||||
if err := c.executeRule(ctx, task, rule); err != nil {
|
||||
var prepErr *preparationError
|
||||
if errors.As(err, &prepErr) && !isDeferredReplay(task) {
|
||||
dueAt := time.Now().UTC().Add(time.Minute).Unix()
|
||||
if deferErr := c.deferTaskWithError(ctx, task, dueAt, prepErr.Error()); deferErr != nil {
|
||||
return false, errors.Join(err, fmt.Errorf("持久化前置失败任务: %w", deferErr))
|
||||
}
|
||||
c.logger.Warn("自动化前置处理失败,任务已持久化等待恢复", "account", task.AccountID,
|
||||
"order_id", task.OrderID, "trigger", task.TriggerType, "retry_at", dueAt, "err", err)
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, errAutomationDeferred) {
|
||||
return true, nil
|
||||
}
|
||||
@@ -194,7 +221,15 @@ func taskDelayCursor(task Task) int {
|
||||
return cursor
|
||||
}
|
||||
|
||||
func isDeferredReplay(task Task) bool {
|
||||
return task.Raw != nil && task.Raw["automation_deferred_replay"] == true
|
||||
}
|
||||
|
||||
func (c *Center) deferTask(ctx context.Context, task Task, dueAt int64) error {
|
||||
return c.deferTaskWithError(ctx, task, dueAt, "")
|
||||
}
|
||||
|
||||
func (c *Center) deferTaskWithError(ctx context.Context, task Task, dueAt int64, errMsg string) error {
|
||||
key := buildTriggerKey(task)
|
||||
if key == "" {
|
||||
return fmt.Errorf("暂停期间的自动化事件缺少可持久化防重键")
|
||||
@@ -206,7 +241,7 @@ func (c *Center) deferTask(ctx context.Context, task Task, dueAt int64) error {
|
||||
}
|
||||
return c.store.Automation.DeferTask(ctx, db.DeferredAutomationTask{
|
||||
TaskKey: task.AccountID + ":" + key, CookieID: task.AccountID,
|
||||
TriggerType: task.TriggerType, TaskJSON: string(raw), DueAt: dueAt,
|
||||
TriggerType: task.TriggerType, TaskJSON: string(raw), DueAt: dueAt, ErrorMessage: errMsg,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -350,9 +385,12 @@ func immediateManualActions(actions []db.AutomationAction) []db.AutomationAction
|
||||
|
||||
func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationRule) error {
|
||||
var err error
|
||||
if len(task.ActionPlan) == 0 && task.TriggerType != TriggerOrderPaid {
|
||||
task.ActionPlan = runnableActions(task, rule.Actions)
|
||||
}
|
||||
task, err = c.prepareTask(ctx, task)
|
||||
if err != nil {
|
||||
return err
|
||||
return &preparationError{err: err}
|
||||
}
|
||||
triggerKey := buildTriggerKey(task)
|
||||
if triggerKey == "" {
|
||||
@@ -615,15 +653,15 @@ func (c *Center) prepareTask(ctx context.Context, task Task) (Task, error) {
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
})
|
||||
needsDetail := task.TriggerType == TriggerOrderPaid || task.TriggerType == TriggerBuyerReviewed
|
||||
needsDetail := task.TriggerType == TriggerOrderPaid
|
||||
if existing, err := c.store.Orders.Get(ctx, task.OrderID); err == nil && existing != nil {
|
||||
task = mergeOrderIntoTask(task, existing)
|
||||
if existing.Quantity == "" || existing.Amount == "" {
|
||||
if needsDetail && (existing.Quantity == "" || existing.Amount == "") {
|
||||
needsDetail = true
|
||||
}
|
||||
// 规则是否多规格由 action.config_json 决定;这里无法提前知道命中的 action,
|
||||
// 因此交易类事件统一补齐规格,确保后续规格映射有事实依据。
|
||||
if existing.SpecName == "" || existing.SpecValue == "" {
|
||||
if needsDetail && (existing.SpecName == "" || existing.SpecValue == "") {
|
||||
needsDetail = true
|
||||
}
|
||||
}
|
||||
@@ -714,6 +752,9 @@ func (c *Center) executeAction(ctx context.Context, task Task, action db.Automat
|
||||
return 0, nil
|
||||
}
|
||||
if err := c.sendText(ctx, task, text); err != nil {
|
||||
if errors.Is(err, ErrMessageNotSent) {
|
||||
return 0, err
|
||||
}
|
||||
return 0, uncertainAction(err)
|
||||
}
|
||||
return 1, nil
|
||||
@@ -906,6 +947,20 @@ func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string)
|
||||
return !paused && enabled, nil
|
||||
}
|
||||
|
||||
func (c *Center) accountSenderReady(accountID string) bool {
|
||||
if c == nil || c.senders == nil {
|
||||
return false
|
||||
}
|
||||
sender, ok := c.senders.Sender(accountID)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if ready, ok := sender.(automationReadySender); ok {
|
||||
return ready.AutomationReady()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Center) lockCard(cardID int64) func() {
|
||||
raw, _ := c.cardLocks.LoadOrStore(cardID, &sync.Mutex{})
|
||||
mu := raw.(*sync.Mutex)
|
||||
@@ -975,14 +1030,14 @@ func (c *Center) cardContent(ctx context.Context, card *db.CardFull) (text, imag
|
||||
|
||||
func (c *Center) sendText(ctx context.Context, task Task, text string) error {
|
||||
if task.ChatID == "" || task.BuyerID == "" {
|
||||
return fmt.Errorf("发送消息缺少 chat_id 或 buyer_id")
|
||||
return fmt.Errorf("%w: 发送消息缺少 chat_id 或 buyer_id", ErrMessageNotSent)
|
||||
}
|
||||
if c.senders == nil {
|
||||
return fmt.Errorf("账号发送器未初始化")
|
||||
return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent)
|
||||
}
|
||||
sender, ok := c.senders.Sender(task.AccountID)
|
||||
if !ok {
|
||||
return fmt.Errorf("账号未在线,无法发送自动化消息")
|
||||
return fmt.Errorf("%w: 账号未在线,无法发送自动化消息", ErrMessageNotSent)
|
||||
}
|
||||
return sender.SendText(ctx, task.ChatID, task.BuyerID, text)
|
||||
}
|
||||
@@ -1012,9 +1067,9 @@ func (c *Center) cookieValue(ctx context.Context, cookieID string) (string, erro
|
||||
return d.Value, nil
|
||||
}
|
||||
|
||||
func (c *Center) markEventFacts(ctx context.Context, task Task) {
|
||||
func (c *Center) markEventFacts(ctx context.Context, task Task) error {
|
||||
if task.OrderID == "" {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if err := c.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{
|
||||
CookieID: task.AccountID,
|
||||
@@ -1027,15 +1082,19 @@ func (c *Center) markEventFacts(ctx context.Context, task Task) {
|
||||
Quantity: task.Quantity,
|
||||
Amount: task.Amount,
|
||||
}); err != nil {
|
||||
c.logger.Warn("记录自动化事件事实前创建订单失败", "order_id", task.OrderID, "trigger", task.TriggerType, "err", err)
|
||||
return
|
||||
return fmt.Errorf("记录自动化事件订单事实: %w", err)
|
||||
}
|
||||
switch task.TriggerType {
|
||||
case TriggerOrderPaid:
|
||||
_ = c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "paid_at")
|
||||
if err := c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "paid_at"); err != nil {
|
||||
return fmt.Errorf("记录订单付款时间: %w", err)
|
||||
}
|
||||
case TriggerBuyerReviewed:
|
||||
_ = c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "buyer_reviewed_at")
|
||||
if err := c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "buyer_reviewed_at"); err != nil {
|
||||
return fmt.Errorf("记录买家评价时间: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildTriggerKey(task Task) string {
|
||||
|
||||
@@ -77,6 +77,47 @@ func TestPartialAutomationRunIsQuarantined(t *testing.T) {
|
||||
t.Fatalf("status=%s sent=%d texts=%v", status, sent, sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageDefinitelyNotSentIsRetried(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "retry-before-send", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "gift", Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{err: fmt.Errorf("%w: websocket reconnecting", ErrMessageNotSent)}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "retry-order", ChatID: "chat", BuyerID: "buyer"}
|
||||
if err := center.HandleTask(ctx, task); err == nil {
|
||||
t.Fatal("首次发送应返回连接未就绪错误")
|
||||
}
|
||||
var status string
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status FROM automation_runs WHERE order_id=?`, task.OrderID).Scan(&status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "failed" {
|
||||
t.Fatalf("确定未发送应进入可重试 failed,got %q", status)
|
||||
}
|
||||
sender.err = nil
|
||||
if _, err := store.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE order_id=?`, task.OrderID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
NewScheduler(center).runRecoveryTasks(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "gift" {
|
||||
t.Fatalf("连接恢复后应安全重试,got %v", sender.texts)
|
||||
}
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT status FROM automation_runs WHERE order_id=?`, task.OrderID).Scan(&status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if status != "success" {
|
||||
t.Fatalf("重试后 status=%q want success", status)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSender) SendImage(context.Context, string, string, string, int64) error { return nil }
|
||||
func (s *testSender) UpdateCookie(cookieStr string) {
|
||||
s.cookieUpdates = append(s.cookieUpdates, cookieStr)
|
||||
@@ -85,10 +126,85 @@ func (s *testSender) UpdateCookie(cookieStr string) {
|
||||
}
|
||||
}
|
||||
|
||||
type testFetcher struct{ detail *OrderDetail }
|
||||
type testFetcher struct {
|
||||
detail *OrderDetail
|
||||
err error
|
||||
calls *int
|
||||
}
|
||||
|
||||
func (f testFetcher) FetchOrderDetail(context.Context, string, string, string, string, string) (*OrderDetail, error) {
|
||||
return f.detail, nil
|
||||
if f.calls != nil {
|
||||
*f.calls++
|
||||
}
|
||||
return f.detail, f.err
|
||||
}
|
||||
|
||||
func TestReviewAutomationsDoNotRequireOrderDetail(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
for _, trigger := range []string{TriggerBuyerReviewed, TriggerReviewMissingTimeout} {
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: trigger, TriggerType: trigger, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: trigger, Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
calls := 0
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetOrderDetailFetcher(testFetcher{err: errors.New("must not fetch"), calls: &calls})
|
||||
for i, trigger := range []string{TriggerBuyerReviewed, TriggerReviewMissingTimeout} {
|
||||
task := Task{Source: "ws", AccountID: "cid", TriggerType: trigger, OrderID: fmt.Sprintf("review-no-detail-%d", i), ChatID: "chat", BuyerID: "buyer", Raw: map[string]any{"attempt": 1}}
|
||||
if err := center.HandleTask(ctx, task); err != nil {
|
||||
t.Fatalf("%s should not fetch order detail: %v", trigger, err)
|
||||
}
|
||||
}
|
||||
if calls != 0 || len(sender.texts) != 2 {
|
||||
t.Fatalf("order detail calls=%d texts=%v", calls, sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderPaidPreparationFailureIsPersistedAndRecovered(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title,is_multi_spec) VALUES ('cid','pending-item','商品',1)`)
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES (91,'库存','text','RECOVERED-CARD',1,?)`, admin.ID)
|
||||
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "pending-item", Name: "付款恢复", TriggerType: TriggerOrderPaid, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendCard, CardID: 91, DeliveryCount: 1, ConfigJSON: `{"spec_name":"套餐","spec_value":"恢复版"}`, Enabled: true}},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetOrderDetailFetcher(testFetcher{err: errors.New("temporary order API failure")})
|
||||
task := Task{Source: "ws", AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "pending-order", ItemID: "pending-item", ChatID: "chat", BuyerID: "buyer", Raw: map[string]any{"message_id": "paid-1"}}
|
||||
if err := center.HandleTask(ctx, task); err != nil {
|
||||
t.Fatalf("preparation failure should be durably deferred: %v", err)
|
||||
}
|
||||
var pending, runs int
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_pending_tasks WHERE cookie_id='cid' AND trigger_type='order_paid'`).Scan(&pending)
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_runs WHERE order_id='pending-order'`).Scan(&runs)
|
||||
if pending != 1 || runs != 0 {
|
||||
t.Fatalf("pending=%d runs=%d", pending, runs)
|
||||
}
|
||||
center.SetOrderDetailFetcher(testFetcher{detail: &OrderDetail{SpecName: "套餐", SpecValue: "恢复版", Quantity: "1", Amount: "9.9"}})
|
||||
_, _ = store.DB.ExecContext(ctx, `UPDATE automation_pending_tasks SET due_at=0`)
|
||||
NewScheduler(center).runDeferredTasks(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "RECOVERED-CARD" {
|
||||
t.Fatalf("recovered sends=%v", sender.texts)
|
||||
}
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_pending_tasks WHERE cookie_id='cid'`).Scan(&pending)
|
||||
var status string
|
||||
_ = store.DB.QueryRowContext(ctx, `SELECT status FROM automation_runs WHERE order_id='pending-order'`).Scan(&status)
|
||||
if pending != 0 || status != "success" {
|
||||
t.Fatalf("pending=%d status=%q", pending, status)
|
||||
}
|
||||
}
|
||||
|
||||
func newAutomationTestStore(t *testing.T) (*db.Store, func()) {
|
||||
|
||||
@@ -192,9 +192,9 @@ func isBuyerReviewedEvent(f rawFields) bool {
|
||||
// reminderContent=[我完成了评价]
|
||||
// updateKey=chat_id:order_id:10:BUYER_RATE_SELLER:26
|
||||
// 仅“服务评价邀请”不含 BUYER_RATE_SELLER,不能误触发赠品。
|
||||
return strings.Contains(f.redReminder, "有新交易评价") &&
|
||||
strings.Contains(f.text, "我完成了评价") &&
|
||||
strings.Contains(f.updateKey, "BUYER_RATE_SELLER")
|
||||
// BUYER_RATE_SELLER 是交易评价的稳定业务标识。展示文案会因客户端版本、
|
||||
// 同一买家重复购买等场景变化,不能再把两段中文文案同时存在作为必要条件。
|
||||
return strings.Contains(strings.ToUpper(f.updateKey), "BUYER_RATE_SELLER")
|
||||
}
|
||||
|
||||
func extFields(ext string) (updateKey, contentType string) {
|
||||
|
||||
@@ -29,6 +29,21 @@ func TestExtractTaskFromWS_BuyerReviewed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTaskFromWS_BuyerReviewedUsesBusinessKeyAcrossCopyVariants(t *testing.T) {
|
||||
raw := mustMap(t, `{
|
||||
"1":{"2":"62904549781@goofish","10":{
|
||||
"reminderContent":"感谢您的再次购买,评价已经完成",
|
||||
"senderUserId":"buyer-2",
|
||||
"reminderUrl":"fleamarket://message_chat?itemId=item-2&peerUserId=buyer-2&sid=62904549781",
|
||||
"extJson":"{\"updateKey\":\"62904549781:order-second:10:buyer_rate_seller:26\",\"contentType\":\"26\"}"
|
||||
}}
|
||||
}`)
|
||||
task := ExtractTaskFromWS("acc1", "cookie", raw)
|
||||
if task == nil || task.TriggerType != TriggerBuyerReviewed || task.OrderID != "order-second" {
|
||||
t.Fatalf("second-purchase review task=%+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTaskFromWS_ServiceReviewInvitationIgnored(t *testing.T) {
|
||||
raw := mustMap(t, `{
|
||||
"1": {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
const defaultReviewRequestScanInterval = 10 * time.Minute
|
||||
const defaultReviewRequestScanInterval = time.Minute
|
||||
|
||||
// Scheduler 执行计划任务类自动化。
|
||||
// 计划任务只负责“发现应该触发的任务”,具体动作仍交给 Center,避免形成第二套执行链。
|
||||
@@ -45,9 +45,15 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
|
||||
func (s *Scheduler) scan(ctx context.Context) {
|
||||
s.runDeferredTasks(ctx)
|
||||
if recovered, err := s.center.store.Automation.RecoverDefinitelyUnsentReviewRuns(ctx); err != nil {
|
||||
s.center.logger.Warn("恢复历史求评价未发送任务失败", "err", err)
|
||||
} else if recovered > 0 {
|
||||
s.center.logger.Info("已恢复历史求评价未发送任务,等待安全重试", "count", recovered)
|
||||
}
|
||||
s.runRecoveryTasks(ctx)
|
||||
// 逐页执行,避免把所有到期订单一次性装入内存。稳定 ID 游标确保本轮有界。
|
||||
afterOrderID := ""
|
||||
waitingForWS := map[string]int{}
|
||||
for {
|
||||
orders, err := s.center.store.Automation.DueReviewRequestOrdersAfter(ctx, afterOrderID, 200)
|
||||
if err != nil {
|
||||
@@ -63,8 +69,16 @@ func (s *Scheduler) scan(ctx context.Context) {
|
||||
if !allowed {
|
||||
continue
|
||||
}
|
||||
if !s.center.accountSenderReady(order.CookieID) {
|
||||
waitingForWS[order.CookieID]++
|
||||
continue
|
||||
}
|
||||
rules, err := s.center.store.Automation.Match(ctx, order.CookieID, order.ItemID, TriggerReviewMissingTimeout)
|
||||
if err != nil || len(rules) == 0 {
|
||||
if err != nil {
|
||||
s.center.logger.Warn("查询求评价自动化规则失败", "account", order.CookieID, "order_id", order.OrderID, "item_id", order.ItemID, "err", err)
|
||||
continue
|
||||
}
|
||||
if len(rules) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, rule := range rules {
|
||||
@@ -75,7 +89,9 @@ func (s *Scheduler) scan(ctx context.Context) {
|
||||
ChatID: order.ChatID, OrderID: order.OrderID, ItemID: order.ItemID, BuyerID: order.BuyerID,
|
||||
Text: "发货后一段时间未评价", Raw: map[string]any{"source": "scheduler", "rule_id": rule.ID,
|
||||
"order_id": order.OrderID, "attempt": order.ReviewRequestCount + 1}}
|
||||
_ = s.center.executeRule(ctx, task, rule)
|
||||
if err := s.center.executeRule(ctx, task, rule); err != nil {
|
||||
s.center.logger.Warn("求评价计划任务执行失败", "account", order.CookieID, "order_id", order.OrderID, "rule_id", rule.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(orders) < 200 {
|
||||
@@ -83,6 +99,9 @@ func (s *Scheduler) scan(ctx context.Context) {
|
||||
}
|
||||
afterOrderID = orders[len(orders)-1].OrderID
|
||||
}
|
||||
for accountID, count := range waitingForWS {
|
||||
s.center.logger.Info("账号 WebSocket 尚未就绪,求评价任务等待下次扫描", "account", accountID, "orders", count)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
@@ -110,6 +129,10 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
_ = s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
continue
|
||||
}
|
||||
if !s.center.accountSenderReady(task.AccountID) {
|
||||
_ = s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, time.Now().UTC().Add(defaultReviewRequestScanInterval).Unix())
|
||||
continue
|
||||
}
|
||||
rule, err := s.center.store.Automation.Get(ctx, run.RuleID)
|
||||
if err != nil || !rule.Enabled {
|
||||
reason := "自动化规则不存在或已停用,无法恢复"
|
||||
@@ -144,6 +167,10 @@ func (s *Scheduler) runDeferredTasks(ctx context.Context) {
|
||||
_ = s.center.store.Automation.FinishDeferredTask(ctx, pending.ID, pending.ClaimVersion, false, "解析任务失败: "+err.Error())
|
||||
continue
|
||||
}
|
||||
if task.Raw == nil {
|
||||
task.Raw = map[string]any{}
|
||||
}
|
||||
task.Raw["automation_deferred_replay"] = true
|
||||
deferredAgain, runErr := s.center.handleTask(ctx, task)
|
||||
if deferredAgain {
|
||||
// handleTask 已按新的 paused_until 重置同一任务;当前 claim 不再删除。
|
||||
@@ -225,7 +252,14 @@ func intFromAny(v any) int {
|
||||
}
|
||||
|
||||
func parseDBTime(s string) time.Time {
|
||||
for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339, "2006-01-02T15:04:05Z07:00"} {
|
||||
for _, layout := range []string{
|
||||
time.RFC3339Nano,
|
||||
"2006-01-02 15:04:05.999999999Z07:00", // Postgres TEXT(CURRENT_TIMESTAMP)
|
||||
"2006-01-02 15:04:05.999999999Z07",
|
||||
"2006-01-02 15:04:05Z07:00",
|
||||
"2006-01-02 15:04:05Z07",
|
||||
"2006-01-02 15:04:05", // SQLite/MySQL 历史值;按既有 UTC 约定解释
|
||||
} {
|
||||
if t, err := time.ParseInLocation(layout, strings.TrimSpace(s), time.UTC); err == nil {
|
||||
return t
|
||||
}
|
||||
|
||||
@@ -10,6 +10,17 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
type readinessTestSender struct {
|
||||
*testSender
|
||||
ready bool
|
||||
}
|
||||
|
||||
func (s *readinessTestSender) AutomationReady() bool { return s.ready }
|
||||
|
||||
type readinessTestProvider struct{ sender MessageSender }
|
||||
|
||||
func (p readinessTestProvider) Sender(string) (MessageSender, bool) { return p.sender, true }
|
||||
|
||||
// TestParseReviewRuleConfig 默认值 + JSON 覆盖 + 非法输入兜底。
|
||||
func TestParseReviewRuleConfig(t *testing.T) {
|
||||
// 空配置 → 默认 72h / 1 次。
|
||||
@@ -133,6 +144,17 @@ func TestReviewRequestRuleDueUsesRepeatIntervalAfterFirstAttempt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDBTimeAcceptsPostgresTimestampText(t *testing.T) {
|
||||
got := parseDBTime("2026-07-27 03:36:29.123456+00")
|
||||
if got.IsZero() {
|
||||
t.Fatal("Postgres CURRENT_TIMESTAMP 文本不应解析为零值")
|
||||
}
|
||||
want := time.Date(2026, 7, 27, 3, 36, 29, 123456000, time.UTC)
|
||||
if !got.Equal(want) {
|
||||
t.Fatalf("parseDBTime=%s want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFirstNonEmpty 返回首个非空串。
|
||||
func TestFirstNonEmpty(t *testing.T) {
|
||||
if got := firstNonEmpty("", "", "x", "y"); got != "x" {
|
||||
@@ -214,6 +236,43 @@ func TestSchedulerScanExecutesDueThenSkipsOnMaxAttempts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerWaitsForWebSocketBeforeCreatingRun(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", ItemID: "item-ready", Name: "wait-ws",
|
||||
TriggerType: TriggerReviewMissingTimeout, Enabled: true,
|
||||
ConfigJSON: `{"after_shipped_hours":1,"max_attempts":1}`,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "review", Enabled: true}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
shipped := time.Now().UTC().Add(-2 * time.Hour).Format(time.RFC3339Nano)
|
||||
if _, err := store.DB.ExecContext(ctx, `INSERT INTO orders
|
||||
(order_id,cookie_id,item_id,buyer_id,chat_id,system_shipped,shipped_at)
|
||||
VALUES ('wait-ws-order','cid','item-ready','buyer','chat',1,?)`, shipped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sender := &readinessTestSender{testSender: &testSender{}, ready: false}
|
||||
scheduler := NewScheduler(New(store, readinessTestProvider{sender: sender}, nil))
|
||||
scheduler.scan(ctx)
|
||||
var count int
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_runs WHERE rule_id=?`, ruleID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("WS 未就绪时不应创建运行记录,got %d", count)
|
||||
}
|
||||
sender.ready = true
|
||||
scheduler.scan(ctx)
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "review" {
|
||||
t.Fatalf("WS 就绪后应发送,got %v", sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerScansMoreThanOneReviewPage(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
+124
-13
@@ -89,6 +89,7 @@ type DeferredAutomationTask struct {
|
||||
TaskJSON string
|
||||
DueAt int64
|
||||
ClaimVersion int
|
||||
ErrorMessage string
|
||||
}
|
||||
|
||||
var ErrDeferredTaskLeaseLost = errors.New("延迟自动化任务租约已失效")
|
||||
@@ -128,6 +129,17 @@ type AutomationRuleInput struct {
|
||||
Actions []AutomationActionInput
|
||||
}
|
||||
|
||||
// AutomationRuleListFilter 是自动化规则列表的筛选和分页条件。
|
||||
type AutomationRuleListFilter struct {
|
||||
UserID int64
|
||||
CookieID string
|
||||
TriggerType string
|
||||
Enabled *bool
|
||||
Search string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// AutomationActionInput 是创建动作的输入。
|
||||
type AutomationActionInput struct {
|
||||
ActionType string
|
||||
@@ -142,15 +154,59 @@ type AutomationActionInput struct {
|
||||
|
||||
// ListForUser 返回用户下全部自动化规则和动作。
|
||||
func (a *AutomationRules) ListForUser(ctx context.Context, userID int64) ([]AutomationRule, error) {
|
||||
rules, _, err := a.ListPageForUser(ctx, AutomationRuleListFilter{UserID: userID})
|
||||
return rules, err
|
||||
}
|
||||
|
||||
// ListPageForUser 按用户隔离筛选并分页查询自动化规则和动作。
|
||||
func (a *AutomationRules) ListPageForUser(ctx context.Context, f AutomationRuleListFilter) ([]AutomationRule, int, error) {
|
||||
where := []string{"r.user_id=?"}
|
||||
args := []any{f.UserID}
|
||||
if f.CookieID != "" {
|
||||
where = append(where, "r.cookie_id=?")
|
||||
args = append(args, f.CookieID)
|
||||
}
|
||||
if f.TriggerType != "" {
|
||||
where = append(where, "r.trigger_type=?")
|
||||
args = append(args, f.TriggerType)
|
||||
}
|
||||
if f.Enabled != nil {
|
||||
where = append(where, "r.enabled=?")
|
||||
args = append(args, boolToInt(*f.Enabled))
|
||||
}
|
||||
if search := strings.ToLower(strings.TrimSpace(f.Search)); search != "" {
|
||||
pattern := "%" + search + "%"
|
||||
where = append(where, `(LOWER(COALESCE(r.name,'')) LIKE ?
|
||||
OR LOWER(COALESCE(r.item_id,'')) LIKE ?
|
||||
OR LOWER(COALESCE(i.item_title,'')) LIKE ?)`)
|
||||
args = append(args, pattern, pattern, pattern)
|
||||
}
|
||||
whereSQL := strings.Join(where, " AND ")
|
||||
|
||||
var total int
|
||||
if err := a.DB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*)
|
||||
FROM automation_rules r
|
||||
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
|
||||
WHERE `+whereSQL, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
queryArgs := append([]any{}, args...)
|
||||
limitSQL := ""
|
||||
if f.Limit > 0 {
|
||||
limitSQL = " LIMIT ? OFFSET ?"
|
||||
queryArgs = append(queryArgs, f.Limit, f.Offset)
|
||||
}
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled,
|
||||
r.priority,r.config_json,r.created_at,r.updated_at
|
||||
FROM automation_rules r
|
||||
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id
|
||||
WHERE r.user_id=?
|
||||
ORDER BY r.created_at DESC,r.id DESC`, userID)
|
||||
WHERE `+whereSQL+`
|
||||
ORDER BY r.created_at DESC,r.id DESC`+limitSQL, queryArgs...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AutomationRule{}
|
||||
@@ -159,17 +215,17 @@ SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.t
|
||||
var enabled int
|
||||
if err := rows.Scan(&r.ID, &r.UserID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.Name, &r.TriggerType,
|
||||
&enabled, &r.Priority, &r.ConfigJSON, &r.CreatedAt, &r.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
return nil, 0, err
|
||||
}
|
||||
r.Enabled = enabled != 0
|
||||
acts, err := a.Actions(ctx, r.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, 0, err
|
||||
}
|
||||
r.Actions = acts
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
return out, total, rows.Err()
|
||||
}
|
||||
|
||||
// Match 查询某事件可触发的规则。商品级规则存在时只返回商品级规则;
|
||||
@@ -562,10 +618,28 @@ SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigg
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// RecoverDefinitelyUnsentReviewRuns 恢复旧版本把“发送前没有 WS 连接”误判成
|
||||
// 结果不确定的求评价运行。这些记录 sent_count=0,且错误明确发生在调用发送
|
||||
// 接口之前,可以安全清除 action_started 并进入现有失败重试流程。
|
||||
func (a *AutomationRules) RecoverDefinitelyUnsentReviewRuns(ctx context.Context) (int64, error) {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='failed',action_started=0,lease_expires_at=0,next_retry_at=0,
|
||||
error_message='历史版本在 WebSocket 就绪前执行,已恢复等待安全重试',
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE trigger_type='review_missing_timeout' AND status='needs_review' AND sent_count=0
|
||||
AND (error_message LIKE '%当前没有可用 WebSocket 连接%'
|
||||
OR error_message LIKE '%账号未在线,无法发送自动化消息%'
|
||||
OR error_message LIKE '%账号发送器未初始化%')`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (a *AutomationRules) DeferTask(ctx context.Context, task DeferredAutomationTask) error {
|
||||
_, err := a.DB.ExecContext(ctx, `INSERT INTO automation_pending_tasks
|
||||
(task_key,cookie_id,trigger_type,task_json,due_at,status,attempt_count,lease_expires_at,error_message)
|
||||
VALUES (?,?,?,?,?,'pending',0,0,'')`+dialectUpsert(a.Dialect, []string{"task_key"}, map[string]string{
|
||||
VALUES (?,?,?,?,?,'pending',0,0,?)`+dialectUpsert(a.Dialect, []string{"task_key"}, map[string]string{
|
||||
"cookie_id": "excluded.cookie_id",
|
||||
"trigger_type": "excluded.trigger_type",
|
||||
"task_json": "excluded.task_json",
|
||||
@@ -573,8 +647,8 @@ VALUES (?,?,?,?,?,'pending',0,0,'')`+dialectUpsert(a.Dialect, []string{"task_key
|
||||
"status": "'pending'",
|
||||
"attempt_count": "0",
|
||||
"lease_expires_at": "0",
|
||||
"error_message": "''",
|
||||
}), task.TaskKey, task.CookieID, task.TriggerType, validJSON(task.TaskJSON), task.DueAt)
|
||||
"error_message": "excluded.error_message",
|
||||
}), task.TaskKey, task.CookieID, task.TriggerType, validJSON(task.TaskJSON), task.DueAt, task.ErrorMessage)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -773,13 +847,45 @@ func (a *AutomationRules) FinishDeferredTask(ctx context.Context, id int64, clai
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
retryDelay := deferredRetryDelay(claimVersion)
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET status=CASE WHEN attempt_count>=5 THEN 'dead_letter' ELSE 'pending' END,
|
||||
due_at=?,lease_expires_at=0,error_message=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, time.Now().UTC().Add(time.Minute).Unix(), errMsg, id, claimVersion)
|
||||
WHERE id=? AND status='running' AND attempt_count=?`, time.Now().UTC().Add(retryDelay).Unix(), errMsg, id, claimVersion)
|
||||
return requireDeferredTaskOwner(res, err)
|
||||
}
|
||||
|
||||
func deferredRetryDelay(attempt int) time.Duration {
|
||||
if attempt < 1 {
|
||||
attempt = 1
|
||||
}
|
||||
delay := 5 * time.Minute * time.Duration(1<<(attempt-1))
|
||||
if delay > time.Hour {
|
||||
return time.Hour
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// WakeCredentialBlocked 让 Cookie 恢复后的账号尽快重新领取明确尚未发送的任务。
|
||||
func (a *AutomationRules) WakeCredentialBlocked(ctx context.Context, cookieID string) error {
|
||||
if strings.TrimSpace(cookieID) == "" {
|
||||
return nil
|
||||
}
|
||||
if _, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET due_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='pending'
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%')`, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET next_retry_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='failed' AND sent_count=0 AND action_started=0
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%')`, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *AutomationRules) RenewDeferredTaskLease(ctx context.Context, id int64, claimVersion int, leaseExpiresAt int64) error {
|
||||
res, err := a.DB.ExecContext(ctx, `UPDATE automation_pending_tasks
|
||||
SET lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
|
||||
@@ -808,18 +914,23 @@ func (a *AutomationRules) MarkOrderEventTime(ctx context.Context, orderID, field
|
||||
default:
|
||||
return fmt.Errorf("不允许更新的订单时间字段: %s", field)
|
||||
}
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=CASE WHEN COALESCE("+field+",'')='' THEN CURRENT_TIMESTAMP ELSE "+field+" END, updated_at=CURRENT_TIMESTAMP WHERE order_id=?", orderID)
|
||||
// 事件时间列是跨方言 TEXT。不能直接写 CURRENT_TIMESTAMP:Postgres 会产生
|
||||
// "2006-01-02 15:04:05.999999+00",而 MySQL 的无时区文本又取决于会话时区,
|
||||
// 调度器无法可靠解释。统一由应用写 RFC3339 UTC,已有值仍保留(幂等)。
|
||||
now := time.Now().UTC().Format(time.RFC3339Nano)
|
||||
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=?, updated_at=CURRENT_TIMESTAMP WHERE order_id=? AND COALESCE("+field+",'')=''", now, orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
// IncrementReviewRequest 记录一次求评价请求。
|
||||
func (a *AutomationRules) IncrementReviewRequest(ctx context.Context, orderID string) error {
|
||||
now := time.Now().UTC().Format(time.RFC3339Nano)
|
||||
_, err := a.DB.ExecContext(ctx, `
|
||||
UPDATE orders
|
||||
SET review_request_count=review_request_count+1,
|
||||
last_review_request_at=CURRENT_TIMESTAMP,
|
||||
last_review_request_at=?,
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
WHERE order_id=?`, orderID)
|
||||
WHERE order_id=?`, now, orderID)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -359,6 +359,44 @@ func TestAutomation_TryStartRunAndFinishRun(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationRecoverDefinitelyUnsentReviewRun(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
userID, cookieID := seedAccount(t, s)
|
||||
ruleID, err := s.Automation.Create(ctx, AutomationRuleInput{
|
||||
UserID: userID, CookieID: cookieID, Name: "review", TriggerType: "review_missing_timeout", Enabled: true,
|
||||
Actions: []AutomationActionInput{{ActionType: "send_text", MessageTemplate: "review", Enabled: true}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{
|
||||
RuleID: ruleID, CookieID: cookieID, OrderID: "legacy-ws", TriggerType: "review_missing_timeout",
|
||||
TriggerKey: "review_missing_timeout:legacy-ws:1", RawEventJSON: `{}`,
|
||||
})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("TryStartRun: started=%v err=%v", started, err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET status='needs_review',sent_count=0,action_started=1,
|
||||
error_message='自动化动作结果需要人工核对: 账号当前没有可用 WebSocket 连接'
|
||||
WHERE id=?`, runID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovered, err := s.Automation.RecoverDefinitelyUnsentReviewRuns(ctx)
|
||||
if err != nil || recovered != 1 {
|
||||
t.Fatalf("RecoverDefinitelyUnsentReviewRuns=%d err=%v", recovered, err)
|
||||
}
|
||||
run, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if run.Status != "failed" || run.ActionStarted || run.NextRetryAt != 0 {
|
||||
t.Fatalf("恢复结果异常: %+v", run)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomation_TryStartRunRecoversStaleAndUnsentFailedRuns(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
@@ -617,6 +655,46 @@ func TestDeferTaskRevivesDeadLetterWithFreshAttemptBudget(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeferredRetryBackoffAndCredentialWake(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_, cid := seedAccount(t, s)
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "wake-task", CookieID: cid, TriggerType: "order_paid", TaskJSON: `{}`, DueAt: 0, ErrorMessage: "FAIL_SYS_SESSION_EXPIRED"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claimed, err := s.Automation.ClaimDueDeferredTasks(ctx, 1)
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claim=%v err=%v", claimed, err)
|
||||
}
|
||||
before := time.Now().UTC().Unix()
|
||||
if err := s.Automation.FinishDeferredTask(ctx, claimed[0].ID, claimed[0].ClaimVersion, false, "session expired"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var dueAt int64
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE id=?`, claimed[0].ID).Scan(&dueAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dueAt < before+int64((5*time.Minute)/time.Second)-1 {
|
||||
t.Fatalf("first retry due_at=%d before=%d", dueAt, before)
|
||||
}
|
||||
if err := s.Automation.WakeCredentialBlocked(ctx, cid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE id=?`, claimed[0].ID).Scan(&dueAt); err != nil || dueAt != 0 {
|
||||
t.Fatalf("wake due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "intentional-delay", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{}`, DueAt: before + 3600}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.WakeCredentialBlocked(ctx, cid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='intentional-delay'`).Scan(&dueAt); err != nil || dueAt != before+3600 {
|
||||
t.Fatalf("intentional delay must not be woken: due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeferredTaskFencingRejectsStaleWorker(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -49,6 +49,7 @@ type ItemPublishBatchRow struct {
|
||||
PostageMode string // 邮费模式:free/buyer/seller
|
||||
Postage string
|
||||
ImagesJSON string // 图片引用 JSON 数组(相对 UploadDir 的路径)
|
||||
CategoryJSON string // 用户指定的优先类目 JSON;为空时自动识别
|
||||
AutomationJSON string // 发布后自动创建的自动化规则配置 JSON
|
||||
Status string // pending/running/success/failed
|
||||
ItemID string // 发布成功后回填的闲鱼商品 ID
|
||||
@@ -94,16 +95,19 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
if row.RawJSON == "" {
|
||||
row.RawJSON = "{}"
|
||||
}
|
||||
if row.CategoryJSON == "" {
|
||||
row.CategoryJSON = "{}"
|
||||
}
|
||||
if row.AutomationJSON == "" {
|
||||
row.AutomationJSON = "{}"
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO item_publish_batch_rows
|
||||
(batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,automation_json,status,item_id,item_url,error_message,failure_kind,raw_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
images_json,category_json,automation_json,status,item_id,item_url,error_message,failure_kind,raw_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
batch.ID, row.RowNo, row.CookieID, row.Title, row.Description, row.Price, row.OriginalPrice,
|
||||
row.Quantity, row.PostageMode, row.Postage, row.ImagesJSON, row.AutomationJSON,
|
||||
row.Quantity, row.PostageMode, row.Postage, row.ImagesJSON, row.CategoryJSON, row.AutomationJSON,
|
||||
row.Status, row.ItemID, row.ItemURL, row.ErrorMessage, row.FailureKind, row.RawJSON); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,7 +193,7 @@ func (b *ItemPublishBatches) Recoverable(ctx context.Context, now int64, limit i
|
||||
func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPublishBatchRow, error) {
|
||||
rows, err := b.DB.QueryContext(ctx,
|
||||
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
images_json,COALESCE(category_json,'{}'),COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
COALESCE(failure_kind,''),COALESCE(worker_token,''),
|
||||
raw_json,created_at,updated_at
|
||||
FROM item_publish_batch_rows WHERE batch_id=? ORDER BY row_no`, batchID)
|
||||
@@ -201,7 +205,7 @@ func (b *ItemPublishBatches) Rows(ctx context.Context, batchID string) ([]ItemPu
|
||||
for rows.Next() {
|
||||
var r ItemPublishBatchRow
|
||||
if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.AutomationJSON,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.CategoryJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.FailureKind, &r.WorkerToken,
|
||||
&r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
@@ -220,7 +224,7 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
}
|
||||
rows, err := b.DB.QueryContext(ctx,
|
||||
`SELECT id,batch_id,row_no,cookie_id,title,description,price,original_price,quantity,postage_mode,postage,
|
||||
images_json,COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
images_json,COALESCE(category_json,'{}'),COALESCE(automation_json,'{}'),status,item_id,item_url,error_message,
|
||||
COALESCE(failure_kind,''),COALESCE(worker_token,''),
|
||||
raw_json,created_at,updated_at
|
||||
FROM item_publish_batch_rows WHERE batch_id=? AND status IN `+statuses+` ORDER BY row_no`, batchID)
|
||||
@@ -232,7 +236,7 @@ func (b *ItemPublishBatches) PendingRows(ctx context.Context, batchID string, fa
|
||||
for rows.Next() {
|
||||
var r ItemPublishBatchRow
|
||||
if err := rows.Scan(&r.ID, &r.BatchID, &r.RowNo, &r.CookieID, &r.Title, &r.Description, &r.Price,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.AutomationJSON,
|
||||
&r.OriginalPrice, &r.Quantity, &r.PostageMode, &r.Postage, &r.ImagesJSON, &r.CategoryJSON, &r.AutomationJSON,
|
||||
&r.Status, &r.ItemID, &r.ItemURL, &r.ErrorMessage, &r.FailureKind, &r.WorkerToken,
|
||||
&r.RawJSON, &r.CreatedAt,
|
||||
&r.UpdatedAt); err != nil {
|
||||
|
||||
@@ -125,8 +125,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// 依次回滚 22 到 14,再整体升级。
|
||||
for i := 0; i < 9; i++ {
|
||||
// 依次回滚 23 到 14,再整体升级。
|
||||
for i := 0; i < 10; i++ {
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -143,6 +143,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
if columnExists(t, d, "account_tokens", "cookie_fingerprint") {
|
||||
t.Fatal("account_tokens.cookie_fingerprint should be removed after migration 22 down")
|
||||
}
|
||||
if columnExists(t, d, "item_publish_batch_rows", "category_json") {
|
||||
t.Fatal("item_publish_batch_rows.category_json should be removed after migration 23 down")
|
||||
}
|
||||
|
||||
if err := goose.Up(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("up after down: %v", err)
|
||||
@@ -160,6 +163,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
{"default_reply_records", "status"},
|
||||
{"default_reply_records", "text_sent"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batch_rows ADD COLUMN category_json LONGTEXT NULL;
|
||||
UPDATE item_publish_batch_rows SET category_json='{}' WHERE category_json IS NULL;
|
||||
ALTER TABLE item_publish_batch_rows MODIFY COLUMN category_json LONGTEXT NOT NULL;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batch_rows DROP COLUMN category_json;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batch_rows ADD COLUMN category_json TEXT NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batch_rows DROP COLUMN category_json;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE item_publish_batch_rows ADD COLUMN category_json TEXT NOT NULL DEFAULT '{}';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE item_publish_batch_rows DROP COLUMN category_json;
|
||||
+128
-1
@@ -577,6 +577,68 @@ func TestMultiDB_AutomationTryStartRunDedup(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_DeferredAutomationCredentialWake 验证延迟任务的失败退避和凭证恢复唤醒
|
||||
// 在各数据库方言下行为一致,同时确保正常的业务延迟不会被提前唤醒。
|
||||
func TestMultiDB_DeferredAutomationCredentialWake(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
ctx := context.Background()
|
||||
s := tg.store
|
||||
suffix := fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
username := tg.name + "_deferred_user_" + suffix
|
||||
if ok, err := s.Users.Create(ctx, username, username+"@e.com", "pw"); err != nil || !ok {
|
||||
t.Fatalf("create user: ok=%v err=%v", ok, err)
|
||||
}
|
||||
user, _ := s.Users.GetByUsername(ctx, username)
|
||||
cookieID := tg.name + "_deferred_cookie_" + suffix
|
||||
if err := s.Cookies.Save(ctx, cookieID, "cv", user.ID); err != nil {
|
||||
t.Fatalf("save cookie: %v", err)
|
||||
}
|
||||
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{
|
||||
TaskKey: "credential-" + suffix, CookieID: cookieID, TriggerType: "order_paid",
|
||||
TaskJSON: `{}`, DueAt: 0, ErrorMessage: "FAIL_SYS_SESSION_EXPIRED",
|
||||
}); err != nil {
|
||||
t.Fatalf("defer credential task: %v", err)
|
||||
}
|
||||
claimed, err := s.Automation.ClaimDueDeferredTasks(ctx, 1)
|
||||
if err != nil || len(claimed) != 1 {
|
||||
t.Fatalf("claim credential task: tasks=%+v err=%v", claimed, err)
|
||||
}
|
||||
before := time.Now().UTC().Unix()
|
||||
if err := s.Automation.FinishDeferredTask(ctx, claimed[0].ID, claimed[0].ClaimVersion, false, "session expired"); err != nil {
|
||||
t.Fatalf("finish failed task: %v", err)
|
||||
}
|
||||
|
||||
intentionalDue := before + 3600
|
||||
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{
|
||||
TaskKey: "intentional-" + suffix, CookieID: cookieID, TriggerType: "buyer_reviewed",
|
||||
TaskJSON: `{}`, DueAt: intentionalDue,
|
||||
}); err != nil {
|
||||
t.Fatalf("defer intentional task: %v", err)
|
||||
}
|
||||
if err := s.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
t.Fatalf("wake credential tasks: %v", err)
|
||||
}
|
||||
|
||||
var credentialDue, normalDue int64
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key=?`, "credential-"+suffix).Scan(&credentialDue); err != nil {
|
||||
t.Fatalf("read credential due_at: %v", err)
|
||||
}
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key=?`, "intentional-"+suffix).Scan(&normalDue); err != nil {
|
||||
t.Fatalf("read intentional due_at: %v", err)
|
||||
}
|
||||
if credentialDue != 0 {
|
||||
t.Fatalf("credential task due_at=%d want 0", credentialDue)
|
||||
}
|
||||
if normalDue != intentionalDue {
|
||||
t.Fatalf("intentional task due_at=%d want %d", normalDue, intentionalDue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_Notifications 验证通知渠道创建 + 账号绑定读写。
|
||||
func TestMultiDB_Notifications(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
@@ -641,7 +703,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
for i := 0; i < 9; i++ {
|
||||
for i := 0; i < 10; i++ {
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration down #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -658,6 +720,9 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "account_tokens", "cookie_fingerprint") {
|
||||
t.Fatal("account_tokens.cookie_fingerprint should be removed after down")
|
||||
}
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "item_publish_batch_rows", "category_json") {
|
||||
t.Fatal("item_publish_batch_rows.category_json should be removed after down")
|
||||
}
|
||||
|
||||
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration up after down: %v", err)
|
||||
@@ -677,6 +742,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
{"automation_runs", "action_cursor"},
|
||||
{"automation_runs", "action_started"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
{"item_publish_batch_rows", "category_json"},
|
||||
} {
|
||||
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)
|
||||
@@ -724,6 +790,67 @@ func TestMultiDB_CardsCreateGet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultiDB_MarkOrderEventTime 验证订单事件时间标记跨三库一致。重点覆盖
|
||||
// Postgres 回归:CASE WHEN ... THEN CURRENT_TIMESTAMP ELSE field END 会因
|
||||
// THEN(timestamptz) 与 ELSE(text) 分支类型不可匹配而报 SQLSTATE 42804。
|
||||
// 语义:字段为空时写入当前时间,已有值时不得覆盖(幂等)。
|
||||
func TestMultiDB_MarkOrderEventTime(t *testing.T) {
|
||||
for _, tg := range allTestTargets(t) {
|
||||
t.Run(tg.name, func(t *testing.T) {
|
||||
defer tg.cleanup()
|
||||
ctx := context.Background()
|
||||
s := tg.store
|
||||
|
||||
uid := tg.name + "_evt_user_" + fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
s.Users.Create(ctx, uid, uid+"@e.com", "pw")
|
||||
user, _ := s.Users.GetByUsername(ctx, uid)
|
||||
cid := tg.name + "_evt_cookie_" + fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
if err := s.Cookies.Save(ctx, cid, "cv", user.ID); err != nil {
|
||||
t.Fatalf("Save cookie: %v", err)
|
||||
}
|
||||
oid := tg.name + "_evt_order_" + fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
|
||||
if err := s.Orders.Upsert(ctx, oid, OrderUpsertOpts{ItemID: "i1", BuyerID: "b1", CookieID: cid}); err != nil {
|
||||
t.Fatalf("Upsert: %v", err)
|
||||
}
|
||||
|
||||
// 白名单字段为空时全部写入当前时间。
|
||||
for _, f := range []string{"paid_at", "shipped_at", "completed_at", "buyer_reviewed_at", "last_review_request_at"} {
|
||||
if err := s.Automation.MarkOrderEventTime(ctx, oid, f); err != nil {
|
||||
t.Fatalf("MarkOrderEventTime(%s) on %s: %v", f, tg.name, err)
|
||||
}
|
||||
}
|
||||
got, err := s.Orders.Get(ctx, oid)
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if got.PaidAt == "" || got.ShippedAt == "" || got.CompletedAt == "" || got.BuyerReviewedAt == "" || got.LastReviewRequestAt == "" {
|
||||
t.Fatalf("event timestamps not set on %s: %#v", tg.name, got)
|
||||
}
|
||||
|
||||
// 已有值时不得覆盖。
|
||||
const original = "2020-01-02 03:04:05"
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE orders SET shipped_at=? WHERE order_id=?`, original, oid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Automation.MarkOrderEventTime(ctx, oid, "shipped_at"); err != nil {
|
||||
t.Fatalf("MarkOrderEventTime(shipped_at) overwrite on %s: %v", tg.name, err)
|
||||
}
|
||||
var shippedAt string
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT shipped_at FROM orders WHERE order_id=?`, oid).Scan(&shippedAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if shippedAt != original {
|
||||
t.Fatalf("event timestamp overwritten on %s: %q want %q", tg.name, shippedAt, original)
|
||||
}
|
||||
|
||||
// 非法字段拒绝。
|
||||
if err := s.Automation.MarkOrderEventTime(ctx, oid, "order_status"); err == nil || !strings.Contains(err.Error(), "不允许") {
|
||||
t.Fatalf("非法字段应拒绝 on %s, got %v", tg.name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func migrationTestSubdir(t *testing.T, dialect Dialect) (string, string) {
|
||||
t.Helper()
|
||||
switch dialect {
|
||||
|
||||
@@ -920,3 +920,39 @@ func TestWSMessages_Add(t *testing.T) {
|
||||
t.Fatalf("ws_messages 行数=%d want 2", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWSMessages_AddBatchAndDeleteBefore(t *testing.T) {
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
_, cid := seedAccount(t, s)
|
||||
|
||||
if err := s.WSMessages.AddBatch(ctx, []WSMessage{
|
||||
{CookieID: cid, RawText: "first"},
|
||||
{CookieID: cid, Direction: "out", ParseStatus: "parsed", RawText: "second"},
|
||||
}); err != nil {
|
||||
t.Fatalf("AddBatch: %v", err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx,
|
||||
`UPDATE ws_messages SET created_at=? WHERE cookie_id=? AND raw_text=?`,
|
||||
time.Now().Add(-8*24*time.Hour), cid, "first"); err != nil {
|
||||
t.Fatalf("设置历史时间: %v", err)
|
||||
}
|
||||
|
||||
deleted, err := s.WSMessages.DeleteBefore(ctx, cid, time.Now().Add(-7*24*time.Hour))
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteBefore: %v", err)
|
||||
}
|
||||
if deleted != 1 {
|
||||
t.Fatalf("删除行数=%d want 1", deleted)
|
||||
}
|
||||
var rawText, direction, parseStatus string
|
||||
if err := s.DB.QueryRowContext(ctx,
|
||||
`SELECT raw_text, direction, parse_status FROM ws_messages WHERE cookie_id=?`, cid,
|
||||
).Scan(&rawText, &direction, &parseStatus); err != nil {
|
||||
t.Fatalf("查询保留记录: %v", err)
|
||||
}
|
||||
if rawText != "second" || direction != "out" || parseStatus != "parsed" {
|
||||
t.Fatalf("保留记录=%q/%q/%q", rawText, direction, parseStatus)
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestPublishBatches_CreateGetRows(t *testing.T) {
|
||||
t.Fatalf("Get 不存在应 ErrNotFound, got %v", err)
|
||||
}
|
||||
|
||||
// Rows 验证缺省值(quantity=1, postage_mode=free, status=pending, images_json=[], automation_json={})。
|
||||
// Rows 验证缺省值(quantity=1, postage_mode=free, status=pending, JSON 字段均已补齐)。
|
||||
gotRows, err := s.PublishBatches.Rows(ctx, "b1")
|
||||
if err != nil {
|
||||
t.Fatalf("Rows: %v", err)
|
||||
@@ -62,7 +62,7 @@ func TestPublishBatches_CreateGetRows(t *testing.T) {
|
||||
}
|
||||
r0 := gotRows[0]
|
||||
if r0.Quantity != 1 || r0.PostageMode != "free" || r0.Status != "pending" ||
|
||||
r0.ImagesJSON != "[]" || r0.AutomationJSON != "{}" || r0.RawJSON != "{}" {
|
||||
r0.ImagesJSON != "[]" || r0.CategoryJSON != "{}" || r0.AutomationJSON != "{}" || r0.RawJSON != "{}" {
|
||||
t.Fatalf("缺省值: %#v", r0)
|
||||
}
|
||||
if gotRows[1].Quantity != 5 || gotRows[1].PostageMode != "buyer" {
|
||||
|
||||
@@ -261,6 +261,29 @@ func (r *RenewalStore) AddAPICookieRenewLog(ctx context.Context, log RenewalLog)
|
||||
return err
|
||||
}
|
||||
|
||||
// RecentAPICookieRenewStatuses 返回账号最近的 API Cookie 续期状态,最新记录在前。
|
||||
func (r *RenewalStore) RecentAPICookieRenewStatuses(ctx context.Context, cookieID string, limit int) ([]string, error) {
|
||||
if limit <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := r.DB.QueryContext(ctx,
|
||||
`SELECT status FROM scheduled_api_cookie_renew_log
|
||||
WHERE cookie_id=? ORDER BY id DESC LIMIT ?`, cookieID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
statuses := make([]string, 0, limit)
|
||||
for rows.Next() {
|
||||
var status string
|
||||
if err := rows.Scan(&status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
statuses = append(statuses, status)
|
||||
}
|
||||
return statuses, rows.Err()
|
||||
}
|
||||
|
||||
// CleanupLogs deletes renewal logs older than retentionDays. Non-positive values skip cleanup.
|
||||
func (r *RenewalStore) CleanupLogs(ctx context.Context, retentionDays int) error {
|
||||
if retentionDays <= 0 {
|
||||
|
||||
@@ -3,6 +3,8 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WSMessage 原始 WS 收包记录。
|
||||
@@ -21,14 +23,43 @@ type WSMessageStore struct{ DB *sql.DB }
|
||||
|
||||
// Add 记录一条 WS 消息。
|
||||
func (w *WSMessageStore) Add(ctx context.Context, m WSMessage) error {
|
||||
if m.Direction == "" {
|
||||
m.Direction = "in"
|
||||
return w.AddBatch(ctx, []WSMessage{m})
|
||||
}
|
||||
|
||||
// AddBatch 在一次数据库操作中记录多条 WS 消息。
|
||||
func (w *WSMessageStore) AddBatch(ctx context.Context, messages []WSMessage) error {
|
||||
if len(messages) == 0 {
|
||||
return nil
|
||||
}
|
||||
if m.ParseStatus == "" {
|
||||
m.ParseStatus = "raw"
|
||||
|
||||
var query strings.Builder
|
||||
query.WriteString("INSERT INTO ws_messages (cookie_id, direction, raw_text, parsed_json, message_kind, parse_status, error, created_at) VALUES ")
|
||||
args := make([]any, 0, len(messages)*7)
|
||||
for i, message := range messages {
|
||||
if i > 0 {
|
||||
query.WriteByte(',')
|
||||
}
|
||||
query.WriteString("(?,?,?,?,?,?,?,CURRENT_TIMESTAMP)")
|
||||
if message.Direction == "" {
|
||||
message.Direction = "in"
|
||||
}
|
||||
if message.ParseStatus == "" {
|
||||
message.ParseStatus = "raw"
|
||||
}
|
||||
args = append(args, message.CookieID, message.Direction, message.RawText, message.ParsedJSON,
|
||||
message.MessageKind, message.ParseStatus, message.Error)
|
||||
}
|
||||
_, err := w.DB.ExecContext(ctx,
|
||||
"INSERT INTO ws_messages (cookie_id, direction, raw_text, parsed_json, message_kind, parse_status, error, created_at) VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP)",
|
||||
m.CookieID, m.Direction, m.RawText, m.ParsedJSON, m.MessageKind, m.ParseStatus, m.Error)
|
||||
|
||||
_, err := w.DB.ExecContext(ctx, query.String(), args...)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteBefore 删除指定账号在 cutoff 之前的 WS 诊断消息。
|
||||
func (w *WSMessageStore) DeleteBefore(ctx context.Context, cookieID string, cutoff time.Time) (int64, error) {
|
||||
result, err := w.DB.ExecContext(ctx,
|
||||
"DELETE FROM ws_messages WHERE cookie_id=? AND created_at < ?", cookieID, cutoff)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
+101
-10
@@ -39,6 +39,10 @@ const (
|
||||
FrequentDisconnectLimit = 5
|
||||
FrequentDisconnectWindow = 5 * time.Minute
|
||||
TokenCaptchaFailureCooldown = 5 * time.Minute
|
||||
WSRecordBatchSize = 32
|
||||
WSRecordFlushInterval = 250 * time.Millisecond
|
||||
WSRecordWriteTimeout = 5 * time.Second
|
||||
WSRecordRetention = 7 * 24 * time.Hour
|
||||
|
||||
// ShortConnectionThreshold 仅用于统计频繁短连接;已经建立后的网络断线
|
||||
// 不会清 Token 缓存。
|
||||
@@ -320,11 +324,11 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.runtimeCtx = ctx
|
||||
a.accepting = true
|
||||
a.taskMu.Unlock()
|
||||
a.startWSRecorder(ctx)
|
||||
if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) {
|
||||
a.logger.Info("账号在启动续期前已禁用")
|
||||
return nil
|
||||
}
|
||||
a.startWSRecorder(ctx)
|
||||
// 官网 /im 启动时执行 auto-login plugin;成功后 location.reload() 会重建
|
||||
// FishEngine 和页面级 device ID。Go 客户端用 HTTP 复刻续期,并在成功时
|
||||
// 只重建这一本地运行时身份。续期失败不能用网页 DOM 阻断 token + WS;
|
||||
@@ -559,17 +563,41 @@ func (a *Account) startWSRecorder(ctx context.Context) {
|
||||
}
|
||||
a.wsRecordOnce.Do(func() {
|
||||
go func() {
|
||||
cleanupCtx, cleanupCancel := context.WithTimeout(ctx, WSRecordWriteTimeout)
|
||||
deleted, cleanupErr := a.store.WSMessages.DeleteBefore(cleanupCtx, a.CookieID, time.Now().Add(-WSRecordRetention))
|
||||
cleanupCancel()
|
||||
if cleanupErr != nil && ctx.Err() == nil {
|
||||
a.logger.Warn("清理过期 WS 报文失败", "cookie_id", a.CookieID, "err", cleanupErr)
|
||||
} else if deleted > 0 {
|
||||
a.logger.Info("已清理过期 WS 报文", "cookie_id", a.CookieID, "deleted", deleted)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(WSRecordFlushInterval)
|
||||
defer ticker.Stop()
|
||||
batch := make([]db.WSMessage, 0, WSRecordBatchSize)
|
||||
flush := func() {
|
||||
if len(batch) == 0 {
|
||||
return
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(ctx, WSRecordWriteTimeout)
|
||||
err := a.store.WSMessages.AddBatch(writeCtx, batch)
|
||||
cancel()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
a.logger.Warn("记录 WS 报文失败", "cookie_id", a.CookieID, "count", len(batch), "err", err)
|
||||
}
|
||||
batch = batch[:0]
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case message := <-a.wsRecordQueue:
|
||||
writeCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
err := a.store.WSMessages.Add(writeCtx, message)
|
||||
cancel()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
a.logger.Warn("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
|
||||
batch = append(batch, message)
|
||||
if len(batch) >= WSRecordBatchSize {
|
||||
flush()
|
||||
}
|
||||
case <-ticker.C:
|
||||
flush()
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -667,6 +695,18 @@ func (a *Account) beginTask() (context.Context, bool) {
|
||||
|
||||
// handleMaxFailures 是历史兼容恢复入口;只尝试 Go 协议续期,不执行密码登录。
|
||||
func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
// 先执行低成本登录态检查。它可能仅凭 loginuser.get 响应头恢复签名
|
||||
// Cookie,也能在进入静默续期前准确识别风控状态。
|
||||
loginStatus := a.tryLoginStatusCheck(ctx)
|
||||
if loginStatus.riskRequired {
|
||||
return fmt.Errorf("账号 %s 需要完成安全验证", a.CookieID)
|
||||
}
|
||||
if loginStatus.recovered {
|
||||
a.logger.Info("登录态检查已恢复 Cookie,重置失败计数")
|
||||
a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接")
|
||||
a.resetFailures()
|
||||
return sleepCtx(ctx, 2*time.Second)
|
||||
}
|
||||
credentialUnlock := func() {}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
@@ -772,10 +812,54 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
|
||||
if !ok {
|
||||
return loginStatusCheckResult{}
|
||||
}
|
||||
credentialUnlock := func() {}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
}
|
||||
defer credentialUnlock()
|
||||
a.mu.Lock()
|
||||
cookieStr := a.CookieStr
|
||||
a.mu.Unlock()
|
||||
res, err := checker.CheckLoginStatusContext(ctx, cookieStr)
|
||||
requestCtx := ctx
|
||||
var cookieSession *mtop.CookieSession
|
||||
metadataJSON := ""
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
|
||||
if detailErr != nil || detail == nil {
|
||||
if detailErr == nil {
|
||||
detailErr = db.ErrNotFound
|
||||
}
|
||||
a.logger.Warn("登录态检查前读取最新 Cookie 失败", "err", detailErr)
|
||||
return loginStatusCheckResult{}
|
||||
}
|
||||
cookieStr = detail.Value
|
||||
metadataJSON = detail.MetadataJSON
|
||||
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
}
|
||||
res, err := checker.CheckLoginStatusContext(requestCtx, cookieStr)
|
||||
if cookieSession != nil {
|
||||
value, snapshot, changed := cookieSession.State()
|
||||
if changed {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
|
||||
if snapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(metadataJSON, snapshot)
|
||||
}
|
||||
if persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, value, metadata, time.Now().Unix()); persistErr != nil {
|
||||
a.logger.Warn("登录态检查保存响应 Cookie Jar 失败", "err", persistErr)
|
||||
return loginStatusCheckResult{}
|
||||
}
|
||||
a.replaceCredentialState(value, credentialStateFingerprint(value, metadata))
|
||||
a.clearTokenCache(ctx)
|
||||
if err != nil {
|
||||
a.logger.Warn("登录态检查失败,已保存响应 Cookie", "err", err)
|
||||
}
|
||||
return loginStatusCheckResult{recovered: res != nil && res.Status == mtop.LoginStatusTokenRefreshed}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("登录态检查失败", "err", err)
|
||||
return loginStatusCheckResult{}
|
||||
@@ -788,7 +872,7 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
|
||||
a.logger.Warn("登录态检查命中风控验证", "ret", strings.Join(res.Ret, ","), "verification_url", res.VerificationURL)
|
||||
return loginStatusCheckResult{riskRequired: true, verificationURL: res.VerificationURL}
|
||||
}
|
||||
if a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") {
|
||||
if res.Status == mtop.LoginStatusTokenRefreshed && len(cookierefresh.ChangedCookieNames(cookieStr, res.UpdatedCookies)) > 0 && a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") {
|
||||
a.logger.Info("登录态检查刷新了 Cookie", "status", res.Status, "message", res.Message)
|
||||
return loginStatusCheckResult{recovered: true}
|
||||
}
|
||||
@@ -1552,18 +1636,25 @@ func (a *Account) currentSenderState() (WSConn, string, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.conn == nil {
|
||||
return nil, "", fmt.Errorf("账号 %s 当前没有可用 WebSocket 连接", a.CookieID)
|
||||
return nil, "", fmt.Errorf("%w: 账号 %s 当前没有可用 WebSocket 连接", automation.ErrMessageNotSent, a.CookieID)
|
||||
}
|
||||
myID := strings.TrimSpace(a.UserID)
|
||||
if myID == "" {
|
||||
myID = protocol.TransCookies(a.CookieStr)["unb"]
|
||||
}
|
||||
if myID == "" {
|
||||
return nil, "", fmt.Errorf("账号 %s 缺少 unb,无法发送消息", a.CookieID)
|
||||
return nil, "", fmt.Errorf("%w: 账号 %s 缺少 unb,无法发送消息", automation.ErrMessageNotSent, a.CookieID)
|
||||
}
|
||||
return a.conn, myID, nil
|
||||
}
|
||||
|
||||
// AutomationReady 报告自动化消息是否可以立即使用当前 WS 连接发送。
|
||||
func (a *Account) AutomationReady() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.conn != nil && a.runtimeState == RuntimeOnline
|
||||
}
|
||||
|
||||
func (a *Account) replaceCookieStr(cookieStr string) {
|
||||
a.replaceCredentialState(cookieStr, credentialStateFingerprint(cookieStr, ""))
|
||||
}
|
||||
|
||||
@@ -60,6 +60,9 @@ func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, fu
|
||||
Store: store,
|
||||
Handler: h,
|
||||
})
|
||||
// 通用账号测试默认不启用 loginuser.get;需要验证登录态恢复的用例会
|
||||
// 显式注入 statusMtop,避免单元测试访问真实网络。
|
||||
acc.mtop = &fakeRunMtop{token: "test-token"}
|
||||
return acc, h, store, func() { d.Close() }
|
||||
}
|
||||
|
||||
|
||||
@@ -264,6 +264,37 @@ func TestTryLoginStatusCheck_RiskRequired(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMaxFailuresRunsLoginStatusCheckBeforeProtocolRenew(t *testing.T) {
|
||||
newCookie := "unb=123; _m_h5_tk=loginuser_recovered; sgcookie=abc"
|
||||
mtopClient := &statusMtop{
|
||||
fakeRunMtop: fakeRunMtop{token: "tok-1"},
|
||||
result: &mtop.LoginStatusResult{
|
||||
Status: mtop.LoginStatusTokenRefreshed,
|
||||
UpdatedCookies: newCookie,
|
||||
Message: "令牌已刷新",
|
||||
},
|
||||
}
|
||||
acc, handler, _, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
acc.mu.Lock()
|
||||
acc.connFailures = MaxConnectionFailures
|
||||
acc.mu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := acc.handleMaxFailures(ctx); err != ctx.Err() {
|
||||
t.Fatalf("登录态恢复后的等待应响应上下文取消: %v", err)
|
||||
}
|
||||
if handler.refresh != 0 {
|
||||
t.Fatalf("loginuser.get 已恢复时不应继续协议续期,calls=%d", handler.refresh)
|
||||
}
|
||||
if got := acc.currentCookieStr(); got != newCookie {
|
||||
t.Fatalf("登录态检查恢复 Cookie=%q want %q", got, newCookie)
|
||||
}
|
||||
if acc.connFailures != 0 {
|
||||
t.Fatalf("登录态恢复后失败计数=%d want 0", acc.connFailures)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache DB cookie 变更时采纳新 cookie 并清旧 token 缓存。
|
||||
func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
|
||||
+188
-33
@@ -20,8 +20,8 @@ import (
|
||||
const (
|
||||
loginRenewInterval = 600 * time.Second
|
||||
cookiesRefreshInterval = 600 * time.Second
|
||||
apiCookieRenewInterval = 3600 * time.Second
|
||||
accountRequestInterval = time.Second
|
||||
apiCookieRenewInterval = 4 * time.Hour
|
||||
accountRequestInterval = time.Minute
|
||||
sessionExpiredCooldown = 300 * time.Second
|
||||
passwordLoginCooldown = 300 * time.Second
|
||||
passwordErrorCooldown = 5 * time.Hour
|
||||
@@ -56,12 +56,22 @@ type Scheduler struct {
|
||||
mtop *mtop.ClientImpl
|
||||
api apirenew.Service
|
||||
cooldown *CooldownManager
|
||||
notifier RenewalNotifier
|
||||
}
|
||||
|
||||
func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRefresher, logger *slog.Logger) *Scheduler {
|
||||
type RenewalNotifier interface {
|
||||
NotifyAccountEvent(cookieID, eventType, level, title, body string)
|
||||
}
|
||||
|
||||
// NewScheduler 的最后一个参数可选,用于发送连续续期失败告警,保持旧调用方兼容。
|
||||
func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRefresher, logger *slog.Logger, notifiers ...RenewalNotifier) *Scheduler {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
var notifier RenewalNotifier
|
||||
if len(notifiers) > 0 {
|
||||
notifier = notifiers[0]
|
||||
}
|
||||
return &Scheduler{
|
||||
store: store,
|
||||
starter: starter,
|
||||
@@ -70,6 +80,7 @@ func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRef
|
||||
mtop: mtop.NewClient(),
|
||||
api: apirenew.Service{},
|
||||
cooldown: GlobalCooldown,
|
||||
notifier: notifier,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,12 +89,31 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
||||
// 官网静默插件只在页面/账号运行时启动时执行,不做每小时轮询。保留
|
||||
// 调度器入口供显式兼容配置使用,但默认关闭。
|
||||
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, false, apiCookieRenewInterval, s.executeAPICookieRenew)
|
||||
// 兼容原 cookies_refresh 配置名,但执行同一套 Go HTTP auto-login
|
||||
// 协议;Chromium 不参与普通 Cookie 续期。
|
||||
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeAPICookieRenew)
|
||||
// 官网静默插件在账号启动时执行,并由此任务按保守频率持续检查;闲鱼
|
||||
// 下发的 sdkSilent 疲劳窗口仍会在请求前阻止重复续期。
|
||||
// cookies_refresh 仅作为旧配置名的兼容别名。两套配置必须汇聚到同一个
|
||||
// goroutine,否则同时开启时会重复续期并连续重启同一账号。
|
||||
go s.runAPICookieRenewFixed(ctx)
|
||||
}
|
||||
|
||||
func (s *Scheduler) runAPICookieRenewFixed(ctx context.Context) {
|
||||
if s.apiRenewEnabled(ctx) {
|
||||
s.executeAPICookieRenew(ctx)
|
||||
}
|
||||
for {
|
||||
timer := time.NewTimer(s.apiRenewInterval(ctx))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
if !s.apiRenewEnabled(ctx) {
|
||||
continue
|
||||
}
|
||||
s.logger.Info("执行续期任务", "task", "api_cookie_renew")
|
||||
s.executeAPICookieRenew(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) runFixed(ctx context.Context, name, settingKey, intervalKey string, defaultEnabled bool, defaultInterval time.Duration, fn func(context.Context)) {
|
||||
@@ -230,6 +260,7 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
latest, err := s.reloadRenewalAccount(ctx, account)
|
||||
if err != nil {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重读账号凭证失败: " + err.Error(), RenewMethod: "auto_login_plugin"})
|
||||
s.logger.Warn("接口续期任务失败", "account", account.ID, "err", "重读账号凭证失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
account = latest
|
||||
@@ -243,10 +274,11 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
message = callErr.Error()
|
||||
}
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: message, RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
|
||||
s.logger.Warn("接口续期任务失败", "account", account.ID, "err", message)
|
||||
return
|
||||
}
|
||||
if res.HasPending() {
|
||||
s.watchPendingAPIRenew(account.ID, res)
|
||||
s.watchPendingAPIRenew(batchID, account.ID, res)
|
||||
}
|
||||
stepDetails := make([]string, 0, len(res.StepDetails)+1)
|
||||
for _, step := range res.StepDetails {
|
||||
@@ -254,13 +286,18 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
}
|
||||
stepDetails = append(stepDetails, fmt.Sprintf("result: success=%v skipped=%v reason=%s", res.Success, res.Skipped, res.SkipReason))
|
||||
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
|
||||
credentialChanged := false
|
||||
if res.CookieSnapshotComplete || len(res.SetCookies) > 0 || res.NewCookies != account.Value {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if res.CookieSnapshotComplete {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, res.CookieSnapshot)
|
||||
}
|
||||
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) {
|
||||
// 扁平 Cookie 的排序和尾分号不是凭证变化;只有字段值变化才需要
|
||||
// 写回和重启。完整 Jar 则还要比较 Domain/Path/Expires 等 metadata。
|
||||
credentialChanged = len(updated) > 0 || metadata != account.MetadataJSON
|
||||
if credentialChanged && !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
|
||||
s.logger.Warn("接口续期任务失败", "account", account.ID, "method", res.RenewMethod, "err", "保存 Cookie 失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -270,21 +307,28 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod,
|
||||
DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount,
|
||||
})
|
||||
s.logger.Warn("api_cookie_renew 失败,已保存响应头 Cookie", "account", account.ID, "err", callErr)
|
||||
s.logger.Warn("接口续期任务失败,已保存响应头 Cookie", "account", account.ID, "method", res.RenewMethod, "updated", strings.Join(updated, ","), "err", callErr)
|
||||
return
|
||||
}
|
||||
if res.Success && account.Enabled {
|
||||
if res.Success && account.Enabled && credentialChanged {
|
||||
s.logger.Info("接口续期任务成功", "account", account.ID, "method", res.RenewMethod, "updated", strings.Join(updated, ","), "message", res.Message)
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if restarter, ok := s.starter.(accountRestarter); ok {
|
||||
s.logger.Info("接口续期成功,正在重启账号以应用最新登录凭证", "account", account.ID)
|
||||
if err := restarter.Restart(ctx, account.ID); err != nil {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重建消息连接失败: " + err.Error(), UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
|
||||
s.logger.Warn("接口续期成功,但重启账号失败", "account", account.ID, "err", err)
|
||||
return
|
||||
}
|
||||
s.logger.Info("接口续期后的账号重启已完成", "account", account.ID)
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(ctx, account.ID)
|
||||
}
|
||||
status := "failed"
|
||||
if res.Skipped {
|
||||
if res.HasPending() {
|
||||
status = "pending"
|
||||
} else if res.Skipped {
|
||||
status = "skipped"
|
||||
} else if res.Success && len(updated) > 0 {
|
||||
status = "cookie_updated"
|
||||
@@ -303,6 +347,13 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
DurationMS: time.Since(started).Milliseconds(),
|
||||
RequestCount: res.RequestCount,
|
||||
})
|
||||
if res.HasPending() {
|
||||
s.logger.Info("接口续期任务等待底层响应", "account", account.ID, "method", res.RenewMethod, "message", res.Message)
|
||||
} else if res.Skipped {
|
||||
s.logger.Info("接口续期任务已跳过", "account", account.ID, "reason", res.SkipReason, "message", res.Message)
|
||||
} else if !res.Success {
|
||||
s.logger.Warn("接口续期任务未成功", "account", account.ID, "method", res.RenewMethod, "message", res.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*apirenew.Result, error) {
|
||||
@@ -311,47 +362,130 @@ func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string, snapshot []c
|
||||
return s.api.RenewAPIFirst(runCtx, cookieStr, snapshot)
|
||||
}
|
||||
|
||||
func (s *Scheduler) watchPendingAPIRenew(cookieID string, result *apirenew.Result) {
|
||||
func (s *Scheduler) watchPendingAPIRenew(batchID, cookieID string, result *apirenew.Result) {
|
||||
if result == nil || !result.HasPending() || s.store == nil || s.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
late, waitErr := result.AwaitPending(waitCtx)
|
||||
waitCancel()
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
s.logger.Warn("等待定时静默续期底层响应失败", "account", cookieID, "err", waitErr)
|
||||
s.addAPILog(context.Background(), db.RenewalLog{BatchID: batchID, CookieID: cookieID, Status: "failed", ErrorMessage: waitErr.Error(), RenewMethod: "auto_login_plugin"})
|
||||
}
|
||||
return
|
||||
}
|
||||
unlock := s.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := s.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
opCtx, opCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer opCancel()
|
||||
var finalErr error
|
||||
changed := func() bool {
|
||||
unlock := s.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := s.store.Cookies.GetDetails(opCtx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
}
|
||||
s.logger.Warn("保存定时静默续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
finalErr = getErr
|
||||
return false
|
||||
}
|
||||
s.logger.Warn("保存定时静默续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
return
|
||||
}
|
||||
newCookies, metadata, changed := apirenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if changed {
|
||||
if saveErr := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
newCookies, metadata, changed := apirenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if !changed {
|
||||
return false
|
||||
}
|
||||
if saveErr := s.store.Cookies.UpdateRenewalCookie(opCtx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
s.logger.Warn("保存定时静默续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
|
||||
return
|
||||
finalErr = saveErr
|
||||
return false
|
||||
}
|
||||
if s.store.Tokens != nil {
|
||||
_ = s.store.Tokens.Clear(ctx, cookieID)
|
||||
_ = s.store.Tokens.Clear(opCtx, cookieID)
|
||||
}
|
||||
return true
|
||||
}()
|
||||
if changed {
|
||||
s.logger.Info("已异步接收定时静默续期迟到 Cookie", "account", cookieID)
|
||||
if restarter, ok := s.starter.(accountRestarter); ok {
|
||||
enabled, _, statusErr := s.store.Cookies.StatusWithReason(opCtx, cookieID)
|
||||
if statusErr != nil {
|
||||
s.logger.Warn("迟到续期 Cookie 已保存,但读取账号状态失败", "account", cookieID, "err", statusErr)
|
||||
finalErr = statusErr
|
||||
} else if !enabled {
|
||||
s.logger.Info("迟到续期 Cookie 已保存,账号已停用,不执行重启", "account", cookieID)
|
||||
} else {
|
||||
s.logger.Info("迟到续期 Cookie 已更新,正在重启账号以应用最新登录凭证", "account", cookieID)
|
||||
if restartErr := restarter.Restart(opCtx, cookieID); restartErr != nil {
|
||||
s.logger.Warn("迟到续期 Cookie 已保存,但重启账号失败", "account", cookieID, "err", restartErr)
|
||||
finalErr = restartErr
|
||||
} else {
|
||||
s.logger.Info("迟到续期 Cookie 更新后的账号重启已完成", "account", cookieID)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(opCtx, cookieID)
|
||||
}
|
||||
if waitErr != nil {
|
||||
s.logger.Warn("定时静默续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
|
||||
finalErr = errors.Join(finalErr, waitErr)
|
||||
}
|
||||
status := "failed"
|
||||
errorMessage := ""
|
||||
if finalErr != nil {
|
||||
errorMessage = finalErr.Error()
|
||||
} else if late.Success {
|
||||
if changed {
|
||||
status = "cookie_updated"
|
||||
} else {
|
||||
status = "success"
|
||||
}
|
||||
} else {
|
||||
errorMessage = late.Message
|
||||
}
|
||||
s.addAPILog(opCtx, db.RenewalLog{
|
||||
BatchID: batchID, CookieID: cookieID, Status: status, Message: late.Message,
|
||||
ErrorMessage: errorMessage, UpdatedCookieNames: late.UpdatedCookieNames,
|
||||
ResponseContent: late.ResponseText, RenewMethod: late.RenewMethod,
|
||||
RequestCount: late.RequestCount,
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Scheduler) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if s == nil || s.store == nil || s.store.Automation == nil {
|
||||
return
|
||||
}
|
||||
if err := s.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
s.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
return
|
||||
}
|
||||
s.logger.Info("Cookie 更新后已唤醒待恢复自动化任务", "account", cookieID)
|
||||
}
|
||||
|
||||
func (s *Scheduler) apiRenewEnabled(ctx context.Context) bool {
|
||||
if s.settingConfigured(ctx, apiCookieRenewEnabledSetting) {
|
||||
return s.settingEnabled(ctx, apiCookieRenewEnabledSetting, true)
|
||||
}
|
||||
return s.settingEnabled(ctx, cookiesRefreshEnabledSetting, true)
|
||||
}
|
||||
|
||||
func (s *Scheduler) apiRenewInterval(ctx context.Context) time.Duration {
|
||||
if s.settingConfigured(ctx, apiCookieRenewIntervalSetting) {
|
||||
return s.settingInterval(ctx, apiCookieRenewIntervalSetting, apiCookieRenewInterval)
|
||||
}
|
||||
return s.settingInterval(ctx, cookiesRefreshIntervalSetting, apiCookieRenewInterval)
|
||||
}
|
||||
|
||||
func (s *Scheduler) settingConfigured(ctx context.Context, key string) bool {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return false
|
||||
}
|
||||
value, err := s.store.Settings.Get(ctx, key)
|
||||
return err == nil && strings.TrimSpace(value) != ""
|
||||
}
|
||||
|
||||
func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalAccount) (db.RenewalAccount, error) {
|
||||
detail, err := s.store.Cookies.GetDetails(ctx, account.ID)
|
||||
if err != nil || detail == nil {
|
||||
@@ -399,7 +533,28 @@ func (s *Scheduler) addLoginLog(ctx context.Context, batchID, cookieID, status,
|
||||
}
|
||||
|
||||
func (s *Scheduler) addAPILog(ctx context.Context, log db.RenewalLog) {
|
||||
_ = s.store.Renewal.AddAPICookieRenewLog(ctx, log)
|
||||
if err := s.store.Renewal.AddAPICookieRenewLog(ctx, log); err != nil {
|
||||
s.logger.Warn("记录 API Cookie 续期日志失败", "account", log.CookieID, "status", log.Status, "err", err)
|
||||
return
|
||||
}
|
||||
if s.notifier == nil || log.Status != "failed" || s.store == nil || s.store.Renewal == nil {
|
||||
return
|
||||
}
|
||||
statuses, err := s.store.Renewal.RecentAPICookieRenewStatuses(ctx, log.CookieID, 4)
|
||||
if err != nil || len(statuses) < 3 || statuses[0] != "failed" || statuses[1] != "failed" || statuses[2] != "failed" {
|
||||
return
|
||||
}
|
||||
if len(statuses) >= 4 && statuses[3] == "failed" {
|
||||
return
|
||||
}
|
||||
reason := strings.TrimSpace(log.ErrorMessage)
|
||||
if reason == "" {
|
||||
reason = strings.TrimSpace(log.Message)
|
||||
}
|
||||
if reason == "" {
|
||||
reason = "未知错误"
|
||||
}
|
||||
s.notifier.NotifyAccountEvent(log.CookieID, "token_renewal", "warn", "闲鱼 Cookie 自动续期连续失败", fmt.Sprintf("账号 %s 的 API 自动续期已连续失败 3 次,最近错误:%s", log.CookieID, reason))
|
||||
}
|
||||
|
||||
func (s *Scheduler) cleanupExpiredLogs(ctx context.Context) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package renewal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -48,10 +49,39 @@ func (f *schedulerFakeStarter) Restart(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type schedulerContextStarter struct {
|
||||
restarts atomic.Int32
|
||||
ctxAlive atomic.Bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *schedulerContextStarter) Start(context.Context, string, string) error { return nil }
|
||||
|
||||
func (f *schedulerContextStarter) Restart(ctx context.Context, _ string) error {
|
||||
f.restarts.Add(1)
|
||||
f.ctxAlive.Store(ctx.Err() == nil)
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
type schedulerFakePasswordRefresher struct {
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
type schedulerFakeNotifier struct {
|
||||
calls atomic.Int32
|
||||
title string
|
||||
message string
|
||||
}
|
||||
|
||||
func (f *schedulerFakeNotifier) NotifyAccountEvent(_ string, _ string, _ string, title, body string) {
|
||||
f.calls.Add(1)
|
||||
f.title = title
|
||||
f.message = body
|
||||
}
|
||||
|
||||
func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, _ string) bool {
|
||||
f.calls.Add(1)
|
||||
return true
|
||||
@@ -121,8 +151,157 @@ func TestSchedulerIntervalsAligned(t *testing.T) {
|
||||
if cookiesRefreshInterval != 10*time.Minute {
|
||||
t.Fatalf("cookiesRefreshInterval=%s want 10m", cookiesRefreshInterval)
|
||||
}
|
||||
if apiCookieRenewInterval != time.Hour {
|
||||
t.Fatalf("apiCookieRenewInterval=%s want 1h", apiCookieRenewInterval)
|
||||
if apiCookieRenewInterval != 4*time.Hour {
|
||||
t.Fatalf("apiCookieRenewInterval=%s want 4h", apiCookieRenewInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingAPIRenewLogsPendingAndRestartsAfterLateCookie(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
account := createSchedulerAccount(t, store, "cid-pending", "unb=1; havana_lgc_exp="+strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10))
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerFakeStarter{}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 10 * time.Millisecond,
|
||||
}
|
||||
s.apiCookieRenewOne(context.Background(), "batch-pending", account)
|
||||
if got := lastAPIRenewLog(t, store, account.ID).status; got != "pending" {
|
||||
t.Fatalf("Promise 未完成时 status=%q want pending", got)
|
||||
}
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for starter.restarts.Load() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if got := starter.restarts.Load(); got != 1 {
|
||||
t.Fatalf("迟到 Cookie 保存后 restarts=%d want 1", got)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(context.Background(), account.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(detail.Value, "sdkSilent=") {
|
||||
t.Fatalf("迟到 Cookie 未保存: %q", detail.Value)
|
||||
}
|
||||
if got := lastAPIRenewLog(t, store, account.ID).status; got != "cookie_updated" {
|
||||
t.Fatalf("迟到响应最终状态=%q want cookie_updated", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICookieRenewSuccessWithoutCredentialChangeDoesNotRestart(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
expire := strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
|
||||
account := createSchedulerAccount(t, store, "cid-no-change", "unb=1; havana_lgc_exp="+expire)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerFakeStarter{}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
s.apiCookieRenewOne(context.Background(), "batch-no-change", account)
|
||||
if got := starter.restarts.Load(); got != 0 {
|
||||
t.Fatalf("Cookie 未变化时不应重启账号,restarts=%d", got)
|
||||
}
|
||||
if got := lastAPIRenewLog(t, store, account.ID).status; got != "success" {
|
||||
t.Fatalf("无变化成功状态=%q want success", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingAPIRenewUsesFreshContextForRestart(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
expire := strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
|
||||
account := createSchedulerAccount(t, store, "cid-fresh-context", "unb=1; havana_lgc_exp="+expire)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureSchedulerMillis(), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerContextStarter{}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond}
|
||||
s.apiCookieRenewOne(context.Background(), "batch-context", account)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for starter.restarts.Load() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if starter.restarts.Load() != 1 || !starter.ctxAlive.Load() {
|
||||
t.Fatalf("迟到响应重启必须使用独立有效上下文: restarts=%d alive=%v", starter.restarts.Load(), starter.ctxAlive.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPendingAPIRenewRestartFailureIsFinalFailure(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
account := createSchedulerAccount(t, store, "cid-restart-failure", "unb=1; havana_lgc_exp="+futureSchedulerMillis())
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureSchedulerMillis(), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
starter := &schedulerContextStarter{err: errors.New("restart failed")}
|
||||
s := NewScheduler(store, starter, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond}
|
||||
s.apiCookieRenewOne(context.Background(), "batch-restart-failure", account)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
log := lastAPIRenewLog(t, store, account.ID)
|
||||
if log.status != "pending" {
|
||||
if log.status != "failed" || !strings.Contains(log.errorMessage, "restart failed") {
|
||||
t.Fatalf("重启失败终态异常: %+v", log)
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("迟到续期没有写入重启失败终态")
|
||||
}
|
||||
|
||||
func futureSchedulerMillis() string {
|
||||
return strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
|
||||
}
|
||||
|
||||
func TestAPIRenewCompatibilitySettingsUseSingleRunner(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
expire := futureSchedulerMillis()
|
||||
createSchedulerAccount(t, store, "cid-single-runner", "unb=1; havana_lgc_exp="+expire)
|
||||
for _, key := range []string{apiCookieRenewEnabledSetting, cookiesRefreshEnabledSetting} {
|
||||
if err := store.Settings.Set(ctx, key, "true"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := store.Settings.Set(ctx, apiCookieRenewIntervalSetting, "10s"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var requests atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
s.api = apirenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
s.Run(ctx)
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for requests.Load() == 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
if got := requests.Load(); got != 1 {
|
||||
t.Fatalf("新旧配置同时开启只能启动一个续期任务,请求数=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,6 +322,27 @@ func TestSchedulerDefaultsMatchUpstreamConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICookieRenewFailureNotifiesOnlyAtThirdConsecutiveFailure(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
notifier := &schedulerFakeNotifier{}
|
||||
s := NewScheduler(store, nil, nil, nil, notifier)
|
||||
ctx := context.Background()
|
||||
for i := 0; i < 3; i++ {
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: "batch", CookieID: "cid-failure", Status: "failed", ErrorMessage: "接口超时"})
|
||||
}
|
||||
if notifier.calls.Load() != 1 {
|
||||
t.Fatalf("连续三次失败应通知 1 次,实际 %d", notifier.calls.Load())
|
||||
}
|
||||
if notifier.title == "" || !strings.Contains(notifier.message, "连续失败 3 次") {
|
||||
t.Fatalf("通知内容异常: title=%q body=%q", notifier.title, notifier.message)
|
||||
}
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: "batch", CookieID: "cid-failure", Status: "failed", ErrorMessage: "接口超时"})
|
||||
if notifier.calls.Load() != 1 {
|
||||
t.Fatalf("连续第四次失败不应重复通知,实际 %d", notifier.calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -76,6 +76,61 @@ func TestAutomationRulesCRUD(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationRulesListFiltersAndPagination(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','item-blue','蓝色会员')`)
|
||||
for _, input := range []db.AutomationRuleInput{
|
||||
{UserID: 1, CookieID: "acc1", ItemID: "item-blue", Name: "付款规则", TriggerType: automation.TriggerOrderPaid, Enabled: true, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionConfirmShipment, Enabled: true}}},
|
||||
{UserID: 1, CookieID: "acc1", Name: "评价赠品", TriggerType: automation.TriggerBuyerReviewed, Enabled: false, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "gift", Enabled: true}}},
|
||||
{UserID: 1, CookieID: "acc1", Name: "求评价", TriggerType: automation.TriggerReviewMissingTimeout, Enabled: true, Priority: 100, Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "review", Enabled: true}}},
|
||||
} {
|
||||
if _, err := store.Automation.Create(ctx, input); err != nil {
|
||||
t.Fatalf("create rule: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
request := func(path string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
var body map[string]any
|
||||
if rec.Code == http.StatusOK {
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
}
|
||||
return rec.Code, body
|
||||
}
|
||||
|
||||
status, filtered := request("/automation-rules?page=1&page_size=10&cookie_id=acc1&trigger_type=order_paid&enabled=true&search=%E8%93%9D%E8%89%B2")
|
||||
if status != http.StatusOK || filtered["total"] != float64(1) || filtered["total_pages"] != float64(1) {
|
||||
t.Fatalf("filtered status=%d body=%+v", status, filtered)
|
||||
}
|
||||
data, ok := filtered["data"].([]any)
|
||||
if !ok || len(data) != 1 || data[0].(map[string]any)["name"] != "付款规则" {
|
||||
t.Fatalf("filtered data=%+v", filtered["data"])
|
||||
}
|
||||
|
||||
status, lastPage := request("/automation-rules?page=99&page_size=1")
|
||||
if status != http.StatusOK || lastPage["total"] != float64(3) || lastPage["page"] != float64(3) {
|
||||
t.Fatalf("last page status=%d body=%+v", status, lastPage)
|
||||
}
|
||||
if data, ok := lastPage["data"].([]any); !ok || len(data) != 1 {
|
||||
t.Fatalf("last page data=%+v", lastPage["data"])
|
||||
}
|
||||
|
||||
status, _ = request("/automation-rules?page=1&enabled=maybe")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("invalid enabled status=%d", status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleBadTriggerType 不支持的触发类型 400。
|
||||
func TestAutomationRuleBadTriggerType(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
|
||||
@@ -104,11 +104,82 @@ type automationRuleRequest struct {
|
||||
|
||||
func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID)
|
||||
query := r.URL.Query()
|
||||
_, paginated := query["page"]
|
||||
if !paginated {
|
||||
rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, automationRulesJSON(rules))
|
||||
return
|
||||
}
|
||||
|
||||
page := atoiDefault(query.Get("page"), 1)
|
||||
pageSize := atoiDefault(query.Get("page_size"), 10)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 10
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
cookieID := strings.TrimSpace(query.Get("cookie_id"))
|
||||
if cookieID != "" {
|
||||
if _, ok := s.cookieForUser(r, sess.UserID, cookieID); !ok {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
}
|
||||
triggerType := strings.TrimSpace(query.Get("trigger_type"))
|
||||
if triggerType != "" {
|
||||
switch triggerType {
|
||||
case automation.TriggerOrderPaid, automation.TriggerBuyerReviewed, automation.TriggerReviewMissingTimeout:
|
||||
default:
|
||||
writeErr(w, http.StatusBadRequest, "不支持的触发类型")
|
||||
return
|
||||
}
|
||||
}
|
||||
var enabled *bool
|
||||
if rawEnabled := strings.TrimSpace(query.Get("enabled")); rawEnabled != "" {
|
||||
value, parseErr := strconv.ParseBool(rawEnabled)
|
||||
if parseErr != nil {
|
||||
writeErr(w, http.StatusBadRequest, "启用状态必须是 true 或 false")
|
||||
return
|
||||
}
|
||||
enabled = &value
|
||||
}
|
||||
|
||||
rules, total, err := s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{
|
||||
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
|
||||
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
|
||||
return
|
||||
}
|
||||
totalPages := (total + pageSize - 1) / pageSize
|
||||
if totalPages > 0 && page > totalPages {
|
||||
page = totalPages
|
||||
rules, _, err = s.Store.Automation.ListPageForUser(r.Context(), db.AutomationRuleListFilter{
|
||||
UserID: sess.UserID, CookieID: cookieID, TriggerType: triggerType, Enabled: enabled,
|
||||
Search: query.Get("search"), Limit: pageSize, Offset: (page - 1) * pageSize,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true, "data": automationRulesJSON(rules), "total": total,
|
||||
"page": page, "page_size": pageSize, "total_pages": totalPages,
|
||||
})
|
||||
}
|
||||
|
||||
func automationRulesJSON(rules []db.AutomationRule) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
actions := make([]map[string]any, 0, len(rule.Actions))
|
||||
@@ -127,7 +198,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
|
||||
"created_at": rule.CreatedAt, "updated_at": rule.UpdatedAt,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -651,10 +651,15 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
credentialUnlock()
|
||||
// Stop 会等待 Account.Run 退出,而 Run 可能正在等待同一凭证锁,因此必须
|
||||
// 在删除事务完成并释放锁后调用。
|
||||
s.Logger.Info("账号已删除",
|
||||
"cookie_id", cid,
|
||||
"nickname", cachedAccountNickname(latest),
|
||||
"user_id", latest.UserID,
|
||||
)
|
||||
// Stop 可能需要等待运行中任务收尾,不应阻塞删除 HTTP 请求。
|
||||
// 数据库事务已完成,先向前端确认删除,再在后台精确停止该 cid 的实例。
|
||||
if s.Manager != nil {
|
||||
s.Manager.Stop(cid)
|
||||
go s.Manager.Stop(cid)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
@@ -738,6 +739,7 @@ func TestDeleteCookie(t *testing.T) {
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
store.Cookies.Save(ctx, "acc-del", "unb=1; _m_h5_tk=t_1;", 1)
|
||||
store.Cookies.Save(ctx, "acc-keep", "unb=2; _m_h5_tk=t_2;", 1)
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
@@ -748,6 +750,12 @@ func TestDeleteCookie(t *testing.T) {
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("delete status=%d", rec.Code)
|
||||
}
|
||||
if _, err := store.Cookies.GetDetails(ctx, "acc-del"); !errors.Is(err, db.ErrNotFound) {
|
||||
t.Fatalf("目标账号应被删除,err=%v", err)
|
||||
}
|
||||
if kept, err := store.Cookies.GetDetails(ctx, "acc-keep"); err != nil || kept.ID != "acc-keep" {
|
||||
t.Fatalf("非目标账号不应被删除,kept=%+v err=%v", kept, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddCookieBad 缺 id 或 value 400。
|
||||
|
||||
@@ -23,6 +23,7 @@ func (s *Server) mountItemsReal(r chi.Router) {
|
||||
r.Post("/items/get-all-from-account", s.syncItemsFromAccount)
|
||||
r.Post("/items/get-by-page", s.syncItemsPageFromAccount)
|
||||
r.Post("/items/publish", s.publishItem)
|
||||
r.Post("/items/publish-categories/recommend", s.recommendItemPublishCategory)
|
||||
r.Post("/items/publish-batches/preview", s.previewItemPublishBatch)
|
||||
r.Post("/items/publish-batches", s.startItemPublishBatch)
|
||||
r.Get("/items/publish-batches", s.listItemPublishBatches)
|
||||
@@ -108,6 +109,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
Quantity: quantity,
|
||||
PostageMode: postageMode,
|
||||
PostageCents: postageCents,
|
||||
Virtual: true,
|
||||
Images: images,
|
||||
})
|
||||
runtimeCookie := ""
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/textproto"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
@@ -20,6 +21,63 @@ type stubPublishMTop struct {
|
||||
publish func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error)
|
||||
}
|
||||
|
||||
func TestRecommendItemPublishCategory(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := srv.Manager.Start(ctx, "acc1", "unb=123; _m_h5_tk=tk1_1;"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Tokens.Save(context.Background(), "acc1", "device", "stale-token", time.Now().Add(time.Hour).Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := mtop.NewClient()
|
||||
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if req.URL.Query().Get("api") != "mtop.taobao.idle.kgraph.property.recommend" {
|
||||
t.Fatalf("api=%q", req.URL.Query().Get("api"))
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Set-Cookie": []string{
|
||||
"_m_h5_tk=recommended_2; Domain=.goofish.com; Path=/; Secure",
|
||||
}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"50023914","catName":"电子资料","channelCatId":"202036301","isClicked":"1"}]}}]}}`,
|
||||
)),
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
srv.MTop = client
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-categories/recommend", strings.NewReader(`{"cookie_id":"acc1","keyword":"课程资料"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
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 response struct {
|
||||
Category mtop.PublishCategory `json:"category"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if response.Category.CatID != "50023914" || response.Category.CatName != "电子资料" || response.Category.ChannelCatID != "202036301" {
|
||||
t.Fatalf("category=%+v", response.Category)
|
||||
}
|
||||
saved, err := store.Cookies.GetValue(context.Background(), "acc1")
|
||||
if err != nil || !strings.Contains(saved, "_m_h5_tk=recommended_2") {
|
||||
t.Fatalf("类目推荐响应 Cookie 未保存: value=%q err=%v", saved, err)
|
||||
}
|
||||
token, err := store.Tokens.Get(context.Background(), "acc1")
|
||||
if err != nil || token.AccessToken != "" {
|
||||
t.Fatalf("类目推荐 Cookie 更新后未同步运行时并清理旧 token: token=%+v err=%v", token, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubPublishMTop) PublishItem(ctx context.Context, cookies string, req mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
return s.publish(ctx, cookies, req)
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ type publishBatchPreviewRow struct {
|
||||
Price string `json:"price"`
|
||||
Quantity int `json:"quantity"`
|
||||
Images []string `json:"images"`
|
||||
Category mtop.PublishCategory `json:"category"`
|
||||
Automation publishAutomationConfig `json:"automation"`
|
||||
}
|
||||
|
||||
@@ -61,6 +62,7 @@ type publishBatchParsedRow struct {
|
||||
PostageMode string
|
||||
Postage string
|
||||
Images []string
|
||||
Category mtop.PublishCategory
|
||||
Automation publishAutomationConfig
|
||||
Errors []string
|
||||
Raw map[string]any
|
||||
@@ -92,6 +94,81 @@ type publishReviewRequestCfg struct {
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
type publishCategoryRecommender interface {
|
||||
RecommendPublishCategory(ctx context.Context, cookiesStr, keyword string) (mtop.PublishCategory, string, error)
|
||||
}
|
||||
|
||||
func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
CookieID string `json:"cookie_id"`
|
||||
Keyword string `json:"keyword"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
req.CookieID = strings.TrimSpace(req.CookieID)
|
||||
req.Keyword = strings.TrimSpace(req.Keyword)
|
||||
if req.CookieID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请先选择发布账号")
|
||||
return
|
||||
}
|
||||
if req.Keyword == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请输入类目关键词")
|
||||
return
|
||||
}
|
||||
_, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
recommender, ok := s.mtopClient().(publishCategoryRecommender)
|
||||
if !ok {
|
||||
writeErr(w, http.StatusNotImplemented, "当前 MTOP 客户端不支持类目推荐")
|
||||
return
|
||||
}
|
||||
|
||||
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
|
||||
runtimeCookie := ""
|
||||
defer func() {
|
||||
credentialUnlock()
|
||||
if runtimeCookie != "" {
|
||||
s.updateRunningCookie(context.Background(), req.CookieID, runtimeCookie)
|
||||
}
|
||||
}()
|
||||
latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID)
|
||||
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
|
||||
category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, req.Keyword)
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
|
||||
if persistErr != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号登录状态失败")
|
||||
return
|
||||
}
|
||||
if !handled && updatedCookies != "" && updatedCookies != latest.Value {
|
||||
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, updatedCookies, userID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号登录状态失败")
|
||||
return
|
||||
}
|
||||
runtimeCookie = updatedCookies
|
||||
} else if handled && valueChanged {
|
||||
runtimeCookie = value
|
||||
}
|
||||
if callErr != nil {
|
||||
if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) {
|
||||
writeErr(w, http.StatusNotFound, "没有匹配到可发布类目,请换一个关键词")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "category": category})
|
||||
}
|
||||
|
||||
func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
s.cleanupExpiredPublishUploads(r.Context())
|
||||
@@ -111,6 +188,17 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusForbidden, "默认账号不属于当前用户")
|
||||
return
|
||||
}
|
||||
fallbackCategory := mtop.PublishCategory{
|
||||
CatID: strings.TrimSpace(r.FormValue("fallback_category_id")),
|
||||
CatName: strings.TrimSpace(r.FormValue("fallback_category_name")),
|
||||
ChannelCatID: strings.TrimSpace(r.FormValue("fallback_channel_category_id")),
|
||||
TBCatID: strings.TrimSpace(r.FormValue("fallback_tb_category_id")),
|
||||
}
|
||||
hasDefaultCategory := fallbackCategory.CatID != "" || fallbackCategory.CatName != "" || fallbackCategory.ChannelCatID != "" || fallbackCategory.TBCatID != ""
|
||||
if hasDefaultCategory && (fallbackCategory.CatID == "" || fallbackCategory.CatName == "" || fallbackCategory.ChannelCatID == "") {
|
||||
writeErr(w, http.StatusBadRequest, "默认类目信息不完整,请重新通过关键词获取")
|
||||
return
|
||||
}
|
||||
source, sourceHeader, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "缺少商品表格文件")
|
||||
@@ -181,7 +269,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusBadRequest, fmt.Sprintf("单个批次最多支持 %d 条商品", maxPublishBatchRows))
|
||||
return
|
||||
}
|
||||
parsed := s.parsePublishRows(r.Context(), sess.UserID, defaultCookieID, uploadDir, maps)
|
||||
parsed := s.parsePublishRows(r.Context(), sess.UserID, defaultCookieID, uploadDir, fallbackCategory, maps)
|
||||
rows := make([]db.ItemPublishBatchRow, 0, len(parsed))
|
||||
previewRows := make([]publishBatchPreviewRow, 0, len(parsed))
|
||||
valid, invalid := 0, 0
|
||||
@@ -193,6 +281,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
invalid++
|
||||
}
|
||||
imagesJSON, _ := json.Marshal(p.Images)
|
||||
categoryJSON, _ := json.Marshal(p.Category)
|
||||
automationJSON, _ := json.Marshal(p.Automation)
|
||||
rawJSON, _ := json.Marshal(p.Raw)
|
||||
status := "pending"
|
||||
@@ -212,6 +301,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
PostageMode: p.PostageMode,
|
||||
Postage: p.Postage,
|
||||
ImagesJSON: string(imagesJSON),
|
||||
CategoryJSON: string(categoryJSON),
|
||||
AutomationJSON: string(automationJSON),
|
||||
Status: status,
|
||||
ErrorMessage: errMsg,
|
||||
@@ -227,6 +317,7 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
Price: p.Price,
|
||||
Quantity: p.Quantity,
|
||||
Images: p.Images,
|
||||
Category: p.Category,
|
||||
Automation: p.Automation,
|
||||
})
|
||||
}
|
||||
@@ -364,10 +455,6 @@ func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
if running {
|
||||
s.cancelPublishBatch(batchID, workerToken)
|
||||
} else {
|
||||
if batch, getErr := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID); getErr == nil {
|
||||
s.removePublishUploadDir(r.Context(), batch)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "status": map[bool]string{true: "canceling", false: "canceled"}[running]})
|
||||
}
|
||||
@@ -473,11 +560,7 @@ func (s *Server) recoverPublishBatchesOnce(ctx context.Context) {
|
||||
}
|
||||
for _, batch := range batches {
|
||||
if batch.Status == "canceling" {
|
||||
finalized, finalizeErr := s.Store.PublishBatches.FinalizeExpiredCancellation(ctx, batch.ID, time.Now().UTC().Unix())
|
||||
if finalizeErr != nil || !finalized {
|
||||
continue
|
||||
}
|
||||
s.removePublishUploadDir(ctx, &batch)
|
||||
_, _ = s.Store.PublishBatches.FinalizeExpiredCancellation(ctx, batch.ID, time.Now().UTC().Unix())
|
||||
continue
|
||||
}
|
||||
workerToken := randomHex(16)
|
||||
@@ -529,11 +612,14 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("\xEF\xBB\xBF")
|
||||
cw := csv.NewWriter(&buf)
|
||||
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "商品ID", "商品URL", "错误原因"})
|
||||
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "默认类目ID", "默认类目名称", "商品ID", "商品URL", "错误原因"})
|
||||
for _, row := range rows {
|
||||
var category mtop.PublishCategory
|
||||
_ = json.Unmarshal([]byte(row.CategoryJSON), &category)
|
||||
_ = cw.Write([]string{
|
||||
strconv.Itoa(row.RowNo), safeCSVCell(row.Status), safeCSVCell(row.CookieID), safeCSVCell(row.Title), safeCSVCell(row.Price),
|
||||
strconv.Itoa(row.Quantity), safeCSVCell(row.ItemID), safeCSVCell(row.ItemURL), safeCSVCell(row.ErrorMessage),
|
||||
strconv.Itoa(row.Quantity), safeCSVCell(category.CatID), safeCSVCell(category.CatName),
|
||||
safeCSVCell(row.ItemID), safeCSVCell(row.ItemURL), safeCSVCell(row.ErrorMessage),
|
||||
})
|
||||
}
|
||||
cw.Flush()
|
||||
@@ -705,12 +791,9 @@ func (s *Server) finishInterruptedPublishBatch(ctx context.Context, userID int64
|
||||
if batch.WorkerToken != workerToken {
|
||||
return
|
||||
}
|
||||
finalized, finalizeErr := s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
if finalizeErr != nil || !finalized {
|
||||
return
|
||||
}
|
||||
_, _ = s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
}
|
||||
s.removePublishUploadDir(wctx, batch)
|
||||
// 取消产生的 interrupted 失败行允许用户稍后重试,图片由统一的过期清理保留 7 天。
|
||||
return
|
||||
}
|
||||
_, _, finalizeErr := s.Store.PublishBatches.FinalizeInterrupted(wctx, batchID, workerToken, "任务超时或已中断")
|
||||
@@ -727,11 +810,8 @@ func (s *Server) finishPublishBatch(ctx context.Context, userID int64, batchID,
|
||||
return
|
||||
}
|
||||
if batch.Status == "canceling" {
|
||||
finalized, finalizeErr := s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
if finalizeErr != nil || !finalized {
|
||||
return
|
||||
}
|
||||
s.removePublishUploadDir(wctx, batch)
|
||||
_, _ = s.Store.PublishBatches.FinalizeCanceled(wctx, batchID, workerToken)
|
||||
// 取消任务仍可“重试失败项”,不能在此删除重试所需的本地图片。
|
||||
return
|
||||
}
|
||||
finalStatus, finished, finishErr := s.Store.PublishBatches.FinalizeBatch(wctx, batchID, workerToken)
|
||||
@@ -777,6 +857,20 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
res := &mtop.PublishItemResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity}
|
||||
var responseCookieErr error
|
||||
if row.ItemID == "" {
|
||||
var preferredCategory *mtop.PublishCategory
|
||||
rawCategory := strings.TrimSpace(row.CategoryJSON)
|
||||
if rawCategory != "" && rawCategory != "{}" {
|
||||
var configured mtop.PublishCategory
|
||||
if err := json.Unmarshal([]byte(rawCategory), &configured); err != nil {
|
||||
return errors.New("默认类目配置损坏,请重新创建批量任务")
|
||||
}
|
||||
if strings.TrimSpace(configured.CatID) != "" || strings.TrimSpace(configured.CatName) != "" || strings.TrimSpace(configured.ChannelCatID) != "" || strings.TrimSpace(configured.TBCatID) != "" {
|
||||
if strings.TrimSpace(configured.CatID) == "" || strings.TrimSpace(configured.CatName) == "" || strings.TrimSpace(configured.ChannelCatID) == "" {
|
||||
return errors.New("默认类目信息不完整,请重新创建批量任务")
|
||||
}
|
||||
preferredCategory = &configured
|
||||
}
|
||||
}
|
||||
images, err := loadBatchPublishImages(ctx, batch.UploadDir, row)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -814,6 +908,8 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
Quantity: row.Quantity,
|
||||
PostageMode: row.PostageMode,
|
||||
PostageCents: postageCents,
|
||||
Virtual: true,
|
||||
PreferredCategory: preferredCategory,
|
||||
Images: images,
|
||||
})
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
@@ -860,6 +956,9 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
}
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, mtop.ErrPublishCategoryUnrecognized) {
|
||||
return err
|
||||
}
|
||||
return &uncertainRemotePublishError{err: fmt.Errorf("远端发布调用失败且结果未知: %w", err)}
|
||||
}
|
||||
rawJSON, _ := json.Marshal(res.RawData)
|
||||
@@ -1004,7 +1103,7 @@ func (s *Server) ensurePublishAutomationRule(ctx context.Context, input db.Autom
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCookieID, uploadDir string, input []map[string]any) []publishBatchParsedRow {
|
||||
func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCookieID, uploadDir string, fallbackCategory mtop.PublishCategory, input []map[string]any) []publishBatchParsedRow {
|
||||
out := make([]publishBatchParsedRow, 0, len(input))
|
||||
for i, m := range input {
|
||||
row := publishBatchParsedRow{
|
||||
@@ -1035,6 +1134,21 @@ func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCook
|
||||
row.PostageMode = "fixed"
|
||||
}
|
||||
row.Quantity = atoiPublishDefault(firstImportString(m, "quantity", "库存", "数量"), 1)
|
||||
rowCategory := mtop.PublishCategory{
|
||||
CatID: firstImportString(m, "category_id", "类目ID", "商品类目ID"),
|
||||
CatName: firstImportString(m, "category_name", "类目名称", "商品类目名称", "类目"),
|
||||
ChannelCatID: firstImportString(m, "channel_category_id", "频道类目ID"),
|
||||
TBCatID: firstImportString(m, "tb_category_id", "淘宝类目ID"),
|
||||
}
|
||||
hasRowCategory := rowCategory.CatID != "" || rowCategory.CatName != "" || rowCategory.ChannelCatID != "" || rowCategory.TBCatID != ""
|
||||
if hasRowCategory {
|
||||
row.Category = rowCategory
|
||||
if rowCategory.CatID == "" || rowCategory.CatName == "" || rowCategory.ChannelCatID == "" {
|
||||
row.Errors = append(row.Errors, "指定行类目时必须同时填写类目ID、类目名称和频道类目ID")
|
||||
}
|
||||
} else {
|
||||
row.Category = fallbackCategory
|
||||
}
|
||||
row.Automation = parsePublishAutomation(m)
|
||||
row.Images = splitImageRefs(firstImportString(m, "images", "image", "图片", "商品图片"))
|
||||
if row.CookieID == "" {
|
||||
@@ -1198,11 +1312,14 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
|
||||
}
|
||||
var refs []string
|
||||
_ = json.Unmarshal([]byte(row.ImagesJSON), &refs)
|
||||
var category mtop.PublishCategory
|
||||
_ = json.Unmarshal([]byte(row.CategoryJSON), &category)
|
||||
var automationCfg publishAutomationConfig
|
||||
_ = json.Unmarshal([]byte(row.AutomationJSON), &automationCfg)
|
||||
outRows = append(outRows, map[string]any{
|
||||
"id": row.ID, "row_no": row.RowNo, "cookie_id": row.CookieID, "title": row.Title,
|
||||
"price": row.Price, "quantity": row.Quantity, "images": refs,
|
||||
"category": category,
|
||||
"automation": automationCfg,
|
||||
"status": row.Status, "item_id": row.ItemID, "item_url": row.ItemURL,
|
||||
"error_message": row.ErrorMessage, "failure_kind": row.FailureKind,
|
||||
|
||||
@@ -181,6 +181,14 @@ func normalizePublishHeader(header string) string {
|
||||
return "postage"
|
||||
case "images", "image", "图片", "商品图片":
|
||||
return "images"
|
||||
case "categoryid", "catid", "类目id", "商品类目id":
|
||||
return "category_id"
|
||||
case "categoryname", "catname", "类目名称", "商品类目名称", "类目":
|
||||
return "category_name"
|
||||
case "channelcategoryid", "channelcatid", "频道类目id":
|
||||
return "channel_category_id"
|
||||
case "tbcategoryid", "tbcatid", "淘宝类目id":
|
||||
return "tb_category_id"
|
||||
case "paiddeliveryenabled", "付款发货启用", "付款后自动发货":
|
||||
return "paid_delivery_enabled"
|
||||
case "paiddeliverycontents", "付款发货内容", "付款后发送的卡密":
|
||||
|
||||
@@ -147,7 +147,7 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.requireChannelOwner(w, r, id) {
|
||||
return
|
||||
}
|
||||
body := "🧪 通知渠道测试\n\n这是一条来自闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " +
|
||||
body := "🧪 通知渠道测试\n\n这是一条来自Ydisks闲鱼助手的测试通知,收到说明渠道配置正常。\n时间: " +
|
||||
time.Now().Format("2006-01-02 15:04:05")
|
||||
if err := s.notifier.SendToChannel(id, body); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "发送失败: "+err.Error())
|
||||
|
||||
@@ -279,6 +279,21 @@ func TestParsePublishCardActions(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizePublishHeaderCategoryFallbackLabels(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"类目ID": "category_id",
|
||||
"类目名称": "category_name",
|
||||
"频道类目ID": "channel_category_id",
|
||||
"淘宝类目ID": "tb_category_id",
|
||||
"category_id": "category_id",
|
||||
}
|
||||
for input, want := range cases {
|
||||
if got := normalizePublishHeader(input); got != want {
|
||||
t.Fatalf("normalizePublishHeader(%q)=%q want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePublishAutomationSupportsMultipleCards(t *testing.T) {
|
||||
cfg := parsePublishAutomation(map[string]any{
|
||||
"paid_delivery_enabled": "是",
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -93,6 +95,9 @@ func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) stri
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -120,6 +125,9 @@ func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\nacc1,商品B,13.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -218,7 +226,7 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
select {
|
||||
@@ -279,12 +287,23 @@ func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
|
||||
if got["failed"] != got["total"] {
|
||||
t.Fatalf("取消后未完成行应全部失败: total=%v failed=%v body=%+v", got["total"], got["failed"], got)
|
||||
}
|
||||
batch, err := store.PublishBatches.Get(context.Background(), 1, batchID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.TrimSpace(batch.UploadDir) == "" {
|
||||
t.Fatal("取消运行中的任务后应保留 upload_dir 供失败项重试")
|
||||
}
|
||||
if _, err := os.Stat(batch.UploadDir); err != nil {
|
||||
t.Fatalf("取消运行中的任务后应保留图片目录: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunItemPublishBatch_Success 启动批次,mock mtop 全程返回 SUCCESS,验证行最终成功。
|
||||
func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
var publishedCategory map[string]any
|
||||
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
|
||||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
u := req.URL.String()
|
||||
@@ -295,9 +314,14 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
|
||||
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"100","catName":"数码"}}}`
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{}}`
|
||||
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","url":"https://x/item/123456","picUrl":"https://img.alicdn.com/published.png","categoryId":"100","categoryName":"数码","title":"商品A","priceText":"12.50","quantity":"5"}}`
|
||||
rawBody, _ := io.ReadAll(req.Body)
|
||||
form, _ := url.ParseQuery(string(rawBody))
|
||||
var publishData map[string]any
|
||||
_ = json.Unmarshal([]byte(form.Get("data")), &publishData)
|
||||
publishedCategory, _ = publishData["itemCatDTO"].(map[string]any)
|
||||
body = `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","url":"https://x/item/123456","picUrl":"https://img.alicdn.com/published.png","categoryId":"5001","categoryName":"虚拟商品","title":"商品A","priceText":"12.50","quantity":"5"}}`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
@@ -365,6 +389,9 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
|
||||
if row["status"] != "success" || row["item_id"] == "" {
|
||||
t.Fatalf("row should be success with item_id: %+v", row)
|
||||
}
|
||||
if publishedCategory["catId"] != "5001" || publishedCategory["catName"] != "虚拟商品" {
|
||||
t.Fatalf("batch did not apply fallback category: %+v", publishedCategory)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *testing.T) {
|
||||
|
||||
@@ -79,6 +79,9 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -98,6 +101,72 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
if res["success"] != true || res["valid"] != float64(1) {
|
||||
t.Fatalf("预检异常: %+v", res)
|
||||
}
|
||||
previewRow := res["rows"].([]any)[0].(map[string]any)
|
||||
category := previewRow["category"].(map[string]any)
|
||||
if category["cat_id"] != "5001" || category["cat_name"] != "虚拟商品" {
|
||||
t.Fatalf("预检未保存兜底类目: %+v", category)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewItemPublishBatchAllowsEmptyDefaultCategory(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
file, _ := mw.CreateFormFile("file", "products.csv")
|
||||
file.Write([]byte("标题,价格,图片\n商品A,12.50,https://example.com/a.png\n"))
|
||||
_ = mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
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 res map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
row := res["rows"].([]any)[0].(map[string]any)
|
||||
category := row["category"].(map[string]any)
|
||||
if category["cat_id"] != "" || category["cat_name"] != "" {
|
||||
t.Fatalf("category should be empty: %+v", category)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewItemPublishBatchRowCategoryOverridesFallback(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "批次类目")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
file, _ := mw.CreateFormFile("file", "products.csv")
|
||||
file.Write([]byte("标题,价格,图片,类目ID,类目名称,频道类目ID\n商品A,12.50,https://example.com/a.png,7001,行指定类目,8001\n"))
|
||||
_ = mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
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 res map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
row := res["rows"].([]any)[0].(map[string]any)
|
||||
category := row["category"].(map[string]any)
|
||||
if category["cat_id"] != "7001" || category["cat_name"] != "行指定类目" {
|
||||
t.Fatalf("row category=%+v", category)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchNoFile 缺表格文件 400。
|
||||
@@ -110,6 +179,9 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
@@ -181,6 +253,10 @@ func TestPreviewItemPublishBatchTooManyRows(t *testing.T) {
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write(csvBuf.Bytes())
|
||||
_ = mw.Close()
|
||||
@@ -211,6 +287,9 @@ func TestPreviewItemPublishBatchZipTraversal(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,../escape.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -280,6 +359,33 @@ func TestCancelItemPublishBatchNotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelPreviewBatchRetainsUploadDirectoryForRetry(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
batchID := previewPublishBatch(t, h, cookie)
|
||||
batch, err := store.PublishBatches.Get(context.Background(), 1, batchID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/"+batchID+"/cancel", nil)
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("cancel status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := os.Stat(batch.UploadDir); err != nil {
|
||||
t.Fatalf("取消后应保留上传目录供重试: %v", err)
|
||||
}
|
||||
retained, err := store.PublishBatches.Get(context.Background(), 1, batchID)
|
||||
if err != nil || retained.UploadDir != batch.UploadDir {
|
||||
t.Fatalf("取消后应保留 upload_dir: batch=%+v err=%v", retained, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletePreviewBatchRemovesUploadDirectory(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -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}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{positiLine truncated
|
||||
@@ -1,19 +0,0 @@
|
||||
import{j as e,r as n,b as Se,c as ra,d as na}from"./react-vendor-DZnRGM0-.js";import{L as ia,U as Pt,S as Tt,C as zs,B as Et,Z as Us,a as xs,b as Ys,c as Ft,d as oa,e as ms,A as rt,D as ca,f as nt,P as Dt,g as Ns,E as Mt,T as da,h as xa,i as Te,Q as Ps,j as ns,k as Ge,l as ds,m as it,R as qe,n as Ot,o as ma,p as Je,X as we,K as ua,q as rs,r as es,s as Ke,t as Qe,u as ot,v as qt,w as us,x as pa,y as ha,z as js,F as ga,G as ba,H as ct,I as dt,J as fa,M as ya,N as ja,O as Na,V as Ts,W as _s,Y as Bt,_ as va,$ as _a,a0 as Ws,a1 as wa,a2 as ka,a3 as Vs,a4 as xt,a5 as Ca,a6 as Ls,a7 as zt,a8 as Sa,a9 as La,aa as Zs,ab as Ut,ac as Aa,ad as Ia}from"./icons-vendor-RenKjhri.js";import{R as ws,B as $a,X as mt,Y as ut,T as Es,a as Ra,C as Fs,A as Pa,b as Ta,c as Ea,P as pt,d as ht,L as Fa}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 h of document.querySelectorAll('link[rel="modulepreload"]'))c(h);new MutationObserver(h=>{for(const f of h)if(f.type==="childList")for(const L of f.addedNodes)L.tagName==="LINK"&&L.rel==="modulepreload"&&c(L)}).observe(document,{childList:!0,subtree:!0});function l(h){const f={};return h.integrity&&(f.integrity=h.integrity),h.referrerPolicy&&(f.referrerPolicy=h.referrerPolicy),h.crossOrigin==="use-credentials"?f.credentials="include":h.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function c(h){if(h.ep)return;h.ep=!0;const f=l(h);fetch(h.href,f)}})();const Da=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),Gs=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(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:ve,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:z,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",disabled:z,children:[z?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),z?"保存中...":"保存"]})]})})]})}),document.body)]})},xr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),mr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],wt=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},ur=()=>{const[s,t]=n.useState([]),[l,c]=n.useState([]),[h,f]=n.useState([]),[L,F]=n.useState({}),[g,I]=n.useState("all"),[j,G]=n.useState(""),[Y,X]=n.useState(""),[de,C]=n.useState(""),M=n.useRef(0),[oe,ee]=n.useState(1),[xe,O]=n.useState(1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState(!1),[ue,Q]=n.useState(!1),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState({}),[H,m]=n.useState(!1),[p,y]=n.useState(""),[S,U]=n.useState(!1),[se,z]=n.useState(null),[re,E]=n.useState(null),[i,q]=n.useState(null),[d,_]=n.useState(!1),[te,Z]=n.useState(null),[pe,Ne]=n.useState(null),ce=async()=>{const x=++M.current;D(!0);try{const P=await cl(j||void 0,g,oe,20,de);if(x!==M.current)return;t(P.data),O(P.total_pages)}catch(P){console.error("加载订单失败:",P)}finally{x===M.current&&D(!1)}},_e=(x,P,me)=>{if(me&&me.trim())return me;if(L[`${x}:${P}`])return L[`${x}:${P}`];const fe=l.find(ze=>{if(me&&ze.item_title){const r=me.toLowerCase(),a=ze.item_title.toLowerCase();return a.includes(r)||r.includes(a)}return!1});return fe!=null&&fe.item_title?fe.item_title:"未知商品"},Re=x=>{const P={};x.forEach(me=>{me.item_id&&(P[`${me.cookie_id}:${me.item_id}`]=me.item_title||me.item_id)}),F(P)};n.useEffect(()=>{const x=window.setTimeout(()=>{ee(1),C(Y.trim())},300);return()=>window.clearTimeout(x)},[Y]),n.useEffect(()=>{ce()},[j,g,oe,de]),n.useEffect(()=>{Promise.all([Rs(),ps()]).then(([x,P])=>{f(x),c(P),Re(P)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const ye=n.useMemo(()=>new Map(h.map(x=>[x.id,x])),[h]),Ae=x=>{const P=ye.get(x),me=(P==null?void 0:P.remark)||(P==null?void 0:P.nickname);return me?`${me} · ${x.slice(0,6)}`:`账号 ${x.slice(0,8)}`},Le=x=>{const P=ye.get(x);return(P==null?void 0:P.remark)||(P==null?void 0:P.nickname)||"未命名账号"},Be=async()=>{D(!0);try{const x=await ml(j||void 0,g);await ce(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{D(!1)}},Ie=x=>{y(x),z(null),m(!0)},Me=async x=>{var P;U(!0),z(null);try{const me=await pl([p],x),fe=(P=me==null?void 0:me.results)==null?void 0:P[0];fe!=null&&fe.success?(z({success:!0,message:fe.message}),ce()):z({success:!1,message:(fe==null?void 0:fe.message)||"发货失败"})}catch(me){z({success:!1,message:(me==null?void 0:me.message)||"请求失败"})}finally{U(!1)}},We=x=>{b(x),$(!0)},Ye=x=>{B({...x}),J(!0)},$e=async()=>{if(!(!v||!v.order_id))try{const x={};v.status!==void 0&&(x.order_status=v.status),v.buyer_id!==void 0&&(x.buyer_id=v.buyer_id),v.amount!==void 0&&(x.amount=v.amount),v.receiver_name!==void 0&&(x.receiver_name=v.receiver_name),v.receiver_phone!==void 0&&(x
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(pe=>pe.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),_=new Blob(["\uFEFF"+d],{type:"text/csv;charset=utf-8"}),te=URL.createObjectURL(_),Z=document.createElement("a");Z.href=te,Z.download="卡密组批量导入模板.csv",document.body.appendChild(Z),Z.click(),Z.remove(),URL.revokeObjectURL(te)},z=async()=>{if(M){le(!0),xe(null);try{const i=await Nl(M);if(xe(i),i.created>0){const q=await Ve();t(q)}}catch(i){xe({error:(i==null?void 0:i.message)||"上传失败"})}finally{le(!1)}}},re=async()=>{if(!(!D||!$.trim())){le(!0),ue(null);try{const i=await vl(D,$);ue({added:i.added}),T("");const q=await Ve();t(q)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{le(!1)}}},E=()=>{var i;C("create"),oe(null),xe(null),N((i=S[0])!=null&&i.id?String(S[0].id):""),T(""),ue(null),X(!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:E,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(js,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>f(!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(Qe,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ga,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:Q,onChange:i=>A(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(qt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:b,onChange:i=>v(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",U.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:U.map(i=>{let q="";return i.type==="data"&&i.data_content?q=`库存: ${i.data_content.split(`
|
||||
`).filter(_=>_.trim()).length} 条`:i.type==="text"&&i.text_content?q=i.text_content:i.type==="api"&&i.api_config?q=i.api_config.url:i.type==="image"&&i.image_url&&(q="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(B,{type:i.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:i.name,children:i.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>y(i.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:i.id}),e.jsx(ba,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:q,children:q})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>p(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>R(i),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>H(i.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},i.id)})})]})}),U.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Dt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&L&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>c(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:i=>I({...g,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:i=>I({...g,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(L==null?void 0:L.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:i=>I({...g,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("Line truncated
|
||||
卡号1:密码1
|
||||
卡号2:密码2
|
||||
或者
|
||||
兑换码1
|
||||
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
|
||||
`).filter(i=>i.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:i=>I({...g,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:i=>I({...g,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:i=>I({...g,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>I({...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:()=>c(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:K,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),h&&Se.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:()=>f(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:i=>G({...j,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(zs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ct,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-Line truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:j.content.split(`
|
||||
`).filter(i=>i.trim()).length})," 条"]})]}),j.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:j.api_method,onChange:i=>G({...j,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:j.api_timeout,onChange:i=>G({...j,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:j.api_headers,onChange:i=>G({...j,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:j.api_params,onChange:i=>G({...j,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:j.description,onChange:i=>G({...j,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:j.delay_seconds,onChange:i=>G({...j,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:()=>f(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Y&&Se.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:()=>X(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>C("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 ${de==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(fa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>C("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 ${de==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(js,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),de==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:se,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 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:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),J&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",J.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:()=>X(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),de==="create"?e.jsxs("button",{onClick:z,disabled:!M||O,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(js,{className:"w-4 h-4"}),O?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:re,disabled:!D||!$.trim()||O||S.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Qe,{className:"w-4 h-4"}),O?"处理中...":"追加卡密"]})]})]})}),document.body)]})},gr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),br=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},fr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[c,h]=n.useState([]),[f,L]=n.useState([]),[F,g]=n.useState(""),[I,j]=n.useState(""),[G,Y]=n.useState(!1),[X,de]=n.useState(!1),[C,M]=n.useState(!1),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState("upload"),[ue,Q]=n.useState(null),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState(null),[H,m]=n.useState(null),p=n.useRef(!1),[y,S]=n.useState(null),[U,se]=n.useState({}),[z,re]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[E,i]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[q,d]=n.useState([]);n.useEffect(()=>{if(!le||E.images.length===0){d([]);return}const r=E.images.map((a,u)=>({key:a.name+u,url:URL.createObjectURL(a)}));return d(r),()=>{r.forEach(a=>URL.revokeObjectURL(a.url))}},[le,E.images]);const _=async()=>{const r=await ps();l(r)},te=async()=>{h(await Is())};n.useEffect(()=>{Promise.all([Rs(),ps(),Is(),yt(20)]).then(([r,a,u,w])=>{L(r),l(a),h(u);const W=w.find(ae=>["running","canceling"].includes(ae.status))||w.find(ae=>ae.status!=="preview");m(W||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!N||!(R!=null&&R.id)||!["running","canceling"].includes(R.status))return;const r=window.setInterval(async()=>{if(!p.current){p.current=!0;try{const a=await os(R.id);K(a),m(a),["running","canceling"].includes(a.status)||(J("done"),await _(),await te())}catch(a){console.error("刷新批量铺货进度失败:",a)}finally{p.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[N,R==null?void 0:R.id,R==null?void 0:R.status]);const Z=async()=>{if(!F)return alert("请先选择账号");Y(!0);try{const r=await _l(F);await _(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{Y(!1)}},pe=r=>{S(r),se({...r}),ee(!0)},Ne=async()=>{if(y)try{await Rl(y.cookie_id,y.item_id,{item_title:U.item_title||"",item_description:U.item_description||"",item_category:U.item_category||"",item_price:U.item_price||"",item_detail:U.item_detail||y.item_detail||""}),await _(),await te(),ee(!1),S(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ce=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await wl(r.cookie_id,r.item_id),l(a=>a.filter(u=>!(u.cookie_id===r.cookie_id&&u.item_id===r.item_id)))}catch(a){console.error("删除商品失败:",a),alert("删除失败,请重试")}},_e=async()=>{try{if(!z.cookie_id||!z.item_id){alert("请选择账号并填写商品ID");return}await kl(z.cookie_id,{item_id:z.item_id,item_title:z.item_title,item_price:z.item_price,item_detail:z.item_image?JSON.stringify({item_image:z.item_image}):""}),await _(),O(!1),re({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},Re=async()=>{if(!E.cookie_id)return alert("请选择发布账号");if(!E.title.trim())return alert("请填写商品标题");if(!E.price.trim())return alert("请填写商品价格");if(!E.quantity||Number(E.quantity)<=0)return alert("库存数量必须大于 0");if(E.images.length===0)return alert("至少上传 1 张商品图片");if(E.postage_mode==="fixed"&&!E.postage.trim())return alert("请填写一口价邮费");de(!0);try{const r=await Cl(E);if(await _(),D(!1),i({cookie_id:F||"",title:"
Line truncated
|
||||
`),w=new Blob(["\uFEFF"+u],{type:"text/csv;charset=utf-8"}),W=URL.createObjectURL(w),ae=document.createElement("a");ae.href=W,ae.download="批量铺货模板.csv",document.body.appendChild(ae),ae.click(),ae.remove(),URL.revokeObjectURL(W)},ss=()=>{re(r=>({...r,cookie_id:F||r.cookie_id})),O(!0)},Ze=()=>{i(r=>({...r,cookie_id:F||r.cookie_id})),D(!0)},Xe=r=>c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id).length>0?c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id):c.filter(a=>a.cookie_id===r.cookie_id&&!a.item_id),He=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},x=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"}},P=n.useMemo(()=>new Map(f.map(r=>[r.id,r])),[f]),me=n.useMemo(()=>I?t.filter(r=>r.cookie_id===I):t,[I,t]),fe=r=>{const a=P.get(r),u=(a==null?void 0:a.remark)||(a==null?void 0:a.nickname);return u?`${u} · ${r.slice(0,6)}`:`账号 ${r.slice(0,8)}`},ze=r=>{const a=P.get(r);return(a==null?void 0:a.remark)||(a==null?void 0:a.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Na,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:r=>j(r.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:r=>g(r.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("button",{onClick:Z,disabled:G||!F,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${G?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ss,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(Qe,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ze,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(Ts,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void ye(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(_s,{className:"w-4 h-4"}),H&&["running","canceling"].includes(H.status)?"继续批量任务":"批量铺货"]}),H&&!["running","canceling"].includes(H.status)&&e.jsx("button",{onClick:()=>void Ae(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[me.map(r=>{const a=Xe(r),u=a.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-
Line truncated
|
||||
@@ -0,0 +1,19 @@
|
||||
import{j as e,r as i,b as Le,c as ba,d as ya}from"./react-vendor-DZnRGM0-.js";import{L as fa,U as Wt,S as Vt,C as Zs,B as Gt,Z as Xs,a as ys,b as it,c as Jt,d as ja,e as cs,A as gt,D as Na,f as bt,P as Kt,g as Ls,E as Qt,T as va,h as wa,i as $e,Q as Us,j as ds,k as ss,l as bs,m as yt,R as Oe,n as Yt,o as _a,p as Je,X as ve,K as ka,q as os,r as rs,s as as,t as ts,u as ft,v as As,w as fs,x as Zt,y as Xt,z as Ss,F as Ht,G as Ca,H as jt,I as Nt,J as Sa,M as La,N as Aa,O as Ia,V as Ws,W as $s,Y as Hs,_ as $a,$ as Ra,a0 as et,a1 as Pa,a2 as Da,a3 as st,a4 as vt,a5 as Fa,a6 as Es,a7 as ea,a8 as Ta,a9 as Ea,aa as ot,ab as sa,ac as Ma,ad as Oa}from"./icons-vendor-RenKjhri.js";import{R as Rs,B as qa,X as wt,Y as _t,T as Vs,a as Ba,C as Gs,A as za,b as Ua,c as Wa,P as kt,d as Ct,L as Va}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const x of document.querySelectorAll('link[rel="modulepreload"]'))d(x);new MutationObserver(x=>{for(const w of x)if(w.type==="childList")for(const S of w.addedNodes)S.tagName==="LINK"&&S.rel==="modulepreload"&&d(S)}).observe(document,{childList:!0,subtree:!0});function r(x){const w={};return x.integrity&&(w.integrity=x.integrity),x.referrerPolicy&&(w.referrerPolicy=x.referrerPolicy),x.crossOrigin==="use-credentials"?w.credentials="include":x.crossOrigin==="anonymous"?w.credentials="omit":w.credentials="same-origin",w}function d(x){if(x.ep)return;x.ep=!0;const w=r(x);fetch(x.href,w)}})();const Ga=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),tt=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88Line truncated
|
||||
|
||||
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:us,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:y,children:"取消"}),e.jsxs("button",{onClick:Z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:y,children:[y?e.jsx($e,{className:"w-4 h-4 animate-spin"}):e.jsx(as,{className:"w-4 h-4"}),y?"保存中...":"保存"]})]})})]})}),document.body)]})},vr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),wr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],Ft=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},r={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:r[s]||s})},_r=()=>{const[s,t]=i.useState([]),[r,d]=i.useState([]),[x,w]=i.useState([]),[S,F]=i.useState({}),[g,R]=i.useState("all"),[b,G]=i.useState(""),[se,re]=i.useState(""),[ie,k]=i.useState(""),B=i.useRef(0),[ne,J]=i.useState(1),[Y,z]=i.useState(1),[xe,oe]=i.useState(!1),[_,T]=i.useState(!1),[U,V]=i.useState(!1),[me,L]=i.useState(!1),[A,K]=i.useState(null),[I,ae]=i.useState(null),[we,Ce]=i.useState({}),[ue,m]=i.useState(!1),[h,q]=i.useState(""),[j,te]=i.useState(!1),[le,H]=i.useState(null),[je,P]=i.useState(null),[o,D]=i.useState(null),[n,y]=i.useState(!1),[E,C]=i.useState(null),[M,he]=i.useState(null),X=async()=>{const u=++B.current;oe(!0);try{const $=await yl(b||void 0,g,ne,20,ie);if(u!==B.current)return;t($.data),z($.total_pages)}catch($){console.error("加载订单失败:",$)}finally{u===B.current&&oe(!1)}},ee=(u,$,ce)=>{if(ce&&ce.trim())return ce;if(S[`${u}:${$}`])return S[`${u}:${$}`];const _e=r.find(Ye=>{if(ce&&Ye.item_title){const Ze=ce.toLowerCase(),Xe=Ye.item_title.toLowerCase();return Xe.includes(Ze)||Ze.includes(Xe)}return!1});return _e!=null&&_e.item_title?_e.item_title:"未知商品"},Se=u=>{const $={};u.forEach(ce=>{ce.item_id&&($[`${ce.cookie_id}:${ce.item_id}`]=ce.item_title||ce.item_id)}),F($)};i.useEffect(()=>{const u=window.setTimeout(()=>{J(1),k(se.trim())},300);return()=>window.clearTimeout(u)},[se]),i.useEffect(()=>{X()},[b,g,ne,ie]),i.useEffect(()=>{Promise.all([qs(),js()]).then(([u,$])=>{w(u),d($),Se($)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const Ne=i.useMemo(()=>new Map(x.map(u=>[u.id,u])),[x]),We=u=>{const $=Ne.get(u),ce=($==null?void 0:$.remark)||($==null?void 0:$.nickname);return ce?`${ce} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},Ie=u=>{const $=Ne.get(u);return($==null?void 0:$.remark)||($==null?void 0:$.nickname)||"未命名账号"},Fe=async()=>{oe(!0);try{const u=await Nl(b||void 0,g);await X(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{oe(!1)}},qe=u=>{q(u),H(null),m(!0)},Te=async u=>{var $;te(!0),H(null);try{const ce=await wl([h],u),_e=($=ce==null?void 0:ce.results)==null?void 0:$[0];_e!=null&&_e.success?(H({success:!0,message:_e.message}),X()):H({success:!1,message:(_e==null?void 0:_e.message)||"发货失败"})}catch(ce){H({success:!1,message:(ce==null?void 0:ce.message)||"请求失败"})}finally{te(!1)}},Ve=u=>{K(u),T(!0)},Ee=u=>{ae({...u}),V(!0)},Re=async()=>{if(!(!I||!I.order_id))try{const u={};I.status!==void 0&&(u.order_status=I.status),I.buyer_id!==void 0&&(u.buyer_id=I.buyer_id),I.amount!==void 0&&(u.amount=I.amount),I.receiver_name!==void 0&&(u.receiver_name=I.receiver_name),I.receiver_phon
Line truncated
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(M=>M.map(he=>`"${String(he).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),y=new Blob(["\uFEFF"+n],{type:"text/csv;charset=utf-8"}),E=URL.createObjectURL(y),C=document.createElement("a");C.href=E,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(E)},H=async()=>{if(B){xe(!0),Y(null);try{const o=await Il(B);if(Y(o),o.created>0){const D=await es();t(D)}}catch(o){Y({error:(o==null?void 0:o.message)||"上传失败"})}finally{xe(!1)}}},je=async()=>{if(!(!oe||!T.trim())){xe(!0),me(null);try{const o=await $l(oe,T);me({added:o.added}),U("");const D=await es();t(D)}catch(o){alert("追加失败:"+((o==null?void 0:o.message)||"未知错误"))}finally{xe(!1)}}},P=()=>{var o;k("create"),ne(null),Y(null),_((o=j[0])!=null&&o.id?String(j[0].id):""),U(""),me(null),re(!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:P,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Ss,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>w(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(ts,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Ht,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:L,onChange:o=>A(o.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(As,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:K,onChange:o=>I(o.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",te.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:te.map(o=>{let D="";return o.type==="data"&&o.data_content?D=`库存: ${o.data_content.split(`
|
||||
`).filter(y=>y.trim()).length} 条`:o.type==="text"&&o.text_content?D=o.text_content:o.type==="api"&&o.api_config?D=o.api_config.url:o.type==="image"&&o.image_url&&(D="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ae,{type:o.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:o.name,children:o.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>q(o.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:o.id}),e.jsx(Ca,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${o.type==="text"?"bg-blue-50 text-blue-600":o.type==="data"?"bg-purple-50 text-purple-600":o.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:o.type==="text"?"文本":o.type==="data"?"批量":o.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:D,children:D})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:o.description||"-",children:o.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>h(o),className:`w-12 h-8 rounded-full relative transition-colors ${o.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 ${o.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>we(o),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(fs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ue(o.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},o.id)})})]})}),te.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Kt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),r&&S&&Le.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>d(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ve,{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:o=>R({...g,name:o.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:o=>R({...g,type:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(S==null?void 0:S.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),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:o=>R({...g,api_url:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine 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(o=>o.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:o=>R({...g,image_url:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),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:o=>{o.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:o=>R({...g,delay_seconds:parseInt(o.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:o=>R({...g,description:o.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:()=>R({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>d(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(as,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),x&&Le.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>w(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ve,{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:o=>G({...b,name:o.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>G({...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(Zs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>G({...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(jt,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>G({...b,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${b.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-grayLine 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(o=>o.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:o=>G({...b,api_method:o.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:o=>G({...b,api_timeout:parseInt(o.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:o=>G({...b,api_headers:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),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:o=>G({...b,api_params:o.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),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:o=>G({...b,description:o.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:o=>G({...b,delay_seconds:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>w(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),se&&Le.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>re(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(ve,{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:()=>k("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ie==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Sa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>k("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${ie==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Ss,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),ie==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:le,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 tex
Line truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),V&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",V.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>re(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),ie==="create"?e.jsxs("button",{onClick:H,disabled:!B||z,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[z?e.jsx($e,{className:"w-4 h-4 animate-spin"}):e.jsx(Ss,{className:"w-4 h-4"}),z?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:je,disabled:!oe||!T.trim()||z||j.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[z?e.jsx($e,{className:"w-4 h-4 animate-spin"}):e.jsx(ts,{className:"w-4 h-4"}),z?"处理中...":"追加卡密"]})]})]})}),document.body)]})},Sr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),Lr=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},Ar=({onConfigureDelivery:s})=>{const[t,r]=i.useState([]),[d,x]=i.useState([]),[w,S]=i.useState([]),[F,g]=i.useState(""),[R,b]=i.useState(""),[G,se]=i.useState(!1),[re,ie]=i.useState(!1),[k,B]=i.useState(!1),[ne,J]=i.useState(!1),[Y,z]=i.useState(!1),[xe,oe]=i.useState(!1),[_,T]=i.useState(!1),[U,V]=i.useState("upload"),[me,L]=i.useState(null),[A,K]=i.useState(null),[I,ae]=i.useState(""),[we,Ce]=i.useState(!1),[ue,m]=i.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[h,q]=i.useState(null),[j,te]=i.useState(null),[le,H]=i.useState(null),je=i.useRef(!1),[P,o]=i.useState(null),[D,n]=i.useState({}),[y,E]=i.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[C,M]=i.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[he,X]=i.useState([]);i.useEffect(()=>{if(!xe||C.images.length===0){X([]);return}const l=C.images.map((N,Z)=>({key:N.name+Z,url:URL.createObjectURL(N)}));return X(l),()=>{l.forEach(N=>URL.revokeObjectURL(N.url))}},[xe,C.images]);const ee=async()=>{const l=await js();r(l)},Se=async()=>{x(await lt())};i.useEffect(()=>{Promise.all([qs(),js(),lt(),It(20)]).then(([l,N,Z,Ue])=>{S(l),r(N),x(Z);const Ge=Ue.find(Pe=>["running","canceling"].includes(Pe.status))||Ue.find(Pe=>Pe.status!=="preview");H(Ge||null)}).catch(l=>console.error("加载商品配置失败:",l))},[]),i.useEffect(()=>{if(!_||!(j!=null&&j.id)||!["running","canceling"].includes(j.status))return;const l=window.setInterval(async()=>{if(!je.current){je.current=!0;try{const N=await hs(j.id);te(N),H(N),["running","canceling"].includes(N.status)||(V("done"),await ee(),await Se())}catch(N){console.error("刷新批量铺货进度失败:",N)}finally{je.current=!1}}},3e3);return()=>{window.clearInterval(l)}},[_,j==null?void 0:j.id,j==null?void 0:j.status]);const Ne=async()=>{if(!F)return alert("请先选择账号");se(!0);try{const l=await Rl(F);await ee(),alert((l==null?void 0:l.message)||"商品同步完成")}catch(l){console.error("同步商品失败:",l),alert((l==null?void 0:l.message)||"同步失败,请重试")}finally{se(!1)}},We=l=>{o(l),n({...l}),J(!0)},Ie=async()=>{if(P)try{await zl(P.cookie_id,P.item_id,{item_title:D.item_title||"",item_description:D.item_description||"",item_category:D.item_category||"",item_price:D.item_price||"",item_detail:D.item_detail||P.item_detail||""}),await ee(),await Se(),J(!1),o(null)}catch(l){console.error("更新商品失败:",l),alert("更新失败,请重试")}},Fe=async l=>{if(confirm(`确认删除商品"${l.item_title}"吗?`))try{await Pl(l.cookie_id,l.item_id),r(N=>N.filter(Z=>!(Z.cookie_id===l.cookie_id&&Z.item_id===l.item_id)))}catch(N){console.error("删除商品失败:",N),alert("删除失败,请重试")}},qe=async()=>{try{if(!y.cookie_id||!y.item_id){alert("请选择账号并填写商品ID");return}await Dl(y.cookie_id,{item_id:y.item_id,item_title:y.item_title,item_price:y.item_price,item_detail:y.item_image?JSON.stringify({item_image:y.item_image}):""}),await ee(),z(!1),E({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(l){console.error("添加商品失败:",l),alert("添加失败,请重试")}},Te=async()=>{if(!C.cookie_id)return alert("请选择发布账号");if(!C.title.trim())return alert("请填写商品标题");if(!C.price.trim())return alert("请填写商品价格");if(!C.quantity||Number(C.quantity)<=0)return alert("库存数量必须大于 0");if(C.images.length===0)return alert("至少上传 1 张商品图片");if(C.postage_mode==="fixed"&&!C.p
Line truncated
|
||||
`),Ue=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),Ge=URL.createObjectURL(Ue),Pe=document.createElement("a");Pe.href=Ge,Pe.download="批量铺货模板.csv",document.body.appendChild(Pe),Pe.click(),Pe.remove(),URL.revokeObjectURL(Ge)},_e=()=>{E(l=>({...l,cookie_id:F||l.cookie_id})),z(!0)},Ye=()=>{M(l=>({...l,cookie_id:F||l.cookie_id})),oe(!0)},Ze=l=>d.filter(N=>N.cookie_id===l.cookie_id&&N.item_id===l.item_id).length>0?d.filter(N=>N.cookie_id===l.cookie_id&&N.item_id===l.item_id):d.filter(N=>N.cookie_id===l.cookie_id&&!N.item_id),Xe=l=>{switch(l){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return l||"-"}},Be=l=>{switch(l){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},ze=i.useMemo(()=>new Map(w.map(l=>[l.id,l])),[w]),xs=i.useMemo(()=>R?t.filter(l=>l.cookie_id===R):t,[R,t]),He=l=>{const N=ze.get(l),Z=(N==null?void 0:N.remark)||(N==null?void 0:N.nickname);return Z?`${Z} · ${l.slice(0,6)}`:`账号 ${l.slice(0,8)}`},ms=l=>{const N=ze.get(l);return(N==null?void 0:N.remark)||(N==null?void 0:N.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ia,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:l=>b(l.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),w.map(l=>e.jsx("option",{value:l.id,children:He(l.id)},l.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ds,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:l=>g(l.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),w.map(l=>e.jsx("option",{value:l.id,children:He(l.id)},l.id))]})]})]}),e.jsxs("button",{onClick:Ne,disabled:G||!F,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(Oe,{className:`w-4 h-4 ${G?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:_e,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(ts,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ye,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Ws,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Ve(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx($s,{className:"w-4 h-4"}),le&&["running","canceling"].includes(le.status)?"继续批量任务":"批量铺货"]}),le&&!["running","canceling"].includes(le.status)&&e.jsx("button",{onClick:()=>void Re(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[xs.map(l=>{const N=Ze(l),Z=N.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relat
Line truncated
|
||||
@@ -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}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-1{top:-.25rem;right:-.25rem;bottom:-.25remLine truncated
|
||||
@@ -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-DWScSBc3.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-av934L0W.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-RenKjhri.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/vendor-w5t2K9ux.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-B_BfwiL0.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-hVsGsb1z.css">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-C7AaUlyC.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
+186
-29
@@ -30,6 +30,10 @@ const (
|
||||
DefaultLocationAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.local.poi.get/1.0/"
|
||||
)
|
||||
|
||||
// ErrPublishCategoryUnrecognized 表示闲鱼类目推荐接口调用成功,但没有给出可发布类目。
|
||||
// 这是发生在最终发布接口之前的确定性结果,调用方可以安全地改用人工指定类目。
|
||||
var ErrPublishCategoryUnrecognized = errors.New("未能自动识别商品类目,请调整标题或图片后重试")
|
||||
|
||||
type PublishErrorCode string
|
||||
|
||||
const (
|
||||
@@ -60,6 +64,25 @@ type PublishImage struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// PublishCategory 是发布商品时可使用的人工兜底类目。
|
||||
// CatID、CatName 和 ChannelCatID 必填;部分闲鱼类目没有 TBCatID。
|
||||
type PublishCategory struct {
|
||||
CatID string `json:"cat_id"`
|
||||
CatName string `json:"cat_name"`
|
||||
ChannelCatID string `json:"channel_cat_id,omitempty"`
|
||||
TBCatID string `json:"tb_cat_id,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultVirtualPublishCategory 是从闲鱼类目推荐响应中核实的“电子资料”类目。
|
||||
// 该类目没有 tbCatId,发布时必须保留为空而不是伪造淘宝类目 ID。
|
||||
func DefaultVirtualPublishCategory() PublishCategory {
|
||||
return PublishCategory{
|
||||
CatID: "50023914",
|
||||
CatName: "电子资料",
|
||||
ChannelCatID: "202036301",
|
||||
}
|
||||
}
|
||||
|
||||
type PublishItemRequest struct {
|
||||
Title string
|
||||
Description string
|
||||
@@ -68,7 +91,10 @@ type PublishItemRequest struct {
|
||||
Quantity int
|
||||
PostageMode string
|
||||
PostageCents int64
|
||||
Images []PublishImage
|
||||
// Virtual 表示商品只通过系统的虚拟发货流程交付,不需要实物发货地址。
|
||||
Virtual bool
|
||||
PreferredCategory *PublishCategory
|
||||
Images []PublishImage
|
||||
}
|
||||
|
||||
type PublishItemResult struct {
|
||||
@@ -109,6 +135,9 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
|
||||
if len(req.Images) > 9 {
|
||||
return nil, errors.New("商品图片最多 9 张")
|
||||
}
|
||||
if req.PreferredCategory != nil && !validPublishCategory(*req.PreferredCategory) {
|
||||
return nil, errors.New("默认类目必须同时包含类目 ID、类目名称和频道类目 ID")
|
||||
}
|
||||
currentCookies := cookiesStr
|
||||
if session := cookieSessionFromContext(ctx); session != nil {
|
||||
currentCookies, _, _ = session.State()
|
||||
@@ -124,23 +153,60 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
|
||||
}
|
||||
uploaded = append(uploaded, res)
|
||||
}
|
||||
category, updated, err := c.recommendPublishCategory(ctx, currentCookies, req.Title, req.Description, uploaded)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
var category map[string]any
|
||||
var updated string
|
||||
var err error
|
||||
if req.PreferredCategory != nil {
|
||||
category = fallbackPublishCategory(*req.PreferredCategory)
|
||||
} else {
|
||||
category, updated, err = c.recommendPublishCategory(ctx, currentCookies, req.Title, req.Description, uploaded)
|
||||
if updated != "" {
|
||||
currentCookies = updated
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrPublishCategoryUnrecognized) {
|
||||
category = fallbackPublishCategory(DefaultVirtualPublishCategory())
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if updated != "" {
|
||||
currentCookies = updated
|
||||
}
|
||||
location, updated, err := c.defaultPublishLocation(ctx, currentCookies)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if updated != "" {
|
||||
currentCookies = updated
|
||||
var location map[string]any
|
||||
if !req.Virtual {
|
||||
location, updated, err = c.defaultPublishLocation(ctx, currentCookies)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if updated != "" {
|
||||
currentCookies = updated
|
||||
}
|
||||
}
|
||||
return c.publishItemOnce(ctx, currentCookies, req, uploaded, category, location)
|
||||
}
|
||||
|
||||
// RecommendPublishCategory 根据关键词调用闲鱼推荐接口,返回可直接用于发布的完整类目。
|
||||
func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, keyword string) (PublishCategory, string, error) {
|
||||
keyword = strings.TrimSpace(keyword)
|
||||
if keyword == "" {
|
||||
return PublishCategory{}, cookiesStr, errors.New("类目关键词不能为空")
|
||||
}
|
||||
data, updated, err := c.recommendPublishCategory(ctx, cookiesStr, keyword, keyword, nil)
|
||||
if err != nil {
|
||||
return PublishCategory{}, updated, err
|
||||
}
|
||||
cat := mapFromAny(data["categoryPredictResult"])
|
||||
category := PublishCategory{
|
||||
CatID: strings.TrimSpace(mtopString(cat["catId"])),
|
||||
CatName: strings.TrimSpace(mtopString(cat["catName"])),
|
||||
ChannelCatID: strings.TrimSpace(mtopString(cat["channelCatId"])),
|
||||
TBCatID: strings.TrimSpace(mtopString(cat["tbCatId"])),
|
||||
}
|
||||
if !validPublishCategory(category) {
|
||||
return PublishCategory{}, updated, fmt.Errorf("%w: 推荐结果缺少完整类目路径", ErrPublishCategoryUnrecognized)
|
||||
}
|
||||
return category, updated, nil
|
||||
}
|
||||
|
||||
func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string, img PublishImage) (uploadedImage, string, error) {
|
||||
hc := c.HTTPClient
|
||||
if hc == nil {
|
||||
@@ -236,9 +302,11 @@ func (c *ClientImpl) recommendPublishCategory(ctx context.Context, cookiesStr, t
|
||||
"publishScene": "mainPublish",
|
||||
"scene": "newPublishChoice",
|
||||
"description": desc,
|
||||
"imageInfos": imageInfos,
|
||||
"uniqueCode": strconv.FormatInt(time.Now().UnixMicro(), 10),
|
||||
}
|
||||
if len(imageInfos) > 0 {
|
||||
data["imageInfos"] = imageInfos
|
||||
}
|
||||
decoded, updated, err := c.callMTop(ctx, cookiesStr, RecommendItemAPI, "mtop.taobao.idle.kgraph.property.recommend", "2.0", "a21ybx.publish.0.0", "a21ybx.item.sidebar.1.67321598K9Vgx8", "67321598K9Vgx8", data)
|
||||
if err != nil {
|
||||
return nil, updated, err
|
||||
@@ -248,15 +316,91 @@ func (c *ClientImpl) recommendPublishCategory(ctx context.Context, cookiesStr, t
|
||||
}
|
||||
dataMap := mapFromAny(decoded["data"])
|
||||
if dataMap == nil {
|
||||
return nil, updated, fmt.Errorf("类目推荐响应缺少 data")
|
||||
return nil, updated, fmt.Errorf("%w: 类目推荐响应缺少 data", ErrPublishCategoryUnrecognized)
|
||||
}
|
||||
cat := mapFromAny(dataMap["categoryPredictResult"])
|
||||
if cat == nil || mtopString(cat["catId"]) == "" {
|
||||
return nil, updated, fmt.Errorf("未能自动识别商品类目,请调整标题或图片后重试")
|
||||
if !validPublishCategoryMap(cat) {
|
||||
// 部分账号/场景仅在 cardList 的“分类”卡片返回已选中的类目,
|
||||
// 不返回 categoryPredictResult。将其转换为统一的发布类目结构。
|
||||
if selected := selectedCategoryFromCards(dataMap); selected != nil {
|
||||
cat = selected
|
||||
dataMap["categoryPredictResult"] = selected
|
||||
}
|
||||
}
|
||||
if !validPublishCategoryMap(cat) {
|
||||
return nil, updated, ErrPublishCategoryUnrecognized
|
||||
}
|
||||
return dataMap, updated, nil
|
||||
}
|
||||
|
||||
func validPublishCategoryMap(category map[string]any) bool {
|
||||
return category != nil &&
|
||||
strings.TrimSpace(mtopString(category["catId"])) != "" &&
|
||||
strings.TrimSpace(mtopString(category["catName"])) != "" &&
|
||||
strings.TrimSpace(mtopString(category["channelCatId"])) != ""
|
||||
}
|
||||
|
||||
func selectedCategoryFromCards(data map[string]any) map[string]any {
|
||||
cards, _ := data["cardList"].([]any)
|
||||
for _, rawCard := range cards {
|
||||
cardData := mapFromAny(mapFromAny(rawCard)["cardData"])
|
||||
if cardData == nil || mtopString(cardData["propertyId"]) != "-10000" {
|
||||
continue
|
||||
}
|
||||
values, _ := cardData["valuesList"].([]any)
|
||||
for _, rawValue := range values {
|
||||
value := mapFromAny(rawValue)
|
||||
if value == nil || !publishLabelSelected(value["isClicked"]) || mtopString(value["catId"]) == "" {
|
||||
continue
|
||||
}
|
||||
return map[string]any{
|
||||
"catId": mtopString(value["catId"]),
|
||||
"catName": mtopString(value["catName"]),
|
||||
"channelCatId": mtopString(value["channelCatId"]),
|
||||
"tbCatId": mtopString(value["tbCatId"]),
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validPublishCategory(category PublishCategory) bool {
|
||||
return strings.TrimSpace(category.CatID) != "" &&
|
||||
strings.TrimSpace(category.CatName) != "" &&
|
||||
strings.TrimSpace(category.ChannelCatID) != ""
|
||||
}
|
||||
|
||||
func fallbackPublishCategory(category PublishCategory) map[string]any {
|
||||
category = PublishCategory{
|
||||
CatID: strings.TrimSpace(category.CatID),
|
||||
CatName: strings.TrimSpace(category.CatName),
|
||||
ChannelCatID: strings.TrimSpace(category.ChannelCatID),
|
||||
TBCatID: strings.TrimSpace(category.TBCatID),
|
||||
}
|
||||
return map[string]any{
|
||||
"categoryPredictResult": map[string]any{
|
||||
"catId": category.CatID,
|
||||
"catName": category.CatName,
|
||||
"channelCatId": category.ChannelCatID,
|
||||
"tbCatId": category.TBCatID,
|
||||
},
|
||||
// 闲鱼将分类作为已选择的标签一并提交;仅传 itemCatDTO 会导致
|
||||
// 部分频道类目无法还原完整路径。
|
||||
"cardList": []any{map[string]any{
|
||||
"cardData": map[string]any{
|
||||
"propertyId": "-10000",
|
||||
"propertyName": "分类",
|
||||
"valuesList": []any{map[string]any{
|
||||
"catName": category.CatName,
|
||||
"channelCatId": category.ChannelCatID,
|
||||
"tbCatId": category.TBCatID,
|
||||
"isClicked": true,
|
||||
}},
|
||||
},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ClientImpl) defaultPublishLocation(ctx context.Context, cookiesStr string) (map[string]any, string, error) {
|
||||
data := map[string]any{"longitude": 118.78248347393424, "latitude": 31.91629189813543}
|
||||
decoded, updated, err := c.callMTop(ctx, cookiesStr, DefaultLocationAPI, "mtop.taobao.idle.local.poi.get", "1.0", "a21ybx.publish.0.0", "a21ybx.item.sidebar.1.38262218ame5nr", "38262218ame5nr", data)
|
||||
@@ -297,16 +441,7 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
|
||||
"enable": false, "serviceCode": "SKILL_PLAY_NO_MIND",
|
||||
}},
|
||||
"itemPostFeeDTO": postageDTO(req),
|
||||
"itemAddrDTO": map[string]any{
|
||||
"area": location["area"],
|
||||
"city": location["city"],
|
||||
"divisionId": location["divisionId"],
|
||||
"gps": fmt.Sprintf("%s,%s", mtopString(location["longitude"]), mtopString(location["latitude"])),
|
||||
"poiId": location["poiId"],
|
||||
"poiName": location["poi"],
|
||||
"prov": location["prov"],
|
||||
},
|
||||
"defaultPrice": false,
|
||||
"defaultPrice": false,
|
||||
"itemCatDTO": map[string]any{
|
||||
"catId": mtopString(cat["catId"]),
|
||||
"catName": mtopString(cat["catName"]),
|
||||
@@ -318,6 +453,17 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
|
||||
"bizcode": "pcMainPublish",
|
||||
"publishScene": "pcMainPublish",
|
||||
}
|
||||
if !req.Virtual {
|
||||
data["itemAddrDTO"] = map[string]any{
|
||||
"area": location["area"],
|
||||
"city": location["city"],
|
||||
"divisionId": location["divisionId"],
|
||||
"gps": fmt.Sprintf("%s,%s", mtopString(location["longitude"]), mtopString(location["latitude"])),
|
||||
"poiId": location["poiId"],
|
||||
"poiName": location["poi"],
|
||||
"prov": location["prov"],
|
||||
}
|
||||
}
|
||||
decoded, updated, err := c.callMTop(ctx, cookiesStr, PublishItemAPI, "mtop.idle.pc.idleitem.publish", "1.0", "a21ybx.publish.0.0", "a21ybx.home.sidebar.1.46413da6EPl7v5", "46413da6EPl7v5", data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -476,8 +622,7 @@ func publishLabels(category map[string]any) []any {
|
||||
values, _ := cardData["valuesList"].([]any)
|
||||
for _, rawValue := range values {
|
||||
value := mapFromAny(rawValue)
|
||||
clicked, _ := value["isClicked"].(bool)
|
||||
if !clicked {
|
||||
if !publishLabelSelected(value["isClicked"]) {
|
||||
continue
|
||||
}
|
||||
propertyID := mtopString(cardData["propertyId"])
|
||||
@@ -509,6 +654,18 @@ func publishLabels(category map[string]any) []any {
|
||||
return out
|
||||
}
|
||||
|
||||
func publishLabelSelected(value any) bool {
|
||||
if selected, ok := value.(bool); ok {
|
||||
return selected
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(mtopString(value))) {
|
||||
case "1", "true":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func classifyPublishError(ret []string, decoded map[string]any) error {
|
||||
bodyBytes, _ := json.Marshal(decoded)
|
||||
body := string(bodyBytes)
|
||||
|
||||
@@ -61,6 +61,7 @@ func TestPublishItemValidationFailures(t *testing.T) {
|
||||
{"zero quantity", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 0, Images: []PublishImage{{}}}, "库存数量必须大于 0"},
|
||||
{"no images", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1}, "至少上传 1 张商品图片"},
|
||||
{"too many images", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1, Images: make([]PublishImage, 10)}, "商品图片最多 9 张"},
|
||||
{"incomplete preferred category", PublishItemRequest{Title: "T", PriceCents: 100, Quantity: 1, PreferredCategory: &PublishCategory{CatID: "5001"}, Images: []PublishImage{{}}}, "默认类目必须同时包含"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
@@ -179,7 +180,7 @@ func TestPublishItemRecommendCategoryFailure(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestPublishItemRecommendCategoryMissingData: ret 成功但 data 缺 categoryPredictResult。
|
||||
func TestPublishItemRecommendCategoryMissingData(t *testing.T) {
|
||||
func TestPublishItemRecommendCategoryMissingDataUsesElectronicMaterials(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
"_upload": func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -188,18 +189,25 @@ func TestPublishItemRecommendCategoryMissingData(t *testing.T) {
|
||||
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
|
||||
},
|
||||
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"fallback-item"}}`)
|
||||
},
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
req := PublishItemRequest{
|
||||
Title: "T",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
Virtual: true,
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
}
|
||||
_, err := client.PublishItem(context.Background(), consignCookies, req)
|
||||
if err == nil || !strings.Contains(err.Error(), "未能自动识别商品类目") {
|
||||
result, err := client.PublishItem(context.Background(), consignCookies, req)
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if result.CategoryID != "50023914" || result.CategoryName != "电子资料" {
|
||||
t.Fatalf("result=%+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemLocationFailure: 默认地址缺失。
|
||||
@@ -229,6 +237,123 @@ func TestPublishItemLocationFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishVirtualItemSkipsLocation 虚拟商品不查询默认地址,也不发送实物地址字段。
|
||||
func TestPublishVirtualItemSkipsLocation(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
var publishedData map[string]any
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
"_upload": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
|
||||
},
|
||||
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
|
||||
},
|
||||
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
|
||||
publishedData, _ = parseDataURL(readBody(r))
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"virtual-item-1"}}`)
|
||||
},
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
res, err := client.PublishItem(context.Background(), consignCookies, PublishItemRequest{
|
||||
Title: "虚拟商品",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
Virtual: true,
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if res.ItemID != "virtual-item-1" {
|
||||
t.Fatalf("ItemID=%q", res.ItemID)
|
||||
}
|
||||
if publishedData == nil {
|
||||
t.Fatal("未解析到发布请求 data")
|
||||
}
|
||||
if _, exists := publishedData["itemAddrDTO"]; exists {
|
||||
t.Fatalf("虚拟商品不应发送 itemAddrDTO: %+v", publishedData["itemAddrDTO"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishVirtualItemUsesPreferredCategoryWithoutRecommendation(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
var publishedData map[string]any
|
||||
recommendCalled := false
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
"_upload": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
|
||||
},
|
||||
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
|
||||
recommendCalled = true
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
|
||||
},
|
||||
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
|
||||
publishedData, _ = parseDataURL(readBody(r))
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"fallback-item-1"}}`)
|
||||
},
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
res, err := client.PublishItem(context.Background(), consignCookies, PublishItemRequest{
|
||||
Title: "虚拟商品",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
Virtual: true,
|
||||
PreferredCategory: &PublishCategory{CatID: "5001", CatName: "虚拟服务", ChannelCatID: "6001", TBCatID: "7001"},
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if recommendCalled {
|
||||
t.Fatal("配置默认类目后不应调用自动推荐接口")
|
||||
}
|
||||
if res.CategoryID != "5001" || res.CategoryName != "虚拟服务" {
|
||||
t.Fatalf("category result=%+v", res)
|
||||
}
|
||||
category, _ := publishedData["itemCatDTO"].(map[string]any)
|
||||
if category["catId"] != "5001" || category["catName"] != "虚拟服务" || category["channelCatId"] != "6001" || category["tbCatId"] != "7001" {
|
||||
t.Fatalf("published category=%+v", category)
|
||||
}
|
||||
if _, exists := publishedData["itemAddrDTO"]; exists {
|
||||
t.Fatalf("虚拟商品不应发送 itemAddrDTO: %+v", publishedData["itemAddrDTO"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishVirtualItemUsesElectronicMaterialsWhenRecommendationIsEmpty(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
var publishedData map[string]any
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
"_upload": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
|
||||
},
|
||||
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{}}`)
|
||||
},
|
||||
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, r *http.Request) {
|
||||
publishedData, _ = parseDataURL(readBody(r))
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"electronic-item-1"}}`)
|
||||
},
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
res, err := client.PublishItem(context.Background(), consignCookies, PublishItemRequest{
|
||||
Title: "无法识别的虚拟商品",
|
||||
PriceCents: 1000,
|
||||
Quantity: 1,
|
||||
Virtual: true,
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if res.CategoryID != "50023914" || res.CategoryName != "电子资料" {
|
||||
t.Fatalf("category result=%+v", res)
|
||||
}
|
||||
category, _ := publishedData["itemCatDTO"].(map[string]any)
|
||||
if category["channelCatId"] != "202036301" {
|
||||
t.Fatalf("published category=%+v", category)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishItemFinalPublishFailure: 发布接口返回 token 过期错误。
|
||||
func TestPublishItemFinalPublishFailure(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
@@ -428,6 +553,43 @@ func TestRecommendPublishCategorySuccess(t *testing.T) {
|
||||
_ = png1
|
||||
}
|
||||
|
||||
func TestRecommendPublishCategoryUsesSelectedCategoryCard(t *testing.T) {
|
||||
imgs := []uploadedImage{{URL: "https://cdn/a.jpg", Width: 800, Height: 600}}
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"50023914","catName":"电子资料","channelCatId":"202036301","isClicked":"1"}]}}]}}`)
|
||||
},
|
||||
}}
|
||||
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
|
||||
category, _, err := client.recommendPublishCategory(context.Background(), consignCookies, "其他虚拟资料", "其他虚拟资料", imgs)
|
||||
if err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
selected := category["categoryPredictResult"].(map[string]any)
|
||||
if selected["catId"] != "50023914" || selected["catName"] != "电子资料" || selected["channelCatId"] != "202036301" {
|
||||
t.Fatalf("selected=%+v", selected)
|
||||
}
|
||||
if labels := publishLabels(category); len(labels) != 1 {
|
||||
t.Fatalf("labels=%+v", labels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultVirtualPublishCategoryIncludesSelectedCategoryLabel(t *testing.T) {
|
||||
category := DefaultVirtualPublishCategory()
|
||||
if category.CatID != "50023914" || category.CatName != "电子资料" || category.ChannelCatID != "202036301" || category.TBCatID != "" {
|
||||
t.Fatalf("default category=%+v", category)
|
||||
}
|
||||
fallback := fallbackPublishCategory(category)
|
||||
labels := publishLabels(fallback)
|
||||
if len(labels) != 1 {
|
||||
t.Fatalf("labels=%+v", labels)
|
||||
}
|
||||
label := labels[0].(map[string]any)
|
||||
if label["channelCateId"] != "202036301" || label["channelCateName"] != "电子资料" || label["propertyId"] != "-10000" {
|
||||
t.Fatalf("label=%+v", label)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecommendPublishCategoryDataNil(t *testing.T) {
|
||||
imgs := []uploadedImage{{URL: "u", Width: 1, Height: 1}}
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
@@ -24,6 +25,7 @@ import (
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/xianyu"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -402,12 +404,27 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
}
|
||||
return
|
||||
}
|
||||
// 二维码组件确认成功后,真实网页还会进入 /im 并跟随登录
|
||||
// 重定向。部分账号的长登录 Cookie 只在这一步下发,不能只
|
||||
// 保存 query.do 的响应头。
|
||||
if err := m.completeConfirmedLogin(ctx, sess); err != nil {
|
||||
m.logger.Warn("扫码确认后的官网登录跳转未完成,保留当前登录凭证", "session_id", sessionID, "err", err)
|
||||
}
|
||||
if err := m.enableConfirmedLongLogin(ctx, sess); err != nil {
|
||||
m.logger.Warn("扫码登录已成功,但官网保持登录开启失败", "session_id", sessionID, "err", err)
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.Status = "success"
|
||||
finalizeSessionCredentialsLocked(sess)
|
||||
unb := sess.unb
|
||||
cookieCount := len(sess.cookies)
|
||||
hasHavanaLongLogin := sess.cookies["havana_lgc_exp"] != ""
|
||||
hasCookie3Backup := sess.cookies["cookie3_bak_exp"] != ""
|
||||
snapshotComplete := sess.cookieSnapshot != nil
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb))
|
||||
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb),
|
||||
"cookie_count", cookieCount, "cookie_snapshot_complete", snapshotComplete,
|
||||
"has_havana_lgc_exp", hasHavanaLongLogin, "has_cookie3_bak_exp", hasCookie3Backup)
|
||||
return
|
||||
case "NEW":
|
||||
// 未扫码,继续
|
||||
@@ -453,6 +470,92 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
|
||||
// completeConfirmedLogin 对齐二维码组件确认后的顶层页面跳转。专用 Cookie
|
||||
// Jar 会捕获自动重定向链上的全部 Set-Cookie,并保留 Domain/Path/HttpOnly。
|
||||
func (m *Manager) completeConfirmedLogin(ctx context.Context, sess *Session) error {
|
||||
if sess == nil {
|
||||
return errors.New("扫码会话为空")
|
||||
}
|
||||
state := sess.snapshot()
|
||||
client, jar, err := m.faceHTTPClient(state.cookies, state.cookieSnapshot, apiScanStatus, qrVerifyTargetURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建扫码完成 Cookie Jar: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, qrVerifyTargetURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建扫码完成请求: %w", err)
|
||||
}
|
||||
m.setDocumentHeaders(req)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("访问闲鱼消息页完成登录: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if _, err := io.Copy(io.Discard, io.LimitReader(resp.Body, 2<<20)); err != nil {
|
||||
return fmt.Errorf("读取扫码完成响应: %w", err)
|
||||
}
|
||||
|
||||
urls := []*url.URL{mustParseURL(qrVerifyTargetURL)}
|
||||
if resp.Request != nil && resp.Request.URL != nil {
|
||||
urls = append(urls, resp.Request.URL)
|
||||
}
|
||||
finalCookies := collectJarCookies(jar, urls...)
|
||||
if finalCookies["unb"] == "" {
|
||||
return errors.New("扫码完成跳转未保留账号标识")
|
||||
}
|
||||
finalSnapshot, snapshotComplete := jar.Snapshot()
|
||||
sess.mu.Lock()
|
||||
sess.cookies = finalCookies
|
||||
if snapshotComplete {
|
||||
sess.cookieSnapshot = finalSnapshot
|
||||
} else {
|
||||
sess.cookieSnapshot = nil
|
||||
}
|
||||
sess.unb = finalCookies["unb"]
|
||||
sess.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// enableConfirmedLongLogin 对齐官网账号安全页的“保持登录”开关:先提交
|
||||
// status=0,再查询 hasLongTokenLogin,并保存两次响应更新后的完整 Cookie Jar。
|
||||
func (m *Manager) enableConfirmedLongLogin(ctx context.Context, sess *Session) error {
|
||||
if sess == nil {
|
||||
return errors.New("扫码会话为空")
|
||||
}
|
||||
state := sess.snapshot()
|
||||
service := xrenew.Service{HTTPClient: m.httpc, DocumentReferer: qrVerifyTargetURL}
|
||||
var settings *xrenew.LongLoginSettings
|
||||
var err error
|
||||
if state.cookieSnapshot != nil {
|
||||
settings, err = service.SetLongLoginSettings(ctx, cookieMarshal(state.cookies), true, state.cookieSnapshot)
|
||||
} else {
|
||||
settings, err = service.SetLongLoginSettings(ctx, cookieMarshal(state.cookies), true)
|
||||
}
|
||||
if settings != nil {
|
||||
sess.mu.Lock()
|
||||
if settings.CookieSnapshotComplete {
|
||||
sess.cookieSnapshot = cookierefresh.NormalizeSnapshot(settings.CookieSnapshot)
|
||||
if sess.cookieSnapshot == nil {
|
||||
sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
finalizeSessionCredentialsLocked(sess)
|
||||
} else if strings.TrimSpace(settings.NewCookies) != "" {
|
||||
sess.cookies = parseCookieStr(settings.NewCookies)
|
||||
if unb := sess.cookies["unb"]; unb != "" {
|
||||
sess.unb = unb
|
||||
}
|
||||
}
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if settings == nil || !settings.CanOpenLongLogin || !settings.Enabled {
|
||||
return errors.New("官网未确认当前会话已开启保持登录")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) runGoVerification(ctx context.Context, sessionID, verificationURL string) {
|
||||
if !strings.Contains(verificationURL, "/iv/") && !strings.Contains(verificationURL, "identity_verify") {
|
||||
m.logger.Warn("扫码验证地址不属于已支持的人脸流程,保持人工验证状态", "session_id", sessionID, "verification_url", logsafe.URL(verificationURL))
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -595,6 +596,59 @@ func TestMonitorQRStatusConfirmed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorQRStatusConfirmedCollectsCookiesFromFinalIMNavigation(t *testing.T) {
|
||||
hc := &handlerChain{}
|
||||
hc.handle("/newlogin/qrcode/query.do", statusHandler("CONFIRMED",
|
||||
&http.Cookie{Name: "unb", Value: "u123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
&http.Cookie{Name: "cookie2", Value: "v2", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
))
|
||||
hc.handle("/im", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.Contains(r.Header.Get("Cookie"), "unb=u123") {
|
||||
t.Fatalf("最终登录跳转未携带扫码 Cookie: %q", r.Header.Get("Cookie"))
|
||||
}
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
}))
|
||||
hc.handle("/ac/account/setLoginSettings.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
|
||||
t.Fatalf("保持登录参数异常: form=%v err=%v", r.Form, err)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "havana_lgc_exp", Value: strconv.FormatInt(time.Now().Add(24*time.Hour).UnixMilli(), 10),
|
||||
Domain: ".goofish.com", Path: "/", Secure: true, HttpOnly: true,
|
||||
})
|
||||
_, _ = w.Write([]byte(`{"data":{"success":true}}`))
|
||||
}))
|
||||
hc.handle("/ac/account/queryLoginSettings.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.Contains(r.Header.Get("Cookie"), "havana_lgc_exp=") {
|
||||
t.Fatalf("查询保持登录状态未携带新凭证: %q", r.Header.Get("Cookie"))
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
|
||||
}))
|
||||
m, _, _ := newStubbedManager(t, hc)
|
||||
sess := newMonitorSession("waiting")
|
||||
sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
m.sessions["s"] = sess
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
m.monitorQRStatus(ctx, "s")
|
||||
|
||||
state := sess.snapshot()
|
||||
if state.status != "success" || state.cookies["havana_lgc_exp"] == "" {
|
||||
t.Fatalf("最终登录跳转 Cookie 未保存: status=%s cookies=%v", state.status, state.cookies)
|
||||
}
|
||||
var longLogin *cookierefresh.BrowserCookie
|
||||
for i := range state.cookieSnapshot {
|
||||
if state.cookieSnapshot[i].Name == "havana_lgc_exp" {
|
||||
longLogin = &state.cookieSnapshot[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if longLogin == nil || !longLogin.HTTPOnly || longLogin.Domain != ".goofish.com" {
|
||||
t.Fatalf("长登录 Cookie 属性未完整保留: %+v", longLogin)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorQRStatusScanned(t *testing.T) {
|
||||
hc := &handlerChain{}
|
||||
// 第一次返回 SCANED,第二次返回 CONFIRMED。
|
||||
|
||||
@@ -343,6 +343,17 @@ const (
|
||||
// It never chains hasLogin/setLoginSettings or escalates to an interactive
|
||||
// login from this proactive renewal path.
|
||||
func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
|
||||
return s.renewAPIFirst(ctx, false, cookiesStr, snapshots...)
|
||||
}
|
||||
|
||||
// RenewAfterSessionExpired 用于服务端已经明确返回 SESSION_EXPIRED 的恢复路径。
|
||||
// sdkSilent 只用于限制健康账号的主动静默续期;它不能阻止一次已经被业务接口
|
||||
// 证实为失效的凭证恢复。长登录凭证本身过期时仍拒绝请求并要求重新扫码。
|
||||
func (s Service) RenewAfterSessionExpired(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
|
||||
return s.renewAPIFirst(ctx, true, cookiesStr, snapshots...)
|
||||
}
|
||||
|
||||
func (s Service) renewAPIFirst(ctx context.Context, sessionExpired bool, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
|
||||
cookiesStr = strings.TrimSpace(cookiesStr)
|
||||
authoritativeSnapshot := len(snapshots) > 0 && snapshots[0] != nil
|
||||
documentURL := s.documentReferer()
|
||||
@@ -354,13 +365,10 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
var snapshot []cookierefresh.BrowserCookie
|
||||
if authoritativeSnapshot {
|
||||
snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
|
||||
documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
|
||||
for _, cookie := range snapshot {
|
||||
if !cookie.HTTPOnly {
|
||||
documentCookies = append(documentCookies, cookie)
|
||||
}
|
||||
}
|
||||
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, documentURL, goofishTopSite, now); authoritative {
|
||||
// havana_lgc_exp 由官网以 HttpOnly Cookie 下发。续期服务保存的是
|
||||
// 浏览器完整 Cookie Jar,不能按 document.cookie 过滤,否则刚登录的
|
||||
// 有效长登录凭证会被误判为不存在。
|
||||
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, documentURL, goofishTopSite, now); authoritative {
|
||||
decisionCookies = scoped
|
||||
}
|
||||
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, now); authoritative {
|
||||
@@ -386,14 +394,12 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
result.NeedPasswordLogin = true
|
||||
return result, nil
|
||||
}
|
||||
if ua := strings.ToLower(xianyu.CurrentBrowserFingerprint().UserAgent); ua != "" &&
|
||||
!strings.Contains(ua, "windows") && !strings.Contains(ua, "macintosh") {
|
||||
result.Skipped = true
|
||||
result.SkipReason = "unsupported_desktop_ua"
|
||||
result.Message = autoLoginSkipMessage(result.SkipReason)
|
||||
return result, nil
|
||||
}
|
||||
mode, skipReason := autoLoginMode(firstCookieValues(decisionCookies), now)
|
||||
if sessionExpired && skipReason == "fatigue" {
|
||||
// 业务接口已明确证明 Session 失效,忽略主动续期疲劳标记,但仍只调用
|
||||
// 一次 silentHasLogin,且继续要求长登录凭证有效。
|
||||
mode, skipReason = autoLoginModeWithoutFatigue(firstCookieValues(decisionCookies), now)
|
||||
}
|
||||
if skipReason != "" {
|
||||
result.Skipped = true
|
||||
result.SkipReason = skipReason
|
||||
@@ -482,7 +488,9 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
late.CookieSnapshot = append([]cookierefresh.BrowserCookie(nil), snapshot...)
|
||||
late.CookieSnapshotComplete = true
|
||||
}
|
||||
late, lateErr := populate(late, outcome.call, outcome.err, true)
|
||||
// Promise 超时只描述前端等待窗口;底层响应到达后必须按真实
|
||||
// HTTP/业务结果生成终态,不能永久标记为失败。
|
||||
late, lateErr := populate(late, outcome.call, outcome.err, false)
|
||||
pending <- pendingRenewResult{result: late, err: lateErr}
|
||||
close(pending)
|
||||
}()
|
||||
@@ -491,6 +499,16 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
return populate(result, call, err, false)
|
||||
}
|
||||
|
||||
func autoLoginModeWithoutFatigue(cookies map[string]string, now time.Time) (mode, skipReason string) {
|
||||
if cookieTimeAfter(cookies["havana_lgc_exp"], now) {
|
||||
return autoLoginModeHavana, ""
|
||||
}
|
||||
if cookieTimeAfter(cookies["cookie3_bak_exp"], now) {
|
||||
return autoLoginModeCookie3, ""
|
||||
}
|
||||
return "", "long_login_expired"
|
||||
}
|
||||
|
||||
func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason string) {
|
||||
if strictCookieTimeAfter(cookies["sdkSilent"], now) {
|
||||
return "", "fatigue"
|
||||
@@ -551,8 +569,6 @@ func autoLoginSkipMessage(reason string) string {
|
||||
return "sdkSilent 疲劳窗口内,跳过静默续期"
|
||||
case "long_login_expired":
|
||||
return "长登录凭证已过期,静默续期不应发起请求"
|
||||
case "unsupported_desktop_ua":
|
||||
return "官网静默续期仅支持 Windows 或 macOS 桌面浏览器"
|
||||
default:
|
||||
return "无需静默续期"
|
||||
}
|
||||
|
||||
@@ -48,6 +48,20 @@ func useTestDesktopFingerprint(t *testing.T) xianyu.BrowserFingerprint {
|
||||
return fingerprint
|
||||
}
|
||||
|
||||
func useTestLinuxFingerprint(t *testing.T) xianyu.BrowserFingerprint {
|
||||
t.Helper()
|
||||
old := xianyu.CurrentBrowserFingerprint()
|
||||
fingerprint := xianyu.BrowserFingerprint{
|
||||
UserAgent: `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36`,
|
||||
SecChUA: `"Chromium";v="138", "Not_A Brand";v="24"`,
|
||||
Platform: "Linux",
|
||||
Mobile: "?0",
|
||||
}
|
||||
xianyu.SetBrowserFingerprint(fingerprint)
|
||||
t.Cleanup(func() { xianyu.SetBrowserFingerprint(old) })
|
||||
return fingerprint
|
||||
}
|
||||
|
||||
func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
|
||||
now := time.Now()
|
||||
tests := []struct {
|
||||
@@ -135,6 +149,35 @@ func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewAfterSessionExpiredBypassesOnlyFatigue(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
calls.Add(1)
|
||||
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "recovered"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
now := time.Now()
|
||||
cookies := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
|
||||
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)
|
||||
service := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
proactive, err := service.RenewAPIFirst(context.Background(), cookies)
|
||||
if err != nil || !proactive.Skipped || proactive.SkipReason != "fatigue" || calls.Load() != 0 {
|
||||
t.Fatalf("proactive=%+v calls=%d err=%v", proactive, calls.Load(), err)
|
||||
}
|
||||
recovered, err := service.RenewAfterSessionExpired(context.Background(), cookies)
|
||||
if err != nil || !recovered.Success || calls.Load() != 1 || !strings.Contains(recovered.NewCookies, "havana_lgc2_77=recovered") {
|
||||
t.Fatalf("recovered=%+v calls=%d err=%v", recovered, calls.Load(), err)
|
||||
}
|
||||
|
||||
expiredLongLogin := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
|
||||
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)
|
||||
blocked, err := service.RenewAfterSessionExpired(context.Background(), expiredLongLogin)
|
||||
if err != nil || !blocked.Skipped || blocked.SkipReason != "long_login_expired" || calls.Load() != 1 {
|
||||
t.Fatalf("blocked=%+v calls=%d err=%v", blocked, calls.Load(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -301,7 +344,7 @@ func TestRenewAPIFirstUsesBrowserCookieScopes(t *testing.T) {
|
||||
host := strings.TrimPrefix(srv.URL, "http://")
|
||||
host = strings.Split(host, ":")[0]
|
||||
snapshot := []cookierefresh.BrowserCookie{
|
||||
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/"},
|
||||
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", HTTPOnly: true},
|
||||
{Name: "request_only", Value: "passport", Domain: host, Path: "/"},
|
||||
{Name: "www_only", Value: "private", Domain: "www.goofish.com", Path: "/im"},
|
||||
{Name: "http_only_document", Value: "hidden", Domain: ".goofish.com", Path: "/", HTTPOnly: true},
|
||||
@@ -319,6 +362,45 @@ func TestRenewAPIFirstUsesBrowserCookieScopes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewAPIFirstUsesHTTPOnlyLongLoginCookieForDecision(t *testing.T) {
|
||||
useTestDesktopFingerprint(t)
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
_, _ = w.Write([]byte(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
snapshot := []cookierefresh.BrowserCookie{{
|
||||
Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", HTTPOnly: true,
|
||||
}}
|
||||
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
|
||||
if err != nil || res == nil || !res.Success || res.Skipped || res.RequestCount != 1 || calls.Load() != 1 {
|
||||
t.Fatalf("result=%+v calls=%d err=%v", res, calls.Load(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewAPIFirstRunsWithLinuxChromiumFingerprint(t *testing.T) {
|
||||
fingerprint := useTestLinuxFingerprint(t)
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
if got := r.Header.Get("User-Agent"); got != fingerprint.UserAgent {
|
||||
t.Fatalf("User-Agent=%q", got)
|
||||
}
|
||||
if got := r.Header.Get("sec-ch-ua-platform"); got != `"Linux"` {
|
||||
t.Fatalf("sec-ch-ua-platform=%q", got)
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
|
||||
res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour))
|
||||
if err != nil || res == nil || !res.Success || res.Skipped || res.RequestCount != 1 || calls.Load() != 1 {
|
||||
t.Fatalf("result=%+v calls=%d err=%v", res, calls.Load(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie(t *testing.T) {
|
||||
useTestDesktopFingerprint(t)
|
||||
snapshot := []cookierefresh.BrowserCookie{
|
||||
@@ -521,8 +603,8 @@ func TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies(t *testing.T) {
|
||||
if lateErr != nil || late == nil || len(late.SetCookies) != 1 || !strings.Contains(late.NewCookies, "sdkSilent=") {
|
||||
t.Fatalf("迟到响应 Cookie 丢失: result=%+v err=%v", late, lateErr)
|
||||
}
|
||||
if !completed.Load() || late.Success || late.NeedPasswordLogin {
|
||||
t.Fatalf("底层请求应完成,但不得在 Promise 超时后触发成功 reload/重新登录: %+v completed=%v", late, completed.Load())
|
||||
if !completed.Load() || !late.Success || late.NeedPasswordLogin {
|
||||
t.Fatalf("底层请求完成后应返回真实业务终态: %+v completed=%v", late, completed.Load())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user