Compare commits

..
Author SHA1 Message Date
Christ 526ac44453 fix: 完善同步生命周期并统一前端视觉
- 同步商品与订单时处理线上删除状态并联动自动化规则\n- 过滤卖家系统中的购买订单,修复订单逻辑删除与数据库迁移\n- 修复聊天新消息自动滚动,并统一前端颜色令牌与硬编码颜色检查
2026-08-10 12:41:10 +08:00
Christ cf76b8898b merge: 合并商品同步与逻辑删除修复 2026-08-10 11:24:37 +08:00
Christ 9adc77df73 fix(商品同步): 修复全量同步删除与规则生命周期 2026-08-10 11:21:35 +08:00
Christ 4fb857da1e merge: 合并商品同步修复到 main 2026-08-10 01:11:56 +08:00
Christ 182cc75e63 fix(商品同步): 完善线上商品全量同步 2026-08-10 01:11:45 +08:00
Christ 450a62c924 修复自动化规则统计口径
- 新增按筛选条件聚合的规则触发类型统计\n- 修复分页数据导致分类数量与规则总数不一致的问题\n- 补充前后端统计接口测试并同步嵌入式前端资源
2026-08-09 00:10:24 +08:00
Christ fe3f715cdc feat: 完善聊天识别与规则页面响应式布局
- 按闲鱼协议字段识别官方系统消息、交易卡片和闲小蜜,清理空会话壳并补齐历史消息校正\n- 同步 README、项目展示页和 GitHub Wiki,补充在线聊天、账号自动评价与每日擦亮说明\n- 优化自动化规则页面的中等宽度布局,补充前端类型、响应式测试和嵌入资源
2026-08-08 23:48:42 +08:00
Christ 4d1f58c5ec merge: promote phase1 chat and account automation 2026-08-08 22:42:14 +08:00
Christ 0de1ec7635 merge: integrate phase1 chat and account automation 2026-08-08 22:19:36 +08:00
Christ 67d7214930 feat: add account automation and isolated chat
- add account-level auto rating and daily polish tasks\n- add cached historical chat, media, emoji, and per-account realtime sync\n- add SQLite, MySQL, and PostgreSQL migrations and regression coverage\n- align account, sidebar, and chat interfaces with the new workflows
2026-08-08 22:16:35 +08:00
Christ d7abbfb2b6 完善服务端交互日志与初始化测试
统一划分 MTOP 与 WebSocket 日志等级,增加 Token 安全指纹和请求耗时诊断;补充 init-admin 临时数据库测试;同步 README 的镜像发布说明。
2026-08-08 12:05:43 +08:00
Christ ad224bf4e9 合并 dev 分支仪表盘优化与文档更新 2026-08-07 14:29:25 +08:00
Christ 474f9c4b65 优化仪表盘图表交互并完善前端文档 2026-08-07 14:28:12 +08:00
Christ 798e3f3221 合并 dev 分支全部修复 2026-08-07 11:27:39 +08:00
Christ f13950f482 合并 WS Token 主动轮换与自动化可靠性修复 2026-08-07 11:14:48 +08:00
Christ bdc64c68f6 修复 WS Token 主动轮换与自动化任务恢复
根据服务端过期时间提前轮换 WS Token,并对缺失期限使用保守刷新窗口。

Token 获取瞬时失败时保持账号运行并在过期前持续重试;统一 Cookie、WS 恢复后的自动化唤醒和安全动作游标重试。

修复多实例恢复租约覆盖、规则查询误隔离及人工核对状态落库错误,并等待自动化调度器、续期 watcher 和批量发布恢复任务优雅退出。

补充 SQLite、PostgreSQL 17、生命周期和竞态回归测试。
2026-08-05 14:50:39 +08:00
Christ 9c742f5e7f 修复自动化凭证恢复与失败任务补偿 2026-08-05 12:33:05 +08:00
Christ 5f4d199231 修复 Cookie 续期终态与账号恢复链路 2026-07-28 11:57:48 +08:00
Christ 50d09eb47a 修改readme的docker图标状态。 2026-07-28 00:14:13 +08:00
Christ 6e678999fc 修复自动化启动时序与失败重试机制 2026-07-27 12:40:40 +08:00
Christ f68c8b8add 修复求评价调度时间解析并完善续期日志 2026-07-27 12:08:39 +08:00
Christ cef2ca92c4 feat(续期): 启用定时静默续期与失败告警
默认每四小时执行 API Cookie 续期,账号间错峰一分钟;记录全部续期结果,并在同一账号连续三次失败时发送续期告警。
2026-07-26 11:30:18 +08:00
Christ 090802e25d fix(WS诊断): 优化报文批量写入与过期清理
延长数据库写入超时并按批次刷盘,降低数据库锁竞争导致的诊断记录失败;账号启动时清理七天前的 WS 报文,并补充批量写入与保留期测试。
2026-07-26 11:01:27 +08:00
Christ 2c6385374a fix(扫码登录): 自动开启官网保持登录 2026-07-26 00:40:20 +08:00
Christ d0569fb1ef fix(扫码登录): 补齐确认后的官网凭证跳转 2026-07-26 00:25:15 +08:00
Christ 90b6e4f5ce fix(续期): 识别 HttpOnly 长登录凭证 2026-07-26 00:03:45 +08:00
Christ 9e4e4bcee9 fix(续期): 支持 Linux Docker 静默自动续期 2026-07-25 23:52:58 +08:00
Christ 8fdc25483f feat(批量铺货): 支持关键词类目推荐与最终兜底 2026-07-25 21:31:12 +08:00
Christ b98c4edf68 feat(发布与自动化): 完善批量发布分类兜底和规则管理 2026-07-25 20:02:37 +08:00
Christ fd30a0d17a fix(发布与账号): 修复虚拟铺货和删除任务体验
- 虚拟商品发布跳过地址查询与地址字段,避免被默认地址校验拦截。
- 取消批量铺货后保留上传图片,支持失败项重试并按过期策略清理。
- 优化账号删除的确认弹窗、进度反馈与后台停止逻辑,避免误删和页面卡顿。
2026-07-25 18:37:30 +08:00
Christ 7fd11106af Merge branches 'main' and 'main' of github.com:Christ9038/Ydisks-Xianyu-Helper 2026-07-25 16:15:54 +08:00
Christ 968c66469d fix(docs): 修正官网 Wiki 与文档指南的跳转链接
- 将 Hero 区块与 Footer 底部中的 Wiki 链接统一更新为官方 GitHub Wiki 地址 https://github.com/Christ9038/Ydisks-Xianyu-Helper/wiki
2026-07-25 16:15:06 +08:00
Christ 085c302be6 Create CNAME 2026-07-25 16:00:52 +08:00
Christ 9705402d1d feat(docs): 添加基于 GitHub Pages 的项目官网首页
- 新增 docs/index.html 官网首页,延续 Apple / Ydisks 品牌设计风格
- 包含毛玻璃 Navigation Header、Hero 标语与系统后台实拍展示
- 整合 Ydisks 网盘拉新协同流转、12 大核心功能模块与系统架构图
- 提供 Docker Compose 与源码构建的一键复制交互命令组件及 FAQ 折叠问答
- 新增 docs/assets/favicon.svg 矢量 Icon 与品牌资源
2026-07-25 15:57:51 +08:00
Christ adbec2b9b0 CI: 限制主分支构建并同步 Wiki 2026-07-25 15:39:39 +08:00
Christ 687e5156af 更新README的图片地址。 2026-07-25 15:26:50 +08:00
Christ 051bf6eb68 添加Readme预览,以及开源协议。 2026-07-25 15:14:43 +08:00
Christ 6cd3ff7d60 文档: 补充许可证文件说明 2026-07-25 14:23:56 +08:00
Christ 614bae4b2b 文档: 完善项目命名、协议与使用指南 2026-07-25 14:17:48 +08:00
Christ 16b2b84fa2 新增 GHCR 一键 Docker 部署配置
新增默认 compose.yml,直接拉取 GHCR 多架构镜像并启动 PostgreSQL 17。服务首次启动自动创建管理员且不会在后续重启时重置密码;同步更新环境变量示例和部署文档。
2026-07-23 20:02:21 +08:00
Christ 0f77607d57 合并 dev:发布 Docker 多架构与完善项目文档 2026-07-23 18:04:16 +08:00
Christ c819810b1b 完善项目 README 与部署文档
补充项目简介、快速开始、配置说明、Docker 多架构部署、备份恢复、安全建议和常见问题,便于公开发布与自托管使用。
2026-07-23 18:04:11 +08:00
Christ fccb5eebc8 发布 Docker 多架构镜像
GitHub Actions 同时构建 amd64 和 arm64,并移除 Compose 的平台锁定,让 Docker 根据宿主机 CPU 自动选择镜像。
2026-07-23 16:24:57 +08:00
Christ a5a8aa9b8b 增加 GitHub Docker 镜像发布流程
通过 GitHub Actions 构建并发布 linux/amd64 镜像到 GHCR,补充镜像标签策略和服务器拉取部署说明。
2026-07-23 16:10:25 +08:00
Christ 6a9a684e5e 合并登录续期与 x86 Docker 部署改进 2026-07-23 16:03:27 +08:00
176 changed files with 14186 additions and 1179 deletions

No files matched your search

