Compare commits
55 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 98631afdc5 | |||
| bc4e739e09 | |||
| 9bffdb7026 | |||
| 42c8b66a01 | |||
| 81b2942cad | |||
| 4b1dea3d3c | |||
| 0d665ad0fe | |||
| 67d925bb91 | |||
| bf0e1656ab | |||
| 66d07781be | |||
| 99c16652a7 | |||
| cc4aa1c00e | |||
| 15eceea38a | |||
| a9dbc2661d | |||
| ebc94ec9a0 | |||
| 98cf8666f6 | |||
| ff3593f057 | |||
| 74422b1848 | |||
| 84f87cd168 | |||
| 386e9269bf | |||
| 17a71b1e2a | |||
| 1b4f029602 | |||
| 2246752724 | |||
| a303782ab4 | |||
| 2cac0cdfee | |||
| 75d334680b | |||
| 35fa5a6560 | |||
| dbd3c88d32 | |||
| 33e29573ca | |||
| 4a80382b60 | |||
| 8eaaf5781a | |||
| 111cc0439c | |||
| a97537660e | |||
| 664d8a2594 | |||
| 6ede88b01b | |||
| 6b42cff492 | |||
| cc1150c1ac | |||
| 032c8e526f | |||
| d442f538e1 | |||
| 20921c6317 | |||
| 097aed6f40 | |||
| a75d57f309 | |||
| fc3bfe09f4 | |||
| b49ef238dd | |||
| 9212273e04 | |||
| 0af640881e | |||
| 7c3e2be828 | |||
| aa0ecfc4f1 | |||
| 0b019ab4b9 | |||
| 5298e30bd0 | |||
| 3a26aaa155 | |||
| 14270ab02d | |||
| edd4e90719 | |||
| 2f93e24a39 | |||
| 49e1cef31c |
@@ -6,6 +6,9 @@ backed/cmd/server/cpdaily-new
|
||||
backed/*.log
|
||||
backed/*.har
|
||||
|
||||
# 本地/生产配置文件(含敏感凭证,禁止入库;模板见 backed/config.toml.example)
|
||||
backed/config.toml
|
||||
|
||||
# Frontend build (rebuilt by Docker multi-stage)
|
||||
backed/dist/
|
||||
frondend/dist/
|
||||
@@ -26,3 +29,6 @@ Thumbs.db
|
||||
|
||||
# Docker
|
||||
*.tar
|
||||
|
||||
# Local DB
|
||||
backed/*.db
|
||||
|
||||
+22
-36
@@ -1,6 +1,6 @@
|
||||
when:
|
||||
- event: tag
|
||||
branch: [v*]
|
||||
tag: v*
|
||||
|
||||
clone:
|
||||
git:
|
||||
@@ -26,33 +26,18 @@ steps:
|
||||
|
||||
IMAGE_TAG="${CI_COMMIT_TAG:-latest}"
|
||||
|
||||
# 确保网络存在
|
||||
docker network create likedream-net 2>/dev/null || true
|
||||
# 应用配置由宿主机 /opt/cpdaily-xiaozhushou/config.toml 运维维护
|
||||
# (已移出版本库,避免密钥入库;容器以只读挂载方式读取)
|
||||
|
||||
# ============================================================
|
||||
# 第一步:初始化 1Panel 站点配置(首次部署时才需要)
|
||||
# ============================================================
|
||||
# nginx 配置文件在 git clone 后位于 deploy/nginx/ 目录
|
||||
# 同步配置文件到 /opt/cpdaily-xiaozhushou/config.toml
|
||||
mkdir -p /opt/cpdaily-xiaozhushou
|
||||
cp backed/config.toml /opt/cpdaily-xiaozhushou/config.toml
|
||||
|
||||
if ! docker exec 1Panel-openresty-ESmn ls /www/sites/xiaozhushou/proxy/api.conf 2>/dev/null; then
|
||||
echo "=== 首次部署:创建 1Panel 站点配置 ==="
|
||||
docker exec 1Panel-openresty-ESmn mkdir -p /www/sites/xiaozhushou/proxy /www/sites/xiaozhushou/log
|
||||
docker cp deploy/nginx/xiaozhushou.conf 1Panel-openresty-ESmn:/usr/local/openresty/nginx/conf/conf.d/xiaozhushou.conf
|
||||
docker cp deploy/nginx/api.conf 1Panel-openresty-ESmn:/www/sites/xiaozhushou/proxy/api.conf
|
||||
docker exec 1Panel-openresty-ESmn nginx -s reload
|
||||
echo " 1Panel 站点配置完成 ✓"
|
||||
fi
|
||||
|
||||
# ============================================================
|
||||
# 第二步:读取当前代理端口,确定蓝绿状态
|
||||
# 第一步:读取当前反代端口,确定蓝绿状态
|
||||
# 反代入口为 1Panel 站点 jinrixiaoyuan.top(frps 公网链路):
|
||||
# /www/sites/jinrixiaoyuan.top/proxy/root.conf → proxy_pass http://127.0.0.1:8884|8885
|
||||
# ============================================================
|
||||
CURRENT_PORT=$(docker exec 1Panel-openresty-ESmn \
|
||||
grep -o 'proxy_pass http://10.10.10.128:[0-9]\+' \
|
||||
/www/sites/xiaozhushou/proxy/api.conf | grep -o '[0-9]\+$')
|
||||
echo "=== 当前 1Panel 反代端口: $CURRENT_PORT ==="
|
||||
grep -oE 'proxy_pass http://[0-9.]+:[0-9]+' \
|
||||
/www/sites/jinrixiaoyuan.top/proxy/root.conf | grep -o '[0-9]\+$')
|
||||
echo "=== 当前反代端口: $CURRENT_PORT ==="
|
||||
|
||||
if [ "$CURRENT_PORT" = "8884" ]; then
|
||||
PORT_ACTIVE=8884
|
||||
@@ -61,9 +46,8 @@ steps:
|
||||
PORT_ACTIVE=8885
|
||||
PORT_STANDBY=8884
|
||||
else
|
||||
echo "未知当前端口 $CURRENT_PORT,默认使用 8884/8885"
|
||||
PORT_ACTIVE=8884
|
||||
PORT_STANDBY=8885
|
||||
echo "ERROR: 未知反代端口 $CURRENT_PORT,中止部署(期望 8884/8885)"
|
||||
exit 1
|
||||
fi
|
||||
echo " 活跃: $PORT_ACTIVE | 备用: $PORT_STANDBY"
|
||||
|
||||
@@ -71,19 +55,20 @@ steps:
|
||||
docker rm -f cpdaily-xiaozhushou-new 2>/dev/null || true
|
||||
|
||||
# ============================================================
|
||||
# 第三步:在备用端口启动新容器
|
||||
# 第二步:在备用端口启动新容器
|
||||
# ============================================================
|
||||
echo "=== 蓝绿部署: 启动新容器 on :$PORT_STANDBY (image: $IMAGE_TAG) ==="
|
||||
|
||||
docker run -d --name cpdaily-xiaozhushou-new \
|
||||
--restart unless-stopped \
|
||||
--network likedream-net \
|
||||
-e TZ=Asia/Shanghai \
|
||||
-p $PORT_STANDBY:8093 \
|
||||
-v /opt/cpdaily-xiaozhushou/config.toml:/app/config.toml:ro \
|
||||
cpdaily-xiaozhushou:$IMAGE_TAG
|
||||
|
||||
# ============================================================
|
||||
# 第四步:健康检查
|
||||
# 第三步:健康检查
|
||||
# ============================================================
|
||||
HEALTHY=false
|
||||
for i in $(seq 1 15); do
|
||||
@@ -104,45 +89,46 @@ steps:
|
||||
echo " 新容器已就绪 ✓"
|
||||
|
||||
# ============================================================
|
||||
# 第五步:切换 1Panel 代理到备用端口
|
||||
# 第四步:切换 1Panel 反代到备用端口
|
||||
# ============================================================
|
||||
echo "=== 切换 1Panel 反代 :$PORT_ACTIVE → :$PORT_STANDBY ==="
|
||||
docker exec 1Panel-openresty-ESmn \
|
||||
sed -i "s|:$PORT_ACTIVE|:$PORT_STANDBY|g" \
|
||||
/www/sites/xiaozhushou/proxy/api.conf
|
||||
/www/sites/jinrixiaoyuan.top/proxy/root.conf
|
||||
docker exec 1Panel-openresty-ESmn nginx -s reload
|
||||
echo " Nginx 热加载完成(零中断)✓"
|
||||
|
||||
# ============================================================
|
||||
# 第六步:停止旧容器
|
||||
# 第五步:停止旧容器
|
||||
# ============================================================
|
||||
echo "=== 清理旧容器 ==="
|
||||
docker stop cpdaily-xiaozhushou 2>/dev/null || true
|
||||
docker rm cpdaily-xiaozhushou 2>/dev/null || true
|
||||
|
||||
# ============================================================
|
||||
# 第七步:在活跃端口启动正式容器
|
||||
# 第六步:在活跃端口启动正式容器
|
||||
# ============================================================
|
||||
echo "=== 启动正式容器 on :$PORT_ACTIVE ==="
|
||||
docker run -d --name cpdaily-xiaozhushou \
|
||||
--restart unless-stopped \
|
||||
--network likedream-net \
|
||||
-e TZ=Asia/Shanghai \
|
||||
-p $PORT_ACTIVE:8093 \
|
||||
-v /opt/cpdaily-xiaozhushou/config.toml:/app/config.toml:ro \
|
||||
cpdaily-xiaozhushou:$IMAGE_TAG
|
||||
|
||||
# ============================================================
|
||||
# 第八步:切回 1Panel 代理到活跃端口
|
||||
# 第七步:切回 1Panel 反代到活跃端口
|
||||
# ============================================================
|
||||
echo "=== 切回 1Panel 反代 :$PORT_STANDBY → :$PORT_ACTIVE ==="
|
||||
docker exec 1Panel-openresty-ESmn \
|
||||
sed -i "s|:$PORT_STANDBY|:$PORT_ACTIVE|g" \
|
||||
/www/sites/xiaozhushou/proxy/api.conf
|
||||
/www/sites/jinrixiaoyuan.top/proxy/root.conf
|
||||
docker exec 1Panel-openresty-ESmn nginx -s reload
|
||||
echo " Nginx 热加载完成(零中断)✓"
|
||||
|
||||
# ============================================================
|
||||
# 第九步:清理
|
||||
# 第八步:清理
|
||||
# ============================================================
|
||||
echo "=== 清理 ==="
|
||||
docker rm -f cpdaily-xiaozhushou-new 2>/dev/null || true
|
||||
|
||||
@@ -24,6 +24,8 @@ RUN go build -ldflags="-s -w" -o server ./cmd/server/
|
||||
# ============================================================
|
||||
FROM alpine:latest
|
||||
RUN apk add --no-cache ca-certificates tzdata
|
||||
# 时区固定为北京时间(tzdata 已安装;进程层 main.go 另有 time.Local 兜底)
|
||||
ENV TZ=Asia/Shanghai
|
||||
COPY --from=backend-builder /build/server /app/server
|
||||
COPY --from=frontend-builder /build/dist /app/dist
|
||||
WORKDIR /app
|
||||
|
||||
+41
-13
@@ -11,6 +11,7 @@ import (
|
||||
"cpdaily-new/internal/handler"
|
||||
"cpdaily-new/internal/middleware"
|
||||
"cpdaily-new/internal/ratelimit"
|
||||
"cpdaily-new/internal/service"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/filesystem"
|
||||
@@ -22,15 +23,33 @@ func main() {
|
||||
log.Fatalf("加载配置失败: %v", err)
|
||||
}
|
||||
|
||||
// 全局时区固定为中国标准时间(必须在 database.Init 之前设置:
|
||||
// DSN 的 loc=Local 跟随 time.Local,影响数据库 datetime 读写序列化)。
|
||||
// 运行镜像若不设 TZ 默认 UTC,会让所有记录/查询/统计/输出偏移 8 小时
|
||||
// (前端展示为"美国时间"),每月 1 日与每日 0-8 点的边界计算也会错位。
|
||||
loc, err := time.LoadLocation("Asia/Shanghai")
|
||||
if err != nil {
|
||||
log.Fatalf("加载时区 Asia/Shanghai 失败: %v", err)
|
||||
}
|
||||
time.Local = loc
|
||||
|
||||
// 连接数据库
|
||||
database.Init()
|
||||
|
||||
// 连接 Redis(验证码存储/限流)
|
||||
service.InitRedis()
|
||||
|
||||
// 启动限流记录定时清理(每5分钟清理一次)
|
||||
ratelimit.Cleanup(5 * time.Minute)
|
||||
|
||||
// 创建 Fiber 应用
|
||||
app := fiber.New(fiber.Config{
|
||||
AppName: "Cpdaily New",
|
||||
// 信任 openresty 反代(frpc 经 PROXY protocol 透传后,openresty 直接来源为 127.0.0.1;
|
||||
// 宿主机 docker NAT 场景来源为 172.22.0.1),从 X-Forwarded-For 取真实客户端 IP
|
||||
TrustedProxies: []string{"172.22.0.0/16", "127.0.0.1"},
|
||||
EnableTrustedProxyCheck: true,
|
||||
ProxyHeader: fiber.HeaderXForwardedFor,
|
||||
})
|
||||
|
||||
// 中间件
|
||||
@@ -49,6 +68,7 @@ func main() {
|
||||
auth.Post("/generate-invite", middleware.AuthRequired(), handler.GenerateMyInviteCode)
|
||||
auth.Get("/my-invite", middleware.AuthRequired(), handler.GetMyInviteInfo)
|
||||
auth.Post("/redeem-invite", middleware.AuthRequired(), handler.RedeemInviteReward)
|
||||
auth.Post("/guide/complete", middleware.AuthRequired(), handler.CompleteGuide)
|
||||
|
||||
// 签到任务相关
|
||||
task := api.Group("/task", middleware.AuthRequired())
|
||||
@@ -69,12 +89,14 @@ func main() {
|
||||
// CDK 兑换
|
||||
cdk := api.Group("/cdk", middleware.AuthRequired())
|
||||
cdk.Post("/redeem", handler.UserRedeemCDK)
|
||||
cdk.Get("/vip-info", handler.GetUserVipInfo)
|
||||
|
||||
// 设备绑定
|
||||
device := api.Group("/device")
|
||||
device.Post("/generate", middleware.AuthRequired(), handler.GenerateDeviceQr)
|
||||
device.Post("/submit", handler.SubmitDeviceCode)
|
||||
device.Get("/status", middleware.AuthRequired(), handler.GetDeviceStatus)
|
||||
device.Post("/random-bind", middleware.AuthRequired(), handler.RandomBindDevice)
|
||||
|
||||
// 管理后台 API
|
||||
admin := api.Group("/admin")
|
||||
@@ -87,32 +109,37 @@ func main() {
|
||||
adminAuth := api.Group("/admin", middleware.AdminAuthRequired())
|
||||
adminAuth.Get("/cdks", handler.ListCDKs)
|
||||
adminAuth.Post("/cdks", handler.GenerateCDK)
|
||||
adminAuth.Get("/all-cdks", handler.ListAllCDKs)
|
||||
adminAuth.Put("/cdks/:id/status", handler.UpdateCDKStatus)
|
||||
// 全量数据仅超管可见(代理只能看自己生成的)
|
||||
adminAuth.Get("/all-cdks", middleware.AdminOnly(), handler.ListAllCDKs)
|
||||
adminAuth.Get("/agents", handler.ListSubAgents)
|
||||
adminAuth.Post("/agents", handler.CreateSubAgent)
|
||||
adminAuth.Put("/agents/:id", handler.UpdateSubAgent)
|
||||
adminAuth.Get("/agents/:id", handler.GetAgentDetail)
|
||||
adminAuth.Put("/agents/:id/password", handler.UpdateAgentPassword)
|
||||
adminAuth.Put("/agents/:id/status", handler.UpdateAgentStatus)
|
||||
adminAuth.Get("/all-agents", handler.ListAllAgents)
|
||||
adminAuth.Get("/agent/list", handler.ListAllAgents)
|
||||
adminAuth.Get("/all-agents", middleware.AdminOnly(), handler.ListAllAgents)
|
||||
adminAuth.Get("/agent/list", middleware.AdminOnly(), handler.ListAllAgents)
|
||||
|
||||
// 管理后台 - 用户管理(仅admin)
|
||||
adminAuth.Get("/users", middleware.AdminOnly(), handler.ListUsers)
|
||||
adminAuth.Get("/users/:id", middleware.AdminOnly(), handler.GetUserDetail)
|
||||
adminAuth.Put("/users/:id/status", middleware.AdminOnly(), handler.UpdateUserStatus)
|
||||
// 任务执行日志查询(供"当天执行总次数"卡片点击查看)
|
||||
adminAuth.Get("/task-logs", middleware.AdminOnly(), handler.AdminListTaskLogs)
|
||||
|
||||
// 管理后台 - 公告
|
||||
adminAuth.Post("/announcements", handler.CreateAnnouncement)
|
||||
adminAuth.Get("/announcements", handler.ListAnnouncements)
|
||||
adminAuth.Get("/announcements/:id", handler.GetAnnouncement)
|
||||
adminAuth.Put("/announcements/:id", handler.UpdateAnnouncement)
|
||||
adminAuth.Delete("/announcements/:id", handler.DeleteAnnouncement)
|
||||
// 管理后台 - 公告(公告面向全站代理/用户推送,管理操作仅超管;代理/管理员通过 /my-announcements 收取公告)
|
||||
adminAuth.Post("/announcements", middleware.AdminOnly(), handler.CreateAnnouncement)
|
||||
adminAuth.Get("/announcements", middleware.AdminOnly(), handler.ListAnnouncements)
|
||||
adminAuth.Get("/announcements/:id", middleware.AdminOnly(), handler.GetAnnouncement)
|
||||
adminAuth.Put("/announcements/:id", middleware.AdminOnly(), handler.UpdateAnnouncement)
|
||||
adminAuth.Delete("/announcements/:id", middleware.AdminOnly(), handler.DeleteAnnouncement)
|
||||
|
||||
// 管理后台 - 系统设置
|
||||
adminAuth.Get("/settings", handler.GetSettings)
|
||||
adminAuth.Post("/settings", handler.UpdateSetting)
|
||||
adminAuth.Put("/settings", handler.UpdateSetting)
|
||||
// 管理后台 - 系统设置(全站计费/奖励/SMTP 配置,仅超管)
|
||||
adminAuth.Get("/settings", middleware.AdminOnly(), handler.GetSettings)
|
||||
adminAuth.Post("/settings", middleware.AdminOnly(), handler.UpdateSetting)
|
||||
adminAuth.Put("/settings", middleware.AdminOnly(), handler.UpdateSetting)
|
||||
adminAuth.Post("/settings/test-mail", middleware.AdminOnly(), handler.TestMail)
|
||||
|
||||
// 管理后台 - 我的公告(代理/管理员视角,共用普通用户公告处理器,但 target_type=agent)
|
||||
adminAuth.Get("/my-announcements", handler.ListUserAnnouncements)
|
||||
@@ -155,6 +182,7 @@ func main() {
|
||||
// 管理后台 - 待适配学校
|
||||
adminAuth.Get("/pending-schools", handler.AdminListPendingSchools)
|
||||
adminAuth.Post("/pending-schools/:id/mark-done", handler.AdminMarkSchoolDone)
|
||||
adminAuth.Post("/pending-schools/:id/reject", handler.AdminRejectSchool)
|
||||
|
||||
// 健康检查(用于蓝绿部署)
|
||||
app.Get("/health", func(c *fiber.Ctx) error {
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
[server]
|
||||
port = 8093
|
||||
mode = "release"
|
||||
|
||||
[database]
|
||||
host = "10.10.10.128"
|
||||
port = 3306
|
||||
user = "xiaozhushou"
|
||||
password = "bh7S4JzPVyY0VLJh44i"
|
||||
dbname = "xiaozhushou"
|
||||
|
||||
[jwt]
|
||||
secret = "cpdaily-new-jwt-secret-key-2026"
|
||||
accessExpire = 3600
|
||||
refreshExpire = 864000
|
||||
|
||||
[captcha]
|
||||
width = 150
|
||||
height = 46
|
||||
length = 4
|
||||
|
||||
[cpdaily]
|
||||
appVersion = "9.8.8"
|
||||
systemVersion = "iOS 17"
|
||||
calVersion = "first_v4"
|
||||
sliderIds = ["1018764144934965", "sdhyxy", "hqdx"]
|
||||
captchaBaseUrl = "http://10.10.10.128:8890"
|
||||
captchaApiKey = "baca122..."
|
||||
|
||||
[agent]
|
||||
systemCdkPrice = 10.0
|
||||
@@ -0,0 +1,43 @@
|
||||
# 配置文件模板:复制为 config.toml 并按环境填写真实值。
|
||||
# 注意:本文件随仓库分发,禁止填写任何真实凭证(数据库/Redis/JWT/第三方密钥)。
|
||||
# 生产配置存放于服务器 /opt/cpdaily-xiaozhushou/config.toml(容器以挂载方式读取),
|
||||
# 请勿将生产 config.toml 提交进 git。
|
||||
|
||||
[server]
|
||||
port = 8093
|
||||
mode = "release"
|
||||
|
||||
[database]
|
||||
host = "127.0.0.1"
|
||||
port = 3306
|
||||
user = "your_db_user"
|
||||
password = "your_db_password"
|
||||
dbname = "xiaozhushou"
|
||||
|
||||
[jwt]
|
||||
# 生产环境必须使用强随机密钥(openssl rand -hex 32),示例值仅用于本地开发,切勿用于生产。
|
||||
secret = "dev-only-change-me-please"
|
||||
accessExpire = 3600
|
||||
refreshExpire = 864000
|
||||
|
||||
[captcha]
|
||||
width = 150
|
||||
height = 46
|
||||
length = 4
|
||||
|
||||
[cpdaily]
|
||||
appVersion = "9.8.8"
|
||||
systemVersion = "iOS 17"
|
||||
calVersion = "first_v4"
|
||||
sliderIds = ["1018764144934965", "sdhyxy", "hqdx"]
|
||||
captchaBaseUrl = "http://127.0.0.1:8890"
|
||||
captchaApiKey = "your_captcha_api_key"
|
||||
|
||||
[agent]
|
||||
systemCdkPrice = 10.0
|
||||
|
||||
[redis]
|
||||
host = "127.0.0.1"
|
||||
port = 6379
|
||||
password = "your_redis_password"
|
||||
db = 0
|
||||
@@ -19,6 +19,8 @@ require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
@@ -26,6 +28,7 @@ require (
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/redis/go-redis/v9 v9.7.0 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
|
||||
@@ -8,6 +8,10 @@ github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1
|
||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
|
||||
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
@@ -32,6 +36,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
|
||||
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
|
||||
@@ -12,10 +12,19 @@ type Config struct {
|
||||
Database DatabaseConfig `toml:"database"`
|
||||
Jwt JwtConfig `toml:"jwt"`
|
||||
Captcha CaptchaConfig `toml:"captcha"`
|
||||
Redis RedisConfig `toml:"redis"`
|
||||
Cpdaily CpdailyConfig `toml:"cpdaily"`
|
||||
Agent AgentConfig `toml:"agent"`
|
||||
}
|
||||
|
||||
// RedisConfig 验证码等缓存使用的 Redis 配置
|
||||
type RedisConfig struct {
|
||||
Host string `toml:"host"`
|
||||
Port int `toml:"port"`
|
||||
Password string `toml:"password"`
|
||||
Db int `toml:"db"`
|
||||
}
|
||||
|
||||
// AgentConfig 代理系统配置
|
||||
type AgentConfig struct {
|
||||
SystemCdkPrice float64 `toml:"systemCdkPrice"` // CDK系统底价(元)
|
||||
|
||||
@@ -7,27 +7,42 @@ import (
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// SysUserListItem 用户列表项
|
||||
type SysUserListItem struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
SchoolID string `json:"schoolId"`
|
||||
SchoolName string `json:"schoolName"`
|
||||
StudentID string `json:"studentId"`
|
||||
RealName string `json:"realName"`
|
||||
MobileCode string `json:"mobileCode"`
|
||||
MobileType string `json:"mobileType"`
|
||||
SignCount int `json:"signCount"`
|
||||
InviteReward float64 `json:"inviteReward"`
|
||||
InvitedCount int `json:"invitedCount"`
|
||||
TaskCount int64 `json:"taskCount"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
LastLoginAt string `json:"lastLoginAt"`
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
SchoolID string `json:"schoolId"`
|
||||
SchoolName string `json:"schoolName"`
|
||||
StudentID string `json:"studentId"`
|
||||
RealName string `json:"realName"`
|
||||
MobileCode string `json:"mobileCode"`
|
||||
MobileType string `json:"mobileType"`
|
||||
SignCount int `json:"signCount"`
|
||||
InviteReward float64 `json:"inviteReward"`
|
||||
InvitedCount int `json:"invitedCount"`
|
||||
InviterID *uint `json:"inviterId"` // 邀请人用户ID(null=非邀请注册)
|
||||
InviterName string `json:"inviterName"` // 邀请人展示名(姓名优先,其次用户名)
|
||||
TaskCount int64 `json:"taskCount"`
|
||||
ExecutedCount int64 `json:"executedCount"` // 累计成功执行次数
|
||||
VipStatus string `json:"vipStatus"` // vip: active / expired / none
|
||||
VipExpireAt string `json:"vipExpireAt"` // VIP 到期时间,未开通为空
|
||||
TodayStatus string `json:"todayStatus"` // today: success / fail / none
|
||||
Status string `json:"status"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
LastLoginAt string `json:"lastLoginAt"`
|
||||
}
|
||||
|
||||
// inviterDisplay 邀请人展示名:姓名优先,其次用户名
|
||||
func inviterDisplay(username, realName string) string {
|
||||
if realName != "" {
|
||||
return realName
|
||||
}
|
||||
return username
|
||||
}
|
||||
|
||||
// ListUsers 获取用户列表(仅admin)
|
||||
@@ -87,36 +102,136 @@ func ListUsers(c *fiber.Ctx) error {
|
||||
taskCountMap[tc.UserID] = tc.Count
|
||||
}
|
||||
|
||||
// 累计成功执行次数(cp_task_logs is_success=1)
|
||||
executedMap := make(map[uint]int64)
|
||||
// 今天执行状态(success/fail/none)
|
||||
todayStatusMap := make(map[uint]string)
|
||||
if len(users) > 0 {
|
||||
userIDs := make([]uint, len(users))
|
||||
for i, u := range users {
|
||||
userIDs[i] = u.ID
|
||||
}
|
||||
|
||||
type LogStat struct {
|
||||
UserID uint
|
||||
Count int64
|
||||
MaxStatus int
|
||||
}
|
||||
var logStats []LogStat
|
||||
database.DB.Model(&model.CpTaskLog{}).
|
||||
Select("user_id, COUNT(*) as count, MAX(is_success) as max_status").
|
||||
Where("user_id IN ? AND is_success = 1", userIDs).
|
||||
Group("user_id").
|
||||
Scan(&logStats)
|
||||
for _, ls := range logStats {
|
||||
executedMap[ls.UserID] = ls.Count
|
||||
}
|
||||
|
||||
// 今天 00:00 起的日志
|
||||
todayStart := time.Now().Format("2006-01-02") + " 00:00:00"
|
||||
var todayLogs []model.CpTaskLog
|
||||
database.DB.Select("user_id, is_success").
|
||||
Where("user_id IN ? AND created_at >= ?", userIDs, todayStart).
|
||||
Find(&todayLogs)
|
||||
for _, tl := range todayLogs {
|
||||
if tl.IsSuccess {
|
||||
todayStatusMap[tl.UserID] = "success"
|
||||
} else if todayStatusMap[tl.UserID] != "success" {
|
||||
todayStatusMap[tl.UserID] = "fail"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 邀请人信息(本页用户的 inviter_id 去重后一次查询)
|
||||
inviterNameMap := make(map[uint]string)
|
||||
if len(users) > 0 {
|
||||
inviterIDs := make([]uint, 0, len(users))
|
||||
seen := make(map[uint]bool)
|
||||
for _, u := range users {
|
||||
if u.InviterID != nil && !seen[*u.InviterID] {
|
||||
seen[*u.InviterID] = true
|
||||
inviterIDs = append(inviterIDs, *u.InviterID)
|
||||
}
|
||||
}
|
||||
if len(inviterIDs) > 0 {
|
||||
var inviters []model.SysUser
|
||||
database.DB.Select("id, username, real_name").Where("id IN ?", inviterIDs).Find(&inviters)
|
||||
for _, iv := range inviters {
|
||||
inviterNameMap[iv.ID] = inviterDisplay(iv.Username, iv.RealName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items := make([]SysUserListItem, 0, len(users))
|
||||
for _, u := range users {
|
||||
lastLogin := ""
|
||||
if u.LastLoginAt != nil {
|
||||
lastLogin = u.LastLoginAt.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
todayStatus := todayStatusMap[u.ID]
|
||||
if todayStatus == "" {
|
||||
todayStatus = "none"
|
||||
}
|
||||
inviterName := ""
|
||||
if u.InviterID != nil {
|
||||
inviterName = inviterNameMap[*u.InviterID]
|
||||
}
|
||||
// VIP 状态:active=有效期内 / expired=已过期 / none=未开通
|
||||
vipStatus := "none"
|
||||
vipExpireAt := ""
|
||||
if u.VipExpireAt != nil {
|
||||
vipExpireAt = u.VipExpireAt.Format("2006-01-02 15:04")
|
||||
if u.VipExpireAt.After(time.Now()) {
|
||||
vipStatus = "active"
|
||||
} else {
|
||||
vipStatus = "expired"
|
||||
}
|
||||
}
|
||||
items = append(items, SysUserListItem{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
SchoolID: u.SchoolID,
|
||||
SchoolName: u.SchoolName,
|
||||
StudentID: u.StudentID,
|
||||
RealName: u.RealName,
|
||||
MobileCode: u.MobileCode,
|
||||
MobileType: u.MobileType,
|
||||
SignCount: u.SignCount,
|
||||
InviteReward: u.InviteReward,
|
||||
InvitedCount: u.InvitedCount,
|
||||
TaskCount: taskCountMap[u.ID],
|
||||
Status: u.Status,
|
||||
CreatedAt: u.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
LastLoginAt: lastLogin,
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
SchoolID: u.SchoolID,
|
||||
SchoolName: u.SchoolName,
|
||||
StudentID: u.StudentID,
|
||||
RealName: u.RealName,
|
||||
MobileCode: u.MobileCode,
|
||||
MobileType: u.MobileType,
|
||||
SignCount: u.SignCount,
|
||||
InviteReward: u.InviteReward,
|
||||
InvitedCount: u.InvitedCount,
|
||||
InviterID: u.InviterID,
|
||||
InviterName: inviterName,
|
||||
TaskCount: taskCountMap[u.ID],
|
||||
ExecutedCount: executedMap[u.ID],
|
||||
VipStatus: vipStatus,
|
||||
VipExpireAt: vipExpireAt,
|
||||
TodayStatus: todayStatus,
|
||||
Status: u.Status,
|
||||
CreatedAt: u.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
LastLoginAt: lastLogin,
|
||||
})
|
||||
}
|
||||
|
||||
// 当天统计:执行总次数 / 成功执行总次数 / 新增用户数 / 登录用户数
|
||||
todayStart := time.Now().Format("2006-01-02") + " 00:00:00"
|
||||
var todayExecuteCount, todaySuccessCount int64
|
||||
database.DB.Model(&model.CpTaskLog{}).Where("created_at >= ?", todayStart).Count(&todayExecuteCount)
|
||||
database.DB.Model(&model.CpTaskLog{}).Where("created_at >= ? AND is_success = 1", todayStart).Count(&todaySuccessCount)
|
||||
var todayNewUsers, todayLoginUsers int64
|
||||
database.DB.Model(&model.SysUser{}).Where("created_at >= ?", todayStart).Count(&todayNewUsers)
|
||||
database.DB.Model(&model.SysUser{}).Where("last_login_at >= ?", todayStart).Count(&todayLoginUsers)
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"total": total,
|
||||
"items": items,
|
||||
"page": page,
|
||||
"total": total,
|
||||
"items": items,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
"todayStats": fiber.Map{
|
||||
"executeCount": todayExecuteCount,
|
||||
"successCount": todaySuccessCount,
|
||||
"newUserCount": todayNewUsers,
|
||||
"loginUserCount": todayLoginUsers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -133,11 +248,14 @@ func GetUserDetail(c *fiber.Ctx) error {
|
||||
var taskCount int64
|
||||
database.DB.Model(&model.CpTask{}).Where("user_id = ?", user.ID).Count(&taskCount)
|
||||
|
||||
// 统计被邀请人(通过邀请码查找)
|
||||
var invitees []model.SysUser
|
||||
database.DB.Where("invite_code = ?", user.InviteCode).Find(&invitees) // 查找使用该用户邀请码注册的人,不对,应该查找谁是被这个用户邀请的
|
||||
// 实际上我们无法直接知道谁是被这个用户邀请的,因为没有记录"被谁邀请"的字段
|
||||
// 可以通过统计该用户的 invited_count 来知道邀请人数
|
||||
// 邀请人信息(被谁邀请)
|
||||
var inviterName string
|
||||
if user.InviterID != nil {
|
||||
var inviter model.SysUser
|
||||
if err := database.DB.Select("id, username, real_name").First(&inviter, *user.InviterID).Error; err == nil {
|
||||
inviterName = inviterDisplay(inviter.Username, inviter.RealName)
|
||||
}
|
||||
}
|
||||
|
||||
lastLogin := ""
|
||||
if user.LastLoginAt != nil {
|
||||
@@ -164,6 +282,8 @@ func GetUserDetail(c *fiber.Ctx) error {
|
||||
"signCount": user.SignCount,
|
||||
"inviteReward": user.InviteReward,
|
||||
"invitedCount": user.InvitedCount,
|
||||
"inviterId": user.InviterID,
|
||||
"inviterName": inviterName,
|
||||
"status": user.Status,
|
||||
"disabledReason": user.DisabledReason,
|
||||
"taskCount": taskCount,
|
||||
@@ -217,3 +337,81 @@ func UpdateUserStatus(c *fiber.Ctx) error {
|
||||
"status": req.Status,
|
||||
})
|
||||
}
|
||||
|
||||
// AdminTaskLogItem 任务执行日志列表项(后台查看用)
|
||||
type AdminTaskLogItem struct {
|
||||
ID uint `json:"id"`
|
||||
UserID uint `json:"userId"`
|
||||
Username string `json:"username"`
|
||||
RealName string `json:"realName"`
|
||||
SchoolName string `json:"schoolName"`
|
||||
TaskType string `json:"taskType"`
|
||||
Title string `json:"title"`
|
||||
RealTitle string `json:"realTitle"`
|
||||
IsSuccess bool `json:"isSuccess"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// AdminListTaskLogs 任务执行日志列表(仅admin,供"当天执行总次数"卡片点击查看)
|
||||
// 支持按日期(默认当天)、执行状态、关键字(用户名/姓名/任务标题)筛选,分页返回
|
||||
func AdminListTaskLogs(c *fiber.Ctx) error {
|
||||
// 日期(yyyy-MM-dd,默认当天)
|
||||
date := strings.TrimSpace(c.Query("date", ""))
|
||||
if date == "" {
|
||||
date = time.Now().Format("2006-01-02")
|
||||
}
|
||||
dayStart, err := time.ParseInLocation("2006-01-02", date, time.Local)
|
||||
if err != nil {
|
||||
return utils.Fail(c, 400, "日期格式错误,应为 yyyy-MM-dd")
|
||||
}
|
||||
dayEnd := dayStart.AddDate(0, 0, 1)
|
||||
|
||||
// 执行状态筛选:all / success / fail
|
||||
status := c.Query("status", "all")
|
||||
if status != "all" && status != "success" && status != "fail" {
|
||||
status = "all"
|
||||
}
|
||||
keyword := strings.TrimSpace(c.Query("keyword", ""))
|
||||
|
||||
// 分页
|
||||
page, _ := strconv.Atoi(c.Query("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.Query("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
query := database.DB.Table("cp_task_logs").
|
||||
Joins("LEFT JOIN sys_user ON sys_user.id = cp_task_logs.user_id").
|
||||
Where("cp_task_logs.created_at >= ? AND cp_task_logs.created_at < ?", dayStart, dayEnd)
|
||||
if status == "success" {
|
||||
query = query.Where("cp_task_logs.is_success = 1")
|
||||
} else if status == "fail" {
|
||||
query = query.Where("cp_task_logs.is_success = 0")
|
||||
}
|
||||
if keyword != "" {
|
||||
like := "%" + keyword + "%"
|
||||
query = query.Where("sys_user.username LIKE ? OR sys_user.real_name LIKE ? OR cp_task_logs.title LIKE ? OR cp_task_logs.real_title LIKE ?",
|
||||
like, like, like, like)
|
||||
}
|
||||
|
||||
var total int64
|
||||
query.Count(&total)
|
||||
|
||||
var items []AdminTaskLogItem
|
||||
query.Select("cp_task_logs.id, cp_task_logs.user_id, sys_user.username, sys_user.real_name, sys_user.school_name, cp_task_logs.task_type, cp_task_logs.title, cp_task_logs.real_title, cp_task_logs.is_success, cp_task_logs.error_message, cp_task_logs.created_at").
|
||||
Order("cp_task_logs.created_at DESC").
|
||||
Offset((page - 1) * pageSize).
|
||||
Limit(pageSize).
|
||||
Scan(&items)
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
"cpdaily-new/internal/utils"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -17,16 +18,22 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GetCaptcha 获取图片验证码
|
||||
// GetCaptcha 获取图片验证码(令牌桶限流:同 IP 5 分钟最多获取 10 次,防刷屏打爆资源)
|
||||
func GetCaptcha(c *fiber.Ctx) error {
|
||||
// 优先取 XFF 真实客户端 IP(openresty 反代受信);直连无 XFF 时回退 socket 源 IP
|
||||
ip := c.IP()
|
||||
if ip == "" {
|
||||
ip = c.Context().RemoteIP().String()
|
||||
}
|
||||
ok, wait := service.AllowCaptchaToken(ip)
|
||||
if !ok {
|
||||
return utils.Fail(c, 429, fmt.Sprintf("验证码获取过于频繁,请 %s后再试", service.FormatWait(wait)))
|
||||
}
|
||||
result, err := service.GenerateCaptcha()
|
||||
if err != nil {
|
||||
slog.Error("生成验证码失败", "err", err)
|
||||
return utils.FailServer(c, "生成验证码失败")
|
||||
}
|
||||
// 调试:记录验证码
|
||||
if code, ok := service.GetCaptchaDebug(result.CaptchaID); ok {
|
||||
slog.Info("验证码", "captchaId", result.CaptchaID[:8], "code", code)
|
||||
}
|
||||
return utils.Success(c, result)
|
||||
}
|
||||
|
||||
@@ -117,7 +124,7 @@ func Login(c *fiber.Ctx) error {
|
||||
userName := buildUsername(school, req.Username)
|
||||
|
||||
// 查找或创建用户
|
||||
user, err := findOrCreateUser(userName, req.Password, req.SchoolID, school.Name, req.Username, cookieStr, req.InviteCode)
|
||||
user, isNew, err := findOrCreateUser(userName, req.Password, req.SchoolID, school.Name, req.Username, cookieStr, req.InviteCode)
|
||||
if err != nil {
|
||||
slog.Error("用户处理失败", "error", err)
|
||||
return utils.FailServer(c, "用户处理失败")
|
||||
@@ -139,7 +146,7 @@ func Login(c *fiber.Ctx) error {
|
||||
// 更新 cookie 和最后登录时间
|
||||
now := time.Now()
|
||||
database.DB.Model(&user).Updates(map[string]interface{}{
|
||||
"cookie": cookieStr,
|
||||
"cookie": cookieStr,
|
||||
"last_login_at": now,
|
||||
})
|
||||
|
||||
@@ -158,8 +165,9 @@ func Login(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"user": user,
|
||||
"token": tokenPair,
|
||||
"user": user,
|
||||
"token": tokenPair,
|
||||
"firstLogin": isNew, // 本次登录是否为新注册账号(前端据此展示首次使用引导)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -215,6 +223,19 @@ func GetUserInfo(c *fiber.Ctx) error {
|
||||
return utils.Success(c, user)
|
||||
}
|
||||
|
||||
// GuideCompleteVersion 当前新手引导版本:看过该版本即不再重复展示(数据库记录,跨设备一致)
|
||||
const GuideCompleteVersion = "v2"
|
||||
|
||||
// CompleteGuide 记录用户已完成当前版本新手引导
|
||||
func CompleteGuide(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
if err := database.DB.Model(&model.SysUser{}).Where("id = ?", userID).
|
||||
Update("guide_version", GuideCompleteVersion).Error; err != nil {
|
||||
return utils.FailServer(c, "记录失败,请稍后重试")
|
||||
}
|
||||
return utils.Success(c, nil)
|
||||
}
|
||||
|
||||
// syncUserProfile 同步 cpdaily 用户信息到数据库
|
||||
func syncUserProfile(user *model.SysUser, cookieStr string, wecloudUrl string) {
|
||||
cookieMap := cpd.ParseCookieJSON(cookieStr)
|
||||
@@ -232,14 +253,14 @@ func syncUserProfile(user *model.SysUser, cookieStr string, wecloudUrl string) {
|
||||
|
||||
func syncProfileToUser(profile *cpd.CpdailyUserProfile) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"real_name": profile.Name,
|
||||
"gender": profile.Gender,
|
||||
"avatar": profile.Img,
|
||||
"academy": profile.Academy,
|
||||
"major": profile.Major,
|
||||
"class_name": profile.ClassName,
|
||||
"grade": profile.Grade,
|
||||
"mobile_phone": profile.MobilePhone,
|
||||
"real_name": profile.Name,
|
||||
"gender": profile.Gender,
|
||||
"avatar": profile.Img,
|
||||
"academy": profile.Academy,
|
||||
"major": profile.Major,
|
||||
"class_name": profile.ClassName,
|
||||
"grade": profile.Grade,
|
||||
"mobile_phone": profile.MobilePhone,
|
||||
"org_full_name": profile.OrgFullName,
|
||||
}
|
||||
}
|
||||
@@ -294,14 +315,14 @@ func getRegisterRewardAmount() float64 {
|
||||
// createSystemAnnouncement 创建系统自动生成的公告(强制弹窗)
|
||||
func createSystemAnnouncement(userID uint, userType string, title, content string) {
|
||||
announcement := model.Announcement{
|
||||
Title: title,
|
||||
Content: content,
|
||||
Source: "system",
|
||||
TargetType: userType,
|
||||
Title: title,
|
||||
Content: content,
|
||||
Source: "system",
|
||||
TargetType: userType,
|
||||
TargetUserID: &userID,
|
||||
ForcePopup: true,
|
||||
LoopPopup: false,
|
||||
CreatedBy: 0, // 系统创建
|
||||
ForcePopup: true,
|
||||
LoopPopup: false,
|
||||
CreatedBy: 0, // 系统创建
|
||||
}
|
||||
if err := database.DB.Create(&announcement).Error; err != nil {
|
||||
slog.Error("创建系统公告失败", "error", err, "userId", userID)
|
||||
@@ -327,21 +348,22 @@ func createInviteNotifications(inviterID, inviteeID uint, inviterReward, invitee
|
||||
}
|
||||
|
||||
// 查找或创建用户
|
||||
func findOrCreateUser(username, password, schoolID, schoolName, studentID, cookie, referralCode string) (*model.SysUser, error) {
|
||||
// findOrCreateUser 查找或自动注册用户;返回 (用户, 是否首次注册, 错误)
|
||||
func findOrCreateUser(username, password, schoolID, schoolName, studentID, cookie, referralCode string) (*model.SysUser, bool, error) {
|
||||
var user model.SysUser
|
||||
err := database.DB.Where("username = ?", username).First(&user).Error
|
||||
if err == nil {
|
||||
return &user, nil
|
||||
return &user, false, nil
|
||||
}
|
||||
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
// 自动注册:生成密码哈希和邀请码
|
||||
hashedPwd, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
// 为新用户生成一个唯一的邀请码(避免空字符串与 uniqueIndex 冲突)
|
||||
@@ -360,13 +382,13 @@ func findOrCreateUser(username, password, schoolID, schoolName, studentID, cooki
|
||||
// 使用事务包裹:用户创建 + 奖励发放,保证原子性
|
||||
err = database.DB.Transaction(func(tx *gorm.DB) error {
|
||||
user = model.SysUser{
|
||||
Username: username,
|
||||
Password: string(hashedPwd),
|
||||
SchoolID: schoolID,
|
||||
SchoolName: schoolName,
|
||||
StudentID: studentID,
|
||||
Cookie: cookie,
|
||||
InviteCode: myInviteCode, // 始终设置邀请码,避免空字符串唯一索引冲突
|
||||
Username: username,
|
||||
Password: string(hashedPwd),
|
||||
SchoolID: schoolID,
|
||||
SchoolName: schoolName,
|
||||
StudentID: studentID,
|
||||
Cookie: cookie,
|
||||
InviteCode: myInviteCode, // 始终设置邀请码,避免空字符串唯一索引冲突
|
||||
}
|
||||
if err := tx.Create(&user).Error; err != nil {
|
||||
return err
|
||||
@@ -387,6 +409,9 @@ func findOrCreateUser(username, password, schoolID, schoolName, studentID, cooki
|
||||
return nil
|
||||
}
|
||||
|
||||
// 记录邀请关系(后台用户管理可展示"被谁邀请")
|
||||
tx.Model(&user).Update("inviter_id", inviter.ID)
|
||||
|
||||
// 给邀请人发放奖励积分 + 增加邀请计数
|
||||
if inviterReward > 0 {
|
||||
tx.Model(&inviter).Updates(map[string]interface{}{
|
||||
@@ -424,7 +449,7 @@ func findOrCreateUser(username, password, schoolID, schoolName, studentID, cooki
|
||||
|
||||
if err != nil {
|
||||
slog.Error("用户创建失败(可能用户名冲突)", "username", username, "error", err)
|
||||
return nil, err
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
// 邀请成功后,在事务外创建系统通知(双方各一条强制弹窗公告)
|
||||
@@ -441,7 +466,7 @@ func findOrCreateUser(username, password, schoolID, schoolName, studentID, cooki
|
||||
}
|
||||
|
||||
slog.Info("新用户自动注册", "username", username, "school", schoolName, "referralCode", referralCode, "myInviteCode", myInviteCode)
|
||||
return &user, nil
|
||||
return &user, true, nil
|
||||
}
|
||||
|
||||
// GenerateMyInviteCode 生成/获取当前用户的邀请码
|
||||
@@ -456,10 +481,12 @@ func GenerateMyInviteCode(c *fiber.Ctx) error {
|
||||
// 已有邀请码直接返回
|
||||
if user.InviteCode != "" {
|
||||
return utils.Success(c, fiber.Map{
|
||||
"inviteCode": user.InviteCode,
|
||||
"inviteReward": user.InviteReward,
|
||||
"invitedCount": user.InvitedCount,
|
||||
"canRedeem": user.InviteReward >= 1.0,
|
||||
"inviteCode": user.InviteCode,
|
||||
"inviteReward": user.InviteReward,
|
||||
"invitedCount": user.InvitedCount,
|
||||
"canRedeem": user.InviteReward >= 1.0,
|
||||
"inviterRewardPerInvite": getInviterRewardAmount(),
|
||||
"inviteeRewardPerInvite": getInviteeRewardAmount(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -473,10 +500,12 @@ func GenerateMyInviteCode(c *fiber.Ctx) error {
|
||||
slog.Info("邀请码已生成", "userId", userID, "inviteCode", code)
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"inviteCode": code,
|
||||
"inviteReward": 0,
|
||||
"invitedCount": 0,
|
||||
"canRedeem": false,
|
||||
"inviteCode": code,
|
||||
"inviteReward": 0,
|
||||
"invitedCount": 0,
|
||||
"canRedeem": false,
|
||||
"inviterRewardPerInvite": getInviterRewardAmount(),
|
||||
"inviteeRewardPerInvite": getInviteeRewardAmount(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -489,10 +518,12 @@ func GetMyInviteInfo(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"inviteCode": user.InviteCode,
|
||||
"inviteReward": user.InviteReward,
|
||||
"invitedCount": user.InvitedCount,
|
||||
"canRedeem": user.InviteReward >= 1.0,
|
||||
"inviteCode": user.InviteCode,
|
||||
"inviteReward": user.InviteReward,
|
||||
"invitedCount": user.InvitedCount,
|
||||
"canRedeem": user.InviteReward >= 1.0,
|
||||
"inviterRewardPerInvite": getInviterRewardAmount(),
|
||||
"inviteeRewardPerInvite": getInviteeRewardAmount(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -96,6 +96,7 @@ func refreshCpdailyCookie(user *model.SysUser) error {
|
||||
// 检测密码错误
|
||||
if strings.Contains(errMsg, "账号或密码错误") ||
|
||||
strings.Contains(errMsg, "密码错误") ||
|
||||
strings.Contains(errMsg, "密码不匹配") ||
|
||||
strings.Contains(errMsg, "账号密码") {
|
||||
return ErrPasswordChanged
|
||||
}
|
||||
|
||||
+293
-35
@@ -10,6 +10,7 @@ import (
|
||||
"log/slog"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
@@ -18,8 +19,10 @@ import (
|
||||
|
||||
// GenerateCDKRequest 生成CDK请求
|
||||
type GenerateCDKRequest struct {
|
||||
Count int `json:"count"` // 生成数量,默认1
|
||||
MaxRuns int `json:"maxRuns"` // 每张CDK可运行次数,默认1
|
||||
Count int `json:"count"` // 生成数量,默认1
|
||||
MaxRuns int `json:"maxRuns"` // 每张CDK可运行次数(type=count),默认1
|
||||
Type string `json:"type"` // CDK类型:count=执行次数(默认)/ vip=VIP时长
|
||||
VipDays int `json:"vipDays"` // VIP天数(type=vip),默认30(一个月)
|
||||
}
|
||||
|
||||
// 获取基础扣费(从系统设置或配置)
|
||||
@@ -35,6 +38,22 @@ func getBaseDeduction() float64 {
|
||||
return config.Global.Agent.SystemCdkPrice
|
||||
}
|
||||
|
||||
// getVipCardPrice 获取 VIP 卡价格(元/张,系统设置)
|
||||
// key: vip_price_week(周卡7天,默认30元)/ vip_price_month(月卡30天,默认100元)
|
||||
// (单次运行基础扣费 6 元,周卡/月卡按次折算后再给折扣)
|
||||
func getVipCardPrice(key string, def float64) float64 {
|
||||
var cfg model.SystemConfig
|
||||
if database.DB.Where("`key` = ?", key).First(&cfg).Error == nil {
|
||||
if v, err := strconv.ParseFloat(cfg.Value, 64); err == nil && v > 0 {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func getVipWeekPrice() float64 { return getVipCardPrice("vip_price_week", 30.00) }
|
||||
func getVipMonthPrice() float64 { return getVipCardPrice("vip_price_month", 100.00) }
|
||||
|
||||
// GenerateCDK 生成CDK
|
||||
func GenerateCDK(c *fiber.Ctx) error {
|
||||
agentID := c.Locals("adminId").(uint)
|
||||
@@ -43,32 +62,70 @@ func GenerateCDK(c *fiber.Ctx) error {
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
// CDK 类型校验(默认次数)
|
||||
if req.Type == "" {
|
||||
req.Type = "count"
|
||||
}
|
||||
if req.Type != "count" && req.Type != "vip" {
|
||||
return utils.Fail(c, 400, "CDK类型无效,必须为 count 或 vip")
|
||||
}
|
||||
if req.Count <= 0 {
|
||||
req.Count = 1
|
||||
}
|
||||
if req.Count > 100 {
|
||||
return utils.Fail(c, 400, "单次最多生成100个CDK")
|
||||
}
|
||||
if req.MaxRuns <= 0 {
|
||||
req.MaxRuns = 1
|
||||
}
|
||||
if req.MaxRuns > 999 {
|
||||
return utils.Fail(c, 400, "每张CDK最多999次")
|
||||
}
|
||||
|
||||
// 获取代理信息
|
||||
var agent model.AgentUser
|
||||
if err := database.DB.First(&agent, agentID).Error; err != nil {
|
||||
return utils.Fail(c, 404, "账号不存在")
|
||||
}
|
||||
|
||||
if agent.Status == "disabled" {
|
||||
return utils.Fail(c, 403, "账号已被禁用")
|
||||
}
|
||||
|
||||
baseDeduction := getBaseDeduction()
|
||||
cdkPrice := baseDeduction * float64(req.MaxRuns) * agent.Rate
|
||||
costTotal := baseDeduction * float64(req.MaxRuns) * agent.Rate * float64(req.Count)
|
||||
|
||||
var maxRuns int
|
||||
var vipDays int
|
||||
var unitPrice float64 // 单张CDK代理扣费
|
||||
var costPerCDK float64
|
||||
|
||||
if req.Type == "vip" {
|
||||
// VIP CDK:仅支持周卡(7天)/ 月卡(30天)两档
|
||||
if req.VipDays <= 0 {
|
||||
req.VipDays = 30
|
||||
}
|
||||
if req.VipDays != 7 && req.VipDays != 30 {
|
||||
return utils.Fail(c, 400, "VIP CDK 仅支持 7 天(周卡)或 30 天(月卡)")
|
||||
}
|
||||
maxRuns = 0
|
||||
vipDays = req.VipDays
|
||||
var vipPrice float64
|
||||
if req.VipDays == 7 {
|
||||
vipPrice = getVipWeekPrice()
|
||||
} else {
|
||||
vipPrice = getVipMonthPrice()
|
||||
}
|
||||
unitPrice = vipPrice * agent.Rate
|
||||
costPerCDK = vipPrice
|
||||
} else {
|
||||
// 次数 CDK
|
||||
if req.MaxRuns <= 0 {
|
||||
req.MaxRuns = 1
|
||||
}
|
||||
if req.MaxRuns > 999 {
|
||||
return utils.Fail(c, 400, "每张CDK最多999次")
|
||||
}
|
||||
maxRuns = req.MaxRuns
|
||||
vipDays = 0
|
||||
unitPrice = baseDeduction * float64(req.MaxRuns) * agent.Rate
|
||||
costPerCDK = baseDeduction * float64(req.MaxRuns)
|
||||
}
|
||||
|
||||
cdkPrice := unitPrice
|
||||
costTotal := unitPrice * float64(req.Count)
|
||||
|
||||
// 事务:扣余额 + 生成CDK
|
||||
cdkCodes := make([]model.CDKCode, 0, req.Count)
|
||||
@@ -89,9 +146,11 @@ func GenerateCDK(c *fiber.Ctx) error {
|
||||
cdk := model.CDKCode{
|
||||
Code: code,
|
||||
Price: cdkPrice,
|
||||
CostPrice: baseDeduction * float64(req.MaxRuns),
|
||||
CostPrice: costPerCDK,
|
||||
AgentID: agentID,
|
||||
MaxRuns: req.MaxRuns,
|
||||
MaxRuns: maxRuns,
|
||||
Type: req.Type,
|
||||
VipDays: vipDays,
|
||||
Status: "unused",
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
@@ -123,22 +182,154 @@ func GenerateCDK(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// ListCDKs 获取自己生成的CDK列表
|
||||
// ListCDKs 获取自己生成的CDK列表(分页)
|
||||
func ListCDKs(c *fiber.Ctx) error {
|
||||
agentID := c.Locals("adminId").(uint)
|
||||
|
||||
var cdks []model.CDKCode
|
||||
database.DB.Where("agent_id = ?", agentID).Order("created_at DESC").Limit(100).Find(&cdks)
|
||||
|
||||
return utils.Success(c, cdks)
|
||||
return listCDKs(c, "agent", agentID)
|
||||
}
|
||||
|
||||
// ListAllCDKs 获取所有CDK列表(仅admin)
|
||||
func ListAllCDKs(c *fiber.Ctx) error {
|
||||
var cdks []model.CDKCode
|
||||
database.DB.Preload("Agent").Order("created_at DESC").Limit(200).Find(&cdks)
|
||||
return listCDKs(c, "all", 0)
|
||||
}
|
||||
|
||||
return utils.Success(c, cdks)
|
||||
// CDKSummary CDK 状态汇总
|
||||
type CDKSummary struct {
|
||||
Total int64 `json:"total"`
|
||||
Unused int64 `json:"unused"`
|
||||
Used int64 `json:"used"`
|
||||
Disabled int64 `json:"disabled"`
|
||||
}
|
||||
|
||||
// listCDKs 分页查询CDK(scope: agent=自己 / all=全部)
|
||||
func listCDKs(c *fiber.Ctx, scope string, agentID uint) error {
|
||||
// 分页
|
||||
page, _ := strconv.Atoi(c.Query("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.Query("pageSize", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
// 筛选:状态 / CDK码关键字
|
||||
status := strings.TrimSpace(c.Query("status", ""))
|
||||
keyword := strings.TrimSpace(c.Query("keyword", ""))
|
||||
|
||||
base := func() *gorm.DB {
|
||||
q := database.DB.Model(&model.CDKCode{})
|
||||
if scope == "agent" {
|
||||
q = q.Where("agent_id = ?", agentID)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
countQuery := base()
|
||||
if status != "" {
|
||||
countQuery = countQuery.Where("status = ?", status)
|
||||
}
|
||||
if keyword != "" {
|
||||
countQuery = countQuery.Where("code LIKE ?", "%"+keyword+"%")
|
||||
}
|
||||
var total int64
|
||||
countQuery.Count(&total)
|
||||
|
||||
// 状态汇总(不受筛选影响,按当前可见范围统计)
|
||||
summary := CDKSummary{}
|
||||
for _, s := range []string{"unused", "used", "disabled"} {
|
||||
var n int64
|
||||
base().Where("status = ?", s).Count(&n)
|
||||
switch s {
|
||||
case "unused":
|
||||
summary.Unused = n
|
||||
case "used":
|
||||
summary.Used = n
|
||||
case "disabled":
|
||||
summary.Disabled = n
|
||||
}
|
||||
}
|
||||
summary.Total = summary.Unused + summary.Used + summary.Disabled
|
||||
|
||||
// 数据
|
||||
var cdks []model.CDKCode
|
||||
dataQuery := base()
|
||||
if status != "" {
|
||||
dataQuery = dataQuery.Where("status = ?", status)
|
||||
}
|
||||
if keyword != "" {
|
||||
dataQuery = dataQuery.Where("code LIKE ?", "%"+keyword+"%")
|
||||
}
|
||||
dataQuery.Order("created_at DESC").Offset(offset).Limit(pageSize)
|
||||
if scope == "all" {
|
||||
dataQuery = dataQuery.Preload("Agent")
|
||||
}
|
||||
dataQuery.Find(&cdks)
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"total": total,
|
||||
"items": cdks,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
"summary": summary,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateCDKStatusRequest 禁用/恢复CDK请求
|
||||
type UpdateCDKStatusRequest struct {
|
||||
Action string `json:"action"` // disable / enable
|
||||
}
|
||||
|
||||
// UpdateCDKStatus 禁用/恢复CDK(代理仅能操作自己生成的,admin可操作全部)
|
||||
func UpdateCDKStatus(c *fiber.Ctx) error {
|
||||
cdkID := c.Params("id")
|
||||
adminID := c.Locals("adminId").(uint)
|
||||
role, _ := c.Locals("adminRole").(string)
|
||||
|
||||
var req UpdateCDKStatusRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
if req.Action != "disable" && req.Action != "enable" {
|
||||
return utils.Fail(c, 400, "操作无效,必须为 disable 或 enable")
|
||||
}
|
||||
|
||||
var cdk model.CDKCode
|
||||
if err := database.DB.First(&cdk, cdkID).Error; err != nil {
|
||||
return utils.Fail(c, 404, "CDK不存在")
|
||||
}
|
||||
|
||||
// 权限:非 admin 只能操作自己生成的 CDK
|
||||
if role != "admin" && cdk.AgentID != adminID {
|
||||
return utils.Fail(c, 403, "无权操作该CDK")
|
||||
}
|
||||
|
||||
if req.Action == "disable" {
|
||||
if cdk.Status == "disabled" {
|
||||
return utils.Fail(c, 400, "该CDK已是禁用状态")
|
||||
}
|
||||
if cdk.Status != "unused" {
|
||||
return utils.Fail(c, 400, "仅未使用的CDK可以禁用")
|
||||
}
|
||||
if err := database.DB.Model(&cdk).Update("status", "disabled").Error; err != nil {
|
||||
slog.Error("禁用CDK失败", "error", err, "cdkId", cdk.ID)
|
||||
return utils.FailServer(c, "操作失败")
|
||||
}
|
||||
slog.Info("禁用CDK成功", "cdkId", cdk.ID, "code", cdk.Code, "adminId", adminID)
|
||||
return utils.Success(c, fiber.Map{"id": cdk.ID, "status": "disabled"})
|
||||
}
|
||||
|
||||
// enable:仅 disabled 可恢复为 unused
|
||||
if cdk.Status != "disabled" {
|
||||
return utils.Fail(c, 400, "仅已禁用的CDK可以恢复")
|
||||
}
|
||||
if err := database.DB.Model(&cdk).Update("status", "unused").Error; err != nil {
|
||||
slog.Error("恢复CDK失败", "error", err, "cdkId", cdk.ID)
|
||||
return utils.FailServer(c, "操作失败")
|
||||
}
|
||||
slog.Info("恢复CDK成功", "cdkId", cdk.ID, "code", cdk.Code, "adminId", adminID)
|
||||
return utils.Success(c, fiber.Map{"id": cdk.ID, "status": "unused"})
|
||||
}
|
||||
|
||||
// UserRedeemCDKRequest 用户兑换CDK请求
|
||||
@@ -178,6 +369,9 @@ func UserRedeemCDK(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 使用行锁(悲观锁)确保并发安全
|
||||
var vipExpireAt time.Time
|
||||
redeemType := cdk.Type
|
||||
redeemRuns := cdk.MaxRuns
|
||||
err = database.DB.Transaction(func(tx *gorm.DB) error {
|
||||
// 重新查询并锁定该行
|
||||
var lockedCDK model.CDKCode
|
||||
@@ -187,28 +381,54 @@ func UserRedeemCDK(c *fiber.Ctx) error {
|
||||
if lockedCDK.Status != "unused" {
|
||||
return errors.New("CDK码已被使用")
|
||||
}
|
||||
if lockedCDK.MaxRuns <= 0 {
|
||||
return errors.New("CDK码已无可运行次数")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
// 一次性消耗全部次数
|
||||
totalRuns := lockedCDK.MaxRuns
|
||||
updates := map[string]interface{}{
|
||||
"status": "used",
|
||||
"user_id": userID,
|
||||
"used_at": now,
|
||||
}
|
||||
|
||||
if lockedCDK.Type == "vip" {
|
||||
// ===== VIP CDK:延长 VIP 到期时间 =====
|
||||
if lockedCDK.VipDays <= 0 {
|
||||
return errors.New("VIP CDK配置无效")
|
||||
}
|
||||
// 锁定用户行,防止并发兑换导致到期时间计算错误
|
||||
var lockedUser model.SysUser
|
||||
if err := tx.Set("gorm:query_option", "FOR UPDATE").First(&lockedUser, userID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 已开通且未过期:在原到期时间上顺延;否则从当前时间起算
|
||||
base := now
|
||||
if lockedUser.VipExpireAt != nil && lockedUser.VipExpireAt.After(base) {
|
||||
base = *lockedUser.VipExpireAt
|
||||
}
|
||||
vipExpireAt = base.AddDate(0, 0, lockedCDK.VipDays)
|
||||
if err := tx.Model(&model.SysUser{}).Where("id = ?", userID).
|
||||
Update("vip_expire_at", vipExpireAt).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// ===== 次数 CDK:一次性消耗全部次数 =====
|
||||
if lockedCDK.MaxRuns <= 0 {
|
||||
return errors.New("CDK码已无可运行次数")
|
||||
}
|
||||
redeemRuns = lockedCDK.MaxRuns
|
||||
if err := tx.Model(&lockedCDK).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 增加用户签到次数(一次性加上所有剩余次数)
|
||||
if err := tx.Model(&model.SysUser{}).Where("id = ?", userID).
|
||||
Update("sign_count", gorm.Expr("sign_count + ?", redeemRuns)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := tx.Model(&lockedCDK).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 增加用户签到次数(一次性加上所有剩余次数)
|
||||
if err := tx.Model(&model.SysUser{}).Where("id = ?", userID).
|
||||
Update("sign_count", gorm.Expr("sign_count + ?", totalRuns)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -219,15 +439,30 @@ func UserRedeemCDK(c *fiber.Ctx) error {
|
||||
if err.Error() == "CDK码已无可运行次数" {
|
||||
return utils.Fail(c, 400, "CDK码已无可运行次数")
|
||||
}
|
||||
if err.Error() == "VIP CDK配置无效" {
|
||||
return utils.Fail(c, 400, "VIP CDK配置无效,请联系管理员")
|
||||
}
|
||||
slog.Error("兑换CDK失败", "error", err)
|
||||
return utils.FailServer(c, "兑换失败")
|
||||
}
|
||||
|
||||
// 按 CDK 类型返回不同提示
|
||||
if redeemType == "vip" {
|
||||
slog.Info("VIP CDK兑换成功", "userId", userID, "code", req.Code, "vipDays", cdk.VipDays, "newExpireAt", vipExpireAt.Format("2006-01-02 15:04:05"))
|
||||
return utils.Success(c, fiber.Map{
|
||||
"message": "VIP兑换成功",
|
||||
"type": "vip",
|
||||
"vipDays": cdk.VipDays,
|
||||
"vipExpireAt": vipExpireAt.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
slog.Info("CDK兑换成功", "userId", userID, "code", req.Code)
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"message": "兑换成功",
|
||||
"totalRuns": cdk.MaxRuns,
|
||||
"type": "count",
|
||||
"totalRuns": redeemRuns,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -246,3 +481,26 @@ func generateCDKCode() string {
|
||||
func formatFloat(f float64) string {
|
||||
return utils.FormatFloat(f)
|
||||
}
|
||||
|
||||
// GetUserVipInfo 获取当前用户 VIP 信息(到期时间 + 售价,供个人中心展示)
|
||||
func GetUserVipInfo(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
var user model.SysUser
|
||||
if err := database.DB.Select("id, vip_expire_at").First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
}
|
||||
|
||||
vipExpireAt := ""
|
||||
if user.VipExpireAt != nil {
|
||||
vipExpireAt = user.VipExpireAt.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
isVip := user.VipExpireAt != nil && user.VipExpireAt.After(time.Now())
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"isVip": isVip,
|
||||
"vipExpireAt": vipExpireAt,
|
||||
"vipWeekPrice": formatFloat(getVipWeekPrice()),
|
||||
"vipMonthPrice": formatFloat(getVipMonthPrice()),
|
||||
"vipPrice": formatFloat(getVipMonthPrice()), // 兼容旧字段:月卡价
|
||||
})
|
||||
}
|
||||
|
||||
@@ -137,6 +137,32 @@ func SubmitDeviceCode(c *fiber.Ctx) error {
|
||||
return utils.Success(c, fiber.Map{"status": "bound"})
|
||||
}
|
||||
|
||||
// RandomBindDevice 随机生成设备码并绑定到当前用户(个人中心「随机」按钮)
|
||||
// 风险:与真实手机绑定的设备码不一致,执行签到时现有手机会提示「频繁切换设备」导致无法签到,
|
||||
// 前端已做连续两次确认;此处不再重复校验,直接生成 UUID(大写,与真实设备码格式一致)绑定。
|
||||
func RandomBindDevice(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return utils.FailServer(c, "生成设备码失败")
|
||||
}
|
||||
// 标准 UUID v4 格式(大写),与真实设备码样式一致
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
deviceCode := fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
|
||||
if err := database.DB.Model(&model.SysUser{}).Where("id = ?", userID).Updates(map[string]interface{}{
|
||||
"mobile_code": deviceCode,
|
||||
"mobile_type": "manual",
|
||||
}).Error; err != nil {
|
||||
return utils.FailServer(c, "绑定失败")
|
||||
}
|
||||
|
||||
slog.Info("随机绑定设备码", "userId", userID, "deviceCode", deviceCode)
|
||||
return utils.Success(c, fiber.Map{"deviceCode": deviceCode})
|
||||
}
|
||||
|
||||
// ClosePage 授权完成页(当 WebView 无法关闭时跳转至此)
|
||||
func ClosePage(c *fiber.Ctx) error {
|
||||
c.Type("html")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"cpdaily-new/internal/service"
|
||||
"cpdaily-new/internal/utils"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -46,6 +47,47 @@ func checkRateLimit(ip string) bool {
|
||||
|
||||
// ---------- 请求结构体 ----------
|
||||
|
||||
// isPrivateIP 判断是否为回环/内网/链路本地等非公网地址
|
||||
func isPrivateIP(ip net.IP) bool {
|
||||
if ip == nil {
|
||||
return true
|
||||
}
|
||||
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
|
||||
ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() {
|
||||
return true
|
||||
}
|
||||
// IPv4 映射的 IPv6 判断
|
||||
if v4 := ip.To4(); v4 != nil {
|
||||
return v4[0] == 0 || v4[0] == 127 || v4[0] == 10 ||
|
||||
(v4[0] == 172 && v4[1] >= 16 && v4[1] <= 31) ||
|
||||
(v4[0] == 192 && v4[1] == 168) ||
|
||||
(v4[0] == 169 && v4[1] == 254)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// cleanClientIP 从可能含多个地址(X-Forwarded-For 链)的值中提取真实公网 IP:
|
||||
// 返回第一个公网(非回环/内网/链路本地等)地址;无公网地址返回空串
|
||||
func cleanClientIP(raw string) string {
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(part, "[]"))
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
if !isPrivateIP(ip) {
|
||||
return part
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// AllowedEmailDomains 允许的国内知名邮箱后缀(白名单)
|
||||
var AllowedEmailDomains = []string{
|
||||
"qq.com", "126.com", "163.com", "163.net", "foxmail.com",
|
||||
@@ -91,15 +133,16 @@ type ReportFailedLoginRequest struct {
|
||||
}
|
||||
|
||||
type PendingSchoolRes struct {
|
||||
ID uint `json:"id"`
|
||||
SchoolID string `json:"schoolId"`
|
||||
SchoolName string `json:"schoolName"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email"`
|
||||
IP string `json:"ip"`
|
||||
Status string `json:"status"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
ID uint `json:"id"`
|
||||
SchoolID string `json:"schoolId"`
|
||||
SchoolName string `json:"schoolName"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email"`
|
||||
IP string `json:"ip"`
|
||||
Status string `json:"status"`
|
||||
RejectReason string `json:"rejectReason"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
}
|
||||
|
||||
// ---------- 用户端 API ----------
|
||||
@@ -136,7 +179,10 @@ func ReportFailedLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 0. 速率限制:同 IP 每天最多 5 次
|
||||
clientIP := c.IP()
|
||||
clientIP := cleanClientIP(c.IP())
|
||||
if clientIP == "" {
|
||||
clientIP = c.IP()
|
||||
}
|
||||
slog.Info("[pending-school] 请求到达",
|
||||
"schoolId", req.SchoolID,
|
||||
"schoolName", req.SchoolName,
|
||||
@@ -151,7 +197,9 @@ func ReportFailedLogin(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 1. 检查该校是否有今天登录过的账号(说明学校可正常使用,忽略本次报告)
|
||||
today := time.Now().Truncate(24 * time.Hour)
|
||||
// 注意:Truncate(24h) 按 UTC 午夜截断会偏移 8 小时,必须按北京时间当日 0 点
|
||||
now := time.Now()
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
var todayLoginCount int64
|
||||
database.DB.Model(&model.SysUser{}).
|
||||
Where("school_id = ? AND last_login_at >= ?", req.SchoolID, today).
|
||||
@@ -203,6 +251,9 @@ func ReportFailedLogin(c *fiber.Ctx) error {
|
||||
"ip", clientIP,
|
||||
)
|
||||
|
||||
// 异步邮件提醒管理员处理新待适配学校
|
||||
service.NotifyNewPendingSchool(record.SchoolName, record.Username, clientIP, record.Email, record.CreatedAt.Format("2006-01-02 15:04"))
|
||||
|
||||
return utils.Success(c, fiber.Map{"accepted": true})
|
||||
}
|
||||
|
||||
@@ -216,6 +267,10 @@ func AdminListPendingSchools(c *fiber.Ctx) error {
|
||||
query := database.DB.Order("created_at DESC")
|
||||
if status == "pending" {
|
||||
query = query.Where("status = ?", "pending")
|
||||
} else if status == "completed" {
|
||||
query = query.Where("status = ?", "completed")
|
||||
} else if status == "rejected" {
|
||||
query = query.Where("status = ?", "rejected")
|
||||
}
|
||||
if err := query.Find(&records).Error; err != nil {
|
||||
return utils.FailServer(c, "查询失败")
|
||||
@@ -223,16 +278,21 @@ func AdminListPendingSchools(c *fiber.Ctx) error {
|
||||
|
||||
items := make([]PendingSchoolRes, 0, len(records))
|
||||
for _, r := range records {
|
||||
ip := cleanClientIP(r.IP)
|
||||
if ip == "" {
|
||||
ip = "-"
|
||||
}
|
||||
items = append(items, PendingSchoolRes{
|
||||
ID: r.ID,
|
||||
SchoolID: r.SchoolID,
|
||||
SchoolName: r.SchoolName,
|
||||
Username: r.Username,
|
||||
Password: r.Password,
|
||||
Email: r.Email,
|
||||
IP: r.IP,
|
||||
Status: r.Status,
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04"),
|
||||
ID: r.ID,
|
||||
SchoolID: r.SchoolID,
|
||||
SchoolName: r.SchoolName,
|
||||
Username: r.Username,
|
||||
Password: r.Password,
|
||||
Email: r.Email,
|
||||
IP: ip,
|
||||
Status: r.Status,
|
||||
RejectReason: r.RejectReason,
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -251,6 +311,20 @@ func AdminMarkSchoolDone(c *fiber.Ctx) error {
|
||||
return utils.Fail(c, 404, "记录不存在")
|
||||
}
|
||||
|
||||
// 收集该校全部记录上的联系邮箱(可能多条记录多个邮箱),去重
|
||||
var schoolRecords []model.PendingSchool
|
||||
database.DB.Where("school_id = ?", record.SchoolID).Find(&schoolRecords)
|
||||
emailSet := make(map[string]bool)
|
||||
for _, sr := range schoolRecords {
|
||||
for _, e := range service.SplitEmailsList(sr.Email) {
|
||||
emailSet[e] = true
|
||||
}
|
||||
}
|
||||
var contactEmails []string
|
||||
for e := range emailSet {
|
||||
contactEmails = append(contactEmails, e)
|
||||
}
|
||||
|
||||
// 将该学校所有待处理的记录标记为已完成
|
||||
database.DB.Model(&model.PendingSchool{}).
|
||||
Where("school_id = ? AND status = ?", record.SchoolID, "pending").
|
||||
@@ -258,5 +332,54 @@ func AdminMarkSchoolDone(c *fiber.Ctx) error {
|
||||
|
||||
slog.Info("学校已标记为适配完成", "schoolId", record.SchoolID, "schoolName", record.SchoolName)
|
||||
|
||||
// 异步邮件通知该学校的全部联系邮箱
|
||||
service.NotifySchoolAdapted(contactEmails, record.SchoolName)
|
||||
|
||||
return utils.Success(c, fiber.Map{"completed": true})
|
||||
}
|
||||
|
||||
// AdminRejectSchool 拒绝某条待适配学校记录(拒绝必须说明理由,理由将邮件通知联系邮箱)
|
||||
func AdminRejectSchool(c *fiber.Ctx) error {
|
||||
recordID, err := c.ParamsInt("id")
|
||||
if err != nil {
|
||||
return utils.FailParam(c, "无效的记录ID")
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
req.Reason = strings.TrimSpace(req.Reason)
|
||||
if req.Reason == "" {
|
||||
return utils.FailParam(c, "拒绝时必须说明理由")
|
||||
}
|
||||
if len([]rune(req.Reason)) > 500 {
|
||||
return utils.FailParam(c, "拒绝理由不能超过500字")
|
||||
}
|
||||
|
||||
var record model.PendingSchool
|
||||
if err := database.DB.First(&record, recordID).Error; err != nil {
|
||||
return utils.Fail(c, 404, "记录不存在")
|
||||
}
|
||||
if record.Status != "pending" {
|
||||
return utils.Fail(c, 400, "该记录已处理,无法拒绝")
|
||||
}
|
||||
|
||||
// 仅拒绝当前这条记录(单条拒绝,不影响同校其他记录)
|
||||
database.DB.Model(&record).Updates(map[string]interface{}{
|
||||
"status": "rejected",
|
||||
"reject_reason": req.Reason,
|
||||
})
|
||||
|
||||
// 邮件只通知该条记录留下的联系邮箱(附拒绝理由)
|
||||
contactEmails := service.SplitEmailsList(record.Email)
|
||||
|
||||
slog.Info("待适配学校记录已被拒绝", "recordId", record.ID, "schoolId", record.SchoolID, "schoolName", record.SchoolName, "reason", req.Reason)
|
||||
|
||||
// 异步邮件通知该条记录的联系邮箱(附拒绝理由)
|
||||
service.NotifySchoolRejected(contactEmails, record.SchoolName, req.Reason)
|
||||
|
||||
return utils.Success(c, fiber.Map{"rejected": true})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCleanClientIP(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"14.31.168.17, 127.0.0.1", "14.31.168.17"},
|
||||
{"127.0.0.1", ""},
|
||||
{"10.0.0.5", ""},
|
||||
{"172.22.0.1", ""},
|
||||
{"192.168.1.1", ""},
|
||||
{"14.31.168.17", "14.31.168.17"},
|
||||
{"", ""},
|
||||
{" ", ""},
|
||||
{"1.2.3.4, 10.1.1.1, ::1", "1.2.3.4"},
|
||||
{"bad-ip", ""},
|
||||
{"8.8.8.8, 2001:4860:4860::8888", "8.8.8.8"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := cleanClientIP(c.in)
|
||||
if got != c.want {
|
||||
t.Errorf("cleanClientIP(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/service"
|
||||
"cpdaily-new/internal/utils"
|
||||
"log/slog"
|
||||
|
||||
@@ -33,6 +34,12 @@ func GetSettings(c *fiber.Ctx) error {
|
||||
if _, ok := settings["register_reward"]; !ok {
|
||||
settings["register_reward"] = "1.00"
|
||||
}
|
||||
if _, ok := settings["vip_price_week"]; !ok {
|
||||
settings["vip_price_week"] = "30.00"
|
||||
}
|
||||
if _, ok := settings["vip_price_month"]; !ok {
|
||||
settings["vip_price_month"] = "100.00"
|
||||
}
|
||||
|
||||
return utils.Success(c, settings)
|
||||
}
|
||||
@@ -55,10 +62,21 @@ func UpdateSetting(c *fiber.Ctx) error {
|
||||
|
||||
// 支持的 key 白名单
|
||||
allowedKeys := map[string]bool{
|
||||
"base_deduction_per_run": true,
|
||||
"inviter_reward_per_invite": true,
|
||||
"invitee_reward_per_invite": true,
|
||||
"register_reward": true,
|
||||
"base_deduction_per_run": true,
|
||||
"inviter_reward_per_invite": true,
|
||||
"invitee_reward_per_invite": true,
|
||||
"register_reward": true,
|
||||
"vip_price_week": true,
|
||||
"vip_price_month": true,
|
||||
// 邮件通知(SMTP)
|
||||
"smtp_host": true,
|
||||
"smtp_port": true,
|
||||
"smtp_user": true,
|
||||
"smtp_password": true,
|
||||
"smtp_from": true,
|
||||
"smtp_from_name": true,
|
||||
"smtp_secure": true,
|
||||
"admin_emails": true,
|
||||
}
|
||||
if !allowedKeys[req.Key] {
|
||||
return utils.Fail(c, 400, "不支持的设置项: "+req.Key)
|
||||
@@ -90,3 +108,18 @@ func UpdateSetting(c *fiber.Ctx) error {
|
||||
"value": req.Value,
|
||||
})
|
||||
}
|
||||
|
||||
// TestMail 发送测试邮件,验证 SMTP 配置是否可用
|
||||
func TestMail(c *fiber.Ctx) error {
|
||||
emails := service.GetAdminEmails()
|
||||
if len(emails) == 0 {
|
||||
return utils.Fail(c, 400, "请先配置管理员邮箱(admin_emails)")
|
||||
}
|
||||
body := `<h2 style="margin:0 0 12px;font-size:16px">SMTP 配置测试</h2>
|
||||
<p style="font-size:14px;color:#555;line-height:1.8">如果您收到本邮件,说明邮件服务配置成功。</p>`
|
||||
if err := service.SendMail(emails, "【小助手】SMTP 测试邮件", service.EmailBody(body)); err != nil {
|
||||
slog.Error("测试邮件发送失败", "to", emails, "error", err)
|
||||
return utils.FailServer(c, "发送失败:"+err.Error())
|
||||
}
|
||||
return utils.Success(c, fiber.Map{"sent": true, "to": emails})
|
||||
}
|
||||
|
||||
@@ -106,6 +106,18 @@ func CreateTask(c *fiber.Ctx) error {
|
||||
return utils.FailParam(c, "参数不完整")
|
||||
}
|
||||
|
||||
// 同一用户禁止创建相同任务名
|
||||
var dupCount int64
|
||||
if err := database.DB.Model(&model.CpTask{}).
|
||||
Where("user_id = ? AND title = ?", userID, req.Title).
|
||||
Count(&dupCount).Error; err != nil {
|
||||
slog.Error("查重任务失败", "error", err)
|
||||
return utils.FailServer(c, "查询任务失败")
|
||||
}
|
||||
if dupCount > 0 {
|
||||
return utils.Fail(c, 400, "任务名称已存在,请勿重复创建")
|
||||
}
|
||||
|
||||
task := model.CpTask{
|
||||
UserID: userID,
|
||||
TaskType: req.TaskType,
|
||||
@@ -145,14 +157,14 @@ func GetTaskForm(c *fiber.Ctx) error {
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 从 cpdaily 拉取任务详情
|
||||
detail, err := cpd.FetchTaskDetail(cookieMap, host, cpd.TaskType(task.TaskType), task.SignWid, task.SignInstanceWid, task.Title)
|
||||
detail, err := cpd.GetTaskDetailByWid(cookieMap, host, cpd.TaskType(task.TaskType), task.SignWid, task.SignInstanceWid, task.Title)
|
||||
if err != nil {
|
||||
// cookie 过期时自动尝试重新登录
|
||||
if isCookieExpired(err) {
|
||||
slog.Info("获取任务表单cookie过期,尝试刷新", "taskId", id)
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
detail, err = cpd.FetchTaskDetail(cookieMap, host, cpd.TaskType(task.TaskType), task.SignWid, task.SignInstanceWid, task.Title)
|
||||
detail, err = cpd.GetTaskDetailByWid(cookieMap, host, cpd.TaskType(task.TaskType), task.SignWid, task.SignInstanceWid, task.Title)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -381,8 +393,11 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
database.DB.Create(&logEntry)
|
||||
}
|
||||
|
||||
// 检查可用次数
|
||||
if user.SignCount <= 0 {
|
||||
// VIP 判定:VIP 且未过期则免扣次数直接执行
|
||||
isVip := user.VipExpireAt != nil && user.VipExpireAt.After(time.Now())
|
||||
|
||||
// 检查可用次数(VIP 免检查)
|
||||
if !isVip && user.SignCount <= 0 {
|
||||
slog.Warn("签到次数不足,拒绝执行", "userId", userID, "taskId", id)
|
||||
sendEvent("task_error", map[string]interface{}{"message": "可用次数不足,请购买CDK或通过邀请获得次数"})
|
||||
return
|
||||
@@ -413,14 +428,14 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 2. 获取表单详情
|
||||
// 2. 获取表单详情(按任务名从当天列表实时匹配实例,wid 每次执行时自动获取)
|
||||
sendEvent("fetching_form", map[string]interface{}{"status": "fetching_form", "message": "正在获取签到表单..."})
|
||||
detail, err := cpd.FetchTaskDetail(cookieMap, host, cpd.TaskType(task.TaskType), task.SignWid, task.SignInstanceWid, task.Title)
|
||||
detail, err := cpd.FetchTodayTaskDetail(cookieMap, host, cpd.TaskType(task.TaskType), task.Title)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("获取签到表单cookie过期,尝试自动刷新", "taskId", id)
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
detail, err = cpd.FetchTaskDetail(cookieMap, host, cpd.TaskType(task.TaskType), task.SignWid, task.SignInstanceWid, task.Title)
|
||||
detail, err = cpd.FetchTodayTaskDetail(cookieMap, host, cpd.TaskType(task.TaskType), task.Title)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
@@ -441,15 +456,10 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 尝试获取实际标题(用于错误消息和日志中的真实签到/查寝名称)
|
||||
if task.RealTitle == "" {
|
||||
todayTasks, _ := cpd.FetchTodayTasks(cookieMap, host, cpd.TaskType(task.TaskType))
|
||||
for _, t := range todayTasks {
|
||||
if t.SignInstanceWid == task.SignInstanceWid && t.TaskName != "" {
|
||||
task.RealTitle = t.TaskName
|
||||
database.DB.Model(&task).Update("real_title", task.RealTitle)
|
||||
break
|
||||
}
|
||||
}
|
||||
// 详情来自当天列表匹配,RealTitle 即列表中的真实任务名
|
||||
if task.RealTitle == "" && detail.RealTitle != "" && detail.RealTitle != task.Title {
|
||||
task.RealTitle = detail.RealTitle
|
||||
database.DB.Model(&task).Update("real_title", task.RealTitle)
|
||||
}
|
||||
|
||||
// 3. 反序列化用户配置的表单
|
||||
@@ -469,6 +479,8 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在提交签到..."})
|
||||
|
||||
submitForm := cpd.FillSubmitForm(detail.Rows, formItems, user.MobileCode)
|
||||
// 历史位置超出查寝组所有签到范围时自动改用最近签到点,避免"位置不在签到范围内"
|
||||
cpd.AdjustSubmitFormToSignRange(submitForm, detail.Rows)
|
||||
err = cpd.SubmitSign(cookieMap, host, cpd.TaskType(task.TaskType), submitForm, user.MobileCode, user.StudentID)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("提交签到cookie过期,尝试自动刷新", "taskId", id)
|
||||
@@ -500,15 +512,22 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
})
|
||||
saveLog(true, "", taskTitle(task))
|
||||
|
||||
// 扣减可用次数(原子操作,防止并发超卖)
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count > 0", userID).
|
||||
Update("sign_count", gorm.Expr("sign_count - 1"))
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "签到成功!",
|
||||
})
|
||||
// 扣减可用次数(原子操作,防止并发超卖;VIP 有效期内免扣)
|
||||
if !isVip {
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count > 0", userID).
|
||||
Update("sign_count", gorm.Expr("sign_count - 1"))
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "签到成功!",
|
||||
})
|
||||
} else {
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "签到成功!(VIP 免扣次数)",
|
||||
})
|
||||
}
|
||||
|
||||
slog.Info("签到成功", "taskId", id, "userId", userID, "title", task.Title)
|
||||
slog.Info("签到成功", "taskId", id, "userId", userID, "title", task.Title, "isVip", isVip)
|
||||
})
|
||||
|
||||
return nil
|
||||
@@ -557,7 +576,7 @@ var _ = time.Now
|
||||
|
||||
// UpdateTaskRequest 更新任务请求
|
||||
type UpdateTaskRequest struct {
|
||||
Title *string `json:"title"`
|
||||
Title *string `json:"title"`
|
||||
FormData *[]model.CpTaskFormItem `json:"formData"`
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/service"
|
||||
"cpdaily-new/internal/utils"
|
||||
"fmt"
|
||||
|
||||
@@ -117,6 +118,12 @@ func CreateTicket(c *fiber.Ctx) error {
|
||||
return utils.FailServer(c, "创建工单失败")
|
||||
}
|
||||
|
||||
// 异步邮件提醒管理员处理新工单
|
||||
var u model.SysUser
|
||||
if err := database.DB.Select("id, username, real_name, school_name").First(&u, userID).Error; err == nil {
|
||||
service.NotifyNewTicket(ticket.ID, u.Username, u.SchoolName, u.RealName, ticket.Title, ticket.Content, ticket.CreatedAt.Format("2006-01-02 15:04"))
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"id": ticket.ID,
|
||||
})
|
||||
|
||||
@@ -38,7 +38,7 @@ func ListUserAnnouncements(c *fiber.Ctx) error {
|
||||
|
||||
var announcements []model.Announcement
|
||||
database.DB.Where(
|
||||
"(target_type = ? AND target_user_id IS NULL) OR target_user_id = ?",
|
||||
"target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)",
|
||||
userType, userID,
|
||||
).Order("created_at DESC").Find(&announcements)
|
||||
|
||||
@@ -75,7 +75,7 @@ func GetUnreadCount(c *fiber.Ctx) error {
|
||||
|
||||
var totalCount int64
|
||||
database.DB.Model(&model.Announcement{}).
|
||||
Where("(target_type = ? AND target_user_id IS NULL) OR target_user_id = ?", userType, userID).
|
||||
Where("target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)", userType, userID).
|
||||
Count(&totalCount)
|
||||
|
||||
var readCount int64
|
||||
@@ -121,7 +121,7 @@ func GetMyAnnouncementInfo(c *fiber.Ctx) error {
|
||||
// 1. 总公告数(包含指定给当前用户的)
|
||||
var totalCount int64
|
||||
database.DB.Model(&model.Announcement{}).
|
||||
Where("(target_type = ? AND target_user_id IS NULL) OR target_user_id = ?", userType, userID).
|
||||
Where("target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)", userType, userID).
|
||||
Count(&totalCount)
|
||||
|
||||
// 2. 已读数
|
||||
@@ -138,7 +138,7 @@ func GetMyAnnouncementInfo(c *fiber.Ctx) error {
|
||||
// 3. 待弹窗队列:forcePopup=true 且 (loopPopup=true 或 未读)
|
||||
var forceAnnouncements []model.Announcement
|
||||
database.DB.Where(
|
||||
"force_popup = 1 AND ((target_type = ? AND target_user_id IS NULL) OR target_user_id = ?)",
|
||||
"force_popup = 1 AND target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)",
|
||||
userType, userID,
|
||||
).Order("created_at ASC").Find(&forceAnnouncements)
|
||||
|
||||
@@ -185,10 +185,11 @@ func MarkAnnouncementRead(c *fiber.Ctx) error {
|
||||
return utils.Fail(c, 404, "公告不存在")
|
||||
}
|
||||
|
||||
// 验证公告目标类型匹配或指定给当前用户
|
||||
if announcement.TargetType != userType && (announcement.TargetUserID == nil || *announcement.TargetUserID != userID) {
|
||||
// 验证公告目标类型匹配(agent 公告仅代理/管理员可见,user 公告仅用户可见)
|
||||
if announcement.TargetType != userType {
|
||||
return utils.Fail(c, 403, "无权操作此公告")
|
||||
}
|
||||
// 指定给其他用户的公告无权操作
|
||||
if announcement.TargetUserID != nil && *announcement.TargetUserID != userID {
|
||||
return utils.Fail(c, 403, "无权操作此公告")
|
||||
}
|
||||
|
||||
@@ -4,17 +4,22 @@ import "time"
|
||||
|
||||
// CDKCode CDK码
|
||||
type CDKCode struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
Code string `gorm:"type:varchar(32);uniqueIndex;not null" json:"code"`
|
||||
Price float64 `gorm:"type:decimal(10,2);not null" json:"price"` // 售价(用户端价格)
|
||||
CostPrice float64 `gorm:"type:decimal(10,2);not null" json:"costPrice"` // 成本价(系统底价)
|
||||
AgentID uint `gorm:"not null;index" json:"agentId"` // 生成此CDK的代理
|
||||
MaxRuns int `gorm:"default:1;not null" json:"maxRuns"` // 可运行次数
|
||||
Status string `gorm:"type:varchar(16);not null;default:unused" json:"status"` // unused / used / disabled
|
||||
UserID *uint `gorm:"index" json:"userId"` // 最近兑换用户
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
Code string `gorm:"type:varchar(32);uniqueIndex;not null" json:"code"`
|
||||
Price float64 `gorm:"type:decimal(10,2);not null" json:"price"` // 售价(用户端价格)
|
||||
CostPrice float64 `gorm:"type:decimal(10,2);not null" json:"costPrice"` // 成本价(系统底价)
|
||||
AgentID uint `gorm:"not null;index" json:"agentId"` // 生成此CDK的代理
|
||||
Agent *AgentUser `gorm:"foreignKey:AgentID" json:"agent,omitempty"` // 生成代理(admin全量列表预加载用)
|
||||
MaxRuns int `gorm:"default:1;not null" json:"maxRuns"` // 可运行次数(type=count 有效)
|
||||
// CDK 类型:count=执行次数 / vip=VIP 时长
|
||||
Type string `gorm:"type:varchar(16);not null;default:count;index" json:"type"`
|
||||
// VIP 时长天数(type=vip 有效,默认 30 天/一个月)
|
||||
VipDays int `gorm:"default:0" json:"vipDays"`
|
||||
Status string `gorm:"type:varchar(16);not null;default:unused" json:"status"` // unused / used / disabled
|
||||
UserID *uint `gorm:"index" json:"userId"` // 最近兑换用户
|
||||
UsedAt *time.Time `json:"usedAt"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
func (CDKCode) TableName() string {
|
||||
|
||||
@@ -6,15 +6,16 @@ import (
|
||||
|
||||
// PendingSchool 待适配学校(用户提交的测试账号)
|
||||
type PendingSchool struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
SchoolID string `gorm:"size:50;not null;index" json:"schoolId"`
|
||||
SchoolName string `gorm:"size:200;not null" json:"schoolName"`
|
||||
Username string `gorm:"size:100;not null" json:"username"`
|
||||
Password string `gorm:"size:200;not null" json:"password"`
|
||||
Email string `gorm:"size:100" json:"email"`
|
||||
IP string `gorm:"size:50;not null;index:idx_ip_status" json:"ip"`
|
||||
Status string `gorm:"size:20;not null;default:pending;index:idx_ip_status;index:idx_school_status" json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
SchoolID string `gorm:"size:50;not null;index" json:"schoolId"`
|
||||
SchoolName string `gorm:"size:200;not null" json:"schoolName"`
|
||||
Username string `gorm:"size:100;not null" json:"username"`
|
||||
Password string `gorm:"size:200;not null" json:"password"`
|
||||
Email string `gorm:"size:100" json:"email"`
|
||||
IP string `gorm:"size:50;not null;index:idx_ip_status" json:"ip"`
|
||||
Status string `gorm:"size:20;not null;default:pending;index:idx_ip_status;index:idx_school_status" json:"status"`
|
||||
RejectReason string `gorm:"size:500" json:"rejectReason"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func (PendingSchool) TableName() string {
|
||||
|
||||
@@ -3,15 +3,15 @@ package model
|
||||
import "time"
|
||||
|
||||
type SysUser struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
Username string `gorm:"type:varchar(255);uniqueIndex;not null" json:"username"`
|
||||
Password string `gorm:"type:varchar(255);not null" json:"-"`
|
||||
SchoolID string `gorm:"type:varchar(255);not null" json:"schoolId"`
|
||||
SchoolName string `gorm:"type:varchar(255)" json:"schoolName"`
|
||||
StudentID string `gorm:"type:varchar(255);not null" json:"studentId"`
|
||||
Cookie string `gorm:"type:longtext" json:"-"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
Username string `gorm:"type:varchar(255);uniqueIndex;not null" json:"username"`
|
||||
Password string `gorm:"type:varchar(255);not null" json:"-"`
|
||||
SchoolID string `gorm:"type:varchar(255);not null" json:"schoolId"`
|
||||
SchoolName string `gorm:"type:varchar(255)" json:"schoolName"`
|
||||
StudentID string `gorm:"type:varchar(255);not null" json:"studentId"`
|
||||
Cookie string `gorm:"type:longtext" json:"-"`
|
||||
// RawPassword AES加密后的cpdaily明文密码(base64编码),用于cookie过期时自动重新登录
|
||||
RawPassword string `gorm:"type:longtext" json:"-"`
|
||||
RawPassword string `gorm:"type:longtext" json:"-"`
|
||||
|
||||
// 今日校园真实姓名
|
||||
RealName string `gorm:"type:varchar(255)" json:"realName"`
|
||||
@@ -37,8 +37,12 @@ type SysUser struct {
|
||||
MobileType string `gorm:"type:varchar(32)" json:"mobileType"`
|
||||
// 可签到次数
|
||||
SignCount int `gorm:"type:int;default:0" json:"signCount"`
|
||||
// VIP 到期时间(null=从未开通;VIP 有效期内执行任务免扣次数)
|
||||
VipExpireAt *time.Time `gorm:"type:datetime" json:"vipExpireAt"`
|
||||
// 邀请码
|
||||
InviteCode string `gorm:"type:varchar(32);uniqueIndex" json:"inviteCode"`
|
||||
// 邀请人用户ID(null=非邀请注册)
|
||||
InviterID *uint `gorm:"type:int;index" json:"inviterId"`
|
||||
// 邀请奖励积分(成功邀请一人得 0.5,满 1 可兑换 1 次签到)
|
||||
InviteReward float64 `gorm:"type:decimal(10,1);default:0" json:"inviteReward"`
|
||||
// 累计邀请人数
|
||||
@@ -52,6 +56,9 @@ type SysUser struct {
|
||||
// 最后登录时间
|
||||
LastLoginAt *time.Time `gorm:"type:datetime" json:"lastLoginAt"`
|
||||
|
||||
// 已看过的新手引导版本(如 v2;空=未看过,登录后需展示引导,跨设备生效)
|
||||
GuideVersion string `gorm:"type:varchar(32);default:''" json:"guideVersion"`
|
||||
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
@@ -2,23 +2,99 @@ package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"cpdaily-new/internal/config"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"log/slog"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
captchaStore = sync.Map{}
|
||||
rng = rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
captchaStore = sync.Map{} // Redis 不可用时的兜底存储(进程级,带过期懒清理)
|
||||
)
|
||||
|
||||
const (
|
||||
captchaTTL = 5 * time.Minute
|
||||
captchaKeyFmt = "captcha:%s" // 验证码内容
|
||||
captchaRLKey = "captcha:rl:%s"
|
||||
|
||||
// 令牌桶:同 IP 5 分钟最多获取 10 次(桶容量 10,速率 10/5min = 每 30s 回补 1 个)
|
||||
// 容忍共享出口 IP(宿舍/校园网多人)短时突发,又能约束爆破频率
|
||||
captchaBucketCapacity = 10
|
||||
captchaBucketWindow = 5 * time.Minute
|
||||
)
|
||||
|
||||
// 令牌桶 Lua 脚本(原子):状态存 "剩余tokens:上次补桶毫秒时间戳"
|
||||
// 返回 {1,0} 放行(已扣 1 个 token);{0, waitMs} 被限流(需等待 waitMs 毫秒后才有新 token)
|
||||
var captchaTokenScript = redis.NewScript(`
|
||||
local cap = tonumber(ARGV[1])
|
||||
local rateMs = tonumber(ARGV[2])
|
||||
local now = tonumber(ARGV[3])
|
||||
local windowMs = tonumber(ARGV[4])
|
||||
|
||||
local tokens = cap
|
||||
local last = now
|
||||
local data = redis.call('GET', KEYS[1])
|
||||
if data then
|
||||
local colon = string.find(data, ':')
|
||||
if colon then
|
||||
tokens = tonumber(string.sub(data, 1, colon - 1))
|
||||
last = tonumber(string.sub(data, colon + 1))
|
||||
if not tokens or not last then tokens = cap end
|
||||
end
|
||||
end
|
||||
|
||||
local elapsedMs = now - last
|
||||
if elapsedMs > 0 then
|
||||
tokens = tokens + elapsedMs * rateMs
|
||||
end
|
||||
if tokens > cap then tokens = cap end
|
||||
|
||||
if tokens < 1 then
|
||||
local waitMs = math.ceil((1 - tokens) / rateMs)
|
||||
if waitMs < 1000 then waitMs = 1000 end
|
||||
redis.call('SET', KEYS[1], tokens .. ':' .. now, 'PX', windowMs)
|
||||
return { 0, waitMs }
|
||||
end
|
||||
|
||||
tokens = tokens - 1
|
||||
redis.call('SET', KEYS[1], tokens .. ':' .. now, 'PX', windowMs)
|
||||
return { 1, 0 }
|
||||
`)
|
||||
|
||||
// redisCaptchaOp 短超时上下文(不阻塞请求)
|
||||
func redisCaptchaCtx() (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), 2*time.Second)
|
||||
}
|
||||
|
||||
// storeCaptchaCode 存储验证码(优先 Redis,Redis 不可用时兜底内存)
|
||||
func storeCaptchaCode(captchaID, code string) error {
|
||||
if Redis != nil {
|
||||
ctx, cancel := redisCaptchaCtx()
|
||||
defer cancel()
|
||||
if err := Redis.Set(ctx, fmt.Sprintf(captchaKeyFmt, captchaID), code, captchaTTL).Err(); err == nil {
|
||||
return nil
|
||||
} else {
|
||||
slog.Warn("验证码写入 Redis 失败,降级内存存储", "err", err)
|
||||
}
|
||||
}
|
||||
captchaStore.Store(captchaID, CaptchaValue{
|
||||
Code: code,
|
||||
ExpiresAt: time.Now().Add(captchaTTL),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type CaptchaResult struct {
|
||||
CaptchaID string `json:"captchaId"`
|
||||
ImageBase64 string `json:"imageBase64"`
|
||||
@@ -55,7 +131,7 @@ func generateCode(length int) string {
|
||||
digits := "0123456789"
|
||||
var sb strings.Builder
|
||||
for i := 0; i < length; i++ {
|
||||
sb.WriteByte(digits[rng.Intn(len(digits))])
|
||||
sb.WriteByte(digits[rand.Intn(len(digits))])
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
@@ -69,63 +145,63 @@ func GenerateCaptcha() (*CaptchaResult, error) {
|
||||
img := image.NewRGBA(image.Rect(0, 0, cfg.Width, cfg.Height))
|
||||
|
||||
// 随机马卡龙色背景
|
||||
bg := pastelBG[rng.Intn(len(pastelBG))]
|
||||
bg := pastelBG[rand.Intn(len(pastelBG))]
|
||||
draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)
|
||||
|
||||
// ── 干扰线(粗线,高不透明度)──
|
||||
for i := 0; i < 10; i++ {
|
||||
col := animeColors[rng.Intn(len(animeColors))]
|
||||
col.A = uint8(rng.Intn(80) + 150) // alpha 150~230
|
||||
col := animeColors[rand.Intn(len(animeColors))]
|
||||
col.A = uint8(rand.Intn(80) + 150) // alpha 150~230
|
||||
|
||||
x1 := rng.Intn(cfg.Width)
|
||||
y1 := rng.Intn(cfg.Height)
|
||||
x2 := rng.Intn(cfg.Width)
|
||||
y2 := rng.Intn(cfg.Height)
|
||||
x1 := rand.Intn(cfg.Width)
|
||||
y1 := rand.Intn(cfg.Height)
|
||||
x2 := rand.Intn(cfg.Width)
|
||||
y2 := rand.Intn(cfg.Height)
|
||||
|
||||
thick := rng.Intn(2) + 2 // 2~3px 粗
|
||||
thick := rand.Intn(2) + 2 // 2~3px 粗
|
||||
drawThickLine(img, x1, y1, x2, y2, col, thick)
|
||||
}
|
||||
|
||||
// ── 二次元风格彩色折线 ──
|
||||
for i := 0; i < 6; i++ {
|
||||
col := animeColors[rng.Intn(len(animeColors))]
|
||||
col.A = uint8(rng.Intn(60) + 130)
|
||||
col := animeColors[rand.Intn(len(animeColors))]
|
||||
col.A = uint8(rand.Intn(60) + 130)
|
||||
|
||||
x1 := rng.Intn(cfg.Width)
|
||||
y1 := rng.Intn(cfg.Height)
|
||||
xm := rng.Intn(cfg.Width)
|
||||
ym := rng.Intn(cfg.Height)
|
||||
x2 := rng.Intn(cfg.Width)
|
||||
y2 := rng.Intn(cfg.Height)
|
||||
x1 := rand.Intn(cfg.Width)
|
||||
y1 := rand.Intn(cfg.Height)
|
||||
xm := rand.Intn(cfg.Width)
|
||||
ym := rand.Intn(cfg.Height)
|
||||
x2 := rand.Intn(cfg.Width)
|
||||
y2 := rand.Intn(cfg.Height)
|
||||
drawThickLine(img, x1, y1, xm, ym, col, 2)
|
||||
drawThickLine(img, xm, ym, x2, y2, col, 2)
|
||||
}
|
||||
|
||||
// ── 装饰圆圈(半透明彩色气泡)──
|
||||
for i := 0; i < 4; i++ {
|
||||
cx := rng.Intn(cfg.Width)
|
||||
cy := rng.Intn(cfg.Height)
|
||||
radius := rng.Intn(5) + 3
|
||||
col := animeColors[rng.Intn(len(animeColors))]
|
||||
cx := rand.Intn(cfg.Width)
|
||||
cy := rand.Intn(cfg.Height)
|
||||
radius := rand.Intn(5) + 3
|
||||
col := animeColors[rand.Intn(len(animeColors))]
|
||||
col.A = 40
|
||||
drawCircle(img, cx, cy, radius, col)
|
||||
}
|
||||
|
||||
// 小星星/闪光装饰点
|
||||
for i := 0; i < 6; i++ {
|
||||
x := rng.Intn(cfg.Width)
|
||||
y := rng.Intn(cfg.Height)
|
||||
starCol := animeColors[rng.Intn(len(animeColors))]
|
||||
x := rand.Intn(cfg.Width)
|
||||
y := rand.Intn(cfg.Height)
|
||||
starCol := animeColors[rand.Intn(len(animeColors))]
|
||||
starCol.A = 100
|
||||
drawStarDot(img, x, y, starCol)
|
||||
}
|
||||
|
||||
// 彩色噪点
|
||||
for i := 0; i < 100; i++ {
|
||||
x := rng.Intn(cfg.Width)
|
||||
y := rng.Intn(cfg.Height)
|
||||
col := animeColors[rng.Intn(len(animeColors))]
|
||||
col.A = uint8(rng.Intn(100) + 80)
|
||||
x := rand.Intn(cfg.Width)
|
||||
y := rand.Intn(cfg.Height)
|
||||
col := animeColors[rand.Intn(len(animeColors))]
|
||||
col.A = uint8(rand.Intn(100) + 80)
|
||||
img.Set(x, y, col)
|
||||
}
|
||||
|
||||
@@ -144,17 +220,17 @@ func GenerateCaptcha() (*CaptchaResult, error) {
|
||||
charY := (cfg.Height - charH) / 2
|
||||
|
||||
// 微调位置
|
||||
charX += rng.Intn(5) - 2
|
||||
charY += rng.Intn(3) - 1
|
||||
charX += rand.Intn(5) - 2
|
||||
charY += rand.Intn(3) - 1
|
||||
|
||||
// 每个字符选择鲜艳的二次元颜色
|
||||
charColor := animeColors[rng.Intn(len(animeColors))]
|
||||
charColor := animeColors[rand.Intn(len(animeColors))]
|
||||
|
||||
// 随机倾斜程度 (shear: 每行偏移像素数)
|
||||
shear := rng.Intn(2) + 1 // 1~2
|
||||
shear := rand.Intn(2) + 1 // 1~2
|
||||
|
||||
// 1/3 概率向右倾斜,2/3 向左倾斜
|
||||
if rng.Intn(3) != 0 {
|
||||
if rand.Intn(3) != 0 {
|
||||
shear = -shear
|
||||
}
|
||||
|
||||
@@ -170,10 +246,9 @@ func GenerateCaptcha() (*CaptchaResult, error) {
|
||||
|
||||
// 生成唯一 ID 并存储验证码
|
||||
captchaID := generateCode(16)
|
||||
captchaStore.Store(captchaID, CaptchaValue{
|
||||
Code: code,
|
||||
ExpiresAt: time.Now().Add(5 * time.Minute),
|
||||
})
|
||||
if err := storeCaptchaCode(captchaID, code); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &CaptchaResult{
|
||||
CaptchaID: captchaID,
|
||||
@@ -190,6 +265,19 @@ func VerifyCaptcha(captchaID, code string) bool {
|
||||
if captchaID == "" || code == "" {
|
||||
return false
|
||||
}
|
||||
// 优先 Redis:GETDEL 原子取出并删除(Redis 6.2+)
|
||||
if Redis != nil {
|
||||
ctx, cancel := redisCaptchaCtx()
|
||||
defer cancel()
|
||||
val, err := Redis.GetDel(ctx, fmt.Sprintf(captchaKeyFmt, captchaID)).Result()
|
||||
if err == nil {
|
||||
return strings.EqualFold(val, code)
|
||||
}
|
||||
if err != redis.Nil {
|
||||
slog.Warn("验证码校验读取 Redis 失败", "err", err)
|
||||
}
|
||||
// 未命中或出错:再查内存兜底
|
||||
}
|
||||
val, ok := captchaStore.Load(captchaID)
|
||||
if !ok {
|
||||
return false
|
||||
@@ -202,14 +290,54 @@ func VerifyCaptcha(captchaID, code string) bool {
|
||||
return strings.EqualFold(cv.Code, code)
|
||||
}
|
||||
|
||||
// GetCaptchaDebug 读取验证码(调试用)
|
||||
func GetCaptchaDebug(captchaID string) (string, bool) {
|
||||
val, ok := captchaStore.Load(captchaID)
|
||||
if !ok {
|
||||
return "", false
|
||||
// AllowCaptchaToken 验证码生成令牌桶限流:同 IP 5 分钟内最多获取 10 次。
|
||||
// 返回 (true, 0) 表示允许生成并已扣减 token;
|
||||
// 返回 (false, wait) 表示被限流,wait 为最快可再次获取的等待时长(已向上取整到秒)。
|
||||
// 空 IP 或 Redis 不可用/出错时放行(存储兜底同样受限,避免误伤正常用户)。
|
||||
func AllowCaptchaToken(ip string) (bool, time.Duration) {
|
||||
if ip == "" || Redis == nil {
|
||||
return true, 0
|
||||
}
|
||||
ctx, cancel := redisCaptchaCtx()
|
||||
defer cancel()
|
||||
|
||||
rateMs := float64(captchaBucketCapacity) / float64(captchaBucketWindow.Milliseconds())
|
||||
res, err := captchaTokenScript.Run(ctx, Redis,
|
||||
[]string{fmt.Sprintf(captchaRLKey, ip)},
|
||||
captchaBucketCapacity,
|
||||
fmt.Sprintf("%.12f", rateMs),
|
||||
time.Now().UnixMilli(),
|
||||
captchaBucketWindow.Milliseconds(),
|
||||
).Int64Slice()
|
||||
if err != nil {
|
||||
slog.Warn("验证码限流 Redis 操作失败,放行", "err", err)
|
||||
return true, 0
|
||||
}
|
||||
if len(res) != 2 {
|
||||
return true, 0
|
||||
}
|
||||
if res[0] == 1 {
|
||||
return true, 0
|
||||
}
|
||||
// waitMs 向上取整到秒(至少 1 秒)
|
||||
wait := time.Duration(((res[1]+999)/1000)*1000) * time.Millisecond
|
||||
if wait < time.Second {
|
||||
wait = time.Second
|
||||
}
|
||||
return false, wait
|
||||
}
|
||||
|
||||
// FormatWait 将等待时长格式化为提示文案片段:如 "5 秒"、"3 分钟"
|
||||
func FormatWait(d time.Duration) string {
|
||||
secs := int((d + 999*time.Millisecond) / time.Second)
|
||||
switch {
|
||||
case secs < 60:
|
||||
return fmt.Sprintf("%d 秒", secs)
|
||||
case secs < 3600:
|
||||
return fmt.Sprintf("%d 分钟", (secs+59)/60)
|
||||
default:
|
||||
return fmt.Sprintf("%d 小时", (secs+3599)/3600)
|
||||
}
|
||||
cv := val.(CaptchaValue)
|
||||
return cv.Code, true
|
||||
}
|
||||
|
||||
// 画粗线(绘制多条平行线模拟粗线)
|
||||
|
||||
@@ -140,6 +140,14 @@ func getCasValidLoginUrl(school *SchoolDetailInfo) string {
|
||||
return school.IdsUrl
|
||||
}
|
||||
}
|
||||
// 优先选择 campusphere / wec 网关入口:登录后 cookie 落在网关域,
|
||||
// 后续签到/查寝等任务请求(wec-counselor-* 均在网关域)才能携带有效会话。
|
||||
// 部分学校 AmpUrl 为学校自研门户(如 ehall),若登录到该域,cookie 与任务接口域不匹配。
|
||||
for _, u := range []string{school.AmpUrl, school.AmpUrl2, school.AmpUrl3} {
|
||||
if u != "" && (strings.Contains(u, "campusphere") || strings.Contains(u, "wec-portal-mobile")) {
|
||||
return u
|
||||
}
|
||||
}
|
||||
for _, u := range []string{school.AmpUrl, school.AmpUrl2, school.AmpUrl3} {
|
||||
if u != "" {
|
||||
return u
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// ========== 合肥师范学院专用登录适配 ==========
|
||||
//
|
||||
// 该校(hfnu.campusphere.net)登录走 portal.hfnu.edu.cn 老式 jasig CAS
|
||||
// (/sso/login,webflow lt/e1sX 风格),与通用 CAS 流程存在两处不兼容,
|
||||
// 故单独适配:
|
||||
// 1. 会话用 URL 重写传递(form action 形如 /sso/login;jsessionid=xxx?service=...),
|
||||
// 服务器不通过 Set-Cookie 建立 session,POST 必须发到 form 的 action
|
||||
// 地址(带 ;jsessionid),否则 webflow 会话丢失、静默回到登录页;
|
||||
// 2. 每次登录都要求图形验证码(页面 JS: codeupdate==0 → 强制显示
|
||||
// #code_validate),验证码图片 /sso/code/code.jsp,4 位纯数字 JPEG,
|
||||
// 提交字段为 validateCode。通用流程探测的 /authserver/needCaptcha.html
|
||||
// 在该校返回空 body,会被误判为"不需要验证码"。
|
||||
//
|
||||
// 密码为明文提交(页面无加密 salt),登录成功后 302 回跳
|
||||
// ehall.hfnu.edu.cn/amp-auth-adapter/loginSuccess?sessionToken=...&ticket=...
|
||||
|
||||
// HfnuSchoolId 合肥师范学院 tenant id
|
||||
const HfnuSchoolId = "hfnu"
|
||||
|
||||
var hfnuJsessionidRegexp = regexp.MustCompile(`;jsessionid=([A-Za-z0-9._-]+)`)
|
||||
|
||||
// hfnuLogin 合肥师范学院专用登录
|
||||
func hfnuLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, error) {
|
||||
sc := newSessionClient()
|
||||
|
||||
loginUrl := getCasValidLoginUrl(school)
|
||||
if loginUrl == "" {
|
||||
return nil, fmt.Errorf("该校登录配置不完整(缺少登录地址)")
|
||||
}
|
||||
slog.Info("合肥师范专用登录", "loginUrl", loginUrl)
|
||||
|
||||
loginCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 1. GET 登录页(跟随重定向到 portal.hfnu.edu.cn/sso/login)
|
||||
loginPageResp, err := sc.R().SetContext(loginCtx).Get(loginUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求登录页面失败: %w", err)
|
||||
}
|
||||
pageBody := readBody(loginPageResp)
|
||||
pageURL := loginPageResp.RawResponse.Request.URL
|
||||
slog.Info("合肥师范登录页", "finalUrl", pageURL.String(), "bodyLen", len(pageBody))
|
||||
|
||||
// 2. 解析 form action(含 ;jsessionid)与 lt
|
||||
postUrl, lt, err := parseHfnuLoginForm(pageBody, pageURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
slog.Info("合肥师范CAS表单", "postUrl", postUrl, "lt", lt)
|
||||
|
||||
// 3. 获取验证码并 OCR(该校每次登录都需要)
|
||||
captchaCode, err := resolveHfnuCaptcha(ctx, pageURL, postUrl, sc.Client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
slog.Info("合肥师范验证码OCR", "code", captchaCode)
|
||||
|
||||
// 4. 提交登录(禁用重定向,登录成功返回 302)
|
||||
sc.SetRedirectPolicy(resty.NoRedirectPolicy())
|
||||
loginResp, err := sc.R().
|
||||
SetContext(loginCtx).
|
||||
SetFormData(map[string]string{
|
||||
"username": username,
|
||||
"password": password,
|
||||
"validateCode": captchaCode,
|
||||
"lt": lt,
|
||||
"_eventId": "submit",
|
||||
}).
|
||||
Post(postUrl)
|
||||
if err != nil {
|
||||
if loginResp != nil && loginResp.StatusCode() == http.StatusFound {
|
||||
slog.Info("合肥师范登录重定向(登录成功)", "location", loginResp.Header().Get("Location"))
|
||||
} else {
|
||||
return nil, fmt.Errorf("提交登录失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
slog.Info("合肥师范登录响应", "statusCode", loginResp.StatusCode())
|
||||
switch loginResp.StatusCode() {
|
||||
case http.StatusFound:
|
||||
return handleCasLoginSuccess(ctx, loginResp, school, sc)
|
||||
case http.StatusOK, http.StatusUnauthorized:
|
||||
// 2026-09 排查:该校认证流程本身可用(账密/验证码校验均可通过),
|
||||
// 但 CAS 认证通过后校方 amp-auth-adapter 单点跳转服务拒绝授权
|
||||
//(用户在浏览器登录同样报"系统拒绝单点登录跳转"),导致无法换取网关会话。
|
||||
// 这里区分两类失败:有明确错误文案的(账密错误等)原样提示;
|
||||
// 无任何错误信息的(认证通过但学校端跳转被拒)给出明确的服务端故障提示。
|
||||
msg := parseHfnuLoginError(readBody(loginResp))
|
||||
if msg == "" {
|
||||
return nil, fmt.Errorf("该校统一认证平台单点登录服务异常(学校端故障),请稍后重试;如持续失败请联系管理员")
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
default:
|
||||
return nil, fmt.Errorf("登录返回异常状态码: %d", loginResp.StatusCode())
|
||||
}
|
||||
}
|
||||
|
||||
// parseHfnuLoginForm 从登录页解析 form action(绝对化,保留 ;jsessionid)与 lt
|
||||
func parseHfnuLoginForm(page []byte, pageURL *url.URL) (string, string, error) {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(page)))
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("解析登录页失败: %w", err)
|
||||
}
|
||||
form := doc.Find("#credentials")
|
||||
if form.Length() == 0 {
|
||||
form = doc.Find("form").First()
|
||||
}
|
||||
if form.Length() == 0 {
|
||||
return "", "", fmt.Errorf("登录页未找到登录表单")
|
||||
}
|
||||
|
||||
action, _ := form.Attr("action")
|
||||
postUrl := ""
|
||||
if action != "" {
|
||||
if u, err := pageURL.Parse(action); err == nil {
|
||||
postUrl = u.String()
|
||||
}
|
||||
}
|
||||
if postUrl == "" {
|
||||
return "", "", fmt.Errorf("登录页未找到表单提交地址")
|
||||
}
|
||||
|
||||
lt := ""
|
||||
form.Find("input").Each(func(_ int, s *goquery.Selection) {
|
||||
name, _ := s.Attr("name")
|
||||
if name == "lt" {
|
||||
lt, _ = s.Attr("value")
|
||||
}
|
||||
})
|
||||
if lt == "" {
|
||||
return "", "", fmt.Errorf("登录页未找到 lt 参数")
|
||||
}
|
||||
return postUrl, lt, nil
|
||||
}
|
||||
|
||||
// resolveHfnuCaptcha 拉取 /sso/code/code.jsp 验证码并 OCR。
|
||||
// 该校 session 走 URL 重写,验证码请求需带上与 form action 相同的 ;jsessionid。
|
||||
func resolveHfnuCaptcha(ctx context.Context, pageURL *url.URL, postUrl string, client *resty.Client) (string, error) {
|
||||
// 登录页路径为 /sso/login;相对路径 code/code.jsp 基于其解析 → /sso/code/code.jsp
|
||||
captchaUrl, err := pageURL.Parse("code/code.jsp")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("解析验证码地址失败: %w", err)
|
||||
}
|
||||
// 该校不依赖 Cookie 而用 URL 重写:把 form action 中的 jsessionid 拼到验证码路径
|
||||
if m := hfnuJsessionidRegexp.FindStringSubmatch(postUrl); len(m) > 1 {
|
||||
captchaUrl.Path = captchaUrl.Path + ";jsessionid=" + m[1]
|
||||
}
|
||||
captchaUrl.RawQuery = fmt.Sprintf("t=%.3d", time.Now().UnixNano()%1000)
|
||||
slog.Info("合肥师范验证码", "url", captchaUrl.String())
|
||||
|
||||
imgResp, err := client.R().SetContext(ctx).Get(captchaUrl.String())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("获取验证码失败: %w", err)
|
||||
}
|
||||
imgData := readBody(imgResp)
|
||||
if len(imgData) == 0 {
|
||||
return "", fmt.Errorf("验证码图片为空")
|
||||
}
|
||||
slog.Info("合肥师范验证码获取成功", "size", len(imgData))
|
||||
|
||||
code := captchaOCR(imgData)
|
||||
if code == "" {
|
||||
return "", fmt.Errorf("验证码识别失败,请重试")
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
|
||||
// parseHfnuLoginError 解析登录失败页的错误提示
|
||||
func parseHfnuLoginError(body []byte) string {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(body)))
|
||||
if err == nil {
|
||||
if msg := strings.TrimSpace(doc.Find("li.err").Text()); msg != "" {
|
||||
return msg
|
||||
}
|
||||
}
|
||||
return "登录失败,请检查账号密码或稍后重试"
|
||||
}
|
||||
@@ -117,22 +117,49 @@ func iapLogin(ctx context.Context, school *SchoolDetailInfo, username, password
|
||||
return handleIapLoginSuccess(ctx, loginResp, school, sc)
|
||||
case 200:
|
||||
body, _ := io.ReadAll(loginResp.RawBody())
|
||||
// resultCode 在不同学校可能是数字(1/-3/-4)或字符串枚举
|
||||
// (如 "FAIL_UPNOTMATCH" 账号密码不匹配、"CAPTCHA_NOTMATCH" 验证码错误),
|
||||
// 用 RawMessage 兼容两种类型
|
||||
var result struct {
|
||||
ResultCode int `json:"resultCode"`
|
||||
ResultMsg string `json:"resultMsg"`
|
||||
ResultCode json.RawMessage `json:"resultCode"`
|
||||
ResultMsg string `json:"resultMsg"`
|
||||
NeedCaptcha bool `json:"needCaptcha"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err == nil {
|
||||
switch result.ResultCode {
|
||||
case 1:
|
||||
codeStr := strings.Trim(string(result.ResultCode), `"`)
|
||||
switch codeStr {
|
||||
case "1":
|
||||
return sc.jar.AllCookies(), nil
|
||||
case -4:
|
||||
case "-4":
|
||||
return nil, fmt.Errorf("验证码错误")
|
||||
case -3:
|
||||
case "-3":
|
||||
return nil, fmt.Errorf("账号或密码错误")
|
||||
case "FAIL_UPNOTMATCH":
|
||||
// 账号密码不匹配(实测返回格式,如哈尔滨商业大学)
|
||||
return nil, fmt.Errorf("用户名或密码不匹配,请检查后重试")
|
||||
case "CAPTCHA_NOTMATCH", "CAPTCHA_INVALID", "CAPTCHA_EXPIRED":
|
||||
return nil, fmt.Errorf("验证码错误或已过期,请重试")
|
||||
case "SUCCESS", "TRUE", "OK":
|
||||
return sc.jar.AllCookies(), nil
|
||||
}
|
||||
if result.ResultMsg != "" {
|
||||
return nil, fmt.Errorf("%s", result.ResultMsg)
|
||||
}
|
||||
if result.NeedCaptcha {
|
||||
return nil, fmt.Errorf("需要输入验证码")
|
||||
}
|
||||
slog.Warn("IAP登录未识别的resultCode",
|
||||
"school", school.Name,
|
||||
"resultCode", codeStr,
|
||||
"needCaptcha", result.NeedCaptcha,
|
||||
"body", string(body),
|
||||
)
|
||||
} else {
|
||||
slog.Warn("IAP登录响应解析失败",
|
||||
"school", school.Name,
|
||||
"error", err,
|
||||
"body", string(body),
|
||||
)
|
||||
}
|
||||
return nil, fmt.Errorf("IAP登录失败,未知错误")
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// ========== 南昌理工学院专用登录适配 ==========
|
||||
//
|
||||
// 该校(nut.campusphere.net)与标准金智 IAP / Apereo CAS 均不同,属于自研
|
||||
// 混合认证:
|
||||
// - /portal/login → 302 到 /iap/login?service=...(金智 IAP 入口)
|
||||
// - /iap/login 页面实际把表单提交到学校自研 CAS(my.nut.edu.cn/cas/login),
|
||||
// 表单字段为 username/password/authcode/execution/_eventId(CAS 风格)
|
||||
// - CAS 登录成功后 302 回跳 /iap/loginSuccess?sessionToken=xxx 建立 IAP 会话
|
||||
//
|
||||
// 该校密码加密特殊(见 security.js encryptedString):
|
||||
// - 密码先反转(split("").reverse().join(""))
|
||||
// - 明文块尾部补 0 到 chunkSize(2*模数最高非零 digit 索引)整数倍
|
||||
// - 每块按小端 16-bit digit 装配成大整数后直接做 m^e mod n(无 PKCS#1 填充)
|
||||
// - 输出各块 hex 密文,以空格分隔
|
||||
// - 公钥由 /cas/v2/getPubKey 动态返回(modulus/exponent,hex)
|
||||
//
|
||||
// 该校每次登录都需要图形验证码(/cas/v2/getKaptchaStatus 恒为 true),
|
||||
// 验证码图片地址 /cas/kaptcha?time=xxx。
|
||||
|
||||
// NutSchoolId 南昌理工学院 tenant id
|
||||
const NutSchoolId = "d6e8f2ca-10b2-4599-bdb8-4b33d419658d"
|
||||
|
||||
// nutCasIapLogin 南昌理工专用登录:CAS 认证 → 回跳 IAP 建立会话
|
||||
func nutCasIapLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, error) {
|
||||
sc := newSessionClient()
|
||||
base := strings.TrimSuffix(school.WecloudUrl, "/")
|
||||
if base == "" {
|
||||
base = strings.TrimSuffix(school.AmpUrl, "/")
|
||||
}
|
||||
slog.Info("南昌理工专用登录", "school", school.Name, "base", base)
|
||||
|
||||
// 1. /portal/login → 302 到 /iap/login?service=...
|
||||
sc.SetRedirectPolicy(resty.NoRedirectPolicy())
|
||||
portalResp, err := sc.R().SetContext(ctx).Get(base + "/portal/login")
|
||||
if err != nil && portalResp == nil {
|
||||
return nil, fmt.Errorf("请求portal/login失败: %w", err)
|
||||
}
|
||||
portalLoc, err := portalResp.RawResponse.Location()
|
||||
if err != nil || portalLoc == nil {
|
||||
return nil, fmt.Errorf("获取portal/login跳转地址失败: %w", err)
|
||||
}
|
||||
slog.Info("南昌理工portal跳转", "url", portalLoc.String())
|
||||
|
||||
// 2. 跟随到 CAS 登录页(my.nut.edu.cn/cas/login?service=...)
|
||||
sc.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
|
||||
loginPageResp, err := sc.R().SetContext(ctx).Get(portalLoc.String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取登录页失败: %w", err)
|
||||
}
|
||||
pageBody := readBody(loginPageResp)
|
||||
pageURL := loginPageResp.RawResponse.Request.URL
|
||||
casBase := pageURL.Scheme + "://" + pageURL.Host
|
||||
slog.Info("南昌理工CAS登录页", "finalUrl", pageURL.String(), "casBase", casBase)
|
||||
|
||||
formAction, execution, err := parseNutCasForm(pageBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
postUrl := casBase + formAction
|
||||
slog.Info("南昌理工CAS表单", "postUrl", postUrl, "executionLen", len(execution))
|
||||
|
||||
// 3-5. 提交登录:每次 attempt 重新获取登录页/公钥/验证码并加密提交
|
||||
// - execution 单次有效,重试必须刷新
|
||||
// - CAS 密钥对可能随登录页刷新而轮换,复用旧公钥加密会导致服务端
|
||||
// 解密失败,误报"用户名或密码错误"(2026-08-30 实测复现)
|
||||
// - 验证码依赖 OCR,存在误识别率;"用户名或密码错误"也可能是
|
||||
// 验证码错误被 CAS 统一提示,故一并纳入重试
|
||||
lastErr := ""
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
if attempt > 1 {
|
||||
// 重试时重新获取登录页(execution 已失效)
|
||||
pageBody, execution, formAction, err = refreshNutCasForm(ctx, sc, portalLoc.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
postUrl = casBase + formAction
|
||||
}
|
||||
|
||||
// 重新获取公钥并加密(每次 attempt 都刷新)
|
||||
pubKey, err := getNutPubKey(ctx, casBase, sc.Client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
slog.Info("南昌理工公钥", "modulusLen", len(pubKey.Modulus), "exponent", pubKey.Exponent)
|
||||
encPwd, err := nutRawRsaEncrypt(pubKey.Modulus, pubKey.Exponent, reverseString(password))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("南昌理工密码加密失败: %w", err)
|
||||
}
|
||||
|
||||
imgData, err := getNutKaptcha(ctx, casBase, sc.Client)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取南昌理工验证码失败: %w", err)
|
||||
}
|
||||
captchaCode := captchaOCR(imgData)
|
||||
slog.Info("南昌理工验证码OCR", "attempt", attempt, "code", captchaCode)
|
||||
if captchaCode == "" {
|
||||
lastErr = "验证码识别失败"
|
||||
continue
|
||||
}
|
||||
|
||||
submitData := map[string]string{
|
||||
"username": username,
|
||||
"password": encPwd,
|
||||
"authcode": captchaCode,
|
||||
"execution": execution,
|
||||
"_eventId": "submit",
|
||||
"rememberMe": "on",
|
||||
}
|
||||
sc.SetRedirectPolicy(resty.NoRedirectPolicy())
|
||||
loginResp, err := sc.R().SetContext(ctx).SetFormData(submitData).Post(postUrl)
|
||||
if err != nil && loginResp == nil {
|
||||
return nil, fmt.Errorf("提交南昌理工登录失败: %w", err)
|
||||
}
|
||||
|
||||
if loginResp.StatusCode() == 302 {
|
||||
loc, _ := loginResp.RawResponse.Location()
|
||||
slog.Info("南昌理工CAS登录成功", "redirect", loc.String())
|
||||
return followNutCasSuccess(ctx, loc, school, sc)
|
||||
}
|
||||
|
||||
// 200:重新渲染登录页,提取错误信息
|
||||
body := readBody(loginResp)
|
||||
msg := extractNutCasError(body)
|
||||
if msg == "" {
|
||||
msg = "登录失败"
|
||||
}
|
||||
slog.Info("南昌理工登录失败", "attempt", attempt, "msg", msg)
|
||||
if strings.Contains(msg, "验证码") || strings.Contains(msg, "用户名或密码") {
|
||||
lastErr = msg
|
||||
continue // OCR 误识别或凭据校验类错误,重试
|
||||
}
|
||||
return nil, errors.New(msg)
|
||||
}
|
||||
return nil, fmt.Errorf("%s", lastErr)
|
||||
}
|
||||
|
||||
// nutCasForm 登录页解析结果
|
||||
type nutCasForm struct {
|
||||
Action string
|
||||
Execution string
|
||||
}
|
||||
|
||||
func parseNutCasForm(page []byte) (action, execution string, err error) {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(page)))
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("解析南昌理工登录页失败: %w", err)
|
||||
}
|
||||
formSel := doc.Find("form").First()
|
||||
action, _ = formSel.Attr("action")
|
||||
if action == "" {
|
||||
return "", "", fmt.Errorf("南昌理工登录页缺少form action")
|
||||
}
|
||||
execution, _ = formSel.Find("input[name=execution]").Attr("value")
|
||||
if execution == "" {
|
||||
return "", "", fmt.Errorf("南昌理工登录页缺少execution")
|
||||
}
|
||||
return action, execution, nil
|
||||
}
|
||||
|
||||
// refreshNutCasForm 重新获取登录页与表单(验证码重试时使用)
|
||||
func refreshNutCasForm(ctx context.Context, sc *sessionClient, iapLoginUrl string) (page []byte, execution, action string, err error) {
|
||||
sc.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
|
||||
resp, err := sc.R().SetContext(ctx).Get(iapLoginUrl)
|
||||
if err != nil {
|
||||
return nil, "", "", fmt.Errorf("重新获取登录页失败: %w", err)
|
||||
}
|
||||
body := readBody(resp)
|
||||
action, execution, err = parseNutCasForm(body)
|
||||
return body, execution, action, err
|
||||
}
|
||||
|
||||
// nutPubKey 动态 RSA 公钥
|
||||
type nutPubKey struct {
|
||||
Modulus string
|
||||
Exponent string
|
||||
}
|
||||
|
||||
// getNutPubKey 获取动态 RSA 公钥
|
||||
func getNutPubKey(ctx context.Context, casBase string, client *resty.Client) (nutPubKey, error) {
|
||||
var result nutPubKey
|
||||
resp, err := client.R().SetContext(ctx).Get(casBase + "/cas/v2/getPubKey")
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("获取南昌理工公钥失败: %w", err)
|
||||
}
|
||||
body := readBody(resp)
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return result, fmt.Errorf("解析南昌理工公钥失败: %w", err)
|
||||
}
|
||||
if result.Modulus == "" || result.Exponent == "" {
|
||||
return result, fmt.Errorf("南昌理工公钥为空")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// getNutKaptcha 获取验证码图片
|
||||
func getNutKaptcha(ctx context.Context, casBase string, client *resty.Client) ([]byte, error) {
|
||||
ts := time.Now().UnixMilli()
|
||||
resp, err := client.R().SetContext(ctx).Get(fmt.Sprintf("%s/cas/kaptcha?time=%d", casBase, ts))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return readBody(resp), nil
|
||||
}
|
||||
|
||||
// followNutCasSuccess 跟随 CAS 成功跳转,回到 IAP 建立会话
|
||||
func followNutCasSuccess(ctx context.Context, jumpUrl *url.URL, school *SchoolDetailInfo, sc *sessionClient) ([]*http.Cookie, error) {
|
||||
sc.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
|
||||
verifyResp, err := sc.R().SetContext(ctx).Get(jumpUrl.String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("跟随南昌理工登录回跳失败: %w", err)
|
||||
}
|
||||
slog.Info("南昌理工IAP回跳", "status", verifyResp.StatusCode(), "finalUrl", verifyResp.RawResponse.Request.URL.String())
|
||||
|
||||
activateSession(ctx, school.WecloudUrl, sc.Client)
|
||||
return sc.jar.AllCookies(), nil
|
||||
}
|
||||
|
||||
// extractNutCasError 提取登录失败页的错误信息(#msg 或 #errormsg)
|
||||
func extractNutCasError(page []byte) string {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(page)))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, sel := range []string{"#msg", "#errormsg", ".error"} {
|
||||
msg := strings.TrimSpace(doc.Find(sel).First().Text())
|
||||
if msg != "" {
|
||||
return msg
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// nutRawRsaEncrypt 南昌理工 raw RSA:明文块直接模幂(无 PKCS#1 填充),hex 空格分隔
|
||||
func nutRawRsaEncrypt(modulusHex, exponentHex, msg string) (string, error) {
|
||||
n := new(big.Int)
|
||||
if _, ok := n.SetString(modulusHex, 16); !ok {
|
||||
return "", fmt.Errorf("modulus解析失败")
|
||||
}
|
||||
e := new(big.Int)
|
||||
if _, ok := e.SetString(exponentHex, 16); !ok {
|
||||
return "", fmt.Errorf("exponent解析失败")
|
||||
}
|
||||
|
||||
// chunkSize = 2 * biHighIndex(m)
|
||||
// biHighIndex: modulus 按 16-bit 小端 digit 存储时最高非零 digit 索引
|
||||
modBytes, err := hex.DecodeString(modulusHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("modulus hex解码失败: %w", err)
|
||||
}
|
||||
digitCount := (len(modBytes) + 1) / 2
|
||||
biHighIndex := -1
|
||||
for i := digitCount - 1; i >= 0; i-- {
|
||||
lo := modBytes[len(modBytes)-1-i*2]
|
||||
var hi byte
|
||||
if idx := len(modBytes) - 2 - i*2; idx >= 0 {
|
||||
hi = modBytes[idx]
|
||||
}
|
||||
if uint16(hi)<<8|uint16(lo) != 0 {
|
||||
biHighIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if biHighIndex <= 0 {
|
||||
return "", fmt.Errorf("modulus异常(biHighIndex=%d)", biHighIndex)
|
||||
}
|
||||
chunkSize := 2 * biHighIndex
|
||||
|
||||
// 明文补 0 到 chunkSize 整数倍
|
||||
a := []byte(msg)
|
||||
for len(a)%chunkSize != 0 {
|
||||
a = append(a, 0)
|
||||
}
|
||||
|
||||
// 分块加密:块内每 2 字节小端装配为一个 16-bit digit
|
||||
var parts []string
|
||||
for i := 0; i < len(a); i += chunkSize {
|
||||
block := new(big.Int)
|
||||
for j := 0; j < chunkSize/2; j++ {
|
||||
d := uint16(a[i+2*j]) | uint16(a[i+2*j+1])<<8
|
||||
block.Add(block, new(big.Int).Lsh(big.NewInt(int64(d)), uint(16*j)))
|
||||
}
|
||||
c := new(big.Int).Exp(block, e, n)
|
||||
parts = append(parts, c.Text(16))
|
||||
}
|
||||
return strings.Join(parts, " "), nil
|
||||
}
|
||||
|
||||
func reverseString(s string) string {
|
||||
r := []rune(s)
|
||||
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
|
||||
r[i], r[j] = r[j], r[i]
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
@@ -149,12 +150,35 @@ var iapSchoolIds = map[string]bool{
|
||||
"01e270d1-00e2-4ce9-b0af-5d5fbd462b8a": true, // 河北石油职业技术大学
|
||||
}
|
||||
|
||||
// hasUsableLoginUrl 判断学校是否具备可用的登录地址(IAP/CAS 都需要)
|
||||
func hasUsableLoginUrl(school *SchoolDetailInfo) bool {
|
||||
return school != nil && (school.IdsUrl != "" || school.WecloudUrl != "" ||
|
||||
school.AmpUrl != "" || school.AmpUrl2 != "" || school.AmpUrl3 != "")
|
||||
}
|
||||
|
||||
// CpdailyLogin 执行 cpdaily 登录
|
||||
// 返回登录成功后的所有 cookies
|
||||
func CpdailyLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, error) {
|
||||
if school.IsIap() || iapSchoolIds[school.ID] {
|
||||
// 南昌理工学院:自研 CAS→IAP 混合认证,与通用 IAP/CAS 流程均不兼容,单独适配
|
||||
if school.ID == NutSchoolId {
|
||||
return nutCasIapLogin(ctx, school, username, password)
|
||||
}
|
||||
// 合肥师范学院:学校统一身份认证 SSO 会拒绝单点登录跳转("系统拒绝单点登录跳转"),
|
||||
// 但其 wecloud 网关(hfnu.campusphere.net)支持标准 IAP 账密登录,单独走 IAP
|
||||
if school.ID == HfnuSchoolId {
|
||||
return iapLogin(ctx, school, username, password)
|
||||
}
|
||||
if school.IsIap() || iapSchoolIds[school.ID] {
|
||||
if !hasUsableLoginUrl(school) {
|
||||
slog.Warn("IAP学校缺少登录地址", "school", school.Name, "schoolId", school.ID)
|
||||
return nil, fmt.Errorf("该校登录配置不完整(缺少登录地址),暂不支持自动登录,请稍后重试或提交待适配反馈")
|
||||
}
|
||||
return iapLogin(ctx, school, username, password)
|
||||
}
|
||||
if !hasUsableLoginUrl(school) {
|
||||
slog.Warn("CAS学校缺少登录地址", "school", school.Name, "schoolId", school.ID)
|
||||
return nil, fmt.Errorf("该校暂未开放自动登录(待适配),请稍后重试或提交待适配反馈")
|
||||
}
|
||||
return casLogin(ctx, school, username, password)
|
||||
}
|
||||
|
||||
|
||||
@@ -221,6 +221,11 @@ func (r *submitCaptchaResolver) getResultFromItStar(rawResponse json.RawMessage)
|
||||
return nil, fmt.Errorf("验证码识别出错: %s", itResp.Msg)
|
||||
}
|
||||
|
||||
// AI 未识别出任何验证码值:直接报错,由上层重试(重新创建验证码图)
|
||||
if len(itResp.Data) == 0 {
|
||||
return nil, fmt.Errorf("验证码识别结果为空: %s", itResp.Msg)
|
||||
}
|
||||
|
||||
return itResp.Data, nil
|
||||
}
|
||||
|
||||
@@ -230,6 +235,13 @@ func (r *submitCaptchaResolver) submitCaptcha(info *ValidationInfo, captchaInfo
|
||||
targetURL := baseURL + "/captcha-open-api/v1/captcha/validate/scenesImage"
|
||||
|
||||
// 构建 URL-encoded 表单数据
|
||||
if captchaInfo.Code == "" {
|
||||
return "", fmt.Errorf("创建验证码返回的场景码为空")
|
||||
}
|
||||
if len(codes) == 0 {
|
||||
return "", fmt.Errorf("验证码识别结果为空,不提交空验证码")
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("accountKey", info.AccountKey)
|
||||
form.Set("sceneCode", info.SceneCode)
|
||||
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -49,20 +51,20 @@ type TodayTaskInfo struct {
|
||||
|
||||
// TaskFormDetail 签到任务表单详情
|
||||
type TaskFormDetail struct {
|
||||
Rows map[string]interface{} `json:"rows"`
|
||||
RealTitle string `json:"realTitle"`
|
||||
SignWid string `json:"signWid"`
|
||||
SignInstanceWid string `json:"signInstanceWid"`
|
||||
IsPhoto bool `json:"isPhoto"`
|
||||
IsNeedExtra bool `json:"isNeedExtra"`
|
||||
ExtraField []interface{} `json:"extraField,omitempty"`
|
||||
HistoryRows map[string]interface{} `json:"historyRows,omitempty"`
|
||||
Rows map[string]interface{} `json:"rows"`
|
||||
RealTitle string `json:"realTitle"`
|
||||
SignWid string `json:"signWid"`
|
||||
SignInstanceWid string `json:"signInstanceWid"`
|
||||
IsPhoto bool `json:"isPhoto"`
|
||||
IsNeedExtra bool `json:"isNeedExtra"`
|
||||
ExtraField []interface{} `json:"extraField,omitempty"`
|
||||
HistoryRows map[string]interface{} `json:"historyRows,omitempty"`
|
||||
}
|
||||
|
||||
// newRestyClient 创建 resty 客户端
|
||||
func newTaskClient() *resty.Client {
|
||||
return resty.New().
|
||||
SetTimeout(30*time.Second).
|
||||
SetTimeout(30 * time.Second).
|
||||
SetDoNotParseResponse(true).
|
||||
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
|
||||
}
|
||||
@@ -324,7 +326,7 @@ func FetchHistoryFormData(cookieMap map[string]string, host string, taskType Tas
|
||||
todayTasks, _ := FetchTodayTasks(cookieMap, host, taskType)
|
||||
for _, t := range todayTasks {
|
||||
if t.IsSigned && globMatch(t.TaskName, realTitle) && t.SignInstanceWid != excludeSignInstanceWid {
|
||||
detail, err := FetchTaskDetail(cookieMap, host, taskType, t.SignWid, t.SignInstanceWid, t.TaskName)
|
||||
detail, err := GetTaskDetailByWid(cookieMap, host, taskType, t.SignWid, t.SignInstanceWid, t.TaskName)
|
||||
if err == nil && detail != nil {
|
||||
return detail.Rows
|
||||
}
|
||||
@@ -339,7 +341,7 @@ func FetchHistoryFormData(cookieMap map[string]string, host string, taskType Tas
|
||||
monthTasks, _ := fetchTasksByYearMonth(cookieMap, host, taskType, year, month)
|
||||
for _, t := range monthTasks {
|
||||
if t.IsSigned && globMatch(t.TaskName, realTitle) && t.SignInstanceWid != excludeSignInstanceWid {
|
||||
detail, err := FetchTaskDetail(cookieMap, host, taskType, t.SignWid, t.SignInstanceWid, t.TaskName)
|
||||
detail, err := GetTaskDetailByWid(cookieMap, host, taskType, t.SignWid, t.SignInstanceWid, t.TaskName)
|
||||
if err == nil && detail != nil {
|
||||
return detail.Rows
|
||||
}
|
||||
@@ -363,8 +365,53 @@ func mapValueStr(m map[string]interface{}, key string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// FetchTaskDetail 获取签到任务详情(表单字段)
|
||||
func FetchTaskDetail(cookieMap map[string]string, host string, taskType TaskType, signWid, signInstanceWid, title string) (*TaskFormDetail, error) {
|
||||
// GetTaskDetailByWid 按 wid 直接拉取任务详情(表单预览、历史表单预填充等场景,无任何回退)
|
||||
func GetTaskDetailByWid(cookieMap map[string]string, host string, taskType TaskType, signWid, signInstanceWid, title string) (*TaskFormDetail, error) {
|
||||
return fetchTaskDetailByWid(cookieMap, host, taskType, signWid, signInstanceWid, title)
|
||||
}
|
||||
|
||||
// FetchTodayTaskDetail 任务执行专用:按任务名从当天列表实时匹配未签到的实例并拉取详情。
|
||||
// wid 每次执行时自动获取,不依赖配置快照;匹配失败直接报明确错误,不做任何回退。
|
||||
func FetchTodayTaskDetail(cookieMap map[string]string, host string, taskType TaskType, title string) (*TaskFormDetail, error) {
|
||||
tasks, err := fetchTasksByEndpoint(cookieMap, host, taskType, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取当日任务列表失败: %w", err)
|
||||
}
|
||||
var signed, target *TodayTaskInfo
|
||||
for i := range tasks {
|
||||
t := tasks[i]
|
||||
if !globMatch(t.TaskName, title) || t.SignInstanceWid == "" {
|
||||
continue
|
||||
}
|
||||
if !t.IsSigned {
|
||||
target = &t
|
||||
break
|
||||
}
|
||||
if signed == nil {
|
||||
s := t
|
||||
signed = &s
|
||||
}
|
||||
}
|
||||
if target == nil {
|
||||
if signed != nil {
|
||||
return nil, fmt.Errorf("「%s」今日已签到,无需重复执行", title)
|
||||
}
|
||||
return nil, fmt.Errorf("当日任务列表中未找到「%s」", title)
|
||||
}
|
||||
slog.Info("按任务名实时匹配到当日任务实例",
|
||||
"title", title, "signInstanceWid", target.SignInstanceWid, "taskType", taskType)
|
||||
detail, err := fetchTaskDetailByWid(cookieMap, host, taskType, target.SignWid, target.SignInstanceWid, target.TaskName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if detail.Rows == nil {
|
||||
return nil, fmt.Errorf("获取「%s」任务详情为空", title)
|
||||
}
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
// fetchTaskDetailByWid 按 wid 拉取任务详情(纯查询,无任何回退逻辑)
|
||||
func fetchTaskDetailByWid(cookieMap map[string]string, host string, taskType TaskType, signWid, signInstanceWid, title string) (*TaskFormDetail, error) {
|
||||
client := newTaskClient()
|
||||
cookieStr := cookiesToStr(cookieMap)
|
||||
baseURL := taskBasePath(host, taskType)
|
||||
@@ -407,6 +454,10 @@ func FetchTaskDetail(cookieMap map[string]string, host string, taskType TaskType
|
||||
SignInstanceWid: signInstanceWid,
|
||||
}
|
||||
|
||||
if rows == nil {
|
||||
return detail, nil
|
||||
}
|
||||
|
||||
if v, ok := rows["isPhoto"]; ok {
|
||||
if f, ok := v.(float64); ok && f == 1 {
|
||||
detail.IsPhoto = true
|
||||
@@ -575,8 +626,16 @@ func ParseTaskForm(detail *TaskFormDetail, historyRows map[string]interface{}) [
|
||||
Tip: "签到完毕后查看时最底部那个最详细的地址信息",
|
||||
})
|
||||
|
||||
// 签到照片(如果需要,必填)
|
||||
if detail.IsPhoto {
|
||||
// 签到照片(如果需要,必填);详情未返回时以历史记录的 isPhoto 兜底
|
||||
isPhoto := detail.IsPhoto
|
||||
if !isPhoto && histRows != nil {
|
||||
if v, ok := histRows["isPhoto"]; ok {
|
||||
if f, ok := v.(float64); ok && f == 1 {
|
||||
isPhoto = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if isPhoto {
|
||||
list = append(list, cpdmodel.CpTaskFormItem{
|
||||
Title: "签到照片",
|
||||
ColName: "signImg",
|
||||
@@ -585,7 +644,6 @@ func ParseTaskForm(detail *TaskFormDetail, historyRows map[string]interface{}) [
|
||||
Content: histSignPhotoUrl,
|
||||
Default: histSignPhotoUrl,
|
||||
Show: true,
|
||||
Tip: "您可以上传多张图片,会顺序轮换更新",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -781,6 +839,132 @@ func FillSubmitForm(rows map[string]interface{}, formItems []cpdmodel.CpTaskForm
|
||||
return result
|
||||
}
|
||||
|
||||
// SignPlace 查寝组/签到任务配置的签到范围点
|
||||
type SignPlace struct {
|
||||
Address string
|
||||
Longitude string // 原始字符串,保持精度
|
||||
Latitude string // 原始字符串,保持精度
|
||||
LongitudeF float64 // 用于距离计算
|
||||
LatitudeF float64
|
||||
RadiusMeters float64
|
||||
}
|
||||
|
||||
// parseSignPlaces 解析任务详情中的 signPlaceSelected(兼容 JSON 字符串与数组两种格式)
|
||||
func parseSignPlaces(rows map[string]interface{}) []SignPlace {
|
||||
if rows == nil {
|
||||
return nil
|
||||
}
|
||||
var places []SignPlace
|
||||
appendPlace := func(m map[string]interface{}) {
|
||||
lon := mapValueStr(m, "longitude")
|
||||
lat := mapValueStr(m, "latitude")
|
||||
if lon == "" || lat == "" {
|
||||
return
|
||||
}
|
||||
lonF, err1 := strconv.ParseFloat(lon, 64)
|
||||
latF, err2 := strconv.ParseFloat(lat, 64)
|
||||
if err1 != nil || err2 != nil {
|
||||
return
|
||||
}
|
||||
radius := 0.0
|
||||
if r, ok := m["radius"]; ok && r != nil {
|
||||
if f, ok := r.(float64); ok {
|
||||
radius = f
|
||||
} else {
|
||||
radius, _ = strconv.ParseFloat(fmt.Sprintf("%v", r), 64)
|
||||
}
|
||||
}
|
||||
if radius <= 0 {
|
||||
return
|
||||
}
|
||||
places = append(places, SignPlace{
|
||||
Address: mapValueStr(m, "address"),
|
||||
Longitude: lon,
|
||||
Latitude: lat,
|
||||
LongitudeF: lonF,
|
||||
LatitudeF: latF,
|
||||
RadiusMeters: radius,
|
||||
})
|
||||
}
|
||||
if sps, ok := rows["signPlaceSelected"]; ok {
|
||||
switch v := sps.(type) {
|
||||
case string:
|
||||
if v != "" && v != "[]" {
|
||||
var arr []map[string]interface{}
|
||||
if json.Unmarshal([]byte(v), &arr) == nil {
|
||||
for _, m := range arr {
|
||||
appendPlace(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
case []interface{}:
|
||||
for _, p := range v {
|
||||
if m, ok := p.(map[string]interface{}); ok {
|
||||
appendPlace(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return places
|
||||
}
|
||||
|
||||
// haversineMeters 计算两个经纬度坐标之间的球面距离(米)
|
||||
func haversineMeters(lat1, lon1, lat2, lon2 float64) float64 {
|
||||
const earthRadius = 6371000.0
|
||||
rad := math.Pi / 180.0
|
||||
dLat := (lat2 - lat1) * rad
|
||||
dLon := (lon2 - lon1) * rad
|
||||
a := math.Sin(dLat/2)*math.Sin(dLat/2) +
|
||||
math.Cos(lat1*rad)*math.Cos(lat2*rad)*math.Sin(dLon/2)*math.Sin(dLon/2)
|
||||
return 2 * earthRadius * math.Asin(math.Sqrt(a))
|
||||
}
|
||||
|
||||
// AdjustSubmitFormToSignRange 提交前校验历史位置是否落在查寝组签到范围内,
|
||||
// 若超出所有签到点范围则自动改用距离最近的签到点坐标(避免服务端拒绝"位置不在签到范围内")。
|
||||
// 返回 true 表示发生了坐标调整。
|
||||
func AdjustSubmitFormToSignRange(submitForm map[string]interface{}, detailRows map[string]interface{}) bool {
|
||||
places := parseSignPlaces(detailRows)
|
||||
if len(places) == 0 {
|
||||
return false
|
||||
}
|
||||
latStr, _ := submitForm["latitude"].(string)
|
||||
lonStr, _ := submitForm["longitude"].(string)
|
||||
lat, err1 := strconv.ParseFloat(strings.TrimSpace(latStr), 64)
|
||||
lon, err2 := strconv.ParseFloat(strings.TrimSpace(lonStr), 64)
|
||||
if err1 != nil || err2 != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
best := -1
|
||||
bestDist := math.MaxFloat64
|
||||
for i, p := range places {
|
||||
d := haversineMeters(lat, lon, p.LatitudeF, p.LongitudeF)
|
||||
if d <= p.RadiusMeters {
|
||||
// 历史位置在某个签到点范围内,正常沿用历史记录
|
||||
return false
|
||||
}
|
||||
if d < bestDist {
|
||||
bestDist = d
|
||||
best = i
|
||||
}
|
||||
}
|
||||
if best < 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
p := places[best]
|
||||
submitForm["latitude"] = p.Latitude
|
||||
submitForm["longitude"] = p.Longitude
|
||||
if p.Address != "" {
|
||||
submitForm["position"] = p.Address
|
||||
}
|
||||
slog.Info("历史位置超出查寝组所有签到范围,自动改用最近签到点",
|
||||
"origLat", latStr, "origLon", lonStr,
|
||||
"newLat", p.Latitude, "newLon", p.Longitude,
|
||||
"place", p.Address, "distM", int(bestDist), "radiusM", int(p.RadiusMeters))
|
||||
return true
|
||||
}
|
||||
|
||||
// GetBodyString 加密提交表单为 bodyString
|
||||
func GetBodyString(form map[string]interface{}) string {
|
||||
data, _ := json.Marshal(form)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 模拟阜阳职业技术学院查寝组真实返回的签到点配置
|
||||
func mockSignPlacesRows() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"signPlaceSelected": `[{"address":"七渔河东区","longitude":"115.78725271446127","latitude":"32.90506452710031","radius":500},
|
||||
{"address":"新建的签到地点","longitude":"115.78725271446127","latitude":"32.90506452710031","radius":790},
|
||||
{"address":"新校区1000米","longitude":"115.77058016419615","latitude":"32.904624876025075","radius":1000},
|
||||
{"address":"新校区边角修正2","longitude":"115.77471236954204","latitude":"32.9053826914217","radius":500},
|
||||
{"address":"新校区边角修正1","longitude":"115.76709473881743","latitude":"32.90250295808209","radius":500}]`,
|
||||
}
|
||||
}
|
||||
|
||||
// 历史位置在"新校区1000米"点范围内(约932m)→ 不调整,沿用历史记录
|
||||
func TestAdjustInKeepHistory(t *testing.T) {
|
||||
form := map[string]interface{}{
|
||||
"latitude": "32.898615",
|
||||
"longitude": "115.763603",
|
||||
"position": "七渔河东区",
|
||||
}
|
||||
adjusted := AdjustSubmitFormToSignRange(form, mockSignPlacesRows())
|
||||
if adjusted {
|
||||
t.Fatalf("历史位置在范围内不应调整, form=%v", form)
|
||||
}
|
||||
if form["latitude"] != "32.898615" || form["longitude"] != "115.763603" {
|
||||
t.Fatalf("范围内历史坐标不应被修改: %v", form)
|
||||
}
|
||||
}
|
||||
|
||||
// 历史位置远离所有签到点(2km+)→ 调整为最近签到点坐标
|
||||
func TestAdjustOutOfRange(t *testing.T) {
|
||||
form := map[string]interface{}{
|
||||
"latitude": "32.880000",
|
||||
"longitude": "115.740000",
|
||||
"position": "旧位置",
|
||||
}
|
||||
adjusted := AdjustSubmitFormToSignRange(form, mockSignPlacesRows())
|
||||
if !adjusted {
|
||||
t.Fatal("完全出界的历史位置应被调整")
|
||||
}
|
||||
if form["longitude"] != "115.76709473881743" || form["latitude"] != "32.90250295808209" {
|
||||
t.Fatalf("应调整为最近的'边角修正1'坐标, got %v", form)
|
||||
}
|
||||
if form["position"] != "新校区边角修正1" {
|
||||
t.Fatalf("地址应同步为最近签到点: %v", form)
|
||||
}
|
||||
}
|
||||
|
||||
// 无 signPlaceSelected / 无 radius 时保持不动
|
||||
func TestAdjustNoPlaces(t *testing.T) {
|
||||
form := map[string]interface{}{"latitude": "32.88", "longitude": "115.74"}
|
||||
if AdjustSubmitFormToSignRange(form, map[string]interface{}{}) {
|
||||
t.Fatal("无签到点配置不应调整")
|
||||
}
|
||||
if AdjustSubmitFormToSignRange(form, map[string]interface{}{"signPlaceSelected": "[]"}) {
|
||||
t.Fatal("空签到点不应调整")
|
||||
}
|
||||
}
|
||||
|
||||
// 坐标解析异常时保持不动
|
||||
func TestAdjustBadCoord(t *testing.T) {
|
||||
form := map[string]interface{}{"latitude": "", "longitude": "abc"}
|
||||
if AdjustSubmitFormToSignRange(form, mockSignPlacesRows()) {
|
||||
t.Fatal("坐标异常不应调整")
|
||||
}
|
||||
}
|
||||
|
||||
// haversine 距离合理性:边角修正1距历史位置约540m,七渔河东区约2.26km
|
||||
func TestHaversineMeters(t *testing.T) {
|
||||
d1 := haversineMeters(32.898615, 115.763603, 32.90250295808209, 115.76709473881743)
|
||||
if d1 < 480 || d1 > 600 {
|
||||
t.Fatalf("距边角修正1应约540m, got %.0f", d1)
|
||||
}
|
||||
d2 := haversineMeters(32.898615, 115.763603, 32.90506452710031, 115.78725271446127)
|
||||
if d2 < 2000 || d2 > 2500 {
|
||||
t.Fatalf("距七渔河东区应约2.26km, got %.0f", d2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
)
|
||||
|
||||
// 系统配置 key(与 system_configs 表对应,后台「系统设置」页可编辑)
|
||||
const (
|
||||
CfgSmtpHost = "smtp_host" // SMTP 服务器地址
|
||||
CfgSmtpPort = "smtp_port" // SMTP 端口
|
||||
CfgSmtpUser = "smtp_user" // SMTP 用户名
|
||||
CfgSmtpPassword = "smtp_password" // SMTP 密码/授权码
|
||||
CfgSmtpFrom = "smtp_from" // 发件人地址(默认取 smtp_user)
|
||||
CfgSmtpFromName = "smtp_from_name" // 发件人显示名称
|
||||
CfgSmtpSecure = "smtp_secure" // ssl / starttls / none,留空按端口自动判断
|
||||
CfgAdminEmails = "admin_emails" // 管理员收件邮箱(多个用英文逗号分隔)
|
||||
)
|
||||
|
||||
type smtpSettings struct {
|
||||
Host string
|
||||
Port string
|
||||
User string
|
||||
Password string
|
||||
From string
|
||||
FromName string
|
||||
Secure string // ssl / starttls / none
|
||||
}
|
||||
|
||||
// loadSmtpSettings 从 system_configs 读取 SMTP 配置
|
||||
func loadSmtpSettings() (*smtpSettings, error) {
|
||||
var configs []model.SystemConfig
|
||||
database.DB.Find(&configs)
|
||||
m := make(map[string]string)
|
||||
for _, cfg := range configs {
|
||||
m[cfg.Key] = cfg.Value
|
||||
}
|
||||
|
||||
s := &smtpSettings{
|
||||
Host: strings.TrimSpace(m[CfgSmtpHost]),
|
||||
Port: strings.TrimSpace(m[CfgSmtpPort]),
|
||||
User: strings.TrimSpace(m[CfgSmtpUser]),
|
||||
Password: m[CfgSmtpPassword],
|
||||
From: strings.TrimSpace(m[CfgSmtpFrom]),
|
||||
FromName: strings.TrimSpace(m[CfgSmtpFromName]),
|
||||
Secure: strings.ToLower(strings.TrimSpace(m[CfgSmtpSecure])),
|
||||
}
|
||||
if s.From == "" {
|
||||
s.From = s.User
|
||||
}
|
||||
if s.Host == "" || s.Port == "" || s.User == "" {
|
||||
return nil, errors.New("SMTP 未配置完整(host/port/user 必填)")
|
||||
}
|
||||
if s.From == "" {
|
||||
return nil, errors.New("SMTP 发件人地址未配置")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// SplitEmailsList 拆分逗号分隔的邮箱列表并过滤空项
|
||||
func SplitEmailsList(raw string) []string {
|
||||
var out []string
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
p := strings.TrimSpace(part)
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// smtpSecureMode 决定连接加密方式:显式配置优先,否则按端口推断
|
||||
func (s *smtpSettings) smtpSecureMode() string {
|
||||
if s.Secure != "" {
|
||||
return s.Secure
|
||||
}
|
||||
if s.Port == "465" {
|
||||
return "ssl"
|
||||
}
|
||||
return "starttls"
|
||||
}
|
||||
|
||||
// encodeRFC2047 编码邮件头中的非 ASCII 文本(如中文主题/发件人名称)
|
||||
func encodeRFC2047(text string) string {
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
ascii := true
|
||||
for _, r := range text {
|
||||
if r > 127 {
|
||||
ascii = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ascii {
|
||||
return text
|
||||
}
|
||||
return "=?utf-8?B?" + base64.StdEncoding.EncodeToString([]byte(text)) + "?="
|
||||
}
|
||||
|
||||
// SendMail 发送一封 HTML 邮件;未配置 SMTP 时返回明确错误(不 panic)
|
||||
func SendMail(to []string, subject, html string) error {
|
||||
if len(to) == 0 {
|
||||
return errors.New("收件人为空")
|
||||
}
|
||||
s, err := loadSmtpSettings()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fromName := s.FromName
|
||||
fromHeader := s.From
|
||||
if fromName != "" {
|
||||
fromHeader = encodeRFC2047(fromName) + " <" + s.From + ">"
|
||||
}
|
||||
|
||||
msg := "From: " + fromHeader + "\r\n" +
|
||||
"To: " + strings.Join(to, ",") + "\r\n" +
|
||||
"Subject: " + encodeRFC2047(subject) + "\r\n" +
|
||||
"MIME-Version: 1.0\r\n" +
|
||||
"Content-Type: text/html; charset=utf-8\r\n" +
|
||||
"Date: " + time.Now().Format(time.RFC1123Z) + "\r\n\r\n" +
|
||||
html
|
||||
|
||||
addr := net.JoinHostPort(s.Host, s.Port)
|
||||
auth := smtp.PlainAuth("", s.User, s.Password, s.Host)
|
||||
|
||||
var client *smtp.Client
|
||||
mode := s.smtpSecureMode()
|
||||
|
||||
switch mode {
|
||||
case "ssl":
|
||||
// 465 直接 TLS
|
||||
conn, err := tls.Dial("tcp", addr, &tls.Config{
|
||||
ServerName: s.Host,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP SSL 连接失败: %w", err)
|
||||
}
|
||||
client, err = smtp.NewClient(conn, s.Host)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return fmt.Errorf("SMTP 握手失败: %w", err)
|
||||
}
|
||||
case "starttls":
|
||||
conn, err := net.DialTimeout("tcp", addr, 15*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 连接失败: %w", err)
|
||||
}
|
||||
client, err = smtp.NewClient(conn, s.Host)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return fmt.Errorf("SMTP 握手失败: %w", err)
|
||||
}
|
||||
if err := client.StartTLS(&tls.Config{ServerName: s.Host, MinVersion: tls.VersionTLS12}); err != nil {
|
||||
client.Close()
|
||||
return fmt.Errorf("SMTP STARTTLS 失败: %w", err)
|
||||
}
|
||||
case "none":
|
||||
conn, err := net.DialTimeout("tcp", addr, 15*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP 连接失败: %w", err)
|
||||
}
|
||||
client, err = smtp.NewClient(conn, s.Host)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return fmt.Errorf("SMTP 握手失败: %w", err)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("不支持的 smtp_secure 值: %s", s.Secure)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
if err := client.Auth(auth); err != nil {
|
||||
// 明文连接下部分服务器(如本地测试)不支持 AUTH,仅在 secure=none 时容忍
|
||||
if mode == "none" {
|
||||
slog.Warn("SMTP AUTH 失败但继续发送(明文模式)", "error", err)
|
||||
} else {
|
||||
return fmt.Errorf("SMTP 认证失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := client.Mail(s.From); err != nil {
|
||||
return fmt.Errorf("SMTP MAIL FROM 失败: %w", err)
|
||||
}
|
||||
for _, rcpt := range to {
|
||||
if err := client.Rcpt(rcpt); err != nil {
|
||||
return fmt.Errorf("SMTP RCPT %s 失败: %w", rcpt, err)
|
||||
}
|
||||
}
|
||||
w, err := client.Data()
|
||||
if err != nil {
|
||||
return fmt.Errorf("SMTP DATA 失败: %w", err)
|
||||
}
|
||||
if _, err := w.Write([]byte(msg)); err != nil {
|
||||
w.Close()
|
||||
return fmt.Errorf("SMTP 写入邮件内容失败: %w", err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return fmt.Errorf("SMTP 发送内容失败: %w", err)
|
||||
}
|
||||
if err := client.Quit(); err != nil {
|
||||
slog.Debug("SMTP QUIT 警告", "error", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendMailAsync 异步发送邮件(带超时与 panic 保护,不阻塞业务)
|
||||
func SendMailAsync(to []string, subject, html string) {
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
slog.Error("发送邮件 panic", "error", r)
|
||||
}
|
||||
}()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- SendMail(to, subject, html)
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
slog.Error("发送邮件失败", "to", to, "subject", subject, "error", err)
|
||||
} else {
|
||||
slog.Info("邮件发送成功", "to", to, "subject", subject)
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
slog.Error("发送邮件超时", "to", to, "subject", subject)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// GetAdminEmails 读取管理员通知邮箱列表
|
||||
func GetAdminEmails() []string {
|
||||
var configs []model.SystemConfig
|
||||
database.DB.Find(&configs)
|
||||
for _, cfg := range configs {
|
||||
if cfg.Key == CfgAdminEmails {
|
||||
return SplitEmailsList(cfg.Value)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ========== 业务邮件模板 ==========
|
||||
|
||||
// EmailBody 组装简单邮件正文
|
||||
func EmailBody(inner string) string {
|
||||
return `<div style="font-family:-apple-system,'PingFang SC','Microsoft YaHei',sans-serif;max-width:600px;margin:0 auto;padding:24px;background:#f7f8fa">` +
|
||||
`<div style="background:#fff;border-radius:12px;padding:24px;border:1px solid #eee">` + inner + `</div>` +
|
||||
`<p style="color:#aaa;font-size:12px;text-align:center;margin-top:16px">小助手自动通知,请勿直接回复</p></div>`
|
||||
}
|
||||
|
||||
// NotifyNewPendingSchool 新待适配学校提醒(发给管理员)
|
||||
func NotifyNewPendingSchool(name, username, ip, email, submitAt string) {
|
||||
adminEmails := GetAdminEmails()
|
||||
if len(adminEmails) == 0 {
|
||||
slog.Info("未配置管理员邮箱,跳过新待适配通知", "school", name)
|
||||
return
|
||||
}
|
||||
subject := "【小助手】新的待适配学校:" + name
|
||||
inner := `<h2 style="margin:0 0 16px;font-size:17px">收到新的待适配学校提交</h2>
|
||||
<table style="border-collapse:collapse;font-size:14px;color:#333;line-height:2">
|
||||
<tr><td style="padding-right:16px;color:#888">学校</td><td><b>` + name + `</b></td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888">测试账号</td><td>` + username + `</td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888">提交IP</td><td>` + ip + `</td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888">联系邮箱</td><td>` + email + `</td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888">提交时间</td><td>` + submitAt + `</td></tr>
|
||||
</table>
|
||||
<p style="color:#888;font-size:13px;margin-top:12px">请到管理后台「待适配学校」查看账号密码并安排适配。</p>`
|
||||
SendMailAsync(adminEmails, subject, EmailBody(inner))
|
||||
}
|
||||
|
||||
// NotifySchoolAdapted 学校适配完成通知(发给该学校提交者留下的全部联系邮箱)
|
||||
func NotifySchoolAdapted(contactEmails []string, schoolName string) {
|
||||
if len(contactEmails) == 0 {
|
||||
slog.Info("学校无联系邮箱,跳过适配完成通知", "school", schoolName)
|
||||
return
|
||||
}
|
||||
subject := "【小助手】" + schoolName + " 已适配完成"
|
||||
inner := `<h2 style="margin:0 0 16px;font-size:17px">好消息!` + schoolName + ` 已适配完成</h2>
|
||||
<p style="font-size:14px;color:#555;line-height:1.8">感谢您的耐心等待与反馈。该学校现已支持自动登录签到,您可以重新登录小助手使用签到、查寝等服务。</p>
|
||||
<p style="font-size:14px;color:#555">若仍有问题,欢迎在应用内提交工单反馈。</p>`
|
||||
SendMailAsync(contactEmails, subject, EmailBody(inner))
|
||||
}
|
||||
|
||||
// NotifySchoolRejected 学校适配申请拒绝通知(发给该学校提交者留下的全部联系邮箱,附拒绝理由)
|
||||
func NotifySchoolRejected(contactEmails []string, schoolName, reason string) {
|
||||
if len(contactEmails) == 0 {
|
||||
slog.Info("学校无联系邮箱,跳过拒绝通知", "school", schoolName)
|
||||
return
|
||||
}
|
||||
escapedReason := html.EscapeString(reason)
|
||||
escapedReason = strings.ReplaceAll(escapedReason, "\n", "<br/>")
|
||||
subject := "【小助手】" + schoolName + " 暂无法适配"
|
||||
inner := `<h2 style="margin:0 0 16px;font-size:17px">很抱歉,` + schoolName + ` 暂无法适配</h2>
|
||||
<p style="font-size:14px;color:#555;line-height:1.8">感谢您的反馈。经管理员核实,该学校暂时无法适配,具体原因如下:</p>
|
||||
<div style="font-size:14px;color:#333;line-height:1.8;background:#f7f8fa;border-radius:8px;padding:12px 16px;margin:12px 0">` + escapedReason + `</div>
|
||||
<p style="font-size:14px;color:#555">请核对账号信息后重新提交,或如有疑问欢迎在应用内提交工单反馈。</p>`
|
||||
SendMailAsync(contactEmails, subject, EmailBody(inner))
|
||||
}
|
||||
|
||||
// NotifyNewTicket 新工单提醒(发给管理员)
|
||||
func NotifyNewTicket(ticketID uint, username, schoolName, realName, title, content, createdAt string) {
|
||||
adminEmails := GetAdminEmails()
|
||||
if len(adminEmails) == 0 {
|
||||
slog.Info("未配置管理员邮箱,跳过新工单通知", "ticketId", ticketID)
|
||||
return
|
||||
}
|
||||
// 内容摘要:HTML 转义防注入,换行转 <br>,超长截断
|
||||
escaped := html.EscapeString(content)
|
||||
if len([]rune(escaped)) > 500 {
|
||||
escaped = string([]rune(escaped)[:500]) + "……"
|
||||
}
|
||||
escaped = strings.ReplaceAll(escaped, "\n", "<br/>")
|
||||
displayName := realName
|
||||
if displayName == "" {
|
||||
displayName = username
|
||||
}
|
||||
subject := "【小助手】新的工单:" + title
|
||||
inner := `<h2 style="margin:0 0 16px;font-size:17px">收到新的工单反馈</h2>
|
||||
<table style="border-collapse:collapse;font-size:14px;color:#333;line-height:2">
|
||||
<tr><td style="padding-right:16px;color:#888;vertical-align:top">标题</td><td><b>` + html.EscapeString(title) + `</b></td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888">用户</td><td>` + html.EscapeString(displayName) + `(` + html.EscapeString(username) + `)</td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888">学校</td><td>` + html.EscapeString(schoolName) + `</td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888;vertical-align:top">内容</td><td style="max-width:420px">` + escaped + `</td></tr>
|
||||
<tr><td style="padding-right:16px;color:#888">提交时间</td><td>` + html.EscapeString(createdAt) + `</td></tr>
|
||||
</table>
|
||||
<p style="color:#888;font-size:13px;margin-top:12px">请到管理后台「工单」查看详情并回复处理。</p>`
|
||||
SendMailAsync(adminEmails, subject, EmailBody(inner))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/config"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Redis 全局客户端(验证码存储/限流等)。启动时初始化,连接失败不阻断进程启动,
|
||||
// go-redis 会在后续请求时自动重连。
|
||||
var Redis *redis.Client
|
||||
|
||||
// InitRedis 初始化 Redis 客户端并做一次连通性探测
|
||||
func InitRedis() {
|
||||
cfg := config.Global.Redis
|
||||
if cfg.Host == "" {
|
||||
slog.Warn("未配置 [redis],验证码相关功能将不可用")
|
||||
return
|
||||
}
|
||||
Redis = redis.NewClient(&redis.Options{
|
||||
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.Db,
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := Redis.Ping(ctx).Err(); err != nil {
|
||||
slog.Error("Redis 连接失败(验证码功能暂不可用,请检查配置)", "addr", cfg.Host, "err", err)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ services:
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8884:8093"
|
||||
environment:
|
||||
- TZ=Asia/Shanghai
|
||||
volumes:
|
||||
- /opt/cpdaily-xiaozhushou/config.toml:/app/config.toml:ro
|
||||
networks:
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
||||
<title>小助手</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -28,7 +28,7 @@ watch(
|
||||
|
||||
<!-- Toast 容器 -->
|
||||
<Teleport to="body">
|
||||
<div class="fixed top-4 right-4 z-50 flex flex-col gap-2 max-w-sm">
|
||||
<div class="fixed top-4 right-4 z-[100] flex flex-col gap-2 max-w-sm">
|
||||
<TransitionGroup name="toast">
|
||||
<div
|
||||
v-for="toast in toasts"
|
||||
|
||||
+103
-7
@@ -137,6 +137,11 @@ export interface CDKCode {
|
||||
price: number
|
||||
costPrice: number
|
||||
agentId: number
|
||||
maxRuns: number
|
||||
/** CDK类型:count=次数卡 / vip=VIP时长卡 */
|
||||
type: 'count' | 'vip'
|
||||
/** VIP 时长天数(type=vip 有效:7=周卡 30=月卡) */
|
||||
vipDays: number
|
||||
status: string
|
||||
userId: number | null
|
||||
usedAt: string | null
|
||||
@@ -144,6 +149,28 @@ export interface CDKCode {
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface CDKSummary {
|
||||
total: number
|
||||
unused: number
|
||||
used: number
|
||||
disabled: number
|
||||
}
|
||||
|
||||
export interface CDKListResult {
|
||||
total: number
|
||||
items: CDKCode[]
|
||||
page: number
|
||||
pageSize: number
|
||||
summary: CDKSummary
|
||||
}
|
||||
|
||||
export interface CDKListParams {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
keyword?: string
|
||||
status?: string
|
||||
}
|
||||
|
||||
export interface GenerateCDKResult {
|
||||
count: number
|
||||
price: number
|
||||
@@ -152,19 +179,39 @@ export interface GenerateCDKResult {
|
||||
cdkCodes: CDKCode[]
|
||||
}
|
||||
|
||||
/** 生成CDK */
|
||||
export function generateCDK(count: number = 1, maxRuns: number = 1) {
|
||||
return api.post<{ data: GenerateCDKResult }>('/admin/cdks', { count, maxRuns })
|
||||
/** 生成CDK(type: count=次数 / vip=VIP时长,vipDays 默认 30 天) */
|
||||
export function generateCDK(
|
||||
count: number = 1,
|
||||
maxRuns: number = 1,
|
||||
type: 'count' | 'vip' = 'count',
|
||||
vipDays: number = 30
|
||||
) {
|
||||
return api.post<{ data: GenerateCDKResult }>('/admin/cdks', { count, maxRuns, type, vipDays })
|
||||
}
|
||||
|
||||
/** 获取自己生成的CDK列表 */
|
||||
export function getMyCDKs() {
|
||||
return api.get<{ data: CDKCode[] }>('/admin/cdks')
|
||||
export function getMyCDKs(params: CDKListParams = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', String(params.page || 1))
|
||||
qs.set('pageSize', String(params.pageSize || 20))
|
||||
if (params.keyword) qs.set('keyword', params.keyword)
|
||||
if (params.status) qs.set('status', params.status)
|
||||
return api.get<{ data: CDKListResult }>(`/admin/cdks?${qs.toString()}`)
|
||||
}
|
||||
|
||||
/** 获取所有CDK列表(admin only) */
|
||||
export function getAllCDKs() {
|
||||
return api.get<{ data: CDKCode[] }>('/admin/all-cdks')
|
||||
export function getAllCDKs(params: CDKListParams = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', String(params.page || 1))
|
||||
qs.set('pageSize', String(params.pageSize || 20))
|
||||
if (params.keyword) qs.set('keyword', params.keyword)
|
||||
if (params.status) qs.set('status', params.status)
|
||||
return api.get<{ data: CDKListResult }>(`/admin/all-cdks?${qs.toString()}`)
|
||||
}
|
||||
|
||||
/** 禁用/恢复CDK */
|
||||
export function updateCDKStatus(id: number, action: 'disable' | 'enable') {
|
||||
return api.put(`/admin/cdks/${id}/status`, { action })
|
||||
}
|
||||
|
||||
// ======== 系统设置(admin only) ========
|
||||
@@ -183,6 +230,11 @@ export function updateSetting(key: string, value: string) {
|
||||
return api.put('/admin/settings', { key, value })
|
||||
}
|
||||
|
||||
/** 发送 SMTP 测试邮件 */
|
||||
export function sendTestMail() {
|
||||
return api.post('/admin/settings/test-mail')
|
||||
}
|
||||
|
||||
// ======== 公告管理(admin only) ========
|
||||
|
||||
export interface Announcement {
|
||||
@@ -265,6 +317,8 @@ export interface UserListItem {
|
||||
signCount: number
|
||||
inviteReward: number
|
||||
invitedCount: number
|
||||
inviterId: number | null
|
||||
inviterName: string
|
||||
taskCount: number
|
||||
status: string
|
||||
createdAt: string
|
||||
@@ -289,6 +343,8 @@ export interface UserDetail {
|
||||
signCount: number
|
||||
inviteReward: number
|
||||
invitedCount: number
|
||||
inviterId: number | null
|
||||
inviterName: string
|
||||
status: string
|
||||
disabledReason: string
|
||||
taskCount: number
|
||||
@@ -316,3 +372,43 @@ export function getUserDetail(id: number) {
|
||||
export function updateUserStatus(id: number, status: 'active' | 'disabled', disabledReason = '') {
|
||||
return api.put(`/admin/users/${id}/status`, { status, disabledReason })
|
||||
}
|
||||
|
||||
// ======== 任务执行日志(admin only) ========
|
||||
|
||||
export interface AdminTaskLogItem {
|
||||
id: number
|
||||
userId: number
|
||||
username: string
|
||||
realName: string
|
||||
schoolName: string
|
||||
taskType: string // sign / sleep_check
|
||||
title: string
|
||||
realTitle: string
|
||||
isSuccess: boolean
|
||||
errorMessage: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface AdminTaskLogResult {
|
||||
total: number
|
||||
items: AdminTaskLogItem[]
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** 获取任务执行日志列表(默认当天) */
|
||||
export function getAdminTaskLogs(params: {
|
||||
date?: string
|
||||
status?: 'all' | 'success' | 'fail'
|
||||
keyword?: string
|
||||
page?: number
|
||||
pageSize?: number
|
||||
}) {
|
||||
const qs = new URLSearchParams()
|
||||
if (params.date) qs.set('date', params.date)
|
||||
qs.set('status', params.status || 'all')
|
||||
if (params.keyword) qs.set('keyword', params.keyword)
|
||||
qs.set('page', String(params.page || 1))
|
||||
qs.set('pageSize', String(params.pageSize || 20))
|
||||
return api.get<{ data: AdminTaskLogResult }>(`/admin/task-logs?${qs.toString()}`)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface LoginParams {
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
firstLogin?: boolean
|
||||
token: {
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
@@ -55,9 +56,25 @@ export interface UserInfo {
|
||||
mobileCode: string
|
||||
mobileType: string
|
||||
signCount: number
|
||||
/** VIP 到期时间(null=从未开通) */
|
||||
vipExpireAt: string | null
|
||||
inviteCode: string
|
||||
inviteReward: number
|
||||
invitedCount: number
|
||||
/** 已看过的新手引导版本(如 v2;空=未看过,登录后需展示引导) */
|
||||
guideVersion: string
|
||||
}
|
||||
|
||||
/** 我的邀请信息(含奖励规则,随系统配置变化) */
|
||||
export interface MyInviteInfo {
|
||||
inviteCode: string
|
||||
inviteReward: number
|
||||
invitedCount: number
|
||||
canRedeem: boolean
|
||||
/** 邀请人每邀请 1 人获得的奖励积分(系统配置) */
|
||||
inviterRewardPerInvite: number
|
||||
/** 被邀请人注册登录后获得的奖励积分(系统配置) */
|
||||
inviteeRewardPerInvite: number
|
||||
}
|
||||
|
||||
/** 搜索学校 */
|
||||
@@ -104,9 +121,28 @@ export function getDeviceStatus(token: string) {
|
||||
})
|
||||
}
|
||||
|
||||
/** 新 CDK 兑换(需验证码,由管理后台生成的 CDK,一次性消耗全部次数) */
|
||||
/** 随机生成设备码并绑定到当前账号(个人中心「随机」按钮,需连续两次风险确认) */
|
||||
export function randomBindDevice() {
|
||||
return api.post<{ data: { deviceCode: string } }>('/device/random-bind')
|
||||
}
|
||||
|
||||
/** 新 CDK 兑换(需验证码,由管理后台生成的 CDK;次数 CDK 加次数 / VIP CDK 延长 VIP) */
|
||||
export function redeemCDK(code: string, captchaId: string, captchaCode: string) {
|
||||
return api.post<{ data: { totalRuns: number } }>('/cdk/redeem', { code, captchaId, captchaCode })
|
||||
return api.post<{
|
||||
data: {
|
||||
type: 'count' | 'vip'
|
||||
totalRuns?: number
|
||||
vipDays?: number
|
||||
vipExpireAt?: string
|
||||
}
|
||||
}>('/cdk/redeem', { code, captchaId, captchaCode })
|
||||
}
|
||||
|
||||
/** 当前用户 VIP 信息(是否 VIP、到期时间、系统配置单价) */
|
||||
export function getVipInfo() {
|
||||
return api.get<{ data: { isVip: boolean; vipExpireAt: string; vipWeekPrice: string; vipMonthPrice: string; vipPrice: string } }>(
|
||||
'/cdk/vip-info'
|
||||
)
|
||||
}
|
||||
|
||||
// ======== 签到任务相关 ========
|
||||
@@ -177,7 +213,7 @@ export function getTaskList() {
|
||||
|
||||
/** 删除任务 */
|
||||
export function deleteTask(id: number) {
|
||||
return api.delete(`/task/${id}`)
|
||||
return api.delete(`/task/delete/${id}`)
|
||||
}
|
||||
|
||||
/** 执行签到(SSE) */
|
||||
@@ -258,15 +294,20 @@ export function deleteTaskLog(id: number) {
|
||||
|
||||
/** 获取/生成邀请码 */
|
||||
export function getMyInvite() {
|
||||
return api.post<{ data: { inviteCode: string; inviteReward: number; invitedCount: number; canRedeem: boolean } }>('/auth/generate-invite')
|
||||
return api.post<{ data: MyInviteInfo }>('/auth/generate-invite')
|
||||
}
|
||||
|
||||
/** 查询邀请信息 */
|
||||
export function getMyInviteInfo() {
|
||||
return api.get<{ data: { inviteCode: string; inviteReward: number; invitedCount: number; canRedeem: boolean } }>('/auth/my-invite')
|
||||
return api.get<{ data: MyInviteInfo }>('/auth/my-invite')
|
||||
}
|
||||
|
||||
/** 兑换邀请奖励 */
|
||||
export function redeemInviteReward() {
|
||||
return api.post<{ data: { quota: number } }>('/auth/redeem-invite')
|
||||
}
|
||||
|
||||
/** 上报已完成当前版本新手引导(数据库记录,跨设备不再重复展示) */
|
||||
export function completeGuide() {
|
||||
return api.post('/auth/guide/complete')
|
||||
}
|
||||
|
||||
@@ -42,7 +42,10 @@ body {
|
||||
#app {
|
||||
max-width: 430px;
|
||||
width: 100%;
|
||||
/* 100vh 兜底(旧浏览器);100dvh 适配 iOS/iPadOS Safari 地址栏动态视口,
|
||||
避免地址栏展开时底部导航被推出屏幕外 */
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
margin: 0 auto;
|
||||
background-color: #ffffff;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -0,0 +1,630 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onBeforeUnmount } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { X, ChevronLeft, ChevronRight, Sparkles, Play } from 'lucide-vue-next'
|
||||
|
||||
const props = defineProps<{
|
||||
show: boolean
|
||||
/** 邀请人每邀请 1 人奖励积分(系统配置,可能尚未加载为 null) */
|
||||
inviterRewardPerInvite?: number | null
|
||||
/** 被邀请人注册后奖励积分(系统配置,可能尚未加载为 null) */
|
||||
inviteeRewardPerInvite?: number | null
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'close'): void
|
||||
/** 请求切换到指定 tab(目标元素在另一页面时) */
|
||||
(e: 'goto', tab: 'home' | 'profile'): void
|
||||
}>()
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
const step = ref(0)
|
||||
const curTarget = ref<Element | null>(null)
|
||||
const holeRect = ref<{ top: number; left: number; width: number; height: number; r: number } | null>(null)
|
||||
const bubblePos = ref<'top' | 'bottom' | 'center'>('center')
|
||||
const waitingTarget = ref(false)
|
||||
const bubbleEl = ref<HTMLElement | null>(null)
|
||||
let locateSeq = 0
|
||||
let rafId = 0
|
||||
let pollTimer: number | undefined
|
||||
let lastFlipAt = 0
|
||||
let bodyObs: ResizeObserver | null = null
|
||||
let targetObs: ResizeObserver | null = null
|
||||
let bubbleObs: ResizeObserver | null = null
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
|
||||
|
||||
function fmtReward(v: number | null | undefined): string | null {
|
||||
if (v === null || v === undefined) return null
|
||||
const n = Math.round(v * 10) / 10
|
||||
return Number.isInteger(n) ? String(n) : n.toFixed(1)
|
||||
}
|
||||
|
||||
interface GuideStep {
|
||||
tab: 'home' | 'profile'
|
||||
title: string
|
||||
/** 目标元素候选(按序取第一个存在的) */
|
||||
targets: string[]
|
||||
/** 不同目标命中时的说明文案 */
|
||||
descByKind: (kind: string | null) => string
|
||||
}
|
||||
|
||||
const steps: GuideStep[] = [
|
||||
{
|
||||
tab: 'profile',
|
||||
title: '领取签到次数',
|
||||
targets: ['[data-guide="profile-invite-redeem"]', '[data-guide="profile-invite-row"]'],
|
||||
descByKind: () =>
|
||||
'新用户注册即送奖励积分,邀请好友也能赚积分。\n积分满 1 后,点这里「兑换」按钮即可换成签到次数,1 积分 = 1 次签到,可重复兑换。',
|
||||
},
|
||||
{
|
||||
tab: 'profile',
|
||||
title: '先绑定设备码',
|
||||
targets: ['[data-guide="profile-device-code"]'],
|
||||
descByKind: () =>
|
||||
'签到任务依赖设备码执行。到这一栏点「重新绑定」用手机扫码授权,或点「随机」直接生成设备码。\n注意:随机设备码与真实手机不一致,执行签到时现有手机会提示「频繁切换设备」无法签到,建议优先扫码授权。',
|
||||
},
|
||||
{
|
||||
tab: 'home',
|
||||
title: '新建每日签到任务',
|
||||
targets: ['[data-guide="home-create-task"]'],
|
||||
descByKind: () => '点击蓝色的「+ 新的签到任务」按钮,选择任务名称(如 晚签到),然后填好对应签到信息并保存,任务就创建好了。',
|
||||
},
|
||||
{
|
||||
tab: 'home',
|
||||
title: '执行任务,自动签到',
|
||||
targets: ['[data-guide="home-task-exec"]', '[data-guide="home-task-empty"]', '[data-guide="home-task-list"]'],
|
||||
descByKind: (kind) =>
|
||||
kind === 'home-task-exec'
|
||||
? '任务创建后显示在下方列表。点任务右侧的「执行」按钮,即可自动完成今天的签到,之后每天无需再手动操作。'
|
||||
: kind === 'home-task-empty'
|
||||
? '你还没有真实任务,下面先展示一张示例任务卡。保存真实任务后它会出现在这里,点卡片右侧「执行」按钮即可自动完成每日签到。'
|
||||
: '任务创建后显示在这个区域。点任务右侧的「执行」按钮即可自动完成每日签到,无需手动操作。',
|
||||
},
|
||||
{
|
||||
tab: 'profile',
|
||||
title: '次数不够?邀请好友赚积分',
|
||||
targets: ['[data-guide="profile-invite-copy"]', '[data-guide="profile-invite-generate"]'],
|
||||
descByKind: (kind) => {
|
||||
const inviter = fmtReward(props.inviterRewardPerInvite)
|
||||
const invitee = fmtReward(props.inviteeRewardPerInvite)
|
||||
if (kind === 'profile-invite-generate') {
|
||||
return '先点「生成邀请码」,生成后把链接发给同学;TA 通过你的链接注册登录后,你们都能获得奖励积分,多邀多得。'
|
||||
}
|
||||
if (inviter !== null && invitee !== null) {
|
||||
return `把链接发给同学,TA 通过你的链接注册登录后,你可得 ${inviter} 积分、TA 得 ${invitee} 积分,多邀多得,随时可兑换签到次数。`
|
||||
}
|
||||
return '把链接发给同学,TA 通过你的链接注册登录后,你和 TA 都能获得一定积分奖励,多邀多得,随时可兑换签到次数。'
|
||||
},
|
||||
},
|
||||
{
|
||||
tab: 'profile',
|
||||
title: 'VIP 会员:签到不限次',
|
||||
targets: ['[data-guide="profile-vip-btn"]'],
|
||||
descByKind: () =>
|
||||
'普通签到次数:每执行一次任务扣 1 次,用完需要再兑换。\nVIP 会员:有效期内执行任务不限次数(无限次),不再扣签到次数。\n点「续费 VIP」输入 VIP 兑换码即可开通,到期时间自动顺延。',
|
||||
},
|
||||
]
|
||||
|
||||
const current = computed(() => steps[step.value])
|
||||
const isLast = computed(() => step.value === steps.length - 1)
|
||||
|
||||
// 当前命中的目标类别(用于生成对应文案)
|
||||
const resolvedKind = computed(() => {
|
||||
const el = curTarget.value
|
||||
if (!el) return null
|
||||
for (const t of current.value.targets) {
|
||||
if (el.matches(t)) return t.replace('[data-guide="', '').replace('"]', '')
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
const guideDesc = computed(() => current.value.descByKind(resolvedKind.value))
|
||||
|
||||
// 第三步且用户没有任何真实任务(命中空态卡)时:展示一张示例任务卡引导
|
||||
const mockMode = computed(() => props.show && step.value === 2 && resolvedKind.value === 'home-task-empty')
|
||||
const mockCardStyle = computed(() => {
|
||||
const r = holeRect.value
|
||||
if (!r) return null
|
||||
return {
|
||||
top: `${Math.max(0, Math.round(r.top + (r.height - 76) / 2))}px`,
|
||||
left: `${r.left}px`,
|
||||
width: `${r.width}px`,
|
||||
}
|
||||
})
|
||||
|
||||
let lastLocateAt = 0
|
||||
|
||||
/* ================= 定位与高亮 ================= */
|
||||
|
||||
// 方位决策(measure 与 ensure 共用同一函数,避免两侧交替乒乓):
|
||||
// 优先下方(移动端阅读流自然向下展开,也符合"上方放不下就放下方"的预期);
|
||||
// 下方放不下才放上方;两侧都不能完整容纳时选"溢出更少"的一侧
|
||||
function choosePos(r: { top: number; bottom: number }, bH: number, vh: number): 'top' | 'bottom' {
|
||||
const gapTop = r.top - 12 // 目标上方可用高度(气泡底距目标顶 12px 间隙)
|
||||
const gapBottom = vh - r.bottom - 12 // 目标下方可用高度
|
||||
const need = Math.max(240, bH > 0 ? bH + 24 : 260)
|
||||
if (gapBottom >= need) return 'bottom'
|
||||
if (gapTop >= need) return 'top'
|
||||
// 两侧都不足:比较溢出量(气泡被视口裁剪的部分),选溢出少的一侧
|
||||
const topLost = Math.max(0, bH - gapTop)
|
||||
const bottomLost = Math.max(0, bH - gapBottom)
|
||||
return bottomLost <= topLost ? 'bottom' : 'top'
|
||||
}
|
||||
|
||||
function measure(el: Element) {
|
||||
const r = el.getBoundingClientRect()
|
||||
const cs = getComputedStyle(el)
|
||||
const br = parseFloat(cs.borderRadius) || 0
|
||||
const vh = window.innerHeight
|
||||
// 目标完全不可见(被遮罩同层遮挡或滚动出屏)时按中心兜底
|
||||
const visibleH = Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0))
|
||||
if (r.width <= 0 || r.height <= 0 || visibleH <= 0) {
|
||||
if (holeRect.value || bubblePos.value !== 'center') {
|
||||
holeRect.value = null
|
||||
bubblePos.value = 'center'
|
||||
}
|
||||
return
|
||||
}
|
||||
// 位置/尺寸变化超过阈值才更新(异步数据/图片导致布局高度变化后自动纠正错位)
|
||||
const next = {
|
||||
top: r.top,
|
||||
left: r.left,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
r: Math.max(0, Math.min(br, r.width / 2, r.height / 2, 18)),
|
||||
}
|
||||
const old = holeRect.value
|
||||
const moved =
|
||||
!old ||
|
||||
Math.abs(old.top - next.top) > 1 ||
|
||||
Math.abs(old.left - next.left) > 1 ||
|
||||
Math.abs(old.width - next.width) > 1 ||
|
||||
Math.abs(old.height - next.height) > 1 ||
|
||||
Math.abs(old.r - next.r) > 1
|
||||
if (moved) holeRect.value = next
|
||||
|
||||
// 用气泡真实高度(内容/文案变化后实时跟随)决定放目标上方还是下方,始终与高亮框保留间隙
|
||||
// need 采用保守估算:保证整颗气泡完整落在目标一侧,杜绝"放上方但上方放不下溢出到视口外"
|
||||
const bH = bubbleEl.value?.offsetHeight || 0
|
||||
const pos = choosePos({ top: r.top, bottom: r.bottom }, bH, vh)
|
||||
if (pos !== bubblePos.value) bubblePos.value = pos
|
||||
}
|
||||
|
||||
// 气泡渲染后自检:若气泡与真实目标元素相交、或被视口裁掉过多(布局错位/文案高度突变/
|
||||
// 测量竞态等未及修正的场景),按真实尺寸重新走同一方位决策绕开目标
|
||||
function ensureBubbleNotOverlapping(el: Element) {
|
||||
requestAnimationFrame(() => {
|
||||
const b = bubbleEl.value
|
||||
if (!props.show || !b) return
|
||||
const br = b.getBoundingClientRect()
|
||||
const tr = el.getBoundingClientRect()
|
||||
const vh = window.innerHeight
|
||||
const overlapped =
|
||||
br.right > tr.left + 2 &&
|
||||
br.left < tr.right - 2 &&
|
||||
br.bottom > tr.top + 2 &&
|
||||
br.top < tr.bottom - 2
|
||||
// top 模式顶部被视口裁切 / bottom 模式底部被裁切 / center 兜底样式压住了目标
|
||||
const topClipped = bubblePos.value === 'top' && br.top < 4
|
||||
const bottomClipped = bubblePos.value === 'bottom' && br.bottom > vh - 4
|
||||
if (!overlapped && !topClipped && !bottomClipped) return
|
||||
// 400ms 防抖:决策后让 measure/轮询先消化,避免高频翻转
|
||||
const now = Date.now()
|
||||
if (now - lastFlipAt < 400) return
|
||||
lastFlipAt = now
|
||||
if (bubblePos.value === 'center') {
|
||||
// 等待/兜底样式与目标相交(目标已渲染):立即重新定位
|
||||
void locate()
|
||||
return
|
||||
}
|
||||
// 与 measure 相同的决策函数:相交/越界时按真实气泡高度重选方位,不会乒乓
|
||||
const bH = b.offsetHeight || 240
|
||||
const desired = choosePos({ top: tr.top, bottom: tr.bottom }, bH, vh)
|
||||
if (desired !== bubblePos.value) bubblePos.value = desired
|
||||
})
|
||||
}
|
||||
|
||||
// 等待平滑滚动结束再测量(滚动中途测到的位置是错的,会导致气泡方位误判)
|
||||
function waitScrollSettled(timeout: number): Promise<void> {
|
||||
if (timeout <= 0) return Promise.resolve()
|
||||
return new Promise((resolve) => {
|
||||
let done = false
|
||||
let t = 0
|
||||
const onScroll = () => {
|
||||
window.clearTimeout(t)
|
||||
t = window.setTimeout(cleanup, 120)
|
||||
}
|
||||
const cleanup = () => {
|
||||
if (done) return
|
||||
done = true
|
||||
window.clearTimeout(t)
|
||||
window.removeEventListener('scroll', onScroll, true)
|
||||
resolve()
|
||||
}
|
||||
window.addEventListener('scroll', onScroll, true)
|
||||
t = window.setTimeout(cleanup, 120) // 120ms 无滚动即视为稳定
|
||||
window.setTimeout(cleanup, timeout) // 最长等待兜底
|
||||
})
|
||||
}
|
||||
|
||||
async function locate() {
|
||||
const seq = ++locateSeq
|
||||
lastLocateAt = Date.now()
|
||||
const s = current.value
|
||||
const crossTab = route.name !== s.tab
|
||||
const prevEl = curTarget.value
|
||||
waitingTarget.value = crossTab
|
||||
curTarget.value = null
|
||||
if (crossTab) {
|
||||
// 跨 tab:旧目标所在页面即将切换,清空高亮避免残影
|
||||
holeRect.value = null
|
||||
emit('goto', s.tab)
|
||||
}
|
||||
// 同 tab 切换步骤时保留旧高亮作为过渡锚点(找到新目标后平滑滑移过去),避免闪黑
|
||||
let el: Element | null = null
|
||||
for (let k = 0; k < 40; k++) {
|
||||
if (seq !== locateSeq) return // 期间步骤已切换
|
||||
if (!el) {
|
||||
for (const sel of s.targets) {
|
||||
el = document.querySelector(sel)
|
||||
if (el) break
|
||||
}
|
||||
}
|
||||
if (el) break
|
||||
await sleep(250)
|
||||
}
|
||||
if (seq !== locateSeq) return
|
||||
waitingTarget.value = false
|
||||
if (!el) {
|
||||
// 找不到任何目标:居中气泡引导
|
||||
curTarget.value = null
|
||||
holeRect.value = null
|
||||
bubblePos.value = 'center'
|
||||
return
|
||||
}
|
||||
curTarget.value = el
|
||||
const moved = !prevEl || prevEl !== el
|
||||
// 找到目标后先立即测量一次:即使后续需要滚动/等待,气泡也已按正确方位
|
||||
// 排在目标上/下方,不会停留在顶部兜底样式遮住目标
|
||||
measure(el)
|
||||
try {
|
||||
if (moved) el.scrollIntoView({ block: 'center', inline: 'center' })
|
||||
} catch {
|
||||
// ignore(个别浏览器不支持 options)
|
||||
}
|
||||
await waitScrollSettled(moved ? 800 : 0)
|
||||
if (seq !== locateSeq) return
|
||||
measure(el)
|
||||
ensureBubbleNotOverlapping(el)
|
||||
}
|
||||
|
||||
function setStep(i: number) {
|
||||
step.value = Math.max(0, Math.min(steps.length - 1, i))
|
||||
locateSeq++
|
||||
void locate()
|
||||
}
|
||||
|
||||
function prev() {
|
||||
if (step.value > 0) setStep(step.value - 1)
|
||||
}
|
||||
function next() {
|
||||
if (step.value < steps.length - 1) setStep(step.value + 1)
|
||||
else emit('close')
|
||||
}
|
||||
function skip() {
|
||||
emit('close')
|
||||
}
|
||||
|
||||
// 目标随页面滚动/窗口/布局(异步数据渲染、图片加载)变化时重新测量校正
|
||||
function scheduleMeasure() {
|
||||
if (!props.show) return
|
||||
cancelAnimationFrame(rafId)
|
||||
rafId = requestAnimationFrame(() => {
|
||||
const el = curTarget.value
|
||||
if (el && el.isConnected && document.contains(el)) {
|
||||
measure(el)
|
||||
ensureBubbleNotOverlapping(el)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 引导展示期间低频轮询校正:兜底 ResizeObserver 覆盖不到的变化
|
||||
// (内容在 overflow 滚动容器内变化时 body 尺寸不变、目标被懒加载/接口数据渲染等)
|
||||
function startLayoutPolling() {
|
||||
stopLayoutPolling()
|
||||
pollTimer = window.setInterval(() => {
|
||||
if (!props.show) return
|
||||
const el = curTarget.value
|
||||
if (el && el.isConnected && document.contains(el)) {
|
||||
measure(el)
|
||||
// 目标升级:异步数据渲染出更高优先级的 v-if 目标(生成→复制 按钮、行→兑换 按钮)时重定位
|
||||
const better = current.value.targets.find((sel) => document.querySelector(sel))
|
||||
if (better && !el.matches(better) && Date.now() - lastLocateAt > 1000) {
|
||||
void locate()
|
||||
}
|
||||
} else if (el) {
|
||||
// 目标已从 DOM 消失(v-if 切换),重新定位到当前存在的最优目标
|
||||
void locate()
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
function stopLayoutPolling() {
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer)
|
||||
pollTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
// ResizeObserver:body(页面整体布局变化)/ 高亮目标自身(尺寸变化)/ 气泡(文案高度变化)→ 触发重定位
|
||||
function observeResize() {
|
||||
try {
|
||||
bodyObs?.disconnect()
|
||||
targetObs?.disconnect()
|
||||
bubbleObs?.disconnect()
|
||||
bodyObs = targetObs = bubbleObs = null
|
||||
if (typeof ResizeObserver === 'undefined') return
|
||||
const body = document.body
|
||||
if (body) {
|
||||
bodyObs = new ResizeObserver(scheduleMeasure)
|
||||
bodyObs.observe(body)
|
||||
}
|
||||
} catch {
|
||||
// ignore(个别环境不支持)
|
||||
}
|
||||
}
|
||||
|
||||
function observeTarget(el: Element | null) {
|
||||
try {
|
||||
targetObs?.disconnect()
|
||||
targetObs = null
|
||||
if (el && typeof ResizeObserver !== 'undefined') {
|
||||
targetObs = new ResizeObserver(scheduleMeasure)
|
||||
targetObs.observe(el)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function observeBubble(el: HTMLElement | null) {
|
||||
try {
|
||||
bubbleObs?.disconnect()
|
||||
bubbleObs = null
|
||||
if (el && typeof ResizeObserver !== 'undefined') {
|
||||
bubbleObs = new ResizeObserver(scheduleMeasure)
|
||||
bubbleObs.observe(el)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.show,
|
||||
(v) => {
|
||||
if (v) {
|
||||
step.value = 0
|
||||
void locate()
|
||||
startLayoutPolling()
|
||||
} else {
|
||||
locateSeq++
|
||||
stopLayoutPolling()
|
||||
holeRect.value = null
|
||||
curTarget.value = null
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
watch(curTarget, (el) => observeTarget(el))
|
||||
watch(bubbleEl, (el) => observeBubble(el))
|
||||
|
||||
observeResize()
|
||||
window.addEventListener('scroll', scheduleMeasure, true)
|
||||
window.addEventListener('resize', scheduleMeasure)
|
||||
document.addEventListener('visibilitychange', scheduleMeasure)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
locateSeq++
|
||||
stopLayoutPolling()
|
||||
window.removeEventListener('scroll', scheduleMeasure, true)
|
||||
window.removeEventListener('resize', scheduleMeasure)
|
||||
document.removeEventListener('visibilitychange', scheduleMeasure)
|
||||
cancelAnimationFrame(rafId)
|
||||
try {
|
||||
bodyObs?.disconnect()
|
||||
targetObs?.disconnect()
|
||||
bubbleObs?.disconnect()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
})
|
||||
|
||||
/* ================= 样式计算 ================= */
|
||||
|
||||
const BUBBLE_W = 300
|
||||
|
||||
const holeStyle = computed(() => {
|
||||
const r = holeRect.value
|
||||
if (!r) return null
|
||||
return {
|
||||
top: `${r.top}px`,
|
||||
left: `${r.left}px`,
|
||||
width: `${r.width}px`,
|
||||
height: `${r.height}px`,
|
||||
borderRadius: `${r.r}px`,
|
||||
}
|
||||
})
|
||||
|
||||
const bubbleStyle = computed(() => {
|
||||
const r = holeRect.value
|
||||
const vw = window.innerWidth
|
||||
const vh = window.innerHeight
|
||||
const bw = Math.min(BUBBLE_W, vw - 24)
|
||||
let style: Record<string, string> = { width: `${bw}px` }
|
||||
if (bubblePos.value === 'center' || !r) {
|
||||
style.top = '96px'
|
||||
style.left = `${Math.max(12, (vw - bw) / 2)}px`
|
||||
return style
|
||||
}
|
||||
// 水平对齐目标中心(防溢出)
|
||||
const left = Math.max(12, Math.min(vw - bw - 12, r.left + r.width / 2 - bw / 2))
|
||||
style.left = `${left}px`
|
||||
if (bubblePos.value === 'top') {
|
||||
style.bottom = `${Math.max(12, vh - r.top + 12)}px`
|
||||
} else {
|
||||
// r 为 {top,left,width,height},底部需用 top+height 合成(r.bottom 不存在会算出 NaNpx 被浏览器丢弃)
|
||||
style.top = `${Math.min(vh - 12, r.top + r.height + 12)}px`
|
||||
}
|
||||
return style
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<transition name="guide-fade">
|
||||
<div v-if="show" class="guide-root fixed inset-0 z-[80]" @touchmove.prevent @scroll.prevent>
|
||||
<!-- 暗色遮罩:高亮框阴影法挖洞(高亮框本身透明露出真实页面元素);mock 时全屏压暗 -->
|
||||
<div v-if="holeRect && !mockMode" :style="holeStyle" class="guide-hole" />
|
||||
<div v-else class="absolute inset-0 bg-black/60" />
|
||||
|
||||
<!-- 无真实任务时的示例任务卡(替换空态区展示,引导指向"执行"按钮) -->
|
||||
<div
|
||||
v-if="mockMode && mockCardStyle"
|
||||
:style="mockCardStyle"
|
||||
class="guide-mock-card absolute pointer-events-none"
|
||||
>
|
||||
<div class="flex items-center justify-between p-3">
|
||||
<div class="flex-1 min-w-0 mr-2">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-sm font-medium text-gray-900 whitespace-nowrap">晚签到</span>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full bg-purple-100 text-purple-600 whitespace-nowrap">晚归签到</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 mt-1">
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-amber-100 text-amber-600 whitespace-nowrap">待签到</span>
|
||||
<span class="text-[10px] text-gray-400 whitespace-nowrap">示例任务</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="w-8 h-8 flex items-center justify-center rounded-lg bg-blue-500 text-white shadow-sm flex-shrink-0" title="执行签到">
|
||||
<Play class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- tooltip 气泡(切步时保留同一实例,仅位置平滑过渡,不重放入场动画) -->
|
||||
<div ref="bubbleEl" :style="bubbleStyle" class="guide-bubble absolute z-10">
|
||||
<!-- 顶部:标识 + 步骤 + 跳过 -->
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="flex items-center gap-1 text-[10px] font-semibold text-blue-600 flex-shrink-0">
|
||||
<Sparkles class="w-3 h-3" />
|
||||
新手引导
|
||||
</span>
|
||||
<div class="flex items-center gap-1 flex-1">
|
||||
<span
|
||||
v-for="(s, i) in steps"
|
||||
:key="i"
|
||||
class="h-1 rounded-full transition-all duration-300"
|
||||
:class="i === step ? 'w-5 bg-blue-500' : i < step ? 'w-1.5 bg-blue-300' : 'w-1.5 bg-gray-200'"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
class="w-6 h-6 rounded-full flex items-center justify-center text-gray-300 hover:text-gray-500 hover:bg-gray-100 transition-colors flex-shrink-0"
|
||||
title="跳过引导"
|
||||
@click="skip"
|
||||
>
|
||||
<X class="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 标题与说明 -->
|
||||
<h3 class="text-[15px] font-bold text-gray-900 mt-2.5">{{ current.title }}</h3>
|
||||
<p v-if="waitingTarget" class="text-[11px] text-blue-500 mt-1.5 font-medium">正在为你切换到目标页面…</p>
|
||||
<p class="text-xs text-gray-500 leading-relaxed whitespace-pre-line mt-1.5 guide-desc">{{ guideDesc }}</p>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="flex items-center gap-2 mt-3.5">
|
||||
<button
|
||||
v-if="step > 0"
|
||||
class="flex items-center justify-center gap-0.5 h-9 px-3 rounded-lg border border-gray-200 text-gray-500 text-xs font-medium hover:bg-gray-50 transition-colors flex-shrink-0"
|
||||
@click="prev"
|
||||
>
|
||||
<ChevronLeft class="w-3.5 h-3.5" />
|
||||
上一步
|
||||
</button>
|
||||
<button
|
||||
class="flex-1 h-9 rounded-lg bg-blue-500 hover:bg-blue-600 text-white text-[13px] font-medium shadow-sm active:scale-[0.99] transition-all flex items-center justify-center gap-1"
|
||||
@click="next"
|
||||
>
|
||||
{{ isLast ? '完成' : '下一步' }}
|
||||
<ChevronRight v-if="!isLast" class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.guide-root {
|
||||
background: transparent;
|
||||
}
|
||||
/* 高亮框:白色 ring + 全屏阴影挖洞(box-shadow 第一层 ring、第二层撑满全屏压暗) */
|
||||
.guide-hole {
|
||||
position: absolute;
|
||||
box-shadow:
|
||||
0 0 0 2px rgba(255, 255, 255, 0.95),
|
||||
0 0 0 9999px rgba(0, 0, 0, 0.62);
|
||||
transition:
|
||||
top 0.25s ease,
|
||||
left 0.25s ease,
|
||||
width 0.25s ease,
|
||||
height 0.25s ease;
|
||||
}
|
||||
|
||||
.guide-mock-card {
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow:
|
||||
0 0 0 2px rgba(255, 255, 255, 0.95),
|
||||
0 10px 28px rgba(0, 0, 0, 0.35);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.guide-bubble {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.28);
|
||||
padding: 14px 16px 12px;
|
||||
/* 布局/文案变化实时重定位时平滑移动(动画只播放入场) */
|
||||
transition:
|
||||
top 0.25s ease,
|
||||
left 0.25s ease,
|
||||
bottom 0.25s ease;
|
||||
animation: guide-pop-in 0.28s cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
.guide-desc {
|
||||
max-height: 132px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.guide-fade-enter-active,
|
||||
.guide-fade-leave-active {
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
.guide-fade-enter-from,
|
||||
.guide-fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
@keyframes guide-pop-in {
|
||||
from {
|
||||
transform: translateY(8px) scale(0.97);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0) scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,6 +4,7 @@ import { useRouter, useRoute } from 'vue-router'
|
||||
import { Home, User, Bell, X, CheckCircle, ChevronDown, MessageSquare } from 'lucide-vue-next'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import GuideOverlay from '@/components/GuideOverlay.vue'
|
||||
import * as authApi from '@/api/auth'
|
||||
import * as announceApi from '@/api/announcement'
|
||||
import * as ticketApi from '@/api/ticket'
|
||||
@@ -24,9 +25,10 @@ const tabs = [
|
||||
|
||||
const activeTab = ref(route.name as string || 'home')
|
||||
|
||||
// 路由变化时同步底部 tab 高亮
|
||||
// 路由变化时同步底部 tab 高亮;回到首页时尝试加载公告强制弹窗(若引导已完成)
|
||||
watch(() => route.name, (name) => {
|
||||
if (name) activeTab.value = name as string
|
||||
if (name === 'home') maybeLoadAnnouncementPopups()
|
||||
})
|
||||
|
||||
// 公告相关
|
||||
@@ -52,6 +54,66 @@ const currentForcePopup = computed(() => forcePopupQueue.value[0] || null)
|
||||
const showDetail = ref(false)
|
||||
const detailItem = ref<AnnouncementItem | null>(null)
|
||||
|
||||
// 新手引导:是否展示由后端数据库记录判定(用户 guideVersion 未达当前版本即展示,
|
||||
// 完成/关闭后上报写库,跨设备不再重复打扰)。测试强播入口 ?guide=1 保留:
|
||||
// main.ts 将其写入 sessionStorage(一次性,本组件读取即消费),仅当次加载生效。
|
||||
const GUIDE_FORCE_KEY = 'xz_guide_force'
|
||||
/** 与后端 handler.GuideCompleteVersion 一致 */
|
||||
const GUIDE_VERSION = 'v2'
|
||||
const showGuide = ref(false)
|
||||
// 本次展示是否来自测试强播(?guide=1,仅当次加载):强播关闭时不写库,可反复重播
|
||||
const guideForced = ref(false)
|
||||
// 邀请奖励规则(供引导第 4 步动态展示;接口失败保持 null,气泡用泛指文案)
|
||||
const inviterRewardPerInvite = ref<number | null>(null)
|
||||
const inviteeRewardPerInvite = ref<number | null>(null)
|
||||
|
||||
async function loadInviteRewardRules() {
|
||||
try {
|
||||
const res = await authApi.getMyInviteInfo()
|
||||
inviterRewardPerInvite.value = res.data.data?.inviterRewardPerInvite ?? null
|
||||
inviteeRewardPerInvite.value = res.data.data?.inviteeRewardPerInvite ?? null
|
||||
} catch {
|
||||
// 静默失败,引导文案退化为"可获得一定积分"
|
||||
}
|
||||
}
|
||||
|
||||
// 公告强制弹窗是否已加载(须在引导完成后才查询,避免弹窗与引导冲突)
|
||||
const announcementLoaded = ref(false)
|
||||
|
||||
function handleGuideAction(target: 'home' | 'profile') {
|
||||
switchTab(target)
|
||||
}
|
||||
|
||||
function closeGuide() {
|
||||
showGuide.value = false
|
||||
// 引导结束:补上公告未读数与强制弹窗队列
|
||||
loadUnreadCount()
|
||||
maybeLoadAnnouncementPopups()
|
||||
// 上报完成状态到数据库(看过当前版本后任何设备都不再弹);
|
||||
// 测试强播来源不写库,避免污染该账号的"首次引导"状态
|
||||
if (!guideForced.value) {
|
||||
authApi.completeGuide().catch(() => {
|
||||
// 上报失败不打扰用户:下次登录该账号会再次展示引导
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** 数据库判定:guideVersion 未达当前引导版本的用户需展示引导 */
|
||||
function needGuide(user: UserInfo): boolean {
|
||||
return (user.guideVersion || '') !== GUIDE_VERSION
|
||||
}
|
||||
|
||||
async function maybeLoadAnnouncementPopups() {
|
||||
if (announcementLoaded.value || showGuide.value || route.name !== 'home') return
|
||||
announcementLoaded.value = true
|
||||
try {
|
||||
const res = await announceApi.getMyAnnouncementInfo()
|
||||
forcePopupQueue.value = res.data.data.popupQueue || []
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function switchTab(name: string) {
|
||||
activeTab.value = name
|
||||
router.push({ name })
|
||||
@@ -140,31 +202,36 @@ async function handleForcePopupDismiss() {
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// 强播标记一次性消费:仅本次整页加载(URL 带 ?guide=1)内优先展示且关闭不写库;
|
||||
// 读取后立即清除,避免会话残留把后续普通访问(刷新/重开)误判为强播——
|
||||
// 否则会出现"看完引导后刷新又弹、且永不上报完成"的假象
|
||||
guideForced.value = sessionStorage.getItem(GUIDE_FORCE_KEY) === '1'
|
||||
sessionStorage.removeItem(GUIDE_FORCE_KEY)
|
||||
try {
|
||||
const res = await authApi.getUserInfo()
|
||||
const data = res.data.data
|
||||
userInfo.value = data
|
||||
|
||||
if (!data.mobileCode) {
|
||||
router.replace('/bind-device')
|
||||
return
|
||||
// 未绑定设备码不再强制跳转绑定页(新建任务时会在入口处弹窗引导)
|
||||
// 新手引导:数据库判定该用户未看过当前版本引导则展示(跨设备一致);
|
||||
// 本次若来自 ?guide=1 强播则优先展示(guideForced 已消费,下次加载不再生效)
|
||||
if (guideForced.value || needGuide(data)) {
|
||||
showGuide.value = true
|
||||
// 引导气泡中展示邀请奖励数值(第 4 步)
|
||||
loadInviteRewardRules()
|
||||
}
|
||||
} catch {
|
||||
message.error('获取用户信息失败')
|
||||
}
|
||||
|
||||
// 加载未读公告数 + 待弹窗队列(仅首页触发弹窗)
|
||||
await loadUnreadCount()
|
||||
if (route.name === 'home') {
|
||||
try {
|
||||
const res = await announceApi.getMyAnnouncementInfo()
|
||||
forcePopupQueue.value = res.data.data.popupQueue || []
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
// 引导展示中不查询公告信息(未读数/强制弹窗),避免公告弹窗与引导冲突;
|
||||
// 引导关闭后由 closeGuide 统一补齐
|
||||
if (!showGuide.value) {
|
||||
loadUnreadCount()
|
||||
maybeLoadAnnouncementPopups()
|
||||
}
|
||||
|
||||
// 定时轮询未读数
|
||||
// 定时轮询未读数(仅更新铃铛角标,不产生弹窗)
|
||||
pollTimer = setInterval(loadUnreadCount, 30000)
|
||||
})
|
||||
|
||||
@@ -206,8 +273,8 @@ onUnmounted(() => {
|
||||
<router-view />
|
||||
</div>
|
||||
|
||||
<!-- 底部 TabBar -->
|
||||
<div class="flex-shrink-0 bg-white border-t border-gray-100 flex">
|
||||
<!-- 底部 TabBar(env 安全区适配 iPhone/iPad 底部 Home 条) -->
|
||||
<div class="flex-shrink-0 bg-white border-t border-gray-100 flex" style="padding-bottom: env(safe-area-inset-bottom)">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.name"
|
||||
@@ -407,6 +474,15 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</transition>
|
||||
</Teleport>
|
||||
|
||||
<!-- ======== 首次登录新手引导(最高层:遮罩高亮真实页面元素 + 气泡推进) ======== -->
|
||||
<GuideOverlay
|
||||
:show="showGuide"
|
||||
:inviter-reward-per-invite="inviterRewardPerInvite"
|
||||
:invitee-reward-per-invite="inviteeRewardPerInvite"
|
||||
@goto="handleGuideAction"
|
||||
@close="closeGuide"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -3,6 +3,16 @@ import App from './App.vue'
|
||||
import router from './router'
|
||||
import './assets/styles/globals.css'
|
||||
|
||||
// 测试入口:URL 带 ?guide=1 强制重播新手引导(不受本地完成标记影响)。
|
||||
// 立即把标记落入 sessionStorage 并移除 URL 参数(登录跳转会丢失 query,故不能等到 MobileLayout)
|
||||
const guideParams = new URLSearchParams(window.location.search)
|
||||
if (guideParams.get('guide') === '1') {
|
||||
sessionStorage.setItem('xz_guide_force', '1')
|
||||
const url = new URL(window.location.href)
|
||||
url.searchParams.delete('guide')
|
||||
window.history.replaceState(null, '', url)
|
||||
}
|
||||
|
||||
const app = createApp(App)
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
|
||||
@@ -4,6 +4,7 @@ import HomeView from '@/views/home/HomeView.vue'
|
||||
import ProfileView from '@/views/profile/ProfileView.vue'
|
||||
import BindDeviceView from '@/views/bind/BindDeviceView.vue'
|
||||
import MobileLayout from '@/layouts/MobileLayout.vue'
|
||||
import BrowserGuideView from '@/views/guide/BrowserGuideView.vue'
|
||||
|
||||
import TicketList from '@/views/ticket/TicketList.vue'
|
||||
import TicketDetail from '@/views/ticket/TicketDetail.vue'
|
||||
@@ -65,31 +66,37 @@ const router = createRouter({
|
||||
{
|
||||
path: 'users',
|
||||
name: 'admin-users',
|
||||
meta: { adminOnly: true },
|
||||
component: AdminUsers,
|
||||
},
|
||||
{
|
||||
path: 'settings',
|
||||
name: 'admin-settings',
|
||||
meta: { adminOnly: true },
|
||||
component: AdminSettings,
|
||||
},
|
||||
{
|
||||
path: 'announcements',
|
||||
name: 'admin-announcements',
|
||||
meta: { adminOnly: true },
|
||||
component: AdminAnnouncements,
|
||||
},
|
||||
{
|
||||
path: 'tickets',
|
||||
name: 'admin-tickets',
|
||||
meta: { adminOnly: true },
|
||||
component: AdminTicketList,
|
||||
},
|
||||
{
|
||||
path: 'tickets/:id',
|
||||
name: 'admin-ticket-detail',
|
||||
meta: { adminOnly: true },
|
||||
component: AdminTicketDetail,
|
||||
},
|
||||
{
|
||||
path: 'pending-schools',
|
||||
name: 'admin-pending-schools',
|
||||
meta: { adminOnly: true },
|
||||
component: AdminPendingSchools,
|
||||
},
|
||||
],
|
||||
@@ -99,6 +106,12 @@ const router = createRouter({
|
||||
path: '/',
|
||||
redirect: '/login',
|
||||
},
|
||||
// 微信/QQ 内置浏览器引导页:提示复制链接用系统浏览器打开
|
||||
{
|
||||
path: '/open-in-browser',
|
||||
name: 'open-in-browser',
|
||||
component: BrowserGuideView,
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
name: 'login',
|
||||
@@ -142,11 +155,31 @@ const router = createRouter({
|
||||
],
|
||||
})
|
||||
|
||||
// 微信/QQ 系内置浏览器检测:
|
||||
// - MicroMessenger: 微信内置浏览器
|
||||
// - QQ/: 手机 QQ 内置浏览器
|
||||
// 注意:不拦纯 QQ 浏览器 App(MQQBrowser),因为安卓微信右上角
|
||||
// "在浏览器打开"唤起的就是它,拦截会造成引导页死循环
|
||||
function isBlockedBrowser(): boolean {
|
||||
const ua = navigator.userAgent
|
||||
return /MicroMessenger|QQ\//i.test(ua)
|
||||
}
|
||||
|
||||
router.beforeEach(async (to, _from) => {
|
||||
// 调试:记录当前路径
|
||||
try {
|
||||
await fetch(`/api/admin/setup/debug?path=${encodeURIComponent(to.path)}`)
|
||||
} catch {}
|
||||
// ======== 微信/QQ 浏览器拦截(优先于一切认证逻辑)========
|
||||
// 引导页自身放行;但若当前已是正常浏览器(如从微信右上角
|
||||
// "在浏览器打开"跳转过来),自动回到 redirect 指向的原页面
|
||||
if (to.name === 'open-in-browser') {
|
||||
if (!isBlockedBrowser()) {
|
||||
const r = to.query.redirect
|
||||
const target = typeof r === 'string' && r.startsWith('/') && r !== to.fullPath ? r : '/'
|
||||
return target
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (isBlockedBrowser()) {
|
||||
return { name: 'open-in-browser', query: { redirect: to.fullPath } }
|
||||
}
|
||||
|
||||
const token = localStorage.getItem('access_token')
|
||||
const adminToken = localStorage.getItem('admin_token')
|
||||
@@ -208,6 +241,12 @@ router.beforeEach(async (to, _from) => {
|
||||
localStorage.removeItem('admin_info')
|
||||
return '/admin/login'
|
||||
}
|
||||
// 代理(agent)只能访问仪表盘 / 代理管理 / CDK管理,其余页面重定向回仪表盘
|
||||
const meData = await meRes.json()
|
||||
const role = meData?.data?.role
|
||||
if (role && role !== 'admin' && to.meta.adminOnly) {
|
||||
return '/admin/dashboard'
|
||||
}
|
||||
} catch {
|
||||
// 网络错误,放行让组件自己处理
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 复制文本到剪贴板(兼容 HTTP / HTTPS / 移动端 WebView)
|
||||
*
|
||||
* 执行顺序刻意为先同步 execCommand:
|
||||
* document.execCommand('copy') 必须在「用户手势调用栈」内同步执行才可靠,
|
||||
* 若先 await Clipboard API 被拒(移动端 WebView 常见 NotAllowedError),
|
||||
* 手势上下文已丢失,后续 execCommand 会静默失败(返回 false 但剪贴板无内容)。
|
||||
*
|
||||
* 返回是否复制成功
|
||||
*/
|
||||
export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
// 1) 同步路径:隐藏 textarea + execCommand(用户手势内,兼容性最好)
|
||||
const ta = document.createElement('textarea')
|
||||
ta.value = text
|
||||
// 必须可见且在屏幕内(不可 display:none / 移出视口),否则 iOS Safari 复制失败;
|
||||
// font-size ≥ 16px 避免 iOS focus 时触发页面缩放
|
||||
ta.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;font-size:16px;border:0;padding:0;margin:0;'
|
||||
ta.setAttribute('readonly', '')
|
||||
document.body.appendChild(ta)
|
||||
ta.focus()
|
||||
ta.select()
|
||||
ta.setSelectionRange(0, text.length)
|
||||
let ok = false
|
||||
try {
|
||||
ok = document.execCommand('copy')
|
||||
} catch {
|
||||
ok = false
|
||||
}
|
||||
document.body.removeChild(ta)
|
||||
if (ok) return true
|
||||
|
||||
// 2) 异步回退:Clipboard API(仅 HTTPS/localhost;注意此时手势可能已丢失,仅作兜底)
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
return true
|
||||
} catch {
|
||||
// 忽略,走失败返回
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,27 +1,66 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { QrCode, Plus, Search, X, LoaderCircle, Copy, CheckCheck } from 'lucide-vue-next'
|
||||
import {
|
||||
QrCode,
|
||||
Plus,
|
||||
Search,
|
||||
X,
|
||||
LoaderCircle,
|
||||
Copy,
|
||||
CheckCheck,
|
||||
Ban,
|
||||
RotateCcw,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
CheckCircle2,
|
||||
} from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import { copyToClipboard } from '@/utils/clipboard'
|
||||
import * as adminApi from '@/api/admin'
|
||||
|
||||
const message = useMessage()
|
||||
|
||||
const cdks = ref<adminApi.CDKCode[]>([])
|
||||
const loading = ref(false)
|
||||
const searchQuery = ref('')
|
||||
const searchKeyword = ref('')
|
||||
const keywordInput = ref('')
|
||||
const statusFilter = ref('')
|
||||
const copiedIndex = ref<number | null>(null)
|
||||
const copiedResultIdx = ref<number | null>(null)
|
||||
const copiedAll = ref(false)
|
||||
|
||||
// 分页
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const total = ref(0)
|
||||
const totalPages = computed(() => Math.ceil(total.value / pageSize.value) || 1)
|
||||
const pageSizeOptions = [20, 50, 100]
|
||||
|
||||
// 汇总(后端按可见范围统计)
|
||||
const summary = ref<adminApi.CDKSummary>({ total: 0, unused: 0, used: 0, disabled: 0 })
|
||||
|
||||
const adminInfo = ref<adminApi.AgentInfo | null>(null)
|
||||
const isAdmin = computed(() => adminInfo.value?.role === 'admin')
|
||||
|
||||
// 生成CDK弹窗
|
||||
// 生成CDK弹窗(form 配置 / result 展示结果)
|
||||
const showGenerateModal = ref(false)
|
||||
const modalView = ref<'form' | 'result'>('form')
|
||||
const generateCount = ref(1)
|
||||
const generateMaxRuns = ref(1)
|
||||
const generateType = ref<'count' | 'vip'>('count')
|
||||
const generateVipDays = ref(30)
|
||||
const generateLoading = ref(false)
|
||||
const resultCdks = ref<adminApi.CDKCode[]>([])
|
||||
const resultCost = ref(0)
|
||||
|
||||
// 禁用/恢复确认弹窗
|
||||
const showStatusModal = ref(false)
|
||||
const statusAction = ref<'disable' | 'enable'>('disable')
|
||||
const statusTarget = ref<adminApi.CDKCode | null>(null)
|
||||
const statusLoading = ref(false)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
@@ -34,44 +73,77 @@ onMounted(async () => {
|
||||
async function loadCDKs() {
|
||||
loading.value = true
|
||||
try {
|
||||
if (isAdmin.value) {
|
||||
const res = await adminApi.getAllCDKs()
|
||||
cdks.value = res.data?.data || []
|
||||
} else {
|
||||
const res = await adminApi.getMyCDKs()
|
||||
cdks.value = res.data?.data || []
|
||||
const params: adminApi.CDKListParams = {
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
keyword: searchKeyword.value,
|
||||
status: statusFilter.value,
|
||||
}
|
||||
const res = isAdmin.value ? await adminApi.getAllCDKs(params) : await adminApi.getMyCDKs(params)
|
||||
const data = res.data?.data
|
||||
cdks.value = data?.items || []
|
||||
total.value = data?.total || 0
|
||||
if (data?.summary) summary.value = data.summary
|
||||
} catch {
|
||||
message.error('加载CDK列表失败')
|
||||
cdks.value = []
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const filteredCDKs = computed(() => {
|
||||
if (!searchQuery.value.trim()) return cdks.value
|
||||
const q = searchQuery.value.toLowerCase()
|
||||
return cdks.value.filter((c) => c.code.toLowerCase().includes(q))
|
||||
})
|
||||
function handleSearch() {
|
||||
page.value = 1
|
||||
searchKeyword.value = keywordInput.value.trim()
|
||||
loadCDKs()
|
||||
}
|
||||
|
||||
function handleStatusChange() {
|
||||
page.value = 1
|
||||
loadCDKs()
|
||||
}
|
||||
|
||||
function handlePage(p: number) {
|
||||
if (p < 1 || p > totalPages.value) return
|
||||
page.value = p
|
||||
loadCDKs()
|
||||
}
|
||||
|
||||
function handlePageSize(size: number) {
|
||||
if (size === pageSize.value) return
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
loadCDKs()
|
||||
}
|
||||
|
||||
async function handleGenerate() {
|
||||
if (generateCount.value <= 0 || generateCount.value > 100) {
|
||||
message.info('数量范围为 1-100')
|
||||
return
|
||||
}
|
||||
if (generateMaxRuns.value <= 0 || generateMaxRuns.value > 999) {
|
||||
if (generateType.value === 'vip') {
|
||||
if (generateVipDays.value !== 7 && generateVipDays.value !== 30) {
|
||||
message.info('VIP CDK 仅支持周卡(7 天)或月卡(30 天)')
|
||||
return
|
||||
}
|
||||
} else if (generateMaxRuns.value <= 0 || generateMaxRuns.value > 999) {
|
||||
message.info('运行次数范围为 1-999')
|
||||
return
|
||||
}
|
||||
generateLoading.value = true
|
||||
try {
|
||||
const res = await adminApi.generateCDK(generateCount.value, generateMaxRuns.value)
|
||||
const res = await adminApi.generateCDK(
|
||||
generateCount.value,
|
||||
generateMaxRuns.value,
|
||||
generateType.value,
|
||||
generateVipDays.value
|
||||
)
|
||||
const data = res.data?.data
|
||||
message.success(`成功生成 ${data?.count || 0} 个CDK(每张 ${data?.maxRuns || 1} 次)`)
|
||||
showGenerateModal.value = false
|
||||
generateCount.value = 1
|
||||
generateMaxRuns.value = 1
|
||||
await loadCDKs()
|
||||
resultCdks.value = data?.cdkCodes || []
|
||||
resultCost.value = data?.costTotal || 0
|
||||
copiedAll.value = false
|
||||
// 切到结果视图,展示全部CDK供复制
|
||||
modalView.value = 'result'
|
||||
} catch (e: any) {
|
||||
message.error(e?.response?.data?.message || e?.message || '生成失败')
|
||||
} finally {
|
||||
@@ -79,30 +151,99 @@ async function handleGenerate() {
|
||||
}
|
||||
}
|
||||
|
||||
function openGenerateModal() {
|
||||
modalView.value = 'form'
|
||||
generateCount.value = 1
|
||||
generateMaxRuns.value = 1
|
||||
generateType.value = 'count'
|
||||
generateVipDays.value = 30
|
||||
showGenerateModal.value = true
|
||||
}
|
||||
|
||||
function closeGenerateModal() {
|
||||
showGenerateModal.value = false
|
||||
// 返回首页重新加载最新数据
|
||||
page.value = 1
|
||||
searchKeyword.value = ''
|
||||
keywordInput.value = ''
|
||||
statusFilter.value = ''
|
||||
loadCDKs()
|
||||
}
|
||||
|
||||
async function copyCode(code: string, index: number) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code)
|
||||
copiedIndex.value = index
|
||||
setTimeout(() => { copiedIndex.value = null }, 2000)
|
||||
} catch {
|
||||
// fallback
|
||||
const ta = document.createElement('textarea')
|
||||
ta.value = code
|
||||
document.body.appendChild(ta)
|
||||
ta.select()
|
||||
document.execCommand('copy')
|
||||
document.body.removeChild(ta)
|
||||
if (await copyToClipboard(code)) {
|
||||
copiedIndex.value = index
|
||||
setTimeout(() => { copiedIndex.value = null }, 2000)
|
||||
message.success('已复制')
|
||||
} else {
|
||||
message.error('复制失败,请长按 CDK 码手动复制')
|
||||
}
|
||||
}
|
||||
|
||||
/** 统计 */
|
||||
const stats = computed(() => ({
|
||||
total: cdks.value.length,
|
||||
used: cdks.value.filter((c) => c.status === 'used').length,
|
||||
unused: cdks.value.filter((c) => c.status === 'unused').length,
|
||||
}))
|
||||
async function copyResultCode(code: string, index: number) {
|
||||
if (await copyToClipboard(code)) {
|
||||
resultCopiedIdx.value = index
|
||||
setTimeout(() => { resultCopiedIdx.value = null }, 2000)
|
||||
message.success('已复制')
|
||||
} else {
|
||||
message.error('复制失败,请长按 CDK 码手动复制')
|
||||
}
|
||||
}
|
||||
|
||||
async function copyAllCodes() {
|
||||
if (resultCdks.value.length === 0) return
|
||||
const all = resultCdks.value.map((c) => c.code).join('\n')
|
||||
if (await copyToClipboard(all)) {
|
||||
copiedAll.value = true
|
||||
message.success(`已复制全部 ${resultCdks.value.length} 个CDK`)
|
||||
setTimeout(() => { copiedAll.value = false }, 2000)
|
||||
} else {
|
||||
message.error('复制失败,请长按 CDK 码手动复制')
|
||||
}
|
||||
}
|
||||
|
||||
function askDisable(cdk: adminApi.CDKCode) {
|
||||
statusAction.value = 'disable'
|
||||
statusTarget.value = cdk
|
||||
showStatusModal.value = true
|
||||
}
|
||||
|
||||
function askEnable(cdk: adminApi.CDKCode) {
|
||||
statusAction.value = 'enable'
|
||||
statusTarget.value = cdk
|
||||
showStatusModal.value = true
|
||||
}
|
||||
|
||||
async function confirmStatusChange() {
|
||||
const target = statusTarget.value
|
||||
if (!target) return
|
||||
statusLoading.value = true
|
||||
try {
|
||||
await adminApi.updateCDKStatus(target.id, statusAction.value)
|
||||
message.success(statusAction.value === 'disable' ? '已禁用该CDK' : '已恢复该CDK')
|
||||
showStatusModal.value = false
|
||||
statusTarget.value = null
|
||||
await loadCDKs()
|
||||
} catch (e: any) {
|
||||
message.error(e?.response?.data?.message || '操作失败')
|
||||
} finally {
|
||||
statusLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const statusText = computed(() => (statusAction.value === 'disable' ? '禁用CDK' : '恢复CDK'))
|
||||
|
||||
function statusLabel(s: string) {
|
||||
if (s === 'used') return '已使用'
|
||||
if (s === 'disabled') return '已禁用'
|
||||
return '未使用'
|
||||
}
|
||||
|
||||
function statusClass(s: string) {
|
||||
if (s === 'used') return 'bg-gray-100 text-gray-600'
|
||||
if (s === 'disabled') return 'bg-red-50 text-red-600'
|
||||
return 'bg-green-100 text-green-700'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -110,32 +251,57 @@ const stats = computed(() => ({
|
||||
<!-- 顶部 -->
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<h1 class="text-xl font-bold text-gray-900">CDK管理</h1>
|
||||
<Button variant="default" size="sm" @click="showGenerateModal = true">
|
||||
<Button variant="default" size="sm" @click="openGenerateModal">
|
||||
<Plus class="w-4 h-4 mr-1" />
|
||||
生成CDK
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 统计 -->
|
||||
<div class="flex gap-4 mb-4">
|
||||
<div class="flex gap-4 mb-4 flex-wrap">
|
||||
<div class="bg-white rounded-lg border border-gray-200 px-4 py-2.5 flex items-center gap-2">
|
||||
<span class="text-xs text-gray-500">总计</span>
|
||||
<span class="text-lg font-bold text-gray-900">{{ stats.total }}</span>
|
||||
<span class="text-lg font-bold text-gray-900">{{ summary.total }}</span>
|
||||
</div>
|
||||
<div class="bg-white rounded-lg border border-green-200 px-4 py-2.5 flex items-center gap-2">
|
||||
<span class="text-xs text-green-600">未使用</span>
|
||||
<span class="text-lg font-bold text-green-700">{{ stats.unused }}</span>
|
||||
<span class="text-lg font-bold text-green-700">{{ summary.unused }}</span>
|
||||
</div>
|
||||
<div class="bg-white rounded-lg border border-gray-200 px-4 py-2.5 flex items-center gap-2">
|
||||
<span class="text-xs text-gray-500">已使用</span>
|
||||
<span class="text-lg font-bold text-gray-700">{{ stats.used }}</span>
|
||||
<span class="text-lg font-bold text-gray-700">{{ summary.used }}</span>
|
||||
</div>
|
||||
<div class="bg-white rounded-lg border border-red-200 px-4 py-2.5 flex items-center gap-2">
|
||||
<span class="text-xs text-red-500">已禁用</span>
|
||||
<span class="text-lg font-bold text-red-600">{{ summary.disabled }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 搜索 -->
|
||||
<div class="relative mb-4">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
|
||||
<Input v-model="searchQuery" placeholder="搜索CDK码..." class="pl-9 h-10 text-sm max-w-xs" />
|
||||
<!-- 筛选:搜索 + 状态 -->
|
||||
<div class="flex items-center gap-3 mb-4">
|
||||
<div class="relative flex-1 max-w-xs">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
|
||||
<Input
|
||||
v-model="keywordInput"
|
||||
placeholder="搜索CDK码..."
|
||||
class="pl-9 h-10 text-sm"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" class="h-10" @click="handleSearch">
|
||||
<Search class="w-4 h-4 mr-1" />
|
||||
搜索
|
||||
</Button>
|
||||
<select
|
||||
v-model="statusFilter"
|
||||
class="h-10 px-3 rounded-lg border border-gray-200 bg-white text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400"
|
||||
@change="handleStatusChange"
|
||||
>
|
||||
<option value="">全部状态</option>
|
||||
<option value="unused">未使用</option>
|
||||
<option value="used">已使用</option>
|
||||
<option value="disabled">已禁用</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
@@ -144,7 +310,7 @@ const stats = computed(() => ({
|
||||
<LoaderCircle class="w-6 h-6 animate-spin text-blue-500" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="filteredCDKs.length === 0" class="text-center py-16 text-sm text-gray-400">
|
||||
<div v-else-if="cdks.length === 0" class="text-center py-16 text-sm text-gray-400">
|
||||
<QrCode class="w-12 h-12 mx-auto mb-3 text-gray-200" />
|
||||
<p>暂无CDK数据</p>
|
||||
<p class="text-xs mt-1">点击右上角"生成CDK"开始创建</p>
|
||||
@@ -154,76 +320,291 @@ const stats = computed(() => ({
|
||||
<thead>
|
||||
<tr class="bg-gray-50 text-left text-xs text-gray-500">
|
||||
<th class="px-4 py-3 font-medium">CDK码</th>
|
||||
<th v-if="isAdmin" class="px-4 py-3 font-medium">生成代理</th>
|
||||
<th class="px-4 py-3 font-medium">售价</th>
|
||||
<th class="px-4 py-3 font-medium">次数</th>
|
||||
<th class="px-4 py-3 font-medium">类型</th>
|
||||
<th class="px-4 py-3 font-medium">额度</th>
|
||||
<th class="px-4 py-3 font-medium">状态</th>
|
||||
<th class="px-4 py-3 font-medium">创建时间</th>
|
||||
<th class="px-4 py-3 font-medium">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(cdk, idx) in filteredCDKs" :key="cdk.id" class="border-t border-gray-50 hover:bg-gray-50/50 transition-colors">
|
||||
<tr
|
||||
v-for="(cdk, idx) in cdks"
|
||||
:key="cdk.id"
|
||||
class="border-t border-gray-50 hover:bg-gray-50/50 transition-colors"
|
||||
:class="cdk.status === 'disabled' ? 'opacity-60' : ''"
|
||||
>
|
||||
<td class="px-4 py-3 whitespace-nowrap">
|
||||
<code class="font-mono text-xs bg-gray-100 px-2 py-1 rounded">{{ cdk.code }}</code>
|
||||
</td>
|
||||
<td v-if="isAdmin" class="px-4 py-3 text-xs text-gray-600 whitespace-nowrap">
|
||||
{{ (cdk as any).agent?.username || cdk.agentId }}
|
||||
</td>
|
||||
<td class="px-4 py-3 font-mono whitespace-nowrap">{{ cdk.price.toFixed(2) }} 元</td>
|
||||
<td class="px-4 py-3 whitespace-nowrap">
|
||||
<span
|
||||
v-if="cdk.type === 'vip'"
|
||||
class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 whitespace-nowrap"
|
||||
>⭐ VIP{{ cdk.vipDays === 7 ? '周卡' : '月卡' }}</span>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700 whitespace-nowrap"
|
||||
>次数卡</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-xs text-gray-600 whitespace-nowrap">
|
||||
{{ cdk.maxRuns ?? 1 }}
|
||||
{{ cdk.type === 'vip' ? `${cdk.vipDays} 天` : `${cdk.maxRuns ?? 1} 次` }}
|
||||
</td>
|
||||
<td class="px-4 py-3 whitespace-nowrap">
|
||||
<span
|
||||
class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium whitespace-nowrap"
|
||||
:class="cdk.status === 'used' ? 'bg-gray-100 text-gray-600' : 'bg-green-100 text-green-700'"
|
||||
:class="statusClass(cdk.status)"
|
||||
>
|
||||
{{ cdk.status === 'used' ? '已使用' : '未使用' }}
|
||||
{{ statusLabel(cdk.status) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">{{ new Date(cdk.createdAt).toLocaleString() }}</td>
|
||||
<td class="px-4 py-3 whitespace-nowrap">
|
||||
<button
|
||||
class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs transition-colors"
|
||||
:class="copiedIndex === idx ? 'bg-green-100 text-green-700' : 'bg-blue-50 text-blue-600 hover:bg-blue-100'"
|
||||
@click="copyCode(cdk.code, idx)"
|
||||
>
|
||||
<Copy v-if="copiedIndex !== idx" class="w-3 h-3" />
|
||||
<CheckCheck v-else class="w-3 h-3" />
|
||||
{{ copiedIndex === idx ? '已复制' : '复制' }}
|
||||
</button>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs transition-colors"
|
||||
:class="copiedIndex === idx ? 'bg-green-100 text-green-700' : 'bg-blue-50 text-blue-600 hover:bg-blue-100'"
|
||||
@click="copyCode(cdk.code, idx)"
|
||||
>
|
||||
<Copy v-if="copiedIndex !== idx" class="w-3 h-3" />
|
||||
<CheckCheck v-else class="w-3 h-3" />
|
||||
{{ copiedIndex === idx ? '已复制' : '复制' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="cdk.status === 'unused'"
|
||||
class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs text-red-500 hover:bg-red-50 transition-colors"
|
||||
@click="askDisable(cdk)"
|
||||
>
|
||||
<Ban class="w-3 h-3" />
|
||||
禁用
|
||||
</button>
|
||||
<button
|
||||
v-else-if="cdk.status === 'disabled'"
|
||||
class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs text-green-600 hover:bg-green-50 transition-colors"
|
||||
@click="askEnable(cdk)"
|
||||
>
|
||||
<RotateCcw class="w-3 h-3" />
|
||||
恢复
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 分页 -->
|
||||
<div
|
||||
v-if="total > 0"
|
||||
class="flex items-center justify-between px-4 py-3 border-t border-gray-100"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-xs text-gray-400">共 {{ total }} 条</span>
|
||||
<select
|
||||
:value="pageSize"
|
||||
class="h-8 px-2 rounded-lg border border-gray-200 bg-white text-xs text-gray-500 focus:outline-none"
|
||||
@change="handlePageSize(Number(($event.target as HTMLSelectElement).value))"
|
||||
>
|
||||
<option v-for="n in pageSizeOptions" :key="n" :value="n">{{ n }} 条/页</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 disabled:opacity-30"
|
||||
:disabled="page <= 1"
|
||||
@click="handlePage(page - 1)"
|
||||
>
|
||||
<ChevronLeft class="w-4 h-4" />
|
||||
</button>
|
||||
<span class="text-sm text-gray-600">{{ page }}/{{ totalPages }}</span>
|
||||
<button
|
||||
class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 disabled:opacity-30"
|
||||
:disabled="page >= totalPages"
|
||||
@click="handlePage(page + 1)"
|
||||
>
|
||||
<ChevronRight class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 生成CDK弹窗 -->
|
||||
<!-- 生成CDK弹窗(form / result 两视图) -->
|
||||
<Teleport to="body">
|
||||
<div v-if="showGenerateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="showGenerateModal = false">
|
||||
<div v-if="showGenerateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="modalView === 'form' ? (showGenerateModal = false) : null">
|
||||
<div
|
||||
class="bg-white rounded-xl shadow-xl w-full mx-4 p-6 flex flex-col"
|
||||
:class="modalView === 'result' ? 'max-w-lg max-h-[80vh]' : 'max-w-sm'"
|
||||
>
|
||||
<!-- 配置视图 -->
|
||||
<template v-if="modalView === 'form'">
|
||||
<div class="flex items-center justify-between mb-4 flex-shrink-0">
|
||||
<h2 class="text-lg font-semibold text-gray-900">生成CDK</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="closeGenerateModal">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<Label class="mb-2 block text-sm text-gray-600">CDK 类型</Label>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 rounded-md border text-sm font-medium transition-colors"
|
||||
:class="generateType === 'count' ? 'bg-emerald-600 text-white border-emerald-600' : 'bg-white text-gray-700 border-gray-300 hover:border-emerald-400'"
|
||||
@click="generateType = 'count'"
|
||||
>次数 CDK</button>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 rounded-md border text-sm font-medium transition-colors"
|
||||
:class="generateType === 'vip' ? 'bg-amber-500 text-white border-amber-500' : 'bg-white text-gray-700 border-gray-300 hover:border-amber-400'"
|
||||
@click="generateType = 'vip'"
|
||||
>⭐ VIP CDK</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">生成数量</Label>
|
||||
<Input v-model.number="generateCount" type="number" min="1" max="100" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">单次最多100个</p>
|
||||
</div>
|
||||
<template v-if="generateType === 'count'">
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">每张可运行次数</Label>
|
||||
<Input v-model.number="generateMaxRuns" type="number" min="1" max="999" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">每张CDK可兑换使用的次数,成本 = 基础单价 × 次数 × 费率</p>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">VIP 卡类型</Label>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 rounded-md border text-sm font-medium transition-colors"
|
||||
:class="generateVipDays === 7 ? 'bg-amber-500 text-white border-amber-500' : 'bg-white text-gray-700 border-gray-300 hover:border-amber-400'"
|
||||
@click="generateVipDays = 7"
|
||||
>周卡 · 7天</button>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 rounded-md border text-sm font-medium transition-colors"
|
||||
:class="generateVipDays === 30 ? 'bg-amber-500 text-white border-amber-500' : 'bg-white text-gray-700 border-gray-300 hover:border-amber-400'"
|
||||
@click="generateVipDays = 30"
|
||||
>月卡 · 30天</button>
|
||||
</div>
|
||||
<p class="text-xs text-gray-400 mt-1">兑换后从当前到期时间顺延,到期即享免扣次数执行任务</p>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showGenerateModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="generateLoading" @click="handleGenerate">
|
||||
<LoaderCircle v-if="generateLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
{{ generateLoading ? '生成中...' : '生成' }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 结果视图:展示全部CDK -->
|
||||
<template v-else>
|
||||
<div class="flex items-center justify-between mb-3 flex-shrink-0">
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold text-gray-900 flex items-center gap-2">
|
||||
<CheckCircle2 class="w-5 h-5 text-green-500" />
|
||||
生成成功
|
||||
</h2>
|
||||
<p class="text-xs text-gray-400 mt-0.5">
|
||||
共 {{ resultCdks.length }} 个CDK ·
|
||||
<template v-if="generateType === 'vip'">{{ generateVipDays === 7 ? 'VIP 周卡 7 天' : 'VIP 月卡 30 天' }} · </template>
|
||||
<template v-else>每张 {{ generateMaxRuns }} 次 · </template>
|
||||
扣费
|
||||
<span class="font-mono text-gray-600">{{ resultCost.toFixed(2) }} 元</span>
|
||||
</p>
|
||||
</div>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="closeGenerateModal">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- CDK 列表(可滚动) -->
|
||||
<div class="flex-1 overflow-y-auto border border-gray-100 rounded-lg bg-gray-50/60 min-h-[120px] max-h-[40vh]">
|
||||
<div
|
||||
v-for="cdk in resultCdks"
|
||||
:key="cdk.id"
|
||||
class="flex items-center justify-between px-3 py-2 border-b border-gray-100 last:border-0 bg-white"
|
||||
>
|
||||
<code class="font-mono text-xs text-gray-800">{{ cdk.code }}</code>
|
||||
<button
|
||||
class="flex-shrink-0 inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] transition-colors"
|
||||
:class="copiedResultIdx === resultCdks.indexOf(cdk) ? 'text-green-600 bg-green-50' : 'text-blue-500 hover:bg-blue-50'"
|
||||
@click="copyResultCode(cdk.code, resultCdks.indexOf(cdk))"
|
||||
>
|
||||
<Copy v-if="copiedResultIdx !== resultCdks.indexOf(cdk)" class="w-3 h-3" />
|
||||
<CheckCheck v-else class="w-3 h-3" />
|
||||
复制
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-4 flex-shrink-0">
|
||||
<Button variant="outline" class="h-10 px-4" @click="openGenerateModal">
|
||||
<Plus class="w-4 h-4 mr-1" />
|
||||
继续生成
|
||||
</Button>
|
||||
<Button class="flex-1 h-10" @click="copyAllCodes">
|
||||
<CheckCheck v-if="copiedAll" class="w-4 h-4 mr-1" />
|
||||
<Copy v-else class="w-4 h-4 mr-1" />
|
||||
{{ copiedAll ? '已复制全部' : '复制全部CDK' }}
|
||||
</Button>
|
||||
</div>
|
||||
<p class="text-center text-[10px] text-gray-300 mt-2">
|
||||
提示:CDK 按行分隔,可直接粘贴到表格/文档批量分发
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<!-- 禁用/恢复确认弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="showStatusModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="showStatusModal = false">
|
||||
<div class="bg-white rounded-xl shadow-xl w-full max-w-sm mx-4 p-6">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-lg font-semibold text-gray-900">生成CDK</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showGenerateModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">生成数量</Label>
|
||||
<Input v-model.number="generateCount" type="number" min="1" max="100" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">单次最多100个</p>
|
||||
<div class="flex items-center gap-2.5 mb-3">
|
||||
<div
|
||||
class="w-9 h-9 rounded-xl flex items-center justify-center"
|
||||
:class="statusAction === 'disable' ? 'bg-red-100' : 'bg-green-100'"
|
||||
>
|
||||
<Ban v-if="statusAction === 'disable'" class="w-4 h-4 text-red-500" />
|
||||
<RotateCcw v-else class="w-4 h-4 text-green-600" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">每张可运行次数</Label>
|
||||
<Input v-model.number="generateMaxRuns" type="number" min="1" max="999" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">每张CDK可兑换使用的次数,成本 = 基础单价 × 次数 × 费率</p>
|
||||
<h2 class="text-base font-semibold text-gray-900">{{ statusText }}</h2>
|
||||
<p class="text-xs text-gray-400 mt-0.5">{{ statusTarget?.code }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showGenerateModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="generateLoading" @click="handleGenerate">
|
||||
<LoaderCircle v-if="generateLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
{{ generateLoading ? '生成中...' : '生成' }}
|
||||
<p class="text-sm text-gray-500 leading-relaxed text-justify">
|
||||
<template v-if="statusAction === 'disable'">
|
||||
禁用后该CDK将<strong class="text-red-500">无法被用户兑换</strong>,如需使用可随时恢复。
|
||||
</template>
|
||||
<template v-else>
|
||||
恢复后该CDK将重新变为<strong class="text-green-600">未使用</strong>状态,可被用户兑换。
|
||||
</template>
|
||||
</p>
|
||||
<div class="flex gap-2 mt-5">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showStatusModal = false">取消</Button>
|
||||
<Button
|
||||
class="flex-1 h-10"
|
||||
:class="statusAction === 'disable' ? 'bg-red-500 hover:bg-red-600' : 'bg-green-500 hover:bg-green-600'"
|
||||
:disabled="statusLoading"
|
||||
@click="confirmStatusChange"
|
||||
>
|
||||
<LoaderCircle v-if="statusLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
{{ statusAction === 'disable' ? '确认禁用' : '确认恢复' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -31,14 +31,15 @@ onMounted(async () => {
|
||||
|
||||
me.value = meRes.data?.data || null
|
||||
subAgents.value = agentRes.data?.data || []
|
||||
cdks.value = cdkRes.data?.data || []
|
||||
cdks.value = cdkRes.data?.data?.items || []
|
||||
|
||||
const agents = agentRes.data?.data || []
|
||||
const summary = cdkRes.data?.data?.summary
|
||||
stats.value = {
|
||||
totalAgents: agents.length,
|
||||
activeAgents: agents.filter((a) => a.status === 'active').length,
|
||||
totalCDKs: cdks.value.length,
|
||||
usedCDKs: cdks.value.filter((c) => c.status === 'used').length,
|
||||
totalCDKs: summary?.total ?? cdks.value.length,
|
||||
usedCDKs: summary?.used ?? cdks.value.filter((c) => c.status === 'used').length,
|
||||
balance: me.value?.balance || 0,
|
||||
rate: me.value?.rate ?? 1,
|
||||
}
|
||||
@@ -133,9 +134,9 @@ onMounted(async () => {
|
||||
<td class="py-2.5">
|
||||
<span
|
||||
class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
:class="cdk.status === 'used' ? 'bg-gray-100 text-gray-600' : 'bg-green-100 text-green-700'"
|
||||
:class="cdk.status === 'used' ? 'bg-gray-100 text-gray-600' : cdk.status === 'disabled' ? 'bg-red-50 text-red-600' : 'bg-green-100 text-green-700'"
|
||||
>
|
||||
{{ cdk.status === 'used' ? '已使用' : '未使用' }}
|
||||
{{ cdk.status === 'used' ? '已使用' : cdk.status === 'disabled' ? '已禁用' : '未使用' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-2.5 text-gray-500">{{ new Date(cdk.createdAt).toLocaleString() }}</td>
|
||||
|
||||
@@ -33,17 +33,22 @@ const adminInfo = ref<AgentInfo | null>(null)
|
||||
const showUserMenu = ref(false)
|
||||
const showSidebar = ref(false)
|
||||
|
||||
const navItems = [
|
||||
const navItems: { name: string; label: string; icon: unknown; path: string; adminOnly?: boolean }[] = [
|
||||
{ name: 'admin-dashboard', label: '仪表盘', icon: LayoutDashboard, path: '/admin/dashboard' },
|
||||
{ name: 'admin-agents', label: '代理管理', icon: Users, path: '/admin/agents' },
|
||||
{ name: 'admin-users', label: '用户管理', icon: UserCheck, path: '/admin/users' },
|
||||
{ name: 'admin-users', label: '用户管理', icon: UserCheck, path: '/admin/users', adminOnly: true },
|
||||
{ name: 'admin-cdks', label: 'CDK管理', icon: QrCode, path: '/admin/cdks' },
|
||||
{ name: 'admin-announcements', label: '公告管理', icon: Megaphone, path: '/admin/announcements' },
|
||||
{ name: 'admin-tickets', label: '工单管理', icon: MessageSquare, path: '/admin/tickets' },
|
||||
{ name: 'admin-pending-schools', label: '待适配学校', icon: School, path: '/admin/pending-schools' },
|
||||
{ name: 'admin-settings', label: '系统设置', icon: Settings, path: '/admin/settings' },
|
||||
{ name: 'admin-announcements', label: '公告管理', icon: Megaphone, path: '/admin/announcements', adminOnly: true },
|
||||
{ name: 'admin-tickets', label: '工单管理', icon: MessageSquare, path: '/admin/tickets', adminOnly: true },
|
||||
{ name: 'admin-pending-schools', label: '待适配学校', icon: School, path: '/admin/pending-schools', adminOnly: true },
|
||||
{ name: 'admin-settings', label: '系统设置', icon: Settings, path: '/admin/settings', adminOnly: true },
|
||||
]
|
||||
|
||||
// 代理(agent)只能访问:仪表盘、代理管理、CDK管理
|
||||
const visibleNavItems = computed(() =>
|
||||
navItems.filter((item) => !item.adminOnly || adminInfo.value?.role === 'admin')
|
||||
)
|
||||
|
||||
const activeNav = computed(() => route.name as string)
|
||||
|
||||
// 公告相关(代理端)
|
||||
@@ -130,7 +135,7 @@ function dismissForcePopup() {
|
||||
forcePopupQueue.value = forcePopupQueue.value.slice(1)
|
||||
}
|
||||
|
||||
function navigateTo(item: typeof navItems[0]) {
|
||||
function navigateTo(item: { name: string; label: string; icon: unknown; path: string; adminOnly?: boolean }) {
|
||||
router.push({ name: item.name })
|
||||
showSidebar.value = false
|
||||
}
|
||||
@@ -148,7 +153,7 @@ function handleLogout() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen bg-gray-100 flex">
|
||||
<div class="min-h-dvh bg-gray-100 flex">
|
||||
<!-- 手机端顶栏 -->
|
||||
<div class="fixed top-0 left-0 right-0 h-14 bg-white border-b border-gray-200 flex items-center px-4 gap-3 z-30 md:hidden">
|
||||
<button
|
||||
@@ -217,7 +222,7 @@ function handleLogout() {
|
||||
<!-- 导航菜单 -->
|
||||
<nav class="flex-1 py-3 px-3 space-y-1 overflow-y-auto">
|
||||
<button
|
||||
v-for="item in navItems"
|
||||
v-for="item in visibleNavItems"
|
||||
:key="item.name"
|
||||
class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-colors"
|
||||
:class="activeNav === item.name
|
||||
|
||||
@@ -49,7 +49,7 @@ async function handleLogin() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
|
||||
<div class="min-h-dvh flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- 标题 -->
|
||||
<div class="text-center mb-8">
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { Shield, RefreshCw, CheckCircle, Search, Eye, EyeOff, Copy } from 'lucide-vue-next'
|
||||
import { Shield, RefreshCw, CheckCircle, XCircle, Search, Eye, EyeOff, Copy } from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import { copyToClipboard } from '@/utils/clipboard'
|
||||
import api from '@/api/index'
|
||||
|
||||
interface PendingSchoolItem {
|
||||
@@ -15,6 +16,7 @@ interface PendingSchoolItem {
|
||||
email: string
|
||||
ip: string
|
||||
status: string
|
||||
rejectReason: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
@@ -32,11 +34,33 @@ const loading = ref(true)
|
||||
const statusFilter = ref('pending')
|
||||
const searchKeyword = ref('')
|
||||
const showPasswordMap = ref<Record<number, boolean>>({})
|
||||
// 已适配学校:schoolId -> 学校名(用于在待处理列表中标识已适配过的学校)
|
||||
const adaptedSchools = ref<Map<string, string>>(new Map())
|
||||
// 拒绝弹窗
|
||||
const rejectTarget = ref<PendingSchoolItem | null>(null)
|
||||
const rejectReason = ref('')
|
||||
const rejectSubmitting = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
loadData()
|
||||
loadAdaptedSchools()
|
||||
})
|
||||
|
||||
async function loadAdaptedSchools() {
|
||||
try {
|
||||
const res = await api.get<{ data: PendingSchoolItem[] }>('/admin/pending-schools', {
|
||||
params: { status: 'completed' },
|
||||
})
|
||||
const map = new Map<string, string>()
|
||||
for (const r of res.data?.data || []) {
|
||||
if (!map.has(r.schoolId)) map.set(r.schoolId, r.schoolName)
|
||||
}
|
||||
adaptedSchools.value = map
|
||||
} catch {
|
||||
// 已适配信息加载失败不影响主列表
|
||||
}
|
||||
}
|
||||
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -84,10 +108,45 @@ async function handleMarkDone(record: PendingSchoolItem) {
|
||||
}
|
||||
}
|
||||
|
||||
function copyText(text: string) {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
function openRejectModal(record: PendingSchoolItem) {
|
||||
rejectTarget.value = record
|
||||
rejectReason.value = ''
|
||||
}
|
||||
|
||||
function closeRejectModal() {
|
||||
if (rejectSubmitting.value) return
|
||||
rejectTarget.value = null
|
||||
rejectReason.value = ''
|
||||
}
|
||||
|
||||
async function confirmReject() {
|
||||
const target = rejectTarget.value
|
||||
if (!target) return
|
||||
const reason = rejectReason.value.trim()
|
||||
if (!reason) {
|
||||
message.error('拒绝时必须说明理由')
|
||||
return
|
||||
}
|
||||
rejectSubmitting.value = true
|
||||
try {
|
||||
await api.post(`/admin/pending-schools/${target.id}/reject`, { reason })
|
||||
message.success(`已拒绝该条记录,拒绝理由将邮件通知联系邮箱`)
|
||||
closeRejectModal()
|
||||
await loadData()
|
||||
} catch (err: any) {
|
||||
message.error(err?.response?.data?.message || '操作失败')
|
||||
} finally {
|
||||
rejectSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function copyText(text: string) {
|
||||
const ok = await copyToClipboard(text)
|
||||
if (ok) {
|
||||
message.success('已复制')
|
||||
})
|
||||
} else {
|
||||
message.error('复制失败,请长按手动复制')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -117,6 +176,11 @@ function copyText(text: string) {
|
||||
:class="statusFilter === 'completed' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-700'"
|
||||
@click="statusFilter = 'completed'; loadData()"
|
||||
>已完成</button>
|
||||
<button
|
||||
class="px-3 py-1.5 text-xs font-medium rounded-md transition-colors"
|
||||
:class="statusFilter === 'rejected' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-700'"
|
||||
@click="statusFilter = 'rejected'; loadData()"
|
||||
>已拒绝</button>
|
||||
<button
|
||||
class="px-3 py-1.5 text-xs font-medium rounded-md transition-colors"
|
||||
:class="statusFilter === '' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-700'"
|
||||
@@ -130,6 +194,23 @@ function copyText(text: string) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 已适配学校信息 -->
|
||||
<div
|
||||
v-if="adaptedSchools.size > 0 && statusFilter !== 'completed'"
|
||||
class="mb-6 bg-green-50 border border-green-200 rounded-xl px-4 py-3"
|
||||
>
|
||||
<div class="flex items-center gap-2 text-sm font-medium text-green-700 mb-1.5">
|
||||
<CheckCircle class="w-4 h-4" />
|
||||
已适配学校({{ adaptedSchools.size }} 所)
|
||||
</div>
|
||||
<p class="text-xs text-green-600 leading-relaxed">
|
||||
<template v-for="(name, schoolId, i) in adaptedSchools" :key="schoolId">
|
||||
{{ name }}<span v-if="i < adaptedSchools.size - 1">、</span>
|
||||
</template>
|
||||
</p>
|
||||
<p class="text-[10px] text-green-500 mt-1">以下学校已适配完成,若有新登录失败反馈请优先核对该学校登录流程</p>
|
||||
</div>
|
||||
|
||||
<!-- 搜索 -->
|
||||
<div class="relative max-w-xs mb-6">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
|
||||
@@ -166,24 +247,43 @@ function copyText(text: string) {
|
||||
<div class="flex items-center gap-2.5">
|
||||
<Shield class="w-4 h-4 text-amber-500" />
|
||||
<span class="text-sm font-semibold text-gray-900">{{ group.schoolName }}</span>
|
||||
<span
|
||||
v-if="adaptedSchools.has(group.schoolId)"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded-full bg-green-50 text-green-600 font-medium border border-green-100"
|
||||
>
|
||||
已适配
|
||||
</span>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full bg-amber-50 text-amber-600 font-medium border border-amber-100">
|
||||
{{ group.count }} 条
|
||||
</span>
|
||||
<span class="text-[10px] text-gray-400 font-mono">{{ group.schoolId }}</span>
|
||||
</div>
|
||||
<Button
|
||||
v-if="statusFilter !== 'completed'"
|
||||
size="sm"
|
||||
class="h-7 text-xs"
|
||||
@click="handleMarkDone(group.records[0])"
|
||||
>
|
||||
<CheckCircle class="w-3 h-3 mr-1" />
|
||||
标记完成
|
||||
</Button>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<Button
|
||||
v-if="statusFilter !== 'completed' && statusFilter !== 'rejected'"
|
||||
size="sm"
|
||||
class="h-7 text-xs whitespace-nowrap"
|
||||
@click="handleMarkDone(group.records[0])"
|
||||
>
|
||||
<CheckCircle class="w-3 h-3 mr-1 shrink-0" />
|
||||
标记完成
|
||||
</Button>
|
||||
<Button
|
||||
v-if="statusFilter === 'pending'"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-7 text-xs text-red-500 border-red-200 hover:bg-red-50 whitespace-nowrap"
|
||||
@click="openRejectModal(group.records[0])"
|
||||
>
|
||||
<XCircle class="w-3 h-3 mr-1 shrink-0" />
|
||||
拒绝
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 账号列表 -->
|
||||
<table class="w-full text-sm">
|
||||
<!-- 账号列表(小屏横向滚动) -->
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm min-w-[760px]">
|
||||
<thead>
|
||||
<tr class="text-left text-xs text-gray-400 border-b border-gray-50">
|
||||
<th class="px-5 py-2.5 font-medium w-[16%]">账号</th>
|
||||
@@ -243,29 +343,82 @@ function copyText(text: string) {
|
||||
<td class="px-5 py-3">
|
||||
<span
|
||||
class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium"
|
||||
:class="r.status === 'pending' ? 'bg-amber-50 text-amber-600' : 'bg-green-50 text-green-600'"
|
||||
:class="r.status === 'pending' ? 'bg-amber-50 text-amber-600' : r.status === 'rejected' ? 'bg-red-50 text-red-600' : 'bg-green-50 text-green-600'"
|
||||
>
|
||||
{{ r.status === 'pending' ? '待处理' : '已完成' }}
|
||||
{{ r.status === 'pending' ? '待处理' : r.status === 'rejected' ? '已拒绝' : '已完成' }}
|
||||
</span>
|
||||
<p
|
||||
v-if="r.status === 'rejected' && r.rejectReason"
|
||||
class="text-[10px] text-red-400 mt-1 max-w-[180px] leading-snug"
|
||||
:title="r.rejectReason"
|
||||
>理由:{{ r.rejectReason }}</p>
|
||||
</td>
|
||||
<!-- 提交时间 -->
|
||||
<td class="px-5 py-3 text-gray-500 text-xs">{{ r.createdAt }}</td>
|
||||
<!-- 操作 -->
|
||||
<td class="px-5 py-3">
|
||||
<button
|
||||
v-if="r.status === 'pending'"
|
||||
class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs text-blue-500 hover:bg-blue-50 transition-colors"
|
||||
@click="handleMarkDone(r)"
|
||||
>
|
||||
<CheckCircle class="w-3 h-3" />
|
||||
完成
|
||||
</button>
|
||||
<td class="px-5 py-3 whitespace-nowrap">
|
||||
<div v-if="r.status === 'pending'" class="flex items-center gap-1 whitespace-nowrap">
|
||||
<button
|
||||
class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs whitespace-nowrap text-blue-500 hover:bg-blue-50 transition-colors"
|
||||
@click="handleMarkDone(r)"
|
||||
>
|
||||
<CheckCircle class="w-3 h-3 shrink-0" />
|
||||
完成
|
||||
</button>
|
||||
<button
|
||||
class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs whitespace-nowrap text-red-500 hover:bg-red-50 transition-colors"
|
||||
@click="openRejectModal(r)"
|
||||
>
|
||||
<XCircle class="w-3 h-3 shrink-0" />
|
||||
拒绝
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 拒绝理由弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="rejectTarget"
|
||||
class="fixed inset-0 z-50 bg-black/40 flex items-center justify-center px-4"
|
||||
@click.self="closeRejectModal"
|
||||
>
|
||||
<div class="bg-white rounded-2xl w-full max-w-md p-6 shadow-xl">
|
||||
<div class="flex items-center gap-3 mb-4">
|
||||
<div class="w-9 h-9 rounded-full bg-red-50 flex items-center justify-center">
|
||||
<XCircle class="w-5 h-5 text-red-500" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="text-base font-bold text-gray-900">拒绝适配申请</h3>
|
||||
<p class="text-xs text-gray-400">{{ rejectTarget.schoolName }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<label class="block text-sm text-gray-600 mb-1.5">拒绝理由 <span class="text-red-500">*</span></label>
|
||||
<textarea
|
||||
v-model="rejectReason"
|
||||
rows="4"
|
||||
maxlength="500"
|
||||
placeholder="请说明拒绝理由(必填),理由将通过邮件通知该学校的联系邮箱"
|
||||
class="w-full rounded-lg border border-gray-200 px-3 py-2.5 text-sm text-gray-900 placeholder:text-gray-300 focus:outline-none focus:ring-2 focus:ring-red-100 focus:border-red-300 resize-none"
|
||||
></textarea>
|
||||
<p class="text-[11px] text-gray-400 mt-1">发送后将邮件通知该条记录的联系邮箱</p>
|
||||
<div class="flex justify-end gap-2 mt-5">
|
||||
<Button variant="outline" size="sm" class="h-9 text-xs" :disabled="rejectSubmitting" @click="closeRejectModal">
|
||||
取消
|
||||
</Button>
|
||||
<Button size="sm" class="h-9 text-xs bg-red-500 hover:bg-red-600 text-white" :disabled="rejectSubmitting" @click="confirmReject">
|
||||
<XCircle class="w-3.5 h-3.5 mr-1" />
|
||||
{{ rejectSubmitting ? '提交中...' : '确认拒绝' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { Save, LoaderCircle, Euro, Gift, UserPlus } from 'lucide-vue-next'
|
||||
import { Save, LoaderCircle, Euro, Gift, Mail, Send, KeyRound } from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
@@ -13,10 +13,24 @@ const message = useMessage()
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const baseDeduction = ref('')
|
||||
const vipWeekPrice = ref('')
|
||||
const vipMonthPrice = ref('')
|
||||
const inviterReward = ref('')
|
||||
const inviteeReward = ref('')
|
||||
const registerReward = ref('')
|
||||
|
||||
// 邮件通知(SMTP)设置
|
||||
const mailSaving = ref(false)
|
||||
const mailTesting = ref(false)
|
||||
const smtpHost = ref('')
|
||||
const smtpPort = ref('465')
|
||||
const smtpSecure = ref('')
|
||||
const smtpUser = ref('')
|
||||
const smtpPassword = ref('')
|
||||
const smtpFrom = ref('')
|
||||
const smtpFromName = ref('')
|
||||
const adminEmails = ref('')
|
||||
|
||||
onMounted(async () => {
|
||||
await loadSettings()
|
||||
})
|
||||
@@ -27,9 +41,19 @@ async function loadSettings() {
|
||||
const res = await adminApi.getSettings()
|
||||
const settings = res.data?.data || {}
|
||||
baseDeduction.value = settings['base_deduction_per_run'] || '1.00'
|
||||
vipWeekPrice.value = settings['vip_price_week'] || '30.00'
|
||||
vipMonthPrice.value = settings['vip_price_month'] || '100.00'
|
||||
inviterReward.value = settings['inviter_reward_per_invite'] || '0.50'
|
||||
inviteeReward.value = settings['invitee_reward_per_invite'] || '0.50'
|
||||
registerReward.value = settings['register_reward'] || '1.00'
|
||||
smtpHost.value = settings['smtp_host'] || ''
|
||||
smtpPort.value = settings['smtp_port'] || '465'
|
||||
smtpSecure.value = settings['smtp_secure'] || ''
|
||||
smtpUser.value = settings['smtp_user'] || ''
|
||||
smtpPassword.value = settings['smtp_password'] || ''
|
||||
smtpFrom.value = settings['smtp_from'] || ''
|
||||
smtpFromName.value = settings['smtp_from_name'] || ''
|
||||
adminEmails.value = settings['admin_emails'] || ''
|
||||
} catch {
|
||||
message.error('加载设置失败')
|
||||
} finally {
|
||||
@@ -37,6 +61,51 @@ async function loadSettings() {
|
||||
}
|
||||
}
|
||||
|
||||
// ======== 邮件通知设置 ========
|
||||
async function handleSaveMail() {
|
||||
if (!smtpHost.value.trim() || !smtpPort.value.trim()) {
|
||||
message.info('请填写 SMTP 服务器与端口')
|
||||
return
|
||||
}
|
||||
if (!adminEmails.value.trim()) {
|
||||
message.info('请填写管理员通知邮箱')
|
||||
return
|
||||
}
|
||||
mailSaving.value = true
|
||||
try {
|
||||
const items: Record<string, string> = {
|
||||
smtp_host: smtpHost.value.trim(),
|
||||
smtp_port: smtpPort.value.trim(),
|
||||
smtp_user: smtpUser.value.trim(),
|
||||
smtp_password: smtpPassword.value,
|
||||
smtp_from: smtpFrom.value.trim(),
|
||||
smtp_from_name: smtpFromName.value.trim(),
|
||||
smtp_secure: smtpSecure.value,
|
||||
admin_emails: adminEmails.value.trim(),
|
||||
}
|
||||
for (const [k, v] of Object.entries(items)) {
|
||||
await adminApi.updateSetting(k, v)
|
||||
}
|
||||
message.success('邮件配置已保存,可点击"发送测试邮件"验证')
|
||||
} catch (e: any) {
|
||||
message.error(e?.response?.data?.message || e?.message || '保存失败')
|
||||
} finally {
|
||||
mailSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTestMail() {
|
||||
mailTesting.value = true
|
||||
try {
|
||||
await adminApi.sendTestMail()
|
||||
message.success('测试邮件已发送,请检查管理员邮箱')
|
||||
} catch (e: any) {
|
||||
message.error(e?.response?.data?.message || e?.message || '发送失败')
|
||||
} finally {
|
||||
mailTesting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
const deduction = parseFloat(baseDeduction.value)
|
||||
if (isNaN(deduction) || deduction <= 0) {
|
||||
@@ -58,10 +127,22 @@ async function handleSave() {
|
||||
message.info('直接注册奖励积分请输入有效的非负数')
|
||||
return
|
||||
}
|
||||
const vipWeek = parseFloat(vipWeekPrice.value)
|
||||
if (isNaN(vipWeek) || vipWeek <= 0) {
|
||||
message.info('VIP 周卡售价请输入有效的正数')
|
||||
return
|
||||
}
|
||||
const vipMonth = parseFloat(vipMonthPrice.value)
|
||||
if (isNaN(vipMonth) || vipMonth <= 0) {
|
||||
message.info('VIP 月卡售价请输入有效的正数')
|
||||
return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
await adminApi.updateSetting('base_deduction_per_run', deduction.toFixed(2))
|
||||
await adminApi.updateSetting('vip_price_week', vipWeek.toFixed(2))
|
||||
await adminApi.updateSetting('vip_price_month', vipMonth.toFixed(2))
|
||||
await adminApi.updateSetting('inviter_reward_per_invite', invReward.toFixed(2))
|
||||
await adminApi.updateSetting('invitee_reward_per_invite', ineeReward.toFixed(2))
|
||||
await adminApi.updateSetting('register_reward', regReward.toFixed(2))
|
||||
@@ -103,6 +184,34 @@ async function handleSave() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">⭐ VIP 周卡售价(元 / 7天)</Label>
|
||||
<Input
|
||||
v-model="vipWeekPrice"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
class="h-10 text-sm max-w-[200px]"
|
||||
/>
|
||||
<p class="text-xs text-gray-400 mt-1">
|
||||
生成 VIP 周卡 CDK 的单张售价,VIP 有效期内执行任务免扣次数
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">⭐ VIP 月卡售价(元 / 30天)</Label>
|
||||
<Input
|
||||
v-model="vipMonthPrice"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
class="h-10 text-sm max-w-[200px]"
|
||||
/>
|
||||
<p class="text-xs text-gray-400 mt-1">
|
||||
生成 VIP 月卡 CDK 的单张售价,前台开通/续费 VIP 展示此价格
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 pt-2">
|
||||
<Button :disabled="saving" @click="handleSave">
|
||||
<Save class="w-4 h-4 mr-1" />
|
||||
@@ -181,5 +290,93 @@ async function handleSave() {
|
||||
</template>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<!-- 邮件通知设置 -->
|
||||
<Card class="max-w-2xl mt-6">
|
||||
<div class="border-b border-gray-100 px-6 py-4 flex items-center gap-2">
|
||||
<Mail class="w-4 h-4 text-green-500" />
|
||||
<span class="font-semibold text-gray-900 text-sm">邮件通知设置(SMTP)</span>
|
||||
</div>
|
||||
<div class="p-6 space-y-4">
|
||||
<p class="text-xs text-gray-400 leading-relaxed -mt-2">
|
||||
配置后:收到新的待适配学校提交时自动邮件提醒管理员;学校适配完成时自动邮件通知提交者留下的联系邮箱。
|
||||
未配置时相关邮件通知自动跳过,不影响其他功能。
|
||||
</p>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">SMTP 服务器地址</Label>
|
||||
<Input v-model="smtpHost" placeholder="smtp.qq.com" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">SMTP 端口</Label>
|
||||
<Input v-model="smtpPort" placeholder="465" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">465=SSL,587/25=STARTTLS,端口决定加密方式</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">SMTP 用户名</Label>
|
||||
<Input v-model="smtpUser" placeholder="your@qq.com" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">SMTP 密码 / 授权码</Label>
|
||||
<div class="relative">
|
||||
<Input v-model="smtpPassword" type="password" placeholder="授权码" class="h-10 text-sm pr-9" />
|
||||
<KeyRound class="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-300" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">发件人地址</Label>
|
||||
<Input v-model="smtpFrom" placeholder="留空则使用 SMTP 用户名" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">发件人显示名称</Label>
|
||||
<Input v-model="smtpFromName" placeholder="小助手" class="h-10 text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">加密方式</Label>
|
||||
<select
|
||||
v-model="smtpSecure"
|
||||
class="h-10 w-full px-3 rounded-lg border border-gray-200 text-sm text-gray-700 bg-white focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400"
|
||||
>
|
||||
<option value="">自动(按端口判断)</option>
|
||||
<option value="ssl">SSL(465)</option>
|
||||
<option value="starttls">STARTTLS(587/25)</option>
|
||||
<option value="none">无加密</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">管理员通知邮箱</Label>
|
||||
<Input v-model="adminEmails" placeholder="admin@qq.com(多个用逗号分隔)" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">新待适配学校提交时提醒到此邮箱</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 pt-2">
|
||||
<Button :disabled="mailSaving" @click="handleSaveMail">
|
||||
<Save class="w-4 h-4 mr-1" />
|
||||
{{ mailSaving ? '保存中...' : '保存邮件配置' }}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
:disabled="mailTesting || mailSaving"
|
||||
@click="handleTestMail"
|
||||
class="text-blue-500"
|
||||
>
|
||||
<Send v-if="!mailTesting" class="w-4 h-4 mr-1" />
|
||||
<LoaderCircle v-else class="w-4 h-4 mr-1 animate-spin" />
|
||||
{{ mailTesting ? '发送中...' : '发送测试邮件' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -59,7 +59,7 @@ async function handleSetup() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
|
||||
<div class="min-h-dvh flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
|
||||
<div class="w-full max-w-md">
|
||||
<!-- 标题 -->
|
||||
<div class="text-center mb-8">
|
||||
|
||||
@@ -21,6 +21,10 @@ import {
|
||||
Clock,
|
||||
Calendar,
|
||||
AlertTriangle,
|
||||
Activity,
|
||||
LogIn,
|
||||
Copy,
|
||||
CheckCircle2,
|
||||
} from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -43,12 +47,25 @@ interface UserItem {
|
||||
signCount: number
|
||||
inviteReward: number
|
||||
invitedCount: number
|
||||
inviterId: number | null
|
||||
inviterName: string
|
||||
taskCount: number
|
||||
executedCount: number
|
||||
vipStatus: string
|
||||
vipExpireAt: string
|
||||
todayStatus: string
|
||||
status: string
|
||||
createdAt: string
|
||||
lastLoginAt: string
|
||||
}
|
||||
|
||||
interface TodayStats {
|
||||
executeCount: number
|
||||
successCount: number
|
||||
newUserCount: number
|
||||
loginUserCount: number
|
||||
}
|
||||
|
||||
interface UserDetail {
|
||||
id: number
|
||||
username: string
|
||||
@@ -60,6 +77,8 @@ interface UserDetail {
|
||||
signCount: number
|
||||
inviteReward: number
|
||||
invitedCount: number
|
||||
inviterId: number | null
|
||||
inviterName: string
|
||||
status: string
|
||||
disabledReason: string
|
||||
taskCount: number
|
||||
@@ -77,6 +96,7 @@ const pageSize = ref(20)
|
||||
const keyword = ref('')
|
||||
const searchKeyword = ref('')
|
||||
const showPasswordMap = ref<Record<number, boolean>>({})
|
||||
const todayStats = ref<TodayStats>({ executeCount: 0, successCount: 0, newUserCount: 0, loginUserCount: 0 })
|
||||
|
||||
// 详情弹窗
|
||||
const showDetail = ref(false)
|
||||
@@ -89,7 +109,119 @@ const disableTarget = ref<UserItem | null>(null)
|
||||
const disableReason = ref('')
|
||||
const disabling = ref(false)
|
||||
|
||||
// 当天执行日志弹窗
|
||||
interface AdminTaskLogItem {
|
||||
id: number
|
||||
userId: number
|
||||
username: string
|
||||
realName: string
|
||||
schoolName: string
|
||||
taskType: string
|
||||
title: string
|
||||
realTitle: string
|
||||
isSuccess: boolean
|
||||
errorMessage: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
const showLogsModal = ref(false)
|
||||
const logsLoading = ref(false)
|
||||
const logItems = ref<AdminTaskLogItem[]>([])
|
||||
const logsTotal = ref(0)
|
||||
const logsPage = ref(1)
|
||||
const logsPageSize = ref(20)
|
||||
const logsDate = ref(todayStr())
|
||||
const logsStatus = ref<'all' | 'success' | 'fail'>('all')
|
||||
const logsKeyword = ref('')
|
||||
const logsSearchKeyword = ref('')
|
||||
|
||||
const logsStatusOptions = [
|
||||
{ key: 'all' as const, label: '全部' },
|
||||
{ key: 'success' as const, label: '成功' },
|
||||
{ key: 'fail' as const, label: '失败' },
|
||||
]
|
||||
|
||||
const logsTotalPages = computed(() => Math.ceil(logsTotal.value / logsPageSize.value) || 1)
|
||||
|
||||
function todayStr() {
|
||||
const d = new Date()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${m}-${day}`
|
||||
}
|
||||
|
||||
function openTodayLogs() {
|
||||
logsDate.value = todayStr()
|
||||
logsStatus.value = 'all'
|
||||
logsKeyword.value = ''
|
||||
logsSearchKeyword.value = ''
|
||||
logsPage.value = 1
|
||||
showLogsModal.value = true
|
||||
loadTodayLogs()
|
||||
}
|
||||
|
||||
async function loadTodayLogs() {
|
||||
logsLoading.value = true
|
||||
try {
|
||||
const res = await adminApi.getAdminTaskLogs({
|
||||
date: logsDate.value,
|
||||
status: logsStatus.value,
|
||||
keyword: logsSearchKeyword.value,
|
||||
page: logsPage.value,
|
||||
pageSize: logsPageSize.value,
|
||||
})
|
||||
const data = res.data?.data
|
||||
logItems.value = data?.items || []
|
||||
logsTotal.value = data?.total || 0
|
||||
} catch {
|
||||
message.error('加载执行日志失败')
|
||||
logItems.value = []
|
||||
} finally {
|
||||
logsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleLogsStatusChange(val: 'all' | 'success' | 'fail') {
|
||||
if (logsStatus.value === val) return
|
||||
logsStatus.value = val
|
||||
logsPage.value = 1
|
||||
loadTodayLogs()
|
||||
}
|
||||
|
||||
function handleLogsDateChange(e: Event) {
|
||||
logsDate.value = (e.target as HTMLInputElement).value || todayStr()
|
||||
logsPage.value = 1
|
||||
loadTodayLogs()
|
||||
}
|
||||
|
||||
function handleLogsSearch() {
|
||||
logsPage.value = 1
|
||||
logsSearchKeyword.value = logsKeyword.value.trim()
|
||||
loadTodayLogs()
|
||||
}
|
||||
|
||||
function handleLogsPage(p: number) {
|
||||
if (p < 1 || p > logsTotalPages.value) return
|
||||
logsPage.value = p
|
||||
loadTodayLogs()
|
||||
}
|
||||
|
||||
function formatLogTime(iso: string) {
|
||||
if (!iso) return '--'
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return iso
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||
}
|
||||
|
||||
function taskTypeLabel(t: string) {
|
||||
if (t === 'sign') return '签到'
|
||||
if (t === 'sleep_check') return '查寝'
|
||||
return t
|
||||
}
|
||||
|
||||
const totalPages = computed(() => Math.ceil(total.value / pageSize.value) || 1)
|
||||
const pageSizeOptions = [20, 50, 100]
|
||||
|
||||
onMounted(() => {
|
||||
loadUsers()
|
||||
@@ -102,6 +234,9 @@ async function loadUsers() {
|
||||
const data = res.data?.data || {}
|
||||
users.value = data.items || []
|
||||
total.value = data.total || 0
|
||||
if (data.todayStats) {
|
||||
todayStats.value = data.todayStats
|
||||
}
|
||||
} catch {
|
||||
message.error('加载用户列表失败')
|
||||
users.value = []
|
||||
@@ -122,6 +257,13 @@ function handlePage(p: number) {
|
||||
loadUsers()
|
||||
}
|
||||
|
||||
function handlePageSize(size: number) {
|
||||
if (size === pageSize.value) return
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
loadUsers()
|
||||
}
|
||||
|
||||
async function openDetail(user: UserItem) {
|
||||
showDetail.value = true
|
||||
detailLoading.value = true
|
||||
@@ -183,8 +325,27 @@ function togglePassword(id: number) {
|
||||
showPasswordMap.value[id] = !showPasswordMap.value[id]
|
||||
}
|
||||
|
||||
function statusLabel(s: string) {
|
||||
return s === 'disabled' ? '已禁用' : '正常'
|
||||
// 设备码脱敏缩略:保留前4后4,中间打码
|
||||
function maskDeviceCode(code: string) {
|
||||
if (!code) return ''
|
||||
if (code.length <= 8) return code
|
||||
return `${code.slice(0, 4)}****${code.slice(-4)}`
|
||||
}
|
||||
|
||||
// 复制完整设备码
|
||||
async function copyDeviceCode(code: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code)
|
||||
message.success('已复制设备码')
|
||||
} catch {
|
||||
message.error('复制失败,请手动复制')
|
||||
}
|
||||
}
|
||||
|
||||
function todayStatusLabel(s: string) {
|
||||
if (s === 'success') return '已成功'
|
||||
if (s === 'fail') return '失败'
|
||||
return '未执行'
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -203,6 +364,51 @@ function statusLabel(s: string) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 当天统计卡片 -->
|
||||
<div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
|
||||
<div
|
||||
class="bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-3 cursor-pointer transition-all hover:border-blue-300 hover:shadow-md group"
|
||||
title="点击查看执行日志明细"
|
||||
@click="openTodayLogs"
|
||||
>
|
||||
<div class="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0">
|
||||
<Activity class="w-5 h-5 text-blue-600" />
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="text-xs text-gray-400">当天执行总次数</p>
|
||||
<p class="text-xl font-bold text-gray-900 leading-tight">{{ todayStats.executeCount }}</p>
|
||||
</div>
|
||||
<ChevronRight class="w-4 h-4 text-gray-300 group-hover:text-blue-400 transition-colors flex-shrink-0" />
|
||||
</div>
|
||||
<div class="bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-3">
|
||||
<div class="w-10 h-10 rounded-xl bg-green-100 flex items-center justify-center flex-shrink-0">
|
||||
<CheckCircle2 class="w-5 h-5 text-green-600" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<p class="text-xs text-gray-400">成功执行总次数</p>
|
||||
<p class="text-xl font-bold text-gray-900 leading-tight">{{ todayStats.successCount }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-3">
|
||||
<div class="w-10 h-10 rounded-xl bg-orange-100 flex items-center justify-center flex-shrink-0">
|
||||
<UserPlus class="w-5 h-5 text-orange-600" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<p class="text-xs text-gray-400">当天新增用户数</p>
|
||||
<p class="text-xl font-bold text-gray-900 leading-tight">{{ todayStats.newUserCount }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-3">
|
||||
<div class="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center flex-shrink-0">
|
||||
<LogIn class="w-5 h-5 text-purple-600" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<p class="text-xs text-gray-400">当天登录用户数</p>
|
||||
<p class="text-xl font-bold text-gray-900 leading-tight">{{ todayStats.loginUserCount }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 搜索栏 -->
|
||||
<div class="mb-4 flex gap-2">
|
||||
<div class="relative flex-1 max-w-xs">
|
||||
@@ -235,21 +441,20 @@ function statusLabel(s: string) {
|
||||
|
||||
<!-- 表格 -->
|
||||
<div v-else class="overflow-x-auto">
|
||||
<table class="w-full text-sm table-fixed min-w-[1080px]">
|
||||
<table class="w-full text-sm table-fixed min-w-[1260px]">
|
||||
<thead>
|
||||
<tr class="bg-gray-50 text-left text-xs text-gray-500">
|
||||
<th class="px-4 py-3 font-medium w-[10%]">用户名</th>
|
||||
<th class="px-4 py-3 font-medium w-[8%]">学工号</th>
|
||||
<th class="px-4 py-3 font-medium w-[6%]">真实姓名</th>
|
||||
<th class="px-4 py-3 font-medium w-[10%]">学校</th>
|
||||
<th class="px-4 py-3 font-medium w-[9%]">学工号</th>
|
||||
<th class="px-4 py-3 font-medium w-[7%]">真实姓名</th>
|
||||
<th class="px-4 py-3 font-medium w-[13%]">设备码</th>
|
||||
<th class="px-4 py-3 font-medium w-[5%]">次数</th>
|
||||
<th class="px-4 py-3 font-medium w-[7%]">邀请积分</th>
|
||||
<th class="px-4 py-3 font-medium w-[5%]">邀请人数</th>
|
||||
<th class="px-4 py-3 font-medium w-[5%]">任务数</th>
|
||||
<th class="px-4 py-3 font-medium w-[5%]">状态</th>
|
||||
<th class="px-4 py-3 font-medium w-[12%]">创建时间</th>
|
||||
<th class="px-4 py-3 font-medium text-center w-[12%]">操作</th>
|
||||
<th class="px-4 py-3 font-medium w-[10%]">设备码</th>
|
||||
<th class="px-4 py-3 font-medium w-[8%]">可执行/已执行</th>
|
||||
<th class="px-4 py-3 font-medium w-[8%]">VIP</th>
|
||||
<th class="px-4 py-3 font-medium w-[8%]">积分/邀请数</th>
|
||||
<th class="px-4 py-3 font-medium w-[7%]">邀请人</th>
|
||||
<th class="px-4 py-3 font-medium w-[8%]">今天执行状态</th>
|
||||
<th class="px-4 py-3 font-medium w-[9%]">创建时间</th>
|
||||
<th class="px-4 py-3 font-medium text-center w-[18%]">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -258,24 +463,60 @@ function statusLabel(s: string) {
|
||||
:key="user.id"
|
||||
class="border-t border-gray-50 hover:bg-gray-50/50 transition-colors"
|
||||
>
|
||||
<td class="px-4 py-3 truncate">{{ user.username }}</td>
|
||||
<td class="px-4 py-3 truncate" :title="user.schoolName">{{ user.schoolName }}</td>
|
||||
<td class="px-4 py-3 truncate font-mono text-xs">{{ user.studentId }}</td>
|
||||
<td class="px-4 py-3 truncate">{{ user.realName || '--' }}</td>
|
||||
<td class="px-4 py-3 truncate font-mono text-xs" :title="user.mobileCode || ''">
|
||||
<span v-if="user.mobileCode" class="text-gray-700">{{ user.mobileCode }}</span>
|
||||
<span v-else class="text-gray-300">未绑定</span>
|
||||
<td class="px-4 py-3 truncate text-xs text-gray-600" :title="user.schoolName">{{ user.schoolName || '--' }}</td>
|
||||
<td class="px-4 py-3 truncate font-mono text-xs">
|
||||
<div class="flex items-center gap-1.5 min-w-0">
|
||||
<span v-if="user.mobileCode" class="text-gray-700 truncate" :title="user.mobileCode">{{ maskDeviceCode(user.mobileCode) }}</span>
|
||||
<span v-else class="text-gray-300">未绑定</span>
|
||||
<button
|
||||
v-if="user.mobileCode"
|
||||
class="flex-shrink-0 text-gray-400 hover:text-blue-500 transition-colors"
|
||||
:title="'复制完整设备码'"
|
||||
@click="copyDeviceCode(user.mobileCode)"
|
||||
>
|
||||
<Copy class="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-4 py-3">
|
||||
<span class="font-medium text-gray-900">{{ user.signCount }}</span>
|
||||
<span class="text-gray-300 mx-0.5">/</span>
|
||||
<span class="text-gray-500">{{ user.executedCount }}</span>
|
||||
</td>
|
||||
<td class="px-4 py-3">
|
||||
<span
|
||||
v-if="user.vipStatus === 'active'"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-amber-100 text-amber-700"
|
||||
:title="`VIP 到期时间:${user.vipExpireAt}`"
|
||||
>
|
||||
VIP · {{ user.vipExpireAt.slice(5, 10) }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="user.vipStatus === 'expired'"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-gray-100 text-gray-400"
|
||||
:title="`VIP 已于 ${user.vipExpireAt} 过期`"
|
||||
>
|
||||
VIP · 已过期
|
||||
</span>
|
||||
<span v-else class="text-xs text-gray-300">非VIP</span>
|
||||
</td>
|
||||
<td class="px-4 py-3">
|
||||
<span class="font-medium text-gray-900">{{ user.inviteReward }}</span>
|
||||
<span class="text-gray-300 mx-0.5">/</span>
|
||||
<span class="text-gray-500">{{ user.invitedCount }}</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 truncate">
|
||||
<span v-if="user.inviterName" class="text-gray-700" :title="user.inviterName">{{ user.inviterName }}</span>
|
||||
<span v-else class="text-gray-300">--</span>
|
||||
</td>
|
||||
<td class="px-4 py-3">{{ user.signCount }}</td>
|
||||
<td class="px-4 py-3">{{ user.inviteReward }}</td>
|
||||
<td class="px-4 py-3">{{ user.invitedCount }}</td>
|
||||
<td class="px-4 py-3">{{ user.taskCount }}</td>
|
||||
<td class="px-4 py-3">
|
||||
<span
|
||||
class="text-[10px] px-1.5 py-0.5 rounded-full font-medium"
|
||||
:class="user.status === 'disabled' ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'"
|
||||
:class="user.todayStatus === 'success' ? 'bg-green-100 text-green-700' : user.todayStatus === 'fail' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-400'"
|
||||
>
|
||||
{{ statusLabel(user.status) }}
|
||||
{{ todayStatusLabel(user.todayStatus) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-xs text-gray-500">{{ user.createdAt }}</td>
|
||||
@@ -313,10 +554,19 @@ function statusLabel(s: string) {
|
||||
|
||||
<!-- 分页 -->
|
||||
<div
|
||||
v-if="total > pageSize"
|
||||
v-if="total > 0"
|
||||
class="flex items-center justify-between px-4 py-3 border-t border-gray-100"
|
||||
>
|
||||
<span class="text-xs text-gray-400">共 {{ total }} 条</span>
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-xs text-gray-400">共 {{ total }} 条</span>
|
||||
<select
|
||||
:value="pageSize"
|
||||
class="h-8 px-2 rounded-lg border border-gray-200 bg-white text-xs text-gray-500 focus:outline-none"
|
||||
@change="handlePageSize(Number(($event.target as HTMLSelectElement).value))"
|
||||
>
|
||||
<option v-for="n in pageSizeOptions" :key="n" :value="n">{{ n }} 条/页</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 disabled:opacity-30"
|
||||
@@ -420,6 +670,12 @@ function statusLabel(s: string) {
|
||||
</div>
|
||||
<p class="text-sm font-medium text-gray-900">{{ detailUser.invitedCount }} 人</p>
|
||||
</div>
|
||||
<div class="bg-gray-50 rounded-xl p-3.5">
|
||||
<div class="flex items-center gap-2 text-xs text-gray-400 mb-1">
|
||||
<UserPlus class="w-3.5 h-3.5" /> 邀请人
|
||||
</div>
|
||||
<p class="text-sm font-medium text-gray-900 truncate">{{ detailUser.inviterName || '--' }}</p>
|
||||
</div>
|
||||
<div class="bg-gray-50 rounded-xl p-3.5">
|
||||
<div class="flex items-center gap-2 text-xs text-gray-400 mb-1">
|
||||
<ClipboardCheck class="w-3.5 h-3.5" /> 任务数
|
||||
@@ -497,6 +753,151 @@ function statusLabel(s: string) {
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
|
||||
<!-- 当天执行日志弹窗 -->
|
||||
<Teleport to="body">
|
||||
<Transition name="fade">
|
||||
<div v-if="showLogsModal" class="fixed inset-0 z-50 flex items-center justify-center px-4">
|
||||
<div class="absolute inset-0 bg-black/40" @click="showLogsModal = false" />
|
||||
<div class="relative w-full sm:max-w-3xl bg-white rounded-2xl shadow-xl overflow-hidden flex flex-col max-h-[85vh]">
|
||||
<div class="h-1.5 bg-gradient-to-r from-blue-500 to-cyan-400 flex-shrink-0" />
|
||||
|
||||
<!-- 头部 -->
|
||||
<div class="px-5 pt-4 pb-3 flex items-start justify-between flex-shrink-0">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold text-gray-900">执行日志明细</h3>
|
||||
<p class="text-xs text-gray-400 mt-0.5">{{ logsDate }} · 共 {{ logsTotal }} 条记录</p>
|
||||
</div>
|
||||
<button
|
||||
class="p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors"
|
||||
@click="showLogsModal = false"
|
||||
>
|
||||
<X class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 筛选栏 -->
|
||||
<div class="px-5 pb-3 flex flex-wrap items-center gap-2 flex-shrink-0">
|
||||
<input
|
||||
type="date"
|
||||
:value="logsDate"
|
||||
class="h-9 px-2.5 rounded-lg border border-gray-200 text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400"
|
||||
@change="handleLogsDateChange"
|
||||
/>
|
||||
<div class="flex rounded-lg border border-gray-200 overflow-hidden">
|
||||
<button
|
||||
v-for="opt in logsStatusOptions"
|
||||
:key="opt.key"
|
||||
class="h-9 px-3 text-xs font-medium transition-colors"
|
||||
:class="logsStatus === opt.key ? 'bg-blue-500 text-white' : 'bg-white text-gray-500 hover:bg-gray-50'"
|
||||
@click="handleLogsStatusChange(opt.key)"
|
||||
>
|
||||
{{ opt.label }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="relative flex-1 min-w-[180px]">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
|
||||
<input
|
||||
v-model="logsKeyword"
|
||||
placeholder="搜索用户名/姓名/任务标题"
|
||||
class="w-full h-9 pl-8 pr-3 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400"
|
||||
@keyup.enter="handleLogsSearch"
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" class="h-9 text-sm" @click="handleLogsSearch">
|
||||
<Search class="w-3.5 h-3.5 mr-1" />
|
||||
搜索
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="flex-1 overflow-y-auto border-t border-gray-100">
|
||||
<!-- 加载骨架 -->
|
||||
<div v-if="logsLoading" class="p-5 space-y-3">
|
||||
<div v-for="i in 6" :key="i" class="h-10 bg-gray-50 rounded animate-pulse" />
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-else-if="logItems.length === 0" class="text-center py-16 text-gray-400">
|
||||
<ClipboardCheck class="w-10 h-10 mx-auto mb-3 opacity-30" />
|
||||
<p class="text-sm">该日期暂无执行记录</p>
|
||||
</div>
|
||||
|
||||
<!-- 日志表格 -->
|
||||
<table v-else class="w-full text-sm table-fixed min-w-[640px]">
|
||||
<thead>
|
||||
<tr class="bg-gray-50 text-left text-xs text-gray-500 sticky top-0">
|
||||
<th class="px-4 py-2.5 font-medium w-[80px]">时间</th>
|
||||
<th class="px-4 py-2.5 font-medium w-[130px]">用户</th>
|
||||
<th class="px-4 py-2.5 font-medium w-[64px]">类型</th>
|
||||
<th class="px-4 py-2.5 font-medium">任务标题</th>
|
||||
<th class="px-4 py-2.5 font-medium w-[60px]">状态</th>
|
||||
<th class="px-4 py-2.5 font-medium">说明</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="log in logItems"
|
||||
:key="log.id"
|
||||
class="border-t border-gray-50 hover:bg-gray-50/50 transition-colors align-top"
|
||||
>
|
||||
<td class="px-4 py-2.5 text-xs text-gray-500 whitespace-nowrap tabular-nums">{{ formatLogTime(log.createdAt) }}</td>
|
||||
<td class="px-4 py-2.5 truncate" :title="`${log.realName || ''}(${log.username})`">
|
||||
<p class="text-gray-900 truncate leading-tight">{{ log.realName || log.username || '--' }}</p>
|
||||
<p class="text-[11px] text-gray-400 truncate leading-tight">{{ log.schoolName || '--' }}</p>
|
||||
</td>
|
||||
<td class="px-4 py-2.5">
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-gray-100 text-gray-600">
|
||||
{{ taskTypeLabel(log.taskType) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-2.5 truncate text-gray-700" :title="log.realTitle || log.title">
|
||||
{{ log.realTitle || log.title || '--' }}
|
||||
</td>
|
||||
<td class="px-4 py-2.5 whitespace-nowrap">
|
||||
<span
|
||||
class="text-[10px] px-1.5 py-0.5 rounded-full font-medium inline-block"
|
||||
:class="log.isSuccess ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
|
||||
>
|
||||
{{ log.isSuccess ? '成功' : '失败' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-2.5">
|
||||
<span v-if="log.errorMessage" class="text-xs text-red-500 break-words">{{ log.errorMessage }}</span>
|
||||
<span v-else class="text-xs text-gray-300">--</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- 分页 -->
|
||||
<div
|
||||
v-if="logsTotal > 0"
|
||||
class="flex items-center justify-between px-5 py-3 border-t border-gray-100 flex-shrink-0"
|
||||
>
|
||||
<span class="text-xs text-gray-400">第 {{ logsPage }} / {{ logsTotalPages }} 页</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 disabled:opacity-30"
|
||||
:disabled="logsPage <= 1"
|
||||
@click="handleLogsPage(logsPage - 1)"
|
||||
>
|
||||
<ChevronLeft class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 disabled:opacity-30"
|
||||
:disabled="logsPage >= logsTotalPages"
|
||||
@click="handleLogsPage(logsPage + 1)"
|
||||
>
|
||||
<ChevronRight class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { Smartphone, RefreshCw, CheckCircle, AlertCircle, Download } from 'lucide-vue-next'
|
||||
import { Smartphone, RefreshCw, CheckCircle, AlertCircle, Download, LogOut } from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import * as authApi from '@/api/auth'
|
||||
@@ -144,6 +144,15 @@ function stopPolling() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 退出登录:清除登录态并返回登录页(未扫码时可随时退出,避免一直卡在绑定页) */
|
||||
function handleLogout() {
|
||||
stopPolling()
|
||||
if (countdownTimer) clearInterval(countdownTimer)
|
||||
localStorage.removeItem('access_token')
|
||||
localStorage.removeItem('refresh_token')
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
generateQr()
|
||||
})
|
||||
@@ -256,5 +265,16 @@ onUnmounted(() => {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部:退出登录(未扫码时可随时退出当前账号) -->
|
||||
<div class="px-6 pb-8 flex justify-center">
|
||||
<button
|
||||
class="inline-flex items-center gap-1.5 px-5 py-2 rounded-lg text-sm text-gray-500 hover:text-red-500 hover:bg-red-50 transition-colors"
|
||||
@click="handleLogout"
|
||||
>
|
||||
<LogOut class="w-4 h-4" />
|
||||
退出登录
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { Globe, Copy } from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
|
||||
const route = useRoute()
|
||||
const message = useMessage()
|
||||
|
||||
// 原始地址(含参数),在系统浏览器中打开后由路由守卫自动回到原页面
|
||||
const targetUrl = computed(() => {
|
||||
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/'
|
||||
const path = redirect.startsWith('/') ? redirect : `/${redirect}`
|
||||
return `${window.location.origin}${path}`
|
||||
})
|
||||
|
||||
function copyLink() {
|
||||
const text = targetUrl.value
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => message.success('链接已复制,请在浏览器中打开'))
|
||||
.catch(() => fallbackCopy(text))
|
||||
return
|
||||
}
|
||||
fallbackCopy(text)
|
||||
}
|
||||
|
||||
function fallbackCopy(text: string) {
|
||||
const ta = document.createElement('textarea')
|
||||
ta.value = text
|
||||
ta.style.position = 'fixed'
|
||||
ta.style.opacity = '0'
|
||||
document.body.appendChild(ta)
|
||||
ta.select()
|
||||
try {
|
||||
document.execCommand('copy')
|
||||
message.success('链接已复制,请在浏览器中打开')
|
||||
} catch {
|
||||
message.error('复制失败,请手动复制地址栏链接')
|
||||
}
|
||||
document.body.removeChild(ta)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="guide-wrap">
|
||||
<div class="guide-card">
|
||||
<!-- 右上角:模拟浏览器菜单 + 手指指向(业界通用引导样式)-->
|
||||
<div class="top-hint" aria-hidden="true">
|
||||
<div class="hand">👆</div>
|
||||
<div class="fake-menu">···</div>
|
||||
</div>
|
||||
|
||||
<div class="icon-circle">
|
||||
<Globe :size="34" :stroke-width="1.8" />
|
||||
</div>
|
||||
<h2 class="title">请在浏览器中打开</h2>
|
||||
<p class="desc">
|
||||
请点击<b>右上角 ···</b>(或 <b>⋮</b>)<br />
|
||||
选择「<b>在浏览器中打开</b>」
|
||||
</p>
|
||||
<Button class="open-btn" size="lg" @click="copyLink">
|
||||
<Copy :size="18" />
|
||||
复制链接去浏览器打开
|
||||
</Button>
|
||||
<p class="tip">如果上方按钮无效,也可以手动复制地址栏链接</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.guide-wrap {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: linear-gradient(160deg, #eef4ff 0%, #f7f9fc 60%, #eefaf3 100%);
|
||||
}
|
||||
|
||||
.guide-card {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
background: #fff;
|
||||
border-radius: 20px;
|
||||
padding: 56px 24px 32px;
|
||||
text-align: center;
|
||||
box-shadow: 0 12px 40px rgba(31, 58, 122, 0.12);
|
||||
}
|
||||
|
||||
/* 右上角菜单图标 + 手指:手指位于菜单左下方、指向右上角 */
|
||||
.top-hint {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
right: 20px;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.fake-menu {
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
background: #f3f4f6;
|
||||
border: 1.5px solid #d1d5db;
|
||||
color: #6b7280;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1px;
|
||||
line-height: 34px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.hand {
|
||||
font-size: 30px;
|
||||
line-height: 1;
|
||||
margin-right: 6px;
|
||||
margin-bottom: -2px;
|
||||
transform: rotate(38deg);
|
||||
filter: drop-shadow(0 2px 3px rgba(0, 0, 0, 0.18));
|
||||
animation: hand-tap 1.1s ease-in-out infinite;
|
||||
transform-origin: 30% 90%;
|
||||
}
|
||||
|
||||
@keyframes hand-tap {
|
||||
0%,
|
||||
100% {
|
||||
transform: rotate(38deg) translate(0, 0);
|
||||
}
|
||||
50% {
|
||||
transform: rotate(38deg) translate(5px, -5px);
|
||||
}
|
||||
}
|
||||
|
||||
.icon-circle {
|
||||
width: 68px;
|
||||
height: 68px;
|
||||
margin: 0 auto 18px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #3b82f6;
|
||||
background: #eff6ff;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 19px;
|
||||
font-weight: 600;
|
||||
color: #1f2937;
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: 14px;
|
||||
line-height: 1.8;
|
||||
color: #6b7280;
|
||||
margin: 0 0 24px;
|
||||
}
|
||||
|
||||
.desc b {
|
||||
color: #1f2937;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.open-btn {
|
||||
width: 100%;
|
||||
height: 46px;
|
||||
font-size: 15px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.tip {
|
||||
margin: 14px 0 0;
|
||||
font-size: 12.5px;
|
||||
color: #9ca3af;
|
||||
line-height: 1.6;
|
||||
}
|
||||
</style>
|
||||
@@ -58,6 +58,7 @@ const savingEdit = ref(false)
|
||||
|
||||
// ======== 执行状态 ========
|
||||
const executingId = ref<number | null>(null)
|
||||
const deletingId = ref<number | null>(null)
|
||||
const execStatus = ref('')
|
||||
const execMessage = ref('')
|
||||
|
||||
@@ -87,9 +88,19 @@ async function removeTaskLog(id: number) {
|
||||
}
|
||||
}
|
||||
|
||||
// ======== 设备码绑定状态(新建任务入口拦截用) ========
|
||||
const deviceCode = ref('')
|
||||
const showBindDeviceDialog = ref(false)
|
||||
|
||||
// ======== 初始化 ========
|
||||
onMounted(async () => {
|
||||
// MobileLayout 已加载用户信息并处理绑设备检查
|
||||
// 拉取设备码绑定状态(新建任务入口检测未绑定时弹窗引导)
|
||||
try {
|
||||
const res = await authApi.getUserInfo()
|
||||
deviceCode.value = res.data.data?.mobileCode || ''
|
||||
} catch {
|
||||
// 拉取失败不阻塞页面
|
||||
}
|
||||
// 这里直接加载任务数据和日志
|
||||
await loadTasks()
|
||||
await loadTaskLogs()
|
||||
@@ -141,6 +152,11 @@ async function loadTasks() {
|
||||
|
||||
// ======== Step 0: 选择任务标题 ========
|
||||
async function startCreateTask() {
|
||||
// 未绑定设备码:弹窗引导去个人中心绑定,不进入创建流程
|
||||
if (!deviceCode.value) {
|
||||
showBindDeviceDialog.value = true
|
||||
return
|
||||
}
|
||||
showStep.value = true
|
||||
step.value = 0
|
||||
stepTitle.value = '选择签到任务'
|
||||
@@ -500,8 +516,18 @@ function executeTask(task: authApi.TaskInfo) {
|
||||
// ======== 删除任务 ========
|
||||
async function removeTask(id: number) {
|
||||
if (!confirm('确定要删除此任务吗?')) return
|
||||
await authApi.deleteTask(id)
|
||||
await loadTasks()
|
||||
deletingId.value = id
|
||||
try {
|
||||
await authApi.deleteTask(id)
|
||||
message.success('任务已删除')
|
||||
// 删除完成后重新拉取最新任务列表
|
||||
await loadTasks()
|
||||
await loadTaskLogs()
|
||||
} catch {
|
||||
message.error('删除失败,请重试')
|
||||
} finally {
|
||||
deletingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
// ======== 工具函数 ========
|
||||
@@ -703,6 +729,7 @@ function getGPSLocation(source: string) {
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
data-guide="home-create-task"
|
||||
@click="startCreateTask"
|
||||
class="w-full flex items-center justify-center gap-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg py-2.5 text-sm font-medium transition-colors"
|
||||
>
|
||||
@@ -736,7 +763,7 @@ function getGPSLocation(source: string) {
|
||||
</div>
|
||||
|
||||
<!-- 任务列表(不显示 WID) -->
|
||||
<div class="bg-white rounded-xl border border-gray-100 p-4 shadow-sm">
|
||||
<div data-guide="home-task-list" class="bg-white rounded-xl border border-gray-100 p-4 shadow-sm">
|
||||
<h3 class="text-sm font-semibold text-gray-900 mb-3">签到任务</h3>
|
||||
|
||||
<div v-if="tasks.length > 0" class="space-y-2">
|
||||
@@ -748,8 +775,8 @@ function getGPSLocation(source: string) {
|
||||
>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-sm font-medium text-gray-900 truncate">{{ task.title }}</span>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full" :class="task.taskType === 'sleep_check' ? 'bg-purple-100 text-purple-600' : 'bg-blue-100 text-blue-600'">{{ taskTypeLabel(task.taskType) }}</span>
|
||||
<span class="text-sm font-medium text-gray-900 truncate min-w-0">{{ task.title }}</span>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full shrink-0 whitespace-nowrap" :class="task.taskType === 'sleep_check' ? 'bg-purple-100 text-purple-600' : 'bg-blue-100 text-blue-600'">{{ taskTypeLabel(task.taskType) }}</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 mt-1">
|
||||
<!-- 每任务只显示一个最相关的状态标签 -->
|
||||
@@ -790,6 +817,7 @@ function getGPSLocation(source: string) {
|
||||
<!-- 执行按钮:pending 或 fail 时可执行 -->
|
||||
<button
|
||||
v-if="task.taskStatus === 'pending' || task.taskStatus === 'fail'"
|
||||
data-guide="home-task-exec"
|
||||
@click="executeTask(task)"
|
||||
:disabled="executingId !== null"
|
||||
class="w-8 h-8 flex items-center justify-center rounded-lg bg-blue-500 hover:bg-blue-600 disabled:bg-blue-300 text-white transition-colors"
|
||||
@@ -807,15 +835,18 @@ function getGPSLocation(source: string) {
|
||||
<!-- 删除 -->
|
||||
<button
|
||||
@click="removeTask(task.id)"
|
||||
class="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-200 text-gray-400 hover:text-red-500 transition-colors"
|
||||
:disabled="deletingId !== null"
|
||||
class="w-8 h-8 flex items-center justify-center rounded-lg text-gray-400 transition-colors disabled:opacity-60 hover:bg-gray-200 hover:text-red-500"
|
||||
:title="deletingId === task.id ? '删除中…' : '删除任务'"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
<LoaderCircle v-if="deletingId === task.id" class="w-4 h-4 animate-spin" />
|
||||
<Trash2 v-else class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="flex items-center justify-center py-8">
|
||||
<div v-else data-guide="home-task-empty" class="flex items-center justify-center py-8">
|
||||
<div class="text-center">
|
||||
<ListTodo class="w-8 h-8 text-gray-200 mx-auto mb-2" />
|
||||
<p class="text-xs text-gray-400">暂无签到任务</p>
|
||||
@@ -856,7 +887,7 @@ function getGPSLocation(source: string) {
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
class="text-[10px] px-1.5 py-0.5 rounded-full shrink-0 ml-2"
|
||||
class="text-[10px] px-1.5 py-0.5 rounded-full shrink-0 whitespace-nowrap ml-2"
|
||||
:class="log.taskType === 'sleep_check' ? 'bg-purple-100 text-purple-600' : 'bg-blue-100 text-blue-600'"
|
||||
>
|
||||
{{ log.taskType === 'sleep_check' ? '查寝' : '签到' }}
|
||||
@@ -909,8 +940,8 @@ function getGPSLocation(source: string) {
|
||||
class="p-3 rounded-lg border border-gray-100 hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-colors"
|
||||
>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<p class="text-sm font-medium text-gray-900">{{ item.taskName }}</p>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full" :class="item.taskType === 'sleep_check' ? 'bg-purple-100 text-purple-600' : 'bg-blue-100 text-blue-600'">{{ taskTypeLabel(item.taskType) }}</span>
|
||||
<p class="text-sm font-medium text-gray-900 flex-1 min-w-0 truncate">{{ item.taskName }}</p>
|
||||
<span class="text-[10px] px-1.5 py-0.5 rounded-full shrink-0 whitespace-nowrap" :class="item.taskType === 'sleep_check' ? 'bg-purple-100 text-purple-600' : 'bg-blue-100 text-blue-600'">{{ taskTypeLabel(item.taskType) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="titles.length === 0 && !loadingTitles" class="text-center py-8">
|
||||
@@ -1033,9 +1064,16 @@ function getGPSLocation(source: string) {
|
||||
@click="handleImageUpload(idx, false)"
|
||||
class="cursor-pointer"
|
||||
>
|
||||
<!-- 上传中:loading 动画 -->
|
||||
<div
|
||||
v-if="uploadingImage"
|
||||
class="w-24 h-24 flex items-center justify-center border-2 border-dashed border-gray-300 rounded-lg text-blue-500"
|
||||
>
|
||||
<LoaderCircle class="w-6 h-6 animate-spin" />
|
||||
</div>
|
||||
<!-- 已有图片:显示缩略图,点击替换 -->
|
||||
<img
|
||||
v-if="item.content && (item.content.startsWith('http') || item.content.startsWith('data:image'))"
|
||||
v-else-if="item.content && (item.content.startsWith('http') || item.content.startsWith('data:image'))"
|
||||
:src="item.content"
|
||||
class="w-24 h-24 object-cover rounded-lg border border-gray-200 hover:opacity-70 transition-opacity"
|
||||
/>
|
||||
@@ -1193,8 +1231,15 @@ function getGPSLocation(source: string) {
|
||||
@click="handleImageUpload(idx, true)"
|
||||
class="cursor-pointer"
|
||||
>
|
||||
<!-- 上传中:loading 动画 -->
|
||||
<div
|
||||
v-if="uploadingImage"
|
||||
class="w-24 h-24 flex items-center justify-center border-2 border-dashed border-gray-300 rounded-lg text-blue-500"
|
||||
>
|
||||
<LoaderCircle class="w-6 h-6 animate-spin" />
|
||||
</div>
|
||||
<img
|
||||
v-if="item.content && (item.content.startsWith('http') || item.content.startsWith('data:image'))"
|
||||
v-else-if="item.content && (item.content.startsWith('http') || item.content.startsWith('data:image'))"
|
||||
:src="item.content"
|
||||
class="w-24 h-24 object-cover rounded-lg border border-gray-200 hover:opacity-70 transition-opacity"
|
||||
/>
|
||||
@@ -1265,6 +1310,38 @@ function getGPSLocation(source: string) {
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<!-- ======== 未绑定设备码弹窗(新建任务入口拦截) ======== -->
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="showBindDeviceDialog"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center"
|
||||
>
|
||||
<div class="absolute inset-0 bg-black/40" @click="showBindDeviceDialog = false" />
|
||||
<div class="relative w-[85%] sm:max-w-sm bg-white rounded-2xl shadow-xl overflow-hidden">
|
||||
<div class="p-6 text-center">
|
||||
<div class="w-14 h-14 rounded-full bg-indigo-100 flex items-center justify-center mx-auto mb-4">
|
||||
<Smartphone class="w-7 h-7 text-indigo-500" />
|
||||
</div>
|
||||
<h3 class="text-base font-semibold text-gray-900 mb-2">未绑定设备码</h3>
|
||||
<p class="text-sm text-gray-500 leading-relaxed">
|
||||
请先在个人中心绑定设备码,绑定后才能创建和执行签到任务
|
||||
</p>
|
||||
<div class="flex gap-2 mt-5">
|
||||
<Button variant="outline" class="flex-1 h-10 text-sm" @click="showBindDeviceDialog = false">
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
class="flex-1 h-10 text-sm font-medium"
|
||||
@click="showBindDeviceDialog = false; router.push('/profile')"
|
||||
>
|
||||
去绑定
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<!-- ======== 操作频繁弹窗(限流) ======== -->
|
||||
<Teleport to="body">
|
||||
<div
|
||||
|
||||
@@ -27,6 +27,7 @@ const captchaId = ref('')
|
||||
const captchaImage = ref('')
|
||||
const captchaCode = ref('')
|
||||
const loadingCaptcha = ref(false)
|
||||
const captchaError = ref('')
|
||||
|
||||
const logging = ref(false)
|
||||
|
||||
@@ -42,6 +43,7 @@ const reportCaptchaImage = ref('')
|
||||
const reportCaptchaCode = ref('')
|
||||
const reportLoadingCaptcha = ref(false)
|
||||
const reportSubmitting = ref(false)
|
||||
const reportCaptchaError = ref('')
|
||||
|
||||
// 联系邮箱:前缀 + 下拉选择国内邮箱后缀
|
||||
const reportEmailPrefix = ref('')
|
||||
@@ -112,14 +114,25 @@ function handleBlur() {
|
||||
}, 200)
|
||||
}
|
||||
|
||||
// 从 axios 错误中提取后端提示文案(429 限流/服务端错误等),失败兜底通用文案
|
||||
function captchaFailMsg(e: unknown): string {
|
||||
const err = e as { response?: { data?: { message?: string } } }
|
||||
return err?.response?.data?.message || '验证码加载失败,请点击重试'
|
||||
}
|
||||
|
||||
async function loadCaptcha() {
|
||||
loadingCaptcha.value = true
|
||||
captchaError.value = ''
|
||||
try {
|
||||
const res = await authApi.getCaptcha()
|
||||
captchaId.value = res.data?.data?.captchaId || ''
|
||||
captchaImage.value = res.data?.data?.imageBase64 || ''
|
||||
} catch {
|
||||
} catch (e) {
|
||||
captchaId.value = ''
|
||||
captchaImage.value = ''
|
||||
const msg = captchaFailMsg(e)
|
||||
captchaError.value = msg
|
||||
message.error(msg)
|
||||
} finally {
|
||||
loadingCaptcha.value = false
|
||||
}
|
||||
@@ -159,6 +172,7 @@ async function handleLogin() {
|
||||
if (data?.token?.accessToken) {
|
||||
localStorage.setItem('access_token', data.token.accessToken)
|
||||
localStorage.setItem('refresh_token', data.token.refreshToken)
|
||||
// 新手引导:由 MobileLayout 按引导版本号控制展示(新老用户统一),此处无需标记
|
||||
message.success('登录成功')
|
||||
router.replace('/home')
|
||||
} else {
|
||||
@@ -216,12 +230,17 @@ function handleSubmitTicket() {
|
||||
|
||||
async function loadReportCaptcha() {
|
||||
reportLoadingCaptcha.value = true
|
||||
reportCaptchaError.value = ''
|
||||
try {
|
||||
const res = await authApi.getCaptcha()
|
||||
reportCaptchaId.value = res.data?.data?.captchaId || ''
|
||||
reportCaptchaImage.value = res.data?.data?.imageBase64 || ''
|
||||
} catch {
|
||||
} catch (e) {
|
||||
reportCaptchaId.value = ''
|
||||
reportCaptchaImage.value = ''
|
||||
const msg = captchaFailMsg(e)
|
||||
reportCaptchaError.value = msg
|
||||
message.error(msg)
|
||||
} finally {
|
||||
reportLoadingCaptcha.value = false
|
||||
}
|
||||
@@ -380,6 +399,9 @@ async function handleReportSubmit() {
|
||||
alt="验证码"
|
||||
class="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
<div v-else-if="!loadingCaptcha && captchaError" class="w-full h-full px-1 flex items-center justify-center">
|
||||
<span class="text-[10px] leading-tight text-red-400 text-center">{{ captchaError }}</span>
|
||||
</div>
|
||||
<div v-else class="w-full h-full flex items-center justify-center">
|
||||
<RefreshCw v-if="loadingCaptcha" class="h-4 w-4 animate-spin text-gray-400" />
|
||||
<span v-else class="text-xs text-gray-400">加载中</span>
|
||||
@@ -388,13 +410,13 @@ async function handleReportSubmit() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 邀请码(仅在 URL 带 ?invite= 时展示,可编辑) -->
|
||||
<!-- 邀请码(仅在 URL 带 ?invite= 时展示,只读不可编辑) -->
|
||||
<div v-if="showInviteInput">
|
||||
<div class="flex items-center gap-1 mb-1.5">
|
||||
<Label class="text-xs font-medium text-gray-500">邀请码</Label>
|
||||
<span class="text-[10px] text-gray-400">(可编辑)</span>
|
||||
<span class="text-[10px] text-gray-400">(邀请链接自动带入,不可修改)</span>
|
||||
</div>
|
||||
<Input v-model="inviteCode" placeholder="填写邀请码可给邀请人增加奖励" class="h-10 text-sm" />
|
||||
<Input v-model="inviteCode" placeholder="填写邀请码可给邀请人增加奖励" class="h-10 text-sm" disabled />
|
||||
</div>
|
||||
|
||||
<!-- 登录按钮 -->
|
||||
@@ -449,7 +471,7 @@ async function handleReportSubmit() {
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-sm font-medium text-gray-900">忘记密码?</p>
|
||||
<p class="text-xs text-gray-500 mt-0.5">进入学校登录地址自行找回</p>
|
||||
<p class="text-xs text-gray-500 mt-0.5">点击将会打开学校官方登录地址,您可以在官方地址测试登录或者找回密码,然后回到本网站继续登录</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -563,6 +585,9 @@ async function handleReportSubmit() {
|
||||
alt="验证码"
|
||||
class="max-w-full max-h-full object-contain"
|
||||
/>
|
||||
<div v-else-if="!reportLoadingCaptcha && reportCaptchaError" class="w-full h-full px-1 flex items-center justify-center">
|
||||
<span class="text-[10px] leading-tight text-red-400 text-center">{{ reportCaptchaError }}</span>
|
||||
</div>
|
||||
<div v-else class="w-full h-full flex items-center justify-center">
|
||||
<RefreshCw v-if="reportLoadingCaptcha" class="h-4 w-4 animate-spin text-gray-400" />
|
||||
<span v-else class="text-xs text-gray-400">加载中</span>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { User, IdCard, LogOut, RefreshCw, ClipboardCheck, Gift, Share2, X, MessageSquare } from 'lucide-vue-next'
|
||||
import { User, IdCard, LogOut, RefreshCw, ClipboardCheck, Gift, Share2, X, MessageSquare, Dices, TriangleAlert } from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import * as authApi from '@/api/auth'
|
||||
import type { UserInfo } from '@/api/auth'
|
||||
import type { UserInfo, MyInviteInfo } from '@/api/auth'
|
||||
|
||||
const router = useRouter()
|
||||
const message = useMessage()
|
||||
@@ -20,6 +20,29 @@ const invitedCount = ref(0)
|
||||
const canRedeem = ref(false)
|
||||
const generatingInvite = ref(false)
|
||||
const redeemingInvite = ref(false)
|
||||
// 邀请奖励规则(来自系统配置,非写死)
|
||||
const inviterRewardPerInvite = ref<number | null>(null)
|
||||
const inviteeRewardPerInvite = ref<number | null>(null)
|
||||
|
||||
// 格式化奖励数字:整数不带小数点(3 → "3"),小数保留原样(0.5 → "0.5")
|
||||
function fmtReward(v: number | null): string {
|
||||
if (v === null) return ''
|
||||
const n = Math.round(v * 10) / 10
|
||||
return Number.isInteger(n) ? String(n) : n.toFixed(1)
|
||||
}
|
||||
|
||||
function applyInviteInfo(data: MyInviteInfo) {
|
||||
inviteCode.value = data.inviteCode
|
||||
inviteReward.value = data.inviteReward
|
||||
invitedCount.value = data.invitedCount
|
||||
canRedeem.value = data.canRedeem
|
||||
if (typeof data.inviterRewardPerInvite === 'number') {
|
||||
inviterRewardPerInvite.value = data.inviterRewardPerInvite
|
||||
}
|
||||
if (typeof data.inviteeRewardPerInvite === 'number') {
|
||||
inviteeRewardPerInvite.value = data.inviteeRewardPerInvite
|
||||
}
|
||||
}
|
||||
|
||||
// 邀请链接 URL
|
||||
const inviteUrl = computed(() => {
|
||||
@@ -33,18 +56,41 @@ const showRedeemModal = ref(false)
|
||||
const redeemCodeText = ref('')
|
||||
const redeeming = ref(false)
|
||||
const redeemError = ref('')
|
||||
// 弹窗打开来源:count=兑换次数 / vip=开通或续费VIP(仅影响标题文案)
|
||||
const redeemKind = ref<'count' | 'vip'>('count')
|
||||
// VIP 信息
|
||||
const isVip = ref(false)
|
||||
const vipExpireAt = ref('')
|
||||
// 验证码
|
||||
const captchaId = ref('')
|
||||
const captchaImage = ref('')
|
||||
const captchaCode = ref('')
|
||||
const captchaError = ref('')
|
||||
|
||||
// VIP 到期时间短格式(2026-10-08)
|
||||
const vipExpireShort = computed(() => {
|
||||
if (!vipExpireAt.value) return ''
|
||||
return vipExpireAt.value.slice(0, 10)
|
||||
})
|
||||
|
||||
// 从 axios 错误中提取后端提示文案(429 限流/服务端错误等),失败兜底通用文案
|
||||
function captchaFailMsg(e: unknown): string {
|
||||
const err = e as { response?: { data?: { message?: string } } }
|
||||
return err?.response?.data?.message || '验证码加载失败,请点击重试'
|
||||
}
|
||||
|
||||
async function refreshCaptcha() {
|
||||
captchaError.value = ''
|
||||
try {
|
||||
const res = await authApi.getCaptcha()
|
||||
captchaId.value = res.data?.data?.captchaId || ''
|
||||
captchaImage.value = res.data?.data?.imageBase64 || ''
|
||||
} catch {
|
||||
// ignore
|
||||
} catch (e) {
|
||||
captchaId.value = ''
|
||||
captchaImage.value = ''
|
||||
const msg = captchaFailMsg(e)
|
||||
captchaError.value = msg
|
||||
message.error(msg)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,16 +108,21 @@ onMounted(async () => {
|
||||
// 加载邀请信息
|
||||
try {
|
||||
const inviteRes = await authApi.getMyInviteInfo()
|
||||
inviteCode.value = inviteRes.data.data.inviteCode
|
||||
inviteReward.value = inviteRes.data.data.inviteReward
|
||||
invitedCount.value = inviteRes.data.data.invitedCount
|
||||
canRedeem.value = inviteRes.data.data.canRedeem
|
||||
applyInviteInfo(inviteRes.data.data)
|
||||
} catch {
|
||||
// invite info not yet generated
|
||||
}
|
||||
} catch {
|
||||
message.error('获取用户信息失败')
|
||||
}
|
||||
// 加载 VIP 信息
|
||||
try {
|
||||
const vipRes = await authApi.getVipInfo()
|
||||
isVip.value = vipRes.data.data.isVip
|
||||
vipExpireAt.value = vipRes.data.data.vipExpireAt
|
||||
} catch {
|
||||
// VIP 信息加载失败不阻塞页面
|
||||
}
|
||||
})
|
||||
|
||||
function handleLogout() {
|
||||
@@ -84,8 +135,43 @@ function goRebind() {
|
||||
router.push('/bind-device')
|
||||
}
|
||||
|
||||
// ---- 随机绑定设备码(连续两次风险确认) ----
|
||||
// 0=关闭 1=第一次确认 2=第二次确认
|
||||
const randBindStep = ref(0)
|
||||
const randBinding = ref(false)
|
||||
|
||||
function openRandomBind() {
|
||||
randBindStep.value = 1
|
||||
}
|
||||
|
||||
function closeRandomBind() {
|
||||
randBindStep.value = 0
|
||||
}
|
||||
|
||||
async function confirmRandomBind() {
|
||||
if (randBindStep.value === 1) {
|
||||
// 第一次确认 → 进入第二次确认
|
||||
randBindStep.value = 2
|
||||
return
|
||||
}
|
||||
randBinding.value = true
|
||||
try {
|
||||
const res = await authApi.randomBindDevice()
|
||||
if (userInfo.value) {
|
||||
userInfo.value.mobileCode = res.data.data.deviceCode
|
||||
}
|
||||
randBindStep.value = 0
|
||||
message.success('随机设备码绑定成功')
|
||||
} catch (e: any) {
|
||||
message.error(e?.response?.data?.message || e?.message || '绑定失败')
|
||||
} finally {
|
||||
randBinding.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 兑换弹窗 ----
|
||||
function openRedeemModal() {
|
||||
function openRedeemModal(kind: 'count' | 'vip' = 'count') {
|
||||
redeemKind.value = kind
|
||||
showRedeemModal.value = true
|
||||
redeemCodeText.value = ''
|
||||
redeemError.value = ''
|
||||
@@ -97,6 +183,17 @@ function closeRedeemModal() {
|
||||
showRedeemModal.value = false
|
||||
}
|
||||
|
||||
// 刷新 VIP 信息(兑换 VIP CDK 后调用)
|
||||
async function reloadVipInfo() {
|
||||
try {
|
||||
const vipRes = await authApi.getVipInfo()
|
||||
isVip.value = vipRes.data.data.isVip
|
||||
vipExpireAt.value = vipRes.data.data.vipExpireAt
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRedeem() {
|
||||
if (!redeemCodeText.value.trim()) {
|
||||
redeemError.value = '请输入兑换码'
|
||||
@@ -111,12 +208,19 @@ async function handleRedeem() {
|
||||
redeeming.value = true
|
||||
try {
|
||||
const res = await authApi.redeemCDK(redeemCodeText.value.trim(), captchaId.value, captchaCode.value.trim())
|
||||
// 一次性消耗全部剩余次数
|
||||
const totalRuns = res.data.data.totalRuns
|
||||
if (userInfo.value) {
|
||||
userInfo.value.signCount = (userInfo.value.signCount || 0) + totalRuns
|
||||
const data = res.data.data
|
||||
if (data.type === 'vip') {
|
||||
// VIP CDK:延长 VIP 到期时间
|
||||
await reloadVipInfo()
|
||||
message.success(`VIP 兑换成功!已延长至 ${data.vipExpireAt || ''}`)
|
||||
} else {
|
||||
// 次数 CDK:一次性消耗全部剩余次数
|
||||
const totalRuns = data.totalRuns ?? 0
|
||||
if (userInfo.value) {
|
||||
userInfo.value.signCount = (userInfo.value.signCount || 0) + totalRuns
|
||||
}
|
||||
message.success(`兑换成功!获得 ${totalRuns} 次签到次数`)
|
||||
}
|
||||
message.success(`兑换成功!获得 ${totalRuns} 次签到次数`)
|
||||
closeRedeemModal()
|
||||
} catch (err: any) {
|
||||
redeemError.value = err.response?.data?.message || '兑换失败'
|
||||
@@ -130,10 +234,7 @@ async function handleGenerateInvite() {
|
||||
generatingInvite.value = true
|
||||
try {
|
||||
const res = await authApi.getMyInvite()
|
||||
inviteCode.value = res.data.data.inviteCode
|
||||
inviteReward.value = res.data.data.inviteReward
|
||||
invitedCount.value = res.data.data.invitedCount
|
||||
canRedeem.value = res.data.data.canRedeem
|
||||
applyInviteInfo(res.data.data)
|
||||
} catch {
|
||||
message.error('生成邀请码失败')
|
||||
} finally {
|
||||
@@ -192,12 +293,34 @@ async function handleRedeemInvite() {
|
||||
<div class="flex flex-col min-h-full">
|
||||
<!-- 顶部大蓝色卡片:个人基础信息撑满上半部 -->
|
||||
<div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 pt-10 pb-14 text-white text-center flex-shrink-0">
|
||||
<div class="w-20 h-20 rounded-full bg-white/20 flex items-center justify-center mx-auto mb-4 overflow-hidden ring-4 ring-white/30">
|
||||
<img v-show="userInfo?.avatar && !avatarFailed" :src="userInfo?.avatar" class="w-full h-full object-cover" @error="avatarFailed = true" />
|
||||
<span v-if="!userInfo?.avatar || avatarFailed" class="text-3xl font-bold">{{ userInfo?.realName?.[0] || userInfo?.username?.[0] || '?' }}</span>
|
||||
<!-- 头像 + VIP 徽标(头像右上角,反光动画) -->
|
||||
<div class="relative w-20 h-20 rounded-full bg-white/20 flex items-center justify-center mx-auto mb-4 overflow-visible ring-4 ring-white/30">
|
||||
<div class="w-full h-full rounded-full overflow-hidden flex items-center justify-center">
|
||||
<img v-show="userInfo?.avatar && !avatarFailed" :src="userInfo?.avatar" class="w-full h-full object-cover" @error="avatarFailed = true" />
|
||||
<span v-if="!userInfo?.avatar || avatarFailed" class="text-3xl font-bold">{{ userInfo?.realName?.[0] || userInfo?.username?.[0] || '?' }}</span>
|
||||
</div>
|
||||
<div v-if="isVip" class="vip-badge absolute -right-3 -top-1.5 z-10 whitespace-nowrap">VIP</div>
|
||||
</div>
|
||||
<p class="text-xl font-bold">{{ userInfo?.realName || userInfo?.username || '--' }}</p>
|
||||
<p class="text-sm text-white/80 mt-1">{{ userInfo?.schoolName || '--' }}</p>
|
||||
|
||||
<!-- VIP 状态行:到期时间 + 开通/续费按钮 -->
|
||||
<div class="mt-3 flex items-center justify-center gap-2">
|
||||
<span
|
||||
v-if="isVip"
|
||||
class="text-xs bg-white/20 rounded-full px-3 py-1.5 text-white/95"
|
||||
>
|
||||
{{ vipExpireShort ? `VIP 至 ${vipExpireShort}` : 'VIP 会员' }}
|
||||
</span>
|
||||
<span v-else class="text-xs bg-white/20 rounded-full px-3 py-1.5 text-white/95">未开通 VIP</span>
|
||||
<button
|
||||
data-guide="profile-vip-btn"
|
||||
class="vip-btn text-xs font-semibold px-3.5 py-1.5 rounded-full text-amber-900 shadow"
|
||||
@click="openRedeemModal('vip')"
|
||||
>
|
||||
续费 VIP
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 详情列表 -->
|
||||
@@ -210,13 +333,13 @@ async function handleRedeemInvite() {
|
||||
<ClipboardCheck class="w-4 h-4 text-green-500" />
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-xs text-gray-400">可签到次数</p>
|
||||
<p class="text-sm font-medium text-gray-900">{{ (userInfo?.signCount ?? 0) }} 次</p>
|
||||
<p class="text-xs text-gray-400">{{ isVip ? 'VIP 签到次数' : '可签到次数' }}</p>
|
||||
<p class="text-sm font-medium text-gray-900">{{ isVip ? '无限次' : `${userInfo?.signCount ?? 0} 次` }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="flex items-center gap-1 px-3 py-1.5 rounded-full bg-gradient-to-r from-amber-400 to-orange-500 text-white text-xs font-medium shadow-sm hover:brightness-105 transition-all"
|
||||
@click="openRedeemModal"
|
||||
@click="openRedeemModal('count')"
|
||||
>
|
||||
<Gift class="w-3 h-3" />
|
||||
兑换
|
||||
@@ -234,16 +357,22 @@ async function handleRedeemInvite() {
|
||||
<div class="flex items-center gap-1.5">
|
||||
<code class="font-mono text-sm text-purple-600 bg-purple-50 px-2 py-1 rounded font-bold tracking-wider">{{ inviteCode }}</code>
|
||||
<button
|
||||
data-guide="profile-invite-copy"
|
||||
class="flex-shrink-0 flex items-center gap-1 px-2 py-1 rounded bg-purple-100 text-purple-600 text-xs font-medium hover:bg-purple-200 transition-colors"
|
||||
@click="copyInviteUrl"
|
||||
>
|
||||
复制
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-[10px] text-gray-400 mt-1 leading-relaxed">邀请好友可获得奖励积分,满 1 积分可兑换 1 次签到次数</p>
|
||||
<p v-if="inviterRewardPerInvite !== null" class="text-[10px] text-gray-400 mt-1 leading-relaxed">
|
||||
好友通过你的链接注册登录,你可得 <span class="text-amber-500 font-medium">{{ fmtReward(inviterRewardPerInvite) }}</span> 积分、TA 得
|
||||
<span class="text-amber-500 font-medium">{{ fmtReward(inviteeRewardPerInvite) }}</span> 积分;满 1 积分可兑换 1 次签到次数
|
||||
</p>
|
||||
<p v-else class="text-[10px] text-gray-400 mt-1 leading-relaxed">邀请好友注册可获得奖励积分,满 1 积分可兑换 1 次签到次数</p>
|
||||
</div>
|
||||
<div v-else class="mt-1">
|
||||
<button
|
||||
data-guide="profile-invite-generate"
|
||||
class="inline-flex items-center gap-1 px-2.5 py-1 rounded bg-purple-500 text-white text-xs font-medium hover:bg-purple-600 transition-colors"
|
||||
:disabled="generatingInvite"
|
||||
@click="handleGenerateInvite"
|
||||
@@ -256,7 +385,7 @@ async function handleRedeemInvite() {
|
||||
</div>
|
||||
</div>
|
||||
<!-- 邀请信息 + 兑换按钮 -->
|
||||
<div class="flex items-center justify-between px-4 py-3.5">
|
||||
<div data-guide="profile-invite-row" class="flex items-center justify-between px-4 py-3.5">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="w-8 h-8 rounded-full bg-amber-50 flex items-center justify-center">
|
||||
<Gift class="w-4 h-4 text-amber-500" />
|
||||
@@ -271,6 +400,7 @@ async function handleRedeemInvite() {
|
||||
</div>
|
||||
<button
|
||||
v-if="inviteCode"
|
||||
data-guide="profile-invite-redeem"
|
||||
class="flex items-center gap-1 px-3 py-1.5 rounded-full text-xs font-medium transition-colors"
|
||||
:class="canRedeem ? 'bg-amber-400 text-white hover:brightness-105 shadow-sm' : 'bg-gray-200 text-gray-400 cursor-not-allowed'"
|
||||
:disabled="!canRedeem || redeemingInvite"
|
||||
@@ -323,7 +453,7 @@ async function handleRedeemInvite() {
|
||||
</div>
|
||||
</div>
|
||||
<!-- 设备码 -->
|
||||
<div class="flex items-center justify-between px-4 py-3.5">
|
||||
<div data-guide="profile-device-code" class="flex items-center justify-between px-4 py-3.5">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="w-8 h-8 rounded-full bg-indigo-50 flex items-center justify-center">
|
||||
<svg class="w-4 h-4 text-indigo-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
@@ -337,13 +467,22 @@ async function handleRedeemInvite() {
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="text-xs text-blue-500 flex items-center gap-1 hover:text-blue-600"
|
||||
@click="goRebind"
|
||||
>
|
||||
<RefreshCw class="w-3 h-3" />
|
||||
重新绑定
|
||||
</button>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
class="text-xs text-amber-600 flex items-center gap-1 hover:text-amber-700"
|
||||
@click="openRandomBind"
|
||||
>
|
||||
<Dices class="w-3 h-3" />
|
||||
随机
|
||||
</button>
|
||||
<button
|
||||
class="text-xs text-blue-500 flex items-center gap-1 hover:text-blue-600"
|
||||
@click="goRebind"
|
||||
>
|
||||
<RefreshCw class="w-3 h-3" />
|
||||
重新绑定
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -368,7 +507,9 @@ async function handleRedeemInvite() {
|
||||
<div class="bg-white rounded-2xl shadow-xl w-full max-w-sm overflow-hidden">
|
||||
<!-- 弹窗头部 -->
|
||||
<div class="flex items-center justify-between px-5 pt-5 pb-2">
|
||||
<h3 class="text-base font-semibold text-gray-900">兑换签到次数</h3>
|
||||
<h3 class="text-base font-semibold text-gray-900">
|
||||
{{ redeemKind === 'vip' ? '续费 VIP' : '兑换签到次数' }}
|
||||
</h3>
|
||||
<button class="w-7 h-7 rounded-full bg-gray-100 flex items-center justify-center text-gray-400 hover:text-gray-600" @click="closeRedeemModal">
|
||||
<X class="w-4 h-4" />
|
||||
</button>
|
||||
@@ -378,7 +519,7 @@ async function handleRedeemInvite() {
|
||||
<div class="px-5 pb-5 space-y-4">
|
||||
<!-- 兑换码输入 -->
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-500 mb-1.5">兑换码</label>
|
||||
<label class="block text-xs font-medium text-gray-500 mb-1.5">{{ redeemKind === 'vip' ? 'VIP 兑换码' : '兑换码' }}</label>
|
||||
<Input
|
||||
v-model="redeemCodeText"
|
||||
placeholder="请输入 CDK 兑换码"
|
||||
@@ -404,6 +545,14 @@ async function handleRedeemInvite() {
|
||||
@click="refreshCaptcha"
|
||||
title="点击刷新验证码"
|
||||
/>
|
||||
<div
|
||||
v-else-if="captchaError"
|
||||
class="h-10 w-24 rounded-lg border border-red-200 bg-red-50 flex items-center justify-center text-[10px] leading-tight text-red-400 text-center px-1 cursor-pointer"
|
||||
title="点击重试"
|
||||
@click="refreshCaptcha"
|
||||
>
|
||||
{{ captchaError }}
|
||||
</div>
|
||||
<div v-else class="h-10 w-24 rounded-lg border border-gray-200 bg-gray-50 flex items-center justify-center text-xs text-gray-400">
|
||||
加载中
|
||||
</div>
|
||||
@@ -425,6 +574,66 @@ async function handleRedeemInvite() {
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
|
||||
<!-- 随机绑定设备码:连续两次风险确认弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="randBindStep > 0" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4" @click.self="closeRandomBind">
|
||||
<div class="bg-white rounded-2xl shadow-xl w-full max-w-sm overflow-hidden">
|
||||
<!-- 第一次确认 -->
|
||||
<template v-if="randBindStep === 1">
|
||||
<div class="px-5 pt-5 pb-2 flex items-center justify-between">
|
||||
<h3 class="text-base font-semibold text-gray-900">随机生成设备码</h3>
|
||||
<button class="w-7 h-7 rounded-full bg-gray-100 flex items-center justify-center text-gray-400 hover:text-gray-600" @click="closeRandomBind">
|
||||
<X class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="px-5 pb-5">
|
||||
<div class="flex items-start gap-2.5 bg-amber-50 border border-amber-200 rounded-lg p-3">
|
||||
<TriangleAlert class="w-4 h-4 text-amber-500 flex-shrink-0 mt-0.5" />
|
||||
<p class="text-xs text-amber-700 leading-relaxed">
|
||||
随机设备码与你真实手机不一致。若你已有绑定的手机在用本系统,随机后该手机执行签到时会出现
|
||||
<strong>「频繁切换设备」提示,无法正常签到</strong>。
|
||||
</p>
|
||||
</div>
|
||||
<p class="text-xs text-gray-400 mt-3">仅建议目前依旧因为其他人帮忙打卡/其他设备打卡导致已经出现「频繁切换设备」提示的用户使用。</p>
|
||||
<div class="flex gap-2 mt-4">
|
||||
<Button variant="outline" class="flex-1 h-10 text-sm" @click="closeRandomBind">取消</Button>
|
||||
<Button class="flex-1 h-10 text-sm font-medium" @click="confirmRandomBind">继续</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 第二次确认 -->
|
||||
<template v-else>
|
||||
<div class="px-5 pt-5 pb-2 flex items-center justify-between">
|
||||
<h3 class="text-base font-semibold text-red-600">再次确认:确定随机?</h3>
|
||||
<button class="w-7 h-7 rounded-full bg-gray-100 flex items-center justify-center text-gray-400 hover:text-gray-600" @click="closeRandomBind">
|
||||
<X class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="px-5 pb-5">
|
||||
<p class="text-sm text-gray-600 leading-relaxed">
|
||||
随机后,你现有手机登录 App 执行签到时将提示
|
||||
<strong class="text-red-500">「频繁切换设备」而无法正常签到</strong>,
|
||||
需要重新扫码授权绑定才能恢复。
|
||||
</p>
|
||||
<p class="text-xs text-gray-400 mt-2">这是最后一次确认,确定要随机生成设备码吗?</p>
|
||||
<div class="flex gap-2 mt-4">
|
||||
<Button variant="outline" class="flex-1 h-10 text-sm" @click="closeRandomBind">取消</Button>
|
||||
<Button
|
||||
class="flex-1 h-10 text-sm font-medium bg-red-500 hover:bg-red-600"
|
||||
:disabled="randBinding"
|
||||
@click="confirmRandomBind"
|
||||
>
|
||||
<RefreshCw v-if="randBinding" class="h-4 w-4 animate-spin" />
|
||||
{{ randBinding ? '绑定中...' : '确定随机' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -437,4 +646,72 @@ async function handleRedeemInvite() {
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* VIP 徽标:金色渐变 + 反光条扫过动画
|
||||
注意:不可设置 position,徽标由模板上的 Tailwind absolute 类控制浮层定位,
|
||||
若此处声明 position:relative 会覆盖 absolute,导致徽标挤进头像布局使其变形 */
|
||||
.vip-badge {
|
||||
overflow: hidden;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
font-style: italic;
|
||||
letter-spacing: 0.5px;
|
||||
color: #5b3a00;
|
||||
background: linear-gradient(135deg, #ffe9a8 0%, #f6c445 45%, #e8a020 100%);
|
||||
border: 1px solid rgba(255, 255, 255, 0.65);
|
||||
box-shadow: 0 2px 6px rgba(160, 100, 0, 0.35);
|
||||
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
.vip-badge::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -60%;
|
||||
left: -45%;
|
||||
width: 38%;
|
||||
height: 220%;
|
||||
background: linear-gradient(
|
||||
100deg,
|
||||
transparent 0%,
|
||||
rgba(255, 255, 255, 0.85) 50%,
|
||||
transparent 100%
|
||||
);
|
||||
transform: rotate(18deg);
|
||||
animation: vip-shine 2.4s ease-in-out infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
@keyframes vip-shine {
|
||||
0% {
|
||||
left: -45%;
|
||||
}
|
||||
55%,
|
||||
100% {
|
||||
left: 135%;
|
||||
}
|
||||
}
|
||||
|
||||
/* VIP 开通/续费按钮:金色渐变 + 周期性微光扫过 */
|
||||
.vip-btn {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(135deg, #ffe9a8 0%, #f6c445 45%, #e8a020 100%);
|
||||
}
|
||||
.vip-btn::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -60%;
|
||||
left: -45%;
|
||||
width: 30%;
|
||||
height: 220%;
|
||||
background: linear-gradient(
|
||||
100deg,
|
||||
transparent 0%,
|
||||
rgba(255, 255, 255, 0.7) 50%,
|
||||
transparent 100%
|
||||
);
|
||||
transform: rotate(18deg);
|
||||
animation: vip-shine 3s ease-in-out infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user