Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
542241d241 | ||
|
|
2df324647a | ||
|
|
94f4e070f6 | ||
|
|
6032dfed0f | ||
|
|
80baba46ff | ||
|
|
b7444e8090 | ||
|
|
fed5d582e7 | ||
|
|
0bafa50dbf | ||
|
|
3aabc3e8e4 | ||
|
|
1ac6912c7b | ||
|
|
d4e9717570 | ||
|
|
bfa72fd9b7 | ||
|
|
9cb50a229c | ||
|
|
13b57891fb | ||
|
|
8c5c305221 | ||
|
|
137a08489d | ||
|
|
07fea7d1e6 | ||
|
|
761d57f9bf | ||
|
|
3d715e916b | ||
|
|
07e91afc22 | ||
|
|
733a536031 | ||
|
|
c21a3a33dc | ||
|
|
86d659cf40 | ||
|
|
f0accce14a | ||
|
|
430fbc0767 | ||
|
|
bac5aa0c4f | ||
|
|
07b5be626b | ||
|
|
a99ea5c20d | ||
|
|
1204655170 | ||
|
|
526ac44453 | ||
|
|
cf76b8898b | ||
|
|
9adc77df73 | ||
|
|
4fb857da1e | ||
|
|
182cc75e63 | ||
|
|
450a62c924 | ||
|
|
fe3f715cdc | ||
|
|
4d1f58c5ec | ||
|
|
0de1ec7635 | ||
|
|
67d7214930 | ||
|
|
d7abbfb2b6 | ||
|
|
ad224bf4e9 | ||
|
|
474f9c4b65 | ||
|
|
798e3f3221 | ||
|
|
f13950f482 |
No files matched your search
@@ -0,0 +1 @@
|
||||
|
||||
@@ -14,3 +14,6 @@ init-admin
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
cover.out
|
||||
!/.docker/
|
||||
!/.docker/playwright-runtime/
|
||||
!/.docker/playwright-runtime/**
|
||||
@@ -13,7 +13,7 @@ DATABASE_URL=postgres://xianyu:请替换为URL编码后的数据库密码@postgr
|
||||
XIANYU_IMAGE=ghcr.io/christ9038/ydisks-xianyu-helper:latest
|
||||
XIANYU_DATA_KEY=请替换为稳定且足够长的随机密钥
|
||||
XIANYU_BIND_ADDRESS=0.0.0.0
|
||||
XIANYU_HTTP_PORT=8080
|
||||
XIANYU_HTTP_PORT=59188
|
||||
XIANYU_UPLOAD_DIR=/app/data/uploads
|
||||
TZ=Asia/Shanghai
|
||||
LOG_LEVEL=info
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
name: 构建桌面端安装包
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- codex/desktop-packaging
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: desktop-cd-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
APP_VERSION: 0.0.0-${{ github.run_number }}
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
name: Linux 安装包 (${{ matrix.arch }})
|
||||
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/codex/desktop-packaging'
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
runner: ubuntu-24.04
|
||||
playwright_platform: ubuntu24.04-x64
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
playwright_platform: ubuntu24.04-arm64
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 配置 Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: 配置 Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: 构建嵌入式前端
|
||||
run: npm ci --prefix frontend && npm run build --prefix frontend
|
||||
|
||||
- name: 编译 Linux 二进制
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 0
|
||||
run: |
|
||||
package_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}"
|
||||
mkdir -p "$package_dir"
|
||||
go build -trimpath -ldflags='-s -w' -o "$package_dir/xianyu-server" ./cmd/server
|
||||
go build -trimpath -ldflags='-s -w' -o "$package_dir/browser-install" ./cmd/browser-install
|
||||
|
||||
- name: 缓存 Linux Chromium runtime
|
||||
id: cache-linux-playwright
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}/playwright-runtime
|
||||
key: ydisks-playwright-runtime-v6-linux-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum') }}
|
||||
|
||||
- name: 在原生架构 runner 预下载 Linux Chromium runtime
|
||||
if: steps.cache-linux-playwright.outputs.cache-hit != 'true'
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE: ${{ matrix.playwright_platform }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
case "$(uname -m)" in
|
||||
x86_64) runner_arch=amd64 ;;
|
||||
aarch64|arm64) runner_arch=arm64 ;;
|
||||
*) echo "不支持的 runner 架构:$(uname -m)" >&2; exit 1 ;;
|
||||
esac
|
||||
if [ "$runner_arch" != "$GOARCH" ]; then
|
||||
echo "runner 架构 $runner_arch 与目标架构 $GOARCH 不一致,拒绝使用模拟器构建。" >&2
|
||||
exit 1
|
||||
fi
|
||||
package_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}"
|
||||
runtime_dir="$package_dir/playwright-runtime/$GOARCH"
|
||||
mkdir -p "$runtime_dir/playwright-driver" "$runtime_dir/playwright-browsers"
|
||||
"$package_dir/browser-install" \
|
||||
-driver-dir "$PWD/$runtime_dir/playwright-driver" \
|
||||
-browser-dir "$PWD/$runtime_dir/playwright-browsers"
|
||||
|
||||
- name: 校验 Linux Chromium runtime 架构
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
runtime_dir="dist/ydisks-xianyu-helper-linux-${GOARCH}/playwright-runtime/${GOARCH}"
|
||||
node_path="$runtime_dir/playwright-driver/node"
|
||||
test -x "$node_path"
|
||||
"$node_path" --version
|
||||
node_type="$(file -b "$node_path")"
|
||||
case "$GOARCH:$node_type" in
|
||||
amd64:*x86-64*) ;;
|
||||
arm64:*aarch64*|arm64:*ARM64*) ;;
|
||||
*) echo "Playwright driver 架构错误:$node_type" >&2; exit 1 ;;
|
||||
esac
|
||||
chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \
|
||||
\( -name chrome -o -name headless_shell -o -name chrome-headless-shell \) -perm -111 -print -quit)"
|
||||
test -n "$chromium_path"
|
||||
chromium_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
||||
headless_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
|
||||
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
|
||||
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
|
||||
chromium_type="$(file -b "$chromium_path")"
|
||||
case "$GOARCH:$chromium_type" in
|
||||
amd64:*x86-64*) ;;
|
||||
arm64:*aarch64*|arm64:*ARM64*) ;;
|
||||
*) echo "Chromium 架构错误:$chromium_type" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
- name: 组装 Linux 安装目录
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
package_dir="dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}"
|
||||
cp icon/linux/icon.png "$package_dir/icon.png"
|
||||
cp packaging/linux/install.sh packaging/linux/uninstall.sh packaging/linux/ydisks-xianyu-helper.service "$package_dir/"
|
||||
chmod +x "$package_dir/install.sh" "$package_dir/uninstall.sh"
|
||||
tar -C dist -czf "dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}-${APP_VERSION}.tar.gz" "$(basename "$package_dir")"
|
||||
|
||||
- name: 上传 Linux 安装包
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ydisks-xianyu-helper-linux-${{ matrix.arch }}-${{ env.APP_VERSION }}
|
||||
path: dist/ydisks-xianyu-helper-linux-${{ matrix.arch }}-${{ env.APP_VERSION }}.tar.gz
|
||||
if-no-files-found: error
|
||||
|
||||
windows:
|
||||
name: Windows 安装包
|
||||
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/codex/desktop-packaging'
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 配置 Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: 配置 Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: 构建嵌入式前端
|
||||
shell: pwsh
|
||||
run: npm ci --prefix frontend; npm run build --prefix frontend
|
||||
|
||||
- name: 验证 Windows 托盘逻辑与安装脚本
|
||||
shell: pwsh
|
||||
run: |
|
||||
go test ./cmd/tray
|
||||
$tokens = $null
|
||||
$parseErrors = $null
|
||||
[void][System.Management.Automation.Language.Parser]::ParseFile(
|
||||
(Resolve-Path 'packaging/windows/service-control.ps1'),
|
||||
[ref]$tokens,
|
||||
[ref]$parseErrors
|
||||
)
|
||||
if ($parseErrors.Count -gt 0) {
|
||||
$parseErrors | ForEach-Object { Write-Error $_.Message }
|
||||
throw 'Windows 服务安装脚本语法检查失败'
|
||||
}
|
||||
|
||||
- name: 编译 Windows 桌面程序
|
||||
shell: pwsh
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path dist/windows | Out-Null
|
||||
go build -trimpath -ldflags "-s -w" -o dist/windows/xianyu-server.exe ./cmd/server
|
||||
go build -trimpath -ldflags "-s -w" -o dist/windows/browser-install.exe ./cmd/browser-install
|
||||
go build -trimpath -ldflags "-s -w -H=windowsgui" -o dist/windows/xianyu-tray.exe ./cmd/tray
|
||||
|
||||
- name: 缓存 Windows Chromium runtime
|
||||
id: cache-windows-playwright
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: dist/windows/playwright-runtime/amd64
|
||||
key: ydisks-playwright-runtime-v6-windows-amd64-${{ hashFiles('go.mod', 'go.sum') }}
|
||||
|
||||
- name: 预下载 Windows Chromium runtime
|
||||
if: steps.cache-windows-playwright.outputs.cache-hit != 'true'
|
||||
shell: pwsh
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path dist/windows/playwright-runtime/amd64/playwright-driver | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path dist/windows/playwright-runtime/amd64/playwright-browsers | Out-Null
|
||||
& dist/windows/browser-install.exe `
|
||||
-driver-dir "$PWD/dist/windows/playwright-runtime/amd64/playwright-driver" `
|
||||
-browser-dir "$PWD/dist/windows/playwright-runtime/amd64/playwright-browsers"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows Playwright runtime 下载失败' }
|
||||
|
||||
- name: 校验 Windows Chromium runtime
|
||||
shell: pwsh
|
||||
run: |
|
||||
$runtimeRoot = Resolve-Path 'dist/windows/playwright-runtime/amd64'
|
||||
$driverNode = Join-Path $runtimeRoot 'playwright-driver/node.exe'
|
||||
$driverCli = Join-Path $runtimeRoot 'playwright-driver/package/cli.js'
|
||||
if (-not (Test-Path -LiteralPath $driverNode -PathType Leaf)) { throw 'Windows Playwright driver 缺少 node.exe' }
|
||||
if (-not (Test-Path -LiteralPath $driverCli -PathType Leaf)) { throw 'Windows Playwright driver 缺少 package/cli.js' }
|
||||
$browserSpec = Get-Content -Raw -LiteralPath (Join-Path $runtimeRoot 'playwright-driver/package/browsers.json') | ConvertFrom-Json
|
||||
$chromiumRevision = ($browserSpec.browsers | Where-Object name -eq 'chromium').revision
|
||||
$headlessRevision = ($browserSpec.browsers | Where-Object name -eq 'chromium-headless-shell').revision
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $runtimeRoot "playwright-browsers/chromium-$chromiumRevision") -PathType Container)) { throw 'Windows Chromium revision 与 driver 不匹配' }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $runtimeRoot "playwright-browsers/chromium_headless_shell-$headlessRevision") -PathType Container)) { throw 'Windows headless shell revision 与 driver 不匹配' }
|
||||
$chromium = Get-ChildItem -LiteralPath (Join-Path $runtimeRoot 'playwright-browsers') -Recurse -File |
|
||||
Where-Object { $_.Name -in @('chrome.exe', 'headless_shell.exe', 'chrome-headless-shell.exe') } |
|
||||
Select-Object -First 1
|
||||
if ($null -eq $chromium) { throw 'Windows Chromium runtime 缺少 Chromium 可执行文件' }
|
||||
|
||||
- name: 导入 Windows 签名证书
|
||||
shell: pwsh
|
||||
env:
|
||||
WINDOWS_SIGNING_PFX_BASE64: ${{ secrets.WINDOWS_SIGNING_PFX_BASE64 }}
|
||||
WINDOWS_SIGNING_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }}
|
||||
WINDOWS_SIGNING_IDENTITY: ${{ secrets.WINDOWS_SIGNING_IDENTITY }}
|
||||
run: |
|
||||
$pfxPath = Join-Path $env:RUNNER_TEMP 'ydisks-windows-signing.pfx'
|
||||
[IO.File]::WriteAllBytes($pfxPath, [Convert]::FromBase64String($env:WINDOWS_SIGNING_PFX_BASE64))
|
||||
if (-not (Test-Path -LiteralPath $pfxPath -PathType Leaf)) { throw 'Windows PFX 文件写入失败' }
|
||||
"WINDOWS_SIGNING_PFX_PATH=$pfxPath" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
|
||||
|
||||
- name: 签名 Windows 桌面程序
|
||||
shell: pwsh
|
||||
env:
|
||||
WINDOWS_SIGNING_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }}
|
||||
WINDOWS_SIGNING_IDENTITY: ${{ secrets.WINDOWS_SIGNING_IDENTITY }}
|
||||
run: |
|
||||
& packaging/windows/sign.ps1 `
|
||||
-PfxPath $env:WINDOWS_SIGNING_PFX_PATH `
|
||||
-Files 'dist/windows/xianyu-server.exe','dist/windows/xianyu-tray.exe'
|
||||
|
||||
- name: 安装 Inno Setup
|
||||
shell: pwsh
|
||||
run: choco install innosetup --no-progress --yes
|
||||
|
||||
- name: 构建 Windows 安装器
|
||||
shell: pwsh
|
||||
env:
|
||||
APP_VERSION: ${{ env.APP_VERSION }}
|
||||
run: |
|
||||
& 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe' /Qp /O"dist\windows" packaging\windows\installer.iss
|
||||
$installer = Get-ChildItem -Path dist/windows -Filter 'Ydisks-Xianyu-Helper-Setup.exe' -Recurse | Select-Object -First 1
|
||||
if ($null -eq $installer) { throw 'Inno Setup 未生成安装器' }
|
||||
$target = Join-Path (Resolve-Path dist/windows) 'Ydisks-Xianyu-Helper-Setup.exe'
|
||||
if ($installer.FullName -ne $target) { Copy-Item $installer.FullName $target -Force }
|
||||
|
||||
- name: 签名 Windows 安装器
|
||||
shell: pwsh
|
||||
env:
|
||||
WINDOWS_SIGNING_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }}
|
||||
WINDOWS_SIGNING_IDENTITY: ${{ secrets.WINDOWS_SIGNING_IDENTITY }}
|
||||
run: |
|
||||
& packaging/windows/sign.ps1 `
|
||||
-PfxPath $env:WINDOWS_SIGNING_PFX_PATH `
|
||||
-Files 'dist/windows/Ydisks-Xianyu-Helper-Setup.exe'
|
||||
|
||||
- name: 打包 Windows 二进制归档
|
||||
shell: pwsh
|
||||
env:
|
||||
APP_VERSION: ${{ env.APP_VERSION }}
|
||||
run: |
|
||||
Compress-Archive -Path dist/windows/xianyu-server.exe,dist/windows/xianyu-tray.exe,dist/windows/playwright-runtime -DestinationPath "dist/windows/Ydisks-Xianyu-Helper-${env:APP_VERSION}-binaries.zip"
|
||||
|
||||
- name: 上传 Windows 安装包
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ydisks-xianyu-helper-windows-${{ env.APP_VERSION }}
|
||||
path: |
|
||||
dist/windows/Ydisks-Xianyu-Helper-Setup.exe
|
||||
dist/windows/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-binaries.zip
|
||||
if-no-files-found: error
|
||||
|
||||
macos:
|
||||
name: macOS 安装包
|
||||
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/codex/desktop-packaging'
|
||||
runs-on: macos-14
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 配置 Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: 配置 Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: 构建嵌入式前端
|
||||
run: npm ci --prefix frontend && npm run build --prefix frontend
|
||||
|
||||
- name: 验证 macOS 托盘逻辑
|
||||
run: go test ./cmd/tray
|
||||
|
||||
- name: 编译 macOS 桌面程序
|
||||
run: |
|
||||
mkdir -p dist/macos/arm64 dist/macos/amd64
|
||||
for arch in arm64 amd64; do
|
||||
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/xianyu-server" ./cmd/server
|
||||
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/browser-install" ./cmd/browser-install
|
||||
GOOS=darwin GOARCH="$arch" CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' -o "dist/macos/$arch/xianyu-tray" ./cmd/tray
|
||||
done
|
||||
|
||||
- name: 缓存 macOS Chromium runtime
|
||||
id: cache-macos-playwright
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: |
|
||||
dist/macos/playwright-runtime/arm64
|
||||
dist/macos/playwright-runtime/amd64
|
||||
key: ydisks-playwright-runtime-v6-macos-universal-${{ hashFiles('go.mod', 'go.sum') }}
|
||||
|
||||
- name: 预下载 macOS Chromium runtime
|
||||
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
mkdir -p dist/macos/playwright-runtime/arm64/playwright-driver
|
||||
mkdir -p dist/macos/playwright-runtime/arm64/playwright-browsers
|
||||
mkdir -p dist/macos/playwright-runtime/amd64/playwright-driver
|
||||
mkdir -p dist/macos/playwright-runtime/amd64/playwright-browsers
|
||||
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=mac14-arm64 \
|
||||
dist/macos/arm64/browser-install \
|
||||
-driver-dir "$PWD/dist/macos/playwright-runtime/arm64/playwright-driver" \
|
||||
-browser-dir "$PWD/dist/macos/playwright-runtime/arm64/playwright-browsers"
|
||||
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=mac14 \
|
||||
arch -x86_64 dist/macos/amd64/browser-install \
|
||||
-driver-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-driver" \
|
||||
-browser-dir "$PWD/dist/macos/playwright-runtime/amd64/playwright-browsers"
|
||||
|
||||
- name: 保存 macOS Chromium runtime 缓存
|
||||
if: steps.cache-macos-playwright.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: |
|
||||
dist/macos/playwright-runtime/arm64
|
||||
dist/macos/playwright-runtime/amd64
|
||||
key: ${{ steps.cache-macos-playwright.outputs.cache-primary-key }}
|
||||
|
||||
- name: 导入 macOS 签名证书
|
||||
env:
|
||||
MACOS_SIGNING_P12_BASE64: ${{ secrets.MACOS_SIGNING_P12_BASE64 }}
|
||||
MACOS_INSTALLER_SIGNING_P12_BASE64: ${{ secrets.MACOS_INSTALLER_SIGNING_P12_BASE64 }}
|
||||
MACOS_SIGNING_P12_PASSWORD: ${{ secrets.MACOS_SIGNING_P12_PASSWORD }}
|
||||
MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
|
||||
MACOS_INSTALLER_SIGNING_IDENTITY: ${{ secrets.MACOS_INSTALLER_SIGNING_IDENTITY }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
keychain_path="$RUNNER_TEMP/ydisks-signing.keychain-db"
|
||||
keychain_password="$(uuidgen)"
|
||||
app_p12_path="$RUNNER_TEMP/ydisks-signing-app.p12"
|
||||
app_cert_path="$RUNNER_TEMP/ydisks-signing-app.pem"
|
||||
installer_p12_path="$RUNNER_TEMP/ydisks-signing-installer.p12"
|
||||
installer_cert_path="$RUNNER_TEMP/ydisks-signing-installer.pem"
|
||||
printf '%s' "$MACOS_SIGNING_P12_BASE64" | base64 --decode > "$app_p12_path"
|
||||
printf '%s' "$MACOS_INSTALLER_SIGNING_P12_BASE64" | base64 --decode > "$installer_p12_path"
|
||||
security create-keychain -p "$keychain_password" "$keychain_path"
|
||||
security set-keychain-settings -lut 21600 "$keychain_path"
|
||||
security unlock-keychain -p "$keychain_password" "$keychain_path"
|
||||
# 临时 CI 钥匙串使用 -A 授权签名工具,避免 set-key-partition-list 触发交互确认。
|
||||
security import "$app_p12_path" -k "$keychain_path" -P "$MACOS_SIGNING_P12_PASSWORD" -A
|
||||
security import "$installer_p12_path" -k "$keychain_path" -P "$MACOS_SIGNING_P12_PASSWORD" -A
|
||||
security find-certificate -c "$MACOS_SIGNING_IDENTITY" -p "$keychain_path" > "$app_cert_path"
|
||||
security find-certificate -c "$MACOS_INSTALLER_SIGNING_IDENTITY" -p "$keychain_path" > "$installer_cert_path"
|
||||
# GitHub macOS hosted runner 提供免密码 sudo;只修改 admin Trust Settings,避免弹认证对话框。
|
||||
# 不传 -k,避免 sudo 以 root 身份把同一张证书重复写入临时钥匙串,破坏私钥匹配。
|
||||
sudo -n security add-trusted-cert -d -r trustRoot -p codeSign "$app_cert_path"
|
||||
sudo -n security add-trusted-cert -d -r trustRoot -p basic "$installer_cert_path"
|
||||
security list-keychains -d user -s "$keychain_path"
|
||||
security unlock-keychain -p "$keychain_password" "$keychain_path"
|
||||
echo "MACOS_SIGNING_KEYCHAIN=$keychain_path" >> "$GITHUB_ENV"
|
||||
|
||||
- name: 构建 macOS arm64 与 amd64 安装包
|
||||
env:
|
||||
MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }}
|
||||
MACOS_INSTALLER_SIGNING_IDENTITY: ${{ secrets.MACOS_INSTALLER_SIGNING_IDENTITY }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
chmod +x packaging/macos/build-pkg.sh
|
||||
for arch in arm64 amd64; do
|
||||
packaging/macos/build-pkg.sh "$APP_VERSION" "$PWD/dist/macos" "$arch"
|
||||
done
|
||||
|
||||
- name: 上传 macOS arm64 安装包
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ydisks-xianyu-helper-macos-arm64-${{ env.APP_VERSION }}
|
||||
path: dist/macos/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-arm64.pkg
|
||||
if-no-files-found: error
|
||||
|
||||
- name: 上传 macOS amd64 安装包
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ydisks-xianyu-helper-macos-amd64-${{ env.APP_VERSION }}
|
||||
path: dist/macos/Ydisks-Xianyu-Helper-${{ env.APP_VERSION }}-amd64.pkg
|
||||
if-no-files-found: error
|
||||
@@ -4,6 +4,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- codex/desktop-packaging
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -15,21 +16,149 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: 发布多架构镜像
|
||||
runs-on: ubuntu-latest
|
||||
build:
|
||||
name: 构建镜像 (${{ matrix.arch }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: amd64
|
||||
runner: ubuntu-24.04
|
||||
platform: linux/amd64
|
||||
playwright_platform: debian13-x64
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
platform: linux/arm64
|
||||
playwright_platform: debian13-arm64
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 配置 QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: 校验 runner 原生架构
|
||||
shell: bash
|
||||
env:
|
||||
EXPECTED_ARCH: ${{ matrix.arch }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
case "$(uname -m)" in
|
||||
x86_64) actual_arch=amd64 ;;
|
||||
aarch64|arm64) actual_arch=arm64 ;;
|
||||
*) echo "不支持的 runner 架构:$(uname -m)" >&2; exit 1 ;;
|
||||
esac
|
||||
if [ "$actual_arch" != "$EXPECTED_ARCH" ]; then
|
||||
echo "runner 架构 $actual_arch 与目标架构 $EXPECTED_ARCH 不一致,拒绝使用模拟器构建。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 配置 Go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: 缓存 Docker Chromium runtime
|
||||
id: cache-docker-playwright
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: .docker/playwright-runtime/${{ matrix.arch }}
|
||||
key: ydisks-playwright-runtime-v6-docker-${{ matrix.arch }}-${{ hashFiles('go.mod', 'go.sum') }}
|
||||
|
||||
- name: 准备 Docker Chromium runtime
|
||||
if: steps.cache-docker-playwright.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE: ${{ matrix.playwright_platform }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
mkdir -p ".docker/playwright-runtime/$GOARCH/playwright-driver" ".docker/playwright-runtime/$GOARCH/playwright-browsers"
|
||||
GOOS=linux GOARCH="$GOARCH" CGO_ENABLED=0 go build \
|
||||
-trimpath -ldflags='-s -w' \
|
||||
-o "$RUNNER_TEMP/browser-install" ./cmd/browser-install
|
||||
"$RUNNER_TEMP/browser-install" \
|
||||
-driver-dir "$PWD/.docker/playwright-runtime/$GOARCH/playwright-driver" \
|
||||
-browser-dir "$PWD/.docker/playwright-runtime/$GOARCH/playwright-browsers"
|
||||
|
||||
- name: 校验 Docker Chromium runtime
|
||||
shell: bash
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
runtime_dir=".docker/playwright-runtime/$GOARCH"
|
||||
test -x "$runtime_dir/playwright-driver/node"
|
||||
test -f "$runtime_dir/playwright-driver/package/cli.js"
|
||||
chromium_path="$(find "$runtime_dir/playwright-browsers" -type f \
|
||||
\( -name chrome -o -name headless_shell -o -name chrome-headless-shell \) -perm -111 -print -quit)"
|
||||
test -n "$chromium_path"
|
||||
chromium_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium").revision)')"
|
||||
headless_revision="$(RUNTIME_SPEC="$runtime_dir/playwright-driver/package/browsers.json" node -e 'const b=require(process.env.RUNTIME_SPEC).browsers; console.log(b.find(x=>x.name==="chromium-headless-shell").revision)')"
|
||||
test -d "$runtime_dir/playwright-browsers/chromium-$chromium_revision"
|
||||
test -d "$runtime_dir/playwright-browsers/chromium_headless_shell-$headless_revision"
|
||||
|
||||
- name: 配置 Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: 登录 GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
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: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.debian13
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,name=${{ steps.image.outputs.name }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=gha,scope=ydisks-docker-${{ matrix.arch }}
|
||||
cache-to: type=gha,mode=max,scope=ydisks-docker-${{ matrix.arch }}
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
|
||||
- name: 保存镜像摘要
|
||||
shell: bash
|
||||
env:
|
||||
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
mkdir -p dist/digests
|
||||
touch "dist/digests/${IMAGE_DIGEST#sha256:}"
|
||||
|
||||
- name: 上传镜像摘要
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ydisks-docker-digest-${{ matrix.arch }}
|
||||
path: dist/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
publish:
|
||||
name: 合并多架构镜像
|
||||
needs: build
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: 配置 Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: 下载镜像摘要
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: ydisks-docker-digest-*
|
||||
path: dist/digests
|
||||
merge-multiple: true
|
||||
|
||||
- name: 登录 GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
@@ -42,26 +171,46 @@ jobs:
|
||||
|
||||
- name: 生成镜像标签
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v6
|
||||
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=main,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
type=raw,value=desktop-packaging,enable=${{ github.ref == 'refs/heads/codex/desktop-packaging' }}
|
||||
type=raw,value=alpha,enable=${{ github.ref == 'refs/heads/codex/desktop-packaging' }}
|
||||
|
||||
- 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
|
||||
- name: 创建并推送多架构 manifest
|
||||
shell: bash
|
||||
env:
|
||||
IMAGE_NAME: ${{ steps.image.outputs.name }}
|
||||
IMAGE_TAGS: ${{ steps.meta.outputs.tags }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
mapfile -t digest_files < <(find dist/digests -maxdepth 1 -type f -print | sort)
|
||||
if [ "${#digest_files[@]}" -ne 2 ]; then
|
||||
echo "预期 2 个镜像摘要,实际 ${#digest_files[@]} 个。" >&2
|
||||
exit 1
|
||||
fi
|
||||
digest_args=()
|
||||
for digest_file in "${digest_files[@]}"; do
|
||||
digest_args+=("$IMAGE_NAME@sha256:$(basename "$digest_file")")
|
||||
done
|
||||
tag_args=()
|
||||
while IFS= read -r tag; do
|
||||
[ -n "$tag" ] && tag_args+=(--tag "$tag")
|
||||
done <<< "$IMAGE_TAGS"
|
||||
docker buildx imagetools create "${tag_args[@]}" "${digest_args[@]}"
|
||||
|
||||
- name: 检查多架构 manifest
|
||||
shell: bash
|
||||
env:
|
||||
IMAGE_TAGS: ${{ steps.meta.outputs.tags }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
first_tag="$(printf '%s\n' "$IMAGE_TAGS" | sed -n '/./{p;q;}')"
|
||||
test -n "$first_tag"
|
||||
docker buildx imagetools inspect "$first_tag"
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出主分支文档
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
The active application contains:
|
||||
|
||||
- `cmd/server/` — server entrypoint, administrator bootstrap (`-init-admin`), and HTTP server.
|
||||
- `cmd/server/` — server entrypoint, administrator bootstrap (`/initialize` and `-init-admin`), and HTTP server.
|
||||
- `cmd/init-admin/` — interactive administrator initialization CLI.
|
||||
- `cmd/dbverify/` — migration + core CRUD verification tool across SQLite/MySQL/Postgres.
|
||||
- `internal/server/` — chi HTTP API and SPA serving.
|
||||
@@ -34,14 +34,18 @@ make frontend # build frontend into internal/webui/static
|
||||
Run the server (SQLite by default; MySQL/Postgres via `-db-url` or `DATABASE_URL`):
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
DATABASE_URL="mysql://user:pass@tcp(host:3306)/db" go run ./cmd/server -addr :8080
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
DATABASE_URL="mysql://user:pass@tcp(host:3306)/db" go run ./cmd/server -addr :59188
|
||||
```
|
||||
|
||||
On a new database, open the management page after starting the server. The first-run page accepts
|
||||
and confirms an administrator password, creates the `admin` user, and signs the user in automatically.
|
||||
The CLI bootstrap remains available for headless or operational environments.
|
||||
|
||||
Disable browser automation when Chromium is unavailable:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser
|
||||
```
|
||||
|
||||
Initialize or reset the administrator:
|
||||
@@ -85,7 +89,85 @@ Run the frontend development server:
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Vite proxies backend routes to `localhost:8080`. Production builds are written to `internal/webui/static/` and embedded by the Go server.
|
||||
Vite proxies backend routes to `localhost:59188`. Production builds are written to `internal/webui/static/` and embedded by the Go server.
|
||||
|
||||
## Desktop packaging and service behavior
|
||||
|
||||
The application defaults to port `59188`; commands using `-addr :59188` listen on all interfaces. Desktop
|
||||
packages explicitly bind the server to `127.0.0.1:59188` and keep the server and tray as separate processes:
|
||||
|
||||
- Windows installs the `YdisksXianyuHelper` Windows Service and starts `xianyu-tray.exe` for the current
|
||||
user. The installer grants the interactive user only service status/start/stop rights, so tray service
|
||||
actions do not launch UAC prompts after installation. Service configuration and deletion remain admin-only.
|
||||
- macOS registers `com.ydisks.xianyu-helper.server` and `com.ydisks.xianyu-helper.tray` LaunchAgents.
|
||||
The app is `/Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app`, and the tray executable is named
|
||||
`Ydisks闲鱼助手` with `LSUIElement=true` so it does not appear in the Dock.
|
||||
- Linux packages are architecture-specific tar archives. `install.sh` must run as root on a native matching
|
||||
architecture, installs `ydisks-xianyu-helper.service`, and keeps data in `/var/lib/ydisks-xianyu-helper`.
|
||||
|
||||
All desktop packages contain the matching Playwright driver, Chromium and headless shell. Do not add a
|
||||
Debian Chromium package or download a second browser during installation. The Docker final image uses
|
||||
`node:latest`, copies the cached runtime prepared by CI, and does not run `apt-get update`. The desktop CI workflow
|
||||
runs on `main` and `codex/desktop-packaging`; Linux amd64 and arm64 jobs use native GitHub-hosted runners and
|
||||
must not use QEMU or cross-architecture emulation. Docker publishing also builds each architecture on its native
|
||||
runner and publishes `main` and `latest` from `main`, `desktop-packaging` and `alpha` from
|
||||
`codex/desktop-packaging`.
|
||||
|
||||
The tray state machine is shared by Windows and macOS: it serializes actions, shows transition states,
|
||||
waits for a healthy `/health` response after start/restart, waits for the endpoint to become unreachable
|
||||
after stop, and stops the server before exiting. The tray also provides an “Open log directory” action.
|
||||
|
||||
Desktop first-run initialization is done in the web UI at `http://127.0.0.1:59188`; users enter and confirm
|
||||
the initial administrator password. `-init-admin` remains an operational/headless fallback, while Docker
|
||||
Compose uses `XIANYU_ADMIN_PASSWORD` for non-interactive initialization.
|
||||
|
||||
## macOS 本地安装包构建
|
||||
|
||||
macOS 安装包必须通过 `packaging/macos/build-pkg.sh` 构建,禁止手工复制 Chromium、Playwright
|
||||
driver 或 headless shell 到 `dist`。打包脚本会检查目标架构的 runtime;runtime 不完整时自动调用
|
||||
`packaging/macos/prepare-runtime.sh`,从本机 Playwright 缓存整理出与 driver 匹配的 Chromium
|
||||
和 Chromium headless shell。
|
||||
|
||||
本机 arm64 打包流程:
|
||||
|
||||
```bash
|
||||
npm ci --prefix frontend
|
||||
npm run build --prefix frontend
|
||||
mkdir -p dist/macos/arm64
|
||||
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-server ./cmd/server
|
||||
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/browser-install ./cmd/browser-install
|
||||
go build -trimpath -ldflags='-s -w' -o dist/macos/arm64/xianyu-tray ./cmd/tray
|
||||
packaging/macos/build-pkg.sh 0.0.0-local "$PWD/dist/macos" arm64
|
||||
```
|
||||
|
||||
`prepare-runtime.sh` 默认读取:
|
||||
|
||||
- `~/Library/Caches/ms-playwright-go`:Playwright Go driver
|
||||
- `~/Library/Caches/ms-playwright`:Chromium 与 `chromium_headless_shell`
|
||||
|
||||
如果本机缓存尚未准备好,先运行编译出的 `browser-install`;不要只复制
|
||||
`chromium-<revision>`,服务启动还需要同版本的 `chromium_headless_shell-<revision>`。打包前必须确认
|
||||
服务能使用包内 runtime 启动并访问健康检查;可用临时端口验证:
|
||||
|
||||
```bash
|
||||
runtime_app="$PWD/dist/macos/pkgroot-arm64/Applications/Ydisks闲鱼助手/Ydisks闲鱼助手.app"
|
||||
mkdir -p /tmp/ydisks-local-data
|
||||
"$runtime_app/Contents/Helpers/xianyu-server" \
|
||||
-addr 127.0.0.1:59189 \
|
||||
-workdir /tmp/ydisks-local-data \
|
||||
-playwright-runtime-root "$runtime_app/Contents/Resources/playwright-runtime"
|
||||
curl -fsS http://127.0.0.1:59189/health
|
||||
```
|
||||
|
||||
本地没有签名身份时可以生成未签名 pkg,但必须明确告知未签名状态;CI 使用固定签名 Secrets 生成可分发包。
|
||||
|
||||
## CI desktop package rules
|
||||
|
||||
Do not manually assemble desktop packages in CI. The desktop workflow must build the embedded frontend,
|
||||
compile the platform binaries, restore or populate the architecture-specific Playwright runtime cache,
|
||||
assemble the package with the platform packaging script, and run the package-specific signing step.
|
||||
Windows uses `packaging/windows/installer.iss`; macOS uses `packaging/macos/build-pkg.sh`; Linux archives
|
||||
the directory containing `install.sh`, `uninstall.sh`, the systemd unit, binaries and matching runtime.
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
@@ -1,21 +1,12 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM --platform=$BUILDPLATFORM node:22-trixie AS frontend
|
||||
FROM --platform=$BUILDPLATFORM node:latest AS frontend
|
||||
WORKDIR /src/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM --platform=$BUILDPLATFORM node:22-trixie AS playwright-driver
|
||||
RUN npm install -g playwright@1.57.0 \
|
||||
&& mkdir -p /ms-playwright-go/package \
|
||||
&& cp -a /usr/local/lib/node_modules/playwright/. /ms-playwright-go/package/ \
|
||||
&& if [ -d /usr/local/lib/node_modules/playwright-core ]; then \
|
||||
mkdir -p /ms-playwright-go/package/node_modules \
|
||||
&& cp -a /usr/local/lib/node_modules/playwright-core /ms-playwright-go/package/node_modules/playwright-core; \
|
||||
fi
|
||||
|
||||
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS backend
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
@@ -28,28 +19,63 @@ RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldfl
|
||||
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
|
||||
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
|
||||
|
||||
FROM debian:13-slim AS runtime
|
||||
# 本地 Docker 构建没有主机 runtime 缓存时使用此工具下载一次;CI 会优先复制缓存,
|
||||
# 不会走这个兜底路径。
|
||||
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS browser-install-builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY cmd/browser-install ./cmd/browser-install
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/browser-install-host ./cmd/browser-install
|
||||
|
||||
# Docker CI 会把与独立安装包相同的目标架构 runtime 放到
|
||||
# .docker/playwright-runtime,构建时直接复制,不在 Dockerfile 内重复下载浏览器。
|
||||
FROM --platform=$BUILDPLATFORM node:latest AS playwright-runtime
|
||||
ARG TARGETARCH
|
||||
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||
ENV PLAYWRIGHT_NODEJS_PATH=/usr/local/bin/node
|
||||
COPY --from=browser-install-builder /out/browser-install-host /usr/local/bin/browser-install
|
||||
COPY .docker/playwright-runtime /prebuilt-playwright-runtime
|
||||
RUN set -eux; \
|
||||
mkdir -p /ms-playwright-go /ms-playwright; \
|
||||
case "$TARGETARCH" in \
|
||||
amd64) runtime_arch=amd64 ;; \
|
||||
arm64) runtime_arch=arm64 ;; \
|
||||
*) echo "不支持的 Docker 架构:$TARGETARCH" >&2; exit 1 ;; \
|
||||
esac; \
|
||||
if [ -f "/prebuilt-playwright-runtime/$runtime_arch/playwright-driver/package/cli.js" ]; then \
|
||||
cp -R "/prebuilt-playwright-runtime/$runtime_arch/playwright-driver/." /ms-playwright-go/; \
|
||||
cp -R "/prebuilt-playwright-runtime/$runtime_arch/playwright-browsers/." /ms-playwright/; \
|
||||
else \
|
||||
case "$TARGETARCH" in \
|
||||
amd64) playwright_platform=debian13-x64 ;; \
|
||||
arm64) playwright_platform=debian13-arm64 ;; \
|
||||
esac; \
|
||||
PLAYWRIGHT_HOST_PLATFORM_OVERRIDE="$playwright_platform" /usr/local/bin/browser-install \
|
||||
-driver-dir /ms-playwright-go \
|
||||
-browser-dir /ms-playwright; \
|
||||
fi; \
|
||||
test -f /ms-playwright-go/package/cli.js; \
|
||||
chromium_revision="$(node -e 'const b=require("/ms-playwright-go/package/browsers.json").browsers; process.stdout.write(b.find(x=>x.name==="chromium").revision)')"; \
|
||||
headless_revision="$(node -e 'const b=require("/ms-playwright-go/package/browsers.json").browsers; process.stdout.write(b.find(x=>x.name==="chromium-headless-shell").revision)')"; \
|
||||
test -d "/ms-playwright/chromium-$chromium_revision"; \
|
||||
test -d "/ms-playwright/chromium_headless_shell-$headless_revision"; \
|
||||
find /ms-playwright -type f -perm -111 \( -name chrome -o -name chrome-headless-shell -o -name headless_shell \) -print -quit | grep -q .
|
||||
|
||||
FROM node:latest AS runtime
|
||||
ENV TZ=Asia/Shanghai
|
||||
ENV BROWSER_HEADLESS=true
|
||||
ENV PLAYWRIGHT_DRIVER_PATH=/ms-playwright-go
|
||||
ENV PLAYWRIGHT_NODEJS_PATH=/usr/bin/node
|
||||
ENV PLAYWRIGHT_NODEJS_PATH=/usr/local/bin/node
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
||||
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
chromium \
|
||||
curl \
|
||||
fonts-liberation \
|
||||
fonts-noto-cjk \
|
||||
nodejs \
|
||||
tzdata \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=backend /out/xianyu-server /app/xianyu-server
|
||||
COPY --from=backend /out/xianyu-dbseed /app/xianyu-dbseed
|
||||
COPY --from=backend /out/xianyu-dbverify /app/xianyu-dbverify
|
||||
COPY --from=playwright-driver /ms-playwright-go /ms-playwright-go
|
||||
COPY --from=playwright-runtime /ms-playwright-go /ms-playwright-go
|
||||
COPY --from=playwright-runtime /ms-playwright /ms-playwright
|
||||
RUN mkdir -p /app/data /app/browser_data
|
||||
EXPOSE 8080
|
||||
CMD ["/app/xianyu-server", "-addr", ":8080"]
|
||||
EXPOSE 59188
|
||||
CMD ["/app/xianyu-server", "-addr", ":59188"]
|
||||
@@ -1,7 +1,7 @@
|
||||
FROM alpine:3.22 AS sqlite-tools
|
||||
RUN apk add --no-cache sqlite
|
||||
|
||||
FROM node:22-trixie AS frontend-assets
|
||||
FROM node:latest AS frontend-assets
|
||||
WORKDIR /src/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
@@ -24,7 +24,7 @@ COPY . .
|
||||
COPY --from=frontend-assets /src/internal/webui/static ./internal/webui/static
|
||||
CMD ["golangci-lint", "run", "./..."]
|
||||
|
||||
FROM node:22-trixie AS frontend-test
|
||||
FROM node:latest AS frontend-test
|
||||
WORKDIR /src/frontend
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
@@ -3,12 +3,20 @@
|
||||
GO ?= go
|
||||
GOLANGCI_LINT ?= golangci-lint
|
||||
|
||||
.PHONY: build build-int test test-int vet lint cover tidy frontend fmt check
|
||||
.PHONY: build build-int build-browser-install build-tray test test-int vet lint cover tidy frontend fmt check
|
||||
|
||||
## build: 编译 server(默认,跳过 integration build tag)
|
||||
build:
|
||||
$(GO) build ./cmd/server
|
||||
|
||||
## build-browser-install: 编译独立的 Chromium 安装辅助程序
|
||||
build-browser-install:
|
||||
$(GO) build ./cmd/browser-install
|
||||
|
||||
## build-tray: 编译 Windows/macOS 菜单栏控制器(需在目标桌面系统上编译)
|
||||
build-tray:
|
||||
$(GO) build ./cmd/tray
|
||||
|
||||
## build-int: 带 integration tag 编译(含 browser 包,需要 Chromium 环境)
|
||||
build-int:
|
||||
$(GO) build -tags integration ./...
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
[Docker 部署](#docker-部署) · [开发指南](#开发指南) · [开源协议](#开源协议)
|
||||
|
||||
操作手册见仓库内的 [GitHub Wiki 文档](docs/wiki/Home.md):包含数据库选择、账号接入、
|
||||
批量铺货、自动化发货、AI、通知和运维流程。
|
||||
在线聊天、账号自动任务、批量铺货、自动化发货、AI、通知和运维流程。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或
|
||||
@@ -57,8 +57,9 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
|
||||
| --- | --- |
|
||||
| 账号管理 | 多账号启停、扫码登录、密码登录、资料刷新、在线状态、登录审计与备注管理 |
|
||||
| 凭证续期 | Cookie/token 定时续期、WebSocket 凭证更新、失效恢复、冷却与失败停用 |
|
||||
| 即时消息 | 闲鱼 WebSocket 长连接、消息收发、关键词回复、默认回复及仅回复一次 |
|
||||
| 即时消息 | 按账号隔离的在线聊天、会话列表与历史消息、闲鱼表情、文本/图片收发、官方系统消息识别、关键词回复、默认回复及仅回复一次 |
|
||||
| 自动化中心 | 付款后自动发货、评价后赠品、超时未评价提醒、失败任务恢复与幂等检查点 |
|
||||
| 账号自动任务 | 账号级持续扫描待评价订单并统一好评、按北京时间每日擦亮、手动立即执行、执行记录与幂等保护 |
|
||||
| 卡密库存 | 文本、批量卡密和图片三种交付类型,库存追加、批量导入、规格与延迟发送 |
|
||||
| 商品管理 | 商品同步、手工关联、单商品发布、CSV + ZIP 批量铺货、关键词获取默认类目、逐行类目优先、自动识别与“电子资料”最终兜底、任务恢复与结果导出 |
|
||||
| 订单管理 | 订单同步、插入、编辑、平台发货、补发卡密、仅确认发货及异常状态处理 |
|
||||
@@ -97,7 +98,13 @@ flowchart LR
|
||||
|
||||
## 页面预览
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
## 快速开始
|
||||
|
||||
@@ -139,7 +146,7 @@ openssl rand -base64 48 # 适合作为 XIANYU_DATA_KEY
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
浏览器访问 `http://localhost:8080`,使用用户名 `admin` 和 `.env` 中的
|
||||
浏览器访问 `http://localhost:59188`,使用用户名 `admin` 和 `.env` 中的
|
||||
`XIANYU_ADMIN_PASSWORD` 登录。
|
||||
|
||||
> GHCR 镜像公开时可以匿名拉取。若镜像仍为私有,请先执行
|
||||
@@ -164,7 +171,84 @@ npm --prefix frontend ci
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
初始化管理员:
|
||||
前端资源会在构建时通过 Go 的 `//go:embed` 嵌入服务;如果服务已经在运行,构建完成后
|
||||
需要重启 Go 服务,浏览器硬刷新本身不会替换运行中进程已加载的前端资源。
|
||||
|
||||
### 方式三:桌面端安装包
|
||||
|
||||
桌面端由两个进程组成:后台 `xianyu-server` 负责 HTTP API、账号运行时和 Chromium;
|
||||
`xianyu-tray` 只负责 Windows 托盘或 macOS 菜单栏状态、打开管理页面、打开日志目录和服务控制。
|
||||
Chromium 不打进 Go 二进制,但 Linux、Windows 和 macOS 独立安装包会内置对应架构的
|
||||
Playwright driver 与 Chromium runtime,安装后无需用户再下载浏览器。
|
||||
|
||||
- Windows:安装器注册 `YdisksXianyuHelper` Windows Service,并将托盘控制器加入当前用户登录启动项。安装阶段会为交互式登录用户授予该服务的状态查询、启动和停止权限;安装完成后从托盘启动、停止、重启或退出服务不再触发 UAC,也不会获得修改或删除服务的权限。
|
||||
- macOS:安装器注册当前登录用户的两个 LaunchAgent,分别运行后台服务和菜单栏控制器。
|
||||
- Linux:下载对应架构的 tar 包后,以 root 执行 `./install.sh`;安装包已经包含对应架构的
|
||||
Playwright driver 与 Chromium,脚本只通过 Playwright 安装系统依赖,不会再下载浏览器。
|
||||
脚本创建专用系统用户并安装 systemd unit。安装完成后打开管理页面,首次设置管理员密码。
|
||||
卸载时执行 `./uninstall.sh`,
|
||||
默认保留 `/var/lib/ydisks-xianyu-helper` 数据。
|
||||
|
||||
桌面端安装后的固定位置和服务标识如下:
|
||||
|
||||
| 平台 | 后台服务 | 托盘/菜单栏程序 | 数据与日志 |
|
||||
| --- | --- | --- | --- |
|
||||
| Windows | `YdisksXianyuHelper` Windows Service | 当前用户登录启动的 `xianyu-tray.exe` | `C:\ProgramData\YdisksXianyuHelper\data`、`C:\ProgramData\YdisksXianyuHelper\logs` |
|
||||
| macOS | `com.ydisks.xianyu-helper.server` LaunchAgent | `Ydisks闲鱼助手.app` 内的菜单栏程序 | `~/Library/Application Support/YdisksXianyuHelper`、`~/Library/Logs/YdisksXianyuHelper` |
|
||||
| Linux | `ydisks-xianyu-helper.service` systemd unit | 无桌面托盘 | `/var/lib/ydisks-xianyu-helper`、`/var/log/ydisks-xianyu-helper` |
|
||||
|
||||
Windows 和 macOS 托盘启动时会自动启动后台服务,并显示检查中、启动中、运行正常、正在停止
|
||||
等状态。选择“退出托盘”时,只有确认后台服务已经停止后托盘才会退出;“打开日志目录”可直接
|
||||
打开日志位置。Windows 安装阶段会为交互式登录用户授予当前服务的查询、启动和停止权限,
|
||||
安装完成后托盘控制服务不需要重复确认 UAC;修改服务配置或删除服务仍需管理员权限。
|
||||
|
||||
托盘菜单中的“退出托盘”会先停止后台服务,再退出托盘程序;“打开日志目录”可直接打开当前平台的日志目录:Windows
|
||||
为 `C:\ProgramData\YdisksXianyuHelper\logs`,macOS 为
|
||||
`~/Library/Logs/YdisksXianyuHelper`。Linux 服务日志同时写入
|
||||
`/var/log/ydisks-xianyu-helper/server.log`,也可以使用
|
||||
`journalctl -u ydisks-xianyu-helper.service` 查看。
|
||||
|
||||
桌面端安装包由 GitHub Actions 工作流在 `main` 和 `codex/desktop-packaging` 分支构建:Linux 上传
|
||||
amd64/arm64 tar 包,Windows 上传安装器,macOS 分别上传 arm64 和 amd64 安装包。Windows
|
||||
和 macOS 安装包使用工作流中配置的固定签名证书签名;未配置对应 GitHub Secrets 时,签名
|
||||
步骤会失败,不会生成可分发的安装包。
|
||||
|
||||
Linux 安装包的 `install.sh` 必须在与安装包相同架构的 Linux 主机上以 root 执行。安装包已经
|
||||
包含对应架构的 Playwright driver、Chromium 和 headless shell;安装时只安装 Chromium 所需
|
||||
系统库,不会从 Debian 仓库重新安装 Chromium。
|
||||
|
||||
本地 macOS 打包可直接执行:
|
||||
|
||||
```bash
|
||||
./packaging/macos/prepare-runtime.sh arm64 ./dist/macos/playwright-runtime/arm64
|
||||
./packaging/macos/build-pkg.sh 0.0.0-local ./dist/macos arm64
|
||||
```
|
||||
|
||||
`build-pkg.sh` 会自动复用 `~/Library/Caches/ms-playwright-go` 和
|
||||
`~/Library/Caches/ms-playwright` 中与当前 Playwright driver 匹配的 Chromium;缓存不完整时会明确报错,
|
||||
不会生成安装后无法启动服务的残缺安装包。Intel macOS 使用 `amd64` 参数,并需要本机已有对应 x64 runtime。
|
||||
|
||||
桌面端首次启动:
|
||||
|
||||
1. 安装对应平台的安装包。macOS 请选择 arm64(Apple Silicon)或 amd64(Intel)版本。
|
||||
2. 启动后台服务和托盘/菜单栏控制器。
|
||||
3. 打开托盘菜单中的管理页面,或访问 `http://127.0.0.1:59188`。
|
||||
4. 如果数据库尚未初始化,页面会要求设置并确认管理员密码;完成后会自动登录,管理员用户名为 `admin`。
|
||||
|
||||
Linux 需要先安装并启动 systemd 服务:
|
||||
|
||||
```bash
|
||||
sudo ./install.sh
|
||||
```
|
||||
|
||||
然后访问 `http://127.0.0.1:59188` 完成首次初始化。
|
||||
|
||||
Linux、Windows、macOS 和源码运行默认都使用网页初始化:启动服务后打开
|
||||
`http://127.0.0.1:59188`,在“首次设置管理员密码”页面输入并确认不少于 8 个字符的密码,
|
||||
系统会创建 `admin` 并自动登录。只有 Docker Compose 使用 `.env` 中的
|
||||
`XIANYU_ADMIN_PASSWORD` 做非交互初始化;CLI 方式仅用于无浏览器、自动化部署或重置密码。
|
||||
|
||||
对于无浏览器环境、自动化部署或需要重置管理员密码的运维场景,仍可使用 CLI 初始化:
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
@@ -177,16 +261,16 @@ go run ./cmd/server \
|
||||
启动服务:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
```
|
||||
|
||||
首次启动会准备 Playwright 运行环境和 Chromium;下载速度取决于当前网络。启动完成后
|
||||
访问 `http://localhost:8080`。
|
||||
启动完成后访问 `http://localhost:59188`。如果数据库尚未初始化,直接在页面填写并确认
|
||||
管理员密码即可,不需要知道数据库文件路径,也不需要先执行 CLI 命令。
|
||||
|
||||
如当前环境无法安装 Chromium,可以使用 `-no-browser` 启动:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser
|
||||
```
|
||||
|
||||
此模式仍可运行管理后台,但浏览器指纹读取和滑块风控处理不可用,不建议用于需要登录
|
||||
@@ -200,7 +284,9 @@ go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser
|
||||
4. 等待账号状态变为在线,再同步商品和订单。
|
||||
5. 在“卡密库存”创建交付内容。
|
||||
6. 在“自动化规则”将闲鱼商品与卡密、规格和触发条件关联。
|
||||
7. 按需配置关键词回复、默认回复、AI 回复和通知渠道。
|
||||
7. 在“在线聊天”按账号查看历史会话、发送文本/表情/图片;官方交易卡片和闲小蜜消息会以系统消息显示,不会进入普通用户回复链。
|
||||
8. 在“账号管理 → 自动评价与每日擦亮”按账号配置统一评价文案、评价开关和擦亮时间;确认测试账号行为后再启用。
|
||||
9. 按需配置关键词回复、默认回复、AI 回复和通知渠道。
|
||||
|
||||
扫码登录是推荐方式。密码登录适合已有明确需求的环境,但更容易触发平台安全校验。
|
||||
无论使用哪种方式,都不要把 Cookie、密码、二维码或人脸验证地址分享给不可信第三方。
|
||||
@@ -219,12 +305,13 @@ DATABASE_URL > -db-url > -db
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | 空 | 数据库连接 URL;生产环境推荐 PostgreSQL |
|
||||
| `XIANYU_DATA_KEY` | 空 | 敏感字段加密主密钥;生产环境必须固定并备份 |
|
||||
| `XIANYU_ADMIN_PASSWORD` | 空 | 非交互初始化或重置管理员时使用 |
|
||||
| `XIANYU_ADMIN_PASSWORD` | 空 | Docker Compose 非交互初始化或重置管理员时使用;源码和桌面端可通过首次打开页面设置密码 |
|
||||
| `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_BROWSERS_PATH` | 自动发现;Docker 为 `/ms-playwright` | Playwright Chromium runtime 目录 |
|
||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | 自动发现 | 仅在需要强制使用外部 Chromium 时指定 |
|
||||
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | 源码 `false` / Docker `true` | 跳过下载 |
|
||||
| `TZ` | 系统时区;Docker 为 `Asia/Shanghai` | 容器和日志时区 |
|
||||
|
||||
@@ -239,7 +326,7 @@ Docker Compose 还支持:
|
||||
| `POSTGRES_PASSWORD` | 必填 | 数据库密码 |
|
||||
| `XIANYU_IMAGE` | `ghcr.io/christ9038/ydisks-xianyu-helper:latest` | 应用镜像与标签 |
|
||||
| `XIANYU_BIND_ADDRESS` | `0.0.0.0` | 应用在宿主机上的绑定地址 |
|
||||
| `XIANYU_HTTP_PORT` | `8080` | 应用在宿主机上的端口 |
|
||||
| `XIANYU_HTTP_PORT` | `59188` | 应用在宿主机上的端口 |
|
||||
|
||||
默认 `compose.yml` 直接拉取 GHCR 的 `:latest` 多架构镜像;如需固定版本,请将
|
||||
`XIANYU_IMAGE` 改为 `:main`、版本号或 `:sha-<提交号>` 标签。
|
||||
@@ -254,7 +341,7 @@ Docker Compose 还支持:
|
||||
| --- | --- | --- |
|
||||
| `-db` | `data/xianyu_data.db` | SQLite 数据库路径 |
|
||||
| `-db-url` | 空 | `sqlite://`、`mysql://` 或 `postgres://` 连接 URL |
|
||||
| `-addr` | `:8080` | HTTP 监听地址 |
|
||||
| `-addr` | `:59188` | HTTP 监听地址 |
|
||||
| `-web` | 内嵌前端 | 外部前端静态资源目录,目录内需包含 `index.html` |
|
||||
| `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 |
|
||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 |
|
||||
@@ -287,6 +374,7 @@ DATABASE_URL="postgres://user:pass@127.0.0.1:5432/xianyu?sslmode=disable" ./xian
|
||||
以下配置通过 Web 管理后台维护并保存在数据库中:
|
||||
|
||||
- **账号设置**:启停状态、备注、通知渠道绑定和单账号 AI 回复策略
|
||||
- **账号自动任务**:自动评价开关、统一好评文案(最多 500 个字符)、每日擦亮开关、北京时间执行时间和最近执行记录
|
||||
- **自动化规则**:触发条件、商品、规格、卡密组、发送数量、延迟和后续动作
|
||||
- **回复规则**:关键词、文本或图片回复、默认回复及回复次数限制
|
||||
- **AI 设置**:OpenAI 兼容 API 地址、API Key、模型和全局提示词
|
||||
@@ -307,7 +395,7 @@ LocalAI 或兼容网关。只有在明确了解数据流向时才应向外部 AI
|
||||
GitHub Actions 会将同一标签发布为多架构镜像:
|
||||
|
||||
```text
|
||||
ghcr.io/christ9038/ydisks-xianyu-helper:dev
|
||||
ghcr.io/christ9038/ydisks-xianyu-helper:latest
|
||||
├── linux/amd64
|
||||
└── linux/arm64
|
||||
```
|
||||
@@ -319,10 +407,14 @@ ARM64 Linux 拉取 arm64,不需要手动设置 `platform`。
|
||||
|
||||
| Git 引用 | 镜像标签 |
|
||||
| --- | --- |
|
||||
| `dev` 分支 | `dev`、`sha-<完整提交号>` |
|
||||
| `main` 分支 | `main`、`latest`、`sha-<完整提交号>` |
|
||||
| `codex/desktop-packaging` 分支 | `alpha`、`desktop-packaging`、`sha-<完整提交号>` |
|
||||
| `v1.2.3` 标签 | `1.2.3`、`1.2`、`sha-<完整提交号>` |
|
||||
|
||||
当前 Docker 发布工作流会在 `main` 分支发布 `main` 和 `latest` 正式镜像,并在
|
||||
`codex/desktop-packaging` 分支发布 `desktop-packaging` 和 `alpha` 标签用于验收;其他开发分支
|
||||
不会自动生成 GHCR 标签。
|
||||
|
||||
生产环境建议使用明确的版本标签或 SHA 标签,避免上游更新导致未经验证的自动升级。
|
||||
|
||||
### Compose 服务
|
||||
@@ -374,7 +466,7 @@ docker compose up -d
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
curl -fsS http://127.0.0.1:8080/health
|
||||
curl -fsS http://127.0.0.1:59188/health
|
||||
docker compose logs --tail=200 app
|
||||
```
|
||||
|
||||
@@ -438,7 +530,7 @@ docker volume ls --filter name=xianyu
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-secure"]
|
||||
command: ["/app/xianyu-server", "-addr", ":59188", "-secure"]
|
||||
```
|
||||
|
||||
## 开发指南
|
||||
@@ -449,6 +541,8 @@ services:
|
||||
.
|
||||
├── cmd/
|
||||
│ ├── server/ # 主服务与管理员初始化入口
|
||||
│ ├── browser-install/ # Playwright Chromium 安装辅助程序
|
||||
│ ├── tray/ # Windows 托盘/macOS 菜单栏控制器
|
||||
│ ├── init-admin/ # 交互式管理员初始化工具
|
||||
│ ├── dbverify/ # 多数据库迁移和 CRUD 验证
|
||||
│ └── dbseed/ # Docker 功能测试数据种子
|
||||
@@ -465,6 +559,7 @@ services:
|
||||
│ └── xianyu/ # MTOP、WebSocket、登录和协议实现
|
||||
├── frontend/ # React、TypeScript、Vite 前端
|
||||
├── docs/ # 专题文档和行为规范
|
||||
├── packaging/ # Linux systemd、Windows Inno Setup、macOS pkg
|
||||
├── scripts/ # Docker 与回归测试脚本
|
||||
└── Dockerfile.debian13 # 多阶段生产镜像
|
||||
```
|
||||
@@ -474,7 +569,7 @@ services:
|
||||
启动后端:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
```
|
||||
|
||||
启动前端开发服务器:
|
||||
@@ -484,7 +579,7 @@ npm --prefix frontend ci
|
||||
npm --prefix frontend run dev
|
||||
```
|
||||
|
||||
访问 `http://localhost:3000`。Vite 会将 API 请求代理到 `http://localhost:8080`。
|
||||
访问 `http://localhost:3000`。Vite 会将 API 请求代理到 `http://localhost:59188`。
|
||||
|
||||
构建嵌入式前端和 Go 二进制:
|
||||
|
||||
@@ -525,15 +620,20 @@ go run ./cmd/dbverify "postgres://user:pass@127.0.0.1:5432/xianyu"
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 首次部署无法完成管理员初始化
|
||||
### 首次打开页面如何初始化管理员
|
||||
|
||||
确认 `.env` 已设置非空的 `XIANYU_ADMIN_PASSWORD`,然后执行:
|
||||
启动服务后访问管理页面。如果数据库中还没有管理员,页面会显示“首次设置管理员密码”,
|
||||
填写两次不少于 8 个字符的密码并提交即可。初始化成功后会自动登录,默认管理员用户名为
|
||||
`admin`。
|
||||
|
||||
Docker Compose 使用非交互初始化,因此必须在 `.env` 中设置非空的
|
||||
`XIANYU_ADMIN_PASSWORD`,然后执行:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
源码运行时可执行:
|
||||
无浏览器、自动化部署或需要重置管理员密码时可执行:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密码'
|
||||
@@ -549,7 +649,11 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
||||
|
||||
### Chromium 或 Playwright 初始化失败
|
||||
|
||||
- Docker 部署优先使用项目提供的镜像,镜像已包含 Chromium 和运行依赖。
|
||||
- Docker 部署优先使用项目提供的镜像,镜像在构建阶段已下载并校验匹配架构的 Chromium runtime;
|
||||
Docker CI 优先复用 GitHub Actions 缓存,不依赖 Debian 仓库中的 `chromium` 包,也不会在最终镜像
|
||||
构建阶段执行 `apt-get update`。
|
||||
- 独立安装包在 CI 构建阶段下载对应架构的 Playwright driver 和 Chromium;Linux 安装时只
|
||||
安装系统库,不需要再次下载浏览器。
|
||||
- 源码运行时确认系统允许下载 Playwright 驱动和 Chromium。
|
||||
- 自带 Chromium 时设置 `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`,并按需设置
|
||||
`PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1`。
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// Command browser-install prepares the Playwright driver and Chromium runtime.
|
||||
// It intentionally does not change the server's browser launch behavior.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
driverDir := flag.String("driver-dir", "", "Playwright driver directory")
|
||||
browserDir := flag.String("browser-dir", "", "Playwright browser cache directory")
|
||||
withDeps := flag.Bool("with-deps", false, "also install Linux system dependencies")
|
||||
depsOnly := flag.Bool("deps-only", false, "only install Linux system dependencies; do not download Chromium")
|
||||
flag.Parse()
|
||||
if *depsOnly && !*withDeps {
|
||||
*withDeps = true
|
||||
}
|
||||
|
||||
if *driverDir != "" {
|
||||
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", *driverDir); err != nil {
|
||||
fatal("设置 driver 目录失败", err)
|
||||
}
|
||||
}
|
||||
if *browserDir != "" {
|
||||
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", *browserDir); err != nil {
|
||||
fatal("设置浏览器目录失败", err)
|
||||
}
|
||||
}
|
||||
|
||||
options := &playwright.RunOptions{
|
||||
Browsers: []string{"chromium"},
|
||||
Verbose: true,
|
||||
}
|
||||
if *driverDir != "" {
|
||||
options.DriverDirectory = *driverDir
|
||||
}
|
||||
driver, err := playwright.NewDriver(options)
|
||||
if err != nil {
|
||||
fatal("创建 Playwright driver 失败", err)
|
||||
}
|
||||
if err := driver.DownloadDriver(); err != nil {
|
||||
fatal("下载 Playwright driver 失败", err)
|
||||
}
|
||||
|
||||
args := []string{"install"}
|
||||
if *depsOnly {
|
||||
args = []string{"install-deps", "chromium"}
|
||||
} else if *withDeps {
|
||||
args = append(args, "--with-deps")
|
||||
args = append(args, "chromium")
|
||||
} else {
|
||||
args = append(args, "chromium")
|
||||
}
|
||||
cmd := driver.Command(args...)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
fatal("安装 Chromium 失败", err)
|
||||
}
|
||||
}
|
||||
|
||||
func fatal(message string, err error) {
|
||||
fmt.Fprintf(os.Stderr, "%s: %v\n", message, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -1,25 +1,20 @@
|
||||
// Package main 是闲鱼管家 Go 主进程入口。
|
||||
// 启动:DB 迁移 → 加载账号引擎 → HTTP API 服务。
|
||||
//
|
||||
// 用法:
|
||||
//
|
||||
// go run ./cmd/server -db data/xianyu_data.db -addr :8080 [-web ./static] [-secure] [-no-browser]
|
||||
// go run ./cmd/server -db data/xianyu_data.db -init-admin -admin-password '...'
|
||||
//
|
||||
// 首次使用可直接用本二进制初始化管理员,不再需要单独 init-admin。
|
||||
//
|
||||
// Chromium 仅用于读取本机浏览器指纹和处理 token 滑块,首次使用时由
|
||||
// playwright-go 准备运行环境。加 -no-browser 可禁用这两项能力。
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
@@ -28,6 +23,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"
|
||||
@@ -35,121 +31,226 @@ import (
|
||||
"xianyu-go/internal/server"
|
||||
)
|
||||
|
||||
type serverOptions struct {
|
||||
dbPath string
|
||||
dbURL string
|
||||
addr string
|
||||
webDir string
|
||||
workDir string
|
||||
playwrightRuntimeRoot string
|
||||
playwrightDriverDir string
|
||||
playwrightBrowserDir string
|
||||
dataKeyFile string
|
||||
secure bool
|
||||
noBrowser bool
|
||||
verbose bool
|
||||
logLevel string
|
||||
logFormat string
|
||||
initAdmin bool
|
||||
ensureAdmin bool
|
||||
adminEmail string
|
||||
adminPassword string
|
||||
service bool
|
||||
}
|
||||
|
||||
const (
|
||||
defaultDBPath = "data/xianyu_data.db"
|
||||
userDataDirName = "YdisksXianyuHelper"
|
||||
defaultDataKeyName = "data-key"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径(兼容旧用法)")
|
||||
dbURL := flag.String("db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
|
||||
addr := flag.String("addr", ":8080", "HTTP 监听地址")
|
||||
webDir := flag.String("web", "", "前端静态资源目录(含 index.html)")
|
||||
secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)")
|
||||
noBrowser := flag.Bool("no-browser", false, "禁用 Chromium(本机浏览器指纹读取和 token 滑块自动处理将不可用)")
|
||||
verbose := flag.Bool("v", false, "调试日志")
|
||||
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 环境变量")
|
||||
opts := parseOptions()
|
||||
if opts.workDir != "" {
|
||||
if err := os.Chdir(opts.workDir); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "切换工作目录失败: %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
run := func(ctx context.Context) error { return runServer(ctx, opts) }
|
||||
if opts.service {
|
||||
if err := runPlatformService("YdisksXianyuHelper", run); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "服务运行失败: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
if err := run(ctx); err != nil {
|
||||
slog.Error("服务退出", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func parseOptions() serverOptions {
|
||||
var opts serverOptions
|
||||
flag.StringVar(&opts.dbPath, "db", defaultDBPath, "SQLite 数据库路径(兼容旧用法)")
|
||||
flag.StringVar(&opts.dbURL, "db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
|
||||
flag.StringVar(&opts.addr, "addr", ":59188", "HTTP 监听地址")
|
||||
flag.StringVar(&opts.webDir, "web", "", "前端静态资源目录(含 index.html)")
|
||||
flag.StringVar(&opts.workDir, "workdir", "", "服务工作目录;用于桌面服务固定数据和浏览器目录")
|
||||
flag.StringVar(&opts.playwrightRuntimeRoot, "playwright-runtime-root", "", "随安装包分发的 Playwright runtime 根目录")
|
||||
flag.StringVar(&opts.playwrightDriverDir, "playwright-driver-dir", "", "Playwright driver 目录")
|
||||
flag.StringVar(&opts.playwrightBrowserDir, "playwright-browser-dir", "", "Playwright 浏览器缓存目录")
|
||||
flag.StringVar(&opts.dataKeyFile, "data-key-file", "", "XIANYU_DATA_KEY 持久化文件;不存在时自动生成")
|
||||
flag.BoolVar(&opts.secure, "secure", false, "HTTPS 模式(Cookie 加 Secure)")
|
||||
flag.BoolVar(&opts.noBrowser, "no-browser", false, "禁用 Chromium(本机浏览器指纹读取和 token 滑块自动处理将不可用)")
|
||||
flag.BoolVar(&opts.verbose, "v", false, "调试日志")
|
||||
flag.StringVar(&opts.logLevel, "log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置")
|
||||
flag.StringVar(&opts.logFormat, "log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT")
|
||||
flag.BoolVar(&opts.initAdmin, "init-admin", false, "初始化或重置 admin 管理员后退出")
|
||||
flag.BoolVar(&opts.ensureAdmin, "ensure-admin", false, "仅在 admin 管理员不存在时初始化;已存在时不修改密码")
|
||||
flag.StringVar(&opts.adminEmail, "admin-email", "admin@example.com", "初始化 admin 的邮箱")
|
||||
flag.StringVar(&opts.adminPassword, "admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量")
|
||||
flag.BoolVar(&opts.service, "service", false, "以 Windows Service 模式运行")
|
||||
flag.Parse()
|
||||
return opts
|
||||
}
|
||||
|
||||
func runServer(parent context.Context, opts serverOptions) error {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
|
||||
dataDir, err := resolveDataDir(opts.workDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
applyPlaywrightRuntimeRoot(&opts)
|
||||
if dataDir != "" {
|
||||
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
||||
return fmt.Errorf("创建应用数据目录失败: %w", err)
|
||||
}
|
||||
if opts.dataKeyFile == "" {
|
||||
opts.dataKeyFile = filepath.Join(dataDir, defaultDataKeyName)
|
||||
}
|
||||
if opts.playwrightDriverDir == "" {
|
||||
opts.playwrightDriverDir = filepath.Join(dataDir, "playwright-driver")
|
||||
}
|
||||
if opts.playwrightBrowserDir == "" {
|
||||
opts.playwrightBrowserDir = filepath.Join(dataDir, "playwright-browsers")
|
||||
}
|
||||
}
|
||||
|
||||
if opts.playwrightDriverDir != "" {
|
||||
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", opts.playwrightDriverDir); err != nil {
|
||||
return fmt.Errorf("设置 Playwright driver 目录失败: %w", err)
|
||||
}
|
||||
}
|
||||
if opts.playwrightBrowserDir != "" {
|
||||
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", opts.playwrightBrowserDir); err != nil {
|
||||
return fmt.Errorf("设置 Playwright 浏览器目录失败: %w", err)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(os.Getenv("XIANYU_DATA_KEY")) == "" && opts.dataKeyFile != "" {
|
||||
key, err := loadOrCreateDataKey(opts.dataKeyFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Setenv("XIANYU_DATA_KEY", key); err != nil {
|
||||
return fmt.Errorf("设置 XIANYU_DATA_KEY 失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 解析数据库连接:DATABASE_URL > -db-url > -db(SQLite 路径,向后兼容)。
|
||||
resolvedDBURL := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||
if resolvedDBURL == "" {
|
||||
resolvedDBURL = strings.TrimSpace(*dbURL)
|
||||
resolvedDBURL = strings.TrimSpace(opts.dbURL)
|
||||
}
|
||||
if resolvedDBURL == "" {
|
||||
resolvedDBURL = *dbPath
|
||||
resolvedDBURL = resolveDBPath(dataDir, opts.dbPath)
|
||||
}
|
||||
if dataDir != "" && resolvedDBURL == resolveDBPath(dataDir, defaultDBPath) {
|
||||
if err := os.MkdirAll(filepath.Dir(resolvedDBURL), 0o700); err != nil {
|
||||
return fmt.Errorf("创建数据库目录失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
resolvedLogLevel := strings.TrimSpace(os.Getenv("LOG_LEVEL"))
|
||||
explicitLogLevel := resolvedLogLevel != ""
|
||||
if strings.TrimSpace(*logLevel) != "" {
|
||||
resolvedLogLevel = strings.TrimSpace(*logLevel)
|
||||
if strings.TrimSpace(opts.logLevel) != "" {
|
||||
resolvedLogLevel = strings.TrimSpace(opts.logLevel)
|
||||
explicitLogLevel = true
|
||||
}
|
||||
if resolvedLogLevel == "" && *verbose {
|
||||
if resolvedLogLevel == "" && opts.verbose {
|
||||
resolvedLogLevel = "debug"
|
||||
explicitLogLevel = true
|
||||
}
|
||||
if err := logging.SetLevel(resolvedLogLevel); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "日志等级无效: %v\n", err)
|
||||
os.Exit(2)
|
||||
return fmt.Errorf("日志等级无效: %w", err)
|
||||
}
|
||||
resolvedLogFormat := strings.TrimSpace(os.Getenv("LOG_FORMAT"))
|
||||
explicitLogFormat := resolvedLogFormat != ""
|
||||
if strings.TrimSpace(*logFormat) != "" {
|
||||
resolvedLogFormat = strings.TrimSpace(*logFormat)
|
||||
if strings.TrimSpace(opts.logFormat) != "" {
|
||||
resolvedLogFormat = strings.TrimSpace(opts.logFormat)
|
||||
explicitLogFormat = true
|
||||
}
|
||||
logger := logging.NewLogger(os.Stdout, resolvedLogFormat)
|
||||
logWriter, closeLog, err := openServerLogWriter(dataDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeLog()
|
||||
logger := logging.NewLogger(logWriter, resolvedLogFormat)
|
||||
slog.SetDefault(logger)
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
|
||||
// 1) DB。
|
||||
database, dialect, err := db.Open(ctx, resolvedDBURL)
|
||||
if err != nil {
|
||||
logger.Error("打开数据库失败", "err", err)
|
||||
os.Exit(1)
|
||||
return fmt.Errorf("打开数据库失败: %w", err)
|
||||
}
|
||||
defer database.Close()
|
||||
logger.Info("数据库已就绪", "dialect", dialect)
|
||||
store := db.NewStore(database, dialect)
|
||||
if err := store.EncryptLegacySecrets(ctx); err != nil {
|
||||
logger.Error("校验或升级数据库敏感字段失败", "err", err)
|
||||
os.Exit(1)
|
||||
return fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
|
||||
}
|
||||
defer database.Close()
|
||||
if !explicitLogLevel {
|
||||
if lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" {
|
||||
if err := logging.SetLevel(lv); err != nil {
|
||||
logger.Warn("忽略无效的系统日志等级设置", "value", lv, "err", err)
|
||||
logger.Warn("忽略无效的系统日志设置", "value", lv, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !explicitLogFormat {
|
||||
if format, err := store.Settings.Get(ctx, "log_format"); err == nil && strings.TrimSpace(format) != "" {
|
||||
logger = logging.NewLogger(os.Stdout, format)
|
||||
logger = logging.NewLogger(logWriter, format)
|
||||
slog.SetDefault(logger)
|
||||
}
|
||||
}
|
||||
|
||||
if *initAdmin {
|
||||
if err := ensureAdmin(ctx, store, *adminEmail, *adminPassword); err != nil {
|
||||
logger.Error("初始化管理员失败", "err", err)
|
||||
os.Exit(1)
|
||||
if opts.initAdmin {
|
||||
if err := ensureAdmin(ctx, store, opts.adminEmail, opts.adminPassword); err != nil {
|
||||
return fmt.Errorf("初始化管理员失败: %w", err)
|
||||
}
|
||||
logger.Info("管理员初始化完成", "username", "admin")
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if *ensureAdminOnStart {
|
||||
created, err := ensureAdminIfMissing(ctx, store, *adminEmail, *adminPassword)
|
||||
if opts.ensureAdmin {
|
||||
created, err := ensureAdminIfMissing(ctx, store, opts.adminEmail, opts.adminPassword)
|
||||
if err != nil {
|
||||
logger.Error("检查或初始化管理员失败", "err", err)
|
||||
os.Exit(1)
|
||||
return fmt.Errorf("检查或初始化管理员失败: %w", err)
|
||||
}
|
||||
if created {
|
||||
logger.Info("管理员初始化完成", "username", "admin")
|
||||
}
|
||||
}
|
||||
|
||||
// 检查系统是否已初始化。
|
||||
if init, _ := store.Users.IsSystemInitialized(ctx); !init {
|
||||
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
|
||||
}
|
||||
|
||||
// 2) Chromium 只负责读取本机浏览器指纹和处理 token 滑块。
|
||||
// 扫码、人脸、续期、MTOP、Cookie 与 WebSocket 全部走 Go 协议实现。
|
||||
var bm *browser.Manager
|
||||
if !*noBrowser {
|
||||
if !opts.noBrowser {
|
||||
bm = browser.NewManager(logger)
|
||||
if err := bm.Initialize(); err != nil {
|
||||
logger.Error("初始化 Playwright Chromium 指纹失败", "err", err)
|
||||
os.Exit(1)
|
||||
return fmt.Errorf("初始化 Playwright Chromium 指纹失败: %w", err)
|
||||
}
|
||||
}
|
||||
var mgr *account.Manager
|
||||
|
||||
ap := adapter.New(store, bm, logger)
|
||||
mgr = account.NewManager(store, ap, logger)
|
||||
chatService := chat.New(store)
|
||||
ap.SetChatService(chatService)
|
||||
mgr := account.NewManager(store, ap, logger)
|
||||
autoCenter := automation.New(store, mgr, logger)
|
||||
autoCenter.SetOrderDetailFetcher(ap)
|
||||
notifier := notify.New("", store, logger)
|
||||
@@ -165,23 +266,14 @@ func main() {
|
||||
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)
|
||||
srv := server.New(store, mgr, opts.secure, opts.webDir, opts.addr, logger, autoCenter, notifier)
|
||||
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()
|
||||
}
|
||||
os.Exit(1)
|
||||
runErr := srv.Run(ctx)
|
||||
if runErr != nil {
|
||||
logger.Error("HTTP 服务退出", "err", runErr)
|
||||
}
|
||||
// HTTP 服务正常退出(ctx 取消触发 Shutdown):停账号引擎、关浏览器。
|
||||
cancel()
|
||||
srv.WaitForBackground()
|
||||
automationScheduler.Wait()
|
||||
renewalScheduler.Wait()
|
||||
@@ -190,11 +282,102 @@ func main() {
|
||||
_ = bm.Close()
|
||||
}
|
||||
notifier.Wait()
|
||||
return runErr
|
||||
}
|
||||
|
||||
// handlerAdapter 已下沉到 internal/adapter 包;本文件只负责装配。
|
||||
// openServerLogWriter keeps container and interactive runs on stdout while
|
||||
// desktop/system-service installations persist logs in their platform log
|
||||
// directory. Windows services do not have a useful console, so they get a
|
||||
// default log file beside the service data directory.
|
||||
func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
|
||||
logDir := strings.TrimSpace(os.Getenv("XIANYU_LOG_DIR"))
|
||||
if logDir == "" && runtime.GOOS == "windows" && dataDir != "" {
|
||||
logDir = filepath.Join(dataDir, "logs")
|
||||
}
|
||||
if logDir == "" {
|
||||
return os.Stdout, func() {}, nil
|
||||
}
|
||||
if err := os.MkdirAll(logDir, 0o700); err != nil {
|
||||
return nil, nil, fmt.Errorf("创建日志目录失败: %w", err)
|
||||
}
|
||||
logPath := filepath.Join(logDir, "server.log")
|
||||
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("打开日志文件失败: %w", err)
|
||||
}
|
||||
return file, func() { _ = file.Close() }, nil
|
||||
}
|
||||
|
||||
func applyPlaywrightRuntimeRoot(opts *serverOptions) {
|
||||
if opts == nil {
|
||||
return
|
||||
}
|
||||
root := strings.TrimSpace(opts.playwrightRuntimeRoot)
|
||||
if root == "" {
|
||||
return
|
||||
}
|
||||
archRoot := filepath.Join(root, runtime.GOARCH)
|
||||
if opts.playwrightDriverDir == "" {
|
||||
opts.playwrightDriverDir = filepath.Join(archRoot, "playwright-driver")
|
||||
}
|
||||
if opts.playwrightBrowserDir == "" {
|
||||
opts.playwrightBrowserDir = filepath.Join(archRoot, "playwright-browsers")
|
||||
}
|
||||
}
|
||||
|
||||
// resolveDataDir 返回桌面端的标准用户数据目录。
|
||||
// Linux/Docker 保留原有相对路径行为;macOS 和 Windows 在没有显式 -workdir
|
||||
// 时使用当前用户的系统配置目录,避免把具体用户路径写进安装包或代码。
|
||||
func resolveDataDir(workDir string) (string, error) {
|
||||
if strings.TrimSpace(workDir) != "" {
|
||||
return filepath.Clean(workDir), nil
|
||||
}
|
||||
if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
|
||||
return "", nil
|
||||
}
|
||||
configDir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("读取用户配置目录失败: %w", err)
|
||||
}
|
||||
return filepath.Join(configDir, userDataDirName), nil
|
||||
}
|
||||
|
||||
func resolveDBPath(dataDir, configuredPath string) string {
|
||||
if dataDir != "" && configuredPath == defaultDBPath {
|
||||
return filepath.Join(dataDir, "data", "xianyu_data.db")
|
||||
}
|
||||
return configuredPath
|
||||
}
|
||||
|
||||
func loadOrCreateDataKey(path string) (string, error) {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("data key 文件路径不能为空")
|
||||
}
|
||||
if raw, err := os.ReadFile(path); err == nil {
|
||||
key := strings.TrimSpace(string(raw))
|
||||
if key == "" {
|
||||
return "", fmt.Errorf("data key 文件为空: %s", path)
|
||||
}
|
||||
return key, nil
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("读取 data key 文件失败: %w", err)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return "", fmt.Errorf("创建 data key 目录失败: %w", err)
|
||||
}
|
||||
raw := make([]byte, 48)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", fmt.Errorf("生成 data key 失败: %w", err)
|
||||
}
|
||||
key := base64.RawStdEncoding.EncodeToString(raw)
|
||||
if err := os.WriteFile(path, []byte(key+"\n"), 0o600); err != nil {
|
||||
return "", fmt.Errorf("写入 data key 文件失败: %w", err)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ensureAdmin 解析密码后委托 auth.InitAdmin 完成创建或重置。
|
||||
func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error {
|
||||
if password == "" {
|
||||
password = os.Getenv("XIANYU_ADMIN_PASSWORD")
|
||||
@@ -206,7 +389,6 @@ func ensureAdmin(ctx context.Context, store *db.Store, email, password string) e
|
||||
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) {
|
||||
|
||||
@@ -2,7 +2,10 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
@@ -32,3 +35,95 @@ func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
|
||||
t.Fatalf("later password must not reset admin: ok=%v err=%v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOrCreateDataKeyPersists(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "data-key")
|
||||
first, err := loadOrCreateDataKey(path)
|
||||
if err != nil {
|
||||
t.Fatalf("create data key: %v", err)
|
||||
}
|
||||
if first == "" {
|
||||
t.Fatal("created data key is empty")
|
||||
}
|
||||
second, err := loadOrCreateDataKey(path)
|
||||
if err != nil {
|
||||
t.Fatalf("load data key: %v", err)
|
||||
}
|
||||
if first != second {
|
||||
t.Fatalf("data key changed between loads")
|
||||
}
|
||||
if raw, err := os.ReadFile(path); err != nil || string(raw) == "" {
|
||||
t.Fatalf("data key file was not written: err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
|
||||
logDir := t.TempDir()
|
||||
t.Setenv("XIANYU_LOG_DIR", logDir)
|
||||
|
||||
writer, closeLog, err := openServerLogWriter("")
|
||||
if err != nil {
|
||||
t.Fatalf("open log writer: %v", err)
|
||||
}
|
||||
if _, err := io.WriteString(writer, "test log\n"); err != nil {
|
||||
t.Fatalf("write log: %v", err)
|
||||
}
|
||||
closeLog()
|
||||
|
||||
content, err := os.ReadFile(filepath.Join(logDir, "server.log"))
|
||||
if err != nil {
|
||||
t.Fatalf("read log file: %v", err)
|
||||
}
|
||||
if string(content) != "test log\n" {
|
||||
t.Fatalf("unexpected log content: %q", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDataDirKeepsExplicitDirectory(t *testing.T) {
|
||||
explicit := filepath.Join(t.TempDir(), "ydisks-data")
|
||||
got, err := resolveDataDir(explicit)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve explicit data directory: %v", err)
|
||||
}
|
||||
if got != explicit {
|
||||
t.Fatalf("explicit data directory changed: got %q want %q", got, explicit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserDataDirName(t *testing.T) {
|
||||
base := filepath.Join(t.TempDir(), "Application Support")
|
||||
got := filepath.Join(base, userDataDirName)
|
||||
want := filepath.Join(base, "YdisksXianyuHelper")
|
||||
if got != want {
|
||||
t.Fatalf("unexpected user data directory: got %q want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDBPathUsesDataDirectoryForDefault(t *testing.T) {
|
||||
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
|
||||
got := resolveDBPath(dataDir, defaultDBPath)
|
||||
want := filepath.Join(dataDir, "data", "xianyu_data.db")
|
||||
if got != want {
|
||||
t.Fatalf("unexpected default database path: got %q want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDBPathPreservesCustomPath(t *testing.T) {
|
||||
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
|
||||
custom := filepath.Join(t.TempDir(), "custom.db")
|
||||
if got := resolveDBPath(dataDir, custom); got != custom {
|
||||
t.Fatalf("custom database path changed: got %q want %q", got, custom)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaywrightRuntimeRootUsesProcessArchitecture(t *testing.T) {
|
||||
opts := serverOptions{playwrightRuntimeRoot: filepath.Join(t.TempDir(), "playwright-runtime")}
|
||||
applyPlaywrightRuntimeRoot(&opts)
|
||||
wantRoot := filepath.Join(opts.playwrightRuntimeRoot, runtime.GOARCH)
|
||||
if opts.playwrightDriverDir != filepath.Join(wantRoot, "playwright-driver") {
|
||||
t.Fatalf("driver 目录=%q", opts.playwrightDriverDir)
|
||||
}
|
||||
if opts.playwrightBrowserDir != filepath.Join(wantRoot, "playwright-browsers") {
|
||||
t.Fatalf("browser 目录=%q", opts.playwrightBrowserDir)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func runPlatformService(_ string, _ func(context.Context) error) error {
|
||||
return fmt.Errorf("当前平台不支持 -service;请使用系统服务管理器启动普通进程")
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sys/windows/svc"
|
||||
)
|
||||
|
||||
type windowsServiceHandler struct {
|
||||
run func(context.Context) error
|
||||
}
|
||||
|
||||
func runPlatformService(name string, run func(context.Context) error) error {
|
||||
if err := svc.Run(name, windowsServiceHandler{run: run}); err != nil {
|
||||
return fmt.Errorf("Windows Service %q: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h windowsServiceHandler) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
|
||||
const accepted = svc.AcceptStop | svc.AcceptShutdown
|
||||
status <- svc.Status{State: svc.StartPending}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- h.run(ctx) }()
|
||||
status <- svc.Status{State: svc.Running, Accepts: accepted}
|
||||
|
||||
for {
|
||||
select {
|
||||
case request := <-requests:
|
||||
switch request.Cmd {
|
||||
case svc.Stop, svc.Shutdown:
|
||||
status <- svc.Status{State: svc.StopPending, Accepts: accepted}
|
||||
cancel()
|
||||
}
|
||||
case err := <-done:
|
||||
cancel()
|
||||
if err != nil {
|
||||
return true, 1
|
||||
}
|
||||
return false, 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 117 KiB |
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/binary"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// icon.png 是从根目录 icon/windows/icon.png 同步的彩色产品图标,并直接嵌入托盘二进制。
|
||||
//
|
||||
//go:embed icon.png
|
||||
var productIconPNG []byte
|
||||
|
||||
//go:embed icon-gray.png
|
||||
var productIconGrayPNG []byte
|
||||
|
||||
// trayIconBytes 返回当前服务状态对应的图标,避免运行时依赖外部图标文件。
|
||||
// Windows 的 Shell_NotifyIcon 需要 ICO;macOS/Linux 可以直接使用 PNG。
|
||||
func trayIconBytes(running bool) []byte {
|
||||
data := productIconGrayPNG
|
||||
if running {
|
||||
data = productIconPNG
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
return data
|
||||
}
|
||||
return pngToICO(data, 256)
|
||||
}
|
||||
|
||||
func pngToICO(data []byte, size int) []byte {
|
||||
const headerSize = 6
|
||||
const entrySize = 16
|
||||
result := make([]byte, headerSize+entrySize+len(data))
|
||||
// ICONDIR: reserved, type=icon, image count=1.
|
||||
binary.LittleEndian.PutUint16(result[0:2], 0)
|
||||
binary.LittleEndian.PutUint16(result[2:4], 1)
|
||||
binary.LittleEndian.PutUint16(result[4:6], 1)
|
||||
entry := result[headerSize : headerSize+entrySize]
|
||||
if size >= 256 {
|
||||
entry[0] = 0
|
||||
entry[1] = 0
|
||||
} else {
|
||||
entry[0] = byte(size)
|
||||
entry[1] = byte(size)
|
||||
}
|
||||
entry[2] = 0
|
||||
entry[3] = 0
|
||||
binary.LittleEndian.PutUint16(entry[4:6], 1)
|
||||
binary.LittleEndian.PutUint16(entry[6:8], 32)
|
||||
binary.LittleEndian.PutUint32(entry[8:12], uint32(len(data)))
|
||||
binary.LittleEndian.PutUint32(entry[12:16], headerSize+entrySize)
|
||||
copy(result[headerSize+entrySize:], data)
|
||||
return result
|
||||
}
|
||||
|
After Width: | Height: | Size: 171 KiB |
@@ -0,0 +1,43 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||
cacheDirectory, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("获取用户缓存目录失败: %w", err)
|
||||
}
|
||||
lockDirectory := filepath.Join(cacheDirectory, "YdisksXianyuHelper")
|
||||
if err := os.MkdirAll(lockDirectory, 0o755); err != nil {
|
||||
return nil, false, fmt.Errorf("创建托盘锁目录失败: %w", err)
|
||||
}
|
||||
|
||||
return acquireTrayFileLock(filepath.Join(lockDirectory, "tray.lock"))
|
||||
}
|
||||
|
||||
func acquireTrayFileLock(lockPath string) (release func(), acquired bool, err error) {
|
||||
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("打开托盘锁文件失败: %w", err)
|
||||
}
|
||||
if err := unix.Flock(int(lockFile.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
|
||||
_ = lockFile.Close()
|
||||
if err == unix.EWOULDBLOCK || err == unix.EAGAIN {
|
||||
return func() {}, false, nil
|
||||
}
|
||||
return nil, false, fmt.Errorf("锁定托盘实例失败: %w", err)
|
||||
}
|
||||
|
||||
return func() {
|
||||
_ = unix.Flock(int(lockFile.Fd()), unix.LOCK_UN)
|
||||
_ = lockFile.Close()
|
||||
}, true, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) {
|
||||
lockPath := filepath.Join(t.TempDir(), "tray.lock")
|
||||
releaseFirst, acquired, err := acquireTrayFileLock(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("acquire first tray instance: %v", err)
|
||||
}
|
||||
if !acquired {
|
||||
t.Fatal("first tray instance should acquire lock")
|
||||
}
|
||||
defer releaseFirst()
|
||||
|
||||
releaseSecond, acquired, err := acquireTrayFileLock(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("acquire second tray instance: %v", err)
|
||||
}
|
||||
defer releaseSecond()
|
||||
if acquired {
|
||||
t.Fatal("second tray instance must be rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||
mutexName, err := windows.UTF16PtrFromString(`Local\YdisksXianyuHelperTray`)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("生成托盘互斥锁名称失败: %w", err)
|
||||
}
|
||||
handle, err := windows.CreateMutex(nil, false, mutexName)
|
||||
if err == windows.ERROR_ALREADY_EXISTS {
|
||||
if handle != 0 {
|
||||
_ = windows.CloseHandle(handle)
|
||||
}
|
||||
return func() {}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("创建托盘互斥锁失败: %w", err)
|
||||
}
|
||||
return func() { _ = windows.CloseHandle(handle) }, true, nil
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
// Command tray provides the small desktop controller for the background server.
|
||||
// The server remains a separate process managed by the operating system.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"fyne.io/systray"
|
||||
)
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
Database string `json:"database"`
|
||||
}
|
||||
|
||||
var serviceURL = strings.TrimRight(envOr("XIANYU_SERVICE_URL", "http://127.0.0.1:59188"), "/")
|
||||
|
||||
var (
|
||||
actionMu sync.Mutex
|
||||
transitioning atomic.Bool
|
||||
exitRequested atomic.Bool
|
||||
)
|
||||
|
||||
func main() {
|
||||
closeLog := configureTrayLogger()
|
||||
defer closeLog()
|
||||
releaseInstance, acquired, err := acquireTrayInstance()
|
||||
if err != nil {
|
||||
log.Printf("获取托盘单实例锁失败: %v", err)
|
||||
return
|
||||
}
|
||||
if !acquired {
|
||||
log.Printf("托盘已经运行,本次启动直接退出")
|
||||
return
|
||||
}
|
||||
defer releaseInstance()
|
||||
log.Printf("托盘启动,PID=%d", os.Getpid())
|
||||
watchTerminationSignals()
|
||||
systray.Run(onReady, onTrayExit)
|
||||
|
||||
// systray 的退出回调运行在 Cocoa/系统托盘事件循环中,不能在回调
|
||||
// 内同步执行 launchctl,否则 macOS 可能把 LaunchAgent 标记为已退出,
|
||||
// 但实际托盘进程仍然存活。等事件循环真正返回后再处理外部退出。
|
||||
if !exitRequested.Load() {
|
||||
log.Printf("托盘事件循环结束,清理后台服务")
|
||||
if err := quitTray(); err != nil {
|
||||
log.Printf("清理后台服务失败: %v", err)
|
||||
} else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
log.Printf("等待后台服务退出失败: %v", err)
|
||||
}
|
||||
}
|
||||
log.Printf("托盘退出")
|
||||
}
|
||||
|
||||
func watchTerminationSignals() {
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
reason := <-signals
|
||||
log.Printf("收到进程终止信号: %s", reason)
|
||||
|
||||
actionMu.Lock()
|
||||
// actionMu 保证不会与菜单动作并发;拿到锁时其它动作已经完成。
|
||||
transitioning.Store(true)
|
||||
if err := quitTray(); err != nil {
|
||||
log.Printf("终止前停止后台服务失败: %v", err)
|
||||
} else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
log.Printf("终止前等待后台服务退出失败: %v", err)
|
||||
}
|
||||
transitioning.Store(false)
|
||||
actionMu.Unlock()
|
||||
signal.Stop(signals)
|
||||
os.Exit(0)
|
||||
}()
|
||||
}
|
||||
|
||||
func onTrayExit() {
|
||||
// 这里只记录事件。服务清理由 main 在 systray.Run 返回后执行,避免
|
||||
// 阻塞原生托盘事件循环。
|
||||
log.Printf("收到托盘退出事件")
|
||||
}
|
||||
|
||||
func configureTrayLogger() func() {
|
||||
directory, err := logDirectoryPath()
|
||||
if err != nil {
|
||||
return func() {}
|
||||
}
|
||||
if err := os.MkdirAll(directory, 0o755); err != nil {
|
||||
return func() {}
|
||||
}
|
||||
path := filepath.Join(directory, "tray.log")
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return func() {}
|
||||
}
|
||||
log.SetOutput(file)
|
||||
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
|
||||
return func() { _ = file.Close() }
|
||||
}
|
||||
|
||||
func onReady() {
|
||||
systray.SetTitle("")
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
systray.SetTooltip("Ydisks闲鱼助手服务")
|
||||
|
||||
statusItem := systray.AddMenuItem("服务状态:检查中", "读取后台服务状态")
|
||||
openItem := systray.AddMenuItem("打开管理页面", "在默认浏览器打开管理页面")
|
||||
logItem := systray.AddMenuItem("打开日志目录", "打开后台服务和托盘日志所在目录")
|
||||
systray.AddSeparator()
|
||||
startItem := systray.AddMenuItem("启动服务", "启动后台服务")
|
||||
stopItem := systray.AddMenuItem("停止服务", "停止后台服务")
|
||||
restartItem := systray.AddMenuItem("重启服务", "重启后台服务")
|
||||
systray.AddSeparator()
|
||||
quitItem := systray.AddMenuItem("退出托盘", "停止后台服务并退出菜单栏控制器")
|
||||
|
||||
// 安装脚本只负责注册平台服务。用户再次打开托盘时,托盘本身必须确保
|
||||
// 后台服务已启动。首次启动动作完成后再进入轮询,避免“检查中”的旧请求
|
||||
// 覆盖“启动中”等中间状态。
|
||||
go func() {
|
||||
runServiceAction(statusItem, "启动服务", "启动中", "start", startItem, stopItem, restartItem, quitItem)
|
||||
refreshStatus(statusItem)
|
||||
}()
|
||||
go func() {
|
||||
for range openItem.ClickedCh {
|
||||
_ = openURL(serviceURL)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for range logItem.ClickedCh {
|
||||
if err := openLogDirectory(); err != nil {
|
||||
statusItem.SetTitle("日志目录:打开失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:打开日志目录失败:%v", err))
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for range startItem.ClickedCh {
|
||||
runServiceAction(statusItem, "启动服务", "启动中", "start", startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for range stopItem.ClickedCh {
|
||||
runServiceAction(statusItem, "停止服务", "正在停止", "stop", startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for range restartItem.ClickedCh {
|
||||
runServiceAction(statusItem, "重启服务", "正在重启", "restart", startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for range quitItem.ClickedCh {
|
||||
exitTray(statusItem, startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func refreshStatus(item *systray.MenuItem) {
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
for {
|
||||
// 与菜单动作使用同一把锁,避免一次已经开始的健康检查在“启动中”
|
||||
// 或“正在停止”之后才返回,并把中间状态错误覆盖掉。
|
||||
actionMu.Lock()
|
||||
if !transitioning.Load() {
|
||||
refreshStatusOnce(item, client)
|
||||
}
|
||||
actionMu.Unlock()
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func refreshStatusOnce(item *systray.MenuItem, client *http.Client) {
|
||||
status, err := readHealth(client)
|
||||
if err != nil {
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
item.SetTitle("服务状态:未运行")
|
||||
systray.SetTooltip("Ydisks闲鱼助手:后台服务未运行")
|
||||
} else if status.Status == "ok" && status.Database == "ok" {
|
||||
systray.SetIcon(trayIconBytes(true))
|
||||
item.SetTitle("服务状态:运行正常")
|
||||
systray.SetTooltip("Ydisks闲鱼助手:运行正常")
|
||||
} else {
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
item.SetTitle("服务状态:异常")
|
||||
systray.SetTooltip("Ydisks闲鱼助手:数据库或服务异常")
|
||||
}
|
||||
}
|
||||
|
||||
func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle, action string, actionItems ...*systray.MenuItem) {
|
||||
actionMu.Lock()
|
||||
defer actionMu.Unlock()
|
||||
if transitioning.Swap(true) {
|
||||
return
|
||||
}
|
||||
defer transitioning.Store(false)
|
||||
log.Printf("开始执行服务操作: %s", actionName)
|
||||
setMenuItemsDisabled(true, actionItems...)
|
||||
defer setMenuItemsDisabled(false, actionItems...)
|
||||
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
statusItem.SetTitle("服务状态:" + transitionTitle)
|
||||
systray.SetTooltip("Ydisks闲鱼助手:" + transitionTitle)
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
if action == "start" {
|
||||
if health, err := readHealth(client); err == nil && health.Status == "ok" && health.Database == "ok" {
|
||||
statusItem.SetTitle("服务状态:运行正常")
|
||||
systray.SetIcon(trayIconBytes(true))
|
||||
systray.SetTooltip("Ydisks闲鱼助手:运行正常")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := serviceAction(action); err != nil {
|
||||
log.Printf("服务操作失败: %s: %v", actionName, err)
|
||||
statusItem.SetTitle("服务状态:操作失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s失败:%v", actionName, err))
|
||||
return
|
||||
}
|
||||
wantRunning := action != "stop"
|
||||
if err := waitForService(client, wantRunning, 30*time.Second); err != nil {
|
||||
log.Printf("服务操作状态确认失败: %s: %v", actionName, err)
|
||||
statusItem.SetTitle("服务状态:操作失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s后状态确认失败:%v", actionName, err))
|
||||
return
|
||||
}
|
||||
if wantRunning {
|
||||
statusItem.SetTitle("服务状态:运行正常")
|
||||
systray.SetIcon(trayIconBytes(true))
|
||||
systray.SetTooltip("Ydisks闲鱼助手:运行正常")
|
||||
} else {
|
||||
statusItem.SetTitle("服务状态:未运行")
|
||||
systray.SetTooltip("Ydisks闲鱼助手:后台服务已停止")
|
||||
}
|
||||
log.Printf("服务操作完成: %s", actionName)
|
||||
}
|
||||
|
||||
func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
||||
actionMu.Lock()
|
||||
defer actionMu.Unlock()
|
||||
if transitioning.Swap(true) {
|
||||
return
|
||||
}
|
||||
defer transitioning.Store(false)
|
||||
log.Printf("开始退出托盘")
|
||||
setMenuItemsDisabled(true, actionItems...)
|
||||
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
statusItem.SetTitle("托盘状态:正在退出")
|
||||
systray.SetTooltip("Ydisks闲鱼助手:正在停止后台服务")
|
||||
if err := quitTray(); err != nil {
|
||||
log.Printf("退出托盘停止服务失败: %v", err)
|
||||
statusItem.SetTitle("托盘状态:退出失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务停止失败:%v", err))
|
||||
setMenuItemsDisabled(false, actionItems...)
|
||||
return
|
||||
}
|
||||
if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
log.Printf("退出托盘等待服务停止失败: %v", err)
|
||||
statusItem.SetTitle("托盘状态:退出失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务仍未退出:%v", err))
|
||||
setMenuItemsDisabled(false, actionItems...)
|
||||
return
|
||||
}
|
||||
systray.SetTooltip("Ydisks闲鱼助手:后台服务已退出")
|
||||
exitRequested.Store(true)
|
||||
systray.Quit()
|
||||
}
|
||||
|
||||
func setMenuItemsDisabled(disabled bool, items ...*systray.MenuItem) {
|
||||
for _, item := range items {
|
||||
if disabled {
|
||||
item.Disable()
|
||||
} else {
|
||||
item.Enable()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitForService(client *http.Client, wantRunning bool, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
health, reachable, err := probeHealth(client)
|
||||
running := reachable && err == nil && health.Status == "ok" && health.Database == "ok"
|
||||
if wantRunning && running {
|
||||
return nil
|
||||
}
|
||||
// “已停止”要求监听端口确实不可达。服务仍能返回异常状态或非 2xx
|
||||
// 响应时,进程仍然存在,不能让托盘提前退出。
|
||||
if !wantRunning && !reachable {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
if wantRunning {
|
||||
return fmt.Errorf("等待后台服务启动超时")
|
||||
}
|
||||
return fmt.Errorf("等待后台服务退出超时")
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func readHealth(client *http.Client) (healthResponse, error) {
|
||||
health, _, err := probeHealth(client)
|
||||
return health, err
|
||||
}
|
||||
|
||||
func probeHealth(client *http.Client) (healthResponse, bool, error) {
|
||||
resp, err := client.Get(serviceURL + "/health")
|
||||
if err != nil {
|
||||
return healthResponse{}, false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return healthResponse{}, true, fmt.Errorf("health status %d", resp.StatusCode)
|
||||
}
|
||||
var health healthResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
|
||||
return healthResponse{}, true, err
|
||||
}
|
||||
return health, true, nil
|
||||
}
|
||||
|
||||
func openURL(url string) error {
|
||||
if runtime.GOOS == "windows" {
|
||||
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
||||
}
|
||||
return exec.Command("open", url).Start()
|
||||
}
|
||||
|
||||
func openLogDirectory() error {
|
||||
directory, err := logDirectoryPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(directory, 0o755); err != nil {
|
||||
return fmt.Errorf("创建日志目录失败: %w", err)
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return exec.Command("explorer.exe", directory).Start()
|
||||
case "darwin":
|
||||
return exec.Command("open", directory).Start()
|
||||
default:
|
||||
return exec.Command("xdg-open", directory).Start()
|
||||
}
|
||||
}
|
||||
|
||||
func envOr(name, fallback string) string {
|
||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWaitForServiceRequiresHealthyResponse(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"degraded","database":"error"}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
|
||||
client := server.Client()
|
||||
if err := waitForService(client, true, 20*time.Millisecond); err == nil {
|
||||
t.Fatal("degraded health response must not count as running")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForServiceAcceptsHealthyResponse(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"ok","database":"ok"}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
|
||||
if err := waitForService(server.Client(), true, time.Second); err != nil {
|
||||
t.Fatalf("healthy response should count as running: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForServiceDoesNotTreatUnhealthyResponseAsStopped(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
|
||||
if err := waitForService(server.Client(), false, 20*time.Millisecond); err == nil {
|
||||
t.Fatal("reachable unhealthy service must not count as stopped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForServiceAcceptsUnreachableAsStopped(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
||||
client := server.Client()
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
server.Close()
|
||||
|
||||
if err := waitForService(client, false, time.Second); err != nil {
|
||||
t.Fatalf("unreachable service should count as stopped: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//go:build darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func serviceAction(action string) error {
|
||||
label := envOr("XIANYU_SERVICE_NAME", "com.ydisks.xianyu-helper.server")
|
||||
uid := fmt.Sprint(os.Getuid())
|
||||
domain := "gui/" + uid
|
||||
target := domain + "/" + label
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取用户目录失败: %w", err)
|
||||
}
|
||||
plistPath := filepath.Join(home, "Library", "LaunchAgents", label+".plist")
|
||||
switch action {
|
||||
case "start":
|
||||
if err := launchctl("print", target); err == nil {
|
||||
if err := launchctl("kickstart", target); err == nil {
|
||||
return nil
|
||||
}
|
||||
// launchd 可能仍保留一个正在退出的旧 job;先完整卸载,
|
||||
// 等它消失后再 bootstrap,避免第二次启动报 Input/output error。
|
||||
_ = launchctl("bootout", target)
|
||||
if err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||
return err
|
||||
}
|
||||
return launchctl("kickstart", target)
|
||||
case "stop":
|
||||
if err := launchctl("print", target); err != nil {
|
||||
return nil
|
||||
}
|
||||
if err := launchctl("bootout", target); err != nil {
|
||||
return err
|
||||
}
|
||||
return waitForLaunchctlGone(target, 10*time.Second)
|
||||
case "restart":
|
||||
_ = launchctl("bootout", target)
|
||||
if err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||
return err
|
||||
}
|
||||
return launchctl("kickstart", target)
|
||||
default:
|
||||
return fmt.Errorf("未知服务操作: %s", action)
|
||||
}
|
||||
}
|
||||
|
||||
func waitForLaunchctlGone(target string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
if err := launchctl("print", target); err != nil {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("等待 LaunchAgent 退出超时: %s", target)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func quitTray() error {
|
||||
if err := serviceAction("stop"); err != nil {
|
||||
return fmt.Errorf("停止后台服务失败: %w", err)
|
||||
}
|
||||
// 不要从托盘进程内部 bootout 自己的 LaunchAgent。launchctl 可能会先
|
||||
// 卸载 job 再留下当前进程,导致旧托盘残留而新托盘无法正确接管。
|
||||
// KeepAlive=false,随后由 systray.Quit() 正常退出进程即可。
|
||||
return nil
|
||||
}
|
||||
|
||||
func logDirectoryPath() (string, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("获取用户目录失败: %w", err)
|
||||
}
|
||||
return filepath.Join(home, "Library", "Logs", "YdisksXianyuHelper"), nil
|
||||
}
|
||||
|
||||
func launchctl(args ...string) error {
|
||||
cmd := exec.Command("launchctl", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
message := strings.TrimSpace(string(output))
|
||||
if message == "" {
|
||||
return fmt.Errorf("launchctl %s 失败: %w", strings.Join(args, " "), err)
|
||||
}
|
||||
return fmt.Errorf("launchctl %s 失败: %s", strings.Join(args, " "), message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build !windows && !darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func serviceAction(action string) error {
|
||||
return fmt.Errorf("当前平台不支持托盘服务操作: %s", action)
|
||||
}
|
||||
|
||||
func quitTray() error { return nil }
|
||||
|
||||
func logDirectoryPath() (string, error) {
|
||||
return filepath.Join("/var", "log", "ydisks-xianyu-helper"), nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
const windowsServiceAccess = windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP
|
||||
|
||||
type windowsServiceController interface {
|
||||
state() (uint32, error)
|
||||
start() error
|
||||
stop() error
|
||||
close()
|
||||
}
|
||||
|
||||
type nativeWindowsServiceController struct {
|
||||
handle windows.Handle
|
||||
}
|
||||
|
||||
func serviceAction(action string) error {
|
||||
if action != "start" && action != "stop" && action != "restart" {
|
||||
return fmt.Errorf("未知服务操作: %s", action)
|
||||
}
|
||||
|
||||
name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper")
|
||||
controller, err := openWindowsServiceController(name)
|
||||
if err != nil {
|
||||
if action == "stop" && errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, windows.ERROR_ACCESS_DENIED) {
|
||||
return fmt.Errorf("没有控制 Windows 服务的权限,请重新安装当前版本以更新服务权限")
|
||||
}
|
||||
return fmt.Errorf("打开 Windows 服务 %s 失败: %w", name, err)
|
||||
}
|
||||
defer controller.close()
|
||||
|
||||
return controlWindowsService(controller, action, 30*time.Second, 250*time.Millisecond)
|
||||
}
|
||||
|
||||
func openWindowsServiceController(name string) (windowsServiceController, error) {
|
||||
manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer windows.CloseServiceHandle(manager) //nolint:errcheck
|
||||
|
||||
namePointer, err := windows.UTF16PtrFromString(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handle, err := windows.OpenService(manager, namePointer, windowsServiceAccess)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &nativeWindowsServiceController{handle: handle}, nil
|
||||
}
|
||||
|
||||
func controlWindowsService(controller windowsServiceController, action string, timeout, pollInterval time.Duration) error {
|
||||
switch action {
|
||||
case "start":
|
||||
return ensureWindowsServiceRunning(controller, timeout, pollInterval)
|
||||
case "stop":
|
||||
return ensureWindowsServiceStopped(controller, timeout, pollInterval)
|
||||
case "restart":
|
||||
if err := ensureWindowsServiceStopped(controller, timeout, pollInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
return ensureWindowsServiceRunning(controller, timeout, pollInterval)
|
||||
default:
|
||||
return fmt.Errorf("未知服务操作: %s", action)
|
||||
}
|
||||
}
|
||||
|
||||
func ensureWindowsServiceRunning(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
||||
state, err := controller.state()
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||
}
|
||||
switch state {
|
||||
case windows.SERVICE_RUNNING:
|
||||
return nil
|
||||
case windows.SERVICE_START_PENDING:
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
||||
case windows.SERVICE_STOP_PENDING:
|
||||
if err := waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := controller.start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
|
||||
return fmt.Errorf("启动 Windows 服务失败: %w", err)
|
||||
}
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
||||
}
|
||||
|
||||
func ensureWindowsServiceStopped(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
||||
state, err := controller.state()
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||
}
|
||||
switch state {
|
||||
case windows.SERVICE_STOPPED:
|
||||
return nil
|
||||
case windows.SERVICE_STOP_PENDING:
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
||||
case windows.SERVICE_START_PENDING:
|
||||
if err := waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := controller.stop(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {
|
||||
return fmt.Errorf("停止 Windows 服务失败: %w", err)
|
||||
}
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
||||
}
|
||||
|
||||
func waitForWindowsServiceState(controller windowsServiceController, expected uint32, timeout, pollInterval time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
state, err := controller.state()
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||
}
|
||||
if state == expected {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("等待 Windows 服务状态 %d 超时,当前状态 %d", expected, state)
|
||||
}
|
||||
time.Sleep(pollInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func (controller *nativeWindowsServiceController) state() (uint32, error) {
|
||||
var status windows.SERVICE_STATUS
|
||||
if err := windows.QueryServiceStatus(controller.handle, &status); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return status.CurrentState, nil
|
||||
}
|
||||
|
||||
func (controller *nativeWindowsServiceController) start() error {
|
||||
return windows.StartService(controller.handle, 0, nil)
|
||||
}
|
||||
|
||||
func (controller *nativeWindowsServiceController) stop() error {
|
||||
var status windows.SERVICE_STATUS
|
||||
return windows.ControlService(controller.handle, windows.SERVICE_CONTROL_STOP, &status)
|
||||
}
|
||||
|
||||
func (controller *nativeWindowsServiceController) close() {
|
||||
_ = windows.CloseServiceHandle(controller.handle)
|
||||
}
|
||||
|
||||
func quitTray() error {
|
||||
if err := serviceAction("stop"); err != nil {
|
||||
return fmt.Errorf("停止后台服务失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func logDirectoryPath() (string, error) {
|
||||
base := strings.TrimSpace(os.Getenv("PROGRAMDATA"))
|
||||
if base == "" {
|
||||
var err error
|
||||
base, err = os.UserConfigDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("获取 Windows 数据目录失败: %w", err)
|
||||
}
|
||||
}
|
||||
return filepath.Join(base, "YdisksXianyuHelper", "logs"), nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
type fakeWindowsServiceController struct {
|
||||
states []uint32
|
||||
actions []string
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) state() (uint32, error) {
|
||||
if len(controller.states) == 0 {
|
||||
return 0, fmt.Errorf("测试状态序列为空")
|
||||
}
|
||||
state := controller.states[0]
|
||||
if len(controller.states) > 1 {
|
||||
controller.states = controller.states[1:]
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) start() error {
|
||||
controller.actions = append(controller.actions, "start")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) stop() error {
|
||||
controller.actions = append(controller.actions, "stop")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (controller *fakeWindowsServiceController) close() {}
|
||||
|
||||
func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) {
|
||||
controller := &fakeWindowsServiceController{
|
||||
states: []uint32{
|
||||
windows.SERVICE_RUNNING,
|
||||
windows.SERVICE_STOP_PENDING,
|
||||
windows.SERVICE_STOPPED,
|
||||
windows.SERVICE_STOPPED,
|
||||
windows.SERVICE_START_PENDING,
|
||||
windows.SERVICE_RUNNING,
|
||||
},
|
||||
}
|
||||
if err := controlWindowsService(controller, "restart", time.Second, time.Millisecond); err != nil {
|
||||
t.Fatalf("restart Windows service: %v", err)
|
||||
}
|
||||
if want := []string{"stop", "start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsStartWaitsForPreviousStop(t *testing.T) {
|
||||
controller := &fakeWindowsServiceController{
|
||||
states: []uint32{
|
||||
windows.SERVICE_STOP_PENDING,
|
||||
windows.SERVICE_STOPPED,
|
||||
windows.SERVICE_START_PENDING,
|
||||
windows.SERVICE_RUNNING,
|
||||
},
|
||||
}
|
||||
if err := controlWindowsService(controller, "start", time.Second, time.Millisecond); err != nil {
|
||||
t.Fatalf("start Windows service: %v", err)
|
||||
}
|
||||
if want := []string{"start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsServiceAccessIsLimitedToStatusStartStop(t *testing.T) {
|
||||
want := uint32(windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP)
|
||||
if windowsServiceAccess != want {
|
||||
t.Fatalf("service access = %#x, want %#x", windowsServiceAccess, want)
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@ x-app-env: &app-env
|
||||
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_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/local/bin/node}
|
||||
PLAYWRIGHT_BROWSERS_PATH: ${PLAYWRIGHT_BROWSERS_PATH:-/ms-playwright}
|
||||
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
|
||||
@@ -45,12 +45,12 @@ services:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment: *app-env
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-ensure-admin"]
|
||||
command: ["/app/xianyu-server", "-addr", ":59188", "-ensure-admin"]
|
||||
ports:
|
||||
- "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-8080}:8080"
|
||||
- "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-59188}:59188"
|
||||
volumes: *app-volumes
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"]
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
@@ -7,9 +7,9 @@ x-app-env: &app-env
|
||||
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_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/local/bin/node}
|
||||
PLAYWRIGHT_BROWSERS_PATH: ${PLAYWRIGHT_BROWSERS_PATH:-/ms-playwright}
|
||||
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
|
||||
@@ -45,12 +45,12 @@ services:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment: *app-env
|
||||
command: ["/app/xianyu-server", "-addr", ":8080"]
|
||||
command: ["/app/xianyu-server", "-addr", ":59188"]
|
||||
ports:
|
||||
- "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-8080}:8080"
|
||||
- "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-59188}:59188"
|
||||
volumes: *app-volumes
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"]
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
@@ -121,14 +121,14 @@ services:
|
||||
DATABASE_URL: *mysql-url
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
TZ: Asia/Shanghai
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
|
||||
command: ["/app/xianyu-server", "-addr", ":59188", "-no-browser"]
|
||||
ports:
|
||||
- "28081:8080"
|
||||
- "28081:59188"
|
||||
volumes:
|
||||
- app_mysql_data:/app/data
|
||||
- app_mysql_browser_data:/app/browser_data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
@@ -143,14 +143,14 @@ services:
|
||||
DATABASE_URL: sqlite:///app/data/xianyu-functional.db
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
TZ: Asia/Shanghai
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
|
||||
command: ["/app/xianyu-server", "-addr", ":59188", "-no-browser"]
|
||||
ports:
|
||||
- "28080:8080"
|
||||
- "28080:59188"
|
||||
volumes:
|
||||
- app_sqlite_data:/app/data
|
||||
- app_sqlite_browser_data:/app/browser_data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
@@ -165,14 +165,14 @@ services:
|
||||
DATABASE_URL: *postgres-url
|
||||
XIANYU_DATA_KEY: *data-key
|
||||
TZ: Asia/Shanghai
|
||||
command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"]
|
||||
command: ["/app/xianyu-server", "-addr", ":59188", "-no-browser"]
|
||||
ports:
|
||||
- "28082:8080"
|
||||
- "28082:59188"
|
||||
volumes:
|
||||
- app_postgres_data:/app/data
|
||||
- app_postgres_browser_data:/app/browser_data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"]
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:59188/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
|
||||
|
Before Width: | Height: | Size: 494 KiB |
|
After Width: | Height: | Size: 379 KiB |
|
After Width: | Height: | Size: 473 KiB |
|
After Width: | Height: | Size: 728 KiB |
@@ -4,12 +4,12 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Ydisks闲鱼助手 - 基于 Go 与 React 构建的闲鱼多账号管理与自动发货系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手是一个面向闲鱼卖家的自托管管理系统。整合多账号登录、WebSocket即时消息、卡密库存交付、AI智能客服、自动化规则与多渠道告警。">
|
||||
<meta name="description" content="Ydisks闲鱼助手是一个面向闲鱼卖家的自托管管理系统。整合多账号登录、按账号隔离的在线聊天、账号自动评价与每日擦亮、卡密库存交付、AI智能客服、自动化规则与多渠道告警。">
|
||||
<meta name="keywords" content="闲鱼助手, 闲鱼自动发货, 闲鱼多账号管理, 闲鱼自动回复, 闲鱼AI客服, 闲鱼卡密发货, Go, React, Ydisks">
|
||||
|
||||
<!-- Open Graph -->
|
||||
<meta property="og:title" content="Ydisks闲鱼助手 - 闲鱼多账号管理与自动发货系统">
|
||||
<meta property="og:description" content="基于 Go 1.26 + React 19 构建的闲鱼自托管管理后台。自动化发货、AI回复、即时消息与风控续期。">
|
||||
<meta property="og:description" content="基于 Go 1.26 + React 19 构建的闲鱼自托管管理后台。在线聊天、账号自动评价与每日擦亮、自动化发货、AI回复与风控续期。">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:image" content="img/slogan.png">
|
||||
|
||||
@@ -976,7 +976,7 @@
|
||||
<div class="feature-card">
|
||||
<div class="feature-icon-box">💬</div>
|
||||
<h3 class="feature-card-title">WebSocket 即时消息处理</h3>
|
||||
<p class="feature-card-desc">内置 Go 原生闲鱼 WebSocket 长连接通道,实时接收与推送聊天消息,支持关键词回复、默认回复及单次回复控制。</p>
|
||||
<p class="feature-card-desc">按账号隔离在线聊天、历史消息和实时同步,支持闲鱼表情、文本/图片收发,并识别交易卡片与闲小蜜系统消息;普通消息继续支持关键词、默认回复及单次回复控制。</p>
|
||||
</div>
|
||||
|
||||
<!-- Card 3 -->
|
||||
@@ -986,6 +986,12 @@
|
||||
<p class="feature-card-desc">自动关联买家付款事件,支持付款即发货、评价后赠品发放、超时提醒评价,内置幂等检查点防止重复发送。</p>
|
||||
</div>
|
||||
|
||||
<div class="feature-card">
|
||||
<div class="feature-icon-box">✨</div>
|
||||
<h3 class="feature-card-title">账号自动评价与每日擦亮</h3>
|
||||
<p class="feature-card-desc">按账号持续扫描待评价订单并使用统一文案评价;每日擦亮按北京时间执行,每个账号每天最多一次,并支持手动执行与结果记录。</p>
|
||||
</div>
|
||||
|
||||
<!-- Card 4 -->
|
||||
<div class="feature-card">
|
||||
<div class="feature-icon-box">📦</div>
|
||||
@@ -1114,6 +1120,7 @@
|
||||
<div class="code-tabs">
|
||||
<button class="code-tab-btn active" onclick="switchTab('docker')">🐳 Docker Compose (推荐)</button>
|
||||
<button class="code-tab-btn" onclick="switchTab('source')">🛠️ 源码构建运行</button>
|
||||
<button class="code-tab-btn" onclick="switchTab('desktop')">🖥️ 独立安装包</button>
|
||||
</div>
|
||||
|
||||
<!-- Tab Content 1: Docker -->
|
||||
@@ -1127,14 +1134,15 @@
|
||||
<span class="command">cd</span> Ydisks-Xianyu-Helper
|
||||
<span class="command">cp</span> .env.example .env
|
||||
|
||||
<span class="comment"># 2. 修改 .env 填入自己的强密码与主密钥</span>
|
||||
<span class="comment"># 2. 修改 .env 填入数据库密码、管理员密码与主密钥</span>
|
||||
<span class="comment"># POSTGRES_PASSWORD=...</span>
|
||||
<span class="comment"># XIANYU_DATA_KEY=...</span>
|
||||
<span class="comment"># XIANYU_ADMIN_PASSWORD=...</span>
|
||||
|
||||
<span class="comment"># 3. 启动应用 (会自动拉取 GHCR 镜像并初始化 PostgreSQL 17)</span>
|
||||
<span class="command">docker compose up</span> -d
|
||||
|
||||
<span class="comment"># 4. 浏览器访问 http://localhost:8080,使用 admin 账号登录</span></code></pre>
|
||||
<span class="comment"># 4. 浏览器访问 http://localhost:59188,使用 admin 账号登录</span></code></pre>
|
||||
</div>
|
||||
|
||||
<!-- Tab Content 2: Source -->
|
||||
@@ -1147,15 +1155,38 @@
|
||||
<span class="command">npm</span> --prefix frontend ci
|
||||
<span class="command">npm</span> --prefix frontend run build
|
||||
|
||||
<span class="comment"># 2. 初始化管理员账号 (使用默认 SQLite)</span>
|
||||
<span class="comment"># 2. 启动服务端 (默认监听 :59188)</span>
|
||||
<span class="command">mkdir</span> -p data
|
||||
<span class="command">go run</span> ./cmd/server \
|
||||
-init-admin \
|
||||
-db data/xianyu_data.db \
|
||||
-admin-password <span class="string">'设置管理员密码'</span>
|
||||
-addr :59188
|
||||
|
||||
<span class="comment"># 3. 启动服务端 (默认监听 :8080)</span>
|
||||
<span class="command">go run</span> ./cmd/server -db data/xianyu_data.db -addr :8080</code></pre>
|
||||
<span class="comment"># 3. 浏览器访问 http://localhost:59188,在首次初始化页面设置管理员密码</span></code></pre>
|
||||
</div>
|
||||
|
||||
<!-- Tab Content 3: Desktop packages -->
|
||||
<div id="tab-desktop" class="code-box-wrapper" style="display: none;">
|
||||
<div class="code-box-header">
|
||||
<span class="code-box-title">Windows / macOS / Linux</span>
|
||||
</div>
|
||||
<pre><code id="code-desktop"><span class="comment"># Windows</span>
|
||||
下载安装器并运行;安装器会注册 YdisksXianyuHelper 服务,并在当前用户登录时启动托盘程序。
|
||||
|
||||
<span class="comment"># macOS</span>
|
||||
根据 CPU 选择 arm64(Apple Silicon)或 amd64(Intel)安装包并运行。
|
||||
安装器会注册后台服务和菜单栏控制器。
|
||||
|
||||
<span class="comment"># Linux</span>
|
||||
下载与主机架构匹配的 amd64 或 arm64 压缩包后执行:
|
||||
<span class="command">sudo</span> ./install.sh
|
||||
|
||||
<span class="comment"># 三个平台首次启动</span>
|
||||
浏览器访问 http://127.0.0.1:59188,在首次初始化页面填写并确认管理员密码。
|
||||
安装包已经包含匹配架构的 Playwright driver、Chromium 和 headless shell,安装时只补齐系统依赖。</code></pre>
|
||||
<p style="color: var(--text-muted); margin-top: 1rem;">
|
||||
Windows 和 macOS 托盘可以启动、停止、重启服务,显示过渡状态,打开日志目录,并在退出前等待服务停止。
|
||||
Linux 使用 systemd 管理 <code>ydisks-xianyu-helper.service</code>,没有桌面托盘。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -1177,7 +1208,7 @@
|
||||
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
|
||||
</div>
|
||||
<div class="faq-answer">
|
||||
使用 Docker Compose 部署时,服务在启动时会自动读取 <code>.env</code> 文件中的 <code>XIANYU_ADMIN_PASSWORD</code> 创建管理员,默认用户名统一为 <code>admin</code>。使用源码构建时,可运行 <code>go run ./cmd/server -init-admin -db ... -admin-password '你的密码'</code> 初始化。
|
||||
使用 Docker Compose 部署时,服务会读取 <code>.env</code> 文件中的 <code>XIANYU_ADMIN_PASSWORD</code>,在首次启动时自动创建管理员,默认用户名为 <code>admin</code>。源码运行或桌面端安装后,首次访问管理页面会显示密码设置表单,填写并确认密码即可完成初始化并自动登录。无浏览器或自动化部署场景仍可使用 <code>-init-admin</code> CLI。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1207,7 +1238,27 @@
|
||||
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
|
||||
</div>
|
||||
<div class="faq-answer">
|
||||
可以使用 <code>-no-browser</code> 启动参数运行纯 Go 后端与管理后台。但在没有 Chromium 的情况下,遇风控滑块自动通过能力将不可用。推荐直接使用官方 Docker 镜像(已预置 Chromium 与完整运行环境)。
|
||||
可以使用 <code>-no-browser</code> 启动参数运行纯 Go 后端与管理后台,但在没有 Chromium 的情况下,遇风控滑块自动通过能力将不可用。Docker 镜像和 Windows、macOS、Linux 独立安装包都在构建阶段准备了匹配架构的 Chromium 与 Playwright runtime;Linux 安装时只补齐系统依赖,不会从 Debian 仓库重新下载浏览器。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="faq-item">
|
||||
<div class="faq-question" onclick="toggleFaq(this)">
|
||||
<span>Windows、macOS 和 Linux 安装包有什么区别?</span>
|
||||
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
|
||||
</div>
|
||||
<div class="faq-answer">
|
||||
Windows 安装器注册 <code>YdisksXianyuHelper</code> Windows Service,并在当前用户登录时启动托盘;macOS 需要按 CPU 选择 arm64 或 amd64 安装包,并注册后台服务和菜单栏控制器;Linux 需要下载匹配架构的压缩包,以 root 执行 <code>./install.sh</code> 注册 <code>ydisks-xianyu-helper.service</code>。Windows 和 macOS 托盘支持服务控制、过渡状态和打开日志目录,Linux 使用 systemd 管理,没有桌面托盘。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="faq-item">
|
||||
<div class="faq-question" onclick="toggleFaq(this)">
|
||||
<span>桌面端首次启动和退出如何处理?</span>
|
||||
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
|
||||
</div>
|
||||
<div class="faq-answer">
|
||||
桌面端服务默认使用 <code>http://127.0.0.1:59188</code>。首次打开管理页面时直接填写并确认管理员密码即可,不需要查找数据库路径或执行 CLI 初始化命令。托盘显示检查中、启动中、运行正常和正在停止等状态;选择退出托盘后,它会先等待后台服务确认停止,再退出自身。日志可从托盘菜单中的“打开日志目录”查看。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1268,21 +1319,17 @@
|
||||
<script>
|
||||
// Tab switching
|
||||
function switchTab(tabName) {
|
||||
const dockerTab = document.getElementById('tab-docker');
|
||||
const sourceTab = document.getElementById('tab-source');
|
||||
const tabs = {
|
||||
docker: document.getElementById('tab-docker'),
|
||||
source: document.getElementById('tab-source'),
|
||||
desktop: document.getElementById('tab-desktop')
|
||||
};
|
||||
const buttons = document.querySelectorAll('.code-tab-btn');
|
||||
|
||||
buttons.forEach(btn => btn.classList.remove('active'));
|
||||
|
||||
if (tabName === 'docker') {
|
||||
dockerTab.style.display = 'block';
|
||||
sourceTab.style.display = 'none';
|
||||
buttons[0].classList.add('active');
|
||||
} else {
|
||||
dockerTab.style.display = 'none';
|
||||
sourceTab.style.display = 'block';
|
||||
buttons[1].classList.add('active');
|
||||
}
|
||||
Object.values(tabs).forEach(tab => { tab.style.display = 'none'; });
|
||||
tabs[tabName].style.display = 'block';
|
||||
[...buttons].find(button => button.getAttribute('onclick') === `switchTab('${tabName}')`).classList.add('active');
|
||||
}
|
||||
|
||||
// Toggle FAQ
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
# 登录续期与风控能力补齐计划
|
||||
# 登录续期与风控能力实施记录
|
||||
|
||||
> 本文最初是实施计划。当前列出的五个阶段均已落地;后续协议变化应以实际代码、测试和
|
||||
> 本文的实施记录为准,不应把“目标流程”误读为尚未实现的功能。
|
||||
|
||||
## 目标
|
||||
|
||||
|
||||
@@ -1,23 +1,38 @@
|
||||
# Ydisks闲鱼助手 Wiki
|
||||
|
||||
本 Wiki 面向管理后台操作人员。先完成“部署与数据库”和“账号接入”,再配置库存、商品、自动化与 AI。
|
||||
本 Wiki 面向管理后台操作人员。先完成“部署与数据库”和“账号接入”,再配置库存、商品、
|
||||
在线聊天、账号自动任务、交易自动化与 AI。
|
||||
|
||||
## 推荐上线路径
|
||||
|
||||
1. 选择并启动数据库;生产环境推荐 PostgreSQL。
|
||||
2. 设置并备份 `XIANYU_DATA_KEY`,初始化管理员后登录后台。
|
||||
3. 在“账号管理”扫码接入账号,确认账号为启用且在线状态。
|
||||
4. 在“卡密库存”建立可交付内容。
|
||||
5. 同步已有商品,或通过“商品管理”发布商品。
|
||||
6. 在“自动化规则”建立付款发货、评价赠品或求评价规则。
|
||||
7. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
|
||||
8. 建立通知渠道并绑定到账号;用测试通知验证。
|
||||
9. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
|
||||
1. 选择部署方式:Docker Compose、Linux 安装包、Windows 安装包、macOS 安装包或源码运行。
|
||||
2. Docker Compose 设置 `POSTGRES_*`、`DATABASE_URL`、`XIANYU_DATA_KEY` 和
|
||||
`XIANYU_ADMIN_PASSWORD`;其他方式启动服务后打开管理页面,在首次初始化页面填写密码。
|
||||
3. 设置并备份 `XIANYU_DATA_KEY`;默认管理员用户名为 `admin`。
|
||||
4. 在“账号管理”扫码接入账号,确认账号为启用且在线状态。
|
||||
5. 在“卡密库存”建立可交付内容。
|
||||
6. 同步已有商品,或通过“商品管理”发布商品。
|
||||
7. 在“在线聊天”确认账号会话和历史消息正常,必要时发送测试文本或图片。
|
||||
8. 在“账号自动任务”配置自动评价和每日擦亮;在“自动化规则”建立付款发货、评价赠品或求评价规则。
|
||||
9. 可选:在“系统与 AI”配置模型,再为每个账号启用 AI。
|
||||
10. 建立通知渠道并绑定到账号;用测试通知验证。
|
||||
11. 用小额测试订单验证“卡密发送 → 确认发货”全过程后,再开放正式商品。
|
||||
|
||||
桌面安装包的管理地址是 `http://127.0.0.1:59188`。Windows 和 macOS 安装包自带后台服务、托盘/菜单栏
|
||||
控制器以及匹配架构的 Playwright driver、Chromium;Linux 安装包自带相同的浏览器 runtime,
|
||||
安装脚本只补齐系统依赖。桌面托盘退出前会先停止后台服务。
|
||||
|
||||
Windows 安装包注册 `YdisksXianyuHelper` 服务;macOS 安装包分别提供 Apple Silicon(arm64)和
|
||||
Intel(amd64)版本,并注册 `com.ydisks.xianyu-helper.server` 与
|
||||
`com.ydisks.xianyu-helper.tray` 两个 LaunchAgent。Linux 安装包按 amd64/arm64 分发,执行
|
||||
`sudo ./install.sh` 后注册 `ydisks-xianyu-helper.service`。三种独立安装包都在构建阶段准备匹配架构
|
||||
的 Chromium,不依赖 Debian 仓库版本。
|
||||
|
||||
## 先读这些页面
|
||||
|
||||
- [部署与数据库](部署与数据库)
|
||||
- [账号、库存与商品](账号、库存与商品)
|
||||
- [在线聊天与账号自动任务](在线聊天与账号自动任务)
|
||||
- [批量铺货](批量铺货)
|
||||
- [自动化发货与回复](自动化发货与回复)
|
||||
- [AI、通知与运维](AI、通知与运维)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
- [首页](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 回复。
|
||||
|
||||
闲鱼官方系统消息只用于平台事件识别,不应被配置为普通买家关键词触发自动回复。
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
|
||||
系统通知卡片只进入自动化判断;买家普通消息走关键词、默认回复和 AI 规则。
|
||||
|
||||
账号级自动评价和每日擦亮不属于上表的订单规则,配置入口在“账号管理 → 自动评价与每日擦亮”,执行方式见[在线聊天与账号自动任务](在线聊天与账号自动任务)。
|
||||
|
||||
## 配置付款自动发货
|
||||
|
||||
前提:账号在线、商品已同步、卡密组已建立且有库存。
|
||||
|
||||
@@ -18,18 +18,56 @@
|
||||
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` 命令执行。
|
||||
6. 打开 `http://服务器地址:59188`。设置了 `XIANYU_ADMIN_PASSWORD` 时,Compose 会在首次启动
|
||||
自动创建 `admin`;如果使用其他方式启动且数据库尚未初始化,页面会显示初始化表单,填写
|
||||
两次不少于 8 个字符的密码即可。
|
||||
|
||||
默认连接已由 `compose.yml` 注入,不需要手写 PostgreSQL URL。若修改 `COMPOSE_PROJECT_NAME`,新卷名前缀也会变化;已有部署升级时保留原 `.env`,避免误用新空卷。
|
||||
|
||||
Docker 中的自动续期会使用容器内 Chromium 检测到的 Linux 原生浏览器指纹请求闲鱼官网;不会因为宿主系统是 Linux 而跳过静默续期。续期结果仍以闲鱼响应和账号登录态为准。
|
||||
|
||||
## 独立安装包
|
||||
|
||||
独立安装包与 Docker 使用同一套 Playwright Chromium 版本来源:Chromium、headless shell 和
|
||||
Playwright driver 都在构建阶段下载并放入包内,不使用 Debian 仓库的 Chromium。Docker CI 会优先
|
||||
复用架构专属的 GitHub Actions runtime 缓存,Dockerfile 最终使用 `node:latest` 运行时,不执行
|
||||
`apt-get update` 或安装 Debian Chromium。安装时不需要用户再执行浏览器下载命令。
|
||||
|
||||
| 平台 | 安装方式 | 服务标识 | 默认地址 |
|
||||
| --- | --- | --- | --- |
|
||||
| Linux amd64/arm64 | 解压后以 root 执行 `./install.sh` | `ydisks-xianyu-helper.service` | `http://127.0.0.1:59188` |
|
||||
| Windows | 运行 Inno Setup 安装器 | `YdisksXianyuHelper` | `http://127.0.0.1:59188` |
|
||||
| macOS arm64/amd64 | 运行对应架构的 pkg 安装器 | `com.ydisks.xianyu-helper.server` | `http://127.0.0.1:59188` |
|
||||
|
||||
Windows 和 macOS 安装包还会安装独立的托盘/菜单栏控制器。控制器负责显示检查中、启动中、运行正常、
|
||||
正在停止等中间状态,启动、停止和重启后台服务,打开日志目录,并在退出前等待后台服务确认停止。
|
||||
Windows 安装阶段会授予交互式登录用户该服务的查询、启动和停止权限,因此日常托盘操作不需要
|
||||
重复确认 UAC;修改服务配置或删除服务仍需管理员权限。Linux 没有桌面托盘,使用 systemd 和
|
||||
`journalctl -u ydisks-xianyu-helper.service` 管理服务。
|
||||
|
||||
独立安装包的数据和日志位置为:Windows 的 `C:\ProgramData\YdisksXianyuHelper`,macOS 的
|
||||
`~/Library/Application Support/YdisksXianyuHelper` 与 `~/Library/Logs/YdisksXianyuHelper`,Linux 的
|
||||
`/var/lib/ydisks-xianyu-helper` 与 `/var/log/ydisks-xianyu-helper`。macOS 必须选择与 CPU 匹配的
|
||||
arm64 或 amd64 包;Linux 也必须在相同架构的主机上安装,安装脚本不使用 QEMU。
|
||||
|
||||
## 桌面端日志与操作
|
||||
|
||||
日志目录如下。Windows 和 macOS 托盘菜单还可以启动、停止或重启后台服务,打开管理页面和日志目录。
|
||||
选择“退出托盘”时,会先停止后台服务,再退出托盘控制器,避免后台进程脱离用户控制继续运行。
|
||||
Windows 安装器会在安装阶段一次性配置当前机器上该服务的最小控制权限。普通交互式登录用户之后可以从托盘查询、启动和停止 `YdisksXianyuHelper`,这些操作不需要再次确认 UAC;修改服务配置、删除服务和控制其他系统服务仍需要管理员权限。
|
||||
|
||||
- Windows:`C:\ProgramData\YdisksXianyuHelper\logs\server.log`
|
||||
- macOS:`~/Library/Logs/YdisksXianyuHelper/server.log`,托盘日志为同目录下的 `tray.log`
|
||||
- Linux:`/var/log/ydisks-xianyu-helper/server.log`,同时可用 `journalctl -u ydisks-xianyu-helper.service` 查看
|
||||
|
||||
桌面端首次使用时直接打开管理页面,在初始化页面填写并确认管理员密码即可,不需要查找数据库路径或打开终端。
|
||||
|
||||
## SQLite
|
||||
|
||||
适合开发或轻量单机。默认数据库路径为 `data/xianyu_data.db`:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :8080
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
```
|
||||
|
||||
也可显式指定:
|
||||
@@ -46,7 +84,7 @@ DATABASE_URL="sqlite://data/xianyu_data.db" ./xianyu-server
|
||||
|
||||
```bash
|
||||
DATABASE_URL="mysql://user:URL编码后的密码@tcp(db.example:3306)/xianyu" \
|
||||
./xianyu-server -addr :8080
|
||||
./xianyu-server -addr :59188
|
||||
```
|
||||
|
||||
应用会补齐所需 MySQL 连接参数。密码中出现 `@`、`:`、`/` 等字符时必须 URL 编码。使用 TLS 的环境请按数据库驱动/基础设施要求配置安全连接,不要把真实密码写进命令历史。
|
||||
@@ -55,14 +93,22 @@ DATABASE_URL="mysql://user:URL编码后的密码@tcp(db.example:3306)/xianyu" \
|
||||
|
||||
```bash
|
||||
DATABASE_URL="postgres://user:URL编码后的密码@db.example:5432/xianyu?sslmode=require" \
|
||||
./xianyu-server -addr :8080
|
||||
./xianyu-server -addr :59188
|
||||
```
|
||||
|
||||
仅在受信任的本机网络可考虑 `sslmode=disable`;公网或跨网络部署应使用 TLS。数据库账号只应拥有该应用数据库的必要权限。
|
||||
|
||||
## 初始化、备份和升级
|
||||
|
||||
初始化管理员:
|
||||
### Web 页面初始化(推荐)
|
||||
|
||||
启动服务后访问管理页面。系统尚未存在管理员时,会显示“首次设置管理员密码”页面。输入并
|
||||
确认不少于 8 个字符的密码,提交后系统会创建 `admin` 账号并自动登录。此流程不需要用户
|
||||
知道 SQLite 文件路径,也不需要打开终端执行初始化命令。
|
||||
|
||||
### CLI 初始化(运维备用)
|
||||
|
||||
无浏览器、自动化部署或需要重置管理员密码时,可以使用 CLI:
|
||||
|
||||
```bash
|
||||
go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '强密码'
|
||||
|
||||
@@ -8,8 +8,10 @@ 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 { initializeAdmin, login, logout, verifySession } from './services/api';
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
|
||||
interface DeliveryRuleTarget {
|
||||
@@ -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',
|
||||
@@ -36,9 +39,6 @@ const TAB_TO_PATH: Record<string, string> = Object.fromEntries(
|
||||
);
|
||||
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard';
|
||||
|
||||
// 检测 Windows 以显示对应的 CLI 命令(路径分隔符、引号、.exe 后缀)。
|
||||
const isWindows = /Win/i.test(navigator.platform || navigator.userAgent);
|
||||
|
||||
const App: React.FC = () => {
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
@@ -49,7 +49,12 @@ const App: React.FC = () => {
|
||||
const [password, setPassword] = useState('');
|
||||
const [loginLoading, setLoginLoading] = useState(false);
|
||||
const [loginError, setLoginError] = useState('');
|
||||
const [initialPassword, setInitialPassword] = useState('');
|
||||
const [initialPasswordConfirm, setInitialPasswordConfirm] = useState('');
|
||||
const [initializing, setInitializing] = useState(false);
|
||||
const [initializationError, setInitializationError] = useState('');
|
||||
const [deliveryRuleTarget, setDeliveryRuleTarget] = useState<DeliveryRuleTarget | undefined>();
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(readSidebarCollapsed);
|
||||
|
||||
// 切换 tab 并同步 URL。若 tab 没有对应 path(不应发生)则只切 tab。
|
||||
const navigate = (tab: string) => {
|
||||
@@ -129,6 +134,38 @@ const App: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleInitialize = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setInitializationError('');
|
||||
if (initialPassword.length < 8) {
|
||||
setInitializationError('密码至少需要 8 个字符');
|
||||
return;
|
||||
}
|
||||
if (initialPassword !== initialPasswordConfirm) {
|
||||
setInitializationError('两次输入的密码不一致');
|
||||
return;
|
||||
}
|
||||
|
||||
setInitializing(true);
|
||||
try {
|
||||
const res = await initializeAdmin(initialPassword);
|
||||
if (!res.success) {
|
||||
setInitializationError(res.message || '初始化失败,请重试');
|
||||
return;
|
||||
}
|
||||
setNeedsInit(false);
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(res.is_admin === true);
|
||||
setInitialPassword('');
|
||||
setInitialPasswordConfirm('');
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
setInitializationError(msg || '初始化失败,请重试');
|
||||
} finally {
|
||||
setInitializing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await logout();
|
||||
@@ -143,8 +180,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,36 +189,58 @@ 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" />
|
||||
</div>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">系统尚未初始化</h2>
|
||||
<p className="text-gray-600 font-medium">为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。</p>
|
||||
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">首次设置管理员密码</h2>
|
||||
<p className="text-gray-600 font-medium">设置完成后会自动进入系统,管理员账号为 admin。</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 rounded-2xl bg-gray-50 border border-gray-100">
|
||||
<div className="text-sm font-bold text-gray-900 mb-2">请在服务器上执行:</div>
|
||||
<pre className="text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto">{isWindows
|
||||
? '.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"'
|
||||
: './xianyu-server -init-admin -db data/xianyu_data.db -admin-password \'请设置密码\''}</pre>
|
||||
<div className="text-xs text-gray-500 mt-2">完成后刷新页面即可进入登录。</div>
|
||||
<form onSubmit={handleInitialize} className="space-y-5">
|
||||
<div className="space-y-4">
|
||||
<div className="relative group">
|
||||
<Lock className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
||||
<input
|
||||
type="password"
|
||||
placeholder="设置管理员密码(至少 8 个字符)"
|
||||
value={initialPassword}
|
||||
onChange={e => setInitialPassword(e.target.value)}
|
||||
autoFocus
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<ShieldCheck className="absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors" />
|
||||
<input
|
||||
type="password"
|
||||
placeholder="再次输入密码"
|
||||
value={initialPasswordConfirm}
|
||||
onChange={e => setInitialPasswordConfirm(e.target.value)}
|
||||
className="w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{initializationError && (
|
||||
<div className="p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2">
|
||||
<ShieldCheck className="w-4 h-4" /> {initializationError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.location.reload()}
|
||||
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group"
|
||||
type="submit"
|
||||
disabled={initializing}
|
||||
className="w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70"
|
||||
>
|
||||
我已初始化,刷新 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
|
||||
{initializing ? <Loader2 className="w-5 h-5 animate-spin" /> : <>设置密码并进入系统 <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /></>}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="mt-8 pt-6 border-t border-gray-100 text-center">
|
||||
<span className="text-xs text-gray-400 font-medium tracking-widest uppercase">Secure Bootstrap</span>
|
||||
@@ -194,12 +253,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 +325,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 +343,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>
|
||||
|
||||
@@ -8,12 +8,12 @@ React + Vite + TypeScript 单页应用,作为 Ydisks闲鱼助手 Go 后端的
|
||||
frontend/
|
||||
index.html 入口 HTML
|
||||
index.tsx 应用入口(挂载 React、登录态判断、tab 路由)
|
||||
App.tsx 主壳:侧边栏 + 内容区 + 登录/初始化
|
||||
App.tsx 主壳:侧边栏 + 内容区 + 登录/首次初始化
|
||||
components/ 业务组件(Dashboard / OrderList / CardList / Rules / Settings ...)
|
||||
services/ 后端 API 封装(fetch 调用)
|
||||
request.ts 统一请求工具(带 session cookie、错误处理)
|
||||
types.ts 共享类型定义
|
||||
vite.config.ts Vite 配置(base=/static/,代理 /api 到 :8080)
|
||||
vite.config.ts Vite 配置(base=/static/,代理 /api 到 :59188)
|
||||
```
|
||||
|
||||
## 开发
|
||||
@@ -21,10 +21,12 @@ frontend/
|
||||
```bash
|
||||
cd /Users/christ/Workspace/git/xianyu/Ydisks-Xianyu-Helper/frontend
|
||||
npm install
|
||||
npm run dev # http://localhost:3000,API 代理到 localhost:8080
|
||||
npm run dev # http://localhost:3000,API 代理到 localhost:59188
|
||||
```
|
||||
|
||||
开发时先启动后端(`go run ./cmd/server -addr :8080`),再启动前端 dev server。
|
||||
开发时先启动后端(默认端口为 `59188`;桌面安装包绑定 `127.0.0.1`,源码运行可按需指定监听地址),
|
||||
例如 `go run ./cmd/server -addr :59188`,再启动前端 dev server。
|
||||
这里的 `localhost:3000` 仅是 Vite 开发服务器地址,不是应用服务端口。
|
||||
|
||||
## 构建产物
|
||||
|
||||
@@ -33,15 +35,30 @@ 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`。
|
||||
未登录时显示登录表单(客户端状态,非独立路由)。后端 SPA catch-all 对非 API 的 GET 请求返回 `index.html`,支持深链刷新。
|
||||
应用使用 `window.history.pushState` 做 tab 导航,路径包括 `/app/dashboard`、`/app/accounts`、
|
||||
`/app/chat`、`/app/cards`、`/app/items`、`/app/orders`、`/app/rules`、
|
||||
`/app/notifications` 和管理员可见的 `/app/settings`。
|
||||
未登录时显示登录表单(客户端状态,非独立路由)。当后端 `/verify` 返回
|
||||
`initialized: false` 时,显示首次初始化表单;用户确认不少于 8 个字符的管理员密码后,
|
||||
前端调用 `/initialize` 创建 `admin` 并使用返回的会话自动进入系统。后端 SPA catch-all
|
||||
对非 API 的 GET 请求返回 `index.html`,支持深链刷新。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
npx vitest run # 路由一致性、请求工具等单测
|
||||
npm test # 前端单元测试
|
||||
npm run typecheck # TypeScript 类型检查
|
||||
npm run build # 构建并更新 Go 嵌入资源
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { renderXianyuText, xianyuEmojis } from './chatEmojis';
|
||||
|
||||
describe('official Xianyu emoji mapping', () => {
|
||||
test('contains the complete official panel in official order', () => {
|
||||
expect(xianyuEmojis).toHaveLength(126);
|
||||
expect(xianyuEmojis[0][0]).toBe('尊嘟假嘟');
|
||||
expect(xianyuEmojis.at(-1)?.[0]).toBe('爱心');
|
||||
expect(new Set(xianyuEmojis.map(([name]) => name)).size).toBe(126);
|
||||
});
|
||||
|
||||
test('uses official CDN assets and renders bracket codes inline', () => {
|
||||
for (const [, url] of xianyuEmojis) {
|
||||
expect(url).toMatch(/^https:\/\/img\.alicdn\.com\//);
|
||||
}
|
||||
const html = renderToStaticMarkup(<>{renderXianyuText('你好[捂脸哭][送花]')}</>);
|
||||
expect(html).toContain('你好');
|
||||
expect(html).toContain('alt="[捂脸哭]"');
|
||||
expect(html).toContain('alt="[送花]"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,516 @@
|
||||
import React from 'react';
|
||||
|
||||
export const xianyuEmojis = [
|
||||
[
|
||||
"尊嘟假嘟",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"鸡哔你",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"谁懂啊",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吗喽",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"功德+1",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"city不city啊",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"激推",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"微笑",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"龇牙",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"流泪",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"尴尬",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"撇嘴",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"破涕为笑",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"捂脸哭",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"害羞",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"感动",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"滴泪",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"暗中观察",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"偷笑",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"ok",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"送花",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"大哭",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"色",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"惊慌",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"惊讶",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"得意",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"睡",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"不好意思",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"托腮",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"发怒",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"难过",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"调皮",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"愉快",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"白眼",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拒绝",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"期待",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"困",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!6000000003017-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"流汗",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01BU3NZ21gdcSjkqnST_!!6000000004165-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"憨笑",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01Pee9Ql1SJ661eH9By_!!6000000002225-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"耶",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01pFicsL1ipBhIqzcgs_!!6000000004461-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"奋斗",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ZhQ4AV25xBmTK3CnF_!!6000000007592-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"咒骂",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01r1Zh9927QKb4pnf7k_!!6000000007791-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"疑问",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01UZqbzt29MmlNctCQS_!!6000000008054-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"嘘",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01qBlYkM1ojaYF75On5_!!6000000005261-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"晕",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN014zhM2h1wPuSUFoMwV_!!6000000006301-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"开心到模糊",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01T1Dy271j6akZWo7Vr_!!6000000004499-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"衰",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01aOXsNr1LmgMvtyzOO_!!6000000001342-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"委屈",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN013J0bMk1QNYih3UFTk_!!6000000001964-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"再见",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01IHKsQx1UdpFgeTHcA_!!6000000002541-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"鼓掌",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01DHxB5s1G1RRBxekIu_!!6000000000562-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吐",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01xyVxH21LNUaMgW4hh_!!6000000001287-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"坏笑",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01zV7opv1bIU6iI8OhM_!!6000000003442-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"抠鼻",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01QOanju1sNqCrtYstu_!!6000000005755-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"叹气",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01RElx7R1QD1c8ZN07f_!!6000000001941-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"无聊",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01d91LnZ1UJDQjKCouC_!!6000000002496-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"思考",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01wQjg2f1tO84ZWitn9_!!6000000005891-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"呆",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01GLqBWC1DGbhqmpD2L_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"哇哦",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01MtLpS21qRO2bnAA5k_!!6000000005492-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"飞吻",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01q1WpFE25ljsNKjvHX_!!6000000007567-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"好喜欢",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01mD4iQM1O57XyQ5SHD_!!6000000001653-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拜托",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01SQgrTH1dzCH3pIyRN_!!6000000003806-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"真棒",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN017fcAmd1SCgYCj9Upk_!!6000000002211-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"流鼻血",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN0139JscY1rC6RS9GR4j_!!6000000005594-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"费解",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01FqAVvR1tyJMPj13ie_!!6000000005970-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"秃头",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01ZF4bV11thMhqm2Z1h_!!6000000005933-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"嘿哈",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01ObcOw61FOVlvQg7Mw_!!6000000000477-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吃土",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01Z6nJ1b1ZYr22YseHN_!!6000000003207-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"机智",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01rfKY351zDUZJlBiir_!!6000000006680-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"举杯",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01R2tn4F1mn8NuEIE8J_!!6000000004998-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"握手",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01NDcA251JDkvuFhSDb_!!6000000000995-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"挥手",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01iVN0ht1TmEuSwauGt_!!6000000002424-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"yeah",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01opt7hh27Wk8omjR4t_!!6000000007805-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"666",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01YRWDPF1OjQOpXeuTC_!!6000000001741-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"棒",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01agprvs1HU7rPRxOnB_!!6000000000760-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"爱你",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01SzxgcH1GSSo6Lwmwk_!!6000000000621-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"比心",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01YHZ39t1DeQIeb0TWQ_!!6000000000241-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"感谢",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01ywacF81baLYNeyK1n_!!6000000003481-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拍手",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01wbj4wv1K7ArD9AU44_!!6000000001116-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拉钩",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01dePkKH1HOd6ivAcu8_!!6000000000748-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"没钱",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01qhxGjp1zD2AfqmWx5_!!6000000006679-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"小刀",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01tFVx5Y1T2thPjhR6b_!!6000000002325-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"不刀",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01zTxff61clcvOcTS3n_!!6000000003641-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"同出",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01URKas6249R8ozS98O_!!6000000007348-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"递钱",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01PzhgV51FLlOaZHZ6n_!!6000000000471-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"数钱",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01CzXXvp23khkljToQH_!!6000000007294-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"打call",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01X7VUVm1il48IYv8Qw_!!6000000004452-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"号外",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01vg6xSM1Vxo9EKyfjR_!!6000000002720-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"包邮",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01yVS7ys24jA22oVZ2T_!!6000000007426-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"求赞",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01Xwqi5A1giCQMRcX6N_!!6000000004175-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"非主流",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN013wyI1j1hlEfDUoATI_!!6000000004317-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"吃瓜",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01LLOFsh1UUCw0deZba_!!6000000002520-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"种草",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01ooeRC81hA8a4x9S3q_!!6000000004236-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"佛系",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01BYXEe321GMHMZ9w66_!!6000000006957-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"超便宜",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01mqgSZi1Er4rOIDiP7_!!6000000000404-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拥抱",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01yuGD9c1hJkttfKHAm_!!6000000004257-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"摊手",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN014AiIqE1o9repE6STR_!!6000000005183-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"举手",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01xizuHZ1WPkJCogbuj_!!6000000002781-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"蹲",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01Midjjn1FrMj2CWer6_!!6000000000540-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"跪了",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01F2y52j24E16L6RIjF_!!6000000007358-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"拜",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01Jldd1G1oXDrEHH2qr_!!6000000005234-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"排",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01uSUmYD1jD0IJf0UVU_!!6000000004513-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"旺财",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01A25Mv01DKjGseAmuP_!!6000000000198-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"招财猫",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01WmJ7Sr20EhDyp86Bd_!!6000000006818-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"酸了",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01UFgjn61JJi5Iqxdk7_!!6000000001008-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"鸭鸭",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01pHSCSQ1deaS8WDiqG_!!6000000003761-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"方了",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01br7g711whlu8xOPUt_!!6000000006340-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"白菜",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01KABFLt24WKwXjVp08_!!6000000007398-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"桃子",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01CQhhPH1vJfRjDGBv5_!!6000000006152-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"打包",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01oYOkUI1VT7c0ivZHV_!!6000000002653-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"沙发",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN018qUFaE1DGbhqpMIit_!!6000000000189-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"南",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01ZSA6wg1PEZKf4h99R_!!6000000001809-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"盯",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01OWB1Gx1s01bzBhHN6_!!6000000005703-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"hot",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01DDD9uA22cAl7VDH7d_!!6000000007140-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"new",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01rRJXJo1qwzN4YnOHX_!!6000000005561-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"cool",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN013bUubF2855qb2Qt5l_!!6000000007880-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"1",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01U8XG5y1Ie22frQHCQ_!!6000000000917-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"可",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01SMjtPG1iJaN17p94N_!!6000000004392-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"搬砖",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01GbqW6G1LOrm0Gllcb_!!6000000001290-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"菜狗",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01VtN0t91USNLmvfmol_!!6000000002516-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"开心面具",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN017elkpk22EoYlBPKd3_!!6000000007089-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"快递",
|
||||
"https://img.alicdn.com/imgextra/i2/O1CN01AmUZXk1d3wle5O8IJ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"裂开",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN01BihwvO1a5N9bFt0LU_!!6000000003278-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"啤酒",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN01jDkgEj1WvLdXUVBDx_!!6000000002850-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"瑞思拜",
|
||||
"https://img.alicdn.com/imgextra/i4/O1CN011gR0Um1K3VgpYjPOi_!!6000000001108-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"小丑",
|
||||
"https://img.alicdn.com/imgextra/i3/O1CN01jMikhO1NJUM15XKTf_!!6000000001549-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
],
|
||||
[
|
||||
"爱心",
|
||||
"https://img.alicdn.com/imgextra/i1/O1CN015RVSWf23s25eETJqO_!!6000000007310-2-tps-980-980.png_110x10000.jpg_.webp"
|
||||
]
|
||||
] as const;
|
||||
|
||||
export const emojiURL = (url: string) => url;
|
||||
const emojiLookup = new Map<string, string>(xianyuEmojis.map(([name, url]) => [name, url]));
|
||||
|
||||
export const renderXianyuText = (text: string) => text.split(/(\[[^\]]+\])/g).map((part, index) => {
|
||||
const url = part.startsWith('[') ? emojiLookup.get(part.slice(1, -1)) : undefined;
|
||||
return url ? <img key={index} src={url} alt={part} title={part} className="mx-0.5 inline-block h-7 w-7 align-middle" /> : <React.Fragment key={index}>{part}</React.Fragment>;
|
||||
});
|
||||
@@ -0,0 +1,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\'');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
@@ -27,7 +27,7 @@ import { shouldUpdateAccountPause } from './accountPause';
|
||||
import {
|
||||
Plus, Power, Edit2, Trash2, QrCode, X, Check, Loader2,
|
||||
RefreshCw, Save, User, Clock, MessageCircle,
|
||||
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell
|
||||
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell, CalendarClock, Sparkles
|
||||
} from 'lucide-react';
|
||||
import { buildAccountLoginInfoUpdate } from './accountEdit';
|
||||
import { shouldSaveNotificationBindings } from './accountBindings';
|
||||
@@ -35,6 +35,7 @@ import { mergeAccountRuntimeStatuses } from './accountRuntimeState';
|
||||
import { createLatestRequestGate, createQRLoginPoller } from './qrPolling';
|
||||
import { RiskVerificationPanel } from './RiskVerificationPanel';
|
||||
import { SquareQRCode } from './SquareQRCode';
|
||||
import AccountAutomationModal from './AccountAutomationModal';
|
||||
|
||||
type ModalType = 'edit' | 'ai-settings' | null;
|
||||
|
||||
@@ -54,6 +55,7 @@ const AccountList: React.FC = () => {
|
||||
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
|
||||
const [activeModal, setActiveModal] = useState<ModalType>(null);
|
||||
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
|
||||
const [taskAccount, setTaskAccount] = useState<AccountDetail | null>(null);
|
||||
const [longLogin, setLongLogin] = useState({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
|
||||
|
||||
// 通知渠道绑定(编辑弹窗用)
|
||||
@@ -676,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();
|
||||
@@ -726,8 +728,8 @@ const AccountList: React.FC = () => {
|
||||
const runtime = runtimePresentation(account);
|
||||
const requiresLogin = account.runtime_state === 'auth_expired' || account.runtime_state === 'verification_required';
|
||||
return (
|
||||
<div key={account.id} className="ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300">
|
||||
<div className="flex items-center gap-5 sm:gap-8 min-w-0">
|
||||
<div key={account.id} className="ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand">
|
||||
<div className="flex min-w-0 items-start gap-5 sm:gap-8">
|
||||
<div className="relative">
|
||||
{account.avatar_url ? (
|
||||
<img
|
||||
@@ -744,8 +746,8 @@ const AccountList: React.FC = () => {
|
||||
{account.runtime_state === 'online' && <Check className="w-3 h-3 text-white" />}
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-3 mb-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2.5 mb-1">
|
||||
<h3 className="text-xl font-extrabold text-gray-900 break-words">{account.nickname || account.remark || `账号 ${account.id.substring(0,6)}...`}</h3>
|
||||
<span className={`px-2.5 py-0.5 rounded-lg text-xs font-bold ${runtime.badge}`}>{runtime.label}</span>
|
||||
{account.ai_enabled && (
|
||||
@@ -753,6 +755,17 @@ const AccountList: React.FC = () => {
|
||||
<Bot className="w-3 h-3" /> AI
|
||||
</span>
|
||||
)}
|
||||
{account.auto_rate_enabled && (
|
||||
<span className="flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700">
|
||||
<MessageCircle className="h-3 w-3" /> 自动评价
|
||||
</span>
|
||||
)}
|
||||
{account.auto_polish_enabled && (
|
||||
<span className="flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700">
|
||||
<Sparkles className="h-3 w-3" /> 每日擦亮
|
||||
</span>
|
||||
)}
|
||||
{account.auto_confirm && <span className="flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700"><Check className="h-3 w-3" /> 自动确认发货</span>}
|
||||
{account.profile_error && (
|
||||
<span
|
||||
className="px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1"
|
||||
@@ -762,10 +775,11 @@ const AccountList: React.FC = () => {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 font-medium mb-3 space-y-1">
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-4">
|
||||
<div className="text-sm font-medium text-gray-500">
|
||||
<p>{account.remark || account.note || '暂无备注'}</p>
|
||||
<p className="font-mono text-xs text-gray-400">ID: {account.id}</p>
|
||||
</div>
|
||||
</div>
|
||||
{account.runtime_message && account.runtime_state !== 'online' && account.runtime_state !== 'disabled' && (
|
||||
<div className={`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${requiresLogin ? 'text-red-700' : 'text-amber-700'}`}>
|
||||
<AlertCircle className="w-4 h-4 flex-shrink-0" />
|
||||
@@ -781,13 +795,8 @@ const AccountList: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
{account.auto_confirm && <span className="text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5"><Check className="w-3 h-3"/> 自动确认发货</span>}
|
||||
{account.paused && <span className="text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5"><Clock className="w-3 h-3"/> 暂停处理中</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 self-end lg:self-auto flex-shrink-0">
|
||||
{account.paused && <span className="flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-bold text-blue-700"><Clock className="h-3 w-3" /> 暂停处理中</span>}
|
||||
<div className="mt-3 flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
onClick={() => handleRefreshProfile(account)}
|
||||
disabled={refreshingProfileId === account.id}
|
||||
@@ -817,6 +826,13 @@ const AccountList: React.FC = () => {
|
||||
>
|
||||
<Bot className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTaskAccount(account)}
|
||||
className="p-3 rounded-xl hover:bg-amber-100 transition-colors text-amber-600"
|
||||
title="自动评价与每日擦亮"
|
||||
>
|
||||
<CalendarClock className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleToggle(account.id, account.enabled)}
|
||||
className={`p-3 rounded-xl transition-colors ${account.enabled ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-100'}`}
|
||||
@@ -834,8 +850,11 @@ const AccountList: React.FC = () => {
|
||||
? <Loader2 className="w-5 h-5 animate-spin" />
|
||||
: <Trash2 className="w-5 h-5" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)})}
|
||||
|
||||
{accounts.length === 0 && (
|
||||
@@ -855,11 +874,31 @@ 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-[0_24px_64px_rgba(15,23,42,0.22)]"
|
||||
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"
|
||||
@@ -908,7 +947,7 @@ const AccountList: React.FC = () => {
|
||||
role="progressbar"
|
||||
aria-label="正在删除账号"
|
||||
>
|
||||
<Loader2 className="h-5 w-5 flex-shrink-0 animate-spin text-[#0094f7]" />
|
||||
<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>
|
||||
@@ -976,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">
|
||||
@@ -1072,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
|
||||
@@ -1129,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>
|
||||
@@ -1167,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>
|
||||
@@ -1181,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
|
||||
@@ -1263,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" />}
|
||||
@@ -1338,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
|
||||
|
||||
@@ -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" />
|
||||
往单个组充卡密
|
||||
|
||||
@@ -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;
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
|
||||
@@ -638,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) ? '继续批量任务' : '批量铺货'}
|
||||
@@ -670,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" />
|
||||
@@ -710,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" />
|
||||
@@ -892,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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -232,6 +232,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
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('');
|
||||
@@ -283,6 +284,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
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;
|
||||
@@ -351,18 +353,6 @@ 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));
|
||||
@@ -801,7 +791,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
: '编辑默认回复';
|
||||
|
||||
return (
|
||||
<div className="space-y-8 animate-fade-in">
|
||||
<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>
|
||||
@@ -814,7 +804,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
setSelectedAccountId(event.target.value);
|
||||
setAutomationPage(1);
|
||||
}}
|
||||
className="ios-input px-4 py-3 rounded-2xl text-sm min-w-64"
|
||||
className="ios-input w-full px-4 py-3 rounded-2xl text-sm sm:w-64"
|
||||
>
|
||||
<option value="">全部账号</option>
|
||||
{accounts.map(account => (
|
||||
@@ -852,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'
|
||||
}`}
|
||||
>
|
||||
@@ -904,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>
|
||||
@@ -937,7 +927,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
|
||||
<div className="bg-white rounded-xl p-5 border border-gray-100 shadow-sm">
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<h3 className="font-black text-gray-900">本页规则构成</h3>
|
||||
<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">
|
||||
@@ -950,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>
|
||||
);
|
||||
})}
|
||||
@@ -958,8 +948,8 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="rounded-xl border border-gray-100 bg-[#FAFAFA] p-4 shadow-sm">
|
||||
<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" />
|
||||
@@ -1122,7 +1112,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
type="button"
|
||||
disabled={loading}
|
||||
onClick={() => setAutomationPage(pageNumber)}
|
||||
className={`h-9 min-w-9 rounded-lg px-2 text-sm font-bold transition-colors ${pageNumber === automationPage ? 'bg-[#0094f7] text-white' : 'bg-gray-50 text-gray-600 hover:bg-gray-100'} disabled:cursor-not-allowed disabled:opacity-60`}
|
||||
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}
|
||||
>
|
||||
@@ -1154,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>
|
||||
@@ -1197,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" />
|
||||
@@ -1282,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>
|
||||
@@ -1306,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">
|
||||
@@ -1379,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">
|
||||
@@ -1456,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>
|
||||
@@ -1748,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>
|
||||
|
||||
@@ -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>
|
||||
))
|
||||
) : (
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -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)" />
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { readSidebarCollapsed, writeSidebarCollapsed } from './sidebarState';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('sidebar persistence', () => {
|
||||
test('defaults to expanded and persists both states', () => {
|
||||
const values = new Map<string, string>();
|
||||
vi.stubGlobal('window', { localStorage: {
|
||||
getItem: (key: string) => values.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => values.set(key, value),
|
||||
}});
|
||||
expect(readSidebarCollapsed()).toBe(false);
|
||||
writeSidebarCollapsed(true);
|
||||
expect(readSidebarCollapsed()).toBe(true);
|
||||
writeSidebarCollapsed(false);
|
||||
expect(readSidebarCollapsed()).toBe(false);
|
||||
});
|
||||
|
||||
test('storage failures safely fall back to expanded', () => {
|
||||
vi.stubGlobal('window', { localStorage: {
|
||||
getItem: () => { throw new Error('blocked'); },
|
||||
setItem: () => { throw new Error('blocked'); },
|
||||
}});
|
||||
expect(readSidebarCollapsed()).toBe(false);
|
||||
expect(() => writeSidebarCollapsed(true)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
const storageKey = 'ydisks.sidebar.v1';
|
||||
|
||||
export const readSidebarCollapsed = (): boolean => {
|
||||
try {
|
||||
return window.localStorage.getItem(storageKey) === 'collapsed';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const writeSidebarCollapsed = (collapsed: boolean): void => {
|
||||
try {
|
||||
window.localStorage.setItem(storageKey, collapsed ? 'collapsed' : 'expanded');
|
||||
} catch {
|
||||
// Storage can be unavailable in hardened browsers; the in-memory state
|
||||
// remains fully functional.
|
||||
}
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -33,6 +33,12 @@ import {
|
||||
updateNotificationChannel,
|
||||
updateSystemSettings,
|
||||
updateShippingRule,
|
||||
getChatSessions,
|
||||
getChatMessages,
|
||||
sendChatMessage,
|
||||
markChatRead,
|
||||
updateAccountTaskSettings,
|
||||
runAccountTask,
|
||||
} from './api';
|
||||
|
||||
afterEach(() => {
|
||||
@@ -49,6 +55,36 @@ test('updateSystemSettings uses one atomic bulk request', async () => {
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ theme_color: 'blue', renewal_log_retention_days: 15 });
|
||||
});
|
||||
|
||||
test('chat APIs preserve account and conversation scope', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ sessions: [{ account_id: 'a1', chat_id: 'c1' }] }))
|
||||
.mockResolvedValueOnce(jsonResponse({ messages: [{ account_id: 'a1', chat_id: 'c1', id: 1 }] }))
|
||||
.mockImplementation(() => Promise.resolve(jsonResponse({ success: true, message: { id: 2 } })));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await getChatSessions('a1');
|
||||
await getChatMessages('a1', 'c1', 9);
|
||||
await sendChatMessage({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1', text: 'hi' });
|
||||
await markChatRead('a1', 'c1');
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/chat/sessions?account_id=a1');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/chat/messages?account_id=a1&chat_id=c1&before_id=9');
|
||||
expect(JSON.parse(fetchMock.mock.calls[2][1].body)).toMatchObject({ account_id: 'a1', chat_id: 'c1', buyer_id: 'b1' });
|
||||
expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({ account_id: 'a1', chat_id: 'c1' });
|
||||
});
|
||||
|
||||
test('account task APIs keep rating and polish account-scoped', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true, summary: { task_type: 'auto_rate' } })));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await updateAccountTaskSettings('a1', {
|
||||
account_id: 'a1', auto_rate_enabled: true, rate_content: '交易愉快',
|
||||
auto_polish_enabled: true, polish_time: '03:00',
|
||||
});
|
||||
await runAccountTask('a1', 'auto_rate');
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/account-tasks/a1');
|
||||
expect(fetchMock.mock.calls[0][1].method).toBe('PUT');
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/account-tasks/a1/run');
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ task_type: 'auto_rate' });
|
||||
});
|
||||
|
||||
test('getItemPublishBatches unwraps persisted batch list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ batches: [{ id: 'batch-1', status: 'running' }] }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
@@ -116,6 +152,7 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
total_pages: 2,
|
||||
trigger_counts: { order_paid: 8, buyer_reviewed: 7, review_missing_timeout: 6 },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
@@ -128,7 +165,13 @@ test('getShippingRulesPage sends filters and preserves pagination metadata', asy
|
||||
pageSize: 20,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ total: 21, page: 2, page_size: 20, total_pages: 2 });
|
||||
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',
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType
|
||||
, AccountTaskSettings, AccountTaskSummary, ChatSession, ChatMessage
|
||||
} from '../types';
|
||||
import { formatLocalDate } from '../dateRange';
|
||||
|
||||
@@ -21,6 +22,10 @@ export const login = async (data: { username?: string; password?: string; email?
|
||||
return post('/login', data, { skipAuthLogout: true });
|
||||
};
|
||||
|
||||
export const initializeAdmin = async (password: string): Promise<LoginResponse> => {
|
||||
return post('/initialize', { password }, { skipAuthLogout: true });
|
||||
};
|
||||
|
||||
export const verifySession = async (): Promise<{ authenticated: boolean; initialized?: boolean; user_id?: number; username?: string; is_admin?: boolean }> => {
|
||||
return get('/verify');
|
||||
};
|
||||
@@ -82,9 +87,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;
|
||||
@@ -624,6 +690,9 @@ export const getShippingRulesPage = async ({
|
||||
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)]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -10,112 +10,113 @@ export default defineConfig({
|
||||
proxy: {
|
||||
// 代理API请求到后端
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
// 代理其他后端请求
|
||||
'/cookies': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/account': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/qr-login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/password-login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/keywords': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/keywords-with-item-id': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/default-reply': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/items': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/cards': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-rules': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-issues': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-runs': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/automation-pending-tasks': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/notification-channels': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/message-notifications': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/ai-reply-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/ai-models': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/system-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/user-settings': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/admin': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/analytics': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/login': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/verify': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/logout': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/change-password': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/health': {
|
||||
target: 'http://localhost:8080',
|
||||
target: 'http://localhost:59188',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -3,15 +3,18 @@ module xianyu-go
|
||||
go 1.26.4
|
||||
|
||||
require (
|
||||
fyne.io/systray v1.12.2
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/go-chi/chi/v5 v5.3.0
|
||||
github.com/go-sql-driver/mysql v1.10.0
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/playwright-community/playwright-go v0.5700.1
|
||||
github.com/mxschmitt/playwright-go v0.6100.0
|
||||
github.com/pressly/goose/v3 v3.27.1
|
||||
github.com/sashabaranov/go-openai v1.41.2
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
golang.org/x/crypto v0.50.0
|
||||
golang.org/x/sync v0.20.0
|
||||
golang.org/x/sys v0.46.0
|
||||
golang.org/x/term v0.44.0
|
||||
modernc.org/sqlite v1.53.0
|
||||
)
|
||||
@@ -20,8 +23,9 @@ require (
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/deckarep/golang-set/v2 v2.8.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/go-jose/go-jose/v3 v3.0.4 // indirect
|
||||
github.com/go-jose/go-jose/v3 v3.0.5 // indirect
|
||||
github.com/go-stack/stack v1.8.1 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
@@ -32,8 +36,6 @@ require (
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/sethvargo/go-retry v0.3.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
modernc.org/libc v1.73.4 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||
fyne.io/systray v1.12.2 h1:Y8DZxgLHsVQt6rY9Zrkkg+j67S7vv/1F2viOWKPpVeA=
|
||||
fyne.io/systray v1.12.2/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -11,12 +13,14 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM=
|
||||
github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY=
|
||||
github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
|
||||
github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ=
|
||||
github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
|
||||
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
|
||||
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw=
|
||||
github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
@@ -36,10 +40,10 @@ github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLG
|
||||
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||
github.com/mxschmitt/playwright-go v0.6100.0 h1:HYNnbGZsTHz8veJyDGe4fU1iPxfvXqzmwKchzuvGCsY=
|
||||
github.com/mxschmitt/playwright-go v0.6100.0/go.mod h1:A7VtrS3j/c8ToGnSVUaOfNtQQVxi6JotUS0jeuus6r4=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/playwright-community/playwright-go v0.5700.1 h1:PNFb1byWqrTT720rEO0JL88C6Ju0EmUnR5deFLvtP/U=
|
||||
github.com/playwright-community/playwright-go v0.5700.1/go.mod h1:MlSn1dZrx8rszbCxY6x3qK89ZesJUYVx21B2JnkoNF0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.27.1 h1:6uEvcprBybDmW4hcz3gYujhARhye+GoWKhEWyzD5sh4=
|
||||
|
||||
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 171 KiB |
@@ -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 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package auth 实现 HttpOnly Cookie 会话认证,沿用 Fork 版安全基线:
|
||||
// - 无默认口令(管理员必须经 init-admin CLI 初始化)
|
||||
// - 无默认口令(管理员可经首次启动 Web UI 或 init-admin CLI 初始化)
|
||||
// - 会话存 DB(sessions 表),HttpOnly + SameSite=Lax Cookie 传递
|
||||
// - bcrypt 哈希,兼容老库无盐 SHA-26(首次登录静默升级)
|
||||
//
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
const (
|
||||
TaskAutoRate = "auto_rate"
|
||||
TaskAutoPolish = "auto_polish"
|
||||
polishItemPageSize = 20
|
||||
polishItemMaxPages = 20
|
||||
)
|
||||
|
||||
type AccountTaskClient interface {
|
||||
FetchPendingRateOrders(ctx context.Context, cookiesStr string, page, pageSize int) (*mtop.PendingRateResult, error)
|
||||
RateBuyer(ctx context.Context, cookiesStr, tradeID, feedback string) (*mtop.AccountTaskResult, error)
|
||||
FetchAllItems(ctx context.Context, cookiesStr string, pageSize, maxPages int) (*mtop.ItemListResult, error)
|
||||
PolishItem(ctx context.Context, cookiesStr, itemID string) (*mtop.AccountTaskResult, error)
|
||||
}
|
||||
|
||||
type AccountTaskSummary struct {
|
||||
TaskType string `json:"task_type"`
|
||||
Found int `json:"found"`
|
||||
Success int `json:"success"`
|
||||
Failed int `json:"failed"`
|
||||
Skipped int `json:"skipped"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Center) RunAccountTask(ctx context.Context, accountID, taskType string) (AccountTaskSummary, error) {
|
||||
allowed, err := c.accountAutomationAllowed(ctx, accountID)
|
||||
if err != nil {
|
||||
return AccountTaskSummary{TaskType: taskType}, err
|
||||
}
|
||||
if !allowed {
|
||||
return AccountTaskSummary{TaskType: taskType}, fmt.Errorf("账号已停用或暂停,无法执行任务")
|
||||
}
|
||||
settings, err := c.store.AccountTasks.Get(ctx, accountID)
|
||||
if err != nil {
|
||||
return AccountTaskSummary{TaskType: taskType}, err
|
||||
}
|
||||
switch taskType {
|
||||
case TaskAutoRate:
|
||||
return c.runAutoRate(ctx, settings)
|
||||
case TaskAutoPolish:
|
||||
return c.runAutoPolish(ctx, settings, beijingNow(), true)
|
||||
default:
|
||||
return AccountTaskSummary{TaskType: taskType}, fmt.Errorf("不支持的账号任务: %s", taskType)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Center) scanAccountTasks(ctx context.Context) {
|
||||
if c.accountTasks == nil || c.store.AccountTasks == nil {
|
||||
return
|
||||
}
|
||||
settings, err := c.store.AccountTasks.Enabled(ctx)
|
||||
if err != nil {
|
||||
c.logger.Warn("扫描账号任务配置失败", "err", err)
|
||||
return
|
||||
}
|
||||
now := beijingNow()
|
||||
for _, setting := range settings {
|
||||
allowed, err := c.accountAutomationAllowed(ctx, setting.CookieID)
|
||||
if err != nil || !allowed {
|
||||
continue
|
||||
}
|
||||
if setting.AutoRateEnabled {
|
||||
if _, err := c.runAutoRate(ctx, setting); err != nil {
|
||||
c.logger.Warn("自动评价扫描失败", "account", setting.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
if setting.AutoPolishEnabled && polishDue(setting, now) {
|
||||
if _, err := c.runAutoPolish(ctx, setting, now, false); err != nil {
|
||||
c.logger.Warn("每日擦亮失败", "account", setting.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Center) runAutoRate(ctx context.Context, settings db.AccountTaskSettings) (AccountTaskSummary, error) {
|
||||
summary := AccountTaskSummary{TaskType: TaskAutoRate}
|
||||
if c.accountTasks == nil {
|
||||
return summary, fmt.Errorf("自动评价客户端未初始化")
|
||||
}
|
||||
cookies, err := c.store.Cookies.GetValue(ctx, settings.CookieID)
|
||||
if err != nil {
|
||||
return summary, err
|
||||
}
|
||||
current := cookies
|
||||
var orders []mtop.PendingRateOrder
|
||||
for page := 1; page <= 20; page++ {
|
||||
pending, err := c.accountTasks.FetchPendingRateOrders(ctx, current, page, 50)
|
||||
if err != nil {
|
||||
return summary, err
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, pending.UpdatedCookies)
|
||||
orders = append(orders, pending.Orders...)
|
||||
if len(pending.Orders) < 50 {
|
||||
break
|
||||
}
|
||||
}
|
||||
summary.Found = len(orders)
|
||||
for _, order := range orders {
|
||||
runKey := "rate:" + settings.CookieID + ":" + order.TradeID
|
||||
claimed, err := c.store.AccountTasks.ClaimRun(ctx, db.AccountTaskRun{RunKey: runKey, CookieID: settings.CookieID,
|
||||
TaskType: TaskAutoRate, TargetID: order.TradeID}, time.Now().UTC().Unix())
|
||||
if err != nil {
|
||||
return summary, err
|
||||
}
|
||||
if !claimed {
|
||||
summary.Skipped++
|
||||
continue
|
||||
}
|
||||
result, rateErr := c.accountTasks.RateBuyer(ctx, current, order.TradeID, settings.RateContent)
|
||||
if rateErr != nil || result == nil || !result.Success {
|
||||
message := errorString(rateErr)
|
||||
if result != nil && result.Message != "" {
|
||||
message = result.Message
|
||||
}
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, message, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
summary.Failed++
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "success", 1, 0, "", 0)
|
||||
summary.Success++
|
||||
}
|
||||
_ = c.store.AccountTasks.MarkRateScan(ctx, settings.CookieID, time.Now().UTC().Unix())
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (c *Center) runAutoPolish(ctx context.Context, settings db.AccountTaskSettings, now time.Time, manual bool) (AccountTaskSummary, error) {
|
||||
summary := AccountTaskSummary{TaskType: TaskAutoPolish}
|
||||
if c.accountTasks == nil {
|
||||
return summary, fmt.Errorf("擦亮客户端未初始化")
|
||||
}
|
||||
date := now.Format("2006-01-02")
|
||||
runKey := "polish:" + settings.CookieID + ":" + date
|
||||
run := db.AccountTaskRun{RunKey: runKey, CookieID: settings.CookieID, TaskType: TaskAutoPolish, RunDate: date}
|
||||
var claimed bool
|
||||
var err error
|
||||
if manual {
|
||||
claimed, err = c.store.AccountTasks.ClaimRunImmediately(ctx, run, time.Now().UTC().Unix())
|
||||
} else {
|
||||
claimed, err = c.store.AccountTasks.ClaimRun(ctx, run, time.Now().UTC().Unix())
|
||||
}
|
||||
if err != nil || !claimed {
|
||||
if !claimed && err == nil {
|
||||
summary.Skipped = 1
|
||||
summary.Message = "今天已经执行过擦亮"
|
||||
}
|
||||
return summary, err
|
||||
}
|
||||
cookies, err := c.store.Cookies.GetValue(ctx, settings.CookieID)
|
||||
if err != nil {
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
return summary, err
|
||||
}
|
||||
items, err := c.accountTasks.FetchAllItems(ctx, cookies, polishItemPageSize, polishItemMaxPages)
|
||||
if err != nil {
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
return summary, err
|
||||
}
|
||||
current := c.persistTaskCookies(ctx, settings.CookieID, cookies, items.UpdatedCookies)
|
||||
summary.Found = len(items.Items)
|
||||
var lastError string
|
||||
for _, item := range items.Items {
|
||||
result, polishErr := c.accountTasks.PolishItem(ctx, current, item.ID)
|
||||
if polishErr != nil || result == nil || !result.Success {
|
||||
summary.Failed++
|
||||
lastError = errorString(polishErr)
|
||||
if result != nil && result.Message != "" {
|
||||
lastError = result.Message
|
||||
}
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
summary.Success++
|
||||
}
|
||||
status, retryAt := "success", int64(0)
|
||||
if summary.Failed > 0 {
|
||||
status, retryAt = "failed", time.Now().UTC().Add(10*time.Minute).Unix()
|
||||
} else {
|
||||
_ = c.store.AccountTasks.MarkPolished(ctx, settings.CookieID, date, time.Now().UTC().Unix())
|
||||
}
|
||||
_ = c.store.AccountTasks.FinishRun(ctx, runKey, status, summary.Success, summary.Failed, lastError, retryAt)
|
||||
if summary.Failed > 0 {
|
||||
return summary, fmt.Errorf("%d 个商品擦亮失败: %s", summary.Failed, lastError)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (c *Center) persistTaskCookies(ctx context.Context, accountID, oldValue, newValue string) string {
|
||||
newValue = strings.TrimSpace(newValue)
|
||||
if newValue == "" || newValue == oldValue {
|
||||
return oldValue
|
||||
}
|
||||
if err := c.store.Cookies.UpdateValueExisting(ctx, accountID, newValue); err != nil {
|
||||
c.logger.Warn("保存账号任务响应 Cookie 失败", "account", accountID, "err", err)
|
||||
return oldValue
|
||||
}
|
||||
if c.senders != nil {
|
||||
if sender, ok := c.senders.Sender(accountID); ok && sender != nil {
|
||||
sender.UpdateCookie(newValue)
|
||||
}
|
||||
}
|
||||
return newValue
|
||||
}
|
||||
|
||||
func beijingNow() time.Time {
|
||||
return time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
|
||||
}
|
||||
|
||||
func polishDue(settings db.AccountTaskSettings, now time.Time) bool {
|
||||
if settings.LastPolishDate == now.Format("2006-01-02") {
|
||||
return false
|
||||
}
|
||||
target, err := time.Parse("15:04", settings.PolishTime)
|
||||
if err != nil {
|
||||
target, _ = time.Parse("15:04", "03:00")
|
||||
}
|
||||
return now.Hour() > target.Hour() || now.Hour() == target.Hour() && now.Minute() >= target.Minute()
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
type fakeAccountTaskClient struct {
|
||||
pendingCalls int
|
||||
rateCalls int
|
||||
polishCalls int
|
||||
pending []mtop.PendingRateOrder
|
||||
items []mtop.ItemListItem
|
||||
fetchItemsErr error
|
||||
fetchPageSize int
|
||||
fetchMaxPages int
|
||||
polishErr error
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) FetchPendingRateOrders(context.Context, string, int, int) (*mtop.PendingRateResult, error) {
|
||||
f.pendingCalls++
|
||||
return &mtop.PendingRateResult{Orders: f.pending}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) RateBuyer(context.Context, string, string, string) (*mtop.AccountTaskResult, error) {
|
||||
f.rateCalls++
|
||||
return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) FetchAllItems(_ context.Context, _ string, pageSize, maxPages int) (*mtop.ItemListResult, error) {
|
||||
f.fetchPageSize, f.fetchMaxPages = pageSize, maxPages
|
||||
if f.fetchItemsErr != nil {
|
||||
return nil, f.fetchItemsErr
|
||||
}
|
||||
return &mtop.ItemListResult{Items: f.items}, nil
|
||||
}
|
||||
|
||||
func (f *fakeAccountTaskClient) PolishItem(context.Context, string, string) (*mtop.AccountTaskResult, error) {
|
||||
f.polishCalls++
|
||||
if f.polishErr != nil {
|
||||
return nil, f.polishErr
|
||||
}
|
||||
return &mtop.AccountTaskResult{Success: true, Message: "ok"}, nil
|
||||
}
|
||||
|
||||
func TestAccountTaskRateIsOrderIdempotent(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-1"}, {TradeID: "order-2"}}}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "03:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := center.RunAccountTask(ctx, "cid", TaskAutoRate)
|
||||
if err != nil || first.Success != 2 || client.rateCalls != 2 {
|
||||
t.Fatalf("first=%+v calls=%d err=%v", first, client.rateCalls, err)
|
||||
}
|
||||
second, err := center.RunAccountTask(ctx, "cid", TaskAutoRate)
|
||||
if err != nil || second.Skipped != 2 || client.rateCalls != 2 {
|
||||
t.Fatalf("second=%+v calls=%d err=%v", second, client.rateCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountTaskPolishRunsOncePerBeijingDay(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}, {ID: "item-2"}}}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || first.Success != 2 || client.polishCalls != 2 {
|
||||
t.Fatalf("first=%+v calls=%d err=%v", first, client.polishCalls, err)
|
||||
}
|
||||
if client.fetchPageSize != 20 || client.fetchMaxPages != 20 {
|
||||
t.Fatalf("unexpected item pagination: pageSize=%d maxPages=%d", client.fetchPageSize, client.fetchMaxPages)
|
||||
}
|
||||
second, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || second.Skipped != 1 || client.polishCalls != 2 {
|
||||
t.Fatalf("second=%+v calls=%d err=%v", second, client.polishCalls, err)
|
||||
}
|
||||
settings, err := store.AccountTasks.Get(ctx, "cid")
|
||||
if err != nil || settings.LastPolishDate != beijingNow().Format("2006-01-02") {
|
||||
t.Fatalf("settings=%+v err=%v", settings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualPolishReportsItemFailures(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, polishErr: errors.New("both polish APIs failed")}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
summary, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err == nil || summary.Failed != 1 || summary.Success != 0 {
|
||||
t.Fatalf("summary=%+v err=%v", summary, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualPolishCanRetryImmediatelyAfterFailure(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-1"}}, fetchItemsErr: errors.New("upstream 502")}
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
ctx := context.Background()
|
||||
if err := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "00:00"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish); err == nil {
|
||||
t.Fatal("first polish should expose the upstream failure")
|
||||
}
|
||||
client.fetchItemsErr = nil
|
||||
second, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || second.Success != 1 || second.Skipped != 0 || client.polishCalls != 1 {
|
||||
t.Fatalf("manual retry=%+v calls=%d err=%v", second, client.polishCalls, err)
|
||||
}
|
||||
third, err := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if err != nil || third.Skipped != 1 || client.polishCalls != 1 {
|
||||
t.Fatalf("successful day must remain idempotent: summary=%+v calls=%d err=%v", third, client.polishCalls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolishDueHonorsConfiguredTimeAndDate(t *testing.T) {
|
||||
now := beijingNow()
|
||||
settings := db.AccountTaskSettings{PolishTime: now.Add(2 * time.Hour).Format("15:04")}
|
||||
if polishDue(settings, now) && now.Hour() < 22 {
|
||||
t.Fatal("task must not run before configured time")
|
||||
}
|
||||
settings.PolishTime = "00:00"
|
||||
if !polishDue(settings, now) {
|
||||
t.Fatal("task should be due after midnight")
|
||||
}
|
||||
settings.LastPolishDate = now.Format("2006-01-02")
|
||||
if polishDue(settings, now) {
|
||||
t.Fatal("task must not run twice on the same Beijing date")
|
||||
}
|
||||
}
|
||||
@@ -86,15 +86,16 @@ type Notifier interface {
|
||||
// Center 是统一自动化处理中心。
|
||||
// 它只接收已经分类好的系统事件或计划任务,不处理用户消息;用户消息由 engine 的回复链处理。
|
||||
type Center struct {
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
logger *slog.Logger
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
cardLocks sync.Map
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
accountTasks AccountTaskClient
|
||||
logger *slog.Logger
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
cardLocks sync.Map
|
||||
}
|
||||
|
||||
// New 构造自动化中心。
|
||||
@@ -102,12 +103,16 @@ func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Center{store: store, senders: senders, mtop: mtop.NewClient(), logger: logger.With("subsys", "automation")}
|
||||
client := mtop.NewClient()
|
||||
return &Center{store: store, senders: senders, mtop: client, accountTasks: client, logger: logger.With("subsys", "automation")}
|
||||
}
|
||||
|
||||
// SetMTop 注入 mtop 客户端(确认发货用)。未注入时使用默认 HTTP 实现。
|
||||
func (c *Center) SetMTop(m mtop.Client) { c.mtop = m }
|
||||
|
||||
// SetAccountTaskClient overrides automatic rating/polish transport for tests.
|
||||
func (c *Center) SetAccountTaskClient(client AccountTaskClient) { c.accountTasks = client }
|
||||
|
||||
// SetOrderDetailFetcher 注入订单详情查询能力。
|
||||
func (c *Center) SetOrderDetailFetcher(fetcher OrderDetailFetcher) {
|
||||
c.fetcher = fetcher
|
||||
|
||||
@@ -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, "记得及时发货") ||
|
||||
@@ -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 {
|
||||
|
||||
@@ -80,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
|
||||
|
||||
@@ -60,6 +60,7 @@ func (s *Scheduler) Wait() {
|
||||
|
||||
func (s *Scheduler) scan(ctx context.Context) {
|
||||
s.runDeferredTasks(ctx)
|
||||
s.center.scanAccountTasks(ctx)
|
||||
if recovered, err := s.center.store.Automation.RecoverDefinitelyUnsentReviewRuns(ctx); err != nil {
|
||||
s.center.logger.Warn("恢复历史求评价未发送任务失败", "err", err)
|
||||
} else if recovered > 0 {
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package browser 用 playwright-go 在进程内驱动 Chromium。
|
||||
// 首次使用时自动下载 Chromium(playwright.Install),无需手动启动外部服务。
|
||||
// 安装包提供预置 runtime;开发环境没有预置 runtime 时才自动下载。
|
||||
package browser
|
||||
|
||||
import (
|
||||
@@ -10,11 +10,13 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"xianyu-go/internal/xianyu"
|
||||
@@ -58,6 +60,48 @@ func skipPlaywrightBrowserDownload() bool {
|
||||
}
|
||||
}
|
||||
|
||||
func packagedPlaywrightRuntimeReady() bool {
|
||||
driverDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_DRIVER_PATH"))
|
||||
if driverDir == "" {
|
||||
return false
|
||||
}
|
||||
nodeReady := false
|
||||
if nodePath := strings.TrimSpace(os.Getenv("PLAYWRIGHT_NODEJS_PATH")); nodePath != "" {
|
||||
_, err := os.Stat(nodePath)
|
||||
nodeReady = err == nil
|
||||
} else {
|
||||
nodeName := "node"
|
||||
if runtime.GOOS == "windows" {
|
||||
nodeName = "node.exe"
|
||||
}
|
||||
_, err := os.Stat(filepath.Join(driverDir, nodeName))
|
||||
nodeReady = err == nil
|
||||
}
|
||||
if !nodeReady {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(driverDir, "package", "cli.js")); err != nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")) != "" {
|
||||
return true
|
||||
}
|
||||
browserDir := strings.TrimSpace(os.Getenv("PLAYWRIGHT_BROWSERS_PATH"))
|
||||
if browserDir == "" {
|
||||
return false
|
||||
}
|
||||
matches, err := filepath.Glob(filepath.Join(browserDir, "chromium-*"))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, match := range matches {
|
||||
if info, statErr := os.Stat(match); statErr == nil && info.IsDir() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Manager 管理浏览器生命周期与按账号复用的上下文池。
|
||||
type Manager struct {
|
||||
pw *playwright.Playwright
|
||||
@@ -108,6 +152,9 @@ func NewManager(logger *slog.Logger) *Manager {
|
||||
renewLocks: make(map[string]*sync.Mutex),
|
||||
renewSlots: make(chan struct{}, 3),
|
||||
installFn: func() error {
|
||||
if packagedPlaywrightRuntimeReady() {
|
||||
return nil
|
||||
}
|
||||
opts := &playwright.RunOptions{
|
||||
Browsers: []string{"chromium"},
|
||||
Verbose: false,
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
playwright "github.com/playwright-community/playwright-go"
|
||||
playwright "github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
// TestChromiumLaunchArgs 验证启动参数含关键安全/反检测项。
|
||||
@@ -28,6 +31,62 @@ func TestChromiumLaunchArgs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPackagedPlaywrightRuntimeReady(t *testing.T) {
|
||||
runtimeRoot := t.TempDir()
|
||||
driverDir := filepath.Join(runtimeRoot, "driver")
|
||||
browserDir := filepath.Join(runtimeRoot, "browsers")
|
||||
if err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodeName := "node"
|
||||
if runtime.GOOS == "windows" {
|
||||
nodeName = "node.exe"
|
||||
}
|
||||
for _, path := range []string{
|
||||
filepath.Join(driverDir, nodeName),
|
||||
filepath.Join(driverDir, "package", "cli.js"),
|
||||
} {
|
||||
if err := os.WriteFile(path, []byte("runtime"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
t.Setenv("PLAYWRIGHT_DRIVER_PATH", driverDir)
|
||||
t.Setenv("PLAYWRIGHT_BROWSERS_PATH", browserDir)
|
||||
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "")
|
||||
if !packagedPlaywrightRuntimeReady() {
|
||||
t.Fatal("预置 Playwright runtime 应被识别")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPackagedPlaywrightRuntimeReadyWithExternalNode(t *testing.T) {
|
||||
runtimeRoot := t.TempDir()
|
||||
driverDir := filepath.Join(runtimeRoot, "driver")
|
||||
browserDir := filepath.Join(runtimeRoot, "browsers")
|
||||
if err := os.MkdirAll(filepath.Join(driverDir, "package"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(browserDir, "chromium-1228"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(driverDir, "package", "cli.js"), []byte("runtime"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodePath := filepath.Join(runtimeRoot, "node")
|
||||
if err := os.WriteFile(nodePath, []byte("runtime"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PLAYWRIGHT_DRIVER_PATH", driverDir)
|
||||
t.Setenv("PLAYWRIGHT_NODEJS_PATH", nodePath)
|
||||
t.Setenv("PLAYWRIGHT_BROWSERS_PATH", browserDir)
|
||||
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "")
|
||||
if !packagedPlaywrightRuntimeReady() {
|
||||
t.Fatal("配置外部 Node.js 的预置 Playwright runtime 应被识别")
|
||||
}
|
||||
}
|
||||
|
||||
// newTestManager 构造一个不触网的 Manager(pool 空,maxSize 小便于测试驱逐)。
|
||||
func newTestManager(maxSize int) *Manager {
|
||||
return &Manager{
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
// loginFormSelectors 登录表单选择器,主页面和 iframe 中都要找。
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
// sliderSelectors 按优先级排列的滑块相关选择器(移植自 xianyu_slider_stealth.py)。
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
"github.com/mxschmitt/playwright-go"
|
||||
)
|
||||
|
||||
var fallbackTrackSelectors = []string{
|
||||
|
||||