+4 -4
View File
@@ -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=请替换为管理员密码
+67
View File
@@ -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
+48
View File
@@ -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
+2 -2
View File
@@ -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
```
+1 -1
View File
@@ -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
+201
View File
@@ -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 -1
View File
@@ -1,4 +1,4 @@
# xianyu-go 常用命令入口。详见各 target 注释。
# Ydisks-Xianyu-Helper 常用命令入口。详见各 target 注释。
GO ?= go
GOLANGCI_LINT ?= golangci-lint
+5
View File
@@ -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.
+550 -192
View File
@@ -1,264 +1,622 @@
# 闲鱼管家
# Ydisks闲鱼助手
这是当前活跃版本:Go 后端 + React 前端。后续功能迭代均在此目录进行:
![Ydisks闲鱼助手Slogan](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/slogan.png)
```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](https://img.shields.io/badge/Go-1.26-00ADD8?logo=go&logoColor=white)](go.mod)
[![React](https://img.shields.io/badge/React-19-61DAFB?logo=react&logoColor=black)](frontend/package.json)
[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-17-4169E1?logo=postgresql&logoColor=white)](compose.yml)
[![Docker Image](https://github.com/Christ9038/Ydisks-Xianyu-Helper/actions/workflows/docker-publish.yml/badge.svg?branch=main)](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 凭证更新、失效恢复、冷却与失败停用 |
| 即时消息 | 按账号隔离的在线聊天、会话列表与历史消息、闲鱼表情、文本/图片收发、官方系统消息识别、关键词回复、默认回复及仅回复一次 |
| 自动化中心 | 付款后自动发货、评价后赠品、超时未评价提醒、失败任务恢复与幂等检查点 |
| 账号自动任务 | 账号级持续扫描待评价订单并统一好评、按北京时间每日擦亮、手动立即执行、执行记录与幂等保护 |
| 卡密库存 | 文本、批量卡密和图片三种交付类型,库存追加、批量导入、规格与延迟发送 |
| 商品管理 | 商品同步、手工关联、单商品发布、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. 初始化管理员
## 页面预览
![Ydisks闲鱼助手预览](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/preview_account.png)
![Ydisks闲鱼助手预览](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/preview_im.png)
![Ydisks闲鱼助手预览](https://raw.githubusercontent.com/Christ9038/Ydisks-Xianyu-Helper/main/docs/img/preview_auto.png)
## 快速开始
### 方式一: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
```
前端资源会在构建时通过 Go 的 `//go:embed` 嵌入服务;如果服务已经在运行,构建完成后
需要重启 Go 服务,浏览器硬刷新本身不会替换运行中进程已加载的前端资源。
初始化管理员:
```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. 在“在线聊天”按账号查看历史会话、发送文本/表情/图片;官方交易卡片和闲小蜜消息会以系统消息显示,不会进入普通用户回复链。
8. 在“账号管理 → 自动评价与每日擦亮”按账号配置统一评价文案、评价开关和擦亮时间;确认测试账号行为后再启用。
9. 按需配置关键词回复、默认回复、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 回复策略
- **账号自动任务**:自动评价开关、统一好评文案(最多 500 个字符)、每日擦亮开关、北京时间执行时间和最近执行记录
- **自动化规则**:触发条件、商品、规格、卡密组、发送数量、延迟和后续动作
- **回复规则**:关键词、文本或图片回复、默认回复及回复次数限制
- **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:latest
├── 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` | 调试日志 |
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
## 质量门禁与测试
当前 Docker 发布工作流只在 `main` 分支推送和发布镜像;`dev` 分支不会自动生成
GHCR 标签。开发分支如需验证镜像,请在本地使用源码构建 Compose 文件,或手动运行
对应的构建流程。
项目内置 Makefile 与 golangci-lint 配置:
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
### 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)。分发原始或衍生作品时,请保留这两个
文件中的适用声明,并在修改过的文件中显著标注修改。
## 免责声明
本项目仅提供技术研究和自托管管理能力,不保证对闲鱼接口变化、账号风控策略、业务
连续性或数据完整性的长期兼容。因使用本项目造成的账号限制、交易纠纷、数据损失或
其他直接与间接损失,应由使用者自行承担。请勿将本项目用于垃圾消息、欺诈、未授权
访问、规避平台限制或任何违法违规活动。
+84 -35
View File
@@ -7,8 +7,10 @@ package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"strings"
@@ -32,93 +34,140 @@ func main() {
resolved = *dbPath
}
ctx := context.Background()
if err := run(context.Background(), resolved, bufio.NewReader(os.Stdin), os.Stdout); err != nil {
fatalf("初始化管理员失败: %v", err)
}
}
// run 执行一次初始化流程。把数据库、输入和输出显式注入后,CLI 的核心行为
// 可以在临时数据库中回归测试,而不会调用 os.Exit 或污染用户数据。
func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writer) error {
database, dialect, err := db.Open(ctx, resolved)
if err != nil {
fatalf("打开数据库失败: %v", err)
return fmt.Errorf("打开数据库失败: %w", err)
}
defer database.Close()
store := db.NewStore(database, dialect)
reader := bufio.NewReader(os.Stdin)
existing, err := store.Users.GetAdmin(ctx)
if err != nil && !isNotFound(err) {
fatalf("查询 admin 失败: %v", err)
return fmt.Errorf("查询 admin 失败: %w", err)
}
if existing != nil {
fmt.Printf("管理员用户 %s 已存在\n", existing.Username)
fmt.Print("是否重置管理员密码?(y/N): ")
if _, err := fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username); err != nil {
return err
}
if _, err := fmt.Fprint(out, "是否重置管理员密码?(y/N): "); err != nil {
return err
}
ans, _ := reader.ReadString('\n')
if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") {
fmt.Println("跳过初始化")
return
if _, err := fmt.Fprintln(out, "跳过初始化"); err != nil {
return err
}
return nil
}
pw, err := promptPasswordTwice(reader, out)
if err != nil {
return fmt.Errorf("读取密码失败: %w", err)
}
pw := promptPasswordTwice(reader)
if _, err := auth.InitAdmin(ctx, store, "", pw); err != nil {
fatalf("重置 admin 密码失败: %v", err)
return fmt.Errorf("重置 admin 密码失败: %w", err)
}
fmt.Printf("重置完成:已更新 %s 的密码\n", existing.Username)
return
if _, err := fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username); err != nil {
return err
}
return nil
}
fmt.Println("=== 初始化管理员账号(CLI)===")
fmt.Print("请输入管理员邮箱: ")
if _, err := fmt.Fprintln(out, "=== 初始化管理员账号(CLI)==="); err != nil {
return err
}
if _, err := fmt.Fprint(out, "请输入管理员邮箱: "); err != nil {
return err
}
email, _ := reader.ReadString('\n')
email = strings.TrimSpace(email)
if email == "" {
fatalf("邮箱不能为空")
return errors.New("邮箱不能为空")
}
pw, err := promptPasswordTwice(reader, out)
if err != nil {
return fmt.Errorf("读取密码失败: %w", err)
}
pw := promptPasswordTwice(reader)
created, err := auth.InitAdmin(ctx, store, email, pw)
if err != nil {
fatalf("创建 admin 用户失败:%v", err)
return fmt.Errorf("创建 admin 用户失败:%w", err)
}
if created {
fmt.Println("初始化完成:已创建 admin 用户")
if _, err := fmt.Fprintln(out, "初始化完成:已创建 admin 用户"); err != nil {
return err
}
}
return nil
}
// promptPasswordTwice 两次输入密码(不回显)并校验一致性。
func promptPasswordTwice(reader *bufio.Reader) string {
func promptPasswordTwice(reader *bufio.Reader, out io.Writer) (string, error) {
for {
p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ")
p1, err := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out)
if err != nil {
return "", err
}
if p1 == "" {
fmt.Println("密码不能为空")
if _, err := fmt.Fprintln(out, "密码不能为空"); err != nil {
return "", err
}
continue
}
p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ")
p2, err := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out)
if err != nil {
return "", err
}
if p1 != p2 {
fmt.Println("两次输入不一致,请重试")
if _, err := fmt.Fprintln(out, "两次输入不一致,请重试"); err != nil {
return "", err
}
continue
}
return p1
return p1, nil
}
}
// readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道),
// 共用同一 bufio.Reader 避免缓冲吞掉后续输入。
func readPasswordNoEcho(reader *bufio.Reader, prompt string) string {
fmt.Print(prompt)
func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) (string, error) {
if _, err := fmt.Fprint(out, prompt); err != nil {
return "", err
}
if term.IsTerminal(int(os.Stdin.Fd())) {
b, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
if err != nil {
fatalf("读取密码失败: %v", err)
return "", err
}
return strings.TrimSpace(string(b))
if _, err := fmt.Fprintln(out); err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}
// 非 TTY 回退:共用传入的 reader。
s, _ := reader.ReadString('\n')
fmt.Println()
return strings.TrimSpace(s)
s, err := reader.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
return "", err
}
if _, err := fmt.Fprintln(out); err != nil {
return "", err
}
return strings.TrimSpace(s), nil
}
func isNotFound(err error) bool { return err == db.ErrNotFound }
func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) }
func fatalf(format string, a ...any) {
fmt.Fprintf(os.Stderr, format+"\n", a...)
if _, err := fmt.Fprintf(os.Stderr, format+"\n", a...); err != nil {
os.Exit(1)
}
os.Exit(1)
}
+106
View File
@@ -0,0 +1,106 @@
package main
import (
"bufio"
"bytes"
"context"
"flag"
"io"
"os"
"path/filepath"
"strings"
"testing"
"xianyu-go/internal/db"
)
func TestRunCreatesAdminInTemporaryDatabase(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
var out bytes.Buffer
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nsecret\nsecret\n")), &out)
if err != nil {
t.Fatalf("run create: %v", err)
}
if !strings.Contains(out.String(), "初始化完成") {
t.Fatalf("missing create confirmation: %s", out.String())
}
d, dialect, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatal(err)
}
defer d.Close()
admin, err := db.NewStore(d, dialect).Users.GetAdmin(context.Background())
if err != nil || admin == nil || admin.Email != "admin@example.com" {
t.Fatalf("admin=%+v err=%v", admin, err)
}
}
func TestRunExistingAdminCanSkipReset(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
input := "admin@example.com\nsecret\nsecret\n"
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("n\n")), &out); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "跳过初始化") {
t.Fatalf("missing skip confirmation: %s", out.String())
}
}
func TestRunExistingAdminResetsPasswordAfterMismatchRetry(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("admin@example.com\nold\nold\n")), &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
input := "y\nnew\nnot-the-same\nnew\nnew\n"
if err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader(input)), &bytes.Buffer{}); err != nil {
t.Fatal(err)
}
d, dialect, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatal(err)
}
defer d.Close()
store := db.NewStore(d, dialect)
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "old"); ok {
t.Fatal("old password should be invalid")
}
if _, ok, _ := store.Users.VerifyAndUpgrade(context.Background(), "admin", "new"); !ok {
t.Fatal("new password should be valid")
}
}
func TestRunRejectsEmptyEmail(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "init-admin.db")
err := run(context.Background(), dbPath, bufio.NewReader(strings.NewReader("\n")), &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), "邮箱不能为空") {
t.Fatalf("err=%v, want empty email error", err)
}
}
func TestMainCLIEntrypointUsesDatabaseFlag(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "main.db")
stdin, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
oldArgs, oldStdin, oldEnv, oldCommandLine := os.Args, os.Stdin, os.Getenv("DATABASE_URL"), flag.CommandLine
defer func() {
os.Args, os.Stdin, flag.CommandLine = oldArgs, oldStdin, oldCommandLine
_ = os.Setenv("DATABASE_URL", oldEnv)
_ = stdin.Close()
}()
os.Args = []string{"init-admin", "-db", dbPath}
os.Stdin = stdin
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
flag.CommandLine.SetOutput(io.Discard)
_ = os.Unsetenv("DATABASE_URL")
go func() {
_, _ = writer.Write([]byte("admin@example.com\nmain-secret\nmain-secret\n"))
_ = writer.Close()
}()
main()
}
+43 -3
View File
@@ -14,6 +14,7 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
@@ -27,6 +28,7 @@ import (
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
"xianyu-go/internal/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/logging"
"xianyu-go/internal/notify"
@@ -45,6 +47,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 +122,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 {
@@ -137,6 +150,8 @@ func main() {
}
var mgr *account.Manager
ap := adapter.New(store, bm, logger)
chatService := chat.New(store)
ap.SetChatService(chatService)
mgr = account.NewManager(store, ap, logger)
autoCenter := automation.New(store, mgr, logger)
autoCenter.SetOrderDetailFetcher(ap)
@@ -148,15 +163,22 @@ func main() {
if err := mgr.StartAll(ctx); err != nil {
logger.Error("启动账号引擎失败", "err", err)
}
go automation.NewScheduler(autoCenter).Run(ctx)
go renewal.NewScheduler(store, mgr, ap, logger).Run(ctx)
automationScheduler := automation.NewScheduler(autoCenter)
go automationScheduler.Run(ctx)
renewalScheduler := renewal.NewScheduler(store, mgr, ap, logger, notifier)
go renewalScheduler.Run(ctx)
// 3) HTTP 服务。
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
go srv.RunPublishBatchRecovery(ctx)
srv.SetChatService(chatService)
srv.StartPublishBatchRecovery(ctx)
if err := srv.Run(ctx); err != nil {
logger.Error("HTTP 服务退出", "err", err)
// 即便出错也尝试清理已启动的账号与浏览器。
cancel()
srv.WaitForBackground()
automationScheduler.Wait()
renewalScheduler.Wait()
mgr.StopAll()
if bm != nil {
_ = bm.Close()
@@ -164,6 +186,9 @@ func main() {
os.Exit(1)
}
// HTTP 服务正常退出(ctx 取消触发 Shutdown):停账号引擎、关浏览器。
srv.WaitForBackground()
automationScheduler.Wait()
renewalScheduler.Wait()
mgr.StopAll()
if bm != nil {
_ = bm.Close()
@@ -184,3 +209,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
}
+34
View File
@@ -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
View File
@@ -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:
+2 -5
View File
@@ -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
+11 -11
View File
@@ -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:
+1
View File
@@ -0,0 +1 @@
xianyu.ydisks.com
+8
View File
@@ -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: 379 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 473 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 728 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+1324
View File
File diff suppressed because it is too large. Load diff
+6 -3
View File
@@ -1,8 +1,11 @@
# 登录续期与风控能力补齐计划
# 登录续期与风控能力实施记录
> 本文最初是实施计划。当前列出的五个阶段均已落地;后续协议变化应以实际代码、测试和
> 本文的实施记录为准,不应把“目标流程”误读为尚未实现的功能。
## 目标
参考 `zhinianboke/xianyu-auto-reply` 的实现,把当前项目缺少的登录态续期、MTOP 风控识别、扫码人脸验证能力补齐。改造重点是提升账号长期在线能力和风控状态的可恢复性,同时保持 `xianyu-go` 现有单进程架构清晰、可测试、可回滚。
参考 `zhinianboke/xianyu-auto-reply` 的实现,把当前项目缺少的登录态续期、MTOP 风控识别、扫码人脸验证能力补齐。改造重点是提升账号长期在线能力和风控状态的可恢复性,同时保持 `Ydisks-Xianyu-Helper` 现有单进程架构清晰、可测试、可回滚。
## 非目标
@@ -108,7 +111,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% 抖动,降低多账号同时重连造成的风控压力。
+46
View File
@@ -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 和通知配置不可读取。恢复后先禁用高风险自动化,用测试订单逐项确认。
+37
View File
@@ -0,0 +1,37 @@
# Ydisks闲鱼助手 Wiki
本 Wiki 面向管理后台操作人员。先完成“部署与数据库”和“账号接入”,再配置库存、商品、
在线聊天、账号自动任务、交易自动化与 AI。
## 推荐上线路径
1. 选择并启动数据库;生产环境推荐 PostgreSQL。
2. 设置并备份 `XIANYU_DATA_KEY`,初始化管理员后登录后台。
3. 在“账号管理”扫码接入账号,确认账号为启用且在线状态。
4. 在“卡密库存”建立可交付内容。
5. 同步已有商品,或通过“商品管理”发布商品。
6. 在“在线聊天”确认账号会话和历史消息正常,必要时发送测试文本或图片。
7. 在“账号自动任务”配置自动评价和每日擦亮;在“自动化规则”建立付款发货、评价赠品或求评价规则。
8. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
9. 建立通知渠道并绑定到账号;用测试通知验证。
10. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
## 先读这些页面
- [部署与数据库](部署与数据库)
- [账号、库存与商品](账号、库存与商品)
- [在线聊天与账号自动任务](在线聊天与账号自动任务)
- [批量铺货](批量铺货)
- [自动化发货与回复](自动化发货与回复)
- [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 中审阅和版本化维护。
+9
View File
@@ -0,0 +1,9 @@
### Ydisks闲鱼助手
- [首页](Home)
- [部署与数据库](部署与数据库)
- [账号、库存与商品](账号、库存与商品)
- [在线聊天与账号自动任务](在线聊天与账号自动任务)
- [批量铺货](批量铺货)
- [自动化发货与回复](自动化发货与回复)
- [AI、通知与运维](AI、通知与运维)
@@ -0,0 +1,62 @@
# 在线聊天与账号自动任务
## 在线聊天
进入“在线聊天”后,顶部按账号显示 Tab;每个账号拥有独立的会话列表和消息状态。下方是标准两栏布局:左侧为会话列表,右侧为当前会话消息窗口。
聊天功能包括:
- 会话联系人、头像、昵称、用户 ID、商品摘要和未读数;列表按闲鱼会话最后消息时间倒序。
- 进入会话后优先读取本地缓存,再从闲鱼历史消息接口补齐记录;底部可继续加载更早消息和更多历史联系人。
- 文本消息、闲鱼文字表情和图片发送。当前不支持从管理后台发送视频,因此界面不提供视频发送按钮。
- 发送方按“对方/我”区分,并显示对应头像;账号之间的会话和实时消息完全隔离。
- 应用使用后端 `/api/chat/ws` 推送实时事件;刷新或重连后仍以历史接口和本地数据库为准,不只依赖 WebSocket 存续期间收到的消息。
### 官方消息识别
闲鱼的交易卡片和平台通知不能当作普通用户消息处理。当前按协议元数据识别:
- `contentType=14`:平台通知类消息;
- `contentType=26`:交易卡片;
- 发送方用户 ID `1400`:闲小蜜;
- “发来一条新消息”:官方通知占位内容。
识别出的消息不会进入关键词、默认回复或 AI 回复链,并在聊天窗口中以居中的系统消息卡片展示。联系人分页返回的空会话壳不会导入列表,避免出现只有“暂无消息”的伪联系人。
如果昵称或头像缺失,点击会话列表刷新按钮;系统联系人闲小蜜使用平台头像和固定名称,不应把订单卡片标题当成用户昵称。
## 账号自动评价
入口为“账号管理 → 自动评价与每日擦亮”。自动评价是账号级开关,不针对不同买家配置不同文案:
1. 开启“自动评价”;
2. 填写统一好评文案,最多 500 个字符;
3. 保存后,后台持续扫描该账号的待评价订单;
4. 每个待评价订单按交易订单 ID 幂等执行,已经处理过的订单不会重复评价。
它不是每日任务。可以点击“立即评价”执行一次扫描,也可以依赖后台持续扫描。账号停用或暂停时不会执行。
## 每日自动擦亮
每日擦亮同样是账号级开关,但与自动评价不同:
- 按北京时间判断执行时间;
- 每个账号每天最多执行一次;
- 默认执行时间为 `03:00`,可在 `HH:mm` 范围内调整;
- 后台调用商品列表接口并逐个执行擦亮;当前实现按每页 20 条、最多 20 页读取商品;
- 可以点击“立即擦亮”手动触发,但当天已成功执行时会被幂等保护跳过;
- 页面会显示最近完成时间、本次发现数量、成功数、失败数和跳过数。
如果执行中部分商品失败,任务会记录失败原因并进入可重试状态;不要仅根据按钮返回就判断所有商品都已成功,应该查看本次执行结果。
## 与交易自动化的边界
“账号自动评价/每日擦亮”处理账号级任务;“自动化规则”处理订单和聊天触发的业务规则:
- 付款后自动发货;
- 评价后发送赠品;
- 超时未评价求评价;
- 关键词回复、默认回复和 AI 回复。
闲鱼官方系统消息只用于平台事件识别,不应被配置为普通买家关键词触发自动回复。
+62
View File
@@ -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、账号归属、启用列和库存;发布成功后仍应查看自动化规则是否已创建。
- **任务中断**:先重新打开批次详情确认状态,避免重复新建整批任务;仅重试失败行。
+49
View File
@@ -0,0 +1,49 @@
# 自动化发货与回复
## 自动化的三种触发器
| 触发器 | 触发时机 | 标准流程 |
| --- | --- | --- |
| 付款后自动发货 | 收到付款系统卡片 | 匹配商品/规格 → 发送卡密 → 成功后确认发货。 |
| 评价后发送赠品 | 收到评价系统卡片 | 匹配商品/规格 → 发送赠品卡密。 |
| 超时未评价求评价 | 定时扫描已发货未评价订单 | 到达等待时间 → 发送提醒文案。 |
系统通知卡片只进入自动化判断;买家普通消息走关键词、默认回复和 AI 规则。
账号级自动评价和每日擦亮不属于上表的订单规则,配置入口在“账号管理 → 自动评价与每日擦亮”,执行方式见[在线聊天与账号自动任务](在线聊天与账号自动任务)。
## 配置付款自动发货
前提:账号在线、商品已同步、卡密组已建立且有库存。
1. 进入“自动化规则”,选择“付款后自动发货”,点击新增。
2. 设置规则名称,选择目标账号和商品;商品有规格时为每个需要交付的规格建立对应配置。
3. 添加“发送卡密”动作,选择卡密库存、每件发送数量与是否启用。
4. 如需覆盖卡密组默认延迟,打开延迟覆盖并填写秒数;否则使用卡密组的默认延时。
5. 保存并确认规则处于启用状态。
6. 用测试订单确认:卡密内容已发送、卡密库存扣减正确、随后才确认发货。
按购买数量发货:动作中的“每件发送数量”会乘以订单购买数量。不要把每单总量误填为每件数量。
## 配置评价赠品与求评价
评价赠品的配置与付款发货相同,但触发器选择“评价后发送赠品”。赠品应使用独立卡密组,便于核对和补货。
配置求评价:
1. 新建“超时未评价求评价”规则,选择账号和商品。
2. 填写等待时间(发货后多少小时开始检查)、重复间隔及最多提醒次数。
3. 填写发送给买家的求评价文案,保存并启用。
4. 在测试订单上确认不会提前发送;达到最大次数后不再重复提醒。
## 异常处理与补发
“自动化规则”页面的异常区会列出可处理的自动化运行和延迟任务。先查看订单、库存、聊天记录和失败原因,再使用页面的“处理/解决”操作。不要在不确定已发货状态时直接重试,以免重复发卡。
需要人工补发时,在订单管理中定位订单,确认买家、商品和历史交付记录,再使用手动发货/补发能力。处理后记录原因并检查库存。
## 关键词与默认回复
在“自动化规则”的“关键词回复”页:选择账号 → 新增规则 → 填写关键词与文本或图片 URL → 保存。关键词规则用于买家普通消息。
“账号默认回复”只在关键词和 AI 都未处理该消息时使用。可设置文本、图片 URL 和“同一会话只回复一次”。上线前避免关键词、默认回复和 AI 提示词对同类问题给出互相矛盾的答案。
+45
View File
@@ -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. 先用测试订单验证,检查订单列表、自动化异常列表和通知记录。
+84
View File
@@ -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
View File
@@ -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 已知(或已标注需运营补填)
+20 -9
View File
@@ -8,6 +8,8 @@ import ItemList from './components/ItemList';
import Settings from './components/Settings';
import Rules from './components/Rules';
import Notifications from './components/Notifications';
import Chat from './components/Chat';
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
import { YdisksBrandIcon } from './components/YdisksLogo';
import { login, logout, verifySession } from './services/api';
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
@@ -24,6 +26,7 @@ interface DeliveryRuleTarget {
const ROUTES: Record<string, string> = {
'/app/dashboard': 'dashboard',
'/app/accounts': 'accounts',
'/app/chat': 'chat',
'/app/orders': 'orders',
'/app/cards': 'cards',
'/app/items': 'items',
@@ -50,6 +53,7 @@ const App: React.FC = () => {
const [loginLoading, setLoginLoading] = useState(false);
const [loginError, setLoginError] = useState('');
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>();
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
const navigate = (tab: string) => {
@@ -143,8 +147,8 @@ const App: React.FC = () => {
if (checkingAuth) {
return (
<div className="min-h-screen flex items-center justify-center bg-[#f5f5f7]">
<Loader2 className="w-8 h-8 text-[#0094f7] animate-spin" />
<div className="min-h-screen flex items-center justify-center bg-surface">
<Loader2 className="w-8 h-8 text-brand animate-spin" />
</div>
);
}
@@ -152,11 +156,11 @@ const App: React.FC = () => {
// Init Screen (system not initialized)
if (needsInit) {
return (
<div className="min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans">
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in">
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-xl border border-white relative z-10 animate-fade-in">
<div className="text-center mb-8">
<div className="mx-auto mb-6 flex justify-center">
<YdisksBrandIcon sizeClass="w-24 h-24" />
@@ -194,12 +198,12 @@ const App: React.FC = () => {
// Login Screen Component
if (!isLoggedIn) {
return (
<div className="min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans">
<div className="min-h-screen flex items-center justify-center bg-canvas p-4 relative overflow-hidden font-sans">
{/* Animated Background Blobs */}
<div className="absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse" style={{animationDelay: '2s'}}></div>
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in">
<div className="bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-panel w-full max-w-lg border border-white relative z-10 animate-fade-in">
{/* Header with Logo */}
<div className="text-center mb-10">
@@ -266,6 +270,7 @@ const App: React.FC = () => {
switch (activeTab) {
case 'dashboard': return <Dashboard />;
case 'accounts': return <AccountList />;
case 'chat': return <Chat />;
case 'orders': return <OrderList />;
case 'cards': return <CardList />;
case 'items': return <ItemList onConfigureDelivery={(item) => {
@@ -283,19 +288,25 @@ const App: React.FC = () => {
};
return (
<div className="flex min-h-screen bg-[#F4F5F7] text-[#111]">
<div className="flex min-h-screen bg-canvas text-ink">
<Sidebar
activeTab={activeTab}
isAdmin={isAdmin}
collapsed={sidebarCollapsed}
onToggleCollapsed={() => setSidebarCollapsed(current => {
const next = !current;
writeSidebarCollapsed(next);
return next;
})}
onNavigate={navigate}
onLogout={handleLogout}
/>
<main className="flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth">
<main className={`h-screen min-w-0 flex-1 overflow-x-hidden overflow-y-auto scroll-smooth transition-[margin] duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-64'} ${activeTab === 'chat' ? 'p-4 md:p-6' : 'p-8 md:p-12'}`}>
{/* Subtle background decoration */}
<div className="fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"></div>
<div className="max-w-[1400px] mx-auto pb-10">
<div className={`${activeTab === 'chat' ? 'mx-auto max-w-[1680px]' : 'mx-auto max-w-[1400px] pb-10'}`}>
{renderContent()}
</div>
</main>
+18 -6
View File
@@ -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
```
@@ -33,15 +33,27 @@ npm run build
```
产物写入 `../internal/webui/static/`,由 Go 服务通过 `//go:embed` 内嵌并服务于 `/static/*`。
生产部署无需单独分发前端,构建一次即可。
生产部署无需单独分发前端。若 Go 服务已经运行,构建完成后必须重启 Go 服务,
因为嵌入资源在 Go 编译时写入服务二进制;仅刷新浏览器不会更新已运行进程中的前端版本。
## Dashboard 图表约定
Dashboard 的营收趋势柱状图使用统一的品牌蓝 `#0094f7` 表示同一指标序列,日期之间
只通过柱高区分营收,不使用不同颜色表达不同类别。饼图使用中心汇总值、图例和悬浮提示
展示明细;悬停扇区会轻微放大。图表是展示型组件,点击或键盘焦点不会显示浏览器默认
的粗蓝色 SVG 焦点框,避免被误解为业务选中状态。
## 路由
应用使用 `window.history.pushState` 做 tab 导航,路径形如 `/app/dashboard`、`/app/rules`、`/app/settings`。
应用使用 `window.history.pushState` 做 tab 导航,路径包括 `/app/dashboard`、`/app/accounts`、
`/app/chat`、`/app/cards`、`/app/items`、`/app/orders`、`/app/rules`、
`/app/notifications` 和管理员可见的 `/app/settings`。
未登录时显示登录表单(客户端状态,非独立路由)。后端 SPA catch-all 对非 API 的 GET 请求返回 `index.html`,支持深链刷新。
## 测试
```bash
npx vitest run # 路由一致性、请求工具等单测
npm test # 前端单元测试
npm run typecheck # TypeScript 类型检查
npm run build # 构建并更新 Go 嵌入资源
```
+22
View File
@@ -0,0 +1,22 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, test } from 'vitest';
import { renderXianyuText, xianyuEmojis } from './chatEmojis';
describe('official Xianyu emoji mapping', () => {
test('contains the complete official panel in official order', () => {
expect(xianyuEmojis).toHaveLength(126);
expect(xianyuEmojis[0][0]).toBe('尊嘟假嘟');
expect(xianyuEmojis.at(-1)?.[0]).toBe('爱心');
expect(new Set(xianyuEmojis.map(([name]) => name)).size).toBe(126);
});
test('uses official CDN assets and renders bracket codes inline', () => {
for (const [, url] of xianyuEmojis) {
expect(url).toMatch(/^https:\/\/img\.alicdn\.com\//);
}
const html = renderToStaticMarkup(<>{renderXianyuText('你好[捂脸哭][送花]')}</>);
expect(html).toContain('你好');
expect(html).toContain('alt="[捂脸哭]"');
expect(html).toContain('alt="[送花]"');
});
});
+516
View File
@@ -0,0 +1,516 @@
import React from 'react';
export const xianyuEmojis = [
[
"尊嘟假嘟",
"https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"
],
[
"鸡哔你",
"https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"
],
[
"谁懂啊",
"https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"
],
[
"吗喽",
"https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"
],
[
"功德+1",
"https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"
],
[
"city不city啊",
"https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"
],
[
"激推",
"https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"
],
[
"微笑",
"https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"龇牙",
"https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"流泪",
"https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"尴尬",
"https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"撇嘴",
"https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"破涕为笑",
"https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"捂脸哭",
"https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"害羞",
"https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"感动",
"https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"滴泪",
"https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"暗中观察",
"https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"偷笑",
"https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"ok",
"https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"送花",
"https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"大哭",
"https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"色",
"https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"惊慌",
"https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"惊讶",
"https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"得意",
"https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"睡",
"https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"不好意思",
"https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"托腮",
"https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"发怒",
"https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"难过",
"https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"调皮",
"https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"愉快",
"https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"白眼",
"https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"拒绝",
"https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"期待",
"https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"困",
"https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"流汗",
"https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"憨笑",
"https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"耶",
"https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"奋斗",
"https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"咒骂",
"https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"疑问",
"https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"嘘",
"https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"晕",
"https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"开心到模糊",
"https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"衰",
"https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"委屈",
"https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"再见",
"https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"鼓掌",
"https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"吐",
"https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"坏笑",
"https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"抠鼻",
"https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"叹气",
"https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"无聊",
"https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"思考",
"https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"呆",
"https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"哇哦",
"https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"飞吻",
"https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"好喜欢",
"https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"拜托",
"https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"真棒",
"https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"流鼻血",
"https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"费解",
"https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"秃头",
"https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"嘿哈",
"https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"吃土",
"https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"机智",
"https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"举杯",
"https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"握手",
"https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"挥手",
"https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"yeah",
"https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"666",
"https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"棒",
"https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"爱你",
"https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"比心",
"https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"感谢",
"https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"拍手",
"https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"拉钩",
"https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"没钱",
"https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"小刀",
"https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"不刀",
"https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"同出",
"https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"递钱",
"https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"数钱",
"https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"打call",
"https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"号外",
"https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"包邮",
"https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"求赞",
"https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"非主流",
"https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"吃瓜",
"https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"种草",
"https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"佛系",
"https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"超便宜",
"https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"拥抱",
"https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"摊手",
"https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"举手",
"https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"蹲",
"https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"跪了",
"https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"拜",
"https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"排",
"https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"旺财",
"https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"招财猫",
"https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"酸了",
"https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"鸭鸭",
"https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"方了",
"https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"白菜",
"https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"桃子",
"https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"打包",
"https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"沙发",
"https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"南",
"https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"盯",
"https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"hot",
"https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"new",
"https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"cool",
"https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"1",
"https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"可",
"https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"搬砖",
"https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"菜狗",
"https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"开心面具",
"https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"快递",
"https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"裂开",
"https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"啤酒",
"https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"瑞思拜",
"https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"小丑",
"https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"
],
[
"爱心",
"https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"
]
] as const;
export const emojiURL = (url: string) => url;
const emojiLookup = new Map<string, string>(xianyuEmojis.map(([name, url]) => [name, url]));
export const renderXianyuText = (text: string) => text.split(/(\[[^\]]+\])/g).map((part, index) => {
const url = part.startsWith('[') ? emojiLookup.get(part.slice(1, -1)) : undefined;
return url ? <img key={index} src={url} alt={part} title={part} className="mx-0.5 inline-block h-7 w-7 align-middle" /> : <React.Fragment key={index}>{part}</React.Fragment>;
});
+61
View File
@@ -0,0 +1,61 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8');
describe('online chat UI contract', () => {
test('uses account tabs above a two-column buyer/chat layout', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('role="tablist"');
expect(chat).toContain('grid-cols-[320px_minmax(0,1fr)]');
expect(chat).toContain('min-h-0 min-w-0 flex-col overflow-hidden');
expect(chat).not.toContain('grid-cols-[320px_minmax(0,1fr)_');
expect(chat).toContain('activeAccountID');
expect(chat).toContain('activeChatID');
});
test('uses neutral user labels instead of assuming buyer role', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('用户 ID:');
expect(chat).not.toContain('买家 ID:');
expect(chat).not.toContain('选择一个买家');
});
test('frontend connects only to the application chat websocket', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('/api/chat/ws');
expect(chat).not.toContain('wss-goofish.dingtalk.com');
});
test('renders peer/self identity and verified media capabilities', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('selectedSession.buyer_avatar_url');
expect(chat).toContain('activeAccount?.avatar_url');
expect(chat).toContain("message.message_type === 'image'");
expect(chat).toContain("message.message_type === 'video'");
expect(chat).toContain('sendChatImage');
});
test('renders official notices as neutral system messages', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain("message.message_type === 'system'");
expect(chat).toContain('justify-center py-1');
});
test('keeps the active chat at the bottom when new messages arrive', () => {
const chat = source('components/Chat.tsx');
expect(chat).toContain('shouldScrollToBottomRef');
expect(chat).toContain('skipNextMessageScrollRef');
expect(chat).toContain('onScroll={handleMessageScroll}');
expect(chat).toContain('container.scrollHeight - container.scrollTop - container.clientHeight');
expect(chat).toContain('[activeAccountID, activeChatID, messages, messagesLoading]');
});
test('sidebar exposes collapse control and chat primary navigation', () => {
const sidebar = source('components/Sidebar.tsx');
expect(sidebar).toContain("id: 'chat'");
expect(sidebar).toContain('onToggleCollapsed');
expect(sidebar).toContain('collapsed ? \'w-16\' : \'w-64\'');
});
});
+36
View File
@@ -0,0 +1,36 @@
import { readdirSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
const componentsDir = resolve(__dirname, 'components');
const pageSources = [
resolve(__dirname, 'App.tsx'),
...readdirSync(componentsDir)
.filter((fileName) => fileName.endsWith('.tsx') && !fileName.endsWith('.test.tsx'))
.map((fileName) => resolve(componentsDir, fileName)),
];
// rgb(var(--color-*)), CSS classes and the central index.css are references.
// Literal colors in page code would bypass the design-token system.
const hardCodedColorPattern = /#[0-9a-f]{3,8}\b|rgba?\((?!var\(--color-)/gi;
describe('global color token contract', () => {
test('page components do not contain hard-coded color values', () => {
const violations = pageSources.flatMap((filePath) => {
const source = readFileSync(filePath, 'utf8');
return [...source.matchAll(hardCodedColorPattern)].map((match) => `${filePath}:${match[0]}`);
});
expect(violations).toEqual([]);
});
test('the primary brand and highlight colors are defined in the central stylesheet', () => {
const globalStyles = readFileSync(resolve(__dirname, 'index.css'), 'utf8');
expect(globalStyles).toContain('--color-brand: 0 148 247;');
expect(globalStyles).toContain('--color-brand-highlight: 0 113 227;');
expect(globalStyles).toContain('--color-success-500:');
expect(globalStyles).toContain('--color-warning-500:');
expect(globalStyles).toContain('--color-danger-500:');
});
});
@@ -0,0 +1,156 @@
import React, { useState } from 'react';
import { CalendarClock, Loader2, MessageSquareQuote, Play, Save, Sparkles, X } from 'lucide-react';
import { AccountDetail, AccountTaskSettings, AccountTaskSummary } from '../types';
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from '../services/api';
interface Props {
account: AccountDetail;
onClose: () => void;
onSaved: (settings: AccountTaskSettings) => void;
}
const Toggle: React.FC<{checked: boolean; onChange: () => void; label: string}> = ({ checked, onChange, label }) => (
<button type="button" aria-label={label} aria-pressed={checked} onClick={onChange}
className={`relative h-8 w-14 shrink-0 rounded-full transition-colors ${checked ? 'bg-sky-500' : 'bg-slate-300'}`}>
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${checked ? 'translate-x-6' : ''}`} />
</button>
);
const AccountAutomationModal: React.FC<Props> = ({ account, onClose, onSaved }) => {
const [form, setForm] = useState<AccountTaskSettings>({
account_id: account.id,
auto_rate_enabled: account.auto_rate_enabled === true,
rate_content: account.rate_content || '不错的买家,交易愉快',
auto_polish_enabled: account.auto_polish_enabled === true,
polish_time: account.polish_time || '03:00',
last_rate_scan_at: account.last_rate_scan_at,
last_polish_date: account.last_polish_date,
last_polish_at: account.last_polish_at,
});
const [saving, setSaving] = useState(false);
const [running, setRunning] = useState<'' | 'auto_rate' | 'auto_polish'>('');
const [error, setError] = useState('');
const [summary, setSummary] = useState<AccountTaskSummary | null>(null);
const save = async () => {
setSaving(true);
setError('');
try {
const stored = await updateAccountTaskSettings(account.id, form);
setForm(stored);
onSaved(stored);
} catch (saveError) {
setError(saveError instanceof Error ? saveError.message : '保存失败');
} finally {
setSaving(false);
}
};
const run = async (taskType: 'auto_rate' | 'auto_polish') => {
setRunning(taskType);
setError('');
setSummary(null);
try {
await updateAccountTaskSettings(account.id, form);
const result = await runAccountTask(account.id, taskType);
const stored = await getAccountTaskSettings(account.id);
setSummary(result.summary);
setForm(stored);
onSaved(stored);
} catch (runError) {
setError(runError instanceof Error ? runError.message : '任务执行失败');
} finally {
setRunning('');
}
};
return (
<div className="modal-overlay-centered">
<div className="modal-container" style={{ maxWidth: '640px' }} role="dialog" aria-modal="true" aria-labelledby="account-task-title">
<div className="modal-header">
<div>
<h3 id="account-task-title" className="text-2xl font-extrabold text-slate-950">账号自动任务</h3>
<p className="mt-1 text-sm text-slate-500">{account.nickname || account.remark || account.id}</p>
</div>
<button type="button" onClick={onClose} className="rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700" aria-label="关闭">
<X className="h-5 w-5" />
</button>
</div>
<div className="modal-body space-y-5">
<section className="rounded-2xl border border-slate-200 bg-white p-5">
<div className="flex items-start gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><MessageSquareQuote className="h-5 w-5" /></div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-4">
<div>
<h4 className="font-black text-slate-900">自动评价</h4>
<p className="mt-1 text-xs leading-5 text-slate-500">持续扫描待评价订单,按订单执行;不是每日任务。</p>
</div>
<Toggle checked={form.auto_rate_enabled} onChange={() => setForm(current => ({ ...current, auto_rate_enabled: !current.auto_rate_enabled }))} label="自动评价" />
</div>
<label className="mt-4 block text-xs font-extrabold text-slate-600">统一好评文案</label>
<textarea aria-label="统一好评文案" value={form.rate_content} maxLength={500} onChange={event => setForm(current => ({ ...current, rate_content: event.target.value }))}
className="mt-2 h-24 w-full resize-none rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm leading-6 text-slate-800 placeholder:text-slate-400 outline-none focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
<div className="mt-3 flex items-center justify-between gap-3">
<span className="text-xs text-slate-400">最近扫描:{form.last_rate_scan_at ? new Date(form.last_rate_scan_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</span>
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_rate')}
className="flex items-center gap-2 rounded-xl bg-emerald-50 px-3 py-2 text-xs font-extrabold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50">
{running === 'auto_rate' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}立即评价
</button>
</div>
</div>
</div>
</section>
<section className="rounded-2xl border border-slate-200 bg-white p-5">
<div className="flex items-start gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600"><Sparkles className="h-5 w-5" /></div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-4">
<div>
<h4 className="font-black text-slate-900">每日自动擦亮</h4>
<p className="mt-1 text-xs leading-5 text-slate-500">每个账号每天最多执行一次,按北京时间判断。</p>
</div>
<Toggle checked={form.auto_polish_enabled} onChange={() => setForm(current => ({ ...current, auto_polish_enabled: !current.auto_polish_enabled }))} label="每日自动擦亮" />
</div>
<div className="mt-4 flex items-end justify-between gap-4">
<label className="block">
<span className="text-xs font-extrabold text-slate-600">每日执行时间</span>
<input type="time" value={form.polish_time} onChange={event => setForm(current => ({ ...current, polish_time: event.target.value }))}
className="mt-2 block rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-bold text-slate-800 outline-none focus:border-sky-400" />
</label>
<button type="button" disabled={running !== '' || !account.enabled} onClick={() => void run('auto_polish')}
className="flex items-center gap-2 rounded-xl bg-amber-50 px-3 py-2 text-xs font-extrabold text-amber-700 hover:bg-amber-100 disabled:opacity-50">
{running === 'auto_polish' ? <Loader2 className="h-4 w-4 animate-spin" /> : <CalendarClock className="h-4 w-4" />}立即擦亮
</button>
</div>
<div className="mt-3 text-xs text-slate-400">上次完成:{form.last_polish_at ? new Date(form.last_polish_at * 1000).toLocaleString('zh-CN') : '尚未执行'}</div>
</div>
</div>
</section>
{summary && (
<div className="rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900">
本次发现 {summary.found} 项,成功 {summary.success},失败 {summary.failed},跳过 {summary.skipped}。{summary.message || ''}
</div>
)}
{error && <div className="rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm font-medium text-red-700">{error}</div>}
</div>
<div className="modal-footer">
<div className="flex w-full gap-3">
<button type="button" onClick={onClose} disabled={saving || running !== ''}
className="flex-1 rounded-xl bg-gray-100 px-6 py-3 font-bold text-gray-700 transition-colors hover:bg-gray-200 disabled:opacity-50">关闭</button>
<button type="button" onClick={() => void save()} disabled={saving || running !== '' || (form.auto_rate_enabled && !form.rate_content.trim())}
className="ios-btn-primary flex flex-1 items-center justify-center gap-2 rounded-xl px-6 py-3 font-bold disabled:opacity-50">
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}保存
</button>
</div>
</div>
</div>
</div>
);
};
export default AccountAutomationModal;
+197 -30
View File
@@ -27,7 +27,7 @@ import { shouldUpdateAccountPause } from './accountPause';
import {
Plus, Power, Edit2, Trash2, QrCode, X, Check, Loader2,
RefreshCw, Save, User, Clock, MessageCircle,
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell, CalendarClock, Sparkles
} from 'lucide-react';
import { buildAccountLoginInfoUpdate } from './accountEdit';
import { shouldSaveNotificationBindings } from './accountBindings';
@@ -35,6 +35,7 @@ import { mergeAccountRuntimeStatuses } from './accountRuntimeState';
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
import { RiskVerificationPanel } from './RiskVerificationPanel';
import { SquareQRCode } from './SquareQRCode';
import AccountAutomationModal from './AccountAutomationModal';
type ModalType = 'edit' | 'ai-settings' | null;
@@ -43,6 +44,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');
@@ -51,6 +55,7 @@ const AccountList: React.FC = () => {
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
const [activeModal, setActiveModal] = useState<ModalType>(null);
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
const [taskAccount, setTaskAccount] = useState<AccountDetail | null>(null);
const [longLogin, setLongLogin] = useState({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
// 通知渠道绑定(编辑弹窗用)
@@ -260,10 +265,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('');
}
};
@@ -651,7 +678,7 @@ const AccountList: React.FC = () => {
}
};
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-[#0094f7] animate-spin"/></div>;
if (loading) return <div className="p-20 flex justify-center"><Loader2 className="w-8 h-8 text-brand animate-spin"/></div>;
const filteredAccounts = accounts.filter(account => {
const keyword = accountSearch.trim().toLowerCase();
@@ -701,8 +728,8 @@ const AccountList: React.FC = () => {
const runtime = runtimePresentation(account);
const requiresLogin = account.runtime_state === 'auth_expired' || account.runtime_state === 'verification_required';
return (
<div key={account.id} className="ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300">
<div className="flex items-center gap-5 sm:gap-8 min-w-0">
<div key={account.id} className="ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand">
<div className="flex min-w-0 items-start gap-5 sm:gap-8">
<div className="relative">
{account.avatar_url ? (
<img
@@ -719,8 +746,8 @@ const AccountList: React.FC = () => {
{account.runtime_state === 'online' && <Check className="w-3 h-3 text-white" />}
</div>
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-3 mb-1">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2.5 mb-1">
<h3 className="text-xl font-extrabold text-gray-900 break-words">{account.nickname || account.remark || `账号 ${account.id.substring(0,6)}...`}</h3>
<span className={`px-2.5 py-0.5 rounded-lg text-xs font-bold ${runtime.badge}`}>{runtime.label}</span>
{account.ai_enabled && (
@@ -728,6 +755,17 @@ const AccountList: React.FC = () => {
<Bot className="w-3 h-3" /> AI
</span>
)}
{account.auto_rate_enabled && (
<span className="flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700">
<MessageCircle className="h-3 w-3" /> 自动评价
</span>
)}
{account.auto_polish_enabled && (
<span className="flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700">
<Sparkles className="h-3 w-3" /> 每日擦亮
</span>
)}
{account.auto_confirm && <span className="flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700"><Check className="h-3 w-3" /> 自动确认发货</span>}
{account.profile_error && (
<span
className="px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1"
@@ -737,10 +775,11 @@ const AccountList: React.FC = () => {
</span>
)}
</div>
<div className="text-sm text-gray-500 font-medium mb-3 space-y-1">
<div className="mt-3 flex flex-wrap items-center justify-between gap-4">
<div className="text-sm font-medium text-gray-500">
<p>{account.remark || account.note || '暂无备注'}</p>
<p className="font-mono text-xs text-gray-400">ID: {account.id}</p>
</div>
</div>
{account.runtime_message && account.runtime_state !== 'online' && account.runtime_state !== 'disabled' && (
<div className={`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${requiresLogin ? 'text-red-700' : 'text-amber-700'}`}>
<AlertCircle className="w-4 h-4 flex-shrink-0" />
@@ -756,13 +795,8 @@ const AccountList: React.FC = () => {
)}
</div>
)}
<div className="flex gap-2">
{account.auto_confirm && <span className="text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5"><Check className="w-3 h-3"/> 自动确认发货</span>}
{account.paused && <span className="text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5"><Clock className="w-3 h-3"/> 暂停处理中</span>}
</div>
</div>
</div>
<div className="flex items-center gap-3 self-end lg:self-auto flex-shrink-0">
{account.paused && <span className="flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700"><Clock className="h-3 w-3" /> 暂停处理中</span>}
<div className="mt-3 flex flex-wrap items-center justify-end gap-2">
<button
onClick={() => handleRefreshProfile(account)}
disabled={refreshingProfileId === account.id}
@@ -792,6 +826,13 @@ const AccountList: React.FC = () => {
>
<Bot className="w-5 h-5" />
</button>
<button
onClick={() => setTaskAccount(account)}
className="p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600"
title="自动评价与每日擦亮"
>
<CalendarClock className="w-5 h-5" />
</button>
<button
onClick={() => handleToggle(account.id, account.enabled)}
className={`p-3 rounded-xl transition-colors ${account.enabled ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-100'}`}
@@ -800,13 +841,20 @@ 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>
</div>
</div>
</div>
)})}
{accounts.length === 0 && (
@@ -826,6 +874,125 @@ const AccountList: React.FC = () => {
)}
</div>
{taskAccount && createPortal(
<AccountAutomationModal
account={taskAccount}
onClose={() => setTaskAccount(null)}
onSaved={settings => {
setAccounts(current => current.map(account => account.id === taskAccount.id ? {
...account,
auto_rate_enabled: settings.auto_rate_enabled,
rate_content: settings.rate_content,
auto_polish_enabled: settings.auto_polish_enabled,
polish_time: settings.polish_time,
last_rate_scan_at: settings.last_rate_scan_at,
last_polish_date: settings.last_polish_date,
last_polish_at: settings.last_polish_at,
} : account));
}}
/>,
document.body
)}
{/* 删除账号确认弹窗 */}
{deleteDialogAccount && createPortal(
<div className="modal-overlay-centered" role="presentation">
<div
className="h-fit w-full max-w-[400px] self-center overflow-hidden rounded-2xl border border-white/80 bg-white shadow-modal"
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-brand" />
<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">
@@ -848,8 +1015,8 @@ const AccountList: React.FC = () => {
: '请打开闲鱼APP扫描下方二维码'}
</p>
<div className={`w-full bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${qrStatus === 'verification' ? 'max-w-72 min-h-64 h-auto p-2' : 'max-w-64 aspect-square'}`}>
{qrStatus === 'loading' && <Loader2 className="w-10 h-10 text-[#0094f7] animate-spin" />}
<div className={`w-full bg-surface-subtle rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${qrStatus === 'verification' ? 'max-w-72 min-h-64 h-auto p-2' : 'max-w-64 aspect-square'}`}>
{qrStatus === 'loading' && <Loader2 className="w-10 h-10 text-brand animate-spin" />}
{qrStatus === 'waiting' && <SquareQRCode src={qrCodeUrl} alt="闲鱼登录二维码" className="p-2" />}
{qrStatus === 'success' && (
<div className="absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in">
@@ -944,7 +1111,7 @@ const AccountList: React.FC = () => {
type="button"
onClick={() => setEditForm({ ...editForm, auto_confirm: !editForm.auto_confirm })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.auto_confirm ? 'bg-[#0094f7]' : 'bg-gray-300'
editForm.auto_confirm ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
@@ -1001,7 +1168,7 @@ const AccountList: React.FC = () => {
aria-label="保存登录信息"
disabled={longLogin.loading || longLogin.saving || !longLogin.canOpen}
onClick={() => void handleLongLoginToggle()}
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-brand' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
>
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${longLogin.enabled ? 'translate-x-6' : 'translate-x-0'}`} />
</button>
@@ -1039,7 +1206,7 @@ const AccountList: React.FC = () => {
type="checkbox"
checked={editForm.clear_password}
onChange={(e) => setEditForm({ ...editForm, clear_password: e.target.checked, login_password: e.target.checked ? '' : editForm.login_password })}
className="w-4 h-4 accent-[#0094f7]"
className="w-4 h-4 accent-brand"
/>
<span className="text-sm font-bold text-gray-700">清空已保存密码</span>
</label>
@@ -1053,7 +1220,7 @@ const AccountList: React.FC = () => {
type="button"
onClick={() => setEditForm({ ...editForm, show_browser: !editForm.show_browser })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.show_browser ? 'bg-[#0094f7]' : 'bg-gray-300'
editForm.show_browser ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
@@ -1135,7 +1302,7 @@ const AccountList: React.FC = () => {
}}
disabled={!bindingsLoaded}
className={`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${
checked ? 'bg-[#0094f7] border-[#0094f7]' : 'bg-white border-gray-300'
checked ? 'bg-brand border-brand' : 'bg-white border-gray-300'
}`}
>
{checked && <Check className="w-3.5 h-3.5 text-white" />}
@@ -1210,7 +1377,7 @@ const AccountList: React.FC = () => {
type="button"
onClick={() => setAiSettings({ ...aiSettings, ai_enabled: !aiSettings.ai_enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
aiSettings.ai_enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
aiSettings.ai_enabled ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
+9 -9
View File
@@ -313,7 +313,7 @@ const CardList: React.FC = () => {
</div>
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
<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">
<div className="flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-1 flex-col gap-3 sm:flex-row">
<div className="relative sm:w-48">
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
@@ -375,7 +375,7 @@ const CardList: React.FC = () => {
}
return (
<tr key={card.id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
<tr key={card.id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-5 py-5 align-middle">
<div className="flex items-center gap-2.5">
<div className="shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white">
@@ -667,7 +667,7 @@ const CardList: React.FC = () => {
type="button"
onClick={() => setEditForm({ ...editForm, enabled: !editForm.enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${
editForm.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
editForm.enabled ? 'bg-brand' : 'bg-gray-300'
}`}
>
<span
@@ -739,7 +739,7 @@ const CardList: React.FC = () => {
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'data', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'data' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'data' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
>
<CreditCard className="w-5 h-5 mx-auto mb-1" />
批量库存
@@ -747,7 +747,7 @@ const CardList: React.FC = () => {
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'text', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'text' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600'}`}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'text' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<FileText className="w-5 h-5 mx-auto mb-1" />
文本
@@ -755,7 +755,7 @@ const CardList: React.FC = () => {
<button
type="button"
onClick={() => setAddForm({ ...addForm, type: 'image', content: '' })}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'image' ? 'bg-[#0094f7] text-white' : 'bg-gray-100 text-gray-600'}`}
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'image' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600'}`}
>
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
图片
@@ -792,7 +792,7 @@ const CardList: React.FC = () => {
/>
)}
{addForm.type === 'data' && (
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-[#0094f7]">{addForm.content.split('\n').filter(line => line.trim()).length}</span> 条</p>
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(line => line.trim()).length}</span> 条</p>
)}
</div>
@@ -879,14 +879,14 @@ const CardList: React.FC = () => {
<div className="flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl">
<button
onClick={() => setBatchTab('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 ${batchTab === 'create' ? 'bg-[#0094f7] text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${batchTab === 'create' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
>
<ListPlus className="w-4 h-4" />
批量创建卡密组
</button>
<button
onClick={() => setBatchTab('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 ${batchTab === 'append' ? 'bg-[#0094f7] text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
className={`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${batchTab === 'append' ? 'bg-brand text-white shadow-md' : 'bg-white text-gray-600 hover:bg-gray-50'}`}
>
<Upload className="w-4 h-4" />
往单个组充卡密
+557
View File
@@ -0,0 +1,557 @@
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import {
AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw,
Search, Send, Smile, UserRound, Wifi, WifiOff,
} from 'lucide-react';
import { AccountDetail, ChatMessage, ChatSession } from '../types';
import {
getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions,
markChatRead, sendChatImage, sendChatMessage,
} from '../services/api';
import { emojiURL, renderXianyuText, xianyuEmojis } from '../chatEmojis';
type SessionsByAccount = Record<string, ChatSession[]>;
const accountStorageKey = 'ydisks.chat.account.v1';
const formatClock = (value: number): string => {
if (!value) return '';
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
const today = new Date();
if (date.toDateString() === today.toDateString()) {
return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
}
return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
};
const messageTime = (value: number): string => {
const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
};
const Chat: React.FC = () => {
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
const [activeAccountID, setActiveAccountID] = useState('');
const [sessionsByAccount, setSessionsByAccount] = useState<SessionsByAccount>({});
const [activeChatID, setActiveChatID] = useState('');
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [search, setSearch] = useState('');
const [unreadOnly, setUnreadOnly] = useState(false);
const [draft, setDraft] = useState('');
const [loading, setLoading] = useState(true);
const [messagesLoading, setMessagesLoading] = useState(false);
const [olderLoading, setOlderLoading] = useState(false);
const [hasOlder, setHasOlder] = useState(false);
const [historyCursor, setHistoryCursor] = useState<number | undefined>();
const [contactCursors, setContactCursors] = useState<Record<string, number | undefined>>({});
const [hasMoreContacts, setHasMoreContacts] = useState<Record<string, boolean>>({});
const [contactsLoading, setContactsLoading] = useState(false);
const [emojiOpen, setEmojiOpen] = useState(false);
const [sending, setSending] = useState(false);
const [error, setError] = useState('');
const [liveState, setLiveState] = useState<'connecting' | 'online' | 'offline'>('connecting');
const activeAccountRef = useRef('');
const activeChatRef = useRef('');
const scrollRef = useRef<HTMLDivElement | null>(null);
const scrollContextRef = useRef({ accountID: '', chatID: '' });
const shouldScrollToBottomRef = useRef(true);
const skipNextMessageScrollRef = useRef(false);
const imageInputRef = useRef<HTMLInputElement | null>(null);
const refreshedAccountsRef = useRef(new Set<string>());
useEffect(() => { activeAccountRef.current = activeAccountID; }, [activeAccountID]);
useEffect(() => { activeChatRef.current = activeChatID; }, [activeChatID]);
const reloadSessions = async (accountID: string) => {
const page = await getChatSessionPage(accountID, undefined, undefined, true);
setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions }));
setContactCursors(current => ({ ...current, [accountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more }));
return page.sessions;
};
useEffect(() => {
let cancelled = false;
const load = async () => {
setLoading(true);
try {
const [details, statuses] = await Promise.all([getAccountDetails(), getAccountRuntimeStatuses()]);
const withRuntime = details.map(account => ({
...account,
runtime_state: statuses[account.id]?.state || (account.enabled ? 'connecting' : 'disabled'),
runtime_connected: statuses[account.id]?.connected === true,
}));
const enabled = withRuntime.filter(account => account.enabled);
const sessionPages = await Promise.all(enabled.map(async account => [account.id, await getChatSessionPage(account.id)] as const));
if (cancelled) return;
setAccounts(enabled);
setSessionsByAccount(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.sessions])));
setContactCursors(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.next_cursor])));
setHasMoreContacts(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.has_more])));
const stored = window.localStorage.getItem(accountStorageKey) || '';
const first = enabled.some(account => account.id === stored) ? stored : enabled[0]?.id || '';
setActiveAccountID(first);
} catch (loadError) {
if (!cancelled) setError(loadError instanceof Error ? loadError.message : '加载聊天数据失败');
} finally {
if (!cancelled) setLoading(false);
}
};
void load();
return () => { cancelled = true; };
}, []);
useEffect(() => {
let disposed = false;
let timer = 0;
let controller: AbortController | null = null;
const poll = async () => {
controller = new AbortController();
try {
const statuses = await getAccountRuntimeStatuses({ signal: controller.signal, timeoutMs: 10_000 });
if (!disposed) {
setAccounts(current => current.map(account => ({
...account,
runtime_state: statuses[account.id]?.state || account.runtime_state,
runtime_connected: statuses[account.id]?.connected ?? account.runtime_connected,
})));
}
} catch {
// The app WebSocket has its own visible state; a transient status poll
// failure does not invalidate the loaded conversations.
} finally {
if (!disposed) timer = window.setTimeout(poll, 3_000);
}
};
timer = window.setTimeout(poll, 3_000);
return () => {
disposed = true;
window.clearTimeout(timer);
controller?.abort();
};
}, []);
useEffect(() => {
if (!activeAccountID) return;
window.localStorage.setItem(accountStorageKey, activeAccountID);
const sessions = sessionsByAccount[activeAccountID] || [];
setActiveChatID(current => sessions.some(session => session.chat_id === current) ? current : sessions[0]?.chat_id || '');
}, [activeAccountID, sessionsByAccount]);
useEffect(() => {
if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return;
refreshedAccountsRef.current.add(activeAccountID);
void reloadSessions(activeAccountID).catch(loadError => {
setError(loadError instanceof Error ? loadError.message : '同步会话失败');
});
}, [activeAccountID]);
useEffect(() => {
if (!activeAccountID || !activeChatID) {
setMessages([]);
return;
}
const controller = new AbortController();
setMessagesLoading(true);
void Promise.all([
getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }),
markChatRead(activeAccountID, activeChatID),
]).then(([page]) => {
setMessages(page.messages);
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
if (page.session) {
setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === page.session?.chat_id ? page.session! : session) }));
}
setSessionsByAccount(current => ({
...current,
[activeAccountID]: (current[activeAccountID] || []).map(session =>
session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session),
}));
}).catch(loadError => {
if (!controller.signal.aborted) setError(loadError instanceof Error ? loadError.message : '加载消息失败');
}).finally(() => {
if (!controller.signal.aborted) setMessagesLoading(false);
});
return () => controller.abort();
}, [activeAccountID, activeChatID]);
const loadOlderMessages = async () => {
if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return;
const container = scrollRef.current;
const previousHeight = container?.scrollHeight || 0;
skipNextMessageScrollRef.current = true;
setOlderLoading(true);
setError('');
try {
const oldestID = messages[0]?.id;
const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID);
setMessages(current => {
const keys = new Set(current.map(message => message.message_key));
return [...page.messages.filter(message => !keys.has(message.message_key)), ...current];
});
setHasOlder(page.has_more);
setHistoryCursor(page.next_cursor);
requestAnimationFrame(() => {
if (container) container.scrollTop += container.scrollHeight - previousHeight;
});
} catch (loadError) {
skipNextMessageScrollRef.current = false;
setError(loadError instanceof Error ? loadError.message : '加载历史消息失败');
} finally {
setOlderLoading(false);
}
};
useEffect(() => {
let disposed = false;
let reconnectTimer = 0;
let retry = 0;
let socket: WebSocket | null = null;
const connect = () => {
if (disposed) return;
setLiveState('connecting');
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
socket = new WebSocket(`${protocol}//${window.location.host}/api/chat/ws`);
socket.onopen = () => { retry = 0; setLiveState('online'); };
socket.onmessage = event => {
try {
const payload = JSON.parse(event.data);
const message = payload.message as ChatMessage | undefined;
if (!message) return;
const accountID = message.account_id;
setSessionsByAccount(current => {
const rows = current[accountID] || [];
const found = rows.some(row => row.chat_id === message.chat_id);
if (!found) {
void reloadSessions(accountID);
return current;
}
return {
...current,
[accountID]: rows.map(row => row.chat_id === message.chat_id ? {
...row,
last_message: message.content,
last_message_at: message.sent_at,
unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id)
? row.unread_count + 1 : row.unread_count,
} : row).sort((a, b) => b.last_message_at - a.last_message_at),
};
});
if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) {
setMessages(current => {
const index = current.findIndex(item => item.message_key === message.message_key);
if (index >= 0) return current.map((item, i) => i === index ? message : item);
return [...current, message];
});
if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id);
}
} catch {
// Ignore malformed non-chat frames and recover from authoritative REST state.
}
};
socket.onclose = () => {
if (disposed) return;
setLiveState('offline');
const delay = Math.min(15_000, 1_000 * 2 ** Math.min(retry++, 4));
reconnectTimer = window.setTimeout(connect, delay);
};
socket.onerror = () => socket?.close();
};
connect();
return () => {
disposed = true;
window.clearTimeout(reconnectTimer);
socket?.close();
};
}, []);
const handleMessageScroll = () => {
const container = scrollRef.current;
if (!container) return;
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
shouldScrollToBottomRef.current = distanceFromBottom <= 48;
};
useLayoutEffect(() => {
const contextChanged = scrollContextRef.current.accountID !== activeAccountID
|| scrollContextRef.current.chatID !== activeChatID;
scrollContextRef.current = { accountID: activeAccountID, chatID: activeChatID };
if (contextChanged) shouldScrollToBottomRef.current = true;
const container = scrollRef.current;
if (!container) return;
if (skipNextMessageScrollRef.current) {
skipNextMessageScrollRef.current = false;
return;
}
if (messagesLoading || shouldScrollToBottomRef.current) container.scrollTop = container.scrollHeight;
}, [activeAccountID, activeChatID, messages, messagesLoading]);
const activeAccount = accounts.find(account => account.id === activeAccountID);
const activeSessions = sessionsByAccount[activeAccountID] || [];
const selectedSession = activeSessions.find(session => session.chat_id === activeChatID);
const filteredSessions = useMemo(() => {
const keyword = search.trim().toLowerCase();
return activeSessions.filter(session => {
if (unreadOnly && session.unread_count <= 0) return false;
if (!keyword) return true;
return [session.buyer_name, session.buyer_id, session.item_title, session.last_message]
.some(value => (value || '').toLowerCase().includes(keyword));
});
}, [activeSessions, search, unreadOnly]);
const unreadForAccount = (accountID: string) =>
(sessionsByAccount[accountID] || []).reduce((sum, session) => sum + session.unread_count, 0);
const loadMoreContacts = async () => {
if (!activeAccountID || contactsLoading || !hasMoreContacts[activeAccountID]) return;
setContactsLoading(true);
setError('');
try {
const page = await getChatSessionPage(activeAccountID, contactCursors[activeAccountID], undefined, true);
setSessionsByAccount(current => ({ ...current, [activeAccountID]: page.sessions }));
setContactCursors(current => ({ ...current, [activeAccountID]: page.next_cursor }));
setHasMoreContacts(current => ({ ...current, [activeAccountID]: page.has_more }));
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : '加载历史联系人失败');
} finally { setContactsLoading(false); }
};
const handleSend = async () => {
const text = draft.trim();
if (!text || !selectedSession || !activeAccountID || sending) return;
setSending(true);
setError('');
try {
const result = await sendChatMessage({
account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id,
buyer_name: selectedSession.buyer_name, item_id: selectedSession.item_id,
item_title: selectedSession.item_title, text,
});
setDraft('');
setMessages(current => current.some(item => item.message_key === result.message.message_key)
? current.map(item => item.message_key === result.message.message_key ? result.message : item)
: [...current, result.message]);
} catch (sendError) {
setError(sendError instanceof Error ? sendError.message : '消息发送失败');
void getChatMessages(activeAccountID, selectedSession.chat_id).then(setMessages);
} finally {
setSending(false);
}
};
const handleImage = async (file?: File) => {
if (!file || !selectedSession || !activeAccountID || sending) return;
setSending(true);
setError('');
try {
const result = await sendChatImage({
account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id,
buyer_name: selectedSession.buyer_name, buyer_avatar_url: selectedSession.buyer_avatar_url,
item_id: selectedSession.item_id, item_title: selectedSession.item_title, image: file,
});
setMessages(current => current.some(item => item.message_key === result.message.message_key)
? current.map(item => item.message_key === result.message.message_key ? result.message : item)
: [...current, result.message]);
} catch (sendError) {
setError(sendError instanceof Error ? sendError.message : '图片发送失败');
} finally {
setSending(false);
if (imageInputRef.current) imageInputRef.current.value = '';
}
};
if (loading) return <div className="flex h-[calc(100vh-4rem)] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-sky-500" /></div>;
return (
<section className="flex h-[calc(100vh-4rem)] min-h-[560px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-chat">
<header className="border-b border-slate-200 bg-slate-50/70 px-5 pt-4">
<div className="mb-3 flex items-center justify-between gap-4">
<div>
<h2 className="text-xl font-black tracking-tight text-slate-950">在线聊天</h2>
<p className="mt-0.5 text-xs font-medium text-slate-500">复用账号实时连接,消息按账号完全隔离</p>
</div>
<div className={`flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-bold ${liveState === 'online' ? 'bg-emerald-50 text-emerald-700' : liveState === 'connecting' ? 'bg-amber-50 text-amber-700' : 'bg-red-50 text-red-700'}`}>
{liveState === 'online' ? <Wifi className="h-3.5 w-3.5" /> : <WifiOff className="h-3.5 w-3.5" />}
{liveState === 'online' ? '实时同步中' : liveState === 'connecting' ? '正在连接' : '连接已断开'}
</div>
</div>
<div className="flex gap-1 overflow-x-auto pb-0" role="tablist" aria-label="聊天账号">
{accounts.map(account => {
const active = account.id === activeAccountID;
const unread = unreadForAccount(account.id);
const online = account.runtime_state === 'online';
return (
<button key={account.id} type="button" role="tab" aria-selected={active} onClick={() => setActiveAccountID(account.id)}
className={`relative flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-extrabold transition-colors ${active ? 'border-sky-500 text-sky-700' : 'border-transparent text-slate-500 hover:text-slate-900'}`}>
<span className={`h-2 w-2 rounded-full ${online ? 'bg-emerald-500' : 'bg-slate-300'}`} />
<span className="max-w-36 truncate">{account.nickname || account.remark || account.id}</span>
{unread > 0 && <span className="min-w-5 rounded-full bg-red-500 px-1.5 py-0.5 text-[10px] text-white">{unread > 99 ? '99+' : unread}</span>}
</button>
);
})}
</div>
</header>
{accounts.length === 0 ? (
<div className="flex flex-1 flex-col items-center justify-center text-center">
<MessageCircleMore className="h-12 w-12 text-slate-300" />
<h3 className="mt-4 font-black text-slate-800">暂无启用账号</h3>
<p className="mt-1 text-sm text-slate-500">先在账号管理中启用账号,聊天会话会自动出现。</p>
</div>
) : (
<div className="grid min-h-0 flex-1 overflow-hidden grid-cols-[320px_minmax(0,1fr)]">
<aside className="flex min-h-0 flex-col border-r border-slate-200 bg-slate-50/40">
<div className="space-y-3 border-b border-slate-200 p-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
<input value={search} onChange={event => setSearch(event.target.value)} placeholder="搜索用户、商品或消息"
className="h-10 w-full rounded-xl border border-slate-200 bg-white pl-9 pr-3 text-sm outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-100" />
</div>
<div className="flex items-center justify-between">
<button type="button" onClick={() => setUnreadOnly(value => !value)}
className={`rounded-lg px-2.5 py-1.5 text-xs font-bold ${unreadOnly ? 'bg-sky-100 text-sky-700' : 'text-slate-500 hover:bg-slate-100'}`}>
{unreadOnly ? '只看未读' : '全部会话'}
</button>
<button type="button" title="刷新会话" onClick={() => void reloadSessions(activeAccountID)} className="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
<RefreshCw className="h-4 w-4" />
</button>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto">
{filteredSessions.map(session => (
<button key={session.chat_id} type="button" onClick={() => setActiveChatID(session.chat_id)}
className={`flex w-full gap-3 border-b border-slate-100 p-4 text-left transition-colors ${session.chat_id === activeChatID ? 'bg-white shadow-chat-active' : 'hover:bg-white/80'}`}>
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-slate-200 text-slate-500">
{session.buyer_avatar_url ? <img src={session.buyer_avatar_url} alt="" className="h-full w-full object-cover" /> : <UserRound className="h-5 w-5" />}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-extrabold text-slate-900">{session.buyer_name || `用户 ${session.buyer_id}`}</span>
<span className="ml-auto shrink-0 text-[10px] font-medium text-slate-400">{formatClock(session.last_message_at)}</span>
</div>
<div className="mt-1 flex items-center gap-2">
<span className="truncate text-xs text-slate-500">{session.last_message || '暂无消息'}</span>
{session.unread_count > 0 && <span className="ml-auto min-w-5 shrink-0 rounded-full bg-red-500 px-1.5 py-0.5 text-center text-[10px] font-bold text-white">{session.unread_count}</span>}
</div>
{session.item_title && <div className="mt-1.5 truncate text-[10px] font-medium text-sky-700">商品 · {session.item_title}</div>}
</div>
</button>
))}
{filteredSessions.length === 0 && <div className="px-6 py-16 text-center text-sm text-slate-400">当前账号暂无匹配会话</div>}
{hasMoreContacts[activeAccountID] && !search && !unreadOnly && <div className="flex justify-center p-4">
<button type="button" onClick={() => void loadMoreContacts()} disabled={contactsLoading}
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-xs font-bold text-slate-500 shadow-sm hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
{contactsLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{contactsLoading ? '正在加载' : '加载更多历史联系人'}
</button>
</div>}
</div>
</aside>
<main className="flex min-h-0 min-w-0 flex-col overflow-hidden bg-surface-subtle">
{selectedSession ? (
<>
<div className="flex h-16 shrink-0 items-center border-b border-slate-200 bg-white px-5">
<div className="min-w-0">
<div className="truncate text-sm font-black text-slate-950">{selectedSession.buyer_name || selectedSession.buyer_id}</div>
<div className="mt-0.5 truncate text-xs text-slate-500">用户 ID:{selectedSession.buyer_id}</div>
</div>
<span className={`ml-auto rounded-full px-2.5 py-1 text-[10px] font-bold ${activeAccount?.runtime_state === 'online' ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500'}`}>
{activeAccount?.runtime_state === 'online' ? '账号在线' : '账号离线'}
</span>
</div>
<div ref={scrollRef} onScroll={handleMessageScroll} className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
{messagesLoading ? <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-sky-500" /></div> : <>
{hasOlder && <div className="flex justify-center pb-1">
<button type="button" onClick={() => void loadOlderMessages()} disabled={olderLoading}
className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-xs font-bold text-slate-500 shadow-sm transition hover:border-sky-200 hover:text-sky-600 disabled:opacity-50">
{olderLoading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{olderLoading ? '正在加载' : '加载更早消息'}
</button>
</div>}
{messages.map(message => {
const outgoing = message.direction === 'outgoing';
const system = message.message_type === 'system';
if (system) {
return (
<div key={message.message_key} className="flex justify-center py-1">
<div className="max-w-[82%] rounded-xl border border-slate-200 bg-slate-100 px-4 py-2 text-center text-xs leading-5 text-slate-500">
{renderXianyuText(message.content)}
<div className="mt-1 text-[10px] text-slate-400">{messageTime(message.sent_at)}</div>
</div>
</div>
);
}
return (
<div key={message.message_key} className={`flex items-end gap-2.5 ${outgoing ? 'justify-end' : 'justify-start'}`}>
{!outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-slate-200 ring-2 ring-white">
{selectedSession.buyer_avatar_url ? <img src={selectedSession.buyer_avatar_url} alt={selectedSession.buyer_name || '用户'} className="h-full w-full object-cover" /> : <UserRound className="m-2 h-5 w-5 text-slate-500" />}
</div>}
<div className={`max-w-[72%] ${outgoing ? 'items-end' : 'items-start'} flex flex-col`}>
<div className={`mb-1 px-1 text-[10px] font-semibold text-slate-400`}>{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}</div>
{message.message_type === 'image' ? (
<a href={message.content} target="_blank" rel="noreferrer" className={`block overflow-hidden rounded-2xl border bg-white p-1 shadow-sm ${outgoing ? 'rounded-br-md border-sky-200' : 'rounded-bl-md border-slate-200'}`}>
<img src={message.content} alt="聊天图片" className="max-h-80 max-w-full rounded-xl object-contain" />
</a>
) : message.message_type === 'video' ? (
<video src={message.content} controls preload="metadata" className="max-h-80 max-w-full rounded-2xl bg-black" />
) : (
<div className={`rounded-2xl px-4 py-2.5 text-sm leading-6 shadow-sm ${outgoing ? 'rounded-br-md bg-sky-500 text-white' : 'rounded-bl-md border border-slate-200 bg-white text-slate-800'}`}>{renderXianyuText(message.content)}</div>
)}
<div className="mt-1 flex items-center gap-1 text-[10px] text-slate-400">
{messageTime(message.sent_at)}
{outgoing && (message.status === 'failed' ? <AlertCircle className="h-3 w-3 text-red-500" /> : message.status === 'sent' ? <CheckCheck className="h-3 w-3 text-sky-500" /> : <Check className="h-3 w-3" />)}
</div>
</div>
{outgoing && <div className="h-9 w-9 shrink-0 overflow-hidden rounded-full bg-sky-100 ring-2 ring-white">
{activeAccount?.avatar_url ? <img src={activeAccount.avatar_url} alt="我" className="h-full w-full object-cover" /> : <UserRound className="m-2 h-5 w-5 text-sky-600" />}
</div>}
</div>
);
})}
</>}
</div>
{error && <div className="border-t border-red-100 bg-red-50 px-5 py-2 text-xs font-medium text-red-700">{error}</div>}
<div className="relative z-10 shrink-0 border-t border-slate-200 bg-white p-4 shadow-chat-input">
<div className="mb-2 flex items-center gap-1">
<div className="relative">
<button type="button" onClick={() => setEmojiOpen(value => !value)} disabled={sending || activeAccount?.runtime_state !== 'online'} className="rounded-lg p-2 text-slate-500 hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="闲鱼表情"><Smile className="h-5 w-5" /></button>
{emojiOpen && <div className="absolute bottom-11 left-0 z-30 w-[360px] rounded-2xl border border-slate-200 bg-white p-3 shadow-2xl">
<div className="mb-2 text-xs font-bold text-slate-500">全部表情</div>
<div className="grid max-h-72 grid-cols-8 gap-1 overflow-y-auto">
{xianyuEmojis.map(([name,file]) => <button key={name} type="button" title={`[${name}]`} onClick={() => { setDraft(value => value + `[${name}]`); setEmojiOpen(false); }} className="flex h-10 w-10 items-center justify-center rounded-lg hover:bg-slate-100"><img src={emojiURL(file)} alt={`[${name}]`} className="h-8 w-8 object-contain" /></button>)}
</div>
</div>}
</div>
<input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={event => void handleImage(event.target.files?.[0])} />
<button type="button" onClick={() => imageInputRef.current?.click()} disabled={sending || activeAccount?.runtime_state !== 'online'}
className="rounded-lg p-2 text-slate-500 transition hover:bg-sky-50 hover:text-sky-600 disabled:opacity-40" title="发送图片(最大 10MB)"><ImagePlus className="h-5 w-5" /></button>
</div>
<div className="flex items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-2 transition focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100">
<textarea value={draft} onChange={event => setDraft(event.target.value)} rows={2} maxLength={2000}
onKeyDown={event => { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void handleSend(); } }}
disabled={activeAccount?.runtime_state !== 'online'} placeholder={activeAccount?.runtime_state === 'online' ? '输入消息,Enter 发送,Shift + Enter 换行' : '账号离线,暂时无法发送'}
className="max-h-32 min-h-12 flex-1 resize-none bg-transparent px-2 py-2 text-sm leading-6 outline-none disabled:cursor-not-allowed" />
<button type="button" onClick={() => void handleSend()} disabled={!draft.trim() || sending || activeAccount?.runtime_state !== 'online'}
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-500 text-white shadow-md shadow-sky-100 transition hover:bg-sky-600 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none" aria-label="发送消息">
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
</button>
</div>
</div>
</>
) : (
<div className="flex flex-1 flex-col items-center justify-center text-center">
<MessageCircleMore className="h-12 w-12 text-slate-300" />
<h3 className="mt-4 font-black text-slate-700">选择一个用户开始聊天</h3>
<p className="mt-1 text-sm text-slate-400">该账号的新消息会实时出现在左侧列表。</p>
</div>
)}
</main>
</div>
)}
</section>
);
};
export default Chat;
+43
View File
@@ -0,0 +1,43 @@
import React from 'react';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, test } from 'vitest';
import { StatusBadge } from './Dashboard';
const dashboardSource = readFileSync(resolve(__dirname, 'Dashboard.tsx'), 'utf8');
const globalStyles = readFileSync(resolve(__dirname, '../index.css'), 'utf8');
describe('Dashboard presentation safeguards', () => {
test('keeps order status badges on one line', () => {
const html = renderToStaticMarkup(<StatusBadge status="shipped" />);
expect(html).toContain('已发货');
expect(html).toContain('inline-flex');
expect(html).toContain('whitespace-nowrap');
expect(dashboardSource).toContain('min-w-[760px]');
});
test('pie charts use enlarged active sectors without focus rings or external label lines', () => {
expect(dashboardSource.match(/accessibilityLayer=\{false\}/g)).toHaveLength(2);
expect(dashboardSource.match(/activeShape=\{\{/g)).toHaveLength(2);
expect(dashboardSource).toContain('outerRadius: 96');
expect(dashboardSource).toContain('outerRadius: 98');
expect(dashboardSource.match(/stroke: 'none'/g)).toHaveLength(2);
expect(dashboardSource.match(/strokeWidth: 0/g)).toHaveLength(2);
expect(dashboardSource.match(/rootTabIndex=\{-1\}/g)).toHaveLength(2);
expect(dashboardSource.match(/label=\{false\}/g)).toHaveLength(2);
expect(dashboardSource.match(/labelLine=\{false\}/g)).toHaveLength(2);
expect(dashboardSource.match(/wrapperStyle=\{\{ zIndex: 30, outline: 'none' \}\}/g)).toHaveLength(2);
expect(dashboardSource.match(/absolute inset-0 z-10/g)).toHaveLength(2);
expect(globalStyles).toContain('.dashboard-pie-chart .recharts-sector:focus');
expect(dashboardSource).toContain('dashboard-revenue-chart h-[350px] w-full');
expect(dashboardSource).toContain('activeBar={false}');
expect(dashboardSource).not.toMatch(/#[0-9A-Fa-f]{3,8}/);
expect(dashboardSource).toContain("fill={cssColor('brand')}");
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-rectangle:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-curve:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart [class*="recharts-zIndex-layer_"]:focus');
expect(globalStyles).toContain('stroke: none !important');
});
});
+138 -78
View File
@@ -6,11 +6,17 @@ import { formatLocalDateTime } from '../dateTime';
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts';
const cssColor = (token: string, alpha?: number) => (
alpha === undefined
? `rgb(var(--color-${token}))`
: `rgb(var(--color-${token}) / ${alpha})`
);
// 状态徽章组件
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
export const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-[#0094f7] text-white',
pending_ship: 'bg-brand text-white',
shipped: 'bg-blue-100 text-blue-700',
completed: 'bg-green-100 text-green-700',
cancelled: 'bg-gray-100 text-gray-500',
@@ -29,7 +35,7 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
};
return (
<span className={`px-3 py-1.5 rounded-lg text-xs font-bold ${styles[status] || styles.cancelled}`}>
<span className={`inline-flex items-center justify-center whitespace-nowrap px-3 py-1.5 rounded-lg text-xs leading-none font-bold ${styles[status] || styles.cancelled}`}>
{labels[status] || status}
</span>
);
@@ -42,7 +48,7 @@ const StatCard: React.FC<{ title: string; value: string | number; icon: React.El
<div className={`p-4 rounded-2xl ${colorClass} bg-opacity-10 backdrop-blur-sm`}>
<Icon className={`w-6 h-6 ${colorClass.replace('bg-', 'text-')}`} />
</div>
{trend && <span className="text-xs font-bold text-white bg-[#0094f7] px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm">
{trend && <span className="text-xs font-bold text-white bg-brand px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm">
<TrendingUp className="w-3 h-3" /> {trend}
</span>}
</div>
@@ -75,7 +81,13 @@ const Dashboard: React.FC = () => {
const rangeRequestSequence = useRef(0);
// 颜色配置
const COLORS = ['#0094f7', '#3B82F6', '#10B981', '#F59E0B', '#8B5CF6'];
const COLORS = [
cssColor('brand'),
cssColor('brand-highlight'),
cssColor('success-500'),
cssColor('warning-500'),
cssColor('accent-500'),
];
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
const loadRange = async (range: TimeRange) => {
let currentRange;
@@ -159,7 +171,7 @@ const Dashboard: React.FC = () => {
</div>
);
}
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-[#0094f7]" /></div>;
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-brand" /></div>;
const chartData = analytics.daily_stats?.map(d => ({
name: d.date.slice(5), // MM-DD
@@ -267,7 +279,7 @@ const Dashboard: React.FC = () => {
onClick={() => setTimeRange(option.key)}
className={`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${
timeRange === option.key
? 'bg-[#0094f7] text-white shadow-md'
? 'bg-brand text-white shadow-md'
: 'bg-white text-gray-600 hover:text-black hover:bg-gray-50'
}`}
>
@@ -280,14 +292,14 @@ const Dashboard: React.FC = () => {
type="date"
value={customStartDate}
onChange={(e) => setCustomStartDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<span className="self-center text-gray-400">-</span>
<input
type="date"
value={customEndDate}
onChange={(e) => setCustomEndDate(e.target.value)}
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<button
onClick={() => {
@@ -341,7 +353,7 @@ const Dashboard: React.FC = () => {
<h3 className="text-xl font-bold text-gray-900">营收趋势分析</h3>
<p className="text-sm text-gray-400 mt-1">{selectedRangeLabel}的销售额走势</p>
</div>
<div className="h-[350px] w-full">
<div className="dashboard-revenue-chart h-[350px] w-full">
{chartData.length === 0 || analytics.revenue_stats.total_amount === 0 ? (
<div className="h-full flex flex-col items-center justify-center text-gray-400">
<ShoppingCart className="w-16 h-16 mb-4 opacity-20" />
@@ -356,26 +368,26 @@ const Dashboard: React.FC = () => {
dataKey="name"
axisLine={false}
tickLine={false}
tick={{fill: '#374151', fontSize: 14, fontWeight: 600}}
tick={{fill: cssColor('neutral-700'), fontSize: 14, fontWeight: 600}}
dy={10}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{fill: '#9CA3AF', fontSize: 13, fontWeight: 500}}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
tickFormatter={(value) => `¥${value}`}
/>
<Tooltip
contentStyle={{
backgroundColor: '#fff',
backgroundColor: cssColor('white'),
borderRadius: '8px',
border: '1px solid #e5e7eb',
boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1)',
border: `1px solid ${cssColor('neutral-200')}`,
boxShadow: 'var(--shadow-xl)',
padding: '12px 16px'
}}
labelStyle={{ color: '#6b7280', fontWeight: 500 }}
itemStyle={{ color: '#0094f7', fontWeight: 600 }}
cursor={{ fill: 'rgba(0, 148, 247, 0.08)' }}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ fill: cssColor('brand', 0.08) }}
formatter={(value) => {
const num = Number(value);
return [`¥${num.toFixed(2)}`, '营收'];
@@ -383,14 +395,20 @@ const Dashboard: React.FC = () => {
/>
<Bar
dataKey="amount"
fill="#0094f7"
fill={cssColor('brand')}
maxBarSize={72}
radius={[12, 12, 0, 0]}
stroke="#000000"
activeBar={false}
stroke="none"
strokeWidth={0}
>
{chartData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={['#0094f7', '#FCD34D', '#0071e3'][index % 3]} />
{chartData.map((_, index) => (
<Cell
key={`cell-${index}`}
fill={cssColor('brand')}
stroke="none"
strokeWidth={0}
/>
))}
</Bar>
</BarChart>
@@ -401,36 +419,36 @@ const Dashboard: React.FC = () => {
<AreaChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="colorAmount" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#0094f7" stopOpacity={0.5}/>
<stop offset="95%" stopColor="#0094f7" stopOpacity={0}/>
<stop offset="5%" stopColor={cssColor('brand')} stopOpacity={0.5}/>
<stop offset="95%" stopColor={cssColor('brand')} stopOpacity={0}/>
</linearGradient>
</defs>
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
tick={{fill: '#9CA3AF', fontSize: 13, fontWeight: 500}}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
dy={15}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{fill: '#9CA3AF', fontSize: 13, fontWeight: 500}}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
/>
<CartesianGrid vertical={false} stroke="#F3F4F6" strokeDasharray="3 3" />
<CartesianGrid vertical={false} stroke={cssColor('neutral-100')} strokeDasharray="3 3" />
<Tooltip
contentStyle={{
backgroundColor: '#fff',
backgroundColor: cssColor('white'),
borderRadius: '8px',
border: '1px solid #e5e7eb',
boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1)',
border: `1px solid ${cssColor('neutral-200')}`,
boxShadow: 'var(--shadow-xl)',
padding: '12px 16px'
}}
labelStyle={{ color: '#6b7280', fontWeight: 500 }}
itemStyle={{ color: '#0094f7', fontWeight: 600 }}
cursor={{ stroke: '#0094f7', strokeWidth: 2, strokeDasharray: '4 4' }}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ stroke: cssColor('brand'), strokeWidth: 2, strokeDasharray: '4 4' }}
/>
<Area type="monotone" dataKey="amount" stroke="#0094f7" strokeWidth={4} fillOpacity={1} fill="url(#colorAmount)" activeDot={{ r: 8, fill: '#fff', stroke: "#0094f7", strokeWidth: 2 }} />
<Area type="monotone" dataKey="amount" stroke={cssColor('brand')} strokeWidth={4} fillOpacity={1} fill="url(#colorAmount)" activeDot={{ r: 8, fill: cssColor('white'), stroke: cssColor('brand'), strokeWidth: 2 }} />
</AreaChart>
</ResponsiveContainer>
)}
@@ -460,7 +478,7 @@ const Dashboard: React.FC = () => {
</div>
<div className="h-3 rounded-full bg-gray-100 overflow-hidden">
<div
className="h-full rounded-full bg-[#0094f7]"
className="h-full rounded-full bg-brand"
style={{ width: `${Math.max(8, (item.sales / maxProductSales) * 100)}%` }}
/>
</div>
@@ -474,35 +492,61 @@ const Dashboard: React.FC = () => {
{/* 商品下单占比 */}
<div className="ios-card p-6 rounded-xl">
<h3 className="font-bold text-lg text-gray-900 mb-6">商品下单占比</h3>
<div className="h-[280px]">
<div
className="dashboard-pie-chart h-[280px] relative"
role="img"
aria-label={`商品下单占比,共 ${totalOrders} 单`}
>
{sourceDataData.length === 0 ? (
<div className="flex items-center justify-center h-full text-gray-400">暂无数据</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={sourceDataData}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={90}
paddingAngle={2}
dataKey="value"
label={({ name, payload }) => `${name} ${Number(payload?.percent || 0).toFixed(1)}%`}
labelLine={false}
>
{sourceDataData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Legend
verticalAlign="bottom"
height={36}
iconType="circle"
formatter={(value) => <span style={{ color: '#6B7280', fontWeight: 500 }}>{value}</span>}
/>
</PieChart>
</ResponsiveContainer>
<>
<ResponsiveContainer width="100%" height="100%">
<PieChart accessibilityLayer={false}>
<Pie
data={sourceDataData}
cx="50%"
cy="45%"
innerRadius={60}
outerRadius={90}
paddingAngle={2}
dataKey="value"
activeShape={{
outerRadius: 96,
stroke: 'none',
strokeWidth: 0,
}}
rootTabIndex={-1}
label={false}
labelLine={false}
>
{sourceDataData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
formatter={(value) => `${Number(value || 0)} 单`}
wrapperStyle={{ zIndex: 30, outline: 'none' }}
contentStyle={{
backgroundColor: cssColor('white'),
border: `1px solid ${cssColor('neutral-200')}`,
borderRadius: '10px',
boxShadow: 'var(--shadow-md)'
}}
/>
<Legend
verticalAlign="bottom"
height={36}
iconType="circle"
formatter={(value) => <span style={{ color: cssColor('neutral-500'), fontWeight: 500 }}>{value}</span>}
/>
</PieChart>
</ResponsiveContainer>
<div className="pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center pb-9">
<span className="text-2xl font-extrabold text-gray-900 tabular-nums">{totalOrders}</span>
<span className="text-xs font-medium text-gray-400 mt-0.5">总订单</span>
</div>
</>
)}
</div>
</div>
@@ -512,7 +556,7 @@ const Dashboard: React.FC = () => {
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* 参与统计的订单列表 */}
<div className="lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col">
<div className="p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]">
<div className="p-6 border-b border-gray-50 flex justify-between items-center bg-surface-muted">
<div>
<h3 className="font-bold text-lg text-gray-900">参与统计的订单</h3>
{validOrdersTruncated && (
@@ -559,19 +603,19 @@ const Dashboard: React.FC = () => {
)}
</div>
) : (
<table className="w-full text-left border-collapse">
<table className="w-full min-w-[760px] text-left border-collapse">
<thead>
<tr className="bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50">
<th className="px-6 py-4">订单信息</th>
<th className="px-6 py-4">买家信息</th>
<th className="px-6 py-4">金额</th>
<th className="px-6 py-4">状态</th>
<th className="px-6 py-4 whitespace-nowrap">状态</th>
<th className="px-6 py-4 text-right">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{filteredValidOrders.map((order) => (
<tr key={order.order_id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
<tr key={order.order_id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0">
@@ -595,7 +639,7 @@ const Dashboard: React.FC = () => {
<td className="px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum">
¥{order.amount || '0.00'}
</td>
<td className="px-6 py-4">
<td className="px-6 py-4 whitespace-nowrap">
<StatusBadge status={order.status || order.order_status || 'unknown'} />
</td>
<td className="px-6 py-4 text-right">
@@ -624,46 +668,62 @@ const Dashboard: React.FC = () => {
<div className="flex items-center justify-center h-[300px] text-gray-400">暂无数据</div>
) : (
<>
<div className="h-[300px] relative">
<div
className="dashboard-pie-chart h-[280px] relative"
role="img"
aria-label={`商品金额分析,总金额 ${formatCurrency(totalAmount)}`}
>
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<PieChart accessibilityLayer={false}>
<Pie
data={categoryDataData}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={100}
outerRadius={92}
paddingAngle={2}
dataKey="value"
label={({ name, payload }) => `${name} ${payload?.percentage || '0.0'}%`}
activeShape={{
outerRadius: 98,
stroke: 'none',
strokeWidth: 0,
}}
rootTabIndex={-1}
label={false}
labelLine={false}
>
{categoryDataData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color || COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip
wrapperStyle={{ zIndex: 30, outline: 'none' }}
contentStyle={{
backgroundColor: '#fff',
border: '1px solid #e5e7eb',
backgroundColor: cssColor('white'),
border: `1px solid ${cssColor('neutral-200')}`,
borderRadius: '6px',
boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
boxShadow: 'var(--shadow-md)'
}}
formatter={(value) => `¥${Number(value || 0).toLocaleString()}`}
/>
</PieChart>
</ResponsiveContainer>
<div className="pointer-events-none absolute inset-0 z-10 flex flex-col items-center justify-center">
<span className="text-lg font-extrabold text-gray-900 tabular-nums">{formatCurrency(totalAmount)}</span>
<span className="text-xs font-medium text-gray-400 mt-0.5">总金额</span>
</div>
</div>
<div className="space-y-3 mt-4">
{categoryDataData.map((cat) => (
<div key={cat.name} className="flex justify-between items-center text-sm">
<div className="flex items-center gap-2">
<div key={cat.name} className="flex justify-between items-center gap-3 text-sm">
<div className="flex items-center gap-2 min-w-0 flex-1">
<div
className="w-3 h-3 rounded-full"
className="w-3 h-3 rounded-full shrink-0"
style={{ backgroundColor: cat.color || COLORS[categoryDataData.indexOf(cat) % COLORS.length] }}
></div>
<span className="text-gray-600 font-medium">{cat.name}</span>
<span className="text-gray-600 font-medium truncate" title={cat.name}>{cat.name}</span>
</div>
<div className="flex items-center gap-3">
<div className="flex items-center gap-3 shrink-0 whitespace-nowrap">
<span className="font-bold text-gray-900">¥{cat.value.toLocaleString()}</span>
<span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded">{cat.percentage}%</span>
</div>
+119 -8
View File
@@ -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(','))
@@ -594,14 +638,14 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</button>
<button
onClick={openPublishModal}
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"
className="px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100"
>
<PackagePlus className="w-4 h-4" />
发布商品
</button>
<button
onClick={() => void openBatchModal()}
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"
className="px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100"
>
<UploadCloud className="w-4 h-4" />
{recentBatch && ['running', 'canceling'].includes(recentBatch.status) ? '继续批量任务' : '批量铺货'}
@@ -626,7 +670,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">
<button
onClick={() => handleEdit(item)}
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors"
className="p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-brand hover:text-white transition-colors"
title="编辑"
>
<Edit className="w-3.5 h-3.5" />
@@ -666,7 +710,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<div className="space-y-2 mt-auto">
<button
onClick={() => onConfigureDelivery(item)}
className={`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${hasRule ? 'bg-gray-900 text-white hover:bg-black' : 'bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100'}`}
className={`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${hasRule ? 'bg-gray-900 text-white hover:bg-black' : 'bg-brand text-white hover:bg-brand-highlight shadow-md shadow-blue-100'}`}
>
<span className="flex items-center gap-1.5"><Link2 className="w-3.5 h-3.5" />{hasRule ? '查看发货规则' : '关联发货规则'}</span>
<ArrowRight className="w-3.5 h-3.5" />
@@ -848,7 +892,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
</div>
<div className="modal-footer">
<button disabled={publishing} onClick={handlePublishItem} className="w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
<button disabled={publishing} onClick={handlePublishItem} className="w-full bg-emerald-500 hover:bg-emerald-600 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2">
<PackagePlus className="w-4 h-4" />
{publishing ? '正在发布...' : '发布到闲鱼'}
</button>
@@ -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>
+13 -14
View File
@@ -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' },
],
@@ -394,7 +394,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
{/* 说明 */}
<div className="ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100">
<div className="flex items-start gap-3">
<Bell className="w-5 h-5 text-[#0094f7] mt-0.5 flex-shrink-0" />
<Bell className="w-5 h-5 text-brand mt-0.5 flex-shrink-0" />
<div className="text-sm text-gray-700 leading-6">
配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:
<ul className="mt-2 space-y-1 text-gray-600">
@@ -409,7 +409,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
{/* 渠道列表 */}
{loading ? (
<div className="flex justify-center py-20">
<Loader2 className="w-8 h-8 text-[#0094f7] animate-spin" />
<Loader2 className="w-8 h-8 text-brand animate-spin" />
</div>
) : channels.length === 0 ? (
<div className="ios-card rounded-xl p-12 bg-white text-center">
@@ -454,7 +454,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
<button
onClick={() => handleTest(ch)}
disabled={testingId === ch.id}
className="px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-[#0094f7] hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50"
className="px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-brand hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50"
>
{testingId === ch.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <Send className="w-3 h-3" />}
测试
@@ -639,10 +639,10 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
key={t}
type="button"
onClick={() => setForm({ ...form, type: t, config: {} })}
className={`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${selected ? 'border-[#0094f7] bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
className={`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${selected ? 'border-brand bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
>
<TIcon className={`w-5 h-5 ${selected ? 'text-[#0094f7]' : 'text-gray-500'}`} />
<span className={`text-xs font-bold ${selected ? 'text-[#0094f7]' : 'text-gray-600'}`}>{m.label}</span>
<TIcon className={`w-5 h-5 ${selected ? 'text-brand' : 'text-gray-500'}`} />
<span className={`text-xs font-bold ${selected ? 'text-brand' : 'text-gray-600'}`}>{m.label}</span>
</button>
);
})}
@@ -712,7 +712,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
: enableCustomSMTP(form.config, smtp),
});
}}
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-brand' : 'bg-gray-300'}`}
aria-label="使用独立 SMTP"
>
<span className={`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${form.config.use_custom_smtp === true ? 'translate-x-5' : ''}`} />
@@ -839,13 +839,13 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
: [...form.event_types, event.value];
setForm({ ...form, event_types: next });
}}
className={`text-left rounded-xl border px-3 py-2.5 transition-colors ${checked ? 'border-[#0094f7] bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
className={`text-left rounded-xl border px-3 py-2.5 transition-colors ${checked ? 'border-brand bg-blue-50' : 'border-gray-100 hover:border-gray-300'}`}
>
<div className="flex items-center gap-2">
<span className={`w-4 h-4 rounded border flex items-center justify-center ${checked ? 'bg-[#0094f7] border-[#0094f7]' : 'border-gray-300'}`}>
<span className={`w-4 h-4 rounded border flex items-center justify-center ${checked ? 'bg-brand border-brand' : 'border-gray-300'}`}>
{checked && <Check className="w-3 h-3 text-white" />}
</span>
<span className={`text-sm font-bold ${checked ? 'text-[#0094f7]' : 'text-gray-800'}`}>{event.label}</span>
<span className={`text-sm font-bold ${checked ? 'text-brand' : 'text-gray-800'}`}>{event.label}</span>
</div>
<p className="text-xs text-gray-500 mt-1 pl-6 leading-5">{event.description}</p>
</button>
@@ -858,7 +858,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
<button
type="button"
onClick={() => setForm({ ...form, enabled: !form.enabled })}
className={`relative w-11 h-6 rounded-full transition-colors ${form.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
className={`relative w-11 h-6 rounded-full transition-colors ${form.enabled ? 'bg-brand' : 'bg-gray-300'}`}
>
<span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${form.enabled ? 'translate-x-5' : ''}`} />
</button>
@@ -889,8 +889,7 @@ const Notifications: React.FC<NotificationsProps> = ({ isAdmin = false }) => {
{/* Toast */}
{toast && (
<div className="fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in"
style={{ background: toast.type === 'success' ? '#10b981' : '#ef4444', color: 'white' }}>
<div className={`fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in text-white ${toast.type === 'success' ? 'bg-success-500' : 'bg-danger-500'}`}>
{toast.type === 'success' ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
{toast.text}
</div>
+5 -5
View File
@@ -9,7 +9,7 @@ import { formatLocalDateTime } from '../dateTime';
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
const styles = {
processing: 'bg-blue-100 text-blue-800',
pending_ship: 'bg-[#0094f7] text-white',
pending_ship: 'bg-brand text-white',
shipped: 'bg-blue-100 text-blue-700',
completed: 'bg-green-100 text-green-700',
cancelled: 'bg-gray-100 text-gray-500',
@@ -356,7 +356,7 @@ const OrderList: React.FC = () => {
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
{/* Toolbar */}
<div className="p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-[#FAFAFA]">
<div className="p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted">
<div className="flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full">
{[
{k:'all', v:'全部'},
@@ -392,7 +392,7 @@ const OrderList: React.FC = () => {
</select>
</div>
<div className="relative group">
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors" />
<Search className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors" />
<input
type="text"
placeholder="搜索订单号/商品/买家..."
@@ -418,7 +418,7 @@ const OrderList: React.FC = () => {
</thead>
<tbody className="divide-y divide-gray-50">
{orders.map((order) => (
<tr key={order.id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
<tr key={order.id} className="hover:bg-warning-50/50 transition-colors group">
<td className="px-6 py-5">
<div className="flex items-center gap-5">
<div className="w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0">
@@ -800,7 +800,7 @@ const OrderList: React.FC = () => {
<button
onClick={() => executeShip('full_delivery')}
disabled={shipLoading}
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-[#0094f7] hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
className="w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-brand hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
>
<div className="flex items-start gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5">
+224 -50
View File
@@ -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,16 @@ 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 [automationTriggerCounts, setAutomationTriggerCounts] = useState<Record<string, number>>({});
const automationRulesRequest = useRef(0);
const replyRulesRequest = useRef(0);
const selectedAccountRef = useRef('');
selectedAccountRef.current = selectedAccountId;
@@ -253,14 +267,29 @@ 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);
setAutomationTriggerCounts(result.trigger_counts || {});
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 +322,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]);
@@ -316,17 +353,24 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
[accounts, selectedAccountId],
);
const rulesByTrigger = useMemo(() => {
const grouped: Record<AutomationTriggerType, ShippingRule[]> = {
order_paid: [],
buyer_reviewed: [],
review_missing_timeout: [],
};
for (const rule of visibleAutomationRules) {
grouped[rule.trigger_type]?.push(rule);
}
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;
@@ -747,17 +791,20 @@ 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="min-w-0 space-y-8 animate-fade-in">
<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)}
className="ios-input px-4 py-3 rounded-2xl text-sm min-w-64"
onChange={event => {
setSelectedAccountId(event.target.value);
setAutomationPage(1);
}}
className="ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64"
>
<option value="">全部账号</option>
{accounts.map(account => (
@@ -766,7 +813,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 +821,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}
@@ -795,7 +842,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
onClick={() => setActiveTab(tab.id)}
className={`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${
activeTab === tab.id
? 'bg-[#0094f7] text-white shadow-md'
? 'bg-brand text-white shadow-md'
: 'bg-white text-gray-600 hover:text-black hover:bg-gray-50'
}`}
>
@@ -847,8 +894,8 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
)}
{activeTab === 'automation' && (
<div className="grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6">
<aside className="space-y-4">
<div className="grid min-w-0 grid-cols-1 gap-6 xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]">
<aside className="min-w-0 space-y-4">
<div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm">
<h3 className="font-black text-gray-900 mb-1">新建规则</h3>
<p className="text-sm text-gray-500 mb-4">先选自动化类型,再配置对应动作。</p>
@@ -879,7 +926,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];
@@ -890,7 +940,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<Icon className="w-4 h-4 text-gray-500" />
<span className="text-sm font-bold text-gray-700">{meta.shortLabel}</span>
</div>
<span className="text-sm font-black text-gray-900">{rulesByTrigger[trigger].length}</span>
<span className="text-sm font-black text-gray-900">{automationTriggerCounts[trigger] || 0}</span>
</div>
);
})}
@@ -898,15 +948,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="min-w-0 space-y-4">
<div className="rounded-xl border border-gray-100 bg-surface-muted 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 +1074,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-brand 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>
)}
@@ -970,7 +1144,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
</div>
<div className="space-y-3">
{replyRules.map(rule => (
<div key={rule.id} className="flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg transition-all gap-4">
<div key={rule.id} className="flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg transition-all gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-2">
<span className="px-3 py-1 bg-black text-white rounded-lg text-xs font-bold">包含匹配</span>
@@ -1013,7 +1187,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
const defaultReply = defaultReplies[account.id];
const enabled = Boolean(defaultReply?.enabled);
return (
<div key={account.id} className={`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${enabled ? 'border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg' : 'border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg'}`}>
<div key={account.id} className={`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${enabled ? 'border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg' : 'border-gray-100 bg-surface-subtle hover:bg-white hover:shadow-lg'}`}>
<div className="flex items-center gap-4 min-w-0">
<div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${enabled ? 'bg-purple-600 text-white' : 'bg-gray-200 text-gray-400'}`}>
<Bot className="w-5 h-5" />
@@ -1098,7 +1272,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
}`}
>
<div className="flex items-start gap-3">
<Icon className={`w-5 h-5 mt-0.5 ${selected ? 'text-[#0094f7]' : 'text-white'}`} />
<Icon className={`w-5 h-5 mt-0.5 ${selected ? 'text-brand' : 'text-white'}`} />
<div>
<div className="font-black">{meta.label}</div>
<div className={`text-xs mt-1 leading-5 ${selected ? 'text-gray-500' : 'text-gray-400'}`}>{meta.description}</div>
@@ -1122,11 +1296,11 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
</div>
</aside>
<div className="p-6 overflow-y-auto bg-[#F7F8FA]">
<div className="p-6 overflow-y-auto bg-surface-subtle">
<div className="space-y-5">
<section className="bg-white rounded-3xl border border-gray-100 p-5">
<div className="flex items-center gap-2 mb-4">
<CheckCircle2 className="w-5 h-5 text-[#0094f7]" />
<CheckCircle2 className="w-5 h-5 text-brand" />
<h4 className="font-black text-gray-900">生效范围</h4>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
@@ -1195,7 +1369,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<div className="flex items-start justify-between gap-4 mb-4">
<div>
<div className="flex items-center gap-2">
<Layers3 className="w-5 h-5 text-[#0094f7]" />
<Layers3 className="w-5 h-5 text-brand" />
<h4 className="font-black text-gray-900">{currentTrigger === 'buyer_reviewed' ? '赠品库存' : '发货库存'}</h4>
</div>
<p className="text-sm text-gray-500 mt-1">
@@ -1272,7 +1446,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
type="checkbox"
checked={variant.delay_override === true}
onChange={event => updateVariant(index, { delay_override: event.target.checked })}
className="accent-[#0094f7]"
className="accent-brand"
/>
覆盖卡密默认延时
</label>
@@ -1564,7 +1738,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<button
type="button"
onClick={() => setDefaultForm({ ...defaultForm, enabled: !defaultForm.enabled })}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${defaultForm.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
className={`w-14 h-8 rounded-full transition-colors duration-300 relative ${defaultForm.enabled ? 'bg-brand' : 'bg-gray-300'}`}
>
<span className={`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${defaultForm.enabled ? 'translate-x-7' : 'translate-x-1'}`} />
</button>
+3 -3
View File
@@ -269,7 +269,7 @@ const Settings: React.FC = () => {
{/* AI Configuration */}
<section className="space-y-4">
<h3 className="text-lg font-extrabold text-gray-800 flex items-center gap-2">
<div className="p-1.5 rounded-lg bg-[#0094f7] text-white">
<div className="p-1.5 rounded-lg bg-brand text-white">
<Sparkles className="w-4 h-4" />
</div>
AI 智能回复配置
@@ -346,10 +346,10 @@ const Settings: React.FC = () => {
setSettings({...settings, ai_model: model});
setModelDropdownOpen(false);
}}
className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-[#0094f7] flex items-center justify-between gap-3"
className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-brand flex items-center justify-between gap-3"
>
<span className="truncate">{model}</span>
{model === currentModel && <Check className="w-4 h-4 shrink-0 text-[#0094f7]" />}
{model === currentModel && <Check className="w-4 h-4 shrink-0 text-brand" />}
</button>
))
) : (
+65 -39
View File
@@ -1,69 +1,95 @@
import React from 'react';
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, Bell } from 'lucide-react';
import {
Bell, Box, ChevronLeft, ChevronRight, CreditCard, LayoutDashboard,
LogOut, MessageCircleMore, Settings, ShoppingBag, Users, Zap,
} from 'lucide-react';
import { YdisksBrandIcon } from './YdisksLogo';
interface SidebarProps {
activeTab: string;
isAdmin?: boolean;
collapsed: boolean;
onToggleCollapsed: () => void;
onNavigate: (tab: string) => void;
onLogout: () => void;
}
const Sidebar: React.FC<SidebarProps> = ({ activeTab, isAdmin = false, onNavigate, onLogout }) => {
const Sidebar: React.FC<SidebarProps> = ({
activeTab, isAdmin = false, collapsed, onToggleCollapsed, onNavigate, onLogout,
}) => {
const menuItems = [
{ id: 'dashboard', icon: LayoutDashboard, label: '仪表盘' },
{ id: 'accounts', icon: Users, label: '账号管理' },
{ id: 'orders', icon: ShoppingBag, label: '订单管理' },
{ id: 'chat', icon: MessageCircleMore, label: '在线聊天' },
{ id: 'cards', icon: CreditCard, label: '卡密库存' },
{ id: 'items', icon: Box, label: '商品列表' },
{ id: 'orders', icon: ShoppingBag, label: '订单管理' },
{ id: 'rules', icon: Zap, label: '自动化规则' },
{ id: 'notifications', icon: Bell, label: '通知设置' },
...(isAdmin ? [{ id: 'settings', icon: Settings, label: '系统与AI' }] : []),
];
return (
<div className="w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]">
<div className="p-6">
<div className="flex items-center gap-3 mb-12 px-2">
<div className="shrink-0">
<YdisksBrandIcon sizeClass="w-10 h-10" />
<aside className={`fixed inset-y-0 left-0 z-20 flex flex-col border-r border-slate-200/80 bg-white/95 shadow-sidebar backdrop-blur-xl transition-[width] duration-300 ${collapsed ? 'w-16' : 'w-64'}`}>
<div className={`flex h-20 items-center border-b border-slate-100 ${collapsed ? 'justify-center px-2' : 'gap-3 px-5'}`}>
<YdisksBrandIcon sizeClass="h-10 w-10" />
{!collapsed && (
<div className="min-w-0 leading-tight">
<div className="truncate text-base font-black tracking-tight text-slate-950">Ydisks 闲鱼助手</div>
<div className="mt-1 text-[10px] font-extrabold uppercase tracking-[0.22em] text-sky-600">Operations</div>
</div>
<h1 className="text-xl font-extrabold tracking-tight text-gray-900">Ydisks闲鱼助手 <span className="text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1">PRO</span></h1>
</div>
<nav className="space-y-2">
{menuItems.map((item) => {
const Icon = item.icon;
const isActive = activeTab === item.id;
return (
<button
key={item.id}
onClick={() => onNavigate(item.id)}
className={`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${
isActive
? 'bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]'
: 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
}`}
>
<Icon className={`w-5 h-5 transition-colors ${isActive ? 'text-white' : 'text-gray-400 group-hover:text-gray-600'}`} />
<span className="text-sm tracking-wide">{item.label}</span>
{isActive && <Sparkles className="w-4 h-4 absolute right-3 text-white/30 animate-pulse" />}
</button>
);
})}
</nav>
)}
</div>
<div className="p-6 border-t border-gray-50">
<button
onClick={onLogout}
className="w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium"
<nav className={`flex-1 space-y-1.5 overflow-y-auto py-5 ${collapsed ? 'px-2' : 'px-3'}`} aria-label="主导航">
{menuItems.map((item) => {
const Icon = item.icon;
const active = activeTab === item.id;
return (
<button
key={item.id}
type="button"
title={collapsed ? item.label : undefined}
aria-label={item.label}
aria-current={active ? 'page' : undefined}
onClick={() => onNavigate(item.id)}
className={`group relative flex h-11 w-full items-center rounded-xl transition-colors ${collapsed ? 'justify-center' : 'gap-3 px-3.5'} ${
active
? 'bg-brand text-white shadow-brand-active'
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-900'
}`}
>
<Icon className={`h-[19px] w-[19px] shrink-0 ${active ? 'text-white' : 'text-slate-400 group-hover:text-slate-700'}`} />
{!collapsed && <span className="truncate text-sm font-bold">{item.label}</span>}
{active && !collapsed && <span className="ml-auto h-1.5 w-1.5 rounded-full bg-white/90" />}
</button>
);
})}
</nav>
<div className={`space-y-2 border-t border-slate-100 p-2 ${collapsed ? '' : 'p-3'}`}>
<button
type="button"
onClick={onToggleCollapsed}
title={collapsed ? '展开侧边栏' : '收起侧边栏'}
aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-900 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
>
<LogOut className="w-5 h-5" />
<span className="text-sm">退出登录</span>
{collapsed ? <ChevronRight className="h-5 w-5" /> : <ChevronLeft className="h-5 w-5" />}
{!collapsed && <span className="text-sm font-bold">收起侧边栏</span>}
</button>
<button
type="button"
onClick={onLogout}
title={collapsed ? '退出登录' : undefined}
aria-label="退出登录"
className={`flex h-10 w-full items-center rounded-xl text-slate-500 transition-colors hover:bg-red-50 hover:text-red-600 ${collapsed ? 'justify-center' : 'gap-3 px-3'}`}
>
<LogOut className="h-5 w-5" />
{!collapsed && <span className="text-sm font-bold">退出登录</span>}
</button>
</div>
</div>
</aside>
);
};
+2 -2
View File
@@ -27,8 +27,8 @@ export const YdisksBrandIcon: React.FC<YdisksBrandIconProps> = ({
<svg className="absolute inset-0 w-full h-full" viewBox="0 0 120 120" aria-hidden="true">
<defs>
<linearGradient id="login-squircle-gradient" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#0094f7" />
<stop offset="100%" stopColor="#287efe" />
<stop offset="0%" stopColor="rgb(var(--color-brand))" />
<stop offset="100%" stopColor="rgb(var(--color-brand-light))" />
</linearGradient>
</defs>
<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 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z" fill="url(#login-squircle-gradient)" />
+28
View File
@@ -0,0 +1,28 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { readSidebarCollapsed, writeSidebarCollapsed } from './sidebarState';
afterEach(() => vi.unstubAllGlobals());
describe('sidebar persistence', () => {
test('defaults to expanded and persists both states', () => {
const values = new Map<string, string>();
vi.stubGlobal('window', { localStorage: {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
}});
expect(readSidebarCollapsed()).toBe(false);
writeSidebarCollapsed(true);
expect(readSidebarCollapsed()).toBe(true);
writeSidebarCollapsed(false);
expect(readSidebarCollapsed()).toBe(false);
});
test('storage failures safely fall back to expanded', () => {
vi.stubGlobal('window', { localStorage: {
getItem: () => { throw new Error('blocked'); },
setItem: () => { throw new Error('blocked'); },
}});
expect(readSidebarCollapsed()).toBe(false);
expect(() => writeSidebarCollapsed(true)).not.toThrow();
});
});
+18
View File
@@ -0,0 +1,18 @@
const storageKey = 'ydisks.sidebar.v1';
export const readSidebarCollapsed = (): boolean => {
try {
return window.localStorage.getItem(storageKey) === 'collapsed';
} catch {
return false;
}
};
export const writeSidebarCollapsed = (collapsed: boolean): void => {
try {
window.localStorage.setItem(storageKey, collapsed ? 'collapsed' : 'expanded');
} catch {
// Storage can be unavailable in hardened browsers; the in-memory state
// remains fully functional.
}
};
+233 -59
View File
@@ -3,6 +3,157 @@
@tailwind components;
@tailwind utilities;
/*
* 全局颜色令牌:页面组件不得直接写颜色值。
* 颜色使用 RGB 通道存储,Tailwind 和 CSS 可以安全地复用透明度。
*/
:root {
--color-transparent: transparent;
--color-black: 0 0 0;
--color-white: 255 255 255;
--color-brand: 0 148 247;
--color-brand-highlight: 0 113 227;
--color-brand-light: 40 126 254;
--color-ink: 29 29 31;
--color-muted: 134 134 139;
--color-line: 210 210 215;
--color-canvas: 244 245 247;
--color-surface: 255 255 255;
--color-surface-subtle: 247 248 250;
--color-surface-muted: 250 250 250;
--color-neutral-50: 249 250 251;
--color-neutral-100: 243 244 246;
--color-neutral-200: 229 231 235;
--color-neutral-300: 209 213 219;
--color-neutral-400: 156 163 175;
--color-neutral-500: 107 114 128;
--color-neutral-600: 75 85 99;
--color-neutral-700: 55 65 81;
--color-neutral-800: 31 41 55;
--color-neutral-900: 17 24 39;
--color-neutral-950: 3 7 18;
--color-slate-50: 248 250 252;
--color-slate-100: 241 245 249;
--color-slate-200: 226 232 240;
--color-slate-300: 203 213 225;
--color-slate-400: 148 163 184;
--color-slate-500: 100 116 139;
--color-slate-600: 71 85 105;
--color-slate-700: 51 65 85;
--color-slate-800: 30 41 59;
--color-slate-900: 15 23 42;
--color-slate-950: 2 6 23;
/* 主色阶:蓝色只从品牌色体系中取值,避免 blue/sky 各自漂移。 */
--color-brand-50: 239 248 255;
--color-brand-100: 223 241 255;
--color-brand-200: 191 229 255;
--color-brand-300: 143 210 255;
--color-brand-400: 83 184 251;
--color-brand-500: 0 148 247;
--color-brand-600: 0 148 247;
--color-brand-700: 0 113 227;
--color-brand-800: 0 91 181;
--color-brand-900: 0 75 147;
--color-brand-950: 0 53 107;
--color-success-50: 236 253 245;
--color-success-100: 209 250 229;
--color-success-200: 167 243 208;
--color-success-300: 110 231 183;
--color-success-400: 52 211 153;
--color-success-500: 16 185 129;
--color-success-600: 5 150 105;
--color-success-700: 4 120 87;
--color-success-800: 6 95 70;
--color-success-900: 6 78 59;
--color-success-950: 2 44 34;
--color-warning-50: 255 251 235;
--color-warning-100: 254 243 199;
--color-warning-200: 253 230 138;
--color-warning-300: 252 211 77;
--color-warning-400: 251 191 36;
--color-warning-500: 245 158 11;
--color-warning-600: 217 119 6;
--color-warning-700: 180 83 9;
--color-warning-800: 146 64 14;
--color-warning-900: 120 53 15;
--color-warning-950: 69 26 3;
--color-danger-50: 254 242 242;
--color-danger-100: 254 226 226;
--color-danger-200: 254 202 202;
--color-danger-300: 252 165 165;
--color-danger-400: 248 113 113;
--color-danger-500: 239 68 68;
--color-danger-600: 220 38 38;
--color-danger-700: 185 28 28;
--color-danger-800: 153 27 27;
--color-danger-900: 127 29 29;
--color-danger-950: 69 10 10;
--color-info-50: 239 246 255;
--color-info-100: 219 234 254;
--color-info-200: 191 219 254;
--color-info-300: 147 197 253;
--color-info-400: 96 165 250;
--color-info-500: 59 130 246;
--color-info-600: 37 99 235;
--color-info-700: 29 78 216;
--color-info-800: 30 64 175;
--color-info-900: 30 58 138;
--color-info-950: 23 37 84;
/* 非状态性的辅助色只保留一个紫色阶,避免页面出现过多彩色分支。 */
--color-accent-50: 250 245 255;
--color-accent-100: 243 232 255;
--color-accent-200: 233 213 255;
--color-accent-300: 216 180 254;
--color-accent-400: 192 132 252;
--color-accent-500: 168 85 247;
--color-accent-600: 147 51 234;
--color-accent-700: 126 34 206;
--color-accent-800: 107 33 168;
--color-accent-900: 88 28 135;
--color-accent-950: 59 7 100;
--shadow-none: 0 0 0 var(--color-transparent);
--shadow-default: 0 1px 3px 0 rgb(var(--color-black) / 0.1), 0 1px 2px -1px rgb(var(--color-black) / 0.1);
--shadow-sm: 0 1px 2px 0 rgb(var(--color-black) / 0.05);
--shadow-md: 0 4px 6px -1px rgb(var(--color-black) / 0.1), 0 2px 4px -2px rgb(var(--color-black) / 0.1);
--shadow-lg: 0 10px 15px -3px rgb(var(--color-black) / 0.1), 0 4px 6px -4px rgb(var(--color-black) / 0.1);
--shadow-xl: 0 20px 25px -5px rgb(var(--color-black) / 0.1), 0 8px 10px -6px rgb(var(--color-black) / 0.1);
--shadow-2xl: 0 25px 50px -12px rgb(var(--color-black) / 0.25);
--shadow-inner: inset 0 2px 4px 0 rgb(var(--color-black) / 0.05);
--shadow-card: 0 8px 24px rgb(var(--color-black) / 0.04);
--shadow-panel: 0 20px 60px -15px rgb(var(--color-black) / 0.05);
--shadow-modal: 0 25px 50px -12px rgb(var(--color-black) / 0.25);
--shadow-sidebar: 4px 0 24px rgb(var(--color-slate-900) / 0.035);
--shadow-chat: 0 16px 45px rgb(var(--color-slate-900) / 0.06);
--shadow-chat-input: 0 -8px 24px rgb(var(--color-slate-900) / 0.04);
--shadow-chat-active: inset 3px 0 0 rgb(var(--color-brand));
--shadow-brand-soft: 0 2px 8px rgb(var(--color-brand) / 0.2);
--shadow-brand-active: 0 8px 18px rgb(var(--color-brand) / 0.2);
--shadow-brand-strong: 0 8px 20px rgb(var(--color-brand) / 0.3);
}
/* 覆盖 Tailwind 默认的蓝色焦点环和黑色占位阴影,避免预设色偷偷进入页面。 */
*,
::before,
::after {
--tw-ring-offset-color: rgb(var(--color-white));
--tw-ring-color: rgb(var(--color-brand-400) / 0.5);
--tw-ring-offset-shadow: 0 0 0 var(--color-transparent);
--tw-ring-shadow: 0 0 0 var(--color-transparent);
--tw-shadow: 0 0 0 var(--color-transparent);
--tw-shadow-colored: 0 0 0 var(--color-transparent);
}
/* Ydisks 超椭圆 logo 容器:用 squircle mask 实现真超椭圆(比圆角矩形更鼓)。
mask 让容器背景色(蓝)也裁成超椭圆形状。
shadow 改用 filter:drop-shadow,跟随 mask 后的实际形状(box-shadow 会被 mask 裁掉)。 */
@@ -34,50 +185,73 @@ html, body, #root {
body {
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: #F4F5F7;
color: #ffffff;
background-color: rgb(var(--color-canvas));
color: rgb(var(--color-ink));
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* 闲鱼风格卡片 */
.ios-card {
background: #FFFFFF;
background: rgb(var(--color-surface));
border-radius: 8px;
border: 1px solid rgba(0, 0, 0, 0.02);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
border: 1px solid rgb(var(--color-black) / 0.02);
box-shadow: var(--shadow-card);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.ios-card:hover {
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.06);
box-shadow: 0 12px 32px rgb(var(--color-black) / 0.06);
}
/* 仪表盘饼图是展示型图表,避免 Recharts 的 SVG 焦点框和扇区焦点框形成无意义长条。 */
.dashboard-pie-chart .recharts-surface:focus,
.dashboard-pie-chart .recharts-pie:focus,
.dashboard-pie-chart .recharts-pie-sector:focus,
.dashboard-pie-chart .recharts-sector:focus {
outline: none;
}
/* 营收柱形/折线图的数据图形点击后不显示浏览器默认的粗蓝色 SVG 焦点框。 */
.dashboard-revenue-chart .recharts-surface:focus,
.dashboard-revenue-chart .recharts-bar-rectangle:focus,
.dashboard-revenue-chart .recharts-rectangle:focus,
.dashboard-revenue-chart .recharts-curve:focus,
.dashboard-revenue-chart .recharts-dot:focus,
.dashboard-revenue-chart [class*="recharts-zIndex-layer_"]:focus {
outline: none !important;
}
.dashboard-revenue-chart .recharts-bar-rectangle,
.dashboard-revenue-chart .recharts-rectangle {
stroke: none !important;
}
/* 闲鱼风格输入框 */
.ios-input {
background: #F7F8FA;
border: 1px solid transparent;
background: rgb(var(--color-surface-subtle));
border: 1px solid var(--color-transparent);
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
color: #111;
color: rgb(var(--color-ink));
font-weight: 500;
}
.ios-input:focus {
background: #FFFFFF;
border-color: #0094f7;
box-shadow: 0 0 0 4px rgba(0, 148, 247, 0.3);
background: rgb(var(--color-surface));
border-color: rgb(var(--color-brand));
box-shadow: 0 0 0 4px rgb(var(--color-brand) / 0.3);
outline: none;
}
.ios-input::placeholder {
color: #9CA3AF;
color: rgb(var(--color-neutral-400));
font-weight: 400;
}
/* 主按钮 */
.ios-btn-primary {
background: #0094f7;
color: #ffffff;
background: rgb(var(--color-brand));
color: rgb(var(--color-white));
font-weight: 700;
border: none;
transition: all 0.2s cubic-bezier(0.25, 0.8, 0.25, 1);
@@ -85,19 +259,19 @@ body {
}
.ios-btn-primary:hover:not(:disabled) {
background: #0071e3;
background: rgb(var(--color-brand-highlight));
transform: translateY(-1px);
box-shadow: 0 8px 20px rgba(0, 148, 247, 0.3);
box-shadow: var(--shadow-brand-strong);
}
.ios-btn-primary:active:not(:disabled) {
transform: translateY(1px);
box-shadow: 0 2px 8px rgba(0, 148, 247, 0.2);
box-shadow: var(--shadow-brand-soft);
}
.ios-btn-primary:disabled {
background: #F0F0F0;
color: #AAAAAA;
background: rgb(var(--color-neutral-100));
color: rgb(var(--color-neutral-400));
box-shadow: none;
transform: none;
cursor: not-allowed;
@@ -105,32 +279,32 @@ body {
/* 次要按钮 */
.ios-btn-secondary {
background: #F7F8FA;
color: #ffffff;
background: rgb(var(--color-surface-subtle));
color: rgb(var(--color-ink));
font-weight: 600;
border: 1px solid transparent;
border: 1px solid var(--color-transparent);
transition: all 0.2s ease;
cursor: pointer;
}
.ios-btn-secondary:hover {
background: #E5E7EB;
border-color: #D1D5DB;
background: rgb(var(--color-neutral-200));
border-color: rgb(var(--color-neutral-300));
}
/* 危险按钮 */
.ios-btn-danger {
background: #FEE2E2;
color: #DC2626;
background: rgb(var(--color-danger-100));
color: rgb(var(--color-danger-600));
font-weight: 600;
border: 1px solid transparent;
border: 1px solid var(--color-transparent);
transition: all 0.2s ease;
cursor: pointer;
}
.ios-btn-danger:hover {
background: #FECACA;
border-color: #FCA5A5;
background: rgb(var(--color-danger-200));
border-color: rgb(var(--color-danger-300));
}
/* 自定义滚动条 */
@@ -140,16 +314,16 @@ body {
}
::-webkit-scrollbar-track {
background: transparent;
background: var(--color-transparent);
}
::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.1);
background: rgb(var(--color-black) / 0.1);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(0, 0, 0, 0.2);
background: rgb(var(--color-black) / 0.2);
}
/* 动画 */
@@ -211,21 +385,21 @@ body {
/* 文本选择 */
::selection {
background: #0094f7;
color: #fff;
background: rgb(var(--color-brand));
color: rgb(var(--color-white));
}
/* 工具类 */
.text-brand {
color: #0094f7;
color: rgb(var(--color-brand));
}
.bg-brand {
background-color: #0094f7;
background-color: rgb(var(--color-brand));
}
.border-brand {
border-color: #0094f7;
border-color: rgb(var(--color-brand));
}
/* 状态徽章 */
@@ -239,31 +413,31 @@ body {
}
.status-badge-success {
background-color: #D1FAE5;
color: #065F46;
background-color: rgb(var(--color-success-100));
color: rgb(var(--color-success-800));
}
.status-badge-warning {
background-color: #FEF3C7;
color: #92400E;
background-color: rgb(var(--color-warning-100));
color: rgb(var(--color-warning-800));
}
.status-badge-error {
background-color: #FEE2E2;
color: #991B1B;
background-color: rgb(var(--color-danger-100));
color: rgb(var(--color-danger-800));
}
.status-badge-info {
background-color: #DBEAFE;
color: #1E40AF;
background-color: rgb(var(--color-info-100));
color: rgb(var(--color-info-800));
}
/* 加载状态 */
.loading-skeleton {
background: linear-gradient(90deg,
#F3F4F6 0%,
#E5E7EB 50%,
#F3F4F6 100%);
rgb(var(--color-neutral-100)) 0%,
rgb(var(--color-neutral-200)) 50%,
rgb(var(--color-neutral-100)) 100%);
background-size: 200% 100%;
animation: loading 1.5s ease-in-out infinite;
}
@@ -285,7 +459,7 @@ body {
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.4);
background-color: rgb(var(--color-black) / 0.4);
backdrop-filter: blur(8px);
padding: 1rem;
overflow-y: auto;
@@ -299,17 +473,17 @@ body {
margin: auto;
display: flex;
flex-direction: column;
background-color: white;
background-color: rgb(var(--color-white));
border-radius: 10px;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
box-shadow: var(--shadow-modal);
overflow: hidden;
}
.modal-header {
flex-shrink: 0;
padding: 2rem 2rem 1.5rem;
border-bottom: 1px solid #F3F4F6;
background-color: white;
border-bottom: 1px solid rgb(var(--color-neutral-100));
background-color: rgb(var(--color-white));
z-index: 10;
}
@@ -323,8 +497,8 @@ body {
.modal-footer {
flex-shrink: 0;
padding: 1.5rem 2rem 2rem;
border-top: 1px solid #F3F4F6;
background-color: white;
border-top: 1px solid rgb(var(--color-neutral-100));
background-color: rgb(var(--color-white));
z-index: 10;
}
@@ -340,7 +514,7 @@ body {
z-index: 9999;
display: flex;
justify-content: center;
background-color: rgba(0, 0, 0, 0.4);
background-color: rgb(var(--color-black) / 0.4);
backdrop-filter: blur(8px);
padding: 1rem;
overflow-y: auto;
@@ -354,9 +528,9 @@ body {
margin: auto 0;
display: flex;
flex-direction: column;
background-color: white;
background-color: rgb(var(--color-white));
border-radius: 10px;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
box-shadow: var(--shadow-modal);
overflow: hidden;
}
+17
View File
@@ -0,0 +1,17 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
const itemList = readFileSync(resolve(__dirname, 'components/ItemList.tsx'), 'utf8');
describe('item list primary action colors', () => {
test('uses the shared primary blue for batch publishing', () => {
expect(itemList).toContain('bg-brand text-white hover:bg-brand-highlight');
expect(itemList).not.toContain('bg-blue-600 text-white hover:bg-blue-700');
});
test('uses the lighter emerald tone for publishing actions', () => {
expect(itemList).toContain('bg-emerald-500 text-white hover:bg-emerald-600');
expect(itemList).not.toContain('bg-emerald-600 text-white hover:bg-emerald-700');
});
});
+2 -2
View File
@@ -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 -1
View File
@@ -1,5 +1,5 @@
{
"name": "闲鱼自动发货-pro",
"name": "ydisks-xianyu-helper",
"private": true,
"version": "0.0.0",
"type": "module",
+7
View File
@@ -26,6 +26,13 @@ describe('frontend navigation routing', () => {
expect([...sidebarIDs].sort()).toEqual([...appRouteIDs].sort());
});
test('active navigation uses the primary action blue', () => {
const sidebar = readFrontendFile('components/Sidebar.tsx');
expect(sidebar).toContain("'bg-brand text-white shadow-brand-active'");
expect(sidebar).not.toContain("'bg-sky-500 text-white'");
});
test('logout button invalidates the backend session before clearing UI state', () => {
const app = readFrontendFile('App.tsx');
+28
View File
@@ -0,0 +1,28 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
const source = (path: string) => readFileSync(resolve(__dirname, path), 'utf8');
describe('responsive rules layout', () => {
test('allows the rules page to shrink inside the sidebar layout', () => {
const app = source('App.tsx');
const rules = source('components/Rules.tsx');
expect(app).toContain('h-screen min-w-0 flex-1 overflow-x-hidden');
expect(rules).toContain('min-w-0 space-y-8');
expect(rules).toContain('xl:grid-cols-[minmax(270px,0.72fr)_minmax(0,1.28fr)]');
expect(rules).not.toContain('2xl:grid-cols-[360px_1fr]');
});
});
describe('rules summary counts', () => {
test('uses server-side aggregate counts instead of the current page length', () => {
const rules = source('components/Rules.tsx');
const api = source('services/api.ts');
expect(rules).toContain('automationTriggerCounts');
expect(rules).toContain('{automationTriggerCounts[trigger] || 0}');
expect(rules).toContain('筛选结果构成');
expect(rules).not.toContain('rulesByTrigger[trigger].length');
expect(api).toContain('trigger_counts');
});
});
+71
View File
@@ -15,6 +15,7 @@ import {
getOrderAnalytics,
getReplyRules,
getShippingRules,
getShippingRulesPage,
getSystemSettings,
getValidOrders,
logout,
@@ -32,6 +33,12 @@ import {
updateNotificationChannel,
updateSystemSettings,
updateShippingRule,
getChatSessions,
getChatMessages,
sendChatMessage,
markChatRead,
updateAccountTaskSettings,
runAccountTask,
} from './api';
afterEach(() => {
@@ -48,6 +55,36 @@ test('updateSystemSettings uses one atomic bulk request', async () => {
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ theme_color: 'blue', renewal_log_retention_days: 15 });
});
test('chat APIs preserve account and conversation scope', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ sessions: [{ account_id: 'a1', chat_id: 'c1' }] }))
.mockResolvedValueOnce(jsonResponse({ messages: [{ account_id: 'a1', chat_id: 'c1', id: 1 }] }))
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })));
vi.stubGlobal('fetch', fetchMock);
await getChatSessions('a1');
await getChatMessages('a1', 'c1', 9);
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' });
await markChatRead('a1', 'c1');
expect(fetchMock.mock.calls[0][0]).toBe('/api/chat/sessions?account_id=a1');
expect(fetchMock.mock.calls[1][0]).toBe('/api/chat/messages?account_id=a1&chat_id=c1&before_id=9');
expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' });
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' });
});
test('account task APIs keep rating and polish account-scoped', async () => {
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })));
vi.stubGlobal('fetch', fetchMock);
await updateAccountTaskSettings('a1', {
account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快',
auto_polish_enabled: true, polish_time: '03:00',
});
await runAccountTask('a1', 'auto_rate');
expect(fetchMock.mock.calls[0][0]).toBe('/api/account-tasks/a1');
expect(fetchMock.mock.calls[0][1].method).toBe('PUT');
expect(fetchMock.mock.calls[1][0]).toBe('/api/account-tasks/a1/run');
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ task_type: 'auto_rate' });
});
test('getItemPublishBatches unwraps persisted batch list', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] }));
vi.stubGlobal('fetch', fetchMock);
@@ -108,6 +145,40 @@ 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,
trigger_counts: { order_paid: 8, buyer_reviewed: 7, review_missing_timeout: 6 },
}));
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,
trigger_counts: { order_paid: 8, buyer_reviewed: 7, review_missing_timeout: 6 },
});
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' }],
+130 -5
View File
@@ -2,8 +2,9 @@ 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
, AccountTaskSettings, AccountTaskSummary, ChatSession, ChatMessage
} from '../types';
import { formatLocalDate } from '../dateRange';
@@ -82,9 +83,70 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis
avatar_url: accountAvatarURL(item, avatarVersion),
profile_error: item.profile_error || '',
ai_enabled: false,
auto_rate_enabled: item.auto_rate_enabled === true || item.auto_rate_enabled === 1,
rate_content: item.rate_content || '不错的买家,交易愉快',
auto_polish_enabled: item.auto_polish_enabled === true || item.auto_polish_enabled === 1,
polish_time: item.polish_time || '03:00',
last_rate_scan_at: Number(item.last_rate_scan_at || 0),
last_polish_date: item.last_polish_date || '',
last_polish_at: Number(item.last_polish_at || 0),
}));
};
export const getAccountTaskSettings = async (id: string): Promise<AccountTaskSettings> =>
get(`/api/account-tasks/${id}`);
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings): Promise<AccountTaskSettings> =>
put(`/api/account-tasks/${id}`, settings);
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish'): Promise<{success: boolean; summary: AccountTaskSummary}> =>
post(`/api/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000 });
export interface ChatSessionPage { sessions: ChatSession[]; has_more: boolean; next_cursor?: number }
export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise<ChatSessionPage> => {
const result = await get<ChatSessionPage>('/api/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined },
refresh ? { timeoutMs: 60_000, ...options } : options);
return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor };
};
export const getChatSessions = async (accountId: string, options?: RequestControlOptions): Promise<ChatSession[]> =>
(await getChatSessionPage(accountId, undefined, options)).sessions;
export interface ChatMessagePage {
messages: ChatMessage[];
has_more: boolean;
next_cursor?: number;
session?: ChatSession;
}
export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessagePage> => {
const result = await get<ChatMessagePage>('/api/chat/messages', {
account_id: accountId, chat_id: chatId, cursor, before_id: beforeId,
}, options);
return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session };
};
export const getChatMessages = async (accountId: string, chatId: string, beforeId?: number, options?: RequestControlOptions): Promise<ChatMessage[]> =>
(await getChatMessagePage(accountId, chatId, undefined, beforeId, options)).messages;
export const sendChatMessage = async (input: {
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
item_id?: string; item_title?: string; text: string;
}): Promise<{message: ChatMessage}> => post('/api/chat/messages', input);
export const sendChatImage = async (input: {
account_id: string; chat_id: string; buyer_id: string; buyer_name?: string;
buyer_avatar_url?: string; item_id?: string; item_title?: string; image: File;
}): Promise<{message: ChatMessage}> => {
const form = new FormData();
Object.entries(input).forEach(([key, value]) => form.append(key, value));
return postForm('/api/chat/images', form, { timeoutMs: 120_000 });
};
export const markChatRead = async (accountId: string, chatId: string): Promise<ApiResponse> =>
post('/api/chat/read', { account_id: accountId, chat_id: chatId });
export interface AccountRuntimeStatus {
state: NonNullable<AccountDetail['runtime_state']>;
message?: string;
@@ -476,15 +538,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 +602,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 +646,50 @@ 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)),
trigger_counts: Object.fromEntries(
Object.entries(res.trigger_counts || {}).map(([key, value]) => [key, Number(value)]),
),
};
}
const orderAutomationActions = (triggerType: string, actions: AutomationAction[]) => {
+62 -10
View File
@@ -1,3 +1,10 @@
const color = (token) => `rgb(var(--color-${token}) / <alpha-value>)`;
const palette = (name) => Object.fromEntries(
[50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]
.map((shade) => [shade, color(`${name}-${shade}`)]),
);
/** @type {import('tailwindcss').Config} */
export default {
content: [
@@ -8,18 +15,40 @@ export default {
theme: {
extend: {
colors: {
// Ydisks 官网配色:Apple 风格蓝色系 + 浅灰背景 + 深色文字。
// 具体色值统一维护在 index.css 的 --color-* 令牌中,组件只使用语义化 Tailwind 类名。
transparent: 'var(--color-transparent)',
current: 'currentColor',
black: color('black'),
white: color('white'),
brand: {
DEFAULT: '#0094f7', // 主品牌蓝(Ydisks logo/按钮色)
dark: '#0071e3', // 深蓝(hover/强调)
light: '#287efe', // 亮蓝(辅助)
DEFAULT: color('brand'),
highlight: color('brand-highlight'),
light: color('brand-light'),
},
// Ydisks 中性色
ink: '#1d1d1f', // 主文字
muted: '#86868b', // 次要文字
line: '#d2d2d7', // 边框/分隔
canvas: '#fbfbfd', // 页面背景
surface: '#f5f5f7', // 卡片背景/区块
ink: color('ink'),
muted: color('muted'),
line: color('line'),
canvas: color('canvas'),
surface: color('surface'),
'surface-subtle': color('surface-subtle'),
'surface-muted': color('surface-muted'),
success: palette('success'),
warning: palette('warning'),
danger: palette('danger'),
info: palette('info'),
// 保留现有 Tailwind 语义类,但统一指向同一套设计令牌。
gray: palette('neutral'),
slate: palette('slate'),
blue: palette('brand'),
sky: palette('brand'),
emerald: palette('success'),
green: palette('success'),
amber: palette('warning'),
orange: palette('warning'),
red: palette('danger'),
yellow: palette('warning'),
purple: palette('accent'),
pink: palette('accent'),
},
// 圆角统一收紧到 5–10px 区间,UI 更紧凑、信息密度更高。
borderRadius: {
@@ -45,6 +74,29 @@ export default {
'sans-serif',
],
},
accentColor: {
brand: color('brand'),
},
boxShadow: {
none: 'var(--shadow-none)',
sm: 'var(--shadow-sm)',
DEFAULT: 'var(--shadow-default)',
md: 'var(--shadow-md)',
lg: 'var(--shadow-lg)',
xl: 'var(--shadow-xl)',
'2xl': 'var(--shadow-2xl)',
inner: 'var(--shadow-inner)',
card: 'var(--shadow-card)',
panel: 'var(--shadow-panel)',
modal: 'var(--shadow-modal)',
sidebar: 'var(--shadow-sidebar)',
chat: 'var(--shadow-chat)',
'chat-input': 'var(--shadow-chat-input)',
'chat-active': 'var(--shadow-chat-active)',
'brand-soft': 'var(--shadow-brand-soft)',
'brand-active': 'var(--shadow-brand-active)',
'brand-strong': 'var(--shadow-brand-strong)',
},
},
},
plugins: [],
+57
View File
@@ -13,6 +13,7 @@ export interface PaginatedResponse<T> {
page: number;
page_size: number;
total_pages: number;
trigger_counts?: Record<string, number>;
}
// Auth
@@ -55,6 +56,62 @@ export interface AccountDetail {
max_discount_amount?: number;
max_bargain_rounds?: number;
custom_prompts?: string;
// 账号级计划任务
auto_rate_enabled?: boolean;
rate_content?: string;
auto_polish_enabled?: boolean;
polish_time?: string;
last_rate_scan_at?: number;
last_polish_date?: string;
last_polish_at?: number;
}
export interface AccountTaskSettings {
account_id: string;
auto_rate_enabled: boolean;
rate_content: string;
auto_polish_enabled: boolean;
polish_time: string;
last_rate_scan_at?: number;
last_polish_date?: string;
last_polish_at?: number;
}
export interface AccountTaskSummary {
task_type: 'auto_rate' | 'auto_polish';
found: number;
success: number;
failed: number;
skipped: number;
message?: string;
}
export interface ChatSession {
account_id: string;
chat_id: string;
buyer_id: string;
buyer_name: string;
buyer_avatar_url?: string;
item_id?: string;
item_title?: string;
last_message: string;
last_message_at: number;
unread_count: number;
}
export interface ChatMessage {
id: number;
account_id: string;
chat_id: string;
message_key: string;
direction: 'incoming' | 'outgoing';
sender_id: string;
sender_name: string;
/** text/image/video are peer messages; system is an official platform notice or trade card. */
message_type: 'text' | 'image' | 'video' | 'system';
content: string;
status: 'received' | 'sending' | 'sent' | 'failed';
sent_at: number;
}
// Orders
+1
View File
@@ -12,6 +12,7 @@ export default defineConfig({
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
ws: true,
},
// 代理其他后端请求
'/cookies': {
+107 -47
View File
@@ -16,6 +16,7 @@ import (
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
"xianyu-go/internal/chat"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/renewal"
@@ -65,6 +66,7 @@ type Adapter struct {
cooldown *renewal.CooldownManager
captchaReq tokenCaptchaRequester
orderMTop orderDetailClient
chat *chat.Service
orderFetchMu sync.Mutex
lastOrderFetch time.Time
@@ -126,9 +128,37 @@ func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaR
// SetOrderDetailClient 覆盖纯 Go 订单详情客户端,便于测试隔离网络。
func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
// SetChatService installs the user-facing chat side channel. It persists and
// broadcasts messages without changing the automatic reply path.
func (a *Adapter) SetChatService(service *chat.Service) { a.chat = service }
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
return nil
func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMessage) error {
if a.chat == nil {
return nil
}
// Xianyu echoes messages sent by this account back over the same WS. Those
// sends are already captured by HandleOutgoingChatMessage; recording the
// echo as incoming would put our own bubble on the buyer side and duplicate it.
if strings.TrimSuffix(message.SenderUserID, "@goofish") == strings.TrimSuffix(message.AccountID, "@goofish") {
return nil
}
_, _, err := a.chat.RecordIncoming(ctx, chat.Incoming{
AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID,
BuyerName: message.SenderName, Text: message.Text, ItemID: message.ItemID, Raw: message.Raw,
})
return err
}
// HandleOutgoingChatMessage records successful manual/automatic text sends as
// a side channel; it never participates in platform delivery.
func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.OutgoingChatMessage) error {
if a.chat == nil {
return nil
}
_, err := a.chat.RecordOutgoingSent(ctx, db.ChatSession{CookieID: message.AccountID, ChatID: message.ChatID,
BuyerID: message.BuyerID}, message.MessageKey, message.Text)
return err
}
// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器,
@@ -342,6 +372,19 @@ 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.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()
@@ -387,6 +430,7 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
} else {
cookieStr = authoritativeCookies
a.wakeCredentialBlockedAutomation(ctx, cookieID)
}
}
if fetchErr != nil {
@@ -400,6 +444,7 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
}
a.wakeCredentialBlockedAutomation(ctx, cookieID)
}
return &automation.OrderDetail{
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
@@ -407,6 +452,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
@@ -454,6 +508,7 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
renewed, renewErr := a.tryProtocolCredentialRenew(ctx, d)
if renewed {
a.wakeCredentialBlockedAutomation(ctx, cookieID)
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "Go 协议续期成功")
return true
}
@@ -467,6 +522,21 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
return false
}
// RecoverExpiredCredential 供自动化外部动作在平台明确拒绝旧 Session 后恢复凭证。
func (a *Adapter) RecoverExpiredCredential(ctx context.Context, cookieID string) bool {
return a.OnPasswordLoginRefresh(ctx, cookieID)
}
// OnCredentialUpdated 接收账号运行时保存的新凭证并唤醒失败任务。
func (a *Adapter) OnCredentialUpdated(ctx context.Context, cookieID string) {
a.wakeCredentialBlockedAutomation(ctx, cookieID)
}
// OnTransportReady 在 WS 注册完成后立即唤醒发送前明确未执行的任务。
func (a *Adapter) OnTransportReady(ctx context.Context, cookieID string) {
a.wakeCredentialBlockedAutomation(ctx, cookieID)
}
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
a.passwordMu.Lock()
defer a.passwordMu.Unlock()
@@ -551,7 +621,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 +634,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 +677,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)
+102
View File
@@ -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)
+229
View File
@@ -0,0 +1,229 @@
package automation
import (
"context"
"fmt"
"strings"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
const (
TaskAutoRate = "auto_rate"
TaskAutoPolish = "auto_polish"
polishItemPageSize = 20
polishItemMaxPages = 20
)
type AccountTaskClient interface {
FetchPendingRateOrders(ctx context.Context, cookiesStr string, page, pageSize int) (*mtop.PendingRateResult, error)
RateBuyer(ctx context.Context, cookiesStr, tradeID, feedback string) (*mtop.AccountTaskResult, error)
FetchAllItems(ctx context.Context, cookiesStr string, pageSize, maxPages int) (*mtop.ItemListResult, error)
PolishItem(ctx context.Context, cookiesStr, itemID string) (*mtop.AccountTaskResult, error)
}
type AccountTaskSummary struct {
TaskType string `json:"task_type"`
Found int `json:"found"`
Success int `json:"success"`
Failed int `json:"failed"`
Skipped int `json:"skipped"`
Message string `json:"message,omitempty"`
}
func (c *Center) RunAccountTask(ctx context.Context, accountID, taskType string) (AccountTaskSummary, error) {
allowed, err := c.accountAutomationAllowed(ctx, accountID)
if err != nil {
return AccountTaskSummary{TaskType: taskType}, err
}
if !allowed {
return AccountTaskSummary{TaskType: taskType}, fmt.Errorf("账号已停用或暂停,无法执行任务")
}
settings, err := c.store.AccountTasks.Get(ctx, accountID)
if err != nil {
return AccountTaskSummary{TaskType: taskType}, err
}
switch taskType {
case TaskAutoRate:
return c.runAutoRate(ctx, settings)
case TaskAutoPolish:
return c.runAutoPolish(ctx, settings, beijingNow(), true)
default:
return AccountTaskSummary{TaskType: taskType}, fmt.Errorf("不支持的账号任务: %s", taskType)
}
}
func (c *Center) scanAccountTasks(ctx context.Context) {
if c.accountTasks == nil || c.store.AccountTasks == nil {
return
}
settings, err := c.store.AccountTasks.Enabled(ctx)
if err != nil {
c.logger.Warn("扫描账号任务配置失败", "err", err)
return
}
now := beijingNow()
for _, setting := range settings {
allowed, err := c.accountAutomationAllowed(ctx, setting.CookieID)
if err != nil || !allowed {
continue
}
if setting.AutoRateEnabled {
if _, err := c.runAutoRate(ctx, setting); err != nil {
c.logger.Warn("自动评价扫描失败", "account", setting.CookieID, "err", err)
}
}
if setting.AutoPolishEnabled && polishDue(setting, now) {
if _, err := c.runAutoPolish(ctx, setting, now, false); err != nil {
c.logger.Warn("每日擦亮失败", "account", setting.CookieID, "err", err)
}
}
}
}
func (c *Center) runAutoRate(ctx context.Context, settings db.AccountTaskSettings) (AccountTaskSummary, error) {
summary := AccountTaskSummary{TaskType: TaskAutoRate}
if c.accountTasks == nil {
return summary, fmt.Errorf("自动评价客户端未初始化")
}
cookies, err := c.store.Cookies.GetValue(ctx, settings.CookieID)
if err != nil {
return summary, err
}
current := cookies
var orders []mtop.PendingRateOrder
for page := 1; page <= 20; page++ {
pending, err := c.accountTasks.FetchPendingRateOrders(ctx, current, page, 50)
if err != nil {
return summary, err
}
current = c.persistTaskCookies(ctx, settings.CookieID, current, pending.UpdatedCookies)
orders = append(orders, pending.Orders...)
if len(pending.Orders) < 50 {
break
}
}
summary.Found = len(orders)
for _, order := range orders {
runKey := "rate:" + settings.CookieID + ":" + order.TradeID
claimed, err := c.store.AccountTasks.ClaimRun(ctx, db.AccountTaskRun{RunKey: runKey, CookieID: settings.CookieID,
TaskType: TaskAutoRate, TargetID: order.TradeID}, time.Now().UTC().Unix())
if err != nil {
return summary, err
}
if !claimed {
summary.Skipped++
continue
}
result, rateErr := c.accountTasks.RateBuyer(ctx, current, order.TradeID, settings.RateContent)
if rateErr != nil || result == nil || !result.Success {
message := errorString(rateErr)
if result != nil && result.Message != "" {
message = result.Message
}
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, message, time.Now().UTC().Add(10*time.Minute).Unix())
summary.Failed++
continue
}
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "success", 1, 0, "", 0)
summary.Success++
}
_ = c.store.AccountTasks.MarkRateScan(ctx, settings.CookieID, time.Now().UTC().Unix())
return summary, nil
}
func (c *Center) runAutoPolish(ctx context.Context, settings db.AccountTaskSettings, now time.Time, manual bool) (AccountTaskSummary, error) {
summary := AccountTaskSummary{TaskType: TaskAutoPolish}
if c.accountTasks == nil {
return summary, fmt.Errorf("擦亮客户端未初始化")
}
date := now.Format("2006-01-02")
runKey := "polish:" + settings.CookieID + ":" + date
run := db.AccountTaskRun{RunKey: runKey, CookieID: settings.CookieID, TaskType: TaskAutoPolish, RunDate: date}
var claimed bool
var err error
if manual {
claimed, err = c.store.AccountTasks.ClaimRunImmediately(ctx, run, time.Now().UTC().Unix())
} else {
claimed, err = c.store.AccountTasks.ClaimRun(ctx, run, time.Now().UTC().Unix())
}
if err != nil || !claimed {
if !claimed && err == nil {
summary.Skipped = 1
summary.Message = "今天已经执行过擦亮"
}
return summary, err
}
cookies, err := c.store.Cookies.GetValue(ctx, settings.CookieID)
if err != nil {
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
return summary, err
}
items, err := c.accountTasks.FetchAllItems(ctx, cookies, polishItemPageSize, polishItemMaxPages)
if err != nil {
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
return summary, err
}
current := c.persistTaskCookies(ctx, settings.CookieID, cookies, items.UpdatedCookies)
summary.Found = len(items.Items)
var lastError string
for _, item := range items.Items {
result, polishErr := c.accountTasks.PolishItem(ctx, current, item.ID)
if polishErr != nil || result == nil || !result.Success {
summary.Failed++
lastError = errorString(polishErr)
if result != nil && result.Message != "" {
lastError = result.Message
}
continue
}
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
summary.Success++
}
status, retryAt := "success", int64(0)
if summary.Failed > 0 {
status, retryAt = "failed", time.Now().UTC().Add(10*time.Minute).Unix()
} else {
_ = c.store.AccountTasks.MarkPolished(ctx, settings.CookieID, date, time.Now().UTC().Unix())
}
_ = c.store.AccountTasks.FinishRun(ctx, runKey, status, summary.Success, summary.Failed, lastError, retryAt)
if summary.Failed > 0 {
return summary, fmt.Errorf("%d 个商品擦亮失败: %s", summary.Failed, lastError)
}
return summary, nil
}
func (c *Center) persistTaskCookies(ctx context.Context, accountID, oldValue, newValue string) string {
newValue = strings.TrimSpace(newValue)
if newValue == "" || newValue == oldValue {
return oldValue
}
if err := c.store.Cookies.UpdateValueExisting(ctx, accountID, newValue); err != nil {
c.logger.Warn("保存账号任务响应 Cookie 失败", "account", accountID, "err", err)
return oldValue
}
if c.senders != nil {
if sender, ok := c.senders.Sender(accountID); ok && sender != nil {
sender.UpdateCookie(newValue)
}
}
return newValue
}
func beijingNow() time.Time {
return time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
}
func polishDue(settings db.AccountTaskSettings, now time.Time) bool {
if settings.LastPolishDate == now.Format("2006-01-02") {
return false
}
target, err := time.Parse("15:04", settings.PolishTime)
if err != nil {
target, _ = time.Parse("15:04", "03:00")
}
return now.Hour() > target.Hour() || now.Hour() == target.Hour() && now.Minute() >= target.Minute()
}
+156
View File
@@ -0,0 +1,156 @@
package automation
import (
"context"
"errors"
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
type fakeAccountTaskClient struct {
pendingCalls int
rateCalls int
polishCalls int
pending []mtop.PendingRateOrder
items []mtop.ItemListItem
fetchItemsErr error
fetchPageSize int
fetchMaxPages int
polishErr error
}
func (f *fakeAccountTaskClient) FetchPendingRateOrders(context.Context, string, int, int) (*mtop.PendingRateResult, error) {
f.pendingCalls++
return &mtop.PendingRateResult{Orders: f.pending}, nil
}
func (f *fakeAccountTaskClient) RateBuyer(context.Context, string, string, string) (*mtop.AccountTaskResult, error) {
f.rateCalls++
return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil
}
func (f *fakeAccountTaskClient) FetchAllItems(_ context.Context, _ string, pageSize, maxPages int) (*mtop.ItemListResult, error) {
f.fetchPageSize, f.fetchMaxPages = pageSize, maxPages
if f.fetchItemsErr != nil {
return nil, f.fetchItemsErr
}
return &mtop.ItemListResult{Items: f.items}, nil
}
func (f *fakeAccountTaskClient) PolishItem(context.Context, string, string) (*mtop.AccountTaskResult, error) {
f.polishCalls++
if f.polishErr != nil {
return nil, f.polishErr
}
return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil
}
func TestAccountTaskRateIsOrderIdempotent(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-1"}, {TradeID: "order-2"}}}
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
center.SetAccountTaskClient(client)
ctx := context.Background()
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true,
RateContent: "交易愉快", PolishTime: "03:00"}); err != nil {
t.Fatal(err)
}
first, err := center.RunAccountTask(ctx, "cid", TaskAutoRate)
if err != nil || first.Success != 2 || client.rateCalls != 2 {
t.Fatalf("first=%+v calls=%d err=%v", first, client.rateCalls, err)
}
second, err := center.RunAccountTask(ctx, "cid", TaskAutoRate)
if err != nil || second.Skipped != 2 || client.rateCalls != 2 {
t.Fatalf("second=%+v calls=%d err=%v", second, client.rateCalls, err)
}
}
func TestAccountTaskPolishRunsOncePerBeijingDay(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}, {ID: "item-2"}}}
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
center.SetAccountTaskClient(client)
ctx := context.Background()
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
t.Fatal(err)
}
first, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
if err != nil || first.Success != 2 || client.polishCalls != 2 {
t.Fatalf("first=%+v calls=%d err=%v", first, client.polishCalls, err)
}
if client.fetchPageSize != 20 || client.fetchMaxPages != 20 {
t.Fatalf("unexpected item pagination: pageSize=%d maxPages=%d", client.fetchPageSize, client.fetchMaxPages)
}
second, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
if err != nil || second.Skipped != 1 || client.polishCalls != 2 {
t.Fatalf("second=%+v calls=%d err=%v", second, client.polishCalls, err)
}
settings, err := store.AccountTasks.Get(ctx, "cid")
if err != nil || settings.LastPolishDate != beijingNow().Format("2006-01-02") {
t.Fatalf("settings=%+v err=%v", settings, err)
}
}
func TestManualPolishReportsItemFailures(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, polishErr: errors.New("both polish APIs failed")}
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
center.SetAccountTaskClient(client)
ctx := context.Background()
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
t.Fatal(err)
}
summary, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
if err == nil || summary.Failed != 1 || summary.Success != 0 {
t.Fatalf("summary=%+v err=%v", summary, err)
}
}
func TestManualPolishCanRetryImmediatelyAfterFailure(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, fetchItemsErr: errors.New("upstream 502")}
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
center.SetAccountTaskClient(client)
ctx := context.Background()
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
t.Fatal(err)
}
if _, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish); err == nil {
t.Fatal("first polish should expose the upstream failure")
}
client.fetchItemsErr = nil
second, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
if err != nil || second.Success != 1 || second.Skipped != 0 || client.polishCalls != 1 {
t.Fatalf("manual retry=%+v calls=%d err=%v", second, client.polishCalls, err)
}
third, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
if err != nil || third.Skipped != 1 || client.polishCalls != 1 {
t.Fatalf("successful day must remain idempotent: summary=%+v calls=%d err=%v", third, client.polishCalls, err)
}
}
func TestPolishDueHonorsConfiguredTimeAndDate(t *testing.T) {
now := beijingNow()
settings := db.AccountTaskSettings{PolishTime: now.Add(2 * time.Hour).Format("15:04")}
if polishDue(settings, now) && now.Hour() < 22 {
t.Fatal("task must not run before configured time")
}
settings.PolishTime = "00:00"
if !polishDue(settings, now) {
t.Fatal("task should be due after midnight")
}
settings.LastPolishDate = now.Format("2006-01-02")
if polishDue(settings, now) {
t.Fatal("task must not run twice on the same Beijing date")
}
}
+188 -38
View File
@@ -19,8 +19,19 @@ import (
var (
errAutomationDeferred = errors.New("自动化动作已持久化等待执行")
errAutomationNeedsReview = errors.New("自动化动作结果需要人工核对")
errAutomationQuarantine = errors.New("自动化人工核对状态保存失败")
errActionNotPerformed = 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,12 +61,23 @@ type MessageSender interface {
UpdateCookie(cookieStr string)
}
// automationReadySender 由能够报告实时连接状态的发送器选择性实现。
// 未实现的测试或外部发送器保持向后兼容,视为已经就绪。
type automationReadySender interface {
AutomationReady() bool
}
// OrderDetailFetcher 查询闲鱼订单详情。自动发货必须先拿到订单规格和购买数量,
// 再按规则里的规格映射发货。
type OrderDetailFetcher interface {
FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*OrderDetail, error)
}
// CredentialRecoverer 在平台明确返回 Session 失效时执行一次凭证恢复。
type CredentialRecoverer interface {
RecoverExpiredCredential(ctx context.Context, cookieID string) bool
}
// Notifier 发货结果通知器(多渠道)。可选依赖,未注入时跳过通知。
type Notifier interface {
NotifyDelivery(accountID, buyerName, buyerID, itemID, message, chatID string)
@@ -64,14 +86,16 @@ type Notifier interface {
// Center 是统一自动化处理中心。
// 它只接收已经分类好的系统事件或计划任务,不处理用户消息;用户消息由 engine 的回复链处理。
type Center struct {
store *db.Store
senders SenderProvider
fetcher OrderDetailFetcher
notifier Notifier
mtop mtop.Client
logger *slog.Logger
cookieSrc func(context.Context, string) (string, error)
cardLocks sync.Map
store *db.Store
senders SenderProvider
fetcher OrderDetailFetcher
recoverer CredentialRecoverer
notifier Notifier
mtop mtop.Client
accountTasks AccountTaskClient
logger *slog.Logger
cookieSrc func(context.Context, string) (string, error)
cardLocks sync.Map
}
// New 构造自动化中心。
@@ -79,15 +103,22 @@ func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center {
if logger == nil {
logger = slog.Default()
}
return &Center{store: store, senders: senders, mtop: mtop.NewClient(), logger: logger.With("subsys", "automation")}
client := mtop.NewClient()
return &Center{store: store, senders: senders, mtop: client, accountTasks: client, logger: logger.With("subsys", "automation")}
}
// SetMTop 注入 mtop 客户端(确认发货用)。未注入时使用默认 HTTP 实现。
func (c *Center) SetMTop(m mtop.Client) { c.mtop = m }
// SetAccountTaskClient overrides automatic rating/polish transport for tests.
func (c *Center) SetAccountTaskClient(client AccountTaskClient) { c.accountTasks = client }
// SetOrderDetailFetcher 注入订单详情查询能力。
func (c *Center) SetOrderDetailFetcher(fetcher OrderDetailFetcher) {
c.fetcher = fetcher
if recoverer, ok := fetcher.(CredentialRecoverer); ok {
c.recoverer = recoverer
}
}
// SetNotifier 注入发货结果通知器。
@@ -114,7 +145,16 @@ 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
}
if task.OrderID != "" {
if order, orderErr := c.store.Orders.Get(ctx, task.OrderID); orderErr == nil && order != nil {
task = mergeOrderIntoTask(task, order)
} else if orderErr != nil && !errors.Is(orderErr, db.ErrNotFound) {
return false, fmt.Errorf("读取自动化事件订单事实: %w", orderErr)
}
}
paused, until, err := c.store.Cookies.IsPaused(ctx, task.AccountID)
if err != nil {
return false, err
@@ -161,6 +201,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 +244,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 +264,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 +408,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 == "" {
@@ -420,15 +481,19 @@ func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationR
}
if errors.Is(err, errAutomationNeedsReview) {
finish = false
if c.notifier != nil {
if c.notifier != nil && !errors.Is(err, errAutomationQuarantine) {
c.notifyResult(task, "needs_review", sent, err.Error())
}
return err
}
if err != nil {
if sent > 0 {
if sent > 0 && !errors.Is(err, ErrMessageNotSent) && !errors.Is(err, errActionNotPerformed) {
reason := "运行已完成部分动作,后续动作失败,已禁止从头自动重放: " + err.Error()
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason)
if quarantineErr := c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason); quarantineErr != nil {
finish = false
c.logger.Error("保存自动化人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
return errors.Join(errAutomationNeedsReview, errAutomationQuarantine, err, quarantineErr)
}
finish = false
if c.notifier != nil {
c.notifyResult(task, "needs_review", sent, reason)
@@ -436,12 +501,19 @@ func (c *Center) executeRule(ctx context.Context, task Task, rule db.AutomationR
return fmt.Errorf("%w: %v", errAutomationNeedsReview, err)
}
status, errMsg = "failed", err.Error()
if errors.Is(err, ErrMessageNotSent) || errors.Is(err, errActionNotPerformed) {
errMsg = db.SafeRetryErrorPrefix + errMsg
}
return err
}
if task.TriggerType == TriggerReviewMissingTimeout && task.OrderID != "" {
if incrementErr := c.store.Automation.IncrementReviewRequest(ctx, task.OrderID); incrementErr != nil {
reason := "求评价消息已发送,但保存提醒次数失败,已停止自动重放: " + incrementErr.Error()
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason)
if quarantineErr := c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent, reason); quarantineErr != nil {
finish = false
c.logger.Error("保存求评价人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
return errors.Join(errAutomationNeedsReview, errAutomationQuarantine, incrementErr, quarantineErr)
}
finish = false
if c.notifier != nil {
c.notifyResult(task, "needs_review", sent, reason)
@@ -513,14 +585,26 @@ func (c *Center) executeRunActions(ctx context.Context, task Task, ruleID int64,
var uncertain *uncertainActionError
if n > 0 || errors.As(actionErr, &uncertain) {
reason := "外部动作可能已部分或全部执行,已禁止自动重放,请人工核对: " + actionErr.Error()
_ = c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent+n, reason)
if quarantineErr := c.store.Automation.QuarantineRunResult(ctx, run.ID, run.AttemptCount, sent+n, reason); quarantineErr != nil {
c.logger.Error("保存不确定动作人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
return sent + n, false, errors.Join(errAutomationNeedsReview, errAutomationQuarantine, actionErr, quarantineErr)
}
return sent + n, false, fmt.Errorf("%w: %v", errAutomationNeedsReview, actionErr)
}
_ = c.store.Automation.AbortRunAction(ctx, run.ID, run.AttemptCount, cursor)
if abortErr := c.store.Automation.AbortRunAction(ctx, run.ID, run.AttemptCount, cursor); abortErr != nil {
reason := "外部动作明确未执行,但清除动作占用状态失败,已停止自动重放: " + abortErr.Error()
if quarantineErr := c.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason); quarantineErr != nil {
c.logger.Error("隔离动作状态异常的自动化运行失败", "run_id", run.ID, "err", quarantineErr)
}
return sent, false, fmt.Errorf("%w: %s", errAutomationNeedsReview, reason)
}
return sent, false, actionErr
}
if err := c.store.Automation.AdvanceRunAction(ctx, run.ID, run.AttemptCount, cursor, n); err != nil {
_ = c.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, "动作已执行但检查点保存失败,请人工核对,禁止自动重放: "+err.Error())
if quarantineErr := c.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, "动作已执行但检查点保存失败,请人工核对,禁止自动重放: "+err.Error()); quarantineErr != nil {
c.logger.Error("保存检查点异常的人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
return sent + n, false, errors.Join(errAutomationNeedsReview, errAutomationQuarantine, err, quarantineErr)
}
return sent + n, false, fmt.Errorf("%w: %v", errAutomationNeedsReview, err)
}
sent += n
@@ -615,15 +699,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 +798,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
@@ -733,6 +820,10 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
if !enabled && !task.ForceConfirmShipment {
return nil
}
return c.confirmShipmentAttempt(ctx, task, true)
}
func (c *Center) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error {
credentialUnlock := c.store.LockAccountCredentials(task.AccountID)
credentialLocked := true
defer func() {
@@ -798,6 +889,26 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
sender.UpdateCookie(runtimeCookie)
}
}
if runtimeCookieChanged {
c.wakeCredentialBlockedAutomation(ctx, task.AccountID)
}
sessionErr := callErr
if sessionErr == nil && !ok {
sessionErr = errors.New(strings.Join(ret, "; "))
}
if mtop.IsSessionExpiredErr(sessionErr) {
if len(persistenceErrs) > 0 {
return errors.Join(fmt.Errorf("确认发货 Session 已失效: %w", sessionErr), errors.Join(persistenceErrs...))
}
if allowCredentialRecovery && c.recoverer != nil && c.recoverer.RecoverExpiredCredential(ctx, task.AccountID) {
c.logger.Info("确认发货凭证恢复成功,重新执行确认发货", "account", task.AccountID, "order_id", task.OrderID)
return c.confirmShipmentAttempt(ctx, task, false)
}
if !allowCredentialRecovery {
return fmt.Errorf("%w: 确认发货在凭证恢复后仍返回 Session 失效: %v", errActionNotPerformed, sessionErr)
}
return fmt.Errorf("%w: 确认发货 Session 已失效且凭证恢复失败: %v", errActionNotPerformed, sessionErr)
}
if callErr != nil {
if len(persistenceErrs) > 0 {
callErr = errors.Join(callErr, errors.Join(persistenceErrs...))
@@ -831,6 +942,15 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
return nil
}
func (c *Center) wakeCredentialBlockedAutomation(ctx context.Context, accountID string) {
if c == nil || c.store == nil || c.store.Automation == nil {
return
}
if err := c.store.Automation.WakeCredentialBlocked(ctx, accountID); err != nil {
c.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", accountID, "err", err)
}
}
func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
if !actionMatchesOrderSpec(task, action) {
return 0, nil
@@ -857,12 +977,12 @@ func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAc
}
if imageURL != "" {
if err := c.sendImage(ctx, task, imageURL, card.ID); err != nil {
return sent, uncertainAction(err)
return sent, classifyMessageSendError(err)
}
}
if strings.TrimSpace(content) != "" {
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
return sent, uncertainAction(err)
return sent, classifyMessageSendError(err)
}
}
if strings.TrimSpace(content) == "" && strings.TrimSpace(imageURL) == "" {
@@ -884,8 +1004,13 @@ func (c *Center) sendDataCard(ctx context.Context, task Task, card *db.CardFull,
}
if strings.TrimSpace(content) != "" {
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
// 发送接口报错时无法判断远端是否已经收到。恢复库存会让同一卡密
// 再次被消费,因此保守地保留已消费状态并交给人工核对。
if errors.Is(err, ErrMessageNotSent) {
if restoreErr := c.store.Cards.RestoreBatchData(ctx, card.ID, content); restoreErr != nil {
return sent, uncertainAction(errors.Join(err, fmt.Errorf("恢复未发送卡密库存: %w", restoreErr)))
}
return sent, err
}
// 请求已经交给传输层后无法判断远端是否收到,保留消费状态并人工核对。
return sent, uncertainAction(err)
}
}
@@ -894,6 +1019,13 @@ func (c *Center) sendDataCard(ctx context.Context, task Task, card *db.CardFull,
return sent, nil
}
func classifyMessageSendError(err error) error {
if err == nil || errors.Is(err, ErrMessageNotSent) {
return err
}
return uncertainAction(err)
}
func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string) (bool, error) {
paused, _, err := c.store.Cookies.IsPaused(ctx, accountID)
if err != nil {
@@ -906,6 +1038,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,28 +1121,28 @@ 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)
}
func (c *Center) sendImage(ctx context.Context, task Task, imageURL string, cardID int64) 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.SendImage(ctx, task.ChatID, task.BuyerID, imageURL, cardID)
}
@@ -1012,9 +1158,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 +1173,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 {
@@ -5,6 +5,7 @@ import (
"errors"
"strings"
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
@@ -20,6 +21,15 @@ type fakeMTop struct {
consignCalls int
consignCookieIn string
consignOrderIn string
consignCookies []string
consignResults []fakeConsignResult
}
type fakeConsignResult struct {
ok bool
ret []string
updated string
err error
}
func (f *fakeMTop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
@@ -29,6 +39,12 @@ func (f *fakeMTop) ConsignContext(_ context.Context, cookiesStr, orderID string)
f.consignCalls++
f.consignCookieIn = cookiesStr
f.consignOrderIn = orderID
f.consignCookies = append(f.consignCookies, cookiesStr)
if len(f.consignResults) > 0 {
result := f.consignResults[0]
f.consignResults = f.consignResults[1:]
return result.ok, result.ret, result.updated, result.err
}
return f.consignOk, f.consignRet, f.consignUpdated, f.consignErr
}
func (f *fakeMTop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
@@ -44,6 +60,111 @@ func (f *fakeMTop) RefreshTokenWithDeviceIDContext(context.Context, string, stri
return nil, nil
}
type fakeCredentialRecoverer struct {
store *db.Store
calls int
fail bool
}
func (f *fakeCredentialRecoverer) FetchOrderDetail(context.Context, string, string, string, string, string) (*OrderDetail, error) {
return &OrderDetail{Quantity: "1", Amount: "9.9"}, nil
}
func (f *fakeCredentialRecoverer) RecoverExpiredCredential(ctx context.Context, cookieID string) bool {
f.calls++
if f.fail {
return false
}
detail, err := f.store.Cookies.GetDetails(ctx, cookieID)
if err != nil {
return false
}
return f.store.Cookies.UpdateRenewalCookie(ctx, cookieID, "unb=123; _m_h5_tk=fresh_1;", detail.MetadataJSON, time.Now().Unix()) == nil
}
func TestConfirmShipmentRetriesFromCheckpointWithoutResendingCard(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
admin, _ := store.Users.GetByUsername(ctx, "admin")
res, err := store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,text_content,enabled,user_id) VALUES ('gift','text','ONLY-ONCE',1,?)`, admin.ID)
if err != nil {
t.Fatal(err)
}
cardID, _ := res.LastInsertId()
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: admin.ID, CookieID: "cid", ItemID: "checkpoint-item", Name: "checkpoint",
TriggerType: TriggerOrderPaid, Enabled: true,
Actions: []db.AutomationActionInput{
{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, Enabled: true, SortOrder: 1},
{ActionType: ActionConfirmShipment, Enabled: true, SortOrder: 2},
},
}); err != nil {
t.Fatal(err)
}
mtopMock := &fakeMTop{consignResults: []fakeConsignResult{
{ret: []string{"FAIL_SYS_SESSION_EXPIRED::Session过期"}},
{ok: true, ret: []string{"SUCCESS::调用成功"}},
}}
recoverer := &fakeCredentialRecoverer{store: store, fail: true}
sender := &testSender{}
center := New(store, testSenderProvider{sender: sender}, nil)
center.SetMTop(mtopMock)
center.SetOrderDetailFetcher(recoverer)
task := Task{AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "checkpoint-order",
ItemID: "checkpoint-item", BuyerID: "buyer", ChatID: "chat", Quantity: "1", Amount: "9.9"}
if err := center.HandleTask(ctx, task); err == nil {
t.Fatal("首次确认发货应因 Session 恢复失败而返回错误")
}
var status, errMsg string
var sent, cursor int
if err := store.DB.QueryRowContext(ctx, `SELECT status,error_message,sent_count,action_cursor FROM automation_runs WHERE order_id=?`, task.OrderID).
Scan(&status, &errMsg, &sent, &cursor); err != nil {
t.Fatal(err)
}
if status != "failed" || !strings.HasPrefix(errMsg, db.SafeRetryErrorPrefix) || sent != 1 || cursor != 1 {
t.Fatalf("status=%q err=%q sent=%d cursor=%d", status, errMsg, sent, cursor)
}
recoverer.fail = false
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] != "ONLY-ONCE" {
t.Fatalf("恢复确认发货不得重复发送卡密: %v", sender.texts)
}
if mtopMock.consignCalls != 2 {
t.Fatalf("consign calls=%d want 2", mtopMock.consignCalls)
}
}
func TestConfirmShipmentRecoversExpiredSessionAndRetriesOnlyConsign(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
mtopMock := &fakeMTop{consignResults: []fakeConsignResult{
{ret: []string{"FAIL_SYS_SESSION_EXPIRED::Session过期"}},
{ok: true, ret: []string{"SUCCESS::调用成功"}},
}}
recoverer := &fakeCredentialRecoverer{store: store}
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
center.SetMTop(mtopMock)
center.SetOrderDetailFetcher(recoverer)
if err := center.confirmShipment(ctx, Task{AccountID: "cid", OrderID: "session-order", ItemID: "item", BuyerID: "buyer", ChatID: "chat"}); err != nil {
t.Fatal(err)
}
if recoverer.calls != 1 || mtopMock.consignCalls != 2 {
t.Fatalf("recover calls=%d consign calls=%d want 1/2", recoverer.calls, mtopMock.consignCalls)
}
if len(mtopMock.consignCookies) != 2 || !strings.Contains(mtopMock.consignCookies[1], "fresh_1") {
t.Fatalf("确认发货重试未使用续期 Cookie: %v", mtopMock.consignCookies)
}
order, err := store.Orders.Get(ctx, "session-order")
if err != nil || !order.SystemShipped {
t.Fatalf("恢复后应记录系统发货: order=%+v err=%v", order, err)
}
}
// TestCenterConfirmShipment_MockMTopConsigError 用 mock mtop 验证:
// ConsignContext 返回错误时 confirmShipment 透传错误,不写 system_shipped;
// ok=false 但无错误时返回"确认发货失败"错误。
+248 -2
View File
@@ -77,6 +77,177 @@ 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 TestAbortRunActionFailureQuarantinesRun(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: "abort-failure", TriggerType: TriggerBuyerReviewed, Enabled: true,
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "gift", Enabled: true}},
}); err != nil {
t.Fatal(err)
}
if _, err := store.DB.ExecContext(ctx, `CREATE TRIGGER fail_abort_run_action
BEFORE UPDATE OF action_started ON automation_runs
WHEN OLD.action_started = 1 AND NEW.action_started = 0
BEGIN SELECT RAISE(ABORT, 'forced abort failure'); END`); err != nil {
t.Fatal(err)
}
center := New(store, testSenderProvider{sender: &testSender{err: fmt.Errorf("%w: websocket unavailable", ErrMessageNotSent)}}, nil)
task := Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "abort-failure-order", ChatID: "chat", BuyerID: "buyer"}
if err := center.HandleTask(ctx, task); err == nil || !errors.Is(err, errAutomationNeedsReview) {
t.Fatalf("回滚检查点失败后应要求人工核对,err=%v", err)
}
var status string
var actionStarted int
if err := store.DB.QueryRowContext(ctx, `SELECT status,action_started FROM automation_runs WHERE order_id=?`, task.OrderID).Scan(&status, &actionStarted); err != nil {
t.Fatal(err)
}
if status != "needs_review" || actionStarted != 1 {
t.Fatalf("status=%q action_started=%d want needs_review/1", status, actionStarted)
}
}
func TestCardDefinitelyNotSentIsRetriedAndDataInventoryRestored(t *testing.T) {
for _, tc := range []struct {
name string
cardType string
cardColumn string
}{
{name: "text", cardType: "text", cardColumn: "text_content"},
{name: "data", cardType: "data", cardColumn: "data_content"},
} {
t.Run(tc.name, func(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
admin, _ := store.Users.GetByUsername(ctx, "admin")
query := fmt.Sprintf(`INSERT INTO cards (name,type,%s,enabled,user_id) VALUES (?,?,?,?,?)`, tc.cardColumn)
res, err := store.DB.ExecContext(ctx, query, "gift", tc.cardType, "GIFT-CODE", 1, admin.ID)
if err != nil {
t.Fatal(err)
}
cardID, _ := res.LastInsertId()
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: admin.ID, CookieID: "cid", ItemID: "item-card", Name: "card-retry-" + tc.name,
TriggerType: TriggerBuyerReviewed, Enabled: true,
Actions: []db.AutomationActionInput{{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, 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: "card-order-" + tc.name,
ItemID: "item-card", 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)
}
if tc.cardType == "data" {
var inventory string
if err := store.DB.QueryRowContext(ctx, `SELECT data_content FROM cards WHERE id=?`, cardID).Scan(&inventory); err != nil || inventory != "GIFT-CODE" {
t.Fatalf("未发送 Data 卡密必须恢复库存: inventory=%q err=%v", inventory, err)
}
}
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-CODE" {
t.Fatalf("连接恢复后应发送一次卡密,got %v", sender.texts)
}
})
}
}
func TestRuleMatchingUsesStoredOrderItemWhenEventOmitsItemID(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
admin, _ := store.Users.GetByUsername(ctx, "admin")
if err := store.Orders.Upsert(ctx, "known-order", db.OrderUpsertOpts{
CookieID: "cid", ItemID: "known-item", BuyerID: "buyer", ChatID: "chat",
}); err != nil {
t.Fatal(err)
}
if _, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: admin.ID, CookieID: "cid", ItemID: "known-item", Name: "item-specific-review",
TriggerType: TriggerBuyerReviewed, Enabled: true,
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "review-gift", Enabled: true}},
}); err != nil {
t.Fatal(err)
}
sender := &testSender{}
center := New(store, testSenderProvider{sender: sender}, nil)
if err := center.HandleTask(ctx, Task{
AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "known-order",
}); err != nil {
t.Fatal(err)
}
if len(sender.texts) != 1 || sender.texts[0] != "review-gift" {
t.Fatalf("应使用本地订单 item_id 匹配商品规则,got %v", sender.texts)
}
}
func TestImageCardMissingSenderIsDefinitelyNotSent(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
center := New(store, nil, nil)
err := center.sendImage(context.Background(), Task{AccountID: "cid", ChatID: "chat", BuyerID: "buyer"}, "https://example.com/gift.png", 1)
if !errors.Is(err, ErrMessageNotSent) {
t.Fatalf("图片发送器缺失应标记为明确未发送,got %v", err)
}
}
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 +256,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()) {
+66 -3
View File
@@ -98,6 +98,7 @@ type rawFields struct {
redReminder string
title string
detail string
orderRole string
updateKey string
contentType string
chatID string
@@ -121,8 +122,12 @@ func fieldsFromRaw(raw map[string]any) rawFields {
f.reminderURL = strAny(m10["reminderUrl"])
f.buyerID = strAny(m10["senderUserId"])
f.updateKey, f.contentType = extFields(strAny(m10["extJson"]))
f.orderRole = orderRoleFromTaskName(bizTaskName(strAny(m10["bizTag"])))
}
if contentJSON := nestedString(raw, "1", "6", "3", "5"); contentJSON != "" {
if role := extractOrderRoleFromContent(contentJSON); role != "" {
f.orderRole = role
}
if id := extractOrderIDFromContent(contentJSON); id != "" {
f.orderID = id
}
@@ -180,6 +185,9 @@ func fieldsFromRaw(raw map[string]any) rawFields {
}
func isOrderPaidEvent(f rawFields) bool {
if f.orderRole == "buyer" {
return false
}
return strings.Contains(f.text, "我已付款,等待你发货") ||
strings.Contains(f.text, "已付款,待发货") ||
strings.Contains(f.text, "记得及时发货") ||
@@ -192,9 +200,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) {
@@ -279,6 +287,61 @@ var orderIDPatterns = []*regexp.Regexp{
regexp.MustCompile(`id=(\d{10,})`),
}
func extractOrderRoleFromContent(contentJSON string) string {
var c map[string]any
if json.Unmarshal([]byte(contentJSON), &c) != nil {
return ""
}
for _, path := range [][]string{
{"dxCard", "item", "main", "exContent", "button", "targetUrl"},
{"dxCard", "item", "main", "targetUrl"},
{"dynamicOperation", "changeContent", "dxCard", "item", "main", "exContent", "button", "targetUrl"},
} {
if role := orderRoleFromURL(nestedString(c, path...)); role != "" {
return role
}
}
return ""
}
func orderRoleFromURL(rawURL string) string {
if strings.TrimSpace(rawURL) == "" {
return ""
}
if strings.HasPrefix(rawURL, "fleamarket://") {
rawURL = "https://local.invalid/" + strings.TrimPrefix(rawURL, "fleamarket://")
}
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
switch strings.ToLower(strings.TrimSpace(u.Query().Get("role"))) {
case "seller", "buyer":
return strings.ToLower(strings.TrimSpace(u.Query().Get("role")))
default:
return ""
}
}
func bizTaskName(raw string) string {
var tag map[string]any
if json.Unmarshal([]byte(raw), &tag) != nil {
return ""
}
return strAny(tag["taskName"])
}
func orderRoleFromTaskName(taskName string) string {
switch {
case strings.Contains(taskName, "买家"):
return "buyer"
case strings.Contains(taskName, "卖家"):
return "seller"
default:
return ""
}
}
func matchOrderID(s string) string {
for _, re := range orderIDPatterns {
if m := re.FindStringSubmatch(s); len(m) == 2 {
+46
View File
@@ -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": {
@@ -65,6 +80,37 @@ func TestExtractTaskFromWS_OrderPaid(t *testing.T) {
}
}
func TestExtractTaskFromWS_BuyerOrderPaidIgnored(t *testing.T) {
raw := mustMap(t, `{
"1": {
"2": "63107041124@goofish",
"10": {
"redReminder": "等待卖家发货",
"reminderContent": "[我已付款,等待你发货]",
"senderUserId": "2222315258815",
"reminderUrl": "fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815&sid=63107041124"
},
"6": {"3": {"5": "{\"dxCard\":{\"item\":{\"main\":{\"targetUrl\":\"fleamarket://order_detail?id=3310145690545023994&role=buyer\"}}}}"}}
}
}`)
if task := ExtractTaskFromWS("acc1", "cookie", raw); task != nil {
t.Fatalf("买家订单不应进入卖家自动化和订单管理: %+v", task)
}
}
func TestExtractTaskFromWS_BuyerOrderPaidTaskNameIgnored(t *testing.T) {
raw := mustMap(t, `{
"1": {"2": "63107041124@goofish", "10": {
"bizTag": "{\"taskName\":\"付款完成待发货_买家\"}",
"redReminder": "等待卖家发货",
"reminderContent": "[我已付款,等待你发货]"
}}
}`)
if task := ExtractTaskFromWS("acc1", "cookie", raw); task != nil {
t.Fatalf("买家侧 taskName 不应进入卖家自动化和订单管理: %+v", task)
}
}
func mustMap(t *testing.T, s string) map[string]any {
t.Helper()
var m map[string]any
+92 -15
View File
@@ -6,23 +6,26 @@ import (
"errors"
"strconv"
"strings"
"sync"
"time"
"xianyu-go/internal/db"
)
const defaultReviewRequestScanInterval = 10 * time.Minute
const defaultReviewRequestScanInterval = time.Minute
// Scheduler 执行计划任务类自动化。
// 计划任务只负责“发现应该触发的任务”,具体动作仍交给 Center,避免形成第二套执行链。
type Scheduler struct {
center *Center
interval time.Duration
runOnce sync.Once
done chan struct{}
}
// NewScheduler 构造计划任务调度器。
func NewScheduler(center *Center) *Scheduler {
return &Scheduler{center: center, interval: defaultReviewRequestScanInterval}
return &Scheduler{center: center, interval: defaultReviewRequestScanInterval, done: make(chan struct{})}
}
// Run 周期扫描计划任务。调用方应在 goroutine 中启动,并用 ctx 控制生命周期。
@@ -30,24 +33,43 @@ func (s *Scheduler) Run(ctx context.Context) {
if s == nil || s.center == nil || s.center.store == nil {
return
}
ticker := time.NewTicker(s.interval)
defer ticker.Stop()
s.scan(ctx)
for {
select {
case <-ctx.Done():
s.runOnce.Do(func() {
defer close(s.done)
if ctx.Err() != nil {
return
case <-ticker.C:
s.scan(ctx)
}
ticker := time.NewTicker(s.interval)
defer ticker.Stop()
s.scan(ctx)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.scan(ctx)
}
}
})
}
func (s *Scheduler) Wait() {
if s != nil && s.done != nil {
<-s.done
}
}
func (s *Scheduler) scan(ctx context.Context) {
s.runDeferredTasks(ctx)
s.center.scanAccountTasks(ctx)
if recovered, err := s.center.store.Automation.RecoverDefinitelyUnsentReviewRuns(ctx); err != nil {
s.center.logger.Warn("恢复历史求评价未发送任务失败", "err", err)
} else if recovered > 0 {
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 +85,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 +105,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 +115,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) {
@@ -107,16 +142,31 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
}
allowed, err := s.center.accountAutomationAllowed(ctx, task.AccountID)
if err != nil || !allowed {
_ = s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, time.Now().UTC().Add(10*time.Minute).Unix())
if postponeErr := s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, run.AttemptCount, time.Now().UTC().Add(10*time.Minute).Unix()); postponeErr != nil {
s.center.logger.Warn("延期自动化恢复任务失败", "run_id", run.ID, "err", postponeErr)
}
continue
}
rule, err := s.center.store.Automation.Get(ctx, run.RuleID)
if err != nil || !rule.Enabled {
if err != nil && !errors.Is(err, db.ErrNotFound) {
if ctx.Err() != nil {
return
}
s.center.logger.Warn("读取自动化恢复规则失败,保留任务等待重试", "run_id", run.ID, "rule_id", run.RuleID, "err", err)
continue
}
if errors.Is(err, db.ErrNotFound) || rule == nil || !rule.Enabled {
reason := "自动化规则不存在或已停用,无法恢复"
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
s.center.notifyRunNeedsReview(run, reason)
continue
}
if recoveryNeedsSender(task, *rule, run.ActionCursor) && !s.center.accountSenderReady(task.AccountID) {
if postponeErr := s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, run.AttemptCount, time.Now().UTC().Add(defaultReviewRequestScanInterval).Unix()); postponeErr != nil {
s.center.logger.Warn("等待 WebSocket 时延期自动化任务失败", "run_id", run.ID, "err", postponeErr)
}
continue
}
claimed, claimErr := s.center.store.Automation.ClaimRecoveryRun(ctx, run.ID, time.Now().UTC().Add(5*time.Minute).Unix())
if claimErr != nil || !claimed {
continue
@@ -132,6 +182,22 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
}
}
func recoveryNeedsSender(task Task, rule db.AutomationRule, cursor int) bool {
actions := task.ActionPlan
if len(actions) == 0 {
actions = runnableActions(task, rule.Actions)
}
if cursor < 0 || cursor >= len(actions) {
return false
}
switch actions[cursor].ActionType {
case ActionSendText, ActionSendCard:
return true
default:
return false
}
}
func (s *Scheduler) runDeferredTasks(ctx context.Context) {
tasks, err := s.center.store.Automation.ClaimDueDeferredTasks(ctx, 100)
if err != nil {
@@ -144,6 +210,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 +295,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
}
+92
View File
@@ -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()
@@ -240,3 +299,36 @@ func TestSchedulerScansMoreThanOneReviewPage(t *testing.T) {
t.Fatalf("sent=%d want 205", len(sender.texts))
}
}
func TestRecoveryNeedsSenderUsesNextActionType(t *testing.T) {
rule := db.AutomationRule{Actions: []db.AutomationAction{
{ActionType: ActionConfirmShipment, Enabled: true},
{ActionType: ActionSendText, Enabled: true},
}}
task := Task{TriggerType: TriggerBuyerReviewed}
if recoveryNeedsSender(task, rule, 0) {
t.Fatal("确认发货动作不应等待 WebSocket")
}
if !recoveryNeedsSender(task, rule, 1) {
t.Fatal("发送文本动作必须等待 WebSocket")
}
}
func TestAutomationSchedulerWaitsForShutdown(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
scheduler := NewScheduler(New(store, testSenderProvider{sender: &testSender{}}, nil))
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
scheduler.Run(ctx)
close(done)
}()
cancel()
scheduler.Wait()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("自动化调度器关闭后没有退出")
}
}
+579
View File
@@ -0,0 +1,579 @@
package chat
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"xianyu-go/internal/db"
)
type HistoryPage struct {
Messages []db.ChatMessage
HasMore bool
NextCursor int64
}
type ConversationPage struct {
HasMore bool
NextCursor int64
}
const xianxiaomiAvatar = "https://img.alicdn.com/imgextra/i2/O1CN01rxBFRr1II3BU0as29_!!6000000000869-2-tps-144-144.png_110x10000.jpg_.webp"
func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID string, body map[string]any) (ConversationPage, error) {
page := ConversationPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
items, _ := body["userConvs"].([]any)
for _, item := range items {
wrapper, _ := item.(map[string]any)
conv := wrapper
if nested, ok := wrapper["singleChatUserConversation"].(map[string]any); ok {
conv = nested
}
single, _ := conv["singleChatConversation"].(map[string]any)
cid := strings.Split(strings.TrimSpace(fmt.Sprint(single["cid"])), "@")[0]
if visible, exists := conv["visible"]; exists && int64Value(visible) == 0 {
if cid != "" && cid != "<nil>" {
_ = s.store.Chats.DeleteSession(ctx, accountID, cid)
}
continue
}
first := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairFirst"])), "@")[0]
second := strings.Split(strings.TrimSpace(fmt.Sprint(single["pairSecond"])), "@")[0]
ext := mapValue(single["extension"])
if second == "0" && cleanNilString(ext["extUserId"]) != "1400" {
_ = s.store.Chats.DeleteSession(ctx, accountID, cid)
continue
}
peerID := first
if first == myID {
peerID = second
}
if peerID == "0" {
peerID = cleanNilString(ext["extUserId"])
}
if cid == "" || cid == "<nil>" || peerID == "" || peerID == "0" || peerID == "<nil>" {
continue
}
lastWrap, _ := conv["lastMessage"].(map[string]any)
last, _ := lastWrap["message"].(map[string]any)
// The conversation endpoint can return empty shells for notification
// recipients. The official web client does not render these as contacts;
// importing them creates fake users such as numeric IDs with “暂无消息”.
if len(last) == 0 {
continue
}
// reminderTitle belongs to the message presentation layer. Depending on
// the message type it may contain a nickname, an order-state prompt, or
// another card title. The official web client resolves conversation
// identity separately through pc.user.query, so never persist this field
// as the session nickname.
peerName := ""
custom := map[string]any{}
extension := mapValue(last["extension"])
if content, ok := last["content"].(map[string]any); ok {
custom, _ = content["custom"].(map[string]any)
}
summary := cleanNilString(custom["summary"])
if summary == "" {
summary = cleanNilString(extension["reminderContent"])
}
if summary == "" {
summary = cleanNilString(extension["detailNotice"])
}
if summary == "" {
if encoded := cleanNilString(custom["data"]); encoded != "" {
var decoded map[string]any
if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil && json.Unmarshal(raw, &decoded) == nil {
fallback := ""
if textBlock, ok := decoded["text"].(map[string]any); ok {
fallback = cleanNilString(textBlock["text"])
}
_, summary = extractMessageContent(decoded, fallback)
}
}
}
if summary == "" {
summary = "暂无消息"
}
avatar := ""
if peerID == "1400" {
peerName, avatar = "闲小蜜", xianxiaomiAvatar
}
modifyTime := int64Value(conv["modifyTime"])
lastMessageAt := int64Value(last["createAt"])
if lastMessageAt <= 0 {
lastMessageAt = modifyTime
}
session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar,
ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary,
LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))}
if err := s.store.Chats.UpsertSession(ctx, session); err != nil {
return page, err
}
if err := s.store.Chats.SyncSessionSummary(ctx, accountID, cid, summary, lastMessageAt, modifyTime, session.UnreadCount); err != nil {
return page, err
}
}
return page, nil
}
var invalidNicknames = map[string]struct{}{
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
"等待您发货": {}, "超时未付款,系统关闭了订单": {}, "邀您填写售后问卷": {},
}
func ValidNickname(value string) bool {
value = strings.TrimSpace(value)
if value == "" {
return false
}
if strings.Contains(value, "***") {
return false
}
if _, err := strconv.ParseUint(value, 10, 64); err == nil {
return false
}
trimmed := strings.TrimSuffix(strings.TrimPrefix(value, "["), "]")
if _, invalid := invalidNicknames[trimmed]; invalid {
return false
}
return !strings.Contains(value, "发来一条新消息")
}
func cleanNilString(value any) string {
text := strings.TrimSpace(fmt.Sprint(value))
if text == "<nil>" {
return ""
}
return text
}
type Incoming struct {
AccountID string
ChatID string
BuyerID string
BuyerName string
Text string
ItemID string
Raw map[string]any
}
type Event struct {
Type string `json:"type"`
Message *db.ChatMessage `json:"message,omitempty"`
Session *db.ChatSession `json:"session,omitempty"`
}
type subscriber struct {
accounts map[string]struct{}
ch chan Event
}
type Service struct {
store *db.Store
mu sync.RWMutex
next uint64
subs map[uint64]subscriber
}
func New(store *db.Store) *Service {
return &Service{store: store, subs: make(map[uint64]subscriber)}
}
func (s *Service) Subscribe(ctx context.Context, userID int64) (<-chan Event, func(), error) {
accounts, err := s.store.Cookies.AllForUser(ctx, userID)
if err != nil {
return nil, nil, err
}
allowed := make(map[string]struct{}, len(accounts))
for accountID := range accounts {
allowed[accountID] = struct{}{}
}
s.mu.Lock()
s.next++
id := s.next
ch := make(chan Event, 128)
s.subs[id] = subscriber{accounts: allowed, ch: ch}
s.mu.Unlock()
var once sync.Once
cancel := func() {
once.Do(func() {
s.mu.Lock()
if sub, ok := s.subs[id]; ok {
delete(s.subs, id)
close(sub.ch)
}
s.mu.Unlock()
})
}
return ch, cancel, nil
}
func (s *Service) Publish(accountID string, event Event) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, sub := range s.subs {
if _, ok := sub.accounts[accountID]; !ok {
continue
}
select {
case sub.ch <- event:
default:
// A slow browser must not block the account receive loop. The client
// reconnects and reloads authoritative history when its buffer fills.
}
}
}
func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMessage, bool, error) {
if s == nil || s.store == nil || s.store.Chats == nil {
return nil, false, fmt.Errorf("聊天服务未初始化")
}
sentAt := extractUnixMilli(in.Raw)
if sentAt == 0 {
sentAt = time.Now().UTC().UnixMilli()
}
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
if key == "" {
raw, _ := json.Marshal(in.Raw)
digest := sha256.Sum256([]byte(in.AccountID + "\x00" + in.ChatID + "\x00" + in.BuyerID + "\x00" + in.Text + "\x00" + string(raw)))
key = "in-" + hex.EncodeToString(digest[:16])
}
session := db.ChatSession{CookieID: in.AccountID, ChatID: in.ChatID, BuyerID: in.BuyerID,
BuyerName: in.BuyerName, BuyerAvatar: extractString(in.Raw, "avatar", "avatarUrl", "senderAvatar"),
ItemID: in.ItemID, ItemTitle: extractString(in.Raw, "itemTitle", "title")}
messageType, content := extractMessageContent(in.Raw, in.Text)
if isOfficialSystemMessage(in.Raw, in.BuyerID, in.Text) {
messageType = "system"
if strings.TrimSuffix(strings.TrimSpace(in.BuyerID), "@goofish") == "1400" {
in.BuyerName = "闲小蜜"
session.BuyerName = "闲小蜜"
session.BuyerAvatar = xianxiaomiAvatar
}
}
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
stored, inserted, err := s.store.Chats.SaveMessage(ctx, session, message, true)
if err == nil && inserted {
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
}
return stored, inserted, err
}
// RecordHistoryPage normalizes official IM history and stores it idempotently.
func (s *Service) RecordHistoryPage(ctx context.Context, accountID, chatID, myID string, session db.ChatSession, body map[string]any) (HistoryPage, error) {
page := HistoryPage{HasMore: boolValue(body["hasMore"]), NextCursor: int64Value(body["nextCursor"])}
models, _ := body["userMessageModels"].([]any)
for i := len(models) - 1; i >= 0; i-- { // official API returns newest first
model, _ := models[i].(map[string]any)
message, ok := parseHistoryMessage(accountID, chatID, myID, model)
if !ok {
continue
}
session.CookieID, session.ChatID = accountID, chatID
if message.Direction == "incoming" && message.MessageType != "system" {
if session.BuyerID == "" {
session.BuyerID = message.SenderID
}
}
stored, _, err := s.store.Chats.SaveMessage(ctx, session, message, false)
if err != nil {
return page, err
}
if message.MessageType == "system" {
if err := s.store.Chats.UpdateMessageType(ctx, accountID, message.MessageKey, "system"); err != nil {
return page, err
}
stored.MessageType = "system"
}
page.Messages = append(page.Messages, *stored)
}
return page, nil
}
func parseHistoryMessage(accountID, chatID, myID string, model map[string]any) (db.ChatMessage, bool) {
message, _ := model["message"].(map[string]any)
if message == nil {
return db.ChatMessage{}, false
}
extension := mapValue(message["extension"])
senderID := strings.Split(strings.TrimSpace(fmt.Sprint(extension["senderUserId"])), "@")[0]
senderName := strings.TrimSpace(fmt.Sprint(extension["reminderTitle"]))
if senderName == "<nil>" {
senderName = ""
}
key := strings.TrimSpace(fmt.Sprint(message["messageId"]))
if key == "" || key == "<nil>" {
return db.ChatMessage{}, false
}
contentMap, _ := message["content"].(map[string]any)
custom, _ := contentMap["custom"].(map[string]any)
rawContent := map[string]any{}
if encoded := strings.TrimSpace(fmt.Sprint(custom["data"])); encoded != "" && encoded != "<nil>" {
if decoded, err := base64.StdEncoding.DecodeString(encoded); err == nil {
_ = json.Unmarshal(decoded, &rawContent)
}
}
fallback := strings.TrimSpace(fmt.Sprint(custom["summary"]))
if fallback == "<nil>" {
fallback = ""
}
if textBlock, ok := rawContent["text"].(map[string]any); ok {
if text := strings.TrimSpace(fmt.Sprint(textBlock["text"])); text != "" && text != "<nil>" {
fallback = text
}
}
messageType, content := extractMessageContent(rawContent, fallback)
if isOfficialSystemMessage(rawContent, senderID, fallback) {
messageType = "system"
if senderID == "1400" {
senderName = "闲小蜜"
}
}
if content == "" {
content = "[系统消息]"
}
direction, status := "incoming", "received"
if senderID != "" && senderID == strings.TrimSpace(myID) {
direction, status = "outgoing", "sent"
}
return db.ChatMessage{CookieID: accountID, ChatID: chatID, MessageKey: key, Direction: direction,
SenderID: senderID, SenderName: senderName, MessageType: messageType, Content: content,
Status: status, SentAt: int64Value(message["createAt"])}, true
}
func mapValue(value any) map[string]any {
if result, ok := value.(map[string]any); ok {
return result
}
if text, ok := value.(string); ok {
var result map[string]any
if json.Unmarshal([]byte(text), &result) == nil {
return result
}
}
return map[string]any{}
}
func int64Value(value any) int64 {
switch typed := value.(type) {
case float64:
return int64(typed)
case int64:
return typed
case int:
return int64(typed)
case json.Number:
result, _ := typed.Int64()
return result
case string:
var result int64
_, _ = fmt.Sscan(strings.TrimSpace(typed), &result)
return result
}
return 0
}
func boolValue(value any) bool {
switch typed := value.(type) {
case bool:
return typed
case float64:
return typed == 1
case int:
return typed == 1
case string:
return typed == "1" || strings.EqualFold(typed, "true")
}
return false
}
func extractMessageContent(raw map[string]any, fallback string) (string, string) {
var inspect func(any) (string, string)
inspect = func(value any) (string, string) {
switch typed := value.(type) {
case string:
var nested any
if json.Unmarshal([]byte(typed), &nested) == nil {
return inspect(nested)
}
case map[string]any:
contentType := strings.TrimSpace(fmt.Sprint(typed["contentType"]))
if contentType == "2" {
if mediaURL := extractString(typed["image"], "url"); mediaURL != "" {
return "image", mediaURL
}
}
if contentType == "4" || typed["video"] != nil {
if mediaURL := extractString(typed["video"], "url", "videoUrl", "playUrl"); mediaURL != "" {
return "video", mediaURL
}
}
for _, child := range typed {
if kind, mediaURL := inspect(child); mediaURL != "" {
return kind, mediaURL
}
}
case []any:
for _, child := range typed {
if kind, mediaURL := inspect(child); mediaURL != "" {
return kind, mediaURL
}
}
}
return "", ""
}
if kind, mediaURL := inspect(raw); mediaURL != "" {
return kind, mediaURL
}
return "text", strings.TrimSpace(fallback)
}
// isOfficialSystemMessage recognizes platform-generated IM content using the
// protocol metadata, rather than matching a growing list of Chinese prompts.
// contentType=14 is a platform notice and contentType=26 is an official trade
// card. User 1400 is 闲小蜜, whose messages are also not peer chat.
func isOfficialSystemMessage(raw map[string]any, senderID, fallback string) bool {
if strings.TrimSuffix(strings.TrimSpace(senderID), "@goofish") == "1400" {
return true
}
if contentType := findOfficialContentType(raw); contentType == "14" || contentType == "26" {
return true
}
return strings.TrimSpace(fallback) == "发来一条新消息"
}
// findOfficialContentType walks decoded history content as well as live WS
// envelopes. History stores the inner content JSON under custom.data, while
// live messages expose it under 1.6.3 or 1.10.extJson.
func findOfficialContentType(value any) string {
var found string
var walk func(any)
walk = func(current any) {
if found != "" {
return
}
switch typed := current.(type) {
case string:
var nested any
if json.Unmarshal([]byte(typed), &nested) == nil {
walk(nested)
}
case map[string]any:
if candidate := strings.TrimSpace(fmt.Sprint(typed["contentType"])); candidate == "14" || candidate == "26" {
found = candidate
return
}
for _, child := range typed {
walk(child)
}
case []any:
for _, child := range typed {
walk(child)
}
}
}
walk(value)
return found
}
func (s *Service) CreateOutgoing(ctx context.Context, session db.ChatSession, text string) (*db.ChatMessage, error) {
return s.CreateOutgoingMedia(ctx, session, "text", strings.TrimSpace(text))
}
func (s *Service) CreateOutgoingMedia(ctx context.Context, session db.ChatSession, messageType, content string) (*db.ChatMessage, error) {
key := "local-" + randomID()
message := db.ChatMessage{MessageKey: key, Direction: "outgoing", SenderID: session.CookieID,
SenderName: "我", MessageType: messageType, Content: strings.TrimSpace(content), Status: "sending",
SentAt: time.Now().UTC().UnixMilli()}
stored, _, err := s.store.Chats.SaveMessage(ctx, session, message, false)
if err == nil {
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
}
return stored, err
}
// RecordOutgoingSent captures automatic replies and automation messages. A
// supplied key correlates a UI pending message and only updates its status.
func (s *Service) RecordOutgoingSent(ctx context.Context, session db.ChatSession, key, text string) (*db.ChatMessage, error) {
if strings.TrimSpace(key) != "" {
return s.SetOutgoingStatus(ctx, session.CookieID, key, "sent")
}
message := db.ChatMessage{MessageKey: "sent-" + randomID(), Direction: "outgoing", SenderID: session.CookieID,
SenderName: "我", MessageType: "text", Content: strings.TrimSpace(text), Status: "sent",
SentAt: time.Now().UTC().UnixMilli()}
stored, _, err := s.store.Chats.SaveMessage(ctx, session, message, false)
if err == nil {
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
}
return stored, err
}
func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (*db.ChatMessage, error) {
message, err := s.store.Chats.UpdateMessageStatus(ctx, accountID, key, status)
if err == nil {
s.Publish(accountID, Event{Type: "message.updated", Message: message})
}
return message, err
}
func randomID() string {
var value [16]byte
if _, err := rand.Read(value[:]); err == nil {
return hex.EncodeToString(value[:])
}
return fmt.Sprintf("%d", time.Now().UTC().UnixNano())
}
func extractString(value any, keys ...string) string {
wanted := make(map[string]struct{}, len(keys))
for _, key := range keys {
wanted[strings.ToLower(key)] = struct{}{}
}
var walk func(any) string
walk = func(v any) string {
switch x := v.(type) {
case map[string]any:
for key, child := range x {
if _, ok := wanted[strings.ToLower(key)]; ok {
if text := strings.TrimSpace(fmt.Sprint(child)); text != "" && text != "<nil>" {
return text
}
}
}
for _, child := range x {
if text := walk(child); text != "" {
return text
}
}
case []any:
for _, child := range x {
if text := walk(child); text != "" {
return text
}
}
}
return ""
}
return walk(value)
}
func extractUnixMilli(raw map[string]any) int64 {
text := extractString(raw, "sendTime", "timestamp", "time", "createdAt")
var value int64
_, _ = fmt.Sscan(text, &value)
if value > 0 && value < 10_000_000_000 {
value *= 1000
}
return value
}
+317
View File
@@ -0,0 +1,317 @@
package chat
import (
"context"
"encoding/base64"
"path/filepath"
"testing"
"time"
"xianyu-go/internal/db"
)
func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
ctx := context.Background()
encoded := func(value string) string { return base64.StdEncoding.EncodeToString([]byte(value)) }
body := map[string]any{
"hasMore": float64(1), "nextCursor": float64(12345),
"userMessageModels": []any{
map[string]any{"message": map[string]any{"messageId": "m2", "createAt": float64(2000), "extension": `{"senderUserId":"self@goofish","reminderTitle":"我"}`, "content": map[string]any{"custom": map[string]any{"data": encoded(`{"contentType":2,"image":{"pics":[{"url":"https://img.example/2.jpg"}]}}`)}}}},
map[string]any{"message": map[string]any{"messageId": "m1", "createAt": float64(1000), "extension": map[string]any{"senderUserId": "peer@goofish", "reminderTitle": "对方"}, "content": map[string]any{"custom": map[string]any{"data": encoded(`{"contentType":1,"text":{"text":"较早的消息"}}`)}}}},
},
}
session := db.ChatSession{CookieID: "account-1", ChatID: "cid", BuyerID: "peer", BuyerName: "对方"}
page, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body)
if err != nil {
t.Fatal(err)
}
if !page.HasMore || page.NextCursor != 12345 || len(page.Messages) != 2 {
t.Fatalf("unexpected page: %+v", page)
}
if page.Messages[0].Direction != "incoming" || page.Messages[0].Content != "较早的消息" {
t.Fatalf("unexpected incoming: %+v", page.Messages[0])
}
if page.Messages[1].Direction != "outgoing" || page.Messages[1].MessageType != "image" || page.Messages[1].Content != "https://img.example/2.jpg" {
t.Fatalf("unexpected outgoing image: %+v", page.Messages[1])
}
if _, err := service.RecordHistoryPage(ctx, "account-1", "cid", "self", session, body); err != nil {
t.Fatal(err)
}
owner, _ := store.Users.GetByUsername(ctx, "owner")
rows, err := store.Chats.ListMessages(ctx, owner.ID, "account-1", "cid", 0, 20)
if err != nil {
t.Fatal(err)
}
if len(rows) != 2 {
t.Fatalf("history retry inserted duplicates: %d", len(rows))
}
_, _, err = store.Chats.SaveMessage(ctx, session, db.ChatMessage{MessageKey: "system-later", Direction: "incoming", SenderID: "peer", SenderName: "快给ta一个评价吧~", MessageType: "text", Content: "快给ta一个评价吧~", Status: "received", SentAt: 3000}, false)
if err != nil {
t.Fatal(err)
}
name, err := store.Chats.LatestUnmaskedPeerName(ctx, "account-1", "cid")
if err != nil || name != "对方" {
t.Fatalf("historical nickname=%q err=%v", name, err)
}
}
func TestRecordHistoryPageClassifiesOfficialCardsAsSystem(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{"item":{"main":{"exContent":{"title":"我已拍下,待付款"}}}}}`))
body := map[string]any{"userMessageModels": []any{
map[string]any{"message": map[string]any{
"messageId": "official-card", "createAt": float64(3000),
"extension": map[string]any{"senderUserId": "peer@goofish", "reminderTitle": "买家已拍下,待付款"},
"content": map[string]any{"custom": map[string]any{"data": encoded, "summary": "[我已拍下,待付款]"}},
}},
}}
session := db.ChatSession{CookieID: "account-1", ChatID: "official", BuyerID: "peer", BuyerName: "真实昵称"}
if _, _, err := store.Chats.SaveMessage(context.Background(), session, db.ChatMessage{
MessageKey: "official-card", Direction: "incoming", SenderID: "peer", SenderName: "真实昵称",
MessageType: "text", Content: "[我已拍下,待付款]", Status: "received", SentAt: 3000,
}, false); err != nil {
t.Fatal(err)
}
page, err := service.RecordHistoryPage(context.Background(), "account-1", "official", "self", session, body)
if err != nil {
t.Fatal(err)
}
if len(page.Messages) != 1 || page.Messages[0].MessageType != "system" || page.Messages[0].Direction != "incoming" {
t.Fatalf("official card was not classified as system: %+v", page.Messages)
}
if page.Messages[0].SenderName != "真实昵称" {
t.Fatalf("history sender metadata unexpectedly changed: %+v", page.Messages[0])
}
}
func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
message, inserted, err := service.RecordIncoming(context.Background(), Incoming{
AccountID: "account-1", ChatID: "xiaomi", BuyerID: "1400@goofish",
BuyerName: "闲小蜜发来一条新消息", Text: "邀您填写售后问卷",
Raw: map[string]any{"messageId": "xiaomi-1"},
})
if err != nil || !inserted {
t.Fatalf("record xianxiaomi message: message=%+v inserted=%v err=%v", message, inserted, err)
}
if message.MessageType != "system" || message.SenderName != "闲小蜜" {
t.Fatalf("xianxiaomi message was not classified: %+v", message)
}
}
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":1,"text":{"text":"历史消息"}}`))
if err := store.Chats.UpsertSession(context.Background(), db.ChatSession{CookieID: "account-1", ChatID: "history-cid", BuyerID: "peer-9", LastMessage: "错误的新摘要", LastMessageAt: 987654}); err != nil {
t.Fatal(err)
}
body := map[string]any{"hasMore": true, "nextCursor": float64(888), "userConvs": []any{
map[string]any{"singleChatUserConversation": map[string]any{
"singleChatConversation": map[string]any{"cid": "history-cid@goofish", "pairFirst": "self@goofish", "pairSecond": "peer-9@goofish", "extension": `{"itemTitle":"旧商品"}`},
"lastMessage": map[string]any{"message": map[string]any{"createAt": float64(123456), "extension": map[string]any{"senderUserId": "peer-9@goofish", "reminderTitle": "历史用户"}, "content": map[string]any{"custom": map[string]any{"data": encoded}}}},
"modifyTime": float64(987654), "redPoint": float64(2),
}},
}}
page, err := service.RecordConversationPage(context.Background(), "account-1", "self", body)
if err != nil {
t.Fatal(err)
}
if !page.HasMore || page.NextCursor != 888 {
t.Fatalf("unexpected page: %+v", page)
}
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].BuyerID != "peer-9" || rows[0].BuyerName != "" || rows[0].LastMessage != "历史消息" || rows[0].UnreadCount != 2 {
t.Fatalf("unexpected historical contact: %+v", rows)
}
if rows[0].LastMessageAt != 123456 {
t.Fatalf("used conversation modifyTime instead of last message createAt: %d", rows[0].LastMessageAt)
}
}
func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
ctx := context.Background()
service := New(store)
if err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "hidden", BuyerID: "peer", LastMessage: "暂无消息"}); err != nil {
t.Fatal(err)
}
if err := store.Chats.UpsertSession(ctx, db.ChatSession{CookieID: "account-1", ChatID: "platform", BuyerID: "900", LastMessage: "暂无消息"}); err != nil {
t.Fatal(err)
}
body := map[string]any{"userConvs": []any{
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(0), "singleChatConversation": map[string]any{"cid": "hidden@goofish"}}},
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}},
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "modifyTime": float64(123),
"singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}},
"lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}},
}}
if _, err := service.RecordConversationPage(ctx, "account-1", "self", body); err != nil {
t.Fatal(err)
}
owner, _ := store.Users.GetByUsername(ctx, "owner")
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar {
t.Fatalf("unexpected sessions: %+v", rows)
}
}
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
service := New(store)
body := map[string]any{"userConvs": []any{
map[string]any{"singleChatUserConversation": map[string]any{
"singleChatConversation": map[string]any{"cid": "empty@goofish", "pairFirst": "self@goofish", "pairSecond": "69@goofish"},
}},
map[string]any{"singleChatUserConversation": map[string]any{
"singleChatConversation": map[string]any{"cid": "system@goofish", "pairFirst": "self@goofish", "pairSecond": "1400@goofish"},
"lastMessage": map[string]any{"message": map[string]any{
"createAt": float64(100), "reminderContent": "邀您填写售后问卷",
}},
}},
}}
if _, err := service.RecordConversationPage(context.Background(), "account-1", "self", body); err != nil {
t.Fatal(err)
}
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
rows, err := store.Chats.ListSessions(context.Background(), owner.ID, "account-1", 20)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ChatID != "system" {
t.Fatalf("empty conversation shell was imported: %+v", rows)
}
}
func TestDeleteEmptySessionsRemovesGhostsButKeepsRealConversation(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
ctx := context.Background()
ghost := db.ChatSession{CookieID: "account-1", ChatID: "ghost", BuyerID: "peer-ghost", LastMessage: "暂无消息", LastMessageAt: 100}
if err := store.Chats.UpsertSession(ctx, ghost); err != nil {
t.Fatal(err)
}
real := db.ChatSession{CookieID: "account-1", ChatID: "real", BuyerID: "peer-real", LastMessage: "暂无消息", LastMessageAt: 200}
if _, _, err := store.Chats.SaveMessage(ctx, real, db.ChatMessage{MessageKey: "real-1", Direction: "incoming", SenderID: "peer-real", SenderName: "真实用户", MessageType: "text", Content: "真实消息", Status: "received", SentAt: 200}, false); err != nil {
t.Fatal(err)
}
if err := store.Chats.DeleteEmptySessions(ctx, "account-1"); err != nil {
t.Fatal(err)
}
owner, _ := store.Users.GetByUsername(ctx, "owner")
rows, err := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ChatID != "real" {
t.Fatalf("unexpected sessions after pruning: %+v", rows)
}
}
func TestValidNicknameRejectsSystemReminderTitles(t *testing.T) {
for _, value := range []string{"", "203591535", "x***3", "快给ta一个评价吧~", "[卖家已发货]", "闲小蜜发来一条新消息"} {
if ValidNickname(value) {
t.Fatalf("system reminder accepted as nickname: %q", value)
}
}
if !ValidNickname("纽约做手工的石斑") {
t.Fatal("real nickname rejected")
}
}
func TestIncomingMessagePersistsDeduplicatesAndPublishesByOwner(t *testing.T) {
store, cleanup := chatTestStore(t)
defer cleanup()
ctx := context.Background()
owner, _ := store.Users.GetByUsername(ctx, "owner")
other, _ := store.Users.GetByUsername(ctx, "other")
service := New(store)
ownerEvents, cancelOwner, err := service.Subscribe(ctx, owner.ID)
if err != nil {
t.Fatal(err)
}
defer cancelOwner()
otherEvents, cancelOther, err := service.Subscribe(ctx, other.ID)
if err != nil {
t.Fatal(err)
}
defer cancelOther()
incoming := Incoming{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家甲",
Text: "你好", ItemID: "item-1", Raw: map[string]any{"messageId": "platform-1", "sendTime": int64(1234567890000)}}
message, inserted, err := service.RecordIncoming(ctx, incoming)
if err != nil || !inserted || message.MessageKey != "platform-1" {
t.Fatalf("message=%+v inserted=%v err=%v", message, inserted, err)
}
if _, inserted, err := service.RecordIncoming(ctx, incoming); err != nil || inserted {
t.Fatalf("duplicate inserted=%v err=%v", inserted, err)
}
select {
case event := <-ownerEvents:
if event.Type != "message.created" || event.Message.MessageKey != "platform-1" {
t.Fatalf("event=%+v", event)
}
case <-time.After(time.Second):
t.Fatal("owner did not receive event")
}
select {
case event := <-otherEvents:
t.Fatalf("other owner leaked event: %+v", event)
case <-time.After(30 * time.Millisecond):
}
}
func TestExtractMessageContentSupportsImageAndVideo(t *testing.T) {
imageRaw := map[string]any{"payload": `{"contentType":2,"image":{"pics":[{"url":"https://cdn/image.jpg"}]}}`}
if kind, content := extractMessageContent(imageRaw, "[图片]"); kind != "image" || content != "https://cdn/image.jpg" {
t.Fatalf("image kind=%q content=%q", kind, content)
}
videoRaw := map[string]any{"content": map[string]any{"video": map[string]any{"playUrl": "https://cdn/video.mp4"}}}
if kind, content := extractMessageContent(videoRaw, "[视频]"); kind != "video" || content != "https://cdn/video.mp4" {
t.Fatalf("video kind=%q content=%q", kind, content)
}
if kind, content := extractMessageContent(nil, " 你好 "); kind != "text" || content != "你好" {
t.Fatalf("text kind=%q content=%q", kind, content)
}
}
func chatTestStore(t *testing.T) (*db.Store, func()) {
t.Helper()
database, dialect, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "chat.db"))
if err != nil {
t.Fatal(err)
}
store := db.NewStore(database, dialect)
if ok, err := store.Users.Create(context.Background(), "owner", "owner@example.com", "pw"); err != nil || !ok {
t.Fatal(err)
}
if ok, err := store.Users.Create(context.Background(), "other", "other@example.com", "pw"); err != nil || !ok {
t.Fatal(err)
}
owner, _ := store.Users.GetByUsername(context.Background(), "owner")
other, _ := store.Users.GetByUsername(context.Background(), "other")
if err := store.Cookies.Save(context.Background(), "account-1", "unb=1", owner.ID); err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(context.Background(), "account-2", "unb=2", other.ID); err != nil {
t.Fatal(err)
}
return store, func() { _ = database.Close() }
}
+189
View File
@@ -0,0 +1,189 @@
package db
import (
"context"
"database/sql"
"errors"
"strings"
"time"
)
type AccountTaskSettings struct {
CookieID string `json:"account_id"`
AutoRateEnabled bool `json:"auto_rate_enabled"`
RateContent string `json:"rate_content"`
AutoPolishEnabled bool `json:"auto_polish_enabled"`
PolishTime string `json:"polish_time"`
LastRateScanAt int64 `json:"last_rate_scan_at"`
LastPolishDate string `json:"last_polish_date"`
LastPolishAt int64 `json:"last_polish_at"`
}
type AccountTaskRun struct {
ID int64 `json:"id"`
RunKey string `json:"run_key"`
CookieID string `json:"account_id"`
TaskType string `json:"task_type"`
TargetID string `json:"target_id"`
RunDate string `json:"run_date"`
Status string `json:"status"`
SuccessCount int `json:"success_count"`
FailedCount int `json:"failed_count"`
ErrorMessage string `json:"error_message"`
NextRetryAt int64 `json:"next_retry_at"`
StartedAt int64 `json:"started_at"`
FinishedAt int64 `json:"finished_at"`
}
type AccountTaskStore struct {
DB *sql.DB
Dialect Dialect
}
func defaultAccountTaskSettings(cookieID string) AccountTaskSettings {
return AccountTaskSettings{CookieID: cookieID, RateContent: "不错的买家,交易愉快", PolishTime: "03:00"}
}
func (s *AccountTaskStore) Get(ctx context.Context, cookieID string) (AccountTaskSettings, error) {
result := defaultAccountTaskSettings(cookieID)
var rateEnabled, polishEnabled int
err := s.DB.QueryRowContext(ctx, `SELECT auto_rate_enabled,rate_content,auto_polish_enabled,polish_time,
last_rate_scan_at,last_polish_date,last_polish_at FROM account_task_settings WHERE cookie_id=?`, cookieID).Scan(
&rateEnabled, &result.RateContent, &polishEnabled, &result.PolishTime, &result.LastRateScanAt,
&result.LastPolishDate, &result.LastPolishAt)
if errors.Is(err, sql.ErrNoRows) {
return result, nil
}
result.AutoRateEnabled = rateEnabled != 0
result.AutoPolishEnabled = polishEnabled != 0
return result, err
}
func (s *AccountTaskStore) Upsert(ctx context.Context, settings AccountTaskSettings) error {
settings.RateContent = strings.TrimSpace(settings.RateContent)
if settings.RateContent == "" {
settings.RateContent = "不错的买家,交易愉快"
}
if settings.PolishTime == "" {
settings.PolishTime = "03:00"
}
now := time.Now().UTC().Unix()
query := `INSERT INTO account_task_settings
(cookie_id,auto_rate_enabled,rate_content,auto_polish_enabled,polish_time,last_rate_scan_at,last_polish_date,last_polish_at,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?)` + dialectUpsert(s.Dialect, []string{"cookie_id"}, map[string]string{
"auto_rate_enabled": "EXCLUDED.auto_rate_enabled", "rate_content": "EXCLUDED.rate_content",
"auto_polish_enabled": "EXCLUDED.auto_polish_enabled", "polish_time": "EXCLUDED.polish_time",
"updated_at": "EXCLUDED.updated_at",
})
_, err := s.DB.ExecContext(ctx, query, settings.CookieID, boolInt(settings.AutoRateEnabled), settings.RateContent,
boolInt(settings.AutoPolishEnabled), settings.PolishTime, settings.LastRateScanAt, settings.LastPolishDate,
settings.LastPolishAt, now, now)
return err
}
func (s *AccountTaskStore) Enabled(ctx context.Context) ([]AccountTaskSettings, error) {
rows, err := s.DB.QueryContext(ctx, `SELECT s.cookie_id,s.auto_rate_enabled,s.rate_content,s.auto_polish_enabled,s.polish_time,
s.last_rate_scan_at,s.last_polish_date,s.last_polish_at
FROM account_task_settings s JOIN cookies c ON c.id=s.cookie_id
WHERE s.auto_rate_enabled=1 OR s.auto_polish_enabled=1 ORDER BY s.cookie_id`)
if err != nil {
return nil, err
}
defer rows.Close()
var result []AccountTaskSettings
for rows.Next() {
var row AccountTaskSettings
var rate, polish int
if err := rows.Scan(&row.CookieID, &rate, &row.RateContent, &polish, &row.PolishTime,
&row.LastRateScanAt, &row.LastPolishDate, &row.LastPolishAt); err != nil {
return nil, err
}
row.AutoRateEnabled, row.AutoPolishEnabled = rate != 0, polish != 0
result = append(result, row)
}
return result, rows.Err()
}
// ClaimRun creates a run or atomically reclaims a due failed run.
func (s *AccountTaskStore) ClaimRun(ctx context.Context, run AccountTaskRun, now int64) (bool, error) {
return s.claimRun(ctx, run, now, false)
}
// ClaimRunImmediately creates a run or immediately reclaims a failed run. It is
// intended for an explicit user retry; scheduled workers should keep using
// ClaimRun so repeated platform failures still honor their retry delay.
func (s *AccountTaskStore) ClaimRunImmediately(ctx context.Context, run AccountTaskRun, now int64) (bool, error) {
return s.claimRun(ctx, run, now, true)
}
func (s *AccountTaskStore) claimRun(ctx context.Context, run AccountTaskRun, now int64, immediate bool) (bool, error) {
retryCondition := "next_retry_at<=?"
args := []any{now, run.RunKey, now}
if immediate {
retryCondition = "1=1"
args = args[:2]
}
res, err := s.DB.ExecContext(ctx, `UPDATE account_task_runs SET status='running',started_at=?,finished_at=0,error_message=''
WHERE run_key=? AND status='failed' AND `+retryCondition, args...)
if err != nil {
return false, err
}
if n, _ := res.RowsAffected(); n > 0 {
return true, nil
}
query := dialectInsertIgnorePrefix(s.Dialect) + ` INTO account_task_runs
(run_key,cookie_id,task_type,target_id,run_date,status,success_count,failed_count,error_message,next_retry_at,started_at,finished_at)
VALUES(?,?,?,?,?,'running',0,0,'',0,?,0)` + dialectInsertIgnore(s.Dialect, []string{"run_key"})
res, err = s.DB.ExecContext(ctx, query, run.RunKey, run.CookieID, run.TaskType, run.TargetID, run.RunDate, now)
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
return n > 0, nil
}
func (s *AccountTaskStore) FinishRun(ctx context.Context, runKey, status string, success, failed int, message string, nextRetryAt int64) error {
_, err := s.DB.ExecContext(ctx, `UPDATE account_task_runs SET status=?,success_count=?,failed_count=?,error_message=?,next_retry_at=?,finished_at=? WHERE run_key=?`,
status, success, failed, message, nextRetryAt, time.Now().UTC().Unix(), runKey)
return err
}
func (s *AccountTaskStore) MarkRateScan(ctx context.Context, cookieID string, at int64) error {
_, err := s.DB.ExecContext(ctx, `UPDATE account_task_settings SET last_rate_scan_at=?,updated_at=? WHERE cookie_id=?`, at, at, cookieID)
return err
}
func (s *AccountTaskStore) MarkPolished(ctx context.Context, cookieID, date string, at int64) error {
_, err := s.DB.ExecContext(ctx, `UPDATE account_task_settings SET last_polish_date=?,last_polish_at=?,updated_at=? WHERE cookie_id=?`, date, at, at, cookieID)
return err
}
func (s *AccountTaskStore) RecentRuns(ctx context.Context, cookieID string, limit int) ([]AccountTaskRun, error) {
if limit <= 0 || limit > 100 {
limit = 20
}
rows, err := s.DB.QueryContext(ctx, `SELECT id,run_key,cookie_id,task_type,target_id,run_date,status,success_count,failed_count,
error_message,next_retry_at,started_at,finished_at FROM account_task_runs WHERE cookie_id=? ORDER BY id DESC LIMIT ?`, cookieID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var result []AccountTaskRun
for rows.Next() {
var row AccountTaskRun
if err := rows.Scan(&row.ID, &row.RunKey, &row.CookieID, &row.TaskType, &row.TargetID, &row.RunDate,
&row.Status, &row.SuccessCount, &row.FailedCount, &row.ErrorMessage, &row.NextRetryAt,
&row.StartedAt, &row.FinishedAt); err != nil {
return nil, err
}
result = append(result, row)
}
return result, rows.Err()
}
func boolInt(v bool) int {
if v {
return 1
}
return 0
}
+199 -39
View File
@@ -12,6 +12,9 @@ import (
var ErrAutomationRunActive = errors.New("规则仍有待处理的自动化运行")
// SafeRetryErrorPrefix 标记当前动作明确没有产生外部副作用,可以从动作游标安全恢复。
const SafeRetryErrorPrefix = "[safe_retry]"
// AutomationRules 管理自动化规则、动作和执行记录。
//
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
@@ -89,6 +92,7 @@ type DeferredAutomationTask struct {
TaskJSON string
DueAt int64
ClaimVersion int
ErrorMessage string
}
var ErrDeferredTaskLeaseLost = errors.New("延迟自动化任务租约已失效")
@@ -128,6 +132,42 @@ type AutomationRuleInput struct {
Actions []AutomationActionInput
}
// AutomationRuleListFilter 是自动化规则列表的筛选和分页条件。
type AutomationRuleListFilter struct {
UserID int64
CookieID string
TriggerType string
Enabled *bool
Search string
Limit int
Offset int
}
func automationRuleWhere(f AutomationRuleListFilter) (string, []any) {
where := []string{"r.user_id=?", "r.deleted_at IS NULL"}
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)
}
return strings.Join(where, " AND "), args
}
// AutomationActionInput 是创建动作的输入。
type AutomationActionInput struct {
ActionType string
@@ -142,15 +182,38 @@ 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) {
whereSQL, args := automationRuleWhere(f)
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 AND i.deleted_at IS NULL
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)
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
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 +222,43 @@ 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()
}
// CountByTriggerForUser 返回同一筛选条件下各触发类型的规则数量。
// 该统计不受分页影响,确保页面汇总与 total 使用同一数据集。
func (a *AutomationRules) CountByTriggerForUser(ctx context.Context, f AutomationRuleListFilter) (map[string]int, error) {
whereSQL, args := automationRuleWhere(f)
rows, err := a.DB.QueryContext(ctx, `
SELECT r.trigger_type, COUNT(*)
FROM automation_rules r
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE `+whereSQL+`
GROUP BY r.trigger_type`, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := map[string]int{}
for rows.Next() {
var triggerType string
var count int
if err := rows.Scan(&triggerType, &count); err != nil {
return nil, err
}
counts[triggerType] = count
}
return counts, rows.Err()
}
// Match 查询某事件可触发的规则。商品级规则存在时只返回商品级规则;
@@ -198,8 +287,8 @@ func (a *AutomationRules) Get(ctx context.Context, ruleID int64) (*AutomationRul
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.id=?`, ruleID).Scan(&rule.ID, &rule.UserID, &rule.CookieID, &rule.ItemID, &rule.ItemTitle,
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE r.id=? AND r.deleted_at IS NULL`, ruleID).Scan(&rule.ID, &rule.UserID, &rule.CookieID, &rule.ItemID, &rule.ItemTitle,
&rule.Name, &rule.TriggerType, &enabled, &rule.Priority, &rule.ConfigJSON, &rule.CreatedAt, &rule.UpdatedAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
@@ -217,12 +306,13 @@ func (a *AutomationRules) matchScope(ctx context.Context, cookieID, itemID, trig
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.enabled=1
AND r.cookie_id=?
AND r.trigger_type=?
LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL
WHERE r.deleted_at IS NULL
AND r.enabled=1
AND r.cookie_id=?
AND r.trigger_type=?
AND r.item_id=?
ORDER BY r.priority ASC, r.id ASC`, cookieID, triggerType, itemID)
ORDER BY r.priority ASC, r.id ASC`, cookieID, triggerType, itemID)
if err != nil {
return nil, err
}
@@ -273,7 +363,7 @@ func (a *AutomationRules) Update(ctx context.Context, userID, ruleID int64, in A
res, err := tx.ExecContext(ctx, `
UPDATE automation_rules
SET cookie_id=?,item_id=?,name=?,trigger_type=?,enabled=?,priority=?,config_json=?,updated_at=CURRENT_TIMESTAMP
WHERE id=? AND user_id=?`,
WHERE id=? AND user_id=? AND deleted_at IS NULL`,
in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON), ruleID, userID)
if err != nil {
return err
@@ -292,10 +382,11 @@ UPDATE automation_rules
return tx.Commit()
}
// Delete 删除规则。
// Delete 逻辑删除规则,保留动作和执行记录以便审计;逻辑删除后不再出现在规则列表和匹配结果中。
func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) error {
res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_rules
WHERE id=? AND user_id=? AND NOT EXISTS (
res, err := a.DB.ExecContext(ctx, `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE id=? AND user_id=? AND deleted_at IS NULL AND NOT EXISTS (
SELECT 1 FROM automation_runs ar WHERE ar.rule_id=automation_rules.id
AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3)))`, ruleID, userID)
if err != nil {
@@ -303,7 +394,7 @@ func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) erro
}
if n, _ := res.RowsAffected(); n == 0 {
var exists int
if err := a.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_rules WHERE id=? AND user_id=?`, ruleID, userID).Scan(&exists); err != nil {
if err := a.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_rules WHERE id=? AND user_id=? AND deleted_at IS NULL`, ruleID, userID).Scan(&exists); err != nil {
return err
}
if exists > 0 {
@@ -386,7 +477,8 @@ func (a *AutomationRules) reclaimRun(ctx context.Context, ruleID int64, triggerK
attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
WHERE rule_id=? AND trigger_key=?
AND ((status='running' AND action_started=0 AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`,
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`,
leaseExpiresAt, ruleID, triggerKey, now, now)
if err != nil {
return 0, false, err
@@ -480,20 +572,25 @@ func (a *AutomationRules) QuarantineRunResult(ctx context.Context, runID int64,
}
// PostponeRecoveryRun 把暂时不能执行的账号移到恢复队列尾部,避免固定的前 100 条饿死后续任务。
func (a *AutomationRules) PostponeRecoveryRun(ctx context.Context, runID, retryAt int64) error {
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
func (a *AutomationRules) PostponeRecoveryRun(ctx context.Context, runID int64, attempt int, retryAt int64) error {
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
SET lease_expires_at=CASE WHEN status='running' THEN ? ELSE lease_expires_at END,
next_retry_at=CASE WHEN status='failed' THEN ? ELSE next_retry_at END,
updated_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('running','failed')`, retryAt, retryAt, runID)
return err
updated_at=CURRENT_TIMESTAMP
WHERE id=? AND attempt_count=? AND action_started=0 AND status IN ('running','failed')`, retryAt, retryAt, runID, attempt)
if err != nil {
return err
}
return requireAutomationRunOwner(res)
}
func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpiresAt int64) (bool, error) {
now := time.Now().UTC().Unix()
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
SET status='running',error_message='',lease_expires_at=?,next_retry_at=0,attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`, leaseExpiresAt, runID, now, now)
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND attempt_count<3 AND next_retry_at<=?
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`, leaseExpiresAt, runID, now, now)
if err != nil {
return false, err
}
@@ -504,7 +601,7 @@ func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpi
// FinishRun 标记执行完成或失败。
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, attempt int, status string, sentCount int, errMsg string) error {
nextRetryAt := int64(0)
if status == "failed" && sentCount == 0 {
if status == "failed" && (sentCount == 0 || strings.HasPrefix(errMsg, SafeRetryErrorPrefix)) {
nextRetryAt = time.Now().UTC().Add(time.Minute).Unix()
}
res, err := a.DB.ExecContext(ctx, `
@@ -540,7 +637,8 @@ SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigg
status,sent_count,error_message,raw_event_json,lease_expires_at,attempt_count,next_retry_at,action_cursor,action_started
FROM automation_runs
WHERE (status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?)
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
AND (sent_count=0 OR error_message LIKE '[safe_retry]%'))
ORDER BY updated_at,id LIMIT ?`, now, now, limit)
if err != nil {
return nil, err
@@ -562,10 +660,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 +689,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
}
@@ -583,7 +699,7 @@ func (a *AutomationRules) ListIssues(ctx context.Context, userID int64) ([]Autom
ar.action_cursor,ar.sent_count,ar.updated_at,ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0)
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
LEFT JOIN automation_rules r ON r.id=ar.rule_id
WHERE c.user_id=? AND ar.status='needs_review' ORDER BY ar.updated_at DESC,ar.id DESC`, userID)
WHERE c.user_id=? AND ar.status='needs_review' AND r.deleted_at IS NULL ORDER BY ar.updated_at DESC,ar.id DESC`, userID)
if err != nil {
return nil, nil, err
}
@@ -631,7 +747,7 @@ func (a *AutomationRules) ResolveRunIssue(ctx context.Context, userID, runID int
err := a.DB.QueryRowContext(ctx, `SELECT ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0),ar.sent_count,ar.error_message
FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id
LEFT JOIN automation_rules r ON r.id=ar.rule_id
WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=?`, runID, userID).
WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=? AND r.deleted_at IS NULL`, runID, userID).
Scan(&rawEventJSON, &actionStarted, &ruleEnabled, &sentCount, &errorMessage)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
@@ -773,13 +889,50 @@ 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%'
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, 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 action_started=0
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, 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 +961,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
}
@@ -848,12 +1006,14 @@ SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_stat
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
created_at,updated_at
FROM orders o
WHERE o.system_shipped=1
WHERE o.system_shipped=1
AND o.deleted_at IS NULL
AND COALESCE(o.buyer_reviewed_at,'')=''
AND COALESCE(o.chat_id,'')<>''
AND EXISTS (SELECT 1 FROM automation_rules r
WHERE r.cookie_id=o.cookie_id AND r.trigger_type='review_missing_timeout'
AND r.enabled=1 AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+`
AND r.deleted_at IS NULL AND r.enabled=1
AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+`
ORDER BY o.order_id ASC
LIMIT ?`, args...)
if err != nil {
+127 -1
View File
@@ -204,6 +204,14 @@ func TestAutomation_UpdateDelete(t *testing.T) {
if len(rules) != 0 {
t.Fatalf("Delete 后 len=%d want 0", len(rules))
}
var deletedAt string
var enabled int
if err := s.DB.QueryRowContext(ctx, `SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&deletedAt, &enabled); err != nil {
t.Fatalf("逻辑删除后规则原始行不存在: %v", err)
}
if deletedAt == "" || enabled != 0 {
t.Fatalf("规则未逻辑删除并禁用: deleted_at=%q enabled=%d", deletedAt, enabled)
}
// 重复 Delete → ErrNotFound。
if err := s.Automation.Delete(ctx, uid, ruleID); !errors.Is(err, ErrNotFound) {
t.Fatalf("重复 Delete 应 ErrNotFound, got %v", err)
@@ -359,6 +367,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()
@@ -466,6 +512,37 @@ func TestAutomationRunAttemptFencesStaleWorker(t *testing.T) {
}
}
func TestPostponeRecoveryRunCannotOverwriteNewOwnerLease(t *testing.T) {
s, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
uid, cid := seedAccount(t, s)
ruleID, _ := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "item", "paid", true, 0))
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cid, TriggerType: "paid", TriggerKey: "postpone-fence"})
if err != nil || !started {
t.Fatalf("start run: id=%d started=%v err=%v", runID, started, err)
}
stale, err := s.Automation.GetRun(ctx, runID)
if err != nil {
t.Fatal(err)
}
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=0 WHERE id=?`, runID); err != nil {
t.Fatal(err)
}
newLease := time.Now().UTC().Add(5 * time.Minute).Unix()
claimed, err := s.Automation.ClaimRecoveryRun(ctx, runID, newLease)
if err != nil || !claimed {
t.Fatalf("claim=%v err=%v", claimed, err)
}
if err := s.Automation.PostponeRecoveryRun(ctx, runID, stale.AttemptCount, time.Now().UTC().Add(time.Minute).Unix()); !errors.Is(err, ErrAutomationRunLeaseLost) {
t.Fatalf("stale postpone err=%v want lease lost", err)
}
current, err := s.Automation.GetRun(ctx, runID)
if err != nil || current.LeaseExpiresAt != newLease {
t.Fatalf("new owner lease was overwritten: run=%+v err=%v", current, err)
}
}
// TestValidJSON validJSON 的非法 JSON 兜底为 {}。
func TestValidJSON(t *testing.T) {
if got := validJSON(""); got != "{}" {
@@ -524,7 +601,7 @@ func TestAutomationIssuesCanBeListedAndResolved(t *testing.T) {
if run.Status != "running" || run.ActionStarted || run.ActionCursor != 1 {
t.Fatalf("resolved run=%+v", run)
}
if err := s.Automation.PostponeRecoveryRun(ctx, runID, 4102444800); err != nil {
if err := s.Automation.PostponeRecoveryRun(ctx, runID, run.AttemptCount, 4102444800); err != nil {
t.Fatal(err)
}
due, err := s.Automation.DueRecoveryRuns(ctx, 10)
@@ -617,6 +694,55 @@ 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.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "ws-wake", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{}`, DueAt: before + 3600, ErrorMessage: "当前没有可用 WebSocket 连接"}); 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='ws-wake'`).Scan(&dueAt); err != nil || dueAt != 0 {
t.Fatalf("WS 恢复必须立即唤醒任务: due_at=%d err=%v", dueAt, 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()
+281
View File
@@ -0,0 +1,281 @@
package db
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
)
type ChatSession struct {
CookieID string `json:"account_id"`
ChatID string `json:"chat_id"`
BuyerID string `json:"buyer_id"`
BuyerName string `json:"buyer_name"`
BuyerAvatar string `json:"buyer_avatar_url"`
ItemID string `json:"item_id"`
ItemTitle string `json:"item_title"`
LastMessage string `json:"last_message"`
LastMessageAt int64 `json:"last_message_at"`
UnreadCount int `json:"unread_count"`
}
type ChatMessage struct {
ID int64 `json:"id"`
CookieID string `json:"account_id"`
ChatID string `json:"chat_id"`
MessageKey string `json:"message_key"`
Direction string `json:"direction"`
SenderID string `json:"sender_id"`
SenderName string `json:"sender_name"`
MessageType string `json:"message_type"`
Content string `json:"content"`
Status string `json:"status"`
SentAt int64 `json:"sent_at"`
}
type ChatStore struct {
DB *sql.DB
Dialect Dialect
}
func (s *ChatStore) UpsertSession(ctx context.Context, session ChatSession) error {
now := time.Now().UTC().Unix()
prefix := dialectInsertIgnorePrefix(s.Dialect)
query := prefix + ` INTO chat_sessions
(cookie_id,chat_id,buyer_id,buyer_name,buyer_avatar_url,item_id,item_title,last_message,last_message_at,unread_count,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "chat_id"})
if _, err := s.DB.ExecContext(ctx, query, session.CookieID, session.ChatID, session.BuyerID, session.BuyerName,
session.BuyerAvatar, session.ItemID, session.ItemTitle, session.LastMessage, session.LastMessageAt,
session.UnreadCount, now, now); err != nil {
return err
}
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET
buyer_id=CASE WHEN ?<>'' THEN ? ELSE buyer_id END,
buyer_name=CASE WHEN ?<>'' THEN ? ELSE buyer_name END,
buyer_avatar_url=CASE WHEN ?<>'' THEN ? ELSE buyer_avatar_url END,
item_id=CASE WHEN ?<>'' THEN ? ELSE item_id END,
item_title=CASE WHEN ?<>'' THEN ? ELSE item_title END,
last_message=CASE WHEN last_message_at<=? THEN ? ELSE last_message END,
last_message_at=CASE WHEN last_message_at<=? THEN ? ELSE last_message_at END,
unread_count=CASE WHEN ?>unread_count THEN ? ELSE unread_count END,updated_at=?
WHERE cookie_id=? AND chat_id=?`, session.BuyerID, session.BuyerID, session.BuyerName, session.BuyerName,
session.BuyerAvatar, session.BuyerAvatar, session.ItemID, session.ItemID, session.ItemTitle, session.ItemTitle,
session.LastMessageAt, session.LastMessage, session.LastMessageAt, session.LastMessageAt,
session.UnreadCount, session.UnreadCount, now, session.CookieID, session.ChatID)
return err
}
func (s *ChatStore) DeleteSession(ctx context.Context, cookieID, chatID string) error {
_, err := s.DB.ExecContext(ctx, `DELETE FROM chat_sessions WHERE cookie_id=? AND chat_id=?`, cookieID, chatID)
return err
}
// DeleteEmptySessions removes conversation shells returned by IM pagination
// with visible=0 and no lastMessage. Older versions persisted these shells as
// "暂无消息", although the official UI never renders them.
func (s *ChatStore) DeleteEmptySessions(ctx context.Context, cookieID string) error {
_, err := s.DB.ExecContext(ctx, `DELETE FROM chat_sessions
WHERE cookie_id=? AND (last_message='' OR last_message='暂无消息')
AND NOT EXISTS (SELECT 1 FROM chat_messages m WHERE m.cookie_id=chat_sessions.cookie_id AND m.chat_id=chat_sessions.chat_id)`, cookieID)
return err
}
// SyncSessionSummary applies the authoritative last-message timestamp from the
// official conversation response. observedModifyAt guards against overwriting
// a genuinely newer live message that arrived after that response was built.
func (s *ChatStore) SyncSessionSummary(ctx context.Context, cookieID, chatID, summary string, sentAt, observedModifyAt int64, unread int) error {
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET last_message=?,last_message_at=?,unread_count=?,updated_at=?
WHERE cookie_id=? AND chat_id=? AND last_message_at<=?`, summary, sentAt, unread, time.Now().UTC().Unix(),
cookieID, chatID, observedModifyAt)
return err
}
func (s *ChatStore) UpdateSessionIdentity(ctx context.Context, cookieID, chatID, buyerID, buyerName, avatarURL string) error {
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET
buyer_id=CASE WHEN ?<>'' THEN ? ELSE buyer_id END,
buyer_name=CASE WHEN ?<>'' THEN ? ELSE buyer_name END,
buyer_avatar_url=CASE WHEN ?<>'' THEN ? ELSE buyer_avatar_url END,
updated_at=? WHERE cookie_id=? AND chat_id=?`, buyerID, buyerID, buyerName, buyerName,
avatarURL, avatarURL, time.Now().UTC().Unix(), cookieID, chatID)
return err
}
// LatestUnmaskedPeerName recovers the most recent real nickname observed in
// message history. Conversation summaries and profile APIs may return masked
// names such as x***3, while older message extensions still contain the nick.
func (s *ChatStore) LatestUnmaskedPeerName(ctx context.Context, cookieID, chatID string) (string, error) {
var name string
err := s.DB.QueryRowContext(ctx, `SELECT sender_name FROM chat_messages
WHERE cookie_id=? AND chat_id=? AND direction='incoming' AND sender_name<>'' AND sender_name NOT LIKE '%***%'
AND message_type<>'system'
AND sender_name<>content AND sender_name NOT IN ('交易消息','系统消息','卡片消息','我完成了评价','对方完成了评价',
'快给ta一个评价吧~','卖家已发货','买家已付款','买家已确认收货','等待您发货','超时未付款,系统关闭了订单','邀您填写售后问卷')
ORDER BY sent_at DESC,id DESC LIMIT 1`, cookieID, chatID).Scan(&name)
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
return strings.TrimSpace(name), err
}
// SaveMessage inserts a message idempotently and updates its conversation only
// when the message was new. This keeps retries from inflating unread counters.
func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, message ChatMessage, unread bool) (*ChatMessage, bool, error) {
if s == nil || s.DB == nil {
return nil, false, errors.New("聊天存储未初始化")
}
session.CookieID = strings.TrimSpace(session.CookieID)
session.ChatID = strings.TrimSpace(session.ChatID)
message.MessageKey = strings.TrimSpace(message.MessageKey)
if session.CookieID == "" || session.ChatID == "" || message.MessageKey == "" {
return nil, false, errors.New("聊天消息缺少账号、会话或消息键")
}
if message.SentAt <= 0 {
message.SentAt = time.Now().UTC().UnixMilli()
}
message.CookieID, message.ChatID = session.CookieID, session.ChatID
now := time.Now().UTC().Unix()
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return nil, false, err
}
defer tx.Rollback()
// The composite foreign key on chat_messages requires the session to exist
// first. Insert an empty shell without touching an existing conversation.
sessionPrefix := dialectInsertIgnorePrefix(s.Dialect)
sessionInsert := sessionPrefix + ` INTO chat_sessions
(cookie_id,chat_id,buyer_id,buyer_name,buyer_avatar_url,item_id,item_title,last_message,last_message_at,unread_count,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "chat_id"})
if _, err := tx.ExecContext(ctx, sessionInsert, session.CookieID, session.ChatID, session.BuyerID,
session.BuyerName, session.BuyerAvatar, session.ItemID, session.ItemTitle, "", int64(0), 0, now, now); err != nil {
return nil, false, fmt.Errorf("建立聊天会话: %w", err)
}
prefix := dialectInsertIgnorePrefix(s.Dialect)
query := prefix + ` INTO chat_messages
(cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at,created_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(s.Dialect, []string{"cookie_id", "message_key"})
res, err := tx.ExecContext(ctx, query, message.CookieID, message.ChatID, message.MessageKey,
message.Direction, message.SenderID, message.SenderName, message.MessageType, message.Content,
message.Status, message.SentAt, now)
if err != nil {
return nil, false, fmt.Errorf("保存聊天消息: %w", err)
}
inserted, _ := res.RowsAffected()
if inserted > 0 {
unreadDelta := 0
if unread {
unreadDelta = 1
}
if _, err := tx.ExecContext(ctx, `UPDATE chat_sessions SET buyer_id=?,buyer_name=?,buyer_avatar_url=?,
item_id=?,item_title=?,last_message=CASE WHEN last_message_at<=? THEN ? ELSE last_message END,
last_message_at=CASE WHEN last_message_at<=? THEN ? ELSE last_message_at END,
unread_count=unread_count+?,updated_at=?
WHERE cookie_id=? AND chat_id=?`, session.BuyerID, session.BuyerName, session.BuyerAvatar,
session.ItemID, session.ItemTitle, message.SentAt, message.Content, message.SentAt, message.SentAt, unreadDelta, now,
session.CookieID, session.ChatID); err != nil {
return nil, false, fmt.Errorf("更新聊天会话: %w", err)
}
}
if err := tx.Commit(); err != nil {
return nil, false, err
}
stored, err := s.GetMessageByKey(ctx, message.CookieID, message.MessageKey)
return stored, inserted > 0, err
}
func (s *ChatStore) GetMessageByKey(ctx context.Context, cookieID, key string) (*ChatMessage, error) {
var m ChatMessage
err := s.DB.QueryRowContext(ctx, `SELECT id,cookie_id,chat_id,message_key,direction,sender_id,sender_name,message_type,content,status,sent_at
FROM chat_messages WHERE cookie_id=? AND message_key=?`, cookieID, key).Scan(
&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID, &m.SenderName,
&m.MessageType, &m.Content, &m.Status, &m.SentAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return &m, err
}
// UpdateMessageType refreshes the classification of an already persisted
// message when a later history response exposes richer protocol metadata.
func (s *ChatStore) UpdateMessageType(ctx context.Context, cookieID, key, messageType string) error {
_, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET message_type=?
WHERE cookie_id=? AND message_key=?`, messageType, cookieID, key)
return err
}
func (s *ChatStore) ListSessions(ctx context.Context, userID int64, cookieID string, limit int) ([]ChatSession, error) {
if limit <= 0 || limit > 500 {
limit = 200
}
rows, err := s.DB.QueryContext(ctx, `SELECT cs.cookie_id,cs.chat_id,cs.buyer_id,cs.buyer_name,cs.buyer_avatar_url,
cs.item_id,cs.item_title,cs.last_message,cs.last_message_at,cs.unread_count
FROM chat_sessions cs JOIN cookies c ON c.id=cs.cookie_id
WHERE c.user_id=? AND cs.cookie_id=? ORDER BY cs.last_message_at DESC LIMIT ?`, userID, cookieID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var result []ChatSession
for rows.Next() {
var row ChatSession
if err := rows.Scan(&row.CookieID, &row.ChatID, &row.BuyerID, &row.BuyerName, &row.BuyerAvatar,
&row.ItemID, &row.ItemTitle, &row.LastMessage, &row.LastMessageAt, &row.UnreadCount); err != nil {
return nil, err
}
result = append(result, row)
}
return result, rows.Err()
}
func (s *ChatStore) ListMessages(ctx context.Context, userID int64, cookieID, chatID string, beforeID int64, limit int) ([]ChatMessage, error) {
if limit <= 0 || limit > 200 {
limit = 50
}
query := `SELECT m.id,m.cookie_id,m.chat_id,m.message_key,m.direction,m.sender_id,m.sender_name,m.message_type,m.content,m.status,m.sent_at
FROM chat_messages m JOIN cookies c ON c.id=m.cookie_id
WHERE c.user_id=? AND m.cookie_id=? AND m.chat_id=?`
args := []any{userID, cookieID, chatID}
if beforeID > 0 {
query += ` AND (m.sent_at < COALESCE((SELECT older.sent_at FROM chat_messages older WHERE older.id=? AND older.cookie_id=?), m.sent_at)
OR (m.sent_at = COALESCE((SELECT same.sent_at FROM chat_messages same WHERE same.id=? AND same.cookie_id=?), m.sent_at) AND m.id<?))`
args = append(args, beforeID, cookieID, beforeID, cookieID, beforeID)
}
query += ` ORDER BY m.sent_at DESC,m.id DESC LIMIT ?`
args = append(args, limit)
rows, err := s.DB.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var result []ChatMessage
for rows.Next() {
var m ChatMessage
if err := rows.Scan(&m.ID, &m.CookieID, &m.ChatID, &m.MessageKey, &m.Direction, &m.SenderID,
&m.SenderName, &m.MessageType, &m.Content, &m.Status, &m.SentAt); err != nil {
return nil, err
}
result = append(result, m)
}
// API returns chronological order while the query remains index-friendly.
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
result[i], result[j] = result[j], result[i]
}
return result, rows.Err()
}
func (s *ChatStore) MarkRead(ctx context.Context, userID int64, cookieID, chatID string) error {
_, err := s.DB.ExecContext(ctx, `UPDATE chat_sessions SET unread_count=0,updated_at=?
WHERE cookie_id=? AND chat_id=? AND EXISTS(SELECT 1 FROM cookies c WHERE c.id=chat_sessions.cookie_id AND c.user_id=?)`,
time.Now().UTC().Unix(), cookieID, chatID, userID)
return err
}
func (s *ChatStore) UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*ChatMessage, error) {
if _, err := s.DB.ExecContext(ctx, `UPDATE chat_messages SET status=? WHERE cookie_id=? AND message_key=?`, status, cookieID, key); err != nil {
return nil, err
}
return s.GetMessageByKey(ctx, cookieID, key)
}
+3 -3
View File
@@ -53,7 +53,7 @@ func (i *Items) Get(ctx context.Context, cookieID, itemID string) (*ItemInfo, er
err := i.DB.QueryRowContext(ctx,
`SELECT id, cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail,
is_multi_spec, multi_quantity_delivery
FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(
FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(
&it.ID, &it.CookieID, &it.ItemID, &title, &desc, &cat,
&price, &detail, &isMulti, &multiQty)
if err != nil {
@@ -75,7 +75,7 @@ func (i *Items) Get(ctx context.Context, cookieID, itemID string) (*ItemInfo, er
// IsMultiSpec 是否多规格商品。
func (i *Items) IsMultiSpec(ctx context.Context, cookieID, itemID string) bool {
var v int
err := i.DB.QueryRowContext(ctx, `SELECT is_multi_spec FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v)
err := i.DB.QueryRowContext(ctx, `SELECT is_multi_spec FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(&v)
if err != nil {
return false
}
@@ -85,7 +85,7 @@ func (i *Items) IsMultiSpec(ctx context.Context, cookieID, itemID string) bool {
// MultiQuantityDelivery 是否开启多数量发货。
func (i *Items) MultiQuantityDelivery(ctx context.Context, cookieID, itemID string) bool {
var v int
err := i.DB.QueryRowContext(ctx, `SELECT multi_quantity_delivery FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v)
err := i.DB.QueryRowContext(ctx, `SELECT multi_quantity_delivery FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(&v)
if err != nil {
return false
}
+119 -6
View File
@@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"strconv"
"strings"
)
// ---- 关键字 CRUD ----
@@ -520,13 +521,19 @@ type ItemInfoRow struct {
MultiQuantityDelivery bool
}
// ItemSyncResult 是一次远端商品全集同步的结果。
type ItemSyncResult struct {
Saved int
Deleted int
}
// AllForCookie 取某账号全部商品。
func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRow, error) {
rows, err := i.DB.QueryContext(ctx,
`SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''),
COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''),
is_multi_spec, COALESCE(multi_quantity_delivery,0)
FROM item_info WHERE cookie_id=? ORDER BY id DESC`, cookieID)
FROM item_info WHERE cookie_id=? AND deleted_at IS NULL ORDER BY id DESC`, cookieID)
if err != nil {
return nil, err
}
@@ -560,6 +567,7 @@ func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error {
"item_detail": "EXCLUDED.item_detail",
"is_multi_spec": "EXCLUDED.is_multi_spec",
"multi_quantity_delivery": "EXCLUDED.multi_quantity_delivery",
"deleted_at": "NULL",
"updated_at": "CURRENT_TIMESTAMP",
}),
r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription),
@@ -577,6 +585,95 @@ func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) e
return i.upsertBasic(ctx, tx, r)
}
// SyncFromRemote 将远端商品全集同步到本地。
//
// 远端列表只提供商品基础信息,因此保留本地的描述和发货配置;基础字段
// (标题、分类、价格、详情)由远端非空值覆盖。整个 reconcile 在一个事务内
// 完成,只有在全部远端商品写入成功后,才会逻辑删除本次全集中不存在的本地商品及其商品级自动化规则。
func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []ItemInfoRow) (ItemSyncResult, error) {
cookieID = strings.TrimSpace(cookieID)
if cookieID == "" {
return ItemSyncResult{}, errors.New("cookie_id 不能为空")
}
remoteIDs := make(map[string]struct{}, len(rows))
validRows := make([]ItemInfoRow, 0, len(rows))
for _, row := range rows {
row.CookieID = cookieID
row.ItemID = strings.TrimSpace(row.ItemID)
if row.ItemID == "" {
continue
}
if _, exists := remoteIDs[row.ItemID]; exists {
continue
}
remoteIDs[row.ItemID] = struct{}{}
validRows = append(validRows, row)
}
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return ItemSyncResult{}, err
}
rollback := func(err error) (ItemSyncResult, error) {
_ = tx.Rollback()
return ItemSyncResult{}, err
}
for index := range validRows {
if err := i.UpsertBasicTx(ctx, tx, &validRows[index]); err != nil {
return rollback(err)
}
if validRows[index].IsMultiSpec {
if _, err := tx.ExecContext(ctx,
`UPDATE item_info SET is_multi_spec=? WHERE cookie_id=? AND item_id=?`,
boolToInt(true), cookieID, validRows[index].ItemID); err != nil {
return rollback(err)
}
}
}
args := make([]any, 0, len(remoteIDs)+1)
args = append(args, cookieID)
deleteQuery := `UPDATE item_info SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND deleted_at IS NULL`
if len(remoteIDs) > 0 {
placeholders := make([]string, 0, len(remoteIDs))
for itemID := range remoteIDs {
placeholders = append(placeholders, "?")
args = append(args, itemID)
}
deleteQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
}
deletedResult, err := tx.ExecContext(ctx, deleteQuery, args...)
if err != nil {
return rollback(err)
}
deleted, err := deletedResult.RowsAffected()
if err != nil {
return rollback(err)
}
ruleArgs := make([]any, 0, len(remoteIDs)+1)
ruleArgs = append(ruleArgs, cookieID)
ruleQuery := `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id<>'' AND deleted_at IS NULL`
if len(remoteIDs) > 0 {
placeholders := make([]string, 0, len(remoteIDs))
for itemID := range remoteIDs {
placeholders = append(placeholders, "?")
ruleArgs = append(ruleArgs, itemID)
}
ruleQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
}
if _, err := tx.ExecContext(ctx, ruleQuery, ruleArgs...); err != nil {
return rollback(err)
}
if err := tx.Commit(); err != nil {
return ItemSyncResult{}, err
}
return ItemSyncResult{Saved: len(validRows), Deleted: int(deleted)}, nil
}
func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRow) error {
// 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。
// SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。
@@ -589,6 +686,7 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
item_category=CASE WHEN VALUES(item_category) IS NOT NULL AND VALUES(item_category) != '' THEN VALUES(item_category) ELSE item_info.item_category END,
item_price=CASE WHEN VALUES(item_price) IS NOT NULL AND VALUES(item_price) != '' THEN VALUES(item_price) ELSE item_info.item_price END,
item_detail=CASE WHEN VALUES(item_detail) IS NOT NULL AND VALUES(item_detail) != '' THEN VALUES(item_detail) ELSE item_info.item_detail END,
deleted_at=NULL,
updated_at=CURRENT_TIMESTAMP`
default:
conflictClause = ` ON CONFLICT(cookie_id, item_id) DO UPDATE SET
@@ -597,6 +695,7 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
item_category=CASE WHEN EXCLUDED.item_category IS NOT NULL AND EXCLUDED.item_category != '' THEN EXCLUDED.item_category ELSE item_info.item_category END,
item_price=CASE WHEN EXCLUDED.item_price IS NOT NULL AND EXCLUDED.item_price != '' THEN EXCLUDED.item_price ELSE item_info.item_price END,
item_detail=CASE WHEN EXCLUDED.item_detail IS NOT NULL AND EXCLUDED.item_detail != '' THEN EXCLUDED.item_detail ELSE item_info.item_detail END,
deleted_at=NULL,
updated_at=CURRENT_TIMESTAMP`
}
_, err := execer.ExecContext(ctx,
@@ -608,16 +707,30 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo
return err
}
// Delete 删除商品。
// Delete 逻辑删除商品及其商品级自动化规则,保留历史数据以便审计和恢复。
func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error {
_, err := i.DB.ExecContext(ctx, `DELETE FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID)
return err
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `UPDATE item_info
SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE automation_rules
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil {
return err
}
return tx.Commit()
}
// SetMultiSpec 设置多规格开关。
func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bool) error {
_, err := i.DB.ExecContext(ctx,
`UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`,
`UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
boolToInt(on), cookieID, itemID)
return err
}
@@ -625,7 +738,7 @@ func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bo
// SetMultiQuantity 设置多数量发货开关。
func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, on bool) error {
_, err := i.DB.ExecContext(ctx,
`UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`,
`UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`,
boolToInt(on), cookieID, itemID)
return err
}
+158
View File
@@ -2,6 +2,7 @@ package db
import (
"context"
"database/sql"
"testing"
)
@@ -104,3 +105,160 @@ func TestExtraRepositoriesCRUD(t *testing.T) {
t.Fatal(err)
}
}
func TestItemsSyncFromRemoteReconcilesAndPreservesLocalSettings(t *testing.T) {
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
ok, err := store.Users.Create(ctx, "sync-user", "sync@example.com", "password")
if err != nil || !ok {
t.Fatalf("create test user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, "sync-user")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(ctx, "acc1", "unb=1", user.ID); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{
CookieID: "acc1", ItemID: "existing", ItemTitle: "旧标题", ItemDescription: "本地描述", ItemPrice: "¥9.90",
}); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiSpec(ctx, "acc1", "existing", true); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiQuantity(ctx, "acc1", "existing", true); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{CookieID: "acc1", ItemID: "deleted"}); err != nil {
t.Fatal(err)
}
ruleID, err := store.Automation.Create(ctx, AutomationRuleInput{
UserID: user.ID, CookieID: "acc1", ItemID: "deleted", Name: "删除商品规则",
TriggerType: "paid", Enabled: true, Priority: 100,
Actions: []AutomationActionInput{{ActionType: "send_msg", MessageTemplate: "hello", Enabled: true, SortOrder: 1}},
})
if err != nil {
t.Fatal(err)
}
result, err := store.Items.SyncFromRemote(ctx, "acc1", []ItemInfoRow{
{CookieID: "wrong-cookie", ItemID: "existing", ItemTitle: "新标题", ItemPrice: "¥19.90", IsMultiSpec: true},
{ItemID: "new", ItemTitle: "新商品", ItemPrice: "¥3.00"},
})
if err != nil {
t.Fatal(err)
}
if result.Saved != 2 || result.Deleted != 1 {
t.Fatalf("sync result=%+v, want saved=2 deleted=1", result)
}
items, err := store.Items.AllForCookie(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
if len(items) != 2 {
t.Fatalf("items=%+v, want 2 rows", items)
}
item, err := store.Items.Get(ctx, "acc1", "existing")
if err != nil {
t.Fatal(err)
}
if item.ItemTitle != "新标题" || item.ItemPrice != "¥19.90" || item.ItemDescription != "本地描述" ||
!item.IsMultiSpec || !item.MultiQuantityDelivery {
t.Fatalf("existing item was not updated/preserved: %+v", item)
}
if _, err := store.Items.Get(ctx, "acc1", "deleted"); err != ErrNotFound {
t.Fatalf("deleted item should be hidden from active lookup: err=%v", err)
}
var itemDeletedAt sql.NullString
if err := store.DB.QueryRowContext(ctx,
`SELECT deleted_at FROM item_info WHERE cookie_id=? AND item_id=?`, "acc1", "deleted").Scan(&itemDeletedAt); err != nil {
t.Fatalf("商品逻辑删除后原始行不存在: %v", err)
}
if !itemDeletedAt.Valid || itemDeletedAt.String == "" {
t.Fatalf("商品 deleted_at 未写入: %#v", itemDeletedAt)
}
var ruleDeletedAt sql.NullString
var ruleEnabled int
if err := store.DB.QueryRowContext(ctx,
`SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&ruleDeletedAt, &ruleEnabled); err != nil {
t.Fatalf("关联规则逻辑删除后原始行不存在: %v", err)
}
if !ruleDeletedAt.Valid || ruleDeletedAt.String == "" || ruleEnabled != 0 {
t.Fatalf("关联规则未逻辑删除并禁用: deleted_at=%#v enabled=%d", ruleDeletedAt, ruleEnabled)
}
rules, err := store.Automation.ListForUser(ctx, user.ID)
if err != nil {
t.Fatal(err)
}
if len(rules) != 0 {
t.Fatalf("已删除商品的规则不应出现在管理列表: %#v", rules)
}
matched, err := store.Automation.Match(ctx, "acc1", "deleted", "paid")
if err != nil {
t.Fatal(err)
}
if len(matched) != 0 {
t.Fatalf("已删除商品的规则不应再匹配: %#v", matched)
}
// 商品再次出现在远端时只恢复商品,不自动恢复已删除规则,避免旧规则误复活。
if _, err := store.Items.SyncFromRemote(ctx, "acc1", []ItemInfoRow{{ItemID: "existing"}, {ItemID: "deleted"}}); err != nil {
t.Fatal(err)
}
if _, err := store.Items.Get(ctx, "acc1", "deleted"); err != nil {
t.Fatalf("商品重新同步后应恢复商品记录: %v", err)
}
rules, err = store.Automation.ListForUser(ctx, user.ID)
if err != nil {
t.Fatal(err)
}
if len(rules) != 0 {
t.Fatalf("商品恢复后不应自动恢复旧规则: %#v", rules)
}
}
func TestItemsDeleteSoftDeletesRelatedAutomationRule(t *testing.T) {
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "item-delete-user", "item-delete@example.com", "password"); err != nil || !ok {
t.Fatalf("create test user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, "item-delete-user")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(ctx, "item-delete-cookie", "unb=1", user.ID); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{CookieID: "item-delete-cookie", ItemID: "item-1", ItemTitle: "待删除商品"}); err != nil {
t.Fatal(err)
}
ruleID, err := store.Automation.Create(ctx, AutomationRuleInput{
UserID: user.ID, CookieID: "item-delete-cookie", ItemID: "item-1", Name: "商品规则",
TriggerType: "paid", Enabled: true, Priority: 100,
Actions: []AutomationActionInput{{ActionType: "send_msg", MessageTemplate: "hello", Enabled: true, SortOrder: 1}},
})
if err != nil {
t.Fatal(err)
}
if err := store.Items.Delete(ctx, "item-delete-cookie", "item-1"); err != nil {
t.Fatal(err)
}
var itemDeletedAt, ruleDeletedAt string
var ruleEnabled int
if err := store.DB.QueryRowContext(ctx, `SELECT deleted_at FROM item_info WHERE cookie_id=? AND item_id=?`, "item-delete-cookie", "item-1").Scan(&itemDeletedAt); err != nil {
t.Fatalf("商品行未保留: %v", err)
}
if err := store.DB.QueryRowContext(ctx, `SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&ruleDeletedAt, &ruleEnabled); err != nil {
t.Fatalf("规则行未保留: %v", err)
}
if itemDeletedAt == "" || ruleDeletedAt == "" || ruleEnabled != 0 {
t.Fatalf("商品和规则未完成逻辑删除: item_deleted_at=%q rule_deleted_at=%q enabled=%d", itemDeletedAt, ruleDeletedAt, ruleEnabled)
}
}
+11 -7
View File
@@ -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 {
+24 -2
View File
@@ -29,10 +29,13 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
{"orders", "system_shipped"},
{"orders", "receiver_city"},
{"orders", "version"},
{"orders", "deleted_at"},
{"cards", "image_url"},
{"cards", "delay_seconds"},
{"keywords", "item_id"},
{"item_info", "multi_quantity_delivery"},
{"item_info", "deleted_at"},
{"automation_rules", "deleted_at"},
{"default_replies", "reply_once"},
{"default_reply_records", "status"},
{"default_reply_records", "text_sent"},
@@ -125,8 +128,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
t.Fatalf("goose dialect: %v", err)
}
goose.SetBaseFS(migrationsFS)
// 依次回滚 22 到 14,再整体升级。
for i := 0; i < 9; i++ {
// 依次回滚最新版本到 13,再整体升级。
for i := 0; i < 14; i++ {
if err := goose.Down(d, "migrations/sqlite"); err != nil {
t.Fatalf("down migration #%d: %v", i+1, err)
}
@@ -143,6 +146,20 @@ 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 columnExists(t, d, "item_info", "deleted_at") || columnExists(t, d, "automation_rules", "deleted_at") {
t.Fatal("soft-delete columns should be removed after migration 26 down")
}
if columnExists(t, d, "orders", "deleted_at") {
t.Fatal("orders.deleted_at should be removed after migration 27 down")
}
for _, table := range []string{"account_task_settings", "account_task_runs", "chat_sessions", "chat_messages"} {
if tableExists(t, d, table) {
t.Fatalf("table should be removed after migration 24 down: %s", table)
}
}
if err := goose.Up(d, "migrations/sqlite"); err != nil {
t.Fatalf("up after down: %v", err)
@@ -160,6 +177,11 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
{"default_reply_records", "status"},
{"default_reply_records", "text_sent"},
{"account_tokens", "cookie_fingerprint"},
{"item_publish_batch_rows", "category_json"},
{"account_task_settings", "auto_rate_enabled"},
{"account_task_runs", "run_key"},
{"chat_sessions", "unread_count"},
{"chat_messages", "message_key"},
} {
if !columnExists(t, d, c.table, c.col) {
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
@@ -0,0 +1,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,75 @@
-- +goose Up
CREATE TABLE account_task_settings (
cookie_id VARCHAR(191) PRIMARY KEY,
auto_rate_enabled TINYINT(1) NOT NULL DEFAULT 0,
rate_content TEXT NOT NULL,
auto_polish_enabled TINYINT(1) NOT NULL DEFAULT 0,
polish_time VARCHAR(5) NOT NULL DEFAULT '03:00',
last_rate_scan_at BIGINT NOT NULL DEFAULT 0,
last_polish_date VARCHAR(10) NOT NULL DEFAULT '',
last_polish_at BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
CONSTRAINT fk_account_task_settings_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE account_task_runs (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
run_key VARCHAR(255) NOT NULL UNIQUE,
cookie_id VARCHAR(191) NOT NULL,
task_type VARCHAR(32) NOT NULL,
target_id VARCHAR(191) NOT NULL DEFAULT '',
run_date VARCHAR(10) NOT NULL DEFAULT '',
status VARCHAR(24) NOT NULL,
success_count INT NOT NULL DEFAULT 0,
failed_count INT NOT NULL DEFAULT 0,
error_message TEXT NOT NULL,
next_retry_at BIGINT NOT NULL DEFAULT 0,
started_at BIGINT NOT NULL,
finished_at BIGINT NOT NULL DEFAULT 0,
CONSTRAINT fk_account_task_runs_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
INDEX idx_account_task_runs_account_type (cookie_id, task_type, started_at),
INDEX idx_account_task_runs_retry (status, next_retry_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE chat_sessions (
cookie_id VARCHAR(191) NOT NULL,
chat_id VARCHAR(191) NOT NULL,
buyer_id VARCHAR(191) NOT NULL DEFAULT '',
buyer_name VARCHAR(255) NOT NULL DEFAULT '',
buyer_avatar_url TEXT NOT NULL,
item_id VARCHAR(191) NOT NULL DEFAULT '',
item_title VARCHAR(500) NOT NULL DEFAULT '',
last_message TEXT NOT NULL,
last_message_at BIGINT NOT NULL DEFAULT 0,
unread_count INT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
PRIMARY KEY (cookie_id, chat_id),
CONSTRAINT fk_chat_sessions_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
INDEX idx_chat_sessions_account_recent (cookie_id, last_message_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE chat_messages (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
cookie_id VARCHAR(191) NOT NULL,
chat_id VARCHAR(191) NOT NULL,
message_key VARCHAR(255) NOT NULL,
direction VARCHAR(16) NOT NULL,
sender_id VARCHAR(191) NOT NULL DEFAULT '',
sender_name VARCHAR(255) NOT NULL DEFAULT '',
message_type VARCHAR(24) NOT NULL DEFAULT 'text',
content TEXT NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'received',
sent_at BIGINT NOT NULL,
created_at BIGINT NOT NULL,
UNIQUE KEY uq_chat_messages_account_key (cookie_id, message_key),
CONSTRAINT fk_chat_messages_session FOREIGN KEY (cookie_id, chat_id) REFERENCES chat_sessions(cookie_id, chat_id) ON DELETE CASCADE,
INDEX idx_chat_messages_conversation (cookie_id, chat_id, sent_at, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- +goose Down
DROP TABLE IF EXISTS chat_messages;
DROP TABLE IF EXISTS chat_sessions;
DROP TABLE IF EXISTS account_task_runs;
DROP TABLE IF EXISTS account_task_settings;
@@ -0,0 +1,12 @@
-- +goose Up
UPDATE chat_messages SET direction='outgoing', sender_name='我'
WHERE sender_id=cookie_id AND direction='incoming';
UPDATE chat_sessions cs SET buyer_id=COALESCE((
SELECT m.sender_id FROM chat_messages m
WHERE m.cookie_id=cs.cookie_id AND m.chat_id=cs.chat_id
AND m.direction='incoming' AND m.sender_id<>cs.cookie_id
ORDER BY m.sent_at DESC,m.id DESC LIMIT 1
), cs.buyer_id);
-- +goose Down
-- Data repair is intentionally irreversible.
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at);
CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at);
-- +goose Down
DROP INDEX idx_automation_rules_active_match ON automation_rules;
DROP INDEX idx_item_info_active ON item_info;
ALTER TABLE automation_rules DROP COLUMN deleted_at;
ALTER TABLE item_info DROP COLUMN deleted_at;
@@ -0,0 +1,7 @@
-- +goose Up
ALTER TABLE orders ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_orders_active ON orders(cookie_id, deleted_at);
-- +goose Down
DROP INDEX idx_orders_active ON orders;
ALTER TABLE orders DROP COLUMN deleted_at;
@@ -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,72 @@
-- +goose Up
CREATE TABLE account_task_settings (
cookie_id TEXT PRIMARY KEY REFERENCES cookies(id) ON DELETE CASCADE,
auto_rate_enabled INTEGER NOT NULL DEFAULT 0,
rate_content TEXT NOT NULL DEFAULT '不错的买家,交易愉快',
auto_polish_enabled INTEGER NOT NULL DEFAULT 0,
polish_time VARCHAR(5) NOT NULL DEFAULT '03:00',
last_rate_scan_at BIGINT NOT NULL DEFAULT 0,
last_polish_date VARCHAR(10) NOT NULL DEFAULT '',
last_polish_at BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL
);
CREATE TABLE account_task_runs (
id BIGSERIAL PRIMARY KEY,
run_key TEXT NOT NULL UNIQUE,
cookie_id TEXT NOT NULL REFERENCES cookies(id) ON DELETE CASCADE,
task_type VARCHAR(32) NOT NULL,
target_id TEXT NOT NULL DEFAULT '',
run_date VARCHAR(10) NOT NULL DEFAULT '',
status VARCHAR(24) NOT NULL,
success_count INTEGER NOT NULL DEFAULT 0,
failed_count INTEGER NOT NULL DEFAULT 0,
error_message TEXT NOT NULL DEFAULT '',
next_retry_at BIGINT NOT NULL DEFAULT 0,
started_at BIGINT NOT NULL,
finished_at BIGINT NOT NULL DEFAULT 0
);
CREATE INDEX idx_account_task_runs_account_type ON account_task_runs(cookie_id, task_type, started_at DESC);
CREATE INDEX idx_account_task_runs_retry ON account_task_runs(status, next_retry_at);
CREATE TABLE chat_sessions (
cookie_id TEXT NOT NULL REFERENCES cookies(id) ON DELETE CASCADE,
chat_id TEXT NOT NULL,
buyer_id TEXT NOT NULL DEFAULT '',
buyer_name TEXT NOT NULL DEFAULT '',
buyer_avatar_url TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
item_title TEXT NOT NULL DEFAULT '',
last_message TEXT NOT NULL DEFAULT '',
last_message_at BIGINT NOT NULL DEFAULT 0,
unread_count INTEGER NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
PRIMARY KEY (cookie_id, chat_id)
);
CREATE INDEX idx_chat_sessions_account_recent ON chat_sessions(cookie_id, last_message_at DESC);
CREATE TABLE chat_messages (
id BIGSERIAL PRIMARY KEY,
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
message_key TEXT NOT NULL,
direction VARCHAR(16) NOT NULL,
sender_id TEXT NOT NULL DEFAULT '',
sender_name TEXT NOT NULL DEFAULT '',
message_type VARCHAR(24) NOT NULL DEFAULT 'text',
content TEXT NOT NULL DEFAULT '',
status VARCHAR(24) NOT NULL DEFAULT 'received',
sent_at BIGINT NOT NULL,
created_at BIGINT NOT NULL,
UNIQUE (cookie_id, message_key),
FOREIGN KEY (cookie_id, chat_id) REFERENCES chat_sessions(cookie_id, chat_id) ON DELETE CASCADE
);
CREATE INDEX idx_chat_messages_conversation ON chat_messages(cookie_id, chat_id, sent_at DESC, id DESC);
-- +goose Down
DROP TABLE IF EXISTS chat_messages;
DROP TABLE IF EXISTS chat_sessions;
DROP TABLE IF EXISTS account_task_runs;
DROP TABLE IF EXISTS account_task_settings;
@@ -0,0 +1,12 @@
-- +goose Up
UPDATE chat_messages SET direction='outgoing', sender_name='我'
WHERE sender_id=cookie_id AND direction='incoming';
UPDATE chat_sessions cs SET buyer_id=COALESCE((
SELECT m.sender_id FROM chat_messages m
WHERE m.cookie_id=cs.cookie_id AND m.chat_id=cs.chat_id
AND m.direction='incoming' AND m.sender_id<>cs.cookie_id
ORDER BY m.sent_at DESC,m.id DESC LIMIT 1
), cs.buyer_id);
-- +goose Down
-- Data repair is intentionally irreversible.
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at);
CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at);
-- +goose Down
DROP INDEX IF EXISTS idx_automation_rules_active_match;
DROP INDEX IF EXISTS idx_item_info_active;
ALTER TABLE automation_rules DROP COLUMN deleted_at;
ALTER TABLE item_info DROP COLUMN deleted_at;
@@ -0,0 +1,7 @@
-- +goose Up
ALTER TABLE orders ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL;
CREATE INDEX idx_orders_active ON orders(cookie_id, deleted_at);
-- +goose Down
DROP INDEX IF EXISTS idx_orders_active;
ALTER TABLE orders DROP COLUMN deleted_at;
@@ -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,75 @@
-- +goose Up
CREATE TABLE account_task_settings (
cookie_id TEXT PRIMARY KEY,
auto_rate_enabled INTEGER NOT NULL DEFAULT 0,
rate_content TEXT NOT NULL DEFAULT '不错的买家,交易愉快',
auto_polish_enabled INTEGER NOT NULL DEFAULT 0,
polish_time TEXT NOT NULL DEFAULT '03:00',
last_rate_scan_at INTEGER NOT NULL DEFAULT 0,
last_polish_date TEXT NOT NULL DEFAULT '',
last_polish_at INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE TABLE account_task_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_key TEXT NOT NULL UNIQUE,
cookie_id TEXT NOT NULL,
task_type TEXT NOT NULL,
target_id TEXT NOT NULL DEFAULT '',
run_date TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL,
success_count INTEGER NOT NULL DEFAULT 0,
failed_count INTEGER NOT NULL DEFAULT 0,
error_message TEXT NOT NULL DEFAULT '',
next_retry_at INTEGER NOT NULL DEFAULT 0,
started_at INTEGER NOT NULL,
finished_at INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX idx_account_task_runs_account_type ON account_task_runs(cookie_id, task_type, started_at DESC);
CREATE INDEX idx_account_task_runs_retry ON account_task_runs(status, next_retry_at);
CREATE TABLE chat_sessions (
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
buyer_id TEXT NOT NULL DEFAULT '',
buyer_name TEXT NOT NULL DEFAULT '',
buyer_avatar_url TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
item_title TEXT NOT NULL DEFAULT '',
last_message TEXT NOT NULL DEFAULT '',
last_message_at INTEGER NOT NULL DEFAULT 0,
unread_count INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
PRIMARY KEY (cookie_id, chat_id),
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX idx_chat_sessions_account_recent ON chat_sessions(cookie_id, last_message_at DESC);
CREATE TABLE chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
message_key TEXT NOT NULL,
direction TEXT NOT NULL,
sender_id TEXT NOT NULL DEFAULT '',
sender_name TEXT NOT NULL DEFAULT '',
message_type TEXT NOT NULL DEFAULT 'text',
content TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'received',
sent_at INTEGER NOT NULL,
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
UNIQUE (cookie_id, message_key),
FOREIGN KEY (cookie_id, chat_id) REFERENCES chat_sessions(cookie_id, chat_id) ON DELETE CASCADE
);
CREATE INDEX idx_chat_messages_conversation ON chat_messages(cookie_id, chat_id, sent_at DESC, id DESC);
-- +goose Down
DROP TABLE IF EXISTS chat_messages;
DROP TABLE IF EXISTS chat_sessions;
DROP TABLE IF EXISTS account_task_runs;
DROP TABLE IF EXISTS account_task_settings;
@@ -0,0 +1,12 @@
-- +goose Up
UPDATE chat_messages SET direction='outgoing', sender_name='我'
WHERE sender_id=cookie_id AND direction='incoming';
UPDATE chat_sessions SET buyer_id=COALESCE((
SELECT m.sender_id FROM chat_messages m
WHERE m.cookie_id=chat_sessions.cookie_id AND m.chat_id=chat_sessions.chat_id
AND m.direction='incoming' AND m.sender_id<>chat_sessions.cookie_id
ORDER BY m.sent_at DESC,m.id DESC LIMIT 1
), buyer_id);
-- +goose Down
-- Data repair is intentionally irreversible.
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more