Compare commits
91 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7f81d54ea2 | |||
| a802912a55 | |||
| 9074118889 | |||
| 176c43251c | |||
| 839637b3d3 | |||
| 5ee8e47b0f | |||
| af24472e2a | |||
| 518f3506df | |||
| 21b37c6ad8 | |||
| a7180eebba | |||
| 386c6e2bf8 | |||
| 2dd1180bf8 | |||
| a0064881b3 | |||
| 4ca952f2ac | |||
| edeabb0fc0 | |||
| 559b146408 | |||
| d8f2c3676c | |||
| cd963d3834 | |||
| c5e0888639 | |||
| 3bcc32b74e | |||
| 8de7470b9d | |||
| c90784de67 | |||
| 186af6b604 | |||
| a3ec85f4d3 | |||
| ee466b253d | |||
| 2effdbaaf9 | |||
| e979e3cc9f | |||
| 4ec3e55030 | |||
| 0bd354cfee | |||
| 6e145f75e1 | |||
| 879628d0eb | |||
| 8435095b4f | |||
| 200edd75bb | |||
| b39f57b879 | |||
| f20a6b57c1 | |||
| 55eff6e80a | |||
| b436781d7d | |||
| ac743eda88 | |||
| 53cbedeb95 | |||
| 42d3b332a5 | |||
| 021ac7f7bd | |||
| b75e1f9bd9 | |||
| c41176af8d | |||
| 26c5115a32 | |||
| 7639912d7c | |||
| 2f20eebccd | |||
| 3aee45be80 | |||
| 46c8a554ff | |||
| 1507b386bc | |||
| 1a15b359f8 | |||
| f23ab1a261 | |||
| 84a602ae3b | |||
| 35a2f1e432 | |||
| 98689f68f4 | |||
| 3632cb642e | |||
| 47401e7388 | |||
| c5fe95b3ec | |||
| 0f49e7b1da | |||
| 95988c3ca9 | |||
| edd2b248e2 | |||
| 985748a3d3 | |||
| c0ea9ecd8f | |||
| e7e106c606 | |||
| 240e1226ef | |||
| 643e706335 | |||
| 61a8d2b3fb | |||
| 6532025cc0 | |||
| 7a4507903f | |||
| a95c843bf7 | |||
| 764bae23fc | |||
| 1f4d601ffa | |||
| 5de7852786 | |||
| 98631afdc5 | |||
| bc4e739e09 | |||
| 9bffdb7026 | |||
| 42c8b66a01 | |||
| 81b2942cad | |||
| 4b1dea3d3c | |||
| 0d665ad0fe | |||
| 67d925bb91 | |||
| bf0e1656ab | |||
| 66d07781be | |||
| 99c16652a7 | |||
| cc4aa1c00e | |||
| 15eceea38a | |||
| a9dbc2661d | |||
| ebc94ec9a0 | |||
| 98cf8666f6 | |||
| ff3593f057 | |||
| 74422b1848 | |||
| 84f87cd168 |
+117
-83
@@ -26,55 +26,70 @@ steps:
|
||||
|
||||
IMAGE_TAG="${CI_COMMIT_TAG:-latest}"
|
||||
|
||||
# 确保网络存在
|
||||
docker network create likedream-net 2>/dev/null || true
|
||||
|
||||
# ============================================================
|
||||
# 第一步:初始化 1Panel 站点配置(首次部署时才需要)
|
||||
# ============================================================
|
||||
# nginx 配置文件在 git clone 后位于 deploy/nginx/ 目录
|
||||
# 应用配置由宿主机 /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
|
||||
# 两个固定槽位(蓝/绿),任一时刻都保持"两个容器都活着":
|
||||
# 活跃槽 = 反代当前指向的端口;备用槽 = 另一个端口(上一版,供秒级回滚)
|
||||
SLOT_BLUE=8884
|
||||
SLOT_GREEN=8885
|
||||
|
||||
# ============================================================
|
||||
# 第二步:读取当前代理端口,确定蓝绿状态
|
||||
# 第一步:读取当前反代指向的端口,确定活跃/备用槽
|
||||
# 反代入口为 1Panel 站点 jinrixiaoyuan.top(frps 公网链路):
|
||||
# /www/sites/jinrixiaoyuan.top/proxy/root.conf → proxy_pass http://127.0.0.1:8884|8885
|
||||
# 该文件经 conf.d/jinrixiaoyuan.top.conf 的 include /www/sites/.../proxy/*.conf 载入。
|
||||
# ============================================================
|
||||
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
|
||||
PORT_STANDBY=8885
|
||||
elif [ "$CURRENT_PORT" = "8885" ]; then
|
||||
PORT_ACTIVE=8885
|
||||
PORT_STANDBY=8884
|
||||
if [ "$CURRENT_PORT" = "$SLOT_BLUE" ]; then
|
||||
PORT_ACTIVE=$SLOT_BLUE
|
||||
PORT_STANDBY=$SLOT_GREEN
|
||||
elif [ "$CURRENT_PORT" = "$SLOT_GREEN" ]; then
|
||||
PORT_ACTIVE=$SLOT_GREEN
|
||||
PORT_STANDBY=$SLOT_BLUE
|
||||
else
|
||||
echo "未知当前端口 $CURRENT_PORT,默认使用 8884/8885"
|
||||
PORT_ACTIVE=8884
|
||||
PORT_STANDBY=8885
|
||||
echo "ERROR: 未知反代端口 $CURRENT_PORT,中止部署(期望 $SLOT_BLUE/$SLOT_GREEN)"
|
||||
exit 1
|
||||
fi
|
||||
echo " 活跃: $PORT_ACTIVE | 备用: $PORT_STANDBY"
|
||||
|
||||
# 清理之前可能残留的临时容器
|
||||
docker rm -f cpdaily-xiaozhushou-new 2>/dev/null || true
|
||||
echo " 活跃槽: $PORT_ACTIVE | 备用槽: $PORT_STANDBY"
|
||||
echo " 目标: 更新备用槽 :$PORT_STANDBY 到 $IMAGE_TAG 后,切换反代指向它(活跃槽保留,可回滚)"
|
||||
|
||||
# ============================================================
|
||||
# 第三步:在备用端口启动新容器
|
||||
# 第一步附:一次性「收养」旧命名容器
|
||||
# 迁移前的容器名为 cpdaily-xiaozhushou(无端口后缀),本脚本改用
|
||||
# cpdaily-xiaozhushou-<端口>。若不改名,下次部署 rm -f 找不到它 → 端口
|
||||
# 被占用导致 docker run 冲突、部署失败。此处按它实际映射的端口改名(幂等)。
|
||||
# 同时清理历史遗留的 cpdaily-blue 陈尸容器。
|
||||
# ============================================================
|
||||
echo "=== 蓝绿部署: 启动新容器 on :$PORT_STANDBY (image: $IMAGE_TAG) ==="
|
||||
LEGACY_NAME=cpdaily-xiaozhushou
|
||||
if docker inspect "$LEGACY_NAME" >/dev/null 2>&1; then
|
||||
LEGACY_PORT=$(docker port "$LEGACY_NAME" 8093 2>/dev/null | head -1 | grep -oE '[0-9]+$' || true)
|
||||
if [ -n "$LEGACY_PORT" ]; then
|
||||
if docker inspect "cpdaily-xiaozhushou-$LEGACY_PORT" >/dev/null 2>&1; then
|
||||
echo " 发现旧命名容器,但 cpdaily-xiaozhushou-$LEGACY_PORT 已存在,移除旧容器"
|
||||
docker rm -f "$LEGACY_NAME" || true
|
||||
else
|
||||
echo " 收养旧命名容器: $LEGACY_NAME → cpdaily-xiaozhushou-$LEGACY_PORT"
|
||||
docker rename "$LEGACY_NAME" "cpdaily-xiaozhushou-$LEGACY_PORT"
|
||||
fi
|
||||
else
|
||||
echo " 旧命名容器未映射 8093 端口,跳过收养"
|
||||
fi
|
||||
fi
|
||||
docker rm -f cpdaily-blue 2>/dev/null || true
|
||||
|
||||
docker run -d --name cpdaily-xiaozhushou-new \
|
||||
# ============================================================
|
||||
# 第二步:更新「备用槽」容器(此槽当前无流量,停它不会影响线上)
|
||||
# ============================================================
|
||||
echo "=== 停止并移除备用槽旧容器(:$PORT_STANDBY)==="
|
||||
docker rm -f cpdaily-xiaozhushou-$PORT_STANDBY 2>/dev/null || true
|
||||
|
||||
echo "=== 在备用槽启动新容器 :$PORT_STANDBY (image: $IMAGE_TAG) ==="
|
||||
docker run -d --name cpdaily-xiaozhushou-$PORT_STANDBY \
|
||||
--restart unless-stopped \
|
||||
--network likedream-net \
|
||||
-e TZ=Asia/Shanghai \
|
||||
@@ -83,73 +98,92 @@ steps:
|
||||
cpdaily-xiaozhushou:$IMAGE_TAG
|
||||
|
||||
# ============================================================
|
||||
# 第四步:健康检查
|
||||
# 第三步:健康检查(新容器必须就绪,否则直接失败且不动反代)
|
||||
# 用 docker exec 在容器内自测,避免依赖宿主机到容器的网络路径。
|
||||
# ============================================================
|
||||
HEALTHY=false
|
||||
for i in $(seq 1 15); do
|
||||
if wget -q --timeout=3 -O /dev/null http://10.10.10.128:$PORT_STANDBY/health 2>/dev/null; then
|
||||
for i in $(seq 1 30); do
|
||||
if docker exec cpdaily-xiaozhushou-$PORT_STANDBY \
|
||||
wget -q --timeout=3 -O /dev/null http://127.0.0.1:8093/health 2>/dev/null; then
|
||||
HEALTHY=true
|
||||
break
|
||||
fi
|
||||
echo " 等待新容器就绪... ($i/15)"
|
||||
echo " 等待新容器就绪... ($i/30)"
|
||||
sleep 2
|
||||
done
|
||||
|
||||
if [ "$HEALTHY" = false ]; then
|
||||
echo "ERROR: 新容器未通过健康检查,回滚"
|
||||
docker stop cpdaily-xiaozhushou-new
|
||||
docker rm cpdaily-xiaozhushou-new
|
||||
echo "ERROR: 新容器未通过健康检查,中止部署(线上仍由活跃槽 :$PORT_ACTIVE 提供服务,未受影响)"
|
||||
docker rm -f cpdaily-xiaozhushou-$PORT_STANDBY 2>/dev/null || true
|
||||
exit 1
|
||||
fi
|
||||
echo " 新容器已就绪 ✓"
|
||||
|
||||
# ============================================================
|
||||
# 第五步:切换 1Panel 代理到备用端口
|
||||
# 第四步:切换 1Panel 反代到备用槽(唯一一次代理切换)
|
||||
# 切换前先备份配置,nginx -t 通过后再 reload;reload 后等待旧 worker 退出,
|
||||
# 确保旧连接不再按旧配置转发。
|
||||
# ============================================================
|
||||
echo "=== 切换 1Panel 反代 :$PORT_ACTIVE → :$PORT_STANDBY ==="
|
||||
PROXY_CONF=/www/sites/jinrixiaoyuan.top/proxy/root.conf
|
||||
docker exec 1Panel-openresty-ESmn \
|
||||
sed -i "s|:$PORT_ACTIVE|:$PORT_STANDBY|g" \
|
||||
/www/sites/xiaozhushou/proxy/api.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 代理到活跃端口
|
||||
# ============================================================
|
||||
echo "=== 切回 1Panel 反代 :$PORT_STANDBY → :$PORT_ACTIVE ==="
|
||||
cp $PROXY_CONF $PROXY_CONF.bak
|
||||
docker exec 1Panel-openresty-ESmn \
|
||||
sed -i "s|:$PORT_STANDBY|:$PORT_ACTIVE|g" \
|
||||
/www/sites/xiaozhushou/proxy/api.conf
|
||||
docker exec 1Panel-openresty-ESmn nginx -s reload
|
||||
echo " Nginx 热加载完成(零中断)✓"
|
||||
sed -i "s|:$PORT_ACTIVE|:$PORT_STANDBY|g" $PROXY_CONF
|
||||
|
||||
# ============================================================
|
||||
# 第九步:清理
|
||||
# ============================================================
|
||||
echo "=== 清理 ==="
|
||||
docker rm -f cpdaily-xiaozhushou-new 2>/dev/null || true
|
||||
docker images cpdaily-xiaozhushou --format '{{.Tag}}' | grep -v latest | head -n -3 | while read tag; do
|
||||
docker rmi cpdaily-xiaozhushou:$tag 2>/dev/null || true
|
||||
if ! docker exec 1Panel-openresty-ESmn nginx -t 2>&1; then
|
||||
echo "ERROR: nginx 配置校验失败,回滚反代配置"
|
||||
docker exec 1Panel-openresty-ESmn cp $PROXY_CONF.bak $PROXY_CONF
|
||||
docker rm -f cpdaily-xiaozhushou-$PORT_STANDBY 2>/dev/null || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 记录 reload 前的 worker pid,reload 后等其全部退出,避免旧 worker 按旧配置继续转发
|
||||
OLD_WORKERS=$(docker exec 1Panel-openresty-ESmn \
|
||||
sh -c 'ps -eo pid,cmd | grep "[n]ginx: worker" | awk "{print \$1}"' | tr '\n' ' ')
|
||||
docker exec 1Panel-openresty-ESmn nginx -s reload
|
||||
echo " Nginx 热加载完成,等待旧 worker 退出..."
|
||||
|
||||
for i in $(seq 1 15); do
|
||||
STILL=0
|
||||
for p in $OLD_WORKERS; do
|
||||
if docker exec 1Panel-openresty-ESmn sh -c "[ -d /proc/$p ]" 2>/dev/null; then
|
||||
STILL=$((STILL + 1))
|
||||
fi
|
||||
done
|
||||
if [ "$STILL" = "0" ]; then
|
||||
echo " 旧 worker 已全部退出 ✓"
|
||||
break
|
||||
fi
|
||||
echo " 等待旧 worker 释放连接... ($i/15, 剩余 $STILL)"
|
||||
sleep 2
|
||||
done
|
||||
echo "=== 部署完成 ✓ ==="
|
||||
echo " 反代已指向 :$PORT_STANDBY ✓"
|
||||
|
||||
# ============================================================
|
||||
# 第五步:验证线上确实由新槽服务
|
||||
# ============================================================
|
||||
if ! docker exec 1Panel-openresty-ESmn \
|
||||
sh -c "wget -q --timeout=5 -O /dev/null http://127.0.0.1:$PORT_STANDBY/health" 2>/dev/null; then
|
||||
echo "WARN: 新槽健康检查异常,但反代已切换,请人工核查"
|
||||
else
|
||||
echo " 线上验证通过(:$PORT_STANDBY 正常服务)✓"
|
||||
fi
|
||||
|
||||
# ============================================================
|
||||
# 第六步:保留活跃槽用于回滚说明;清理多余历史镜像
|
||||
# 注:旧槽容器不删除 —— 它即上一版本,仍需回滚时可直接把反代切回。
|
||||
# 下次部署时旧槽会被当作「备用槽」重建,因此不会无限堆积。
|
||||
# ============================================================
|
||||
echo "=== 当前容器 ==="
|
||||
docker ps --filter "name=cpdaily-xiaozhushou-" --format '{{.Names}} → {{.Ports}} ({{.Status}})'
|
||||
|
||||
echo "=== 清理历史镜像(保留 latest 与最近 2 个版本)==="
|
||||
docker images cpdaily-xiaozhushou --format '{{.Tag}}' \
|
||||
| grep -v '^latest$' | head -n -2 | while read tag; do
|
||||
docker rmi cpdaily-xiaozhushou:$tag 2>/dev/null || true
|
||||
done
|
||||
|
||||
echo "=== 部署完成 ✓ 活跃槽 :$PORT_STANDBY(旧槽 :$PORT_ACTIVE 保留,可回滚)==="
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/config"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"cpdaily-new/internal/service"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/compress"
|
||||
"github.com/gofiber/fiber/v2/middleware/filesystem"
|
||||
)
|
||||
|
||||
@@ -45,9 +47,9 @@ func main() {
|
||||
// 创建 Fiber 应用
|
||||
app := fiber.New(fiber.Config{
|
||||
AppName: "Cpdaily New",
|
||||
// 信任 openresty 反代(host 网络,经 docker NAT 后源 IP 为 172.22.0.1),
|
||||
// 从 X-Forwarded-For 取真实客户端 IP(如待适配学校提交记录)
|
||||
TrustedProxies: []string{"172.22.0.0/16"},
|
||||
// 信任 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,
|
||||
})
|
||||
@@ -55,6 +57,18 @@ func main() {
|
||||
// 中间件
|
||||
app.Use(middleware.CORS())
|
||||
|
||||
// gzip 压缩:nginx 侧 gzip_types 未覆盖 application/json,接口返回的 JSON
|
||||
// (历史上曾出现单次 2.9MB 的任务列表)会明文传输。在此按内容协商压缩,
|
||||
// 随镜像走版本控制、只影响本服务。
|
||||
// 必须排除 SSE 端点(/api/task/execute/*):它用 SetBodyStreamWriter 流式推送,
|
||||
// 压缩会缓冲响应导致事件无法即时到达。
|
||||
app.Use(compress.New(compress.Config{
|
||||
Level: compress.LevelBestSpeed, // 纯 CPU 敏感场景,优先速度
|
||||
Next: func(c *fiber.Ctx) bool {
|
||||
return strings.HasPrefix(c.Path(), "/api/task/execute/")
|
||||
},
|
||||
}))
|
||||
|
||||
// 路由
|
||||
api := app.Group("/api")
|
||||
|
||||
@@ -63,6 +77,11 @@ func main() {
|
||||
auth.Get("/captcha", handler.GetCaptcha)
|
||||
auth.Get("/schools", handler.SearchSchools)
|
||||
auth.Post("/login", handler.Login)
|
||||
// 手机号验证码登录(无需选择学校:tenantId 由登录响应返回)
|
||||
auth.Post("/sms/send", handler.SmsSend)
|
||||
auth.Post("/sms/login", handler.SmsLogin)
|
||||
auth.Post("/login/mfa", handler.MFAVerify)
|
||||
auth.Post("/login/mfa/send", handler.MFASendCode)
|
||||
auth.Post("/refresh", handler.RefreshToken)
|
||||
auth.Get("/userinfo", middleware.AuthRequired(), handler.GetUserInfo)
|
||||
auth.Post("/generate-invite", middleware.AuthRequired(), handler.GenerateMyInviteCode)
|
||||
@@ -78,6 +97,7 @@ func main() {
|
||||
task.Get("/form/:id", handler.GetTaskForm)
|
||||
task.Post("/form/:id", handler.SaveTaskForm)
|
||||
task.Put("/form/:id", handler.SaveTaskForm)
|
||||
task.Get("/form-data/:id", handler.GetTaskSavedForm)
|
||||
task.Put("/update/:id", handler.UpdateTask)
|
||||
task.Delete("/delete/:id", handler.DeleteTask)
|
||||
task.Get("/execute/:id", handler.ExecuteTask)
|
||||
@@ -86,6 +106,19 @@ func main() {
|
||||
task.Post("/upload-policy", handler.GetUploadPolicy)
|
||||
task.Post("/preview-url", handler.GetPreviewUrl)
|
||||
|
||||
// 销假(请假销假)
|
||||
leave := api.Group("/leave", middleware.AuthRequired())
|
||||
leave.Get("/pending-list", handler.GetPendingLeaves)
|
||||
leave.Post("/approvers", handler.GetLeaveApprovers)
|
||||
leave.Post("/execute", handler.ExecuteLeave)
|
||||
leave.Get("/logs", handler.ListLeaveLogs)
|
||||
leave.Delete("/logs/:id", handler.DeleteLeaveLog)
|
||||
// 请假申请(同模块)
|
||||
leave.Get("/types", handler.GetLeaveTypes)
|
||||
leave.Post("/apply-approvers", handler.GetLeaveApplyApprovers)
|
||||
leave.Post("/cc-search", handler.GetLeaveNewCcSearch)
|
||||
leave.Post("/apply", handler.ExecuteLeaveApply)
|
||||
|
||||
// CDK 兑换
|
||||
cdk := api.Group("/cdk", middleware.AuthRequired())
|
||||
cdk.Post("/redeem", handler.UserRedeemCDK)
|
||||
@@ -96,6 +129,7 @@ func main() {
|
||||
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")
|
||||
@@ -124,6 +158,8 @@ func main() {
|
||||
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)
|
||||
|
||||
// 管理后台 - 公告(公告面向全站代理/用户推送,管理操作仅超管;代理/管理员通过 /my-announcements 收取公告)
|
||||
adminAuth.Post("/announcements", middleware.AdminOnly(), handler.CreateAnnouncement)
|
||||
@@ -142,12 +178,14 @@ func main() {
|
||||
adminAuth.Get("/my-announcements", handler.ListUserAnnouncements)
|
||||
adminAuth.Get("/my-announcements/unread-count", handler.GetUnreadCount)
|
||||
adminAuth.Get("/my-announcements/my-info", handler.GetMyAnnouncementInfo)
|
||||
adminAuth.Get("/my-announcements/pinned", handler.ListPinnedAnnouncements)
|
||||
adminAuth.Post("/my-announcements/:id/read", handler.MarkAnnouncementRead)
|
||||
|
||||
// 用户公告
|
||||
api.Get("/announcements", middleware.AuthRequired(), handler.ListUserAnnouncements)
|
||||
api.Get("/announcements/unread-count", middleware.AuthRequired(), handler.GetUnreadCount)
|
||||
api.Get("/announcements/my-info", middleware.AuthRequired(), handler.GetMyAnnouncementInfo)
|
||||
api.Get("/announcements/pinned", middleware.AuthRequired(), handler.ListPinnedAnnouncements)
|
||||
api.Post("/announcements/:id/read", middleware.AuthRequired(), handler.MarkAnnouncementRead)
|
||||
|
||||
// 设备授权页面(纯 HTML)
|
||||
@@ -179,6 +217,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 {
|
||||
|
||||
@@ -19,6 +19,8 @@ dbname = "xiaozhushou"
|
||||
secret = "dev-only-change-me-please"
|
||||
accessExpire = 3600
|
||||
refreshExpire = 864000
|
||||
# MFA 通道登录短期 token 有效期(秒):与第三方 Cookie 对齐,默认 7200(2 小时)
|
||||
mfaAccessExpire = 7200
|
||||
|
||||
[captcha]
|
||||
width = 150
|
||||
@@ -29,7 +31,7 @@ length = 4
|
||||
appVersion = "9.8.8"
|
||||
systemVersion = "iOS 17"
|
||||
calVersion = "first_v4"
|
||||
sliderIds = ["1018764144934965", "sdhyxy", "hqdx"]
|
||||
sliderIds = ["1018764144934965", "sdhyxy", "hqdx", "lntu"]
|
||||
captchaBaseUrl = "http://127.0.0.1:8890"
|
||||
captchaApiKey = "your_captcha_api_key"
|
||||
|
||||
|
||||
+5
-6
@@ -6,11 +6,11 @@ require (
|
||||
github.com/BurntSushi/toml v1.6.0
|
||||
github.com/PuerkitoBio/goquery v1.12.0
|
||||
github.com/go-resty/resty/v2 v2.16.5
|
||||
github.com/go-sql-driver/mysql v1.8.1
|
||||
github.com/gofiber/fiber/v2 v2.52.13
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/redis/go-redis/v9 v9.7.0
|
||||
golang.org/x/crypto v0.50.0
|
||||
golang.org/x/time v0.6.0
|
||||
golang.org/x/image v0.46.0
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
gorm.io/gorm v1.31.2
|
||||
)
|
||||
@@ -21,6 +21,7 @@ require (
|
||||
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/go-sql-driver/mysql v1.8.1 // 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
|
||||
@@ -28,13 +29,11 @@ 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
|
||||
github.com/valyala/fasthttp v1.51.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
|
||||
+15
-6
@@ -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/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
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=
|
||||
@@ -36,12 +40,12 @@ 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/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
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=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
|
||||
@@ -57,6 +61,8 @@ golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
|
||||
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
@@ -93,8 +99,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -113,8 +119,9 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/time v0.6.0 h1:eTDhh4ZXt5Qf0augr54TN6suAUudPcawVZeIAPU7D4U=
|
||||
golang.org/x/time v0.6.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
@@ -125,5 +132,7 @@ golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxb
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
|
||||
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// Package assets 嵌入静态资源(go:embed 不支持 .. 相对路径,统一放本包供各处引用)。
|
||||
package assets
|
||||
|
||||
import _ "embed"
|
||||
|
||||
// SourGummyDigits Sour Gummy ExtraBold 的 0-9 数字子集字体(SIL OFL 1.1 开源授权,
|
||||
// 可免费商用;来源:Google Fonts / 猫啃网),圆润软糖风格,用于图形验证码。
|
||||
// 经 fonttools pyftsubset 从完整字体(58KB)子集化提取——验证码仅需数字,
|
||||
// 嵌入体积从 58KB 缩至约 3KB,cmap 中仅保留 U+0030-0039。
|
||||
//
|
||||
//go:embed fonts/SourGummy-ExtraBold-Digits.ttf
|
||||
var SourGummyDigits []byte
|
||||
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
Copyright 2018 The Sour Gummy Project Authors (https://github.com/eifetx/Sour-Gummy-Fonts)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -47,6 +47,10 @@ type JwtConfig struct {
|
||||
Secret string `toml:"secret"`
|
||||
AccessExpire int `toml:"accessExpire"`
|
||||
RefreshExpire int `toml:"refreshExpire"`
|
||||
// MfaAccessExpire MFA 通道登录的短期 token 有效期(秒)。MFA 学校第三方会话无法
|
||||
// 自动续期(重新登录需人工输入验证码),token 有效期与第三方 Cookie 对齐;独立于
|
||||
// 普通登录的 accessExpire 便于单独调整(默认 7200 = 2 小时,未配置时自动采用)。
|
||||
MfaAccessExpire int `toml:"mfaAccessExpire"`
|
||||
}
|
||||
|
||||
type CaptchaConfig struct {
|
||||
@@ -87,6 +91,10 @@ func Load(path string) error {
|
||||
if v := os.Getenv("JWT_SECRET"); v != "" {
|
||||
Global.Jwt.Secret = v
|
||||
}
|
||||
// MFA 通道短期 token 有效期默认 2 小时(未配置时采用,部署新版本自动生效)
|
||||
if Global.Jwt.MfaAccessExpire <= 0 {
|
||||
Global.Jwt.MfaAccessExpire = 7200
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ func Init() {
|
||||
}
|
||||
|
||||
// 自动迁移
|
||||
if err := DB.AutoMigrate(&model.SysUser{}, &model.DeviceBindToken{}, &model.CpTask{}, &model.CpTaskLog{}, &model.AgentUser{}, &model.CDKCode{}, &model.SystemConfig{}, &model.Announcement{}, &model.AnnouncementRead{}, &model.Ticket{}, &model.TicketMessage{}, &model.TicketNotification{}, &model.PendingSchool{}); err != nil {
|
||||
if err := DB.AutoMigrate(&model.SysUser{}, &model.DeviceBindToken{}, &model.CpTask{}, &model.CpTaskLog{}, &model.CpLeaveLog{}, &model.AgentUser{}, &model.CDKCode{}, &model.SystemConfig{}, &model.Announcement{}, &model.AnnouncementRead{}, &model.Ticket{}, &model.TicketMessage{}, &model.TicketNotification{}, &model.PendingSchool{}); err != nil {
|
||||
log.Fatalf("自动迁移失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ type CreateAnnouncementRequest struct {
|
||||
TargetUserID *uint `json:"targetUserId,omitempty"` // 指定单个用户(null=推送全部)
|
||||
ForcePopup bool `json:"forcePopup"`
|
||||
LoopPopup bool `json:"loopPopup"`
|
||||
IsPinned bool `json:"isPinned"` // 置顶公告:打卡页顶部横向滚动
|
||||
}
|
||||
|
||||
// CreateAnnouncement 创建公告
|
||||
@@ -39,6 +40,10 @@ func CreateAnnouncement(c *fiber.Ctx) error {
|
||||
if req.TargetType != "agent" && req.TargetType != "user" {
|
||||
return utils.Fail(c, 400, "目标类型必须为 agent 或 user")
|
||||
}
|
||||
// 置顶公告仅在打卡页(普通用户端)展示,仅普通用户公告可置顶
|
||||
if req.IsPinned && req.TargetType != "user" {
|
||||
return utils.Fail(c, 400, "仅普通用户公告可设为置顶")
|
||||
}
|
||||
|
||||
// 如果指定了用户,验证用户存在
|
||||
if req.TargetUserID != nil {
|
||||
@@ -63,6 +68,7 @@ func CreateAnnouncement(c *fiber.Ctx) error {
|
||||
TargetUserID: req.TargetUserID,
|
||||
ForcePopup: req.ForcePopup,
|
||||
LoopPopup: req.LoopPopup,
|
||||
IsPinned: req.IsPinned,
|
||||
CreatedBy: adminID,
|
||||
}
|
||||
|
||||
@@ -83,6 +89,7 @@ type UpdateAnnouncementRequest struct {
|
||||
TargetUserID *uint `json:"targetUserId,omitempty"` // 指定单个用户(null=推送全部)
|
||||
ForcePopup bool `json:"forcePopup"`
|
||||
LoopPopup bool `json:"loopPopup"`
|
||||
IsPinned bool `json:"isPinned"` // 置顶公告:打卡页顶部横向滚动
|
||||
}
|
||||
|
||||
// UpdateAnnouncement 更新公告(仅手动创建的公告可编辑)
|
||||
@@ -113,6 +120,10 @@ func UpdateAnnouncement(c *fiber.Ctx) error {
|
||||
if req.TargetType != "agent" && req.TargetType != "user" {
|
||||
return utils.Fail(c, 400, "目标类型必须为 agent 或 user")
|
||||
}
|
||||
// 置顶公告仅在打卡页(普通用户端)展示,仅普通用户公告可置顶
|
||||
if req.IsPinned && req.TargetType != "user" {
|
||||
return utils.Fail(c, 400, "仅普通用户公告可设为置顶")
|
||||
}
|
||||
|
||||
// 如果指定了用户,验证用户存在
|
||||
if req.TargetUserID != nil {
|
||||
@@ -136,6 +147,7 @@ func UpdateAnnouncement(c *fiber.Ctx) error {
|
||||
"target_user_id": req.TargetUserID,
|
||||
"force_popup": req.ForcePopup,
|
||||
"loop_popup": req.LoopPopup,
|
||||
"is_pinned": req.IsPinned,
|
||||
}
|
||||
if err := database.DB.Model(&announcement).Updates(updates).Error; err != nil {
|
||||
slog.Error("更新公告失败", "error", err)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/utils"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -22,17 +23,20 @@ type SysUserListItem struct {
|
||||
RealName string `json:"realName"`
|
||||
MobileCode string `json:"mobileCode"`
|
||||
MobileType string `json:"mobileType"`
|
||||
SignCount int `json:"signCount"`
|
||||
SignCount float64 `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"`
|
||||
LastLoginIP string `json:"lastLoginIp"`
|
||||
}
|
||||
|
||||
// inviterDisplay 邀请人展示名:姓名优先,其次用户名
|
||||
@@ -100,7 +104,8 @@ func ListUsers(c *fiber.Ctx) error {
|
||||
taskCountMap[tc.UserID] = tc.Count
|
||||
}
|
||||
|
||||
// 累计成功执行次数(cp_task_logs is_success=1)
|
||||
// 累计成功执行次数(cp_task_logs 签到/查寝 + cp_leave_logs 请假/销假,含用户已删除的软删除记录)
|
||||
// 说明:用户在客户端"删除"日志只是前台不可见(软删除),后台统计必须计入,否则执行次数会凭空减少
|
||||
executedMap := make(map[uint]int64)
|
||||
// 今天执行状态(success/fail/none)
|
||||
todayStatusMap := make(map[uint]string)
|
||||
@@ -115,23 +120,46 @@ func ListUsers(c *fiber.Ctx) error {
|
||||
Count int64
|
||||
MaxStatus int
|
||||
}
|
||||
// 签到/查寝成功次数(Unscoped 包含软删除)
|
||||
var logStats []LogStat
|
||||
database.DB.Model(&model.CpTaskLog{}).
|
||||
database.DB.Unscoped().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
|
||||
executedMap[ls.UserID] += ls.Count
|
||||
}
|
||||
// 请假/销假成功次数(Unscoped 包含软删除)
|
||||
var leaveStats []LogStat
|
||||
database.DB.Unscoped().Model(&model.CpLeaveLog{}).
|
||||
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(&leaveStats)
|
||||
for _, ls := range leaveStats {
|
||||
executedMap[ls.UserID] += ls.Count
|
||||
}
|
||||
|
||||
// 今天 00:00 起的日志
|
||||
// 今天 00:00 起的状态(含软删除):签到/查寝 + 请假/销假两类日志统一判定
|
||||
// 任一成功 → success;否则任有失败 → fail;都无 → none
|
||||
todayStart := time.Now().Format("2006-01-02") + " 00:00:00"
|
||||
var todayLogs []model.CpTaskLog
|
||||
database.DB.Select("user_id, is_success").
|
||||
var todayTaskLogs []model.CpTaskLog
|
||||
database.DB.Unscoped().Select("user_id, is_success").
|
||||
Where("user_id IN ? AND created_at >= ?", userIDs, todayStart).
|
||||
Find(&todayLogs)
|
||||
for _, tl := range todayLogs {
|
||||
Find(&todayTaskLogs)
|
||||
var todayLeaveLogs []model.CpLeaveLog
|
||||
database.DB.Unscoped().Select("user_id, is_success").
|
||||
Where("user_id IN ? AND created_at >= ?", userIDs, todayStart).
|
||||
Find(&todayLeaveLogs)
|
||||
for _, tl := range todayTaskLogs {
|
||||
if tl.IsSuccess {
|
||||
todayStatusMap[tl.UserID] = "success"
|
||||
} else if todayStatusMap[tl.UserID] != "success" {
|
||||
todayStatusMap[tl.UserID] = "fail"
|
||||
}
|
||||
}
|
||||
for _, tl := range todayLeaveLogs {
|
||||
if tl.IsSuccess {
|
||||
todayStatusMap[tl.UserID] = "success"
|
||||
} else if todayStatusMap[tl.UserID] != "success" {
|
||||
@@ -174,6 +202,17 @@ func ListUsers(c *fiber.Ctx) error {
|
||||
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,
|
||||
@@ -190,18 +229,27 @@ func ListUsers(c *fiber.Ctx) error {
|
||||
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,
|
||||
LastLoginIP: u.LastLoginIP,
|
||||
})
|
||||
}
|
||||
|
||||
// 当天统计:执行总次数 / 成功执行总次数 / 新增用户数 / 登录用户数
|
||||
// 执行类统计 = 签到/查寝 + 请假/销假(均含用户已删除的软删除记录)
|
||||
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)
|
||||
database.DB.Unscoped().Model(&model.CpTaskLog{}).Where("created_at >= ?", todayStart).Count(&todayExecuteCount)
|
||||
database.DB.Unscoped().Model(&model.CpTaskLog{}).Where("created_at >= ? AND is_success = 1", todayStart).Count(&todaySuccessCount)
|
||||
var todayLeaveExecute, todayLeaveSuccess int64
|
||||
database.DB.Unscoped().Model(&model.CpLeaveLog{}).Where("created_at >= ?", todayStart).Count(&todayLeaveExecute)
|
||||
database.DB.Unscoped().Model(&model.CpLeaveLog{}).Where("created_at >= ? AND is_success = 1", todayStart).Count(&todayLeaveSuccess)
|
||||
todayExecuteCount += todayLeaveExecute
|
||||
todaySuccessCount += todayLeaveSuccess
|
||||
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)
|
||||
@@ -212,9 +260,9 @@ func ListUsers(c *fiber.Ctx) error {
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
"todayStats": fiber.Map{
|
||||
"executeCount": todayExecuteCount,
|
||||
"successCount": todaySuccessCount,
|
||||
"newUserCount": todayNewUsers,
|
||||
"executeCount": todayExecuteCount,
|
||||
"successCount": todaySuccessCount,
|
||||
"newUserCount": todayNewUsers,
|
||||
"loginUserCount": todayLoginUsers,
|
||||
},
|
||||
})
|
||||
@@ -257,25 +305,26 @@ func GetUserDetail(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"id": user.ID,
|
||||
"username": user.Username,
|
||||
"schoolId": user.SchoolID,
|
||||
"schoolName": user.SchoolName,
|
||||
"studentId": user.StudentID,
|
||||
"realName": user.RealName,
|
||||
"password": password,
|
||||
"signCount": user.SignCount,
|
||||
"inviteReward": user.InviteReward,
|
||||
"invitedCount": user.InvitedCount,
|
||||
"inviterId": user.InviterID,
|
||||
"inviterName": inviterName,
|
||||
"status": user.Status,
|
||||
"id": user.ID,
|
||||
"username": user.Username,
|
||||
"schoolId": user.SchoolID,
|
||||
"schoolName": user.SchoolName,
|
||||
"studentId": user.StudentID,
|
||||
"realName": user.RealName,
|
||||
"password": password,
|
||||
"signCount": user.SignCount,
|
||||
"inviteReward": user.InviteReward,
|
||||
"invitedCount": user.InvitedCount,
|
||||
"inviterId": user.InviterID,
|
||||
"inviterName": inviterName,
|
||||
"status": user.Status,
|
||||
"disabledReason": user.DisabledReason,
|
||||
"taskCount": taskCount,
|
||||
"mobileCode": user.MobileCode,
|
||||
"mobileType": user.MobileType,
|
||||
"createdAt": user.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
"lastLoginAt": lastLogin,
|
||||
"taskCount": taskCount,
|
||||
"mobileCode": user.MobileCode,
|
||||
"mobileType": user.MobileType,
|
||||
"createdAt": user.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
"lastLoginAt": lastLogin,
|
||||
"lastLoginIp": user.LastLoginIP,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -322,3 +371,165 @@ 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"`
|
||||
// Deleted 表示该记录已被用户在客户端删除(软删除),仅后台可见
|
||||
Deleted bool `json:"deleted"`
|
||||
// Source 数据来源:1=签到/查寝(cp_task_logs) 2=请假/销假(cp_leave_logs),两表 id 独立自增,前端 key 需组合去重
|
||||
Source int `json:"source"`
|
||||
}
|
||||
|
||||
// adminLogUnionSQL 后台执行日志明细的数据源:cp_task_logs(签到/查寝)+ cp_leave_logs(请假/销假)UNION。
|
||||
// 原始 SQL 绕过 GORM 软删除过滤,故含用户已删除记录(deleted 标注);source 区分来源(1=任务 2=请假销假)。
|
||||
// 占位符顺序:dayStart, dayEnd, dayStart, dayEnd
|
||||
// 注意:两表由不同时期建表,字符串列 collation 不一致(utf8mb4_unicode_ci vs general_ci),
|
||||
// 直接 UNION 会报 1271 Illegal mix of collations,故显式 COLLATE 统一到 utf8mb4_unicode_ci。
|
||||
const adminLogUnionSQL = `
|
||||
SELECT id, user_id, task_type, title, real_title, is_success, error_message, created_at, deleted, source FROM (
|
||||
SELECT id, user_id, task_type, title, real_title, is_success, error_message, created_at,
|
||||
(deleted_at IS NOT NULL) AS deleted, 1 AS source
|
||||
FROM cp_task_logs
|
||||
WHERE created_at >= ? AND created_at < ?
|
||||
UNION ALL
|
||||
SELECT id, user_id,
|
||||
(CASE action WHEN 'apply' THEN 'leave_apply' ELSE 'leave_report' END) COLLATE utf8mb4_unicode_ci AS task_type,
|
||||
title COLLATE utf8mb4_unicode_ci, '' COLLATE utf8mb4_unicode_ci AS real_title, is_success,
|
||||
error_message COLLATE utf8mb4_unicode_ci, created_at,
|
||||
(deleted_at IS NOT NULL) AS deleted, 2 AS source
|
||||
FROM cp_leave_logs
|
||||
WHERE created_at >= ? AND created_at < ?
|
||||
) AS combined`
|
||||
|
||||
// AdminListTaskLogs 任务执行日志列表(仅admin,供"当天执行总次数"卡片点击查看)
|
||||
// 数据源 = 签到/查寝(cp_task_logs)+ 请假/销假(cp_leave_logs),均含用户已删除的软删除记录(标注 deleted);
|
||||
// 支持按日期(默认当天)、执行状态、关键字(用户名/姓名/任务标题)筛选,分页返回
|
||||
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
|
||||
}
|
||||
|
||||
type combinedRow struct {
|
||||
ID uint
|
||||
UserID uint
|
||||
TaskType string
|
||||
Title string
|
||||
RealTitle string
|
||||
IsSuccess bool
|
||||
ErrorMessage string
|
||||
CreatedAt time.Time
|
||||
Deleted bool
|
||||
Source int
|
||||
}
|
||||
|
||||
var rows []combinedRow
|
||||
raw := database.DB.Raw(adminLogUnionSQL, dayStart, dayEnd, dayStart, dayEnd)
|
||||
if status == "success" {
|
||||
raw = database.DB.Raw("SELECT * FROM ("+adminLogUnionSQL+") t WHERE t.is_success = 1", dayStart, dayEnd, dayStart, dayEnd)
|
||||
} else if status == "fail" {
|
||||
raw = database.DB.Raw("SELECT * FROM ("+adminLogUnionSQL+") t WHERE t.is_success = 0", dayStart, dayEnd, dayStart, dayEnd)
|
||||
}
|
||||
raw.Scan(&rows)
|
||||
|
||||
// 用户信息一次性查询
|
||||
userIDs := make([]uint, 0, len(rows))
|
||||
seen := make(map[uint]bool, len(rows))
|
||||
for _, r := range rows {
|
||||
if !seen[r.UserID] {
|
||||
seen[r.UserID] = true
|
||||
userIDs = append(userIDs, r.UserID)
|
||||
}
|
||||
}
|
||||
userMap := make(map[uint]model.SysUser, len(userIDs))
|
||||
if len(userIDs) > 0 {
|
||||
var us []model.SysUser
|
||||
database.DB.Select("id, username, real_name, school_name").Where("id IN ?", userIDs).Find(&us)
|
||||
for _, u := range us {
|
||||
userMap[u.ID] = u
|
||||
}
|
||||
}
|
||||
|
||||
// 关键字过滤(用户名/姓名/标题)在内存中完成(跨表 UNION 后)
|
||||
like := strings.ToLower(keyword)
|
||||
filtered := make([]AdminTaskLogItem, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
u := userMap[r.UserID]
|
||||
if keyword != "" {
|
||||
hay := strings.ToLower(u.Username + u.RealName + r.Title + r.RealTitle)
|
||||
if !strings.Contains(hay, like) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
filtered = append(filtered, AdminTaskLogItem{
|
||||
ID: r.ID,
|
||||
UserID: r.UserID,
|
||||
Username: u.Username,
|
||||
RealName: u.RealName,
|
||||
SchoolName: u.SchoolName,
|
||||
TaskType: r.TaskType,
|
||||
Title: r.Title,
|
||||
RealTitle: r.RealTitle,
|
||||
IsSuccess: r.IsSuccess,
|
||||
ErrorMessage: r.ErrorMessage,
|
||||
CreatedAt: r.CreatedAt,
|
||||
Deleted: r.Deleted,
|
||||
Source: r.Source,
|
||||
})
|
||||
}
|
||||
// 按时间倒序
|
||||
sort.Slice(filtered, func(i, j int) bool {
|
||||
return filtered[i].CreatedAt.After(filtered[j].CreatedAt)
|
||||
})
|
||||
|
||||
total := int64(len(filtered))
|
||||
start := (page - 1) * pageSize
|
||||
if start > len(filtered) {
|
||||
start = len(filtered)
|
||||
}
|
||||
end := start + pageSize
|
||||
if end > len(filtered) {
|
||||
end = len(filtered)
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"items": filtered[start:end],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"pageSize": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
+281
-12
@@ -1,14 +1,20 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"cpdaily-new/internal/config"
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/service"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
"cpdaily-new/internal/utils"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -87,7 +93,11 @@ func Login(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// 执行 cpdaily 登录
|
||||
cookies, err := cpd.CpdailyLogin(c.Context(), school, req.Username, req.Password)
|
||||
cookies, mfaCtx, err := cpd.CpdailyLogin(c.Context(), school, req.Username, req.Password)
|
||||
if errors.Is(err, cpd.ErrMFARequired) && mfaCtx != nil {
|
||||
// 多因子认证:验证码已自动发送,暂存会话并返回 mfaToken 给前端(携带邀请码,注册时同样生效)
|
||||
return startMFALogin(c, school, req.Username, req.Password, req.InviteCode, mfaCtx)
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("cpdaily登录失败", "error", err)
|
||||
return c.Status(401).JSON(utils.Response{
|
||||
@@ -99,6 +109,107 @@ func Login(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// 登录成功:公共处理(MOD_ 检查、用户注册、JWT 签发)
|
||||
return finalizeLogin(c, school, req.Username, req.Password, cookies, false, req.InviteCode)
|
||||
}
|
||||
|
||||
// MFAVerifyRequest 提交多因子认证验证码
|
||||
type MFAVerifyRequest struct {
|
||||
MfaToken string `json:"mfaToken"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// MFAVerify 提交多因子认证验证码,完成登录
|
||||
// 前端在 /auth/login 返回 needMFA=true 后,引导用户输入今日校园收到的验证码并调用本接口
|
||||
func MFAVerify(c *fiber.Ctx) error {
|
||||
var req MFAVerifyRequest
|
||||
if err := c.BodyParser(&req); err != nil || req.MfaToken == "" || req.Code == "" {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
code := strings.TrimSpace(req.Code)
|
||||
|
||||
// 读取暂存的 MFA 会话(成功前不删除,允许验证码输错重试;TTL 到期自动失效)
|
||||
sess, err := loadMFASession(c.Context(), req.MfaToken)
|
||||
if err != nil {
|
||||
// HTTP 200 + 专用业务码 4283:前端关闭验证码弹窗并引导重新登录
|
||||
return utils.RespondWithCode(c, utils.CodeMFAVerifySessionExpired, "验证会话不存在或已过期,请重新登录", nil)
|
||||
}
|
||||
|
||||
school, err := cpd.GetSchoolDetail(sess.SchoolID)
|
||||
if err != nil {
|
||||
slog.Error("MFA验证: 获取学校详情失败", "schoolId", sess.SchoolID, "error", err)
|
||||
return utils.RespondWithCode(c, utils.CodeMFAVerifyFailed, "获取学校信息失败,请稍后重试", nil)
|
||||
}
|
||||
|
||||
// 完成 MFA 认证并走完 CAS 票据交换
|
||||
cookies, err := cpd.CompleteMFALogin(c.Context(), sess.MFA, code)
|
||||
if err != nil {
|
||||
slog.Warn("MFA验证失败", "username", sess.Username, "error", err)
|
||||
if errors.Is(err, cpd.ErrMFASessionExpired) {
|
||||
// 会话失效:前端关闭验证码弹窗,引导重新登录
|
||||
return utils.RespondWithCode(c, utils.CodeMFAVerifySessionExpired, "验证会话已失效,请重新登录", nil)
|
||||
}
|
||||
// 验证码错误或其他失败:弹窗保留,可重新输入(业务码 4282)
|
||||
return utils.RespondWithCode(c, utils.CodeMFAVerifyFailed, "验证失败: "+err.Error(), nil)
|
||||
}
|
||||
|
||||
// 验证成功,清理暂存会话
|
||||
deleteMFASession(c.Context(), req.MfaToken)
|
||||
|
||||
// 短期 JWT:与第三方 Cookie 有效期对齐(MFA 登录无法自动续期)
|
||||
return finalizeLogin(c, school, sess.Username, sess.Password, cookies, true, sess.InviteCode)
|
||||
}
|
||||
|
||||
// MFASendCodeRequest 发送多因子认证验证码(用户已选定验证方式)
|
||||
type MFASendCodeRequest struct {
|
||||
MfaToken string `json:"mfaToken"`
|
||||
ReAuthType string `json:"reAuthType"` // 用户选择的验证方式(reAuthType 编码:3=短信 5=今日校园 11=邮箱 等)
|
||||
}
|
||||
|
||||
// MFASendCode 按用户选定的验证方式发送验证码
|
||||
// 前端在 /auth/login 返回 4281(含 authMethods 列表)后,用户选择方式点击「发送验证码」时调用本接口:
|
||||
// - 成功(code 0):前端进入验证码输入阶段(data 含 mobile/codeTime)
|
||||
// - 4284:发送失败(弹窗留在选择界面,可重试或更换方式)
|
||||
// - 4283:验证会话已过期(关闭弹窗引导重新登录)
|
||||
func MFASendCode(c *fiber.Ctx) error {
|
||||
var req MFASendCodeRequest
|
||||
if err := c.BodyParser(&req); err != nil || req.MfaToken == "" {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
|
||||
sess, err := loadMFASession(c.Context(), req.MfaToken)
|
||||
if err != nil {
|
||||
return utils.RespondWithCode(c, utils.CodeMFAVerifySessionExpired, "验证会话不存在或已过期,请重新登录", nil)
|
||||
}
|
||||
|
||||
result, err := cpd.SendMFADynamicCode(c.Context(), sess.MFA, req.ReAuthType)
|
||||
if err != nil {
|
||||
slog.Warn("MFA发送验证码失败", "username", sess.Username, "reAuthType", req.ReAuthType, "error", err)
|
||||
if errors.Is(err, cpd.ErrMFASessionExpired) {
|
||||
return utils.RespondWithCode(c, utils.CodeMFAVerifySessionExpired, "验证会话已失效,请重新登录", nil)
|
||||
}
|
||||
return utils.RespondWithCode(c, utils.CodeMFASendCodeFailed, "发送失败: "+err.Error(), nil)
|
||||
}
|
||||
|
||||
// 用户选择的验证方式已同步到会话(提交 reAuthSubmit.do 需使用同一方式),更新暂存
|
||||
if err := updateMFASession(c.Context(), req.MfaToken, sess); err != nil {
|
||||
slog.Warn("MFA会话更新失败", "error", err)
|
||||
}
|
||||
|
||||
msg := result.Message
|
||||
if result.Mobile != "" && !strings.Contains(msg, result.Mobile) {
|
||||
msg = fmt.Sprintf("%s,验证码已发送至 %s", msg, result.Mobile)
|
||||
}
|
||||
slog.Info("MFA验证码已发送", "username", sess.Username, "reAuthType", req.ReAuthType)
|
||||
return utils.RespondWithCode(c, 0, msg, fiber.Map{
|
||||
"mobile": result.Mobile,
|
||||
"codeTime": result.CodeTime,
|
||||
})
|
||||
}
|
||||
|
||||
// finalizeLogin 登录成功后的公共处理:MOD_ 检查、Cookie 序列化、查找/注册用户、
|
||||
// 更新登录信息、签发 JWT。shortToken=true 时签发 MFA 短期 token。
|
||||
func finalizeLogin(c *fiber.Ctx, school *cpd.SchoolDetailInfo, username, password string, cookies []*http.Cookie, shortToken bool, referralCode string) error {
|
||||
// 检查 MOD_ cookie
|
||||
hasMOD := false
|
||||
for _, cookie := range cookies {
|
||||
@@ -121,10 +232,10 @@ func Login(c *fiber.Ctx) error {
|
||||
cookieStr := cpd.SerializeCookies(cookies)
|
||||
|
||||
// 构建用户名: 学校简称 + 学号
|
||||
userName := buildUsername(school, req.Username)
|
||||
userName := buildUsername(school, username)
|
||||
|
||||
// 查找或创建用户
|
||||
user, isNew, err := findOrCreateUser(userName, req.Password, req.SchoolID, school.Name, req.Username, cookieStr, req.InviteCode)
|
||||
user, isNew, err := findOrCreateUser(userName, password, school.ID, school.Name, username, cookieStr, referralCode)
|
||||
if err != nil {
|
||||
slog.Error("用户处理失败", "error", err)
|
||||
return utils.FailServer(c, "用户处理失败")
|
||||
@@ -143,23 +254,29 @@ func Login(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// 更新 cookie 和最后登录时间
|
||||
// 更新 cookie 和最后登录时间(含登录 IP)
|
||||
now := time.Now()
|
||||
database.DB.Model(&user).Updates(map[string]interface{}{
|
||||
"cookie": cookieStr,
|
||||
"last_login_at": now,
|
||||
"last_login_ip": utils.ClientIP(c),
|
||||
})
|
||||
|
||||
// 保存明文密码(用于 cookie 过期时自动重新登录)
|
||||
if err := saveRawPassword(user.ID, req.Password); err != nil {
|
||||
if err := saveRawPassword(user.ID, password); err != nil {
|
||||
slog.Error("保存密码失败", "userId", user.ID, "error", err)
|
||||
}
|
||||
|
||||
// 尝试从 cpdaily 获取用户主页信息并更新本地数据
|
||||
go syncUserProfile(user, cookieStr, school.WecloudUrl)
|
||||
|
||||
// 生成 JWT
|
||||
tokenPair, err := service.GenerateTokens(user.ID, user.Username, user.SchoolID)
|
||||
// 生成 JWT:MFA 通道登录使用与第三方 Cookie 对齐的短期 token
|
||||
var tokenPair *service.TokenPair
|
||||
if shortToken {
|
||||
tokenPair, err = service.GenerateShortTokens(user.ID, user.Username, user.SchoolID, int64(config.Global.Jwt.MfaAccessExpire))
|
||||
} else {
|
||||
tokenPair, err = service.GenerateTokens(user.ID, user.Username, user.SchoolID)
|
||||
}
|
||||
if err != nil {
|
||||
return utils.FailServer(c, "生成token失败")
|
||||
}
|
||||
@@ -236,17 +353,47 @@ func CompleteGuide(c *fiber.Ctx) error {
|
||||
return utils.Success(c, nil)
|
||||
}
|
||||
|
||||
// syncUserProfile 同步 cpdaily 用户信息到数据库
|
||||
// syncUserProfile 同步 cpdaily 用户信息到数据库。
|
||||
// 登录态失效(cookie 过期)时自动续期并重试一次,避免用户信息长期同步不上。
|
||||
func syncUserProfile(user *model.SysUser, cookieStr string, wecloudUrl string) {
|
||||
syncUserProfileWith(user, cookieStr, wecloudUrl, true)
|
||||
}
|
||||
|
||||
// syncUserProfileWith allowRefresh=false 时不做 cookie 续期,
|
||||
// 供续期流程内部调用,避免「续期 → 同步 → 再续期」的递归风暴。
|
||||
func syncUserProfileWith(user *model.SysUser, cookieStr string, wecloudUrl string, allowRefresh bool) {
|
||||
cookieMap := cpd.ParseCookieJSON(cookieStr)
|
||||
profile, err := cpd.FetchUserProfile(cookieMap, wecloudUrl)
|
||||
if err != nil {
|
||||
slog.Warn("同步用户信息失败", "userId", user.ID, "error", err)
|
||||
|
||||
fetch := func(cm map[string]string) (*cpd.CpdailyUserProfile, error) {
|
||||
return cpd.FetchUserProfile(cm, wecloudUrl)
|
||||
}
|
||||
|
||||
var profile *cpd.CpdailyUserProfile
|
||||
if allowRefresh {
|
||||
_, err := withCookieRefresh(user, cookieMap, wecloudUrl, func(cm map[string]string) error {
|
||||
var e error
|
||||
profile, e = fetch(cm)
|
||||
return e
|
||||
})
|
||||
if err != nil {
|
||||
slog.Warn("同步用户信息失败", "userId", user.ID, "error", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
p, err := fetch(cookieMap)
|
||||
if err != nil {
|
||||
slog.Warn("同步用户信息失败(禁续期)", "userId", user.ID, "error", err)
|
||||
return
|
||||
}
|
||||
profile = p
|
||||
}
|
||||
if profile == nil {
|
||||
return
|
||||
}
|
||||
|
||||
updates := syncProfileToUser(profile)
|
||||
updates["cookie"] = cookieStr // 确保 cookie 最新
|
||||
// 同步结果不覆盖 cookie:cookie 由调用方(登录/续期流程)负责维护,
|
||||
// 避免异步同步与续期流程并发写 cookie 造成相互覆盖。
|
||||
database.DB.Model(&user).Updates(updates)
|
||||
slog.Info("用户信息同步成功", "userId", user.ID, "name", profile.Name)
|
||||
}
|
||||
@@ -349,6 +496,7 @@ func createInviteNotifications(inviterID, inviteeID uint, inviterReward, invitee
|
||||
|
||||
// 查找或创建用户
|
||||
// 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
|
||||
@@ -360,6 +508,16 @@ func findOrCreateUser(username, password, schoolID, schoolName, studentID, cooki
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
// 兼容手机号登录:同一学校 + 同学工号 视为同一用户
|
||||
if studentID != "" {
|
||||
if e2 := database.DB.Where("school_id = ? AND student_id = ?", schoolID, studentID).First(&user).Error; e2 == nil {
|
||||
slog.Info("按学工号匹配到已有账号(学工号登录)", "userId", user.ID, "studentId", studentID)
|
||||
return &user, false, nil
|
||||
} else if !errors.Is(e2, gorm.ErrRecordNotFound) {
|
||||
return nil, false, e2
|
||||
}
|
||||
}
|
||||
|
||||
// 自动注册:生成密码哈希和邀请码
|
||||
hashedPwd, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
@@ -564,3 +722,114 @@ func generateRandomCode(n int) string {
|
||||
}
|
||||
return string(code)
|
||||
}
|
||||
|
||||
// ========== 多因子认证(MFA)会话暂存 ==========
|
||||
|
||||
const (
|
||||
mfaSessionKeyFmt = "mfa_session:%s"
|
||||
mfaSessionTTL = 10 * time.Minute
|
||||
)
|
||||
|
||||
// mfaSession Redis 暂存的 MFA 中间会话(Password AES 加密存储)
|
||||
type mfaSession struct {
|
||||
SchoolID string `json:"schoolId"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
InviteCode string `json:"inviteCode,omitempty"` // 注册时携带的邀请码(MFA 通道注册同样生效)
|
||||
MFA *cpd.MFAContext `json:"mfa"`
|
||||
}
|
||||
|
||||
// startMFALogin 暂存 MFA 会话并返回 mfaToken 与可用验证方式列表,
|
||||
// 前端引导用户选择验证方式后调用 /auth/login/mfa/send 获取验证码
|
||||
func startMFALogin(c *fiber.Ctx, school *cpd.SchoolDetailInfo, username, password, inviteCode string, mfaCtx *cpd.MFAContext) error {
|
||||
if service.Redis == nil {
|
||||
return utils.FailServer(c, "多因子认证暂不可用(存储服务未就绪),请稍后重试")
|
||||
}
|
||||
|
||||
tokenBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(tokenBytes); err != nil {
|
||||
return utils.FailServer(c, "生成验证会话失败")
|
||||
}
|
||||
mfaToken := hex.EncodeToString(tokenBytes)
|
||||
|
||||
// 密码 AES 加密后暂存,验证成功后用于注册/更新账号
|
||||
encPassword, err := encryptRawPassword(password)
|
||||
if err != nil {
|
||||
return utils.FailServer(c, "生成验证会话失败")
|
||||
}
|
||||
|
||||
data, _ := json.Marshal(mfaSession{
|
||||
SchoolID: school.ID,
|
||||
Username: username,
|
||||
Password: encPassword,
|
||||
InviteCode: inviteCode,
|
||||
MFA: mfaCtx,
|
||||
})
|
||||
if err := service.Redis.Set(context.Background(), fmt.Sprintf(mfaSessionKeyFmt, mfaToken), data, mfaSessionTTL).Err(); err != nil {
|
||||
slog.Error("MFA会话暂存失败", "error", err)
|
||||
return utils.FailServer(c, "生成验证会话失败")
|
||||
}
|
||||
|
||||
slog.Info("MFA会话已创建", "school", school.Name, "username", username,
|
||||
"defaultType", mfaCtx.ReAuthType, "authMethods", len(mfaCtx.AuthMethods))
|
||||
// HTTP 200 + 专用业务码 4281:前端按 code 弹出「选择验证方式」弹窗(而非登录失败弹窗)
|
||||
return utils.RespondWithCode(c, utils.CodeMFARequired, "该校登录需多因子认证,请选择验证方式获取验证码", fiber.Map{
|
||||
"needMFA": true,
|
||||
"mfaToken": mfaToken,
|
||||
"expiresIn": int(mfaSessionTTL.Seconds()),
|
||||
"authMethods": mfaCtx.AuthMethods,
|
||||
"defaultType": mfaCtx.ReAuthType,
|
||||
})
|
||||
}
|
||||
|
||||
// loadMFASession 读取暂存的 MFA 会话(验证码输错可重试,成功后才删除)
|
||||
func loadMFASession(ctx context.Context, mfaToken string) (*mfaSession, error) {
|
||||
if service.Redis == nil || mfaToken == "" {
|
||||
return nil, fmt.Errorf("mfa session unavailable")
|
||||
}
|
||||
val, err := service.Redis.Get(ctx, fmt.Sprintf(mfaSessionKeyFmt, mfaToken)).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var sess mfaSession
|
||||
if err := json.Unmarshal([]byte(val), &sess); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 解密密码
|
||||
raw, err := decryptRawPassword(sess.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sess.Password = raw
|
||||
return &sess, nil
|
||||
}
|
||||
|
||||
// deleteMFASession 删除暂存的 MFA 会话
|
||||
func deleteMFASession(ctx context.Context, mfaToken string) {
|
||||
if service.Redis == nil || mfaToken == "" {
|
||||
return
|
||||
}
|
||||
service.Redis.Del(ctx, fmt.Sprintf(mfaSessionKeyFmt, mfaToken))
|
||||
}
|
||||
|
||||
// updateMFASession 更新暂存的 MFA 会话(如用户切换验证方式后),TTL 顺延
|
||||
func updateMFASession(ctx context.Context, mfaToken string, sess *mfaSession) error {
|
||||
if service.Redis == nil || mfaToken == "" || sess == nil {
|
||||
return fmt.Errorf("mfa session unavailable")
|
||||
}
|
||||
encPassword, err := encryptRawPassword(sess.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := json.Marshal(mfaSession{
|
||||
SchoolID: sess.SchoolID,
|
||||
Username: sess.Username,
|
||||
Password: encPassword,
|
||||
InviteCode: sess.InviteCode,
|
||||
MFA: sess.MFA,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return service.Redis.Set(ctx, fmt.Sprintf(mfaSessionKeyFmt, mfaToken), data, mfaSessionTTL).Err()
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
@@ -46,26 +47,51 @@ func updateRawPassword(userID uint, rawPassword string) error {
|
||||
return saveRawPassword(userID, rawPassword)
|
||||
}
|
||||
|
||||
// isCookieExpired 判断错误是否由 cpdaily cookie 过期引起
|
||||
// isCookieExpired 判断错误是否由 cpdaily 登录态失效(cookie 过期)引起。
|
||||
// 两种来源:
|
||||
// 1. cpd.ErrCookieExpired:响应体是 HTML(被重定向到统一身份认证登录页),
|
||||
// 这是最常见、也最容易被漏判的情形(原文案匹配不到 "invalid character '<'");
|
||||
// 2. 接口以 JSON 形式返回的「未登录 / 登录已过期」。
|
||||
func isCookieExpired(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, cpd.ErrCookieExpired) {
|
||||
return true
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "未登录") ||
|
||||
strings.Contains(msg, "登录已过期")
|
||||
}
|
||||
|
||||
// isCpdailyAuthError 语义化别名:今日校园登录态失效。
|
||||
func isCpdailyAuthError(err error) bool {
|
||||
return isCookieExpired(err)
|
||||
}
|
||||
|
||||
// refreshCpdailyCookie 使用数据库中的 raw_password 重新登录 cpdaily 并更新 cookie
|
||||
// 密码错误时返回 ErrPasswordChanged
|
||||
func refreshCpdailyCookie(user *model.SysUser) error {
|
||||
// 重新从数据库加载用户(获取最新 raw_password)
|
||||
// 重新从数据库加载用户(获取最新 raw_password 与 cookie)
|
||||
var fresh model.SysUser
|
||||
if err := database.DB.First(&fresh, user.ID).Error; err != nil {
|
||||
slog.Error("刷新cookie: 查询用户失败", "userId", user.ID, "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// 优先尝试用长期 cookie(sessionToken/CASTGC)直接换取新的 CAS cookie。
|
||||
// 手机号验证码登录的账号没有 raw_password,只能走此路径自动续期。
|
||||
if refreshed, err := refreshCookieByLongTermToken(&fresh); err == nil && refreshed != "" {
|
||||
if err := database.DB.Model(&fresh).Update("cookie", refreshed).Error; err != nil {
|
||||
slog.Warn("刷新cookie: 写回长期凭证续期结果失败", "userId", user.ID, "error", err)
|
||||
} else {
|
||||
slog.Info("刷新cookie: 已用长期凭证续期成功", "userId", user.ID)
|
||||
return nil
|
||||
}
|
||||
} else if err != nil {
|
||||
slog.Info("刷新cookie: 长期凭证续期未成功,回退密码重登", "userId", user.ID, "error", err)
|
||||
}
|
||||
|
||||
if fresh.RawPassword == "" {
|
||||
slog.Warn("刷新cookie: 未保存密码", "userId", user.ID)
|
||||
return errors.New("未保存登录密码,无法自动重新登录")
|
||||
@@ -88,8 +114,8 @@ func refreshCpdailyCookie(user *model.SysUser) error {
|
||||
slog.Info("刷新cookie: 尝试重新登录cpdaily", "userId", user.ID, "school", school.Name)
|
||||
|
||||
// 执行 cpdaily 登录
|
||||
cookies, err := cpd.CpdailyLogin(context.Background(), school, fresh.StudentID, rawPassword)
|
||||
if err != nil {
|
||||
cookies, mfaCtx, err := cpd.CpdailyLogin(context.Background(), school, fresh.StudentID, rawPassword)
|
||||
if err != nil && !errors.Is(err, cpd.ErrMFARequired) {
|
||||
errMsg := err.Error()
|
||||
slog.Warn("刷新cookie: cpdaily登录失败", "userId", user.ID, "error", errMsg)
|
||||
|
||||
@@ -102,6 +128,11 @@ func refreshCpdailyCookie(user *model.SysUser) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
// 多因子认证学校:重新登录需人工输入验证码,无法自动续期
|
||||
if errors.Is(err, cpd.ErrMFARequired) || mfaCtx != nil {
|
||||
slog.Warn("刷新cookie: 该账号登录需多因子认证,无法自动续期", "userId", user.ID, "school", school.Name)
|
||||
return errors.New("该账号所属学校开启登录验证码校验,需重新登录完成验证")
|
||||
}
|
||||
|
||||
// 检查 MOD_ cookie 确保登录成功
|
||||
hasMOD := false
|
||||
@@ -123,12 +154,77 @@ func refreshCpdailyCookie(user *model.SysUser) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 同步用户信息(异步)
|
||||
go syncUserProfile(user, cookieStr, school.WecloudUrl)
|
||||
|
||||
// 更新传入用户的 cookie(引用),上层重试时使用
|
||||
// 先更新传入用户的 cookie(引用),上层重试与后续同步均使用最新值
|
||||
user.Cookie = cookieStr
|
||||
|
||||
// 同步用户信息(异步,禁续期:避免「续期 → 同步 → 再续期」递归)
|
||||
go syncUserProfileWith(user, cookieStr, school.WecloudUrl, false)
|
||||
|
||||
slog.Info("刷新cookie: 成功", "userId", user.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// refreshCookieByLongTermToken 用已保存的长期 cookie(sessionToken/CASTGC)重新换取 CAS cookie。
|
||||
// 适用于手机号验证码登录(无 raw_password)的账号自动续期;失败时返回错误,由调用方回退。
|
||||
func refreshCookieByLongTermToken(user *model.SysUser) (string, error) {
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
if cookieMap["sessionToken"] == "" {
|
||||
return "", errors.New("缺少长期凭证 sessionToken")
|
||||
}
|
||||
|
||||
school, err := cpd.GetSchoolDetail(user.SchoolID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
cookies, err := cpd.RefreshCasCookie(context.Background(), cookieMap, school.WecloudUrl, user.MobileCode)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hasMOD := false
|
||||
for _, c := range cookies {
|
||||
if strings.HasPrefix(c.Name, "MOD_") {
|
||||
hasMOD = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasMOD {
|
||||
return "", errors.New("续期未获取到 MOD_ cookie")
|
||||
}
|
||||
|
||||
cookieStr := cpd.SerializeCookies(cookies)
|
||||
// 回写传入用户,供上层重试使用
|
||||
user.Cookie = cookieStr
|
||||
return cookieStr, nil
|
||||
}
|
||||
|
||||
// withCookieRefresh 执行一次今日校园调用;若因登录态失效失败,则尝试续期 cookie 后重试一次。
|
||||
// - 返回 (调用结果, 续期后的 cookieMap, error)。cookieMap 有变化时调用方可用于后续调用。
|
||||
// - 续期失败(如 MFA 学校无法自动续期、密码已改)时,返回错误里带上 ErrCookieExpired,
|
||||
// 由上层转成「登录凭证已过期,请重新登录」引导用户重登。
|
||||
//
|
||||
// 说明:MFA 学校登录后签发的是短期 JWT,到期会要求重新登录,本就无需自动续期;
|
||||
// 普通学校(非 MFA)的 cookie 会在此处用长期凭证/密码自动续期,避免用户被莫名踢出。
|
||||
func withCookieRefresh(user *model.SysUser, cookieMap map[string]string, host string,
|
||||
fn func(cm map[string]string) error) (map[string]string, error) {
|
||||
|
||||
err := fn(cookieMap)
|
||||
if err == nil || !isCpdailyAuthError(err) {
|
||||
return cookieMap, err
|
||||
}
|
||||
|
||||
slog.Info("检测到今日校园登录态失效,尝试自动续期 cookie", "userId", user.ID, "host", host)
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr != nil {
|
||||
// 续期失败:保留原始错误语义,让上层引导重新登录
|
||||
slog.Warn("cookie 自动续期失败", "userId", user.ID, "error", refreshErr)
|
||||
return cookieMap, fmt.Errorf("%w: %v", cpd.ErrCookieExpired, refreshErr)
|
||||
}
|
||||
|
||||
// 用续期后的 cookie 重试一次
|
||||
newMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
if retryErr := fn(newMap); retryErr != nil {
|
||||
return newMap, retryErr
|
||||
}
|
||||
return newMap, nil
|
||||
}
|
||||
|
||||
@@ -38,17 +38,22 @@ func getBaseDeduction() float64 {
|
||||
return config.Global.Agent.SystemCdkPrice
|
||||
}
|
||||
|
||||
// getVipPrice 获取 VIP CDK 单张价格(元/张,系统设置,默认15元)
|
||||
func getVipPrice() float64 {
|
||||
// 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` = ?", "vip_price").First(&cfg).Error == nil {
|
||||
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 15.00
|
||||
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)
|
||||
@@ -81,7 +86,6 @@ func GenerateCDK(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
baseDeduction := getBaseDeduction()
|
||||
vipPrice := getVipPrice()
|
||||
|
||||
var maxRuns int
|
||||
var vipDays int
|
||||
@@ -89,21 +93,23 @@ func GenerateCDK(c *fiber.Ctx) error {
|
||||
var costPerCDK float64
|
||||
|
||||
if req.Type == "vip" {
|
||||
// VIP CDK:默认一个月(30天),上限365天
|
||||
// VIP CDK:仅支持周卡(7天)/ 月卡(30天)两档
|
||||
if req.VipDays <= 0 {
|
||||
req.VipDays = 30
|
||||
}
|
||||
if req.VipDays > 365 {
|
||||
return utils.Fail(c, 400, "单张VIP CDK最多365天")
|
||||
}
|
||||
if req.VipDays%30 != 0 {
|
||||
return utils.Fail(c, 400, "VIP天数须为30的整数倍(一个月起)")
|
||||
if req.VipDays != 7 && req.VipDays != 30 {
|
||||
return utils.Fail(c, 400, "VIP CDK 仅支持 7 天(周卡)或 30 天(月卡)")
|
||||
}
|
||||
maxRuns = 0
|
||||
vipDays = req.VipDays
|
||||
months := req.VipDays / 30
|
||||
unitPrice = vipPrice * float64(months) * agent.Rate
|
||||
costPerCDK = vipPrice * float64(months)
|
||||
var vipPrice float64
|
||||
if req.VipDays == 7 {
|
||||
vipPrice = getVipWeekPrice()
|
||||
} else {
|
||||
vipPrice = getVipMonthPrice()
|
||||
}
|
||||
unitPrice = vipPrice * agent.Rate
|
||||
costPerCDK = vipPrice
|
||||
} else {
|
||||
// 次数 CDK
|
||||
if req.MaxRuns <= 0 {
|
||||
@@ -491,8 +497,10 @@ func GetUserVipInfo(c *fiber.Ctx) error {
|
||||
isVip := user.VipExpireAt != nil && user.VipExpireAt.After(time.Now())
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"isVip": isVip,
|
||||
"vipExpireAt": vipExpireAt,
|
||||
"vipPrice": formatFloat(getVipPrice()),
|
||||
"isVip": isVip,
|
||||
"vipExpireAt": vipExpireAt,
|
||||
"vipWeekPrice": formatFloat(getVipWeekPrice()),
|
||||
"vipMonthPrice": formatFloat(getVipMonthPrice()),
|
||||
"vipPrice": formatFloat(getVipMonthPrice()), // 兼容旧字段:月卡价
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// 扣款额度系统设置 key(每次成功执行对应操作扣减的可签到次数)
|
||||
const (
|
||||
settingDeductCheckin = "deduct_checkin" // 打卡
|
||||
settingDeductLeave = "deduct_leave" // 请假
|
||||
settingDeductReport = "deduct_report" // 销假
|
||||
)
|
||||
|
||||
// parseDeductValue 解析扣款额度字符串:非法或负数时回退到 def。
|
||||
// 允许 0(0 表示不扣费),仅负数与解析失败视为无效。
|
||||
func parseDeductValue(value string, def float64) float64 {
|
||||
if v, err := strconv.ParseFloat(value, 64); err == nil && v >= 0 {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// getDeduct 从系统设置读取扣款额度;缺省/非法/负数时回退到 def,允许 0。
|
||||
func getDeduct(key string, def float64) float64 {
|
||||
var cfg model.SystemConfig
|
||||
if database.DB.Where("`key` = ?", key).First(&cfg).Error == nil {
|
||||
return parseDeductValue(cfg.Value, def)
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// getCheckinDeduct 打卡扣减额度(默认 1)
|
||||
func getCheckinDeduct() float64 { return getDeduct(settingDeductCheckin, 1) }
|
||||
|
||||
// getLeaveDeduct 请假扣减额度(默认 1)
|
||||
func getLeaveDeduct() float64 { return getDeduct(settingDeductLeave, 1) }
|
||||
|
||||
// getReportDeduct 销假扣减额度(默认 1)
|
||||
func getReportDeduct() float64 { return getDeduct(settingDeductReport, 1) }
|
||||
|
||||
// fmtDeduct 额度展示:整数去尾零(1.00→1,0.50→0.5,0→0)
|
||||
func fmtDeduct(v float64) string {
|
||||
return strconv.FormatFloat(v, 'f', -1, 64)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package handler
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestParseDeductValue 扣款额度解析:允许 0 与小数,非法/负数回退默认值。
|
||||
func TestParseDeductValue(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
value string
|
||||
def float64
|
||||
want float64
|
||||
}{
|
||||
{"空字符串回退默认", "", 1, 1},
|
||||
{"整数", "2", 1, 2},
|
||||
{"小数", "0.5", 1, 0.5},
|
||||
{"零不扣费", "0", 1, 0},
|
||||
{"零带小数", "0.0", 1, 0},
|
||||
{"负数回退默认", "-1", 1, 1},
|
||||
{"非数字回退默认", "abc", 1, 1},
|
||||
{"科学计数", "1e1", 1, 10},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := parseDeductValue(c.value, c.def); got != c.want {
|
||||
t.Fatalf("parseDeductValue(%q, %v) = %v, want %v", c.value, c.def, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFmtDeduct 额度展示去尾零。
|
||||
func TestFmtDeduct(t *testing.T) {
|
||||
cases := []struct {
|
||||
in float64
|
||||
want string
|
||||
}{
|
||||
{1, "1"},
|
||||
{0, "0"},
|
||||
{0.5, "0.5"},
|
||||
{2.25, "2.25"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := fmtDeduct(c.in); got != c.want {
|
||||
t.Fatalf("fmtDeduct(%v) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/ratelimit"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
"cpdaily-new/internal/utils"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ---------- 销假(请假销假)----------
|
||||
|
||||
// GetPendingLeaves 获取今日校园待销假列表(实时请求今日校园,附带规定销假位置)
|
||||
func GetPendingLeaves(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
}
|
||||
if user.Cookie == "" {
|
||||
return utils.Fail(c, 400, "请先登录")
|
||||
}
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 应用套件分流:新套(leave-new)走独立链路
|
||||
isNewFlavor := schoolLeaveFlavor(&user, cookieMap) == cpd.LeaveFlavorNew
|
||||
|
||||
var items []cpd.LeaveItem
|
||||
_, err := withCookieRefresh(&user, cookieMap, host, func(cm map[string]string) error {
|
||||
if isNewFlavor {
|
||||
// 套件判定用的是会话开始时解析的 cookie;续期后重新判定以保持准确
|
||||
if schoolLeaveFlavor(&user, cm) == cpd.LeaveFlavorNew {
|
||||
var e error
|
||||
items, e = fetchLeaveNewPendingList(cm, host, &user)
|
||||
return e
|
||||
}
|
||||
}
|
||||
var e error
|
||||
items, e = cpd.FetchLeaveList(cm, host)
|
||||
return e
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("获取待销假列表失败", "userId", userID, "error", err)
|
||||
if isCpdailyAuthError(err) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取待销假列表失败: "+err.Error())
|
||||
}
|
||||
|
||||
return utils.Success(c, items)
|
||||
}
|
||||
|
||||
// ExecuteLeaveRequest 销假执行参数
|
||||
type ExecuteLeaveRequest struct {
|
||||
LeaveID string `json:"leaveId"` // 今日校园请假记录 ID
|
||||
Longitude string `json:"longitude"` // 销假经度(必填)
|
||||
Latitude string `json:"latitude"` // 销假纬度(必填)
|
||||
Address string `json:"address"` // 销假地址(无规定位置时必填)
|
||||
ImageURL string `json:"imageUrl"` // 销假图片 URL(可选)
|
||||
ApproverWid string `json:"approverWid"` // 审批人 userWid(reportApplyFlow=1 时为必填)
|
||||
}
|
||||
|
||||
// ExecuteLeave 执行销假(SSE 同步执行:POST 请求 + 流式事件返回进度与结果)。
|
||||
// 事件流:connecting → fetching_detail → submitting → success / task_error
|
||||
func ExecuteLeave(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
|
||||
var req ExecuteLeaveRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
req.LeaveID = strings.TrimSpace(req.LeaveID)
|
||||
req.Longitude = strings.TrimSpace(req.Longitude)
|
||||
req.Latitude = strings.TrimSpace(req.Latitude)
|
||||
req.Address = strings.TrimSpace(req.Address)
|
||||
req.ApproverWid = strings.TrimSpace(req.ApproverWid)
|
||||
if req.LeaveID == "" || req.Longitude == "" || req.Latitude == "" {
|
||||
return utils.FailParam(c, "销假经纬度不能为空")
|
||||
}
|
||||
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
}
|
||||
if user.Cookie == "" {
|
||||
return utils.Fail(c, 400, "请先登录")
|
||||
}
|
||||
// 设备码后端硬校验:销假执行需携带设备码(对齐打卡侧拦截语义),
|
||||
// 账密登录创建的账号可能未绑定设备码,空设备码会触发学校端风控异常
|
||||
if strings.TrimSpace(user.MobileCode) == "" {
|
||||
return utils.Fail(c, 400, "请先在个人中心绑定设备码后再执行销假")
|
||||
}
|
||||
|
||||
// SSE 头
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
c.Set("Cache-Control", "no-cache")
|
||||
c.Set("Connection", "keep-alive")
|
||||
c.Set("X-Accel-Buffering", "no")
|
||||
|
||||
// SSE 写入器:所有检查在流内进行,通过 SSE event 返回结果
|
||||
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
|
||||
sendEvent := func(event string, data map[string]interface{}) {
|
||||
d, _ := json.Marshal(data)
|
||||
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, string(d))
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
// 保存销假日志
|
||||
saveLog := func(isSuccess bool, errMsg, title string) {
|
||||
logEntry := model.CpLeaveLog{
|
||||
UserID: userID,
|
||||
LeaveID: req.LeaveID,
|
||||
Title: title,
|
||||
SchoolName: user.SchoolName,
|
||||
Action: model.LeaveActionReport,
|
||||
IsSuccess: isSuccess,
|
||||
ErrorMessage: errMsg,
|
||||
}
|
||||
database.DB.Create(&logEntry)
|
||||
}
|
||||
|
||||
// VIP 判定:VIP 且未过期则免扣次数直接执行
|
||||
isVip := user.VipExpireAt != nil && user.VipExpireAt.After(time.Now())
|
||||
|
||||
// 本次销假扣减额度(后台可配置,允许小数与 0=不扣费)
|
||||
deduct := getReportDeduct()
|
||||
|
||||
// 检查可用次数(VIP 免检查;0 额度时恒放行)
|
||||
if !isVip && user.SignCount < deduct {
|
||||
slog.Warn("销假次数不足,拒绝执行", "userId", userID, "signCount", user.SignCount, "deduct", deduct)
|
||||
sendEvent("task_error", map[string]interface{}{"message": "可用次数不足,请购买CDK或通过邀请获得次数"})
|
||||
return
|
||||
}
|
||||
|
||||
// 限流:同一用户(销假为同步执行,无任务维度,按用户维度限流)
|
||||
rateKey := fmt.Sprintf("leave:%d", userID)
|
||||
rules := []ratelimit.Rule{
|
||||
{Limit: 3, Window: 2 * time.Minute, Label: "2m"},
|
||||
{Limit: 6, Window: 1 * time.Hour, Label: "1h"},
|
||||
{Limit: 10, Window: 24 * time.Hour, Label: "1d"},
|
||||
}
|
||||
if ok, msg := ratelimit.AllowMulti(rateKey, rules); !ok {
|
||||
slog.Warn("销假触发限流", "userId", userID, "msg", msg)
|
||||
sendEvent("task_error", map[string]interface{}{"message": msg, "rateLimit": true})
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 连接成功
|
||||
sendEvent("connecting", map[string]interface{}{"status": "connecting", "message": "正在连接今日校园..."})
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 新套(leave-new):独立销假链路(详情校验 → 销假提交)
|
||||
if schoolLeaveFlavor(&user, cookieMap) == cpd.LeaveFlavorNew {
|
||||
sendEvent("fetching_detail", map[string]interface{}{"status": "fetching_detail", "message": "正在获取请假详情..."})
|
||||
title := "销假"
|
||||
if d, derr := cpd.FetchLeaveNewDetail(cookieMap, host, req.LeaveID); derr == nil {
|
||||
title = leaveLogTitle(&cpd.LeaveDetail{LeaveType: d.TopicName}, req.LeaveID)
|
||||
}
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在提交销假..."})
|
||||
ok, errMsg, needReLogin := leaveNewExecuteReport(&user, cookieMap, host,
|
||||
req.LeaveID, req.Address, req.Longitude, req.Latitude, req.ImageURL, req.ApproverWid)
|
||||
if !ok {
|
||||
slog.Error("销假失败(新套)", "userId", userID, "leaveId", req.LeaveID, "error", errMsg)
|
||||
saveLog(false, errMsg, title)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg, "needReLogin": needReLogin})
|
||||
return
|
||||
}
|
||||
saveLog(true, "", title)
|
||||
if !isVip {
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count >= ?", userID, deduct).
|
||||
Update("sign_count", gorm.Expr("sign_count - ?", deduct))
|
||||
msg := "销假成功!(已扣 " + fmtDeduct(deduct) + " 次)"
|
||||
if deduct <= 0 {
|
||||
msg = "销假成功!(免扣次数)"
|
||||
}
|
||||
sendEvent("success", map[string]interface{}{"status": "success", "message": msg})
|
||||
} else {
|
||||
sendEvent("success", map[string]interface{}{"status": "success", "message": "销假成功!(VIP 免扣次数)"})
|
||||
}
|
||||
slog.Info("销假成功(新套)", "userId", userID, "leaveId", req.LeaveID, "title", title, "isVip", isVip)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 获取请假详情
|
||||
sendEvent("fetching_detail", map[string]interface{}{"status": "fetching_detail", "message": "正在获取请假详情..."})
|
||||
detail, err := cpd.FetchLeaveDetail(cookieMap, host, req.LeaveID)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("获取请假详情cookie过期,尝试自动刷新", "userId", userID, "leaveId", req.LeaveID)
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
detail, err = cpd.FetchLeaveDetail(cookieMap, host, req.LeaveID)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := "获取请假详情失败: " + err.Error()
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
errMsg = "登录凭证已过期,请重新登录"
|
||||
}
|
||||
slog.Error("获取请假详情失败", "userId", userID, "leaveId", req.LeaveID, "error", err)
|
||||
saveLog(false, errMsg, leaveLogTitle(detail, ""))
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg, "needReLogin": errors.Is(err, ErrPasswordChanged)})
|
||||
return
|
||||
}
|
||||
title := leaveLogTitle(detail, req.LeaveID)
|
||||
|
||||
// 销假地址:用户选择/填写的优先,否则兜底第一个规定销假位置地址;两者皆空时阻止提交
|
||||
if req.Address == "" && len(detail.ReportPlaces) == 0 {
|
||||
errMsg := "该请假未设置规定销假位置,请填写销假地址"
|
||||
saveLog(false, errMsg, title)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
|
||||
// 审批人:请假类型要求销假审批(reportApplyFlow=1)时必须选择审批人
|
||||
if detail.ReportApplyFlow && req.ApproverWid == "" {
|
||||
errMsg := "该请假类型销假需要选择审批人,请重新选择"
|
||||
saveLog(false, errMsg, title)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg, "needApprover": true})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. 构造表单并提交销假
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在提交销假..."})
|
||||
form := cpd.BuildLeaveReportForm(detail, req.Address, req.ImageURL, req.ApproverWid)
|
||||
err = cpd.SubmitLeaveReport(cookieMap, host, form, req.Longitude, req.Latitude, user.MobileCode, user.StudentID)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("提交销假cookie过期,尝试自动刷新", "userId", userID, "leaveId", req.LeaveID)
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
err = cpd.SubmitLeaveReport(cookieMap, host, form, req.Longitude, req.Latitude, user.MobileCode, user.StudentID)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := "销假失败: " + err.Error()
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
errMsg = "登录凭证已过期,请重新登录"
|
||||
}
|
||||
slog.Error("销假失败", "userId", userID, "leaveId", req.LeaveID, "error", err)
|
||||
saveLog(false, errMsg, title)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg, "needReLogin": errors.Is(err, ErrPasswordChanged)})
|
||||
return
|
||||
}
|
||||
|
||||
// 4. 成功:写日志 + 扣减可用次数(VIP 有效期内免扣)
|
||||
saveLog(true, "", title)
|
||||
if !isVip {
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count >= ?", userID, deduct).
|
||||
Update("sign_count", gorm.Expr("sign_count - ?", deduct))
|
||||
msg := "销假成功!(已扣 " + fmtDeduct(deduct) + " 次)"
|
||||
if deduct <= 0 {
|
||||
msg = "销假成功!(免扣次数)"
|
||||
}
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": msg,
|
||||
})
|
||||
} else {
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "销假成功!(VIP 免扣次数)",
|
||||
})
|
||||
}
|
||||
|
||||
slog.Info("销假成功", "userId", userID, "leaveId", req.LeaveID, "title", title, "isVip", isVip)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetLeaveApprovers 获取销假可选审批人(leaveType.reportApplyFlow=1 的请假类型)。
|
||||
// 请求:{ leaveId };服务端自行取详情中的 leaveType/起止时间,前端无需重复传递。
|
||||
func GetLeaveApprovers(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
|
||||
var req struct {
|
||||
LeaveID string `json:"leaveId"`
|
||||
}
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
req.LeaveID = strings.TrimSpace(req.LeaveID)
|
||||
if req.LeaveID == "" {
|
||||
return utils.FailParam(c, "leaveId 不能为空")
|
||||
}
|
||||
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
}
|
||||
if user.Cookie == "" {
|
||||
return utils.Fail(c, 400, "请先登录")
|
||||
}
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 新套:销假确认人(getReportApprovers by leaveId)
|
||||
if schoolLeaveFlavor(&user, cookieMap) == cpd.LeaveFlavorNew {
|
||||
approvers, err := fetchLeaveNewReportApprovers(cookieMap, host, req.LeaveID, &user)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
approvers, err = fetchLeaveNewReportApprovers(cookieMap, host, req.LeaveID, &user)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取销假审批人失败(新套)", "userId", userID, "leaveId", req.LeaveID, "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取销假审批人失败: "+err.Error())
|
||||
}
|
||||
return utils.Success(c, approvers)
|
||||
}
|
||||
|
||||
detail, err := cpd.FetchLeaveDetail(cookieMap, host, req.LeaveID)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
detail, err = cpd.FetchLeaveDetail(cookieMap, host, req.LeaveID)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取请假详情失败(审批人)", "userId", userID, "leaveId", req.LeaveID, "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取请假详情失败: "+err.Error())
|
||||
}
|
||||
if !detail.ReportApplyFlow {
|
||||
return utils.Success(c, []cpd.LeaveApprover{})
|
||||
}
|
||||
|
||||
approvers, err := cpd.FetchReportApprovers(cookieMap, host, detail.LeaveCodeNum, detail.StartTime, detail.EndTime)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
approvers, err = cpd.FetchReportApprovers(cookieMap, host, detail.LeaveCodeNum, detail.StartTime, detail.EndTime)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取销假审批人失败", "userId", userID, "leaveId", req.LeaveID, "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取销假审批人失败: "+err.Error())
|
||||
}
|
||||
|
||||
return utils.Success(c, approvers)
|
||||
}
|
||||
|
||||
// leaveLogTitle 销假日志标题:请假类型名 + "销假";类型名缺失时兜底用 leaveId 前缀避免标题为空
|
||||
func leaveLogTitle(detail *cpd.LeaveDetail, leaveID string) string {
|
||||
if detail != nil && detail.LeaveType != "" {
|
||||
return detail.LeaveType + "销假"
|
||||
}
|
||||
if leaveID != "" {
|
||||
return "销假(" + leaveID + ")"
|
||||
}
|
||||
return "销假"
|
||||
}
|
||||
|
||||
// ListLeaveLogs 获取销假日志列表
|
||||
func ListLeaveLogs(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
|
||||
var logs []model.CpLeaveLog
|
||||
database.DB.Where("user_id = ?", userID).
|
||||
Order("created_at DESC").
|
||||
Limit(10).
|
||||
Find(&logs)
|
||||
|
||||
return utils.Success(c, logs)
|
||||
}
|
||||
|
||||
// DeleteLeaveLog 删除销假日志
|
||||
func DeleteLeaveLog(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
id := c.Params("id")
|
||||
|
||||
var log model.CpLeaveLog
|
||||
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&log).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return utils.Fail(c, 404, "日志不存在")
|
||||
}
|
||||
return utils.FailServer(c, "查询失败")
|
||||
}
|
||||
|
||||
database.DB.Delete(&log)
|
||||
return utils.Success(c, nil)
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/ratelimit"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
"cpdaily-new/internal/utils"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ---------- 请假申请 ----------
|
||||
|
||||
// loadLeaveUser 读取当前用户(请假链路公共前置)
|
||||
func loadLeaveUser(c *fiber.Ctx) (*model.SysUser, error) {
|
||||
userID := c.Locals("userId").(uint)
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return nil, fmt.Errorf("用户不存在")
|
||||
}
|
||||
if user.Cookie == "" {
|
||||
return nil, fmt.Errorf("请先登录")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetLeaveTypes 获取请假类型列表(含全部权威开关,前端据此渲染表单)。
|
||||
// 按学校应用的套件分流:新套(leave-new)翻译为同一契约返回。
|
||||
func GetLeaveTypes(c *fiber.Ctx) error {
|
||||
user, err := loadLeaveUser(c)
|
||||
if err != nil {
|
||||
return utils.FailAuth(c, err.Error())
|
||||
}
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
flavor := schoolLeaveFlavor(user, cookieMap)
|
||||
|
||||
var types []cpd.LeaveType
|
||||
if flavor == cpd.LeaveFlavorNew {
|
||||
types, err = fetchLeaveNewTypesWithDetail(cookieMap, host, user)
|
||||
} else {
|
||||
types, err = cpd.FetchLeaveTypes(cookieMap, host)
|
||||
}
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
if flavor == cpd.LeaveFlavorNew {
|
||||
types, err = fetchLeaveNewTypesWithDetail(cookieMap, host, user)
|
||||
} else {
|
||||
types, err = cpd.FetchLeaveTypes(cookieMap, host)
|
||||
}
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取请假类型失败", "userId", user.ID, "flavor", flavor.String(), "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取请假类型失败: "+err.Error())
|
||||
}
|
||||
|
||||
return utils.Success(c, types)
|
||||
}
|
||||
|
||||
// GetLeaveApplyApprovers 获取请假可选审批人(needApproval=1 的类型)。
|
||||
// 请求:{ leaveType, startTime, endTime }(与销假审批人接口区分:此处选择类型发生在提交前)。
|
||||
// 新套额外返回 flowData(提交请假时原样回传),前端不透明缓存即可。
|
||||
func GetLeaveApplyApprovers(c *fiber.Ctx) error {
|
||||
user, err := loadLeaveUser(c)
|
||||
if err != nil {
|
||||
return utils.FailAuth(c, err.Error())
|
||||
}
|
||||
|
||||
var req struct {
|
||||
LeaveType int `json:"leaveType"`
|
||||
StartTime string `json:"startTime"`
|
||||
EndTime string `json:"endTime"`
|
||||
}
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
if req.StartTime == "" || req.EndTime == "" {
|
||||
return utils.FailParam(c, "开始/结束时间不能为空")
|
||||
}
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
flavor := schoolLeaveFlavor(user, cookieMap)
|
||||
|
||||
if flavor == cpd.LeaveFlavorNew {
|
||||
res, err := fetchLeaveNewApplyApprovers(cookieMap, host, req.LeaveType, req.StartTime, req.EndTime)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
res, err = fetchLeaveNewApplyApprovers(cookieMap, host, req.LeaveType, req.StartTime, req.EndTime)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取请假审批人失败(新套)", "userId", user.ID, "leaveType", req.LeaveType, "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取请假审批人失败: "+err.Error())
|
||||
}
|
||||
// 保持与旧套一致的数组契约(flowData 由服务端在执行时重新获取,前端无需感知)
|
||||
return utils.Success(c, res.Approvers)
|
||||
}
|
||||
|
||||
approvers, err := cpd.FetchReportApprovers(cookieMap, host, req.LeaveType, req.StartTime, req.EndTime)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
approvers, err = cpd.FetchReportApprovers(cookieMap, host, req.LeaveType, req.StartTime, req.EndTime)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取请假审批人失败", "userId", user.ID, "leaveType", req.LeaveType, "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取请假审批人失败: "+err.Error())
|
||||
}
|
||||
|
||||
return utils.Success(c, approvers)
|
||||
}
|
||||
|
||||
// ExecuteLeaveApplyRequest 请假申请执行参数
|
||||
type ExecuteLeaveApplyRequest struct {
|
||||
LeaveType int `json:"leaveType"` // 类型编码
|
||||
StartTime string `json:"startTime"` // yyyy-MM-dd HH:mm:ss
|
||||
EndTime string `json:"endTime"` // yyyy-MM-dd HH:mm:ss
|
||||
LeaveReason string `json:"leaveReason"` // 请假原因
|
||||
OutStatus bool `json:"outStatus"` // 是否离校
|
||||
UrgencyMobile string `json:"urgencyMobile"` // 紧急联系人(离校必填)
|
||||
Address string `json:"address"` // 目的地(离校必填)
|
||||
DetailAddress string `json:"detailAddress"` // 详细地址(离校必填)
|
||||
Longitude string `json:"longitude"` // 定位经度
|
||||
Latitude string `json:"latitude"` // 定位纬度
|
||||
LocationAddr string `json:"locationAddr"` // 定位地址
|
||||
ImageURLs []string `json:"imageUrls"` // 附件图片 URL 列表(可选,最多4张且不超学校上限)
|
||||
ImageURL string `json:"imageUrl"` // 兼容旧前端:单附件 URL(与 imageUrls 合并去重)
|
||||
ApproverWid string `json:"approverWid"` // 审批人 userWid(候选为空时可不传)
|
||||
ApproverId string `json:"approverId"` // 审批人 userId
|
||||
ApproverName string `json:"approverName"` // 审批人姓名
|
||||
CcUsers []cpd.LeaveApprover `json:"ccUsers"` // 抄送人(非必填,候选取自审批人列表)
|
||||
SignatureURL string `json:"signatureUrl"` // 手写承诺书签名图 URL(requireSign=1 的类型必填)
|
||||
}
|
||||
|
||||
// mergeApplyImageURLs 合并 imageUrls 与兼容字段 imageUrl,保序去重并剔除空串
|
||||
func mergeApplyImageURLs(urls []string, legacy string) []string {
|
||||
out := make([]string, 0, len(urls)+1)
|
||||
seen := make(map[string]bool, len(urls)+1)
|
||||
for _, u := range append(append([]string{}, urls...), legacy) {
|
||||
u = strings.TrimSpace(u)
|
||||
if u == "" || seen[u] {
|
||||
continue
|
||||
}
|
||||
seen[u] = true
|
||||
out = append(out, u)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ExecuteLeaveApply 执行请假申请(SSE 同步执行:checkOnceLeave → 提交)。
|
||||
// 事件流:connecting → submitting → success / task_error
|
||||
func ExecuteLeaveApply(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
|
||||
var req ExecuteLeaveApplyRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
req.StartTime = strings.TrimSpace(req.StartTime)
|
||||
req.EndTime = strings.TrimSpace(req.EndTime)
|
||||
req.LeaveReason = strings.TrimSpace(req.LeaveReason)
|
||||
req.Longitude = strings.TrimSpace(req.Longitude)
|
||||
req.Latitude = strings.TrimSpace(req.Latitude)
|
||||
req.LocationAddr = strings.TrimSpace(req.LocationAddr)
|
||||
req.ApproverWid = strings.TrimSpace(req.ApproverWid)
|
||||
// 附件:多图字段 + 旧前端兼容单图字段,去重合并
|
||||
imageURLs := mergeApplyImageURLs(req.ImageURLs, req.ImageURL)
|
||||
if len(imageURLs) > cpd.LeaveMaxAttachCount(0) {
|
||||
return utils.FailParam(c, "附件最多 4 张")
|
||||
}
|
||||
|
||||
if req.StartTime == "" || req.EndTime == "" {
|
||||
return utils.FailParam(c, "开始/结束时间不能为空")
|
||||
}
|
||||
if req.LeaveReason == "" {
|
||||
return utils.FailParam(c, "请假原因不能为空")
|
||||
}
|
||||
if req.Longitude == "" || req.Latitude == "" {
|
||||
return utils.FailParam(c, "定位经纬度不能为空")
|
||||
}
|
||||
if req.LocationAddr == "" {
|
||||
return utils.FailParam(c, "定位地址不能为空")
|
||||
}
|
||||
if req.OutStatus {
|
||||
if strings.TrimSpace(req.UrgencyMobile) == "" {
|
||||
return utils.FailParam(c, "紧急联系人手机号不能为空")
|
||||
}
|
||||
if strings.TrimSpace(req.Address) == "" {
|
||||
return utils.FailParam(c, "目的地不能为空")
|
||||
}
|
||||
if strings.TrimSpace(req.DetailAddress) == "" {
|
||||
return utils.FailParam(c, "详细地址不能为空")
|
||||
}
|
||||
}
|
||||
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
}
|
||||
if user.Cookie == "" {
|
||||
return utils.Fail(c, 400, "请先登录")
|
||||
}
|
||||
// 设备码后端硬校验:请假执行需携带设备码(对齐打卡侧拦截语义),
|
||||
// 账密登录创建的账号可能未绑定设备码,空设备码会触发学校端风控异常
|
||||
if strings.TrimSpace(user.MobileCode) == "" {
|
||||
return utils.Fail(c, 400, "请先在个人中心绑定设备码后再执行请假")
|
||||
}
|
||||
|
||||
// SSE 头
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
c.Set("Cache-Control", "no-cache")
|
||||
c.Set("Connection", "keep-alive")
|
||||
c.Set("X-Accel-Buffering", "no")
|
||||
|
||||
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
|
||||
sendEvent := func(event string, data map[string]interface{}) {
|
||||
d, _ := json.Marshal(data)
|
||||
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, string(d))
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
// 请假记录 ID:申请时平台尚未生成,用时间戳占位(日志/展示用)
|
||||
applyLeaveID := "apply_" + strconv.FormatInt(time.Now().Unix(), 10)
|
||||
|
||||
// 类型配置(拿 needApproval/enableAttach/mustOut 等权威开关做服务端校验)
|
||||
title := leaveApplyLogTitle(req.LeaveType, req.StartTime, req.EndTime)
|
||||
saveLog := func(isSuccess bool, errMsg string) {
|
||||
logEntry := model.CpLeaveLog{
|
||||
UserID: userID,
|
||||
LeaveID: applyLeaveID,
|
||||
Title: title,
|
||||
SchoolName: user.SchoolName,
|
||||
Action: model.LeaveActionApply,
|
||||
IsSuccess: isSuccess,
|
||||
ErrorMessage: errMsg,
|
||||
}
|
||||
database.DB.Create(&logEntry)
|
||||
}
|
||||
|
||||
isVip := user.VipExpireAt != nil && user.VipExpireAt.After(time.Now())
|
||||
|
||||
// 本次请假扣减额度(后台可配置,允许小数与 0=不扣费)
|
||||
deduct := getLeaveDeduct()
|
||||
|
||||
if !isVip && user.SignCount < deduct {
|
||||
slog.Warn("请假次数不足,拒绝执行", "userId", userID, "signCount", user.SignCount, "deduct", deduct)
|
||||
sendEvent("task_error", map[string]interface{}{"message": "可用次数不足,请购买CDK或通过邀请获得次数"})
|
||||
return
|
||||
}
|
||||
|
||||
// 限流:与销假同规则(同一用户维度)
|
||||
rateKey := fmt.Sprintf("leave-apply:%d", userID)
|
||||
rules := []ratelimit.Rule{
|
||||
{Limit: 3, Window: 2 * time.Minute, Label: "2m"},
|
||||
{Limit: 6, Window: 1 * time.Hour, Label: "1h"},
|
||||
{Limit: 10, Window: 24 * time.Hour, Label: "1d"},
|
||||
}
|
||||
if ok, msg := ratelimit.AllowMulti(rateKey, rules); !ok {
|
||||
slog.Warn("请假触发限流", "userId", userID, "msg", msg)
|
||||
sendEvent("task_error", map[string]interface{}{"message": msg, "rateLimit": true})
|
||||
return
|
||||
}
|
||||
|
||||
sendEvent("connecting", map[string]interface{}{"status": "connecting", "message": "正在连接今日校园..."})
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 新套(leave-new):独立请假链路(类型详情复核 + 审批流 + 明文 JSON 提交)
|
||||
if schoolLeaveFlavor(&user, cookieMap) == cpd.LeaveFlavorNew {
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在提交请假申请..."})
|
||||
ok, errMsg, needReLogin, needApprover := leaveNewExecuteApply(&user, cookieMap, host, req, imageURLs)
|
||||
if !ok {
|
||||
slog.Error("请假申请失败(新套)", "userId", userID, "error", errMsg)
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{
|
||||
"status": "error",
|
||||
"message": errMsg,
|
||||
"needReLogin": needReLogin,
|
||||
"needApprover": needApprover,
|
||||
})
|
||||
return
|
||||
}
|
||||
saveLog(true, "")
|
||||
if !isVip {
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count >= ?", userID, deduct).
|
||||
Update("sign_count", gorm.Expr("sign_count - ?", deduct))
|
||||
msg := "请假申请提交成功!(已扣 " + fmtDeduct(deduct) + " 次)"
|
||||
if deduct <= 0 {
|
||||
msg = "请假申请提交成功!(免扣次数)"
|
||||
}
|
||||
sendEvent("success", map[string]interface{}{"status": "success", "message": msg})
|
||||
} else {
|
||||
sendEvent("success", map[string]interface{}{"status": "success", "message": "请假申请提交成功!(VIP 免扣次数)"})
|
||||
}
|
||||
slog.Info("请假申请成功(新套)", "userId", userID, "leaveType", req.LeaveType, "start", req.StartTime, "end", req.EndTime, "isVip", isVip)
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 获取类型配置(服务端复核开关,避免前端被绕过)
|
||||
cfg, err := cpd.FetchLeaveTypeCfg(cookieMap, host, req.LeaveType)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
cfg, err = cpd.FetchLeaveTypeCfg(cookieMap, host, req.LeaveType)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := "获取请假类型配置失败: " + err.Error()
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
errMsg = "登录凭证已过期,请重新登录"
|
||||
}
|
||||
slog.Error("获取请假类型配置失败", "userId", userID, "leaveType", req.LeaveType, "error", err)
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg, "needReLogin": errors.Is(err, ErrPasswordChanged)})
|
||||
return
|
||||
}
|
||||
if cfg.DisableTime == 1 {
|
||||
errMsg := "该请假类型当前不可用,请选择其他类型"
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
if cfg.ReasonWordLimit > 0 && len([]rune(req.LeaveReason)) < cfg.ReasonWordLimit {
|
||||
errMsg := fmt.Sprintf("请假原因至少 %d 字", cfg.ReasonWordLimit)
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
// 审批人:needApproval=1 且学校配置了候选审批人时必选;
|
||||
// 候选列表为空(学校未配置审批节点人员,如 ysdwl「大四学生请假」)时允许不选,跳过即可
|
||||
if cfg.NeedApproval == 1 && req.ApproverWid == "" {
|
||||
candidates, err := cpd.FetchReportApprovers(cookieMap, host, req.LeaveType, req.StartTime, req.EndTime)
|
||||
if err != nil {
|
||||
errMsg := "获取请假审批人失败: " + err.Error()
|
||||
slog.Warn("校验审批人候选失败", "userId", userID, "error", err)
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
if len(candidates) > 0 {
|
||||
errMsg := "该请假类型需要选择审批人"
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg, "needApprover": true})
|
||||
return
|
||||
}
|
||||
slog.Info("该类型无候选审批人,允许不选提交", "userId", userID, "leaveType", req.LeaveType)
|
||||
}
|
||||
|
||||
// 附件复核:类型开关 + 数量上限(学校配置为准,产品上限 4 张)
|
||||
// 注意:实测多所旧套学校 enableAttach 恒为 0(该字段在旧套不代表"可传附件"),
|
||||
// 是否允许以 attachmentNumberLimit>0 为准;仅当两者都表明不可用时才拒绝。
|
||||
if len(imageURLs) > 0 {
|
||||
if cfg.EnableAttach != 1 && cfg.AttachmentNumberLimit <= 0 {
|
||||
errMsg := "该请假类型不支持上传附件"
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
if maxN := cpd.LeaveMaxAttachCount(cfg.AttachmentNumberLimit); len(imageURLs) > maxN {
|
||||
errMsg := fmt.Sprintf("附件最多 %d 张", maxN)
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 可请假检查
|
||||
if err := cpd.CheckOnceLeave(cookieMap, host); err != nil {
|
||||
errMsg := "当前不可请假: " + err.Error()
|
||||
slog.Warn("checkOnceLeave 拒绝", "userId", userID, "error", err)
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. 构造表单并提交
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在提交请假申请..."})
|
||||
p := cpd.LeaveApplyParams{
|
||||
LeaveType: req.LeaveType,
|
||||
StartTime: req.StartTime,
|
||||
EndTime: req.EndTime,
|
||||
LeaveReason: req.LeaveReason,
|
||||
OutStatus: req.OutStatus,
|
||||
UrgencyMobile: req.UrgencyMobile,
|
||||
Address: req.Address,
|
||||
DetailAddress: req.DetailAddress,
|
||||
Longitude: req.Longitude,
|
||||
Latitude: req.Latitude,
|
||||
LocationAddr: req.LocationAddr,
|
||||
ImageURLs: imageURLs,
|
||||
ApproverWid: req.ApproverWid,
|
||||
ApproverId: req.ApproverId,
|
||||
ApproverName: req.ApproverName,
|
||||
CcUsers: req.CcUsers,
|
||||
}
|
||||
form := cpd.BuildLeaveApplyForm(p, user.MobileCode, "15", "9.9.6")
|
||||
err = cpd.SubmitLeaveApply(cookieMap, host, form, req.Longitude, req.Latitude, user.MobileCode, user.StudentID)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("提交请假cookie过期,尝试自动刷新", "userId", userID)
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
err = cpd.SubmitLeaveApply(cookieMap, host, form, req.Longitude, req.Latitude, user.MobileCode, user.StudentID)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := "请假申请失败: " + err.Error()
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
errMsg = "登录凭证已过期,请重新登录"
|
||||
}
|
||||
slog.Error("请假申请失败", "userId", userID, "error", err)
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg, "needReLogin": errors.Is(err, ErrPasswordChanged)})
|
||||
return
|
||||
}
|
||||
|
||||
// 4. 成功:写日志 + 扣减可用次数(VIP 有效期内免扣)
|
||||
saveLog(true, "")
|
||||
if !isVip {
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count >= ?", userID, deduct).
|
||||
Update("sign_count", gorm.Expr("sign_count - ?", deduct))
|
||||
msg := "请假申请提交成功!(已扣 " + fmtDeduct(deduct) + " 次)"
|
||||
if deduct <= 0 {
|
||||
msg = "请假申请提交成功!(免扣次数)"
|
||||
}
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": msg,
|
||||
})
|
||||
} else {
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "请假申请提交成功!(VIP 免扣次数)",
|
||||
})
|
||||
}
|
||||
|
||||
slog.Info("请假申请成功", "userId", userID, "leaveType", req.LeaveType, "start", req.StartTime, "end", req.EndTime, "isVip", isVip)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// leaveApplyLogTitle 请假日志标题:类型名由前端传入 code 时的兜底为「请假」
|
||||
func leaveApplyLogTitle(leaveType int, startTime, endTime string) string {
|
||||
title := fmt.Sprintf("请假申请(类型%d)", leaveType)
|
||||
if startTime != "" && endTime != "" {
|
||||
title = fmt.Sprintf("请假申请 %s ~ %s", startTime, endTime)
|
||||
}
|
||||
return title
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
)
|
||||
|
||||
// TestMergeApplyImageURLs 附件合并:多图字段 + 旧前端兼容单图字段,
|
||||
// 保序去重、剔除空串与首尾空白(避免旧缓存包附件被静默丢弃或重复提交)。
|
||||
func TestMergeApplyImageURLs(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
urls []string
|
||||
legacy string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "仅多图字段",
|
||||
urls: []string{"a", "b"},
|
||||
legacy: "",
|
||||
want: []string{"a", "b"},
|
||||
},
|
||||
{
|
||||
name: "仅旧单图字段",
|
||||
urls: nil,
|
||||
legacy: "a",
|
||||
want: []string{"a"},
|
||||
},
|
||||
{
|
||||
name: "旧字段与多图重复应去重",
|
||||
urls: []string{"a", "b"},
|
||||
legacy: "a",
|
||||
want: []string{"a", "b"},
|
||||
},
|
||||
{
|
||||
name: "旧字段不在多图中应追加",
|
||||
urls: []string{"a"},
|
||||
legacy: "c",
|
||||
want: []string{"a", "c"},
|
||||
},
|
||||
{
|
||||
name: "空串与空白剔除",
|
||||
urls: []string{"", " ", "a"},
|
||||
legacy: " ",
|
||||
want: []string{"a"},
|
||||
},
|
||||
{
|
||||
name: "首尾空白裁剪",
|
||||
urls: []string{" a ", " b"},
|
||||
legacy: "",
|
||||
want: []string{"a", "b"},
|
||||
},
|
||||
{
|
||||
name: "全部为空",
|
||||
urls: []string{""},
|
||||
legacy: "",
|
||||
want: []string{},
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := mergeApplyImageURLs(c.urls, c.legacy)
|
||||
if len(got) != len(c.want) {
|
||||
t.Fatalf("mergeApplyImageURLs(%v, %q) = %v, want %v", c.urls, c.legacy, got, c.want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != c.want[i] {
|
||||
t.Fatalf("mergeApplyImageURLs(%v, %q) = %v, want %v", c.urls, c.legacy, got, c.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLeaveNewToLeaveTypesAttachGating 新套类型翻译:材料区不可见时不得带出数量上限,
|
||||
// 否则前端按「上限>0」的条件会误显示上传入口(旧套学校 enableAttach 恒为 0 的同类问题)。
|
||||
func TestLeaveNewToLeaveTypesAttachGating(t *testing.T) {
|
||||
types := []cpd.LeaveNewType{
|
||||
{TypeWid: 1, TypeName: "可见类型"},
|
||||
{TypeWid: 2, TypeName: "不可见类型"},
|
||||
}
|
||||
details := map[int]*cpd.LeaveNewFormDetail{
|
||||
1: {TypeName: "可见类型", IsVisibledEvidenceFile: true, EvidenceFileCountMax: 4},
|
||||
2: {TypeName: "不可见类型", IsVisibledEvidenceFile: false, EvidenceFileCountMax: 10},
|
||||
}
|
||||
out := leaveNewToLeaveTypes(types, func(wid int) *cpd.LeaveNewFormDetail { return details[wid] })
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("期望 2 个类型, got %d", len(out))
|
||||
}
|
||||
if out[0].EnableAttach != 1 || out[0].AttachmentNumberLimit != 4 {
|
||||
t.Errorf("可见类型应带出开关与上限: %+v", out[0])
|
||||
}
|
||||
if out[1].EnableAttach != 0 || out[1].AttachmentNumberLimit != 0 {
|
||||
t.Errorf("不可见类型不应带出上限(否则前端误显示): %+v", out[1])
|
||||
}
|
||||
}
|
||||
|
||||
// TestLeaveNewRequireSignMapping 手写承诺书需求透传:新套 queryLeaveType.isSign → LeaveType.requireSign
|
||||
func TestLeaveNewRequireSignMapping(t *testing.T) {
|
||||
types := []cpd.LeaveNewType{
|
||||
{TypeWid: 8484, TypeName: "事假", IsSign: true},
|
||||
{TypeWid: 6185, TypeName: "病假", IsSign: false},
|
||||
}
|
||||
out := leaveNewToLeaveTypes(types, func(int) *cpd.LeaveNewFormDetail { return nil })
|
||||
if out[0].RequireSign != 1 {
|
||||
t.Errorf("isSign=true 应标记 requireSign=1: %+v", out[0])
|
||||
}
|
||||
if out[1].RequireSign != 0 {
|
||||
t.Errorf("isSign=false 不应标记 requireSign: %+v", out[1])
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildLeaveNewApplyFormSignature 手写承诺书作为 attachs 中 isStuSign 项附加
|
||||
func TestBuildLeaveNewApplyFormSignature(t *testing.T) {
|
||||
// 无签名时不应出现 isStuSign 项
|
||||
without := cpd.BuildLeaveNewApplyForm(cpd.LeaveNewApplyParams{TypeWid: 1, ImageURLs: []string{"https://obs/a.jpg"}})
|
||||
as := without["attachs"].([]map[string]interface{})
|
||||
if len(as) != 1 {
|
||||
t.Fatalf("无签名时期望 1 个附件, got %d", len(as))
|
||||
}
|
||||
if _, ok := as[0]["isStuSign"]; ok {
|
||||
t.Errorf("普通附件不应带 isStuSign")
|
||||
}
|
||||
|
||||
// 有签名时附加带 isStuSign 的项
|
||||
with := cpd.BuildLeaveNewApplyForm(cpd.LeaveNewApplyParams{TypeWid: 1, SignatureURL: "https://obs/newBucket/sign.jpg?x=1"})
|
||||
as2 := with["attachs"].([]map[string]interface{})
|
||||
if len(as2) != 1 {
|
||||
t.Fatalf("有签名时期望 1 个附件, got %d", len(as2))
|
||||
}
|
||||
sig := as2[0]
|
||||
if sig["isStuSign"] != true {
|
||||
t.Errorf("签名项应带 isStuSign=true: %+v", sig)
|
||||
}
|
||||
if sig["attachName"] != "学生手写承诺书" {
|
||||
t.Errorf("签名项 attachName 应为主学生手写承诺书: %+v", sig)
|
||||
}
|
||||
if sig["obsKey"] != "newBucket/sign.jpg" {
|
||||
t.Errorf("签名项 obsKey 应从 URL 推导: %+v", sig)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/model"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
)
|
||||
|
||||
// 请假应用套件分流(新旧两套 API 并存):
|
||||
//
|
||||
// 新套 wec-counselor-leave-new-apps(「请销假」应用,部分学校已迁移,旧前缀被 420 拦截)
|
||||
// 旧套 wec-counselor-leave-apps(「请假」应用,默认)
|
||||
//
|
||||
// 分流依据:辅导猫 getAppInfos 返回的本校应用列表(openUrl 指向哪套);
|
||||
// 探测失败时试探新套端点兜底;结果按学校缓存 30 分钟。
|
||||
|
||||
type leaveFlavorCacheEntry struct {
|
||||
flavor cpd.LeaveAppFlavor
|
||||
expire time.Time
|
||||
}
|
||||
|
||||
var leaveFlavorCache sync.Map // schoolID -> leaveFlavorCacheEntry
|
||||
|
||||
const leaveFlavorCacheTTL = 30 * time.Minute
|
||||
|
||||
// schoolLeaveFlavor 获取(并缓存)学校请假应用套件类型
|
||||
func schoolLeaveFlavor(user *model.SysUser, cookieMap map[string]string) cpd.LeaveAppFlavor {
|
||||
if v, ok := leaveFlavorCache.Load(user.SchoolID); ok {
|
||||
if e, ok2 := v.(leaveFlavorCacheEntry); ok2 && time.Now().Before(e.expire) {
|
||||
return e.flavor
|
||||
}
|
||||
}
|
||||
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
flavor, openURL := cpd.FetchLeaveAppFlavor(cookieMap, host)
|
||||
if flavor == cpd.LeaveFlavorUnknown {
|
||||
// getAppInfos 失败/无请假应用:试探新套端点兜底
|
||||
if cpd.PingLeaveNew(cookieMap, host) {
|
||||
flavor = cpd.LeaveFlavorNew
|
||||
} else {
|
||||
// 默认按旧套处理(cookie 过期等场景下旧套错误的语义更准确)
|
||||
flavor = cpd.LeaveFlavorOld
|
||||
}
|
||||
}
|
||||
slog.Info("请假应用套件分流", "schoolId", user.SchoolID, "flavor", flavor.String(), "openUrl", openURL)
|
||||
leaveFlavorCache.Store(user.SchoolID, leaveFlavorCacheEntry{flavor: flavor, expire: time.Now().Add(leaveFlavorCacheTTL)})
|
||||
return flavor
|
||||
}
|
||||
|
||||
// invalidateLeaveFlavor 清缓存(应用迁移后可强制重探)
|
||||
func invalidateLeaveFlavor(schoolID string) {
|
||||
leaveFlavorCache.Delete(schoolID)
|
||||
}
|
||||
|
||||
// ---------- 新套 → 现有前端契约的翻译 ----------
|
||||
|
||||
// leaveNewToLeaveTypes 新套类型列表 → 旧契约 LeaveType(前端零改动消费)
|
||||
func leaveNewToLeaveTypes(list []cpd.LeaveNewType, detailOf func(typeWid int) *cpd.LeaveNewFormDetail) []cpd.LeaveType {
|
||||
out := make([]cpd.LeaveType, 0, len(list))
|
||||
for _, t := range list {
|
||||
item := cpd.LeaveType{
|
||||
Code: t.TypeWid,
|
||||
Name: t.TypeName,
|
||||
}
|
||||
// 需先手写承诺书签名后提交(新套 queryLeaveType.isSign)
|
||||
if t.IsSign {
|
||||
item.RequireSign = 1
|
||||
}
|
||||
if d := detailOf(t.TypeWid); d != nil {
|
||||
if d.TypeName != "" {
|
||||
item.Name = d.TypeName
|
||||
}
|
||||
// mustOut=1 表示离校开关固定打开且不可改(新套 isLeaveOut=1)
|
||||
if d.IsLeaveOut == 1 {
|
||||
item.MustOut = 1
|
||||
}
|
||||
// 是否需要审批人由 apply-approvers 实际候选判断;
|
||||
// 类型列表阶段以审批流存在性做提示(有审批流则显示审批人区)
|
||||
item.NeedApproval = 1
|
||||
if d.IsVisibledEvidenceFile {
|
||||
item.EnableAttach = 1
|
||||
item.AttachmentNumberLimit = d.EvidenceFileCountMax
|
||||
} else {
|
||||
// 材料区不可见时不得带出上限,否则前端按「上限>0」会误显示上传入口
|
||||
item.AttachmentNumberLimit = 0
|
||||
}
|
||||
item.ReasonWordLimit = d.LeaveReasonWordsMini
|
||||
item.DisableTime = 0
|
||||
item.LimitDay = 0
|
||||
} else {
|
||||
// 详情获取失败:保守默认(不阻塞列表)
|
||||
item.NeedApproval = 1
|
||||
item.EnableAttach = 1
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// leaveNewPlacesToLeaveReportPlaces 新套销假位置 → 旧契约 LeaveReportPlace
|
||||
func leaveNewPlacesToLeaveReportPlaces(list []cpd.LeaveNewReportPlace) []cpd.LeaveReportPlace {
|
||||
out := make([]cpd.LeaveReportPlace, 0, len(list))
|
||||
for _, p := range list {
|
||||
out = append(out, cpd.LeaveReportPlace{
|
||||
Wid: p.Wid,
|
||||
Address: p.Address,
|
||||
Longitude: p.Longitude,
|
||||
Latitude: p.Latitude,
|
||||
Radius: p.Radius,
|
||||
CounName: p.CounName,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// leaveNewApproversToLeaveApprovers 新套审批人 → 旧契约 LeaveApprover(前端展示用)
|
||||
func leaveNewApproversToLeaveApprovers(list []cpd.LeaveNewApprover) []cpd.LeaveApprover {
|
||||
out := make([]cpd.LeaveApprover, 0, len(list))
|
||||
for _, a := range list {
|
||||
out = append(out, cpd.LeaveApprover{
|
||||
UserWid: a.UserWid,
|
||||
UserId: a.UserId,
|
||||
UserName: a.UserName,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"cpdaily-new/internal/model"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
)
|
||||
|
||||
// ---------- 新套执行链路(请假/销假) ----------
|
||||
|
||||
// leaveNewResolveApproverAndFlow 服务端自取审批流:按 userWid 匹配完整审批人对象 + flowData。
|
||||
// 返回 (approver, flowData, candidates, err):
|
||||
// - approver 为 nil 表示未提供 userWid 或未匹配(调用方决定是否放行)
|
||||
// - candidates 为全部候选(用于「无候选可放行」判定)
|
||||
func leaveNewResolveApproverAndFlow(cookieMap map[string]string, host string, typeWid int, startTime, endTime, approverWid string) (*cpd.LeaveNewApprover, map[string]interface{}, []cpd.LeaveNewApprover, error) {
|
||||
flow, err := cpd.FetchLeaveNewApproveFlow(cookieMap, host, typeWid, startTime, endTime, "")
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
if approverWid == "" {
|
||||
return nil, flow.FlowData, flow.ApproveUsers, nil
|
||||
}
|
||||
for i := range flow.ApproveUsers {
|
||||
if flow.ApproveUsers[i].UserWid == approverWid {
|
||||
return &flow.ApproveUsers[i], flow.FlowData, flow.ApproveUsers, nil
|
||||
}
|
||||
}
|
||||
return nil, flow.FlowData, flow.ApproveUsers, nil
|
||||
}
|
||||
|
||||
// leaveNewResolveCcUsers 抄送人 userWid 列表 → 完整对象(新套 getCcSearchList 全量匹配)
|
||||
func leaveNewResolveCcUsers(cookieMap map[string]string, host string, widList []string) []cpd.LeaveNewApprover {
|
||||
if len(widList) == 0 {
|
||||
return nil
|
||||
}
|
||||
all, err := cpd.FetchLeaveNewCcSearch(cookieMap, host, "")
|
||||
if err != nil {
|
||||
slog.Warn("获取抄送人候选失败,抄送人将被忽略", "error", err)
|
||||
return nil
|
||||
}
|
||||
want := make(map[string]bool, len(widList))
|
||||
for _, w := range widList {
|
||||
if w != "" {
|
||||
want[w] = true
|
||||
}
|
||||
}
|
||||
out := make([]cpd.LeaveNewApprover, 0, len(widList))
|
||||
seen := make(map[string]bool, len(widList))
|
||||
for _, a := range all {
|
||||
if want[a.UserWid] && !seen[a.UserWid] {
|
||||
seen[a.UserWid] = true
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// leaveNewTypeIsSign 该类型是否需手写承诺书(queryLeaveType.isSign;查询失败按 false 容错)
|
||||
func leaveNewTypeIsSign(cookieMap map[string]string, host string, typeWid int) bool {
|
||||
types, err := cpd.FetchLeaveNewTypes(cookieMap, host)
|
||||
if err != nil {
|
||||
slog.Warn("获取请假类型列表失败,跳过手写承诺书校验", "typeWid", typeWid, "error", err)
|
||||
return false
|
||||
}
|
||||
for _, t := range types {
|
||||
if t.TypeWid == typeWid {
|
||||
return t.IsSign
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// leaveNewTypeIsLeaveOut 新套类型详情 → 离校语义:
|
||||
// isLeaveOut=1 强制离校;isLeaveOut=0 强制不离校;其余由用户选择
|
||||
func leaveNewTypeIsLeaveOut(d *cpd.LeaveNewFormDetail) int {
|
||||
if d == nil {
|
||||
return -1
|
||||
}
|
||||
return d.IsLeaveOut
|
||||
}
|
||||
|
||||
// leaveNewValidateApplyForm 新套请假表单的服务端复核(标题/原因字数/证明材料)
|
||||
func leaveNewValidateApplyForm(d *cpd.LeaveNewFormDetail, req ExecuteLeaveApplyRequest, imageURLs []string) string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
if d.IsRequiredLeaveReason && strings.TrimSpace(req.LeaveReason) == "" {
|
||||
return "请填写请假原因"
|
||||
}
|
||||
if d.LeaveReasonWordsMini > 0 && len([]rune(req.LeaveReason)) < d.LeaveReasonWordsMini {
|
||||
return fmt.Sprintf("请假原因不能少于 %d 字", d.LeaveReasonWordsMini)
|
||||
}
|
||||
// 证明材料(附件):多图复核 —— 可见性开关 / 必填 / 张数下限 / 学校上限(产品上限 4)
|
||||
if len(imageURLs) > 0 {
|
||||
if !d.IsVisibledEvidenceFile {
|
||||
return "该请假类型不支持上传附件"
|
||||
}
|
||||
if maxN := cpd.LeaveMaxAttachCount(d.EvidenceFileCountMax); len(imageURLs) > maxN {
|
||||
return fmt.Sprintf("附件最多 %d 张", maxN)
|
||||
}
|
||||
}
|
||||
if d.IsRequiredEvidence {
|
||||
if len(imageURLs) == 0 {
|
||||
return "请上传证明材料"
|
||||
}
|
||||
if d.EvidenceFileCountMini > 0 && len(imageURLs) < d.EvidenceFileCountMini {
|
||||
return fmt.Sprintf("证明材料至少 %d 张", d.EvidenceFileCountMini)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ---------- 新套销假执行 ----------
|
||||
|
||||
// leaveNewExecuteReport 新套销假执行(供 handler SSE 调用)。
|
||||
// 返回 (是否成功, 用户可见错误信息, 需要重新登录)
|
||||
func leaveNewExecuteReport(user *model.SysUser, cookieMap map[string]string, host string,
|
||||
leaveID, address, longitude, latitude, imageURL, approverWid string) (bool, string, bool) {
|
||||
|
||||
// 1. 详情 + 状态复核(是否处于可销假状态)
|
||||
detail, err := cpd.FetchLeaveNewDetail(cookieMap, host, leaveID)
|
||||
if err != nil {
|
||||
if isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
detail, err = cpd.FetchLeaveNewDetail(cookieMap, host, leaveID)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
return false, "登录凭证已过期,请重新登录", true
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return false, "获取请假详情失败: " + err.Error(), false
|
||||
}
|
||||
}
|
||||
if !detail.CanReport {
|
||||
return false, fmt.Sprintf("当前请假单不可销假(状态:%s)", detail.StatusText), false
|
||||
}
|
||||
|
||||
// 2. 确认人(reportMode=2 老师审批销假时需要)
|
||||
var approver *cpd.LeaveNewApprover
|
||||
if detail.ReportMode == "2" && approverWid != "" {
|
||||
list, err := cpd.FetchLeaveNewReportApprovers(cookieMap, host, leaveID)
|
||||
if err == nil {
|
||||
for i := range list {
|
||||
if list[i].UserWid == approverWid {
|
||||
approver = &list[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 构造并提交
|
||||
form := cpd.BuildLeaveNewReportForm(cpd.LeaveNewReportParams{
|
||||
LeaveID: leaveID,
|
||||
Address: address,
|
||||
Longitude: longitude,
|
||||
Latitude: latitude,
|
||||
ImageURL: imageURL,
|
||||
Approver: approver,
|
||||
UserID: user.StudentID,
|
||||
DeviceID: user.MobileCode,
|
||||
Model: "cpdaily",
|
||||
})
|
||||
err = cpd.SubmitLeaveNewReport(cookieMap, host, form)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
err = cpd.SubmitLeaveNewReport(cookieMap, host, form)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
return false, "登录凭证已过期,请重新登录", true
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return false, "销假失败: " + err.Error(), false
|
||||
}
|
||||
return true, "", false
|
||||
}
|
||||
|
||||
// ---------- 新套请假执行 ----------
|
||||
|
||||
// leaveNewExecuteApply 新套请假执行(供 handler SSE 调用)。
|
||||
// 返回 (是否成功, 用户可见错误信息, 需要重新登录, 需要选择审批人)
|
||||
func leaveNewExecuteApply(user *model.SysUser, cookieMap map[string]string, host string, req ExecuteLeaveApplyRequest, imageURLs []string) (bool, string, bool, bool) {
|
||||
// 1. 类型详情复核
|
||||
detail, err := cpd.FetchLeaveNewTypeDetail(cookieMap, host, req.LeaveType)
|
||||
if err != nil {
|
||||
if isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
detail, err = cpd.FetchLeaveNewTypeDetail(cookieMap, host, req.LeaveType)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
return false, "登录凭证已过期,请重新登录", true, false
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return false, "获取请假类型配置失败: " + err.Error(), false, false
|
||||
}
|
||||
}
|
||||
if msg := leaveNewValidateApplyForm(detail, req, imageURLs); msg != "" {
|
||||
return false, msg, false, false
|
||||
}
|
||||
// 手写承诺书:isSign=1 的类型必须携带签名图。
|
||||
// isSign 只出现在 queryLeaveType(详情接口不返回),故单独取一次类型列表匹配。
|
||||
if leaveNewTypeIsSign(cookieMap, host, req.LeaveType) && strings.TrimSpace(req.SignatureURL) == "" {
|
||||
return false, "请先手写承诺书签名", false, false
|
||||
}
|
||||
|
||||
// 2. 审批流:取 flowData + 匹配完整审批人
|
||||
approver, flowData, candidates, err := leaveNewResolveApproverAndFlow(cookieMap, host, req.LeaveType, req.StartTime, req.EndTime, req.ApproverWid)
|
||||
if err != nil {
|
||||
if isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
approver, flowData, candidates, err = leaveNewResolveApproverAndFlow(cookieMap, host, req.LeaveType, req.StartTime, req.EndTime, req.ApproverWid)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
return false, "登录凭证已过期,请重新登录", true, false
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return false, "获取请假审批人失败: " + err.Error(), false, false
|
||||
}
|
||||
}
|
||||
if req.ApproverWid == "" && len(candidates) > 0 {
|
||||
return false, "该请假类型需要选择审批人", false, true
|
||||
}
|
||||
|
||||
// 3. 抄送人解析(非必填)
|
||||
ccWids := make([]string, 0, len(req.CcUsers))
|
||||
for _, cc := range req.CcUsers {
|
||||
ccWids = append(ccWids, cc.UserWid)
|
||||
}
|
||||
ccUsers := leaveNewResolveCcUsers(cookieMap, host, ccWids)
|
||||
|
||||
// 4. 离校语义:类型强制时以类型为准
|
||||
isLeaveOut := 0
|
||||
if req.OutStatus {
|
||||
isLeaveOut = 1
|
||||
}
|
||||
if fixed := leaveNewTypeIsLeaveOut(detail); fixed == 1 {
|
||||
isLeaveOut = 1
|
||||
} else if fixed == 0 && detail != nil {
|
||||
isLeaveOut = 0
|
||||
}
|
||||
|
||||
form := cpd.BuildLeaveNewApplyForm(cpd.LeaveNewApplyParams{
|
||||
TypeWid: req.LeaveType,
|
||||
BeginTime: trimSeconds(req.StartTime),
|
||||
EndTime: trimSeconds(req.EndTime),
|
||||
LeaveReason: req.LeaveReason,
|
||||
ImageURLs: imageURLs,
|
||||
SignatureURL: req.SignatureURL,
|
||||
LocationAddr: req.LocationAddr,
|
||||
Longitude: req.Longitude,
|
||||
Latitude: req.Latitude,
|
||||
IsLeaveOut: isLeaveOut,
|
||||
Destination: req.Address,
|
||||
Detail: req.DetailAddress,
|
||||
EmergencyName: req.UrgencyMobile,
|
||||
EmergencyMobile: req.UrgencyMobile,
|
||||
Approver: approver,
|
||||
CcUsers: ccUsers,
|
||||
FlowData: flowData,
|
||||
UserID: user.StudentID,
|
||||
DeviceID: user.MobileCode,
|
||||
Model: "cpdaily",
|
||||
})
|
||||
err = cpd.SubmitLeaveNewApply(cookieMap, host, form)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
err = cpd.SubmitLeaveNewApply(cookieMap, host, form)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
return false, "登录凭证已过期,请重新登录", true, false
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return false, "请假申请失败: " + err.Error(), false, false
|
||||
}
|
||||
return true, "", false, false
|
||||
}
|
||||
|
||||
// trimSeconds "yyyy-MM-dd HH:mm:ss" → "yyyy-MM-dd HH:mm"(新套时间格式)
|
||||
func trimSeconds(t string) string {
|
||||
t = strings.TrimSpace(t)
|
||||
if len(t) == 19 && t[16] == ':' && t[13] == ':' {
|
||||
return t[:16]
|
||||
}
|
||||
return t
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
"cpdaily-new/internal/utils"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// ---------- 新套(wec-counselor-leave-new-apps)handler 适配 ----------
|
||||
//
|
||||
// 设计:新套数据在 handler 层翻译为现有前端契约(LeaveType/LeaveItem/LeaveApprover),
|
||||
// 前端无需感知新旧差异;老套逻辑保持原样,仅按 flavor 分流。
|
||||
|
||||
// refreshAfterCookieExpired 通用「cookie 过期→刷新→重试一次」包装
|
||||
func refreshAfterCookieExpired(user *model.SysUser, err error, retry func() error) error {
|
||||
if err == nil || !isCookieExpired(err) {
|
||||
return err
|
||||
}
|
||||
slog.Info("cookie过期,尝试刷新", "userId", user.ID)
|
||||
if refreshErr := refreshCpdailyCookie(user); refreshErr != nil {
|
||||
if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
return ErrPasswordChanged
|
||||
}
|
||||
return err
|
||||
}
|
||||
return retry()
|
||||
}
|
||||
|
||||
// ---------- 销假:待销假列表(新套) ----------
|
||||
|
||||
// fetchLeaveNewPendingList 新套待销假列表:拉全部记录 → 过滤可销假 → 补位置与开关
|
||||
func fetchLeaveNewPendingList(cookieMap map[string]string, host string, user *model.SysUser) ([]cpd.LeaveItem, error) {
|
||||
records, err := cpd.FetchLeaveNewList(cookieMap, host, 1, 50, "1")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 规定销假位置全局一份(reportList 与记录无关)
|
||||
places := []cpd.LeaveReportPlace{}
|
||||
if p, err := cpd.FetchLeaveNewReportPlaces(cookieMap, host); err == nil {
|
||||
places = leaveNewPlacesToLeaveReportPlaces(p)
|
||||
} else {
|
||||
slog.Warn("获取新套规定销假位置失败", "userId", user.ID, "error", err)
|
||||
}
|
||||
|
||||
list := make([]cpd.LeaveItem, 0, len(records))
|
||||
for _, r := range records {
|
||||
// 列表接口不返回 reportMode/reportUploadMode/isLeaveOut,需补拉详情判断;
|
||||
// 仅对可能可销假的状态(3 休假中 / 4 销假逾期)补详情,减少请求
|
||||
if r.Status != "3" && r.Status != "4" {
|
||||
continue
|
||||
}
|
||||
detail, derr := cpd.FetchLeaveNewDetail(cookieMap, host, r.LeaveID)
|
||||
if derr != nil {
|
||||
slog.Warn("获取新套请假详情失败,跳过该记录", "leaveId", r.LeaveID, "error", derr)
|
||||
continue
|
||||
}
|
||||
if !detail.CanReport {
|
||||
continue
|
||||
}
|
||||
// 销假需要确认人:reportMode=2(老师审批销假)
|
||||
needApprover := detail.ReportMode == "2"
|
||||
enableAttach := detail.ReportUploadMode == "2" || (detail.ReportUploadMode == "1" && detail.IsLeaveOut == "1")
|
||||
list = append(list, cpd.LeaveItem{
|
||||
ID: detail.LeaveID,
|
||||
LeaveType: leaveNewTypeNameOfTopic(detail.TopicName, detail.TypeWid),
|
||||
Reason: detail.LeaveReason,
|
||||
CreateTime: r.ApplyTime,
|
||||
ActEndTime: detail.EndTime,
|
||||
Status: detail.Status,
|
||||
StatusText: detail.StatusText,
|
||||
ReportPlaces: places,
|
||||
ReportApplyFlow: needApprover,
|
||||
EnableAttach: enableAttach,
|
||||
})
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// leaveNewTypeNameOfTopic 从 topicName(如「李闯闯的事假」)提取类型名兜底
|
||||
func leaveNewTypeNameOfTopic(topicName, typeIcon string) string {
|
||||
if topicName == "" {
|
||||
return "请假"
|
||||
}
|
||||
return topicName
|
||||
}
|
||||
|
||||
// ---------- 请假类型(新套) ----------
|
||||
|
||||
// fetchLeaveNewTypesWithDetail 新套类型列表,逐类型补详情(权威开关)
|
||||
func fetchLeaveNewTypesWithDetail(cookieMap map[string]string, host string, user *model.SysUser) ([]cpd.LeaveType, error) {
|
||||
types, err := cpd.FetchLeaveNewTypes(cookieMap, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
details := make(map[int]*cpd.LeaveNewFormDetail, len(types))
|
||||
for _, t := range types {
|
||||
d, err := cpd.FetchLeaveNewTypeDetail(cookieMap, host, t.TypeWid)
|
||||
if err != nil {
|
||||
slog.Warn("获取新套类型详情失败,使用基础信息", "typeWid", t.TypeWid, "error", err)
|
||||
continue
|
||||
}
|
||||
details[t.TypeWid] = d
|
||||
}
|
||||
return leaveNewToLeaveTypes(types, func(wid int) *cpd.LeaveNewFormDetail {
|
||||
return details[wid]
|
||||
}), nil
|
||||
}
|
||||
|
||||
// ---------- 销假审批人(新套) ----------
|
||||
|
||||
// fetchLeaveNewReportApprovers 新套销假确认人(getReportApprovers by leaveId)
|
||||
func fetchLeaveNewReportApprovers(cookieMap map[string]string, host, leaveID string, user *model.SysUser) ([]cpd.LeaveApprover, error) {
|
||||
list, err := cpd.FetchLeaveNewReportApprovers(cookieMap, host, leaveID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return leaveNewApproversToLeaveApprovers(list), nil
|
||||
}
|
||||
|
||||
// ---------- 请假审批人(新套) ----------
|
||||
|
||||
// leaveNewApplyApproversResult 新套请假审批人结果(含 flowData 透传)
|
||||
type leaveNewApplyApproversResult struct {
|
||||
Approvers []cpd.LeaveApprover `json:"approvers"`
|
||||
NeedApproval bool `json:"needApproval"`
|
||||
InFlowScope bool `json:"inFlowScope"`
|
||||
FlowData map[string]interface{} `json:"flowData"`
|
||||
}
|
||||
|
||||
// fetchLeaveNewApplyApprovers 新套请假审批人 + 审批流数据
|
||||
func fetchLeaveNewApplyApprovers(cookieMap map[string]string, host string, typeWid int, startTime, endTime string) (*leaveNewApplyApproversResult, error) {
|
||||
flow, err := cpd.FetchLeaveNewApproveFlow(cookieMap, host, typeWid, startTime, endTime, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &leaveNewApplyApproversResult{
|
||||
Approvers: leaveNewApproversToLeaveApprovers(flow.ApproveUsers),
|
||||
NeedApproval: flow.IsNeedApproval,
|
||||
InFlowScope: flow.IsInFlowScope,
|
||||
FlowData: flow.FlowData,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetLeaveNewCcSearch 抄送人搜索(新套;searchKey 为空返回全部)
|
||||
func GetLeaveNewCcSearch(c *fiber.Ctx) error {
|
||||
user, err := loadLeaveUser(c)
|
||||
if err != nil {
|
||||
return utils.FailAuth(c, err.Error())
|
||||
}
|
||||
|
||||
var req struct {
|
||||
SearchKey string `json:"searchKey"`
|
||||
}
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
list, err := cpd.FetchLeaveNewCcSearch(cookieMap, host, req.SearchKey)
|
||||
if err != nil {
|
||||
_ = refreshAfterCookieExpired(user, err, func() error {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
var e error
|
||||
list, e = cpd.FetchLeaveNewCcSearch(cookieMap, host, req.SearchKey)
|
||||
return e
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取抄送人失败", "userId", user.ID, "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取抄送人失败: "+err.Error())
|
||||
}
|
||||
|
||||
return utils.Success(c, leaveNewApproversToLeaveApprovers(list))
|
||||
}
|
||||
|
||||
// buildLeaveNewApproverByWid 从审批人列表找 userWid 对应完整对象(提交表单用)
|
||||
func buildLeaveNewApproverByWid(list []cpd.LeaveNewApprover, userWid string) *cpd.LeaveNewApprover {
|
||||
if userWid == "" {
|
||||
return nil
|
||||
}
|
||||
for i := range list {
|
||||
if list[i].UserWid == userWid {
|
||||
return &list[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// leaveNewCheckCookieFresh 简单的 cookie 新鲜度检查(新套首次调用失败即触发刷新重试)
|
||||
func leaveNewRetryOnExpired(user *model.SysUser, err error, retry func() error) error {
|
||||
return refreshAfterCookieExpired(user, err, retry)
|
||||
}
|
||||
|
||||
// leaveNewFriendlyErr 新套错误统一包装(带 401 语义)
|
||||
func leaveNewFriendlyErr(c *fiber.Ctx, action string, err error) error {
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, fmt.Sprintf("%s: %v", action, err))
|
||||
}
|
||||
|
||||
// ---------- 数据库日志辅助 ----------
|
||||
|
||||
// saveLeaveLogEntry 请假/销假日志落库(两套共用)
|
||||
func saveLeaveLogEntry(userID uint, leaveID, title, schoolName, action string, isSuccess bool, errMsg string) {
|
||||
database.DB.Create(&model.CpLeaveLog{
|
||||
UserID: userID,
|
||||
LeaveID: leaveID,
|
||||
Title: title,
|
||||
SchoolName: schoolName,
|
||||
Action: action,
|
||||
IsSuccess: isSuccess,
|
||||
ErrorMessage: errMsg,
|
||||
})
|
||||
}
|
||||
@@ -133,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 ----------
|
||||
@@ -268,6 +269,8 @@ func AdminListPendingSchools(c *fiber.Ctx) error {
|
||||
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, "查询失败")
|
||||
@@ -280,15 +283,16 @@ func AdminListPendingSchools(c *fiber.Ctx) error {
|
||||
ip = "-"
|
||||
}
|
||||
items = append(items, PendingSchoolRes{
|
||||
ID: r.ID,
|
||||
SchoolID: r.SchoolID,
|
||||
SchoolName: r.SchoolName,
|
||||
Username: r.Username,
|
||||
Password: r.Password,
|
||||
Email: r.Email,
|
||||
IP: 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"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -333,3 +337,49 @@ func AdminMarkSchoolDone(c *fiber.Ctx) error {
|
||||
|
||||
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})
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"cpdaily-new/internal/service"
|
||||
"cpdaily-new/internal/utils"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
@@ -34,8 +35,20 @@ func GetSettings(c *fiber.Ctx) error {
|
||||
if _, ok := settings["register_reward"]; !ok {
|
||||
settings["register_reward"] = "1.00"
|
||||
}
|
||||
if _, ok := settings["vip_price"]; !ok {
|
||||
settings["vip_price"] = "15.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"
|
||||
}
|
||||
if _, ok := settings[settingDeductCheckin]; !ok {
|
||||
settings[settingDeductCheckin] = "1.00"
|
||||
}
|
||||
if _, ok := settings[settingDeductLeave]; !ok {
|
||||
settings[settingDeductLeave] = "1.00"
|
||||
}
|
||||
if _, ok := settings[settingDeductReport]; !ok {
|
||||
settings[settingDeductReport] = "1.00"
|
||||
}
|
||||
|
||||
return utils.Success(c, settings)
|
||||
@@ -63,7 +76,12 @@ func UpdateSetting(c *fiber.Ctx) error {
|
||||
"inviter_reward_per_invite": true,
|
||||
"invitee_reward_per_invite": true,
|
||||
"register_reward": true,
|
||||
"vip_price": true,
|
||||
"vip_price_week": true,
|
||||
"vip_price_month": true,
|
||||
// 扣款额度(打卡/请假/销假,每次成功执行扣减的可签到次数,允许小数与 0)
|
||||
settingDeductCheckin: true,
|
||||
settingDeductLeave: true,
|
||||
settingDeductReport: true,
|
||||
// 邮件通知(SMTP)
|
||||
"smtp_host": true,
|
||||
"smtp_port": true,
|
||||
@@ -78,6 +96,14 @@ func UpdateSetting(c *fiber.Ctx) error {
|
||||
return utils.Fail(c, 400, "不支持的设置项: "+req.Key)
|
||||
}
|
||||
|
||||
// 扣款额度:必须为非负数字(允许 0 = 不扣费)
|
||||
if req.Key == settingDeductCheckin || req.Key == settingDeductLeave || req.Key == settingDeductReport {
|
||||
v, err := strconv.ParseFloat(req.Value, 64)
|
||||
if err != nil || v < 0 {
|
||||
return utils.FailParam(c, "扣款额度必须为不小于 0 的数字")
|
||||
}
|
||||
}
|
||||
|
||||
var cfg model.SystemConfig
|
||||
result := database.DB.Where("`key` = ?", req.Key).First(&cfg)
|
||||
if result.Error != nil {
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/service"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
"cpdaily-new/internal/utils"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ========== 手机号验证码登录(无需选择学校) ==========
|
||||
|
||||
// SmsSendRequest 发送短信验证码请求(需独立的图片验证码)
|
||||
type SmsSendRequest struct {
|
||||
Phone string `json:"phone"`
|
||||
CaptchaID string `json:"captchaId"`
|
||||
CaptchaCode string `json:"captchaCode"`
|
||||
}
|
||||
|
||||
// SmsSend 发送手机短信验证码(对接今日校园)
|
||||
func SmsSend(c *fiber.Ctx) error {
|
||||
var req SmsSendRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
phone := strings.TrimSpace(req.Phone)
|
||||
if phone == "" {
|
||||
return utils.FailParam(c, "请输入手机号")
|
||||
}
|
||||
// 独立的图片验证码校验(防脚本刷短信)
|
||||
if req.CaptchaID == "" || req.CaptchaCode == "" {
|
||||
return utils.FailParam(c, "请输入图片验证码")
|
||||
}
|
||||
if !service.VerifyCaptcha(req.CaptchaID, req.CaptchaCode) {
|
||||
return utils.FailParam(c, "验证码错误或已过期")
|
||||
}
|
||||
|
||||
// 按 IP 限流,避免短信轰炸(复用验证码令牌桶)
|
||||
ip := c.IP()
|
||||
if ip == "" {
|
||||
ip = c.Context().RemoteIP().String()
|
||||
}
|
||||
if ok, wait := service.AllowCaptchaToken("sms:" + ip); !ok {
|
||||
return utils.Fail(c, 429, "验证码发送过于频繁,请 "+service.FormatWait(wait)+"后再试")
|
||||
}
|
||||
|
||||
result, err := cpd.SendSmsCode(c.Context(), phone)
|
||||
if err != nil {
|
||||
slog.Warn("短信验证码发送失败", "phone", maskPhone(phone), "error", err)
|
||||
return utils.Fail(c, 400, err.Error())
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"countdown": result.Countdown,
|
||||
"tipMsg": result.TipMsg,
|
||||
})
|
||||
}
|
||||
|
||||
// SmsLoginRequest 手机号登录请求(需独立的图片验证码)
|
||||
type SmsLoginRequest struct {
|
||||
Phone string `json:"phone"`
|
||||
Code string `json:"code"`
|
||||
CaptchaID string `json:"captchaId"`
|
||||
CaptchaCode string `json:"captchaCode"`
|
||||
InviteCode string `json:"inviteCode,omitempty"`
|
||||
}
|
||||
|
||||
// SmsLogin 手机号 + 短信验证码登录。
|
||||
// 登录响应自带 tenantId(学校)与 openId(学工号),故无需用户选择学校。
|
||||
// 用户匹配:优先「同校 + 同学工号」复用已有账号,保证与学工号登录指向同一用户。
|
||||
func SmsLogin(c *fiber.Ctx) error {
|
||||
var req SmsLoginRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return utils.FailParam(c, "请求参数错误")
|
||||
}
|
||||
phone := strings.TrimSpace(req.Phone)
|
||||
code := strings.TrimSpace(req.Code)
|
||||
if phone == "" || code == "" {
|
||||
return utils.FailParam(c, "请输入手机号和验证码")
|
||||
}
|
||||
// 独立的图片验证码校验(登录使用与发码不同的验证码)
|
||||
if req.CaptchaID == "" || req.CaptchaCode == "" {
|
||||
return utils.FailParam(c, "请输入图片验证码")
|
||||
}
|
||||
if !service.VerifyCaptcha(req.CaptchaID, req.CaptchaCode) {
|
||||
return utils.FailParam(c, "验证码错误或已过期")
|
||||
}
|
||||
|
||||
loginData, err := cpd.MobileLoginByCode(c.Context(), phone, code)
|
||||
if err != nil {
|
||||
slog.Warn("手机号登录失败", "phone", maskPhone(phone), "error", err)
|
||||
return utils.Fail(c, 401, "登录失败: "+err.Error())
|
||||
}
|
||||
if loginData.OpenID == "" {
|
||||
return utils.FailServer(c, "登录失败:未获取到学工号")
|
||||
}
|
||||
|
||||
// tenantId 即学校 ID
|
||||
school, err := cpd.GetSchoolDetail(loginData.TenantID)
|
||||
if err != nil {
|
||||
slog.Error("获取学校详情失败", "tenantId", loginData.TenantID, "error", err)
|
||||
return utils.FailServer(c, "获取学校信息失败")
|
||||
}
|
||||
|
||||
// 换取 CAS cookie(含 MOD_AUTH_CAS)
|
||||
deviceID := cpd.CreateDeviceID()
|
||||
cookies, err := cpd.ExchangeCasCookie(c.Context(), school, loginData, deviceID)
|
||||
if err != nil {
|
||||
slog.Warn("换取 CAS cookie 失败", "tenantId", loginData.TenantID, "error", err)
|
||||
return utils.Fail(c, 401, "登录失败: "+err.Error())
|
||||
}
|
||||
|
||||
// 校验是否拿到 MOD_ 认证 cookie
|
||||
hasMOD := false
|
||||
for _, ck := range cookies {
|
||||
if strings.HasPrefix(ck.Name, "MOD_") {
|
||||
hasMOD = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasMOD {
|
||||
return utils.Fail(c, 401, "登录失败,未获取到有效的认证信息")
|
||||
}
|
||||
|
||||
cookieStr := cpd.SerializeCookies(cookies)
|
||||
|
||||
// 用户匹配:同校 + 同学工号 复用已有账号,否则走通用注册流程新建
|
||||
user, isNew, err := findUserByStudentIDOrRegister(school, loginData.OpenID, phone, cookieStr, req.InviteCode)
|
||||
if err != nil {
|
||||
slog.Error("手机号登录用户处理失败", "error", err)
|
||||
return utils.FailServer(c, "用户处理失败")
|
||||
}
|
||||
|
||||
if user.Status == "disabled" {
|
||||
reason := user.DisabledReason
|
||||
if reason == "" {
|
||||
reason = "您的账号已被管理员禁用,如有疑问请联系客服"
|
||||
}
|
||||
return c.Status(403).JSON(utils.Response{Code: 403, Message: reason})
|
||||
}
|
||||
|
||||
// 更新 cookie / 登录时间 / 学工号回填
|
||||
now := time.Now()
|
||||
updates := map[string]interface{}{
|
||||
"cookie": cookieStr,
|
||||
"last_login_at": now,
|
||||
"last_login_ip": utils.ClientIP(c),
|
||||
}
|
||||
// 手机号登录用户也保存其学工号,便于之后用学工号登录时能匹配到同一账号
|
||||
if user.StudentID != loginData.OpenID {
|
||||
updates["student_id"] = loginData.OpenID
|
||||
}
|
||||
if user.MobilePhone == "" {
|
||||
updates["mobile_phone"] = phone
|
||||
}
|
||||
database.DB.Model(user).Updates(updates)
|
||||
user.StudentID = loginData.OpenID
|
||||
|
||||
// 同步 cpdaily 主页信息(头像/姓名等)
|
||||
if school.WecloudUrl != "" {
|
||||
go syncUserProfile(user, cookieStr, school.WecloudUrl)
|
||||
}
|
||||
|
||||
tokenPair, err := service.GenerateTokens(user.ID, user.Username, user.SchoolID)
|
||||
if err != nil {
|
||||
return utils.FailServer(c, "生成token失败")
|
||||
}
|
||||
|
||||
slog.Info("手机号登录成功", "userId", user.ID, "tenantId", loginData.TenantID,
|
||||
"studentId", loginData.OpenID, "isNew", isNew)
|
||||
|
||||
return utils.Success(c, fiber.Map{
|
||||
"user": user,
|
||||
"token": tokenPair,
|
||||
"firstLogin": isNew,
|
||||
})
|
||||
}
|
||||
|
||||
// findUserByStudentIDOrRegister 按「学校 + 学工号」查找用户并复用;
|
||||
// 未命中则调用通用注册流程(findOrCreateUser,复用邀请/注册奖励逻辑),
|
||||
// 用户名同样由「学校短码 + 学工号」构成,保证与学工号登录是同一账号。
|
||||
func findUserByStudentIDOrRegister(school *cpd.SchoolDetailInfo, studentID, phone, cookie, referralCode string) (*model.SysUser, bool, error) {
|
||||
// 1. 同校 + 同学工号
|
||||
var user model.SysUser
|
||||
err := database.DB.Where("school_id = ? AND student_id = ?", school.ID, studentID).First(&user).Error
|
||||
if err == nil {
|
||||
return &user, false, nil
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
// 2. 按 username(学校短码 + 学工号)匹配历史数据,命中则回填 school_id/student_id
|
||||
username := buildUsername(school, studentID)
|
||||
err = database.DB.Where("username = ?", username).First(&user).Error
|
||||
if err == nil {
|
||||
database.DB.Model(&user).Updates(map[string]interface{}{
|
||||
"school_id": school.ID,
|
||||
"student_id": studentID,
|
||||
})
|
||||
return &user, false, nil
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
// 3. 未命中:走通用注册流程(内部含邀请奖励/注册奖励/通知)。
|
||||
// 密码用随机串(SMS 登录用户无密码凭证,仅占位满足非空约束);
|
||||
// 注意不要用设备码样式的值,避免与 MobileCode 绑定语义混淆——
|
||||
// 设备码只能由用户在设备页主动绑定,登录流程不做任何自动绑定。
|
||||
return findOrCreateUser(username, generateRandomCode(32), school.ID, school.Name, studentID, cookie, referralCode)
|
||||
}
|
||||
|
||||
// maskPhone 手机号脱敏(日志用)
|
||||
func maskPhone(p string) string {
|
||||
if len(p) <= 4 {
|
||||
return "****"
|
||||
}
|
||||
return p[:3] + "****" + p[len(p)-4:]
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package handler
|
||||
|
||||
// 事务级软删除探针:验证「用户删除日志 → 仅软删除」的四处语义。
|
||||
// 默认跳过;仅在显式设置 PROBE_DB=1 时连接真实数据库执行(需要 backed/config.toml)。
|
||||
// 全过程在单个事务内进行并最终回滚,不写入任何持久数据(AutoMigrate 除外,与 server 启动行为一致)。
|
||||
//
|
||||
// go test ./internal/handler -run TestSoftDeleteProbe -v # 需 PROBE_DB=1
|
||||
//
|
||||
// 覆盖点:
|
||||
// 1. 前台列表(GORM 默认作用域)不展示已删除记录
|
||||
// 2. 任务完成状态判定(Unscoped 查当天成功日志)不受删除影响
|
||||
// 3. 后台统计(已执行累计 / 今日状态 / 今日卡片)计入已删除记录
|
||||
// 4. 后台明细 UNION SQL(adminLogUnionSQL,与 handler 同一常量)含已删除记录并正确标注 deleted/source
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/config"
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
)
|
||||
|
||||
func TestSoftDeleteProbe(t *testing.T) {
|
||||
if os.Getenv("PROBE_DB") != "1" {
|
||||
t.Skip("跳过:需要 PROBE_DB=1 且可连接数据库")
|
||||
}
|
||||
if err := config.Load("../../config.toml"); err != nil {
|
||||
t.Fatalf("加载配置失败: %v", err)
|
||||
}
|
||||
database.Init()
|
||||
|
||||
tx := database.DB.Begin()
|
||||
if tx.Error != nil {
|
||||
t.Fatalf("开启事务失败: %v", tx.Error)
|
||||
}
|
||||
defer tx.Rollback() // 无论成败一律回滚,探针不留痕
|
||||
|
||||
// ---------- 构造数据(全部在事务内,ID 由自增分配) ----------
|
||||
user := model.SysUser{
|
||||
Username: fmt.Sprintf("sdprobe_%d", time.Now().UnixNano()),
|
||||
Password: "probe",
|
||||
SchoolID: "probe",
|
||||
StudentID: "probe",
|
||||
InviteCode: fmt.Sprintf("p%09d", time.Now().UnixNano()%1000000000), // 避免唯一索引冲突
|
||||
}
|
||||
if err := tx.Create(&user).Error; err != nil {
|
||||
t.Fatalf("创建探针用户失败: %v", err)
|
||||
}
|
||||
uid := user.ID
|
||||
|
||||
taskLog := model.CpTaskLog{
|
||||
CpTaskID: 1, UserID: uid, TaskType: "sign",
|
||||
Title: "探针签到", RealTitle: "探针签到", IsSuccess: true,
|
||||
}
|
||||
leaveLog := model.CpLeaveLog{
|
||||
UserID: uid, LeaveID: "probe_leave", Title: "探针请假",
|
||||
SchoolName: "探针学校", Action: model.LeaveActionApply, IsSuccess: true,
|
||||
}
|
||||
if err := tx.Create(&taskLog).Error; err != nil {
|
||||
t.Fatalf("创建任务日志失败: %v", err)
|
||||
}
|
||||
if err := tx.Create(&leaveLog).Error; err != nil {
|
||||
t.Fatalf("创建请假日志失败: %v", err)
|
||||
}
|
||||
|
||||
// 用户端「删除」= GORM 软删除(handler 中即 database.DB.Delete(&log))
|
||||
if err := tx.Delete(&taskLog).Error; err != nil {
|
||||
t.Fatalf("软删除任务日志失败: %v", err)
|
||||
}
|
||||
if err := tx.Delete(&leaveLog).Error; err != nil {
|
||||
t.Fatalf("软删除请假日志失败: %v", err)
|
||||
}
|
||||
|
||||
// 回读确认 deleted_at 已置位(而非物理删除)
|
||||
var rawCount int64
|
||||
if err := tx.Unscoped().Model(&model.CpTaskLog{}).Where("id = ? AND deleted_at IS NOT NULL", taskLog.ID).Count(&rawCount).Error; err != nil || rawCount != 1 {
|
||||
t.Fatalf("任务日志未软删除: count=%d err=%v", rawCount, err)
|
||||
}
|
||||
if err := tx.Unscoped().Model(&model.CpLeaveLog{}).Where("id = ? AND deleted_at IS NOT NULL", leaveLog.ID).Count(&rawCount).Error; err != nil || rawCount != 1 {
|
||||
t.Fatalf("请假日志未软删除: count=%d err=%v", rawCount, err)
|
||||
}
|
||||
|
||||
// ---------- 1. 前台列表不可见(GORM 默认作用域过滤 deleted_at) ----------
|
||||
var frontTask []model.CpTaskLog
|
||||
tx.Where("user_id = ?", uid).Order("created_at DESC").Limit(10).Find(&frontTask)
|
||||
if len(frontTask) != 0 {
|
||||
t.Errorf("[1] 前台任务日志应不可见已删除记录, got %d 条", len(frontTask))
|
||||
}
|
||||
var frontLeave []model.CpLeaveLog
|
||||
tx.Where("user_id = ?", uid).Order("created_at DESC").Limit(10).Find(&frontLeave)
|
||||
if len(frontLeave) != 0 {
|
||||
t.Errorf("[1] 前台请假日志应不可见已删除记录, got %d 条", len(frontLeave))
|
||||
}
|
||||
|
||||
// ---------- 2. 任务完成状态不受删除影响(task.go ListTasks 的跨天重置查询) ----------
|
||||
now := time.Now()
|
||||
startOfToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
var todaySuccessIDs []uint
|
||||
tx.Unscoped().Model(&model.CpTaskLog{}).
|
||||
Where("user_id = ? AND is_success = 1 AND created_at >= ?", uid, startOfToday).
|
||||
Distinct("cp_task_id").Pluck("cp_task_id", &todaySuccessIDs)
|
||||
if len(todaySuccessIDs) != 1 || todaySuccessIDs[0] != 1 {
|
||||
t.Errorf("[2] 删除当天成功日志后任务完成状态被误重置: IDs=%v", todaySuccessIDs)
|
||||
}
|
||||
|
||||
// ---------- 3. 后台统计计入已删除 ----------
|
||||
var taskSuccess, leaveSuccess int64
|
||||
tx.Unscoped().Model(&model.CpTaskLog{}).Where("user_id = ? AND is_success = 1", uid).Count(&taskSuccess)
|
||||
tx.Unscoped().Model(&model.CpLeaveLog{}).Where("user_id = ? AND is_success = 1", uid).Count(&leaveSuccess)
|
||||
if taskSuccess != 1 || leaveSuccess != 1 {
|
||||
t.Errorf("[3] 后台已执行累计应计入已删除: task=%d leave=%d", taskSuccess, leaveSuccess)
|
||||
}
|
||||
var todayTask, todayLeave int64
|
||||
tx.Unscoped().Model(&model.CpTaskLog{}).Where("user_id = ? AND created_at >= ?", uid, startOfToday).Count(&todayTask)
|
||||
tx.Unscoped().Model(&model.CpLeaveLog{}).Where("user_id = ? AND created_at >= ?", uid, startOfToday).Count(&todayLeave)
|
||||
if todayTask != 1 || todayLeave != 1 {
|
||||
t.Errorf("[3] 今日统计卡片应计入已删除: task=%d leave=%d", todayTask, todayLeave)
|
||||
}
|
||||
|
||||
// ---------- 4. 后台明细 UNION(同一 adminLogUnionSQL 常量) ----------
|
||||
dayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
dayEnd := dayStart.AddDate(0, 0, 1)
|
||||
type combinedRow struct {
|
||||
ID uint
|
||||
UserID uint
|
||||
TaskType string
|
||||
Deleted bool
|
||||
Source int
|
||||
IsSuccess bool
|
||||
}
|
||||
var rows []combinedRow
|
||||
if err := tx.Raw(adminLogUnionSQL, dayStart, dayEnd, dayStart, dayEnd).Scan(&rows).Error; err != nil {
|
||||
t.Fatalf("[4] UNION 查询失败: %v", err)
|
||||
}
|
||||
var mine []combinedRow
|
||||
for _, r := range rows {
|
||||
if r.UserID == uid {
|
||||
mine = append(mine, r)
|
||||
}
|
||||
}
|
||||
if len(mine) != 2 {
|
||||
t.Fatalf("[4] UNION 应返回 2 条(任务+请假,均含已删除), got %d", len(mine))
|
||||
}
|
||||
sourceSeen := map[int]bool{}
|
||||
taskTypeSeen := map[string]bool{}
|
||||
for _, r := range mine {
|
||||
if !r.Deleted {
|
||||
t.Errorf("[4] 已删除记录在明细中未标注 deleted: %+v", r)
|
||||
}
|
||||
sourceSeen[r.Source] = true
|
||||
taskTypeSeen[r.TaskType] = true
|
||||
}
|
||||
if !sourceSeen[1] || !sourceSeen[2] {
|
||||
t.Errorf("[4] source 标注缺失: %v", sourceSeen)
|
||||
}
|
||||
if !taskTypeSeen["sign"] || !taskTypeSeen["leave_apply"] {
|
||||
t.Errorf("[4] task_type 映射缺失: %v", taskTypeSeen)
|
||||
}
|
||||
|
||||
// 用户端状态筛选(success=1)走 UNION 包裹分支,确认占位符与包裹 SQL 兼容
|
||||
var successRows []combinedRow
|
||||
tx.Raw("SELECT * FROM ("+adminLogUnionSQL+") t WHERE t.is_success = 1", dayStart, dayEnd, dayStart, dayEnd).Scan(&successRows)
|
||||
found := 0
|
||||
for _, r := range successRows {
|
||||
if r.UserID == uid {
|
||||
found++
|
||||
}
|
||||
}
|
||||
if found != 2 {
|
||||
t.Errorf("[4] success 过滤分支应保留 2 条已删除成功记录, got %d", found)
|
||||
}
|
||||
|
||||
t.Log("软删除探针全部通过:前台隐藏 / 状态不受影响 / 后台计入 / 明细标注")
|
||||
// defer 回滚,探针不落库
|
||||
}
|
||||
+269
-30
@@ -36,7 +36,20 @@ func GetTaskTitles(c *fiber.Ctx) error {
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
tasks := cpd.FetchAllRecentTasks(cookieMap, host)
|
||||
// 登录态失效时自动续期并重试一次;仍失败则明确提示重新登录
|
||||
var tasks []cpd.TodayTaskInfo
|
||||
_, err := withCookieRefresh(&user, cookieMap, host, func(cm map[string]string) error {
|
||||
var fetchErr error
|
||||
tasks, fetchErr = cpd.FetchAllRecentTasks(cm, host)
|
||||
return fetchErr
|
||||
})
|
||||
if err != nil {
|
||||
if isCpdailyAuthError(err) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取打卡任务失败: "+err.Error())
|
||||
}
|
||||
|
||||
return utils.Success(c, tasks)
|
||||
}
|
||||
|
||||
@@ -148,6 +161,15 @@ func GetTaskForm(c *fiber.Ctx) error {
|
||||
return utils.FailServer(c, "查询失败")
|
||||
}
|
||||
|
||||
// 返校登记无形表单:直接返回空表单,前端保存空 formData 即可
|
||||
if cpd.TaskType(task.TaskType) == cpd.TaskTypeReturnRegister {
|
||||
return utils.Success(c, fiber.Map{
|
||||
"formItems": []model.CpTaskFormItem{},
|
||||
"realTitle": task.RealTitle,
|
||||
"isPhoto": false,
|
||||
})
|
||||
}
|
||||
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
@@ -157,14 +179,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,6 +216,30 @@ type SaveTaskFormRequest struct {
|
||||
FormData []model.CpTaskFormItem `json:"formData"`
|
||||
}
|
||||
|
||||
// missingRequiredFormFields 返回表单中「必填但内容为空」的字段标题列表。
|
||||
// 学校表单模板中必填项为空时提交必然失败(如签到地点未配置 → 服务端报"签到地点纬度不能为空"),
|
||||
// 因此在执行前拦截并给出明确提示,而不是等提交失败后只报笼统错误。
|
||||
func missingRequiredFormFields(formData string) []string {
|
||||
var items []model.CpTaskFormItem
|
||||
if err := json.Unmarshal([]byte(formData), &items); err != nil {
|
||||
return nil
|
||||
}
|
||||
var missing []string
|
||||
for _, it := range items {
|
||||
if !it.Required || !it.Show {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(it.Content) == "" {
|
||||
name := it.Title
|
||||
if name == "" {
|
||||
name = it.ColName
|
||||
}
|
||||
missing = append(missing, name)
|
||||
}
|
||||
}
|
||||
return missing
|
||||
}
|
||||
|
||||
func SaveTaskForm(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
id := c.Params("id")
|
||||
@@ -218,10 +264,20 @@ func SaveTaskForm(c *fiber.Ctx) error {
|
||||
return utils.Success(c, nil)
|
||||
}
|
||||
|
||||
// TaskWithMatch 任务列表附带匹配状态
|
||||
type TaskWithMatch struct {
|
||||
model.CpTask
|
||||
MatchStatus string `json:"matchStatus"` // matched_unsigned, matched_signed, no_match, check_failed
|
||||
// TaskListItem 任务列表的轻量响应项。
|
||||
// 关键:**不包含 formData**。formData 可能是 longtext(历史数据里存过 base64 图片,
|
||||
// 单条曾达 2.9MB),把它放进列表接口会让首页每次多传数 MB。
|
||||
// 列表渲染只需要下面这些字段;表单内容另走 /task/form-data/:id 获取。
|
||||
type TaskListItem struct {
|
||||
ID uint `json:"id"`
|
||||
TaskType string `json:"taskType"`
|
||||
Title string `json:"title"`
|
||||
RealTitle string `json:"realTitle"`
|
||||
TaskStatus string `json:"taskStatus"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
MatchStatus string `json:"matchStatus"`
|
||||
MissingFields []string `json:"missingFields"` // 必填但为空的字段标题(服务端预计算,前端无需解析 formData)
|
||||
}
|
||||
|
||||
// globMatch 简单通配符匹配(仅支持 *)
|
||||
@@ -265,9 +321,36 @@ func ListTasks(c *fiber.Ctx) error {
|
||||
var tasks []model.CpTask
|
||||
database.DB.Where("user_id = ?", userID).Order("created_at DESC").Find(&tasks)
|
||||
|
||||
// 跨天惰性重置:签到/查寝均为每日任务,"已完成(success)"只应代表当天成功。
|
||||
// 昨日及更早的 success 若继续保留,任务卡会一直显示绿色对勾、隐藏执行按钮,
|
||||
// 误导用户"今天已执行"且无法再次打卡。以"当天是否存在成功日志"为准判定并重置回 pending。
|
||||
now := time.Now()
|
||||
startOfToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
var todaySuccessIDs []uint
|
||||
// Unscoped:用户在客户端"删除"日志只是软删除,不代表当天没执行过;
|
||||
// 若漏加会因当天成功日志被删而把任务重置回 pending,导致重复打卡
|
||||
database.DB.Unscoped().Model(&model.CpTaskLog{}).
|
||||
Where("user_id = ? AND is_success = 1 AND created_at >= ?", userID, startOfToday).
|
||||
Distinct("cp_task_id").
|
||||
Pluck("cp_task_id", &todaySuccessIDs)
|
||||
todaySuccessSet := make(map[uint]bool, len(todaySuccessIDs))
|
||||
for _, tid := range todaySuccessIDs {
|
||||
todaySuccessSet[tid] = true
|
||||
}
|
||||
for i := range tasks {
|
||||
if tasks[i].TaskStatus == "success" && !todaySuccessSet[tasks[i].ID] {
|
||||
tasks[i].TaskStatus = "pending"
|
||||
tasks[i].ErrorMessage = ""
|
||||
database.DB.Model(&model.CpTask{}).Where("id = ?", tasks[i].ID).
|
||||
Updates(map[string]interface{}{"task_status": "pending", "error_message": ""})
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试获取今日任务进行匹配
|
||||
var user model.SysUser
|
||||
var todayTasks []cpd.TodayTaskInfo
|
||||
// 返校登记待办(taskWid:stuWid 集合),用于匹配 return_register 任务
|
||||
var returnRegisterPending map[string]bool
|
||||
fetchOk := false
|
||||
|
||||
if err := database.DB.First(&user, userID).Error; err == nil && user.Cookie != "" {
|
||||
@@ -298,12 +381,46 @@ func ListTasks(c *fiber.Ctx) error {
|
||||
fetchOk = true
|
||||
}
|
||||
}
|
||||
|
||||
// 返校登记待办(供 return_register 任务匹配;失败不影响签到类)
|
||||
returnRegisterPending = map[string]bool{}
|
||||
if rr, rerr := cpd.FetchReturnRegisterTasks(cookieMap, host); rerr == nil {
|
||||
for _, t := range rr {
|
||||
returnRegisterPending[t.SignWid] = true
|
||||
}
|
||||
} else {
|
||||
slog.Warn("获取返校登记待办失败", "userId", userID, "error", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
// 构造返回结果
|
||||
result := make([]TaskWithMatch, len(tasks))
|
||||
// 构造返回结果(轻量 DTO:不含 formData)
|
||||
result := make([]TaskListItem, len(tasks))
|
||||
for i, task := range tasks {
|
||||
item := TaskWithMatch{CpTask: task, MatchStatus: "check_failed"}
|
||||
item := TaskListItem{
|
||||
ID: task.ID,
|
||||
TaskType: task.TaskType,
|
||||
Title: task.Title,
|
||||
RealTitle: task.RealTitle,
|
||||
TaskStatus: task.TaskStatus,
|
||||
ErrorMessage: task.ErrorMessage,
|
||||
CreatedAt: task.CreatedAt,
|
||||
MatchStatus: "check_failed",
|
||||
MissingFields: missingRequiredFormFields(task.FormData),
|
||||
}
|
||||
// 返校登记:按待办集合判断(在待办中=未登记;不在=已登记/已过期)
|
||||
if task.TaskType == string(cpd.TaskTypeReturnRegister) {
|
||||
if returnRegisterPending != nil {
|
||||
item.MatchStatus = "no_match"
|
||||
if returnRegisterPending[task.SignWid] {
|
||||
item.MatchStatus = "matched_unsigned"
|
||||
} else {
|
||||
item.MatchStatus = "matched_signed"
|
||||
}
|
||||
}
|
||||
item.MissingFields = nil // 返校登记无形表单
|
||||
result[i] = item
|
||||
continue
|
||||
}
|
||||
if fetchOk {
|
||||
item.MatchStatus = "no_match"
|
||||
// 用 title 做 glob 匹配(支持 * 通配符)
|
||||
@@ -327,6 +444,26 @@ func ListTasks(c *fiber.Ctx) error {
|
||||
return utils.Success(c, result)
|
||||
}
|
||||
|
||||
// GetTaskSavedForm 返回该任务**已保存**的表单内容(formData),供编辑弹窗预填。
|
||||
// 与 GetTaskForm 的区别:后者是从今日校园重新拉取表单模板(会丢失用户已填值)。
|
||||
// 单独成接口,是为了让列表接口(/task/list)不必携带大字段 formData。
|
||||
func GetTaskSavedForm(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
id := c.Params("id")
|
||||
|
||||
var task model.CpTask
|
||||
if err := database.DB.Select("id", "form_data").
|
||||
Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return utils.Fail(c, 404, "任务不存在")
|
||||
}
|
||||
return utils.FailServer(c, "查询失败")
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{"formData": task.FormData})
|
||||
}
|
||||
|
||||
|
||||
// DeleteTask 删除任务
|
||||
func DeleteTask(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
@@ -340,7 +477,8 @@ func DeleteTask(c *fiber.Ctx) error {
|
||||
return utils.Success(c, nil)
|
||||
}
|
||||
|
||||
// ExecuteTask 同步执行签到(SSE 流式返回状态)
|
||||
// ExecuteTask 执行任务(按 taskType 分流)。
|
||||
// sign / sleep_check → 签到提交流程;return_register → 返校登记(确认到达)。
|
||||
func ExecuteTask(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
id := c.Params("id")
|
||||
@@ -353,17 +491,46 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
return utils.FailServer(c, "查询失败")
|
||||
}
|
||||
|
||||
switch cpd.TaskType(task.TaskType) {
|
||||
case cpd.TaskTypeReturnRegister:
|
||||
return executeReturnRegisterTask(c, &task)
|
||||
default:
|
||||
return executeSignTask(c)
|
||||
}
|
||||
}
|
||||
|
||||
// executeSignTask 同步执行签到/查寝(SSE 流式返回状态)
|
||||
func executeSignTask(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
id := c.Params("id")
|
||||
|
||||
var task model.CpTask
|
||||
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return utils.Fail(c, 404, "任务不存在")
|
||||
}
|
||||
return utils.FailServer(c, "查询失败")
|
||||
}
|
||||
|
||||
if task.TaskStatus == "executing" {
|
||||
return utils.Fail(c, 400, "任务正在执行中")
|
||||
}
|
||||
if task.FormData == "" {
|
||||
return utils.Fail(c, 400, "请先配置表单数据")
|
||||
}
|
||||
if missing := missingRequiredFormFields(task.FormData); len(missing) > 0 {
|
||||
return utils.Fail(c, 400, "签到信息未配置完整,缺少:"+strings.Join(missing, "、")+",请编辑任务补全后再执行")
|
||||
}
|
||||
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
}
|
||||
// 设备码后端硬校验:打卡执行需携带设备码。此前仅前端新建任务入口弹窗引导,
|
||||
// 账密登录创建的账号可能未绑定设备码,空设备码会触发学校端风控异常
|
||||
if strings.TrimSpace(user.MobileCode) == "" {
|
||||
return utils.Fail(c, 400, "请先在个人中心绑定设备码后再执行签到")
|
||||
}
|
||||
|
||||
// 设置 SSE 头
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
@@ -396,9 +563,12 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
// VIP 判定:VIP 且未过期则免扣次数直接执行
|
||||
isVip := user.VipExpireAt != nil && user.VipExpireAt.After(time.Now())
|
||||
|
||||
// 检查可用次数(VIP 免检查)
|
||||
if !isVip && user.SignCount <= 0 {
|
||||
slog.Warn("签到次数不足,拒绝执行", "userId", userID, "taskId", id)
|
||||
// 本次打卡扣减额度(后台可配置,允许小数与 0=不扣费)
|
||||
deduct := getCheckinDeduct()
|
||||
|
||||
// 检查可用次数(VIP 免检查;0 额度时恒放行)
|
||||
if !isVip && user.SignCount < deduct {
|
||||
slog.Warn("签到次数不足,拒绝执行", "userId", userID, "taskId", id, "signCount", user.SignCount, "deduct", deduct)
|
||||
sendEvent("task_error", map[string]interface{}{"message": "可用次数不足,请购买CDK或通过邀请获得次数"})
|
||||
return
|
||||
}
|
||||
@@ -428,14 +598,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
|
||||
}
|
||||
@@ -456,15 +626,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. 反序列化用户配置的表单
|
||||
@@ -483,9 +648,37 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
// 4. 填充表单并提交
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在提交签到..."})
|
||||
|
||||
submitForm := cpd.FillSubmitForm(detail.Rows, formItems, user.MobileCode)
|
||||
submitForm, formErr := cpd.FillSubmitForm(detail.Rows, formItems, user.MobileCode)
|
||||
if formErr != nil {
|
||||
errMsg := "生成签到表单失败: " + formErr.Error()
|
||||
slog.Error("生成签到表单失败", "taskId", id, "error", formErr)
|
||||
database.DB.Model(&task).Updates(map[string]interface{}{
|
||||
"task_status": "fail",
|
||||
"error_message": errMsg,
|
||||
})
|
||||
saveLog(false, errMsg, taskTitle(task))
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
// 历史位置超出查寝组所有签到范围时自动改用最近签到点,避免"位置不在签到范围内"
|
||||
cpd.AdjustSubmitFormToSignRange(submitForm, detail.Rows)
|
||||
// 照片仍是本地预览(base64)时自动上传换取正式 URL(用户上传失败保存的表单/历史遗留数据)
|
||||
if photo, ok := submitForm["signPhotoUrl"].(string); ok && cpd.IsDataURIImage(photo) {
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在上传照片..."})
|
||||
previewUrl, upErr := cpd.UploadDataURIImage(cookieMap, host, cpd.TaskType(task.TaskType), photo)
|
||||
if upErr != nil {
|
||||
errMsg := "照片上传失败: " + upErr.Error()
|
||||
slog.Error("照片上传失败", "taskId", id, "error", upErr)
|
||||
database.DB.Model(&task).Updates(map[string]interface{}{
|
||||
"task_status": "fail",
|
||||
"error_message": errMsg,
|
||||
})
|
||||
saveLog(false, errMsg, taskTitle(task))
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
submitForm["signPhotoUrl"] = previewUrl
|
||||
}
|
||||
err = cpd.SubmitSign(cookieMap, host, cpd.TaskType(task.TaskType), submitForm, user.MobileCode, user.StudentID)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("提交签到cookie过期,尝试自动刷新", "taskId", id)
|
||||
@@ -519,11 +712,15 @@ func ExecuteTask(c *fiber.Ctx) error {
|
||||
|
||||
// 扣减可用次数(原子操作,防止并发超卖;VIP 有效期内免扣)
|
||||
if !isVip {
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count > 0", userID).
|
||||
Update("sign_count", gorm.Expr("sign_count - 1"))
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count >= ?", userID, deduct).
|
||||
Update("sign_count", gorm.Expr("sign_count - ?", deduct))
|
||||
msg := "签到成功!(已扣 " + fmtDeduct(deduct) + " 次)"
|
||||
if deduct <= 0 {
|
||||
msg = "签到成功!(免扣次数)"
|
||||
}
|
||||
sendEvent("success", map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "签到成功!",
|
||||
"message": msg,
|
||||
})
|
||||
} else {
|
||||
sendEvent("success", map[string]interface{}{
|
||||
@@ -643,6 +840,27 @@ func GetUploadPolicy(c *fiber.Ctx) error {
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 请假类图片:新套学校走 leave-new OBS 协议(COS 风格),旧套保持原路径
|
||||
if req.TaskType == string(cpd.TaskTypeLeave) && schoolLeaveFlavor(&user, cookieMap) == cpd.LeaveFlavorNew {
|
||||
policy, err := cpd.GetLeaveNewUploadPolicy(cookieMap, host)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
policy, err = cpd.GetLeaveNewUploadPolicy(cookieMap, host)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取上传策略失败(新套)", "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取上传策略失败: "+err.Error())
|
||||
}
|
||||
return utils.Success(c, policy)
|
||||
}
|
||||
|
||||
policy, err := cpd.GetUploadPolicy(cookieMap, host, cpd.TaskType(req.TaskType))
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("获取上传策略cookie过期,尝试刷新", "userId", userID)
|
||||
@@ -687,6 +905,27 @@ func GetPreviewUrl(c *fiber.Ctx) error {
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 请假类图片预览:新套学校走 leave-new OBS 协议(参数 obsKey)
|
||||
if req.TaskType == string(cpd.TaskTypeLeave) && schoolLeaveFlavor(&user, cookieMap) == cpd.LeaveFlavorNew {
|
||||
previewUrl, err := cpd.GetLeaveNewPreviewURL(cookieMap, host, req.FileKey)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
previewUrl, err = cpd.GetLeaveNewPreviewURL(cookieMap, host, req.FileKey)
|
||||
} else if errors.Is(refreshErr, ErrPasswordChanged) {
|
||||
err = ErrPasswordChanged
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("获取预览 URL 失败(新套)", "error", err)
|
||||
if errors.Is(err, ErrPasswordChanged) {
|
||||
return utils.Fail(c, 401, "登录凭证已过期,请重新登录")
|
||||
}
|
||||
return utils.Fail(c, 503, "获取预览 URL 失败: "+err.Error())
|
||||
}
|
||||
return utils.Success(c, fiber.Map{"previewUrl": previewUrl})
|
||||
}
|
||||
|
||||
previewUrl, err := cpd.GetPreviewUrl(cookieMap, host, cpd.TaskType(req.TaskType), req.FileKey)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
slog.Info("获取预览URL cookie过期,尝试刷新", "userId", userID)
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/ratelimit"
|
||||
cpd "cpdaily-new/internal/service/cpdaily"
|
||||
"cpdaily-new/internal/utils"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// executeReturnRegisterTask 执行返校登记任务(SSE 流式返回,与签到执行体验一致)。
|
||||
// 返校登记无形表单:直接取学校配置的校区坐标,对 signWid 中的 (taskWid, stuWid) 提交确认到达。
|
||||
// 事件流:connecting → submitting → success / task_error
|
||||
func executeReturnRegisterTask(c *fiber.Ctx, task *model.CpTask) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
|
||||
// 解析任务标识 "taskWid:stuWid"(在打开 SSE 流前完成,参数错误可直接返回 JSON)
|
||||
taskWid, stuWid, perr := cpd.ParseLeaveReturnSignWid(task.SignWid)
|
||||
if perr != nil {
|
||||
return utils.FailParam(c, "任务配置无效,请删除后重新创建")
|
||||
}
|
||||
|
||||
if task.TaskStatus == "executing" {
|
||||
return utils.Fail(c, 400, "任务正在执行中")
|
||||
}
|
||||
|
||||
var user model.SysUser
|
||||
if err := database.DB.First(&user, userID).Error; err != nil {
|
||||
return utils.FailAuth(c, "用户不存在")
|
||||
}
|
||||
if user.Cookie == "" {
|
||||
return utils.Fail(c, 400, "请先登录")
|
||||
}
|
||||
|
||||
// 设置 SSE 头
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
c.Set("Cache-Control", "no-cache")
|
||||
c.Set("Connection", "keep-alive")
|
||||
c.Set("X-Accel-Buffering", "no")
|
||||
|
||||
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
|
||||
sendEvent := func(event string, data map[string]interface{}) {
|
||||
d, _ := json.Marshal(data)
|
||||
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, string(d))
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
saveLog := func(isSuccess bool, errMsg string) {
|
||||
database.DB.Create(&model.CpTaskLog{
|
||||
CpTaskID: task.ID,
|
||||
UserID: userID,
|
||||
TaskType: task.TaskType,
|
||||
Title: task.Title,
|
||||
RealTitle: task.RealTitle,
|
||||
IsSuccess: isSuccess,
|
||||
ErrorMessage: errMsg,
|
||||
})
|
||||
}
|
||||
|
||||
isVip := user.VipExpireAt != nil && user.VipExpireAt.After(time.Now())
|
||||
deduct := getCheckinDeduct()
|
||||
if !isVip && user.SignCount < deduct {
|
||||
slog.Warn("返校登记次数不足,拒绝执行", "userId", userID, "taskId", task.ID, "signCount", user.SignCount, "deduct", deduct)
|
||||
sendEvent("task_error", map[string]interface{}{"message": "可用次数不足,请购买CDK或通过邀请获得次数"})
|
||||
return
|
||||
}
|
||||
|
||||
// 限流:同一用户同一任务
|
||||
rateKey := fmt.Sprintf("task:%d:%d", userID, task.ID)
|
||||
rules := []ratelimit.Rule{
|
||||
{Limit: 3, Window: 2 * time.Minute, Label: "2m"},
|
||||
{Limit: 6, Window: 1 * time.Hour, Label: "1h"},
|
||||
{Limit: 10, Window: 24 * time.Hour, Label: "1d"},
|
||||
}
|
||||
if ok, msg := ratelimit.AllowMulti(rateKey, rules); !ok {
|
||||
slog.Warn("返校登记触发限流", "userId", userID, "taskId", task.ID, "msg", msg)
|
||||
sendEvent("task_error", map[string]interface{}{"message": msg, "rateLimit": true})
|
||||
return
|
||||
}
|
||||
|
||||
database.DB.Model(task).Updates(map[string]interface{}{
|
||||
"task_status": "executing",
|
||||
"error_message": "",
|
||||
})
|
||||
|
||||
sendEvent("connecting", map[string]interface{}{"status": "connecting", "message": "正在连接今日校园..."})
|
||||
|
||||
cookieMap := cpd.ParseCookieJSON(user.Cookie)
|
||||
host := getSchoolHost(user.SchoolID)
|
||||
|
||||
// 取学校配置的校区坐标(范围内登记)
|
||||
places, err := cpd.FetchLeaveReturnPlaces(cookieMap, host)
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
places, err = cpd.FetchLeaveReturnPlaces(cookieMap, host)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := "获取返校位置配置失败: " + err.Error()
|
||||
slog.Error("返校登记失败", "taskId", task.ID, "error", err)
|
||||
database.DB.Model(task).Updates(map[string]interface{}{"task_status": "fail", "error_message": errMsg})
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
if len(places) == 0 {
|
||||
errMsg := "学校未配置返校确认位置,无法自动登记"
|
||||
database.DB.Model(task).Updates(map[string]interface{}{"task_status": "fail", "error_message": errMsg})
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
place := places[0]
|
||||
|
||||
sendEvent("submitting", map[string]interface{}{"status": "submitting", "message": "正在提交返校登记..."})
|
||||
|
||||
err = cpd.SubmitLeaveReturnRegister(cookieMap, host, taskWid, stuWid, place.Address, place.Longitude, place.Latitude, 1, "")
|
||||
if err != nil && isCookieExpired(err) {
|
||||
if refreshErr := refreshCpdailyCookie(&user); refreshErr == nil {
|
||||
cookieMap = cpd.ParseCookieJSON(user.Cookie)
|
||||
err = cpd.SubmitLeaveReturnRegister(cookieMap, host, taskWid, stuWid, place.Address, place.Longitude, place.Latitude, 1, "")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := "返校登记失败: " + err.Error()
|
||||
slog.Error("返校登记失败", "taskId", task.ID, "error", err)
|
||||
database.DB.Model(task).Updates(map[string]interface{}{"task_status": "fail", "error_message": errMsg})
|
||||
saveLog(false, errMsg)
|
||||
sendEvent("task_error", map[string]interface{}{"status": "error", "message": errMsg})
|
||||
return
|
||||
}
|
||||
|
||||
database.DB.Model(task).Updates(map[string]interface{}{"task_status": "success"})
|
||||
saveLog(true, "")
|
||||
|
||||
if !isVip {
|
||||
database.DB.Model(&model.SysUser{}).Where("id = ? AND sign_count >= ?", userID, deduct).
|
||||
Update("sign_count", gorm.Expr("sign_count - ?", deduct))
|
||||
msg := "返校登记成功!(已扣 " + fmtDeduct(deduct) + " 次)"
|
||||
if deduct <= 0 {
|
||||
msg = "返校登记成功!(免扣次数)"
|
||||
}
|
||||
sendEvent("success", map[string]interface{}{"status": "success", "message": msg})
|
||||
} else {
|
||||
sendEvent("success", map[string]interface{}{"status": "success", "message": "返校登记成功!(VIP 免扣次数)"})
|
||||
}
|
||||
|
||||
slog.Info("返校登记成功", "taskId", task.ID, "userId", userID, "taskWid", taskWid, "stuWid", stuWid)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -44,6 +44,8 @@ type AdminTicketListItem struct {
|
||||
Username string `json:"username"`
|
||||
RealName string `json:"realName"`
|
||||
SchoolName string `json:"schoolName"`
|
||||
// 用户是否已删除该工单(软删除);管理端仍展示,便于追溯
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
type TicketDetail struct {
|
||||
@@ -272,7 +274,9 @@ func CloseTicket(c *fiber.Ctx) error {
|
||||
return utils.Success(c, fiber.Map{"status": "closed"})
|
||||
}
|
||||
|
||||
// DeleteTicket 用户删除工单
|
||||
// DeleteTicket 用户删除工单(软删除)。
|
||||
// 仅标记 tickets.deleted_at:用户端列表不再展示,管理端仍可见并可查看完整对话,
|
||||
// 因此不再级联删除消息/通知,避免用户删除后抹掉处理痕迹。
|
||||
func DeleteTicket(c *fiber.Ctx) error {
|
||||
userID := c.Locals("userId").(uint)
|
||||
ticketID, err := c.ParamsInt("id")
|
||||
@@ -288,10 +292,10 @@ func DeleteTicket(c *fiber.Ctx) error {
|
||||
return utils.FailServer(c, "查询失败")
|
||||
}
|
||||
|
||||
// 级联删除:消息、通知
|
||||
database.DB.Where("ticket_id = ?", ticket.ID).Delete(&model.TicketMessage{})
|
||||
database.DB.Where("ticket_id = ?", ticket.ID).Delete(&model.TicketNotification{})
|
||||
database.DB.Delete(&ticket)
|
||||
// 软删除(GORM 自动转为 UPDATE deleted_at);消息与通知保留,供管理端追溯
|
||||
if err := database.DB.Delete(&ticket).Error; err != nil {
|
||||
return utils.FailServer(c, "删除失败")
|
||||
}
|
||||
|
||||
return utils.Success(c, fiber.Map{"deleted": true})
|
||||
}
|
||||
@@ -346,11 +350,12 @@ func MarkTicketNotificationRead(c *fiber.Ctx) error {
|
||||
// ---------- 管理端 API ----------
|
||||
|
||||
// AdminListTickets 管理端工单列表
|
||||
// 使用 Unscoped 包含用户已软删除的工单,便于管理员追溯(列表中标记「用户已删除」)。
|
||||
func AdminListTickets(c *fiber.Ctx) error {
|
||||
status := c.Query("status")
|
||||
keyword := c.Query("keyword")
|
||||
|
||||
query := database.DB.Table("tickets").
|
||||
query := database.DB.Unscoped().Table("tickets").
|
||||
Select("tickets.*, sys_user.username, sys_user.real_name, sys_user.school_id").
|
||||
Joins("LEFT JOIN sys_user ON sys_user.id = tickets.user_id").
|
||||
Order("tickets.created_at DESC")
|
||||
@@ -389,6 +394,7 @@ func AdminListTickets(c *fiber.Ctx) error {
|
||||
Username: r.Username,
|
||||
RealName: r.RealName,
|
||||
SchoolName: r.SchoolID,
|
||||
Deleted: r.DeletedAt.Valid,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -403,7 +409,8 @@ func AdminGetTicket(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
var ticket model.Ticket
|
||||
if err := database.DB.First(&ticket, ticketID).Error; err != nil {
|
||||
// Unscoped:管理员可查看用户已软删除的工单(含完整对话)
|
||||
if err := database.DB.Unscoped().First(&ticket, ticketID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return utils.Fail(c, 404, "工单不存在")
|
||||
}
|
||||
@@ -441,6 +448,7 @@ func AdminGetTicket(c *fiber.Ctx) error {
|
||||
"schoolName": user.SchoolID,
|
||||
"createdAt": ticket.CreatedAt.Format("2006-01-02 15:04"),
|
||||
"updatedAt": ticket.UpdatedAt.Format("2006-01-02 15:04"),
|
||||
"deleted": ticket.DeletedAt.Valid,
|
||||
"messages": msgRes,
|
||||
})
|
||||
}
|
||||
@@ -462,7 +470,8 @@ func AdminReplyTicket(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
var ticket model.Ticket
|
||||
if err := database.DB.First(&ticket, ticketID).Error; err != nil {
|
||||
// Unscoped:允许对用户已软删除的工单继续回复(工单内容仍保留可追溯)
|
||||
if err := database.DB.Unscoped().First(&ticket, ticketID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return utils.Fail(c, 404, "工单不存在")
|
||||
}
|
||||
@@ -521,7 +530,8 @@ func AdminUpdateTicketStatus(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
var ticket model.Ticket
|
||||
if err := database.DB.First(&ticket, ticketID).Error; err != nil {
|
||||
// Unscoped:允许对用户已软删除的工单更新状态
|
||||
if err := database.DB.Unscoped().First(&ticket, ticketID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return utils.Fail(c, 404, "工单不存在")
|
||||
}
|
||||
|
||||
@@ -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 = ?)",
|
||||
"is_pinned = 0 AND target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)",
|
||||
userType, userID,
|
||||
).Order("created_at DESC").Find(&announcements)
|
||||
|
||||
@@ -66,6 +66,40 @@ func ListUserAnnouncements(c *fiber.Ctx) error {
|
||||
return utils.Success(c, items)
|
||||
}
|
||||
|
||||
// PinnedAnnouncementItem 置顶公告项(打卡页顶部横向滚动展示)
|
||||
type PinnedAnnouncementItem struct {
|
||||
ID uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
}
|
||||
|
||||
// ListPinnedAnnouncements 获取当前用户可见的置顶公告(打卡页顶部横向滚动)
|
||||
func ListPinnedAnnouncements(c *fiber.Ctx) error {
|
||||
userID, userType, err := getCurrentUser(c)
|
||||
if err != nil {
|
||||
return utils.FailAuth(c, "未认证")
|
||||
}
|
||||
|
||||
var announcements []model.Announcement
|
||||
database.DB.Where(
|
||||
"is_pinned = 1 AND target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)",
|
||||
userType, userID,
|
||||
).Order("created_at DESC").Find(&announcements)
|
||||
|
||||
items := make([]PinnedAnnouncementItem, 0, len(announcements))
|
||||
for _, a := range announcements {
|
||||
items = append(items, PinnedAnnouncementItem{
|
||||
ID: a.ID,
|
||||
Title: a.Title,
|
||||
Content: a.Content,
|
||||
CreatedAt: a.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
return utils.Success(c, items)
|
||||
}
|
||||
|
||||
// GetUnreadCount 获取未读公告数
|
||||
func GetUnreadCount(c *fiber.Ctx) error {
|
||||
userID, userType, err := getCurrentUser(c)
|
||||
@@ -75,7 +109,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("is_pinned = 0 AND target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)", userType, userID).
|
||||
Count(&totalCount)
|
||||
|
||||
var readCount int64
|
||||
@@ -118,10 +152,10 @@ func GetMyAnnouncementInfo(c *fiber.Ctx) error {
|
||||
return utils.FailAuth(c, "未认证")
|
||||
}
|
||||
|
||||
// 1. 总公告数(包含指定给当前用户的)
|
||||
// 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("is_pinned = 0 AND target_type = ? AND (target_user_id IS NULL OR target_user_id = ?)", userType, userID).
|
||||
Count(&totalCount)
|
||||
|
||||
// 2. 已读数
|
||||
@@ -185,6 +219,11 @@ func MarkAnnouncementRead(c *fiber.Ctx) error {
|
||||
return utils.Fail(c, 404, "公告不存在")
|
||||
}
|
||||
|
||||
// 置顶公告不进入用户公告列表,不可被标记已读
|
||||
if announcement.IsPinned {
|
||||
return utils.Fail(c, 400, "置顶公告无需标记已读")
|
||||
}
|
||||
|
||||
// 验证公告目标类型匹配(agent 公告仅代理/管理员可见,user 公告仅用户可见)
|
||||
if announcement.TargetType != userType {
|
||||
return utils.Fail(c, 403, "无权操作此公告")
|
||||
|
||||
@@ -1,13 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"cpdaily-new/internal/database"
|
||||
"cpdaily-new/internal/model"
|
||||
"cpdaily-new/internal/service"
|
||||
"cpdaily-new/internal/utils"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// touchDailyLogin 补齐“当天已登录”标记:JWT 有效期较长且可静默续期,
|
||||
// 用户当天在用平台也不会真正重新登录,后台“当天登录人数”会因此偏少。
|
||||
// 这里在认证通过后做一次条件更新:仅当 last_login_at 为空或还停留在昨天及以前时才写入今天,
|
||||
// 即每个用户每天最多产生一次真实写库;并发请求重复触发也只会写同一天,其余请求仅做主键定位、零写入。
|
||||
// 写入当天登录时间的同时同步记录该次访问的客户端 IP(utils.ClientIP),供后台列表展示来源。
|
||||
// 当天起点用 Go 本地时区(与后台统计的 “YYYY-MM-DD 00:00:00” 口径一致)。
|
||||
func touchDailyLogin(c *fiber.Ctx, userID uint) {
|
||||
now := time.Now()
|
||||
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
database.DB.Model(&model.SysUser{}).
|
||||
Where("id = ? AND (last_login_at IS NULL OR last_login_at < ?)", userID, todayStart).
|
||||
Updates(map[string]interface{}{
|
||||
"last_login_at": now,
|
||||
"last_login_ip": utils.ClientIP(c),
|
||||
})
|
||||
}
|
||||
|
||||
func AuthRequired() fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
tokenStr := ""
|
||||
@@ -38,6 +58,8 @@ func AuthRequired() fiber.Handler {
|
||||
c.Locals("userId", claims.UserID)
|
||||
c.Locals("username", claims.Username)
|
||||
c.Locals("schoolId", claims.SchoolID)
|
||||
// 当天首次使用平台时把 last_login_at 顶到今天并记录 IP(详见 touchDailyLogin 注释)
|
||||
touchDailyLogin(c, claims.UserID)
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,11 @@ type Announcement struct {
|
||||
TargetUserID *uint `gorm:"index" json:"targetUserId"` // 指定单个用户(null=推送全部)
|
||||
ForcePopup bool `gorm:"default:false" json:"forcePopup"`
|
||||
LoopPopup bool `gorm:"default:false" json:"loopPopup"`
|
||||
CreatedBy uint `gorm:"not null" json:"createdBy"` // admin_id (system公告为0)
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
// 置顶公告:在打卡页顶部横向滚动展示
|
||||
IsPinned bool `gorm:"default:false;index" json:"isPinned"`
|
||||
CreatedBy uint `gorm:"not null" json:"createdBy"` // admin_id (system公告为0)
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
func (Announcement) TableName() string {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CpLeaveLog 请假/销假执行日志
|
||||
// 说明:DeletedAt 软删除字段——用户在客户端"删除"日志时仅标记 deleted_at,
|
||||
// 前台日志列表不再展示,但后台统计仍计入。
|
||||
type CpLeaveLog struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UserID uint `gorm:"not null;index" json:"userId"`
|
||||
LeaveID string `gorm:"type:varchar(64);not null" json:"leaveId"` // 今日校园请假记录 ID(请假申请为 apply_<时间戳>)
|
||||
Title string `gorm:"type:varchar(255);not null" json:"title"` // 日志标题(请假类型名 + 动作)
|
||||
SchoolName string `gorm:"type:varchar(255)" json:"schoolName"` // 学校名称
|
||||
Action string `gorm:"type:varchar(16);not null;default:report" json:"action"` // report=销假 / apply=请假
|
||||
IsSuccess bool `gorm:"not null;default:0" json:"isSuccess"` // 是否成功
|
||||
ErrorMessage string `gorm:"type:text" json:"errorMessage"` // 失败时的错误信息
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
}
|
||||
|
||||
func (CpLeaveLog) TableName() string {
|
||||
return "cp_leave_logs"
|
||||
}
|
||||
|
||||
// 日志动作类型:请假申请 / 销假
|
||||
const (
|
||||
LeaveActionApply = "apply" // 请假申请
|
||||
LeaveActionReport = "report" // 销假
|
||||
)
|
||||
@@ -6,10 +6,10 @@ import "time"
|
||||
type CpTask struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UserID uint `gorm:"not null;index" json:"userId"`
|
||||
TaskType string `gorm:"type:varchar(32);not null" json:"taskType"` // sign, sleep_check
|
||||
TaskType string `gorm:"type:varchar(32);not null" json:"taskType"` // sign, sleep_check, return_register
|
||||
Title string `gorm:"type:varchar(255);not null" json:"title"` // 用户选择的标题(支持通配符)
|
||||
RealTitle string `gorm:"type:varchar(255)" json:"realTitle"` // cpdaily 返回的实际标题
|
||||
SignWid string `gorm:"type:varchar(255)" json:"signWid"` // cpdaily 任务标识
|
||||
SignWid string `gorm:"type:varchar(255)" json:"signWid"` // cpdaily 任务标识(return_register 为 "taskWid:stuWid")
|
||||
SignInstanceWid string `gorm:"type:varchar(255)" json:"signInstanceWid"` // cpdaily 实例标识
|
||||
FormData string `gorm:"type:longtext" json:"formData"` // JSON: []CpTaskFormItem
|
||||
TaskStatus string `gorm:"type:varchar(32);default:pending" json:"taskStatus"` // pending, executing, success, fail
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CpTaskLog 任务执行日志
|
||||
// 说明:DeletedAt 软删除字段——用户在客户端"删除"日志时仅标记 deleted_at,
|
||||
// 前台日志列表不再展示,但后台统计(已执行次数/今日状态/执行总次数)仍计入。
|
||||
type CpTaskLog struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
CpTaskID uint `gorm:"not null;index" json:"cpTaskId"`
|
||||
UserID uint `gorm:"not null;index" json:"userId"`
|
||||
TaskType string `gorm:"type:varchar(32);not null" json:"taskType"` // sign / sleep_check
|
||||
Title string `gorm:"type:varchar(255);not null" json:"title"` // 用户设置的任务标题(支持通配符)
|
||||
RealTitle string `gorm:"type:varchar(255)" json:"realTitle"` // 本次执行实际匹配的标题
|
||||
IsSuccess bool `gorm:"not null;default:0" json:"isSuccess"` // 是否成功
|
||||
ErrorMessage string `gorm:"type:text" json:"errorMessage"` // 失败时的错误信息
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
CpTaskID uint `gorm:"not null;index" json:"cpTaskId"`
|
||||
UserID uint `gorm:"not null;index" json:"userId"`
|
||||
TaskType string `gorm:"type:varchar(32);not null" json:"taskType"` // sign / sleep_check / return_register
|
||||
Title string `gorm:"type:varchar(255);not null" json:"title"` // 用户设置的任务标题(支持通配符)
|
||||
RealTitle string `gorm:"type:varchar(255)" json:"realTitle"` // 本次执行实际匹配的标题
|
||||
IsSuccess bool `gorm:"not null;default:0" json:"isSuccess"` // 是否成功
|
||||
ErrorMessage string `gorm:"type:text" json:"errorMessage"` // 失败时的错误信息
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
}
|
||||
|
||||
func (CpTaskLog) 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 {
|
||||
|
||||
@@ -35,8 +35,8 @@ type SysUser struct {
|
||||
MobileCode string `gorm:"type:varchar(255)" json:"mobileCode"`
|
||||
// 设备码类型 random/authorize/manual
|
||||
MobileType string `gorm:"type:varchar(32)" json:"mobileType"`
|
||||
// 可签到次数
|
||||
SignCount int `gorm:"type:int;default:0" json:"signCount"`
|
||||
// 可签到次数(支持小数;每次打卡/请假/销假按后台配置的额度扣减,0 表示不扣费)
|
||||
SignCount float64 `gorm:"type:decimal(12,2);default:0" json:"signCount"`
|
||||
// VIP 到期时间(null=从未开通;VIP 有效期内执行任务免扣次数)
|
||||
VipExpireAt *time.Time `gorm:"type:datetime" json:"vipExpireAt"`
|
||||
// 邀请码
|
||||
@@ -56,6 +56,9 @@ type SysUser struct {
|
||||
// 最后登录时间
|
||||
LastLoginAt *time.Time `gorm:"type:datetime" json:"lastLoginAt"`
|
||||
|
||||
// 最后登录 IP(真实登录或当天首次使用平台时记录;nginx 转发 X-Real-IP/X-Forwarded-For)
|
||||
LastLoginIP string `gorm:"type:varchar(64);default:''" json:"lastLoginIp"`
|
||||
|
||||
// 已看过的新手引导版本(如 v2;空=未看过,登录后需展示引导,跨设备生效)
|
||||
GuideVersion string `gorm:"type:varchar(32);default:''" json:"guideVersion"`
|
||||
|
||||
|
||||
@@ -2,17 +2,23 @@ package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Ticket 工单
|
||||
// 说明:DeletedAt 软删除字段——用户在客户端"删除"工单时仅标记 deleted_at,
|
||||
// 用户端列表不再展示,但管理端仍可查看(并标记「用户已删除」),
|
||||
// 保留工单内容与其全部消息记录,避免用户删除后抹掉处理痕迹。
|
||||
type Ticket struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UserID uint `gorm:"not null;index" json:"userId"`
|
||||
Title string `gorm:"size:200;not null" json:"title"`
|
||||
Content string `gorm:"type:text;not null" json:"content"`
|
||||
Status string `gorm:"size:20;not null;default:pending;index" json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UserID uint `gorm:"not null;index" json:"userId"`
|
||||
Title string `gorm:"size:200;not null" json:"title"`
|
||||
Content string `gorm:"type:text;not null" json:"content"`
|
||||
Status string `gorm:"size:20;not null;default:pending;index" json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
}
|
||||
|
||||
func (Ticket) TableName() string {
|
||||
|
||||
+300
-272
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"cpdaily-new/internal/assets"
|
||||
"cpdaily-new/internal/config"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
@@ -11,12 +12,16 @@ import (
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"log/slog"
|
||||
"math"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/opentype"
|
||||
"golang.org/x/image/math/fixed"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -28,6 +33,9 @@ const (
|
||||
captchaKeyFmt = "captcha:%s" // 验证码内容
|
||||
captchaRLKey = "captcha:rl:%s"
|
||||
|
||||
// 验证码四周统一留白(px):文字、干扰线、装饰全部限制在该留白区内
|
||||
captchaMargin = 15
|
||||
|
||||
// 令牌桶:同 IP 5 分钟最多获取 10 次(桶容量 10,速率 10/5min = 每 30s 回补 1 个)
|
||||
// 容忍共享出口 IP(宿舍/校园网多人)短时突发,又能约束爆破频率
|
||||
captchaBucketCapacity = 10
|
||||
@@ -100,6 +108,39 @@ type CaptchaResult struct {
|
||||
ImageBase64 string `json:"imageBase64"`
|
||||
}
|
||||
|
||||
// ───── 字体 ─────
|
||||
|
||||
var (
|
||||
captchaFontOnce sync.Once
|
||||
captchaFont *opentype.Font
|
||||
)
|
||||
|
||||
// loadCaptchaFont 进程内解析一次 Sour Gummy ExtraBold 字体(圆润软糖风格,OFL 开源授权)。
|
||||
// 字体经 go:embed 编译进二进制,解析失败属于构建产物损坏,直接 panic 快速暴露。
|
||||
func loadCaptchaFont() *opentype.Font {
|
||||
captchaFontOnce.Do(func() {
|
||||
f, err := opentype.Parse(assets.SourGummyDigits)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("验证码字体解析失败: %v", err))
|
||||
}
|
||||
captchaFont = f
|
||||
})
|
||||
return captchaFont
|
||||
}
|
||||
|
||||
// captchaFace 按指定字号创建字体 face
|
||||
func captchaFace(size float64) font.Face {
|
||||
face, err := opentype.NewFace(loadCaptchaFont(), &opentype.FaceOptions{
|
||||
Size: size,
|
||||
DPI: 72,
|
||||
Hinting: font.HintingFull,
|
||||
})
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("创建验证码字体 face 失败: %v", err))
|
||||
}
|
||||
return face
|
||||
}
|
||||
|
||||
// 二次元风格配色 — 亮色系
|
||||
var animeColors = []color.RGBA{
|
||||
{0xFF, 0x14, 0x93, 0xFF}, // 深粉红
|
||||
@@ -126,6 +167,22 @@ var pastelBG = []color.RGBA{
|
||||
{0xFF, 0xF8, 0xDC, 0xFF}, // 玉米丝
|
||||
}
|
||||
|
||||
// softCol 生成半透明直线 alpha 颜色(color.NRGBA)。
|
||||
// 必须用 NRGBA 而非给 RGBA 强改 A:image.RGBA 是预乘格式,通道值大于 alpha 属于非法
|
||||
// 预乘值,PNG 编码时按 alpha 除回归会溢出截断,产生黑块/杂色。
|
||||
func softCol(c color.RGBA, a uint8) color.NRGBA {
|
||||
return color.NRGBA{R: c.R, G: c.G, B: c.B, A: a}
|
||||
}
|
||||
|
||||
// 干扰线专用色池:避开红/粉暖色系(用户反馈干扰线太红),取冷色+金色
|
||||
var lineColors = []color.RGBA{
|
||||
{0x00, 0xCE, 0xD1, 0xFF}, // 青色
|
||||
{0x00, 0xBF, 0xFF, 0xFF}, // 天蓝
|
||||
{0x93, 0x70, 0xDB, 0xFF}, // 中紫
|
||||
{0x32, 0xCD, 0x32, 0xFF}, // 酸橙
|
||||
{0xFF, 0xD7, 0x00, 0xFF}, // 金色
|
||||
}
|
||||
|
||||
// 生成随机验证码
|
||||
func generateCode(length int) string {
|
||||
digits := "0123456789"
|
||||
@@ -136,105 +193,102 @@ func generateCode(length int) string {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// 生成图片验证码
|
||||
// 生成图片验证码(可爱风:Sour Gummy 圆润数字 + 白描边贴纸字 + 马卡龙背景 + 弯曲斜线干扰线 + 糖珠点缀)
|
||||
func GenerateCaptcha() (*CaptchaResult, error) {
|
||||
cfg := config.Global.Captcha
|
||||
code := generateCode(cfg.Length)
|
||||
|
||||
// 生成图片
|
||||
img := image.NewRGBA(image.Rect(0, 0, cfg.Width, cfg.Height))
|
||||
// 画布最小尺寸保障:config.toml 服务器侧独立维护、可能未同步新尺寸,
|
||||
// 低于该值时 15px 四周留白会挤占内容区,代码层强制放大
|
||||
w, h := cfg.Width, cfg.Height
|
||||
if w < 180 {
|
||||
w = 180
|
||||
}
|
||||
if h < 60 {
|
||||
h = 60
|
||||
}
|
||||
|
||||
// 随机马卡龙色背景
|
||||
// 生成图片
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
|
||||
// 随机马卡龙色背景(铺满整图)
|
||||
bg := pastelBG[rand.Intn(len(pastelBG))]
|
||||
draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)
|
||||
|
||||
// ── 干扰线(粗线,高不透明度)──
|
||||
for i := 0; i < 10; i++ {
|
||||
// ── 四周统一留白 15px:所有内容元素均限制在留白区内 ──
|
||||
m := captchaMargin
|
||||
ix0, iy0 := m, m
|
||||
ix1, iy1 := w-m, h-m
|
||||
boxW, boxH := ix1-ix0, iy1-iy0
|
||||
|
||||
// ── 背景装饰:白色半透明大圆(软糖气泡感)──
|
||||
for i := 0; i < 2; i++ {
|
||||
col := softCol(color.RGBA{255, 255, 255, 255}, uint8(rand.Intn(14)+18))
|
||||
drawCircle(img, ix0+rand.Intn(boxW), iy0+rand.Intn(boxH), rand.Intn(12)+14, col)
|
||||
}
|
||||
|
||||
// ── 糖珠点缀:实心小圆 + 空心泡泡 ──
|
||||
for i := 0; i < 5; i++ {
|
||||
col := softCol(animeColors[rand.Intn(len(animeColors))], uint8(rand.Intn(60)+90))
|
||||
drawCircle(img, ix0+rand.Intn(boxW), iy0+rand.Intn(boxH), rand.Intn(2)+1, col)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
col := softCol(animeColors[rand.Intn(len(animeColors))], uint8(rand.Intn(40)+70))
|
||||
drawRing(img, ix0+rand.Intn(boxW), iy0+rand.Intn(boxH), rand.Intn(3)+3, col)
|
||||
}
|
||||
|
||||
// ── 字符:Sour Gummy 圆润字体渲染数字,白描边贴纸风 + 随机旋转 ±10° ──
|
||||
// 数字实际字高约 0.65em,字号取内容高的 1.25 倍让字符饱满贴近留白线;
|
||||
// 并以每字符可用宽度约束上限
|
||||
fontSize := float64(boxH) * 1.25
|
||||
if per := float64(boxW) / float64(cfg.Length) / 0.6 * 1.1; fontSize > per {
|
||||
fontSize = per
|
||||
}
|
||||
face := captchaFace(fontSize)
|
||||
defer face.Close()
|
||||
|
||||
for i, c := range code {
|
||||
centerX := ix0 + boxW*(2*i+1)/(2*cfg.Length)
|
||||
centerY := iy0 + boxH/2
|
||||
col := animeColors[rand.Intn(len(animeColors))]
|
||||
col.A = uint8(rand.Intn(80) + 150) // alpha 150~230
|
||||
|
||||
x1 := rand.Intn(cfg.Width)
|
||||
y1 := rand.Intn(cfg.Height)
|
||||
x2 := rand.Intn(cfg.Width)
|
||||
y2 := rand.Intn(cfg.Height)
|
||||
|
||||
thick := rand.Intn(2) + 2 // 2~3px 粗
|
||||
drawThickLine(img, x1, y1, x2, y2, col, thick)
|
||||
angle := rand.Float64()*20 - 10 // -10° ~ +10°
|
||||
drawStickerChar(img, face, centerX, centerY, string(c), col, angle)
|
||||
}
|
||||
|
||||
// ── 二次元风格彩色折线 ──
|
||||
for i := 0; i < 6; i++ {
|
||||
col := animeColors[rand.Intn(len(animeColors))]
|
||||
col.A = uint8(rand.Intn(60) + 130)
|
||||
|
||||
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 < 20; i++ {
|
||||
x := ix0 + rand.Intn(boxW)
|
||||
y := iy0 + rand.Intn(boxH)
|
||||
col := softCol(animeColors[rand.Intn(len(animeColors))], uint8(rand.Intn(50)+40))
|
||||
setPx(img, x, y, col)
|
||||
}
|
||||
|
||||
// ── 装饰圆圈(半透明彩色气泡)──
|
||||
for i := 0; i < 4; i++ {
|
||||
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 := 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 := 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)
|
||||
}
|
||||
|
||||
// ── 绘制文字 — 4px 像素块,带倾斜效果 ──
|
||||
charBlockW := cfg.Width / cfg.Length
|
||||
charPixelSize := 4 // 4px 像素块
|
||||
charMapW := 7 // 字符矩阵宽度
|
||||
charMapH := 9 // 字符矩阵高度
|
||||
charW := charMapW * charPixelSize
|
||||
charH := charMapH * charPixelSize
|
||||
|
||||
for i, ch := range code {
|
||||
// 每个字符在其块中居中
|
||||
blockCenterX := i*charBlockW + charBlockW/2
|
||||
charX := blockCenterX - charW/2
|
||||
charY := (cfg.Height - charH) / 2
|
||||
|
||||
// 微调位置
|
||||
charX += rand.Intn(5) - 2
|
||||
charY += rand.Intn(3) - 1
|
||||
|
||||
// 每个字符选择鲜艳的二次元颜色
|
||||
charColor := animeColors[rand.Intn(len(animeColors))]
|
||||
|
||||
// 随机倾斜程度 (shear: 每行偏移像素数)
|
||||
shear := rand.Intn(2) + 1 // 1~2
|
||||
|
||||
// 1/3 概率向右倾斜,2/3 向左倾斜
|
||||
if rand.Intn(3) != 0 {
|
||||
shear = -shear
|
||||
// ── 干扰线:贯穿式弯曲斜线(左右端随机高度 + 强制大倾角 + 四向随机,
|
||||
// 线条本身带 1~2 个正弦拱——单拱似抛物线,双拱似波浪;绘制在数字上层)──
|
||||
for i := 0; i < 3; i++ {
|
||||
col := softCol(lineColors[rand.Intn(len(lineColors))], uint8(rand.Intn(40)+60))
|
||||
y1 := iy0 + rand.Intn(boxH+1)
|
||||
y2 := iy0 + rand.Intn(boxH+1)
|
||||
// 保证“很斜”:两端高度差至少内容高的一半;差值方向即上斜/下斜随机
|
||||
if dy := y2 - y1; abs(dy) < boxH/2 {
|
||||
step := boxH/2 + rand.Intn(boxH/4+1)
|
||||
if dy < 0 {
|
||||
y2 = y1 - step // 右端更低 → 左高右低(下斜)
|
||||
if y2 < iy0 {
|
||||
y2, y1 = iy0, min(iy0+step, iy1)
|
||||
}
|
||||
} else {
|
||||
y2 = y1 + step // 右端更高 → 左低右高(上斜)
|
||||
if y2 > iy1 {
|
||||
y2, y1 = iy1, max(iy1-step, iy0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
drawCharLarge(img, charX, charY, string(ch), charColor, charPixelSize, shear)
|
||||
// 随机交换起止端点,覆盖左斜/右斜方向
|
||||
if rand.Intn(2) == 0 {
|
||||
y1, y2 = y2, y1
|
||||
}
|
||||
drawCurvedLine(img, ix0, y1, ix1, y2, col, 2)
|
||||
}
|
||||
|
||||
// 编码为 PNG base64
|
||||
@@ -340,50 +394,183 @@ func FormatWait(d time.Duration) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 画粗线(绘制多条平行线模拟粗线)
|
||||
func drawThickLine(img *image.RGBA, x1, y1, x2, y2 int, col color.Color, thickness int) {
|
||||
// setPx 带边界检查的安全画点
|
||||
func setPx(img *image.RGBA, x, y int, col color.Color) {
|
||||
if x >= 0 && x < img.Bounds().Max.X && y >= 0 && y < img.Bounds().Max.Y {
|
||||
img.Set(x, y, col)
|
||||
}
|
||||
}
|
||||
|
||||
// drawCurvedLine 绘制带弧度的贯穿斜线:沿 (x1,y1)→(x2,y2) 直线走向,
|
||||
// 按线段法向叠加 1~2 个正弦拱偏移(单拱似抛物线、双拱似波浪),拱向随机,
|
||||
// 起止点仍在直线两端——整体保持大倾角四向随机,线条本身带柔和小波浪。
|
||||
func drawCurvedLine(img *image.RGBA, x1, y1, x2, y2 int, col color.Color, thickness int) {
|
||||
dx, dy := x2-x1, y2-y1
|
||||
steps := max(abs(dx), abs(dy))
|
||||
if steps == 0 {
|
||||
return
|
||||
}
|
||||
lineLen := math.Hypot(float64(dx), float64(dy))
|
||||
amp := 3 + rand.Intn(4) // 拱高 3~6px
|
||||
arches := 1 + rand.Intn(2) // 1~2 个拱
|
||||
phase := rand.Float64() * 2 * math.Pi
|
||||
flip := 1.0
|
||||
if rand.Intn(2) == 0 {
|
||||
flip = -1.0 // 拱起方向随机(法向正/负)
|
||||
}
|
||||
nx, ny := float64(-dy)/lineLen, float64(dx)/lineLen // 单位法向量
|
||||
for i := 0; i <= steps; i++ {
|
||||
cx := x1 + dx*i/steps
|
||||
cy := y1 + dy*i/steps
|
||||
// 在垂直方向偏移绘制粗线效果
|
||||
for t := -(thickness - 1); t < thickness; t++ {
|
||||
// 根据线的方向决定偏移方向
|
||||
var px, py int
|
||||
if abs(dx) > abs(dy) {
|
||||
px = cx
|
||||
py = cy + t
|
||||
} else {
|
||||
px = cx + t
|
||||
py = cy
|
||||
}
|
||||
if px >= 0 && px < img.Bounds().Max.X && py >= 0 && py < img.Bounds().Max.Y {
|
||||
img.Set(px, py, col)
|
||||
}
|
||||
t := float64(i) / float64(steps)
|
||||
cx := float64(x1) + float64(dx)*t
|
||||
cy := float64(y1) + float64(dy)*t
|
||||
off := flip * float64(amp) * math.Sin(float64(arches)*2*math.Pi*t+phase)
|
||||
px := int(cx + nx*off + 0.5)
|
||||
py := int(cy + ny*off + 0.5)
|
||||
for k := 0; k < thickness; k++ {
|
||||
setPx(img, px, py+k-thickness/2, col)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 划线(单像素)
|
||||
func drawLine(img *image.RGBA, x1, y1, x2, y2 int, col color.Color) {
|
||||
dx, dy := x2-x1, y2-y1
|
||||
steps := max(abs(dx), abs(dy))
|
||||
if steps == 0 {
|
||||
// drawRing 绘制空心圆环(泡泡装饰)
|
||||
func drawRing(img *image.RGBA, cx, cy, radius int, col color.Color) {
|
||||
for step := 0; step < 72; step++ {
|
||||
a := float64(step) * math.Pi / 36
|
||||
x := cx + int(float64(radius)*math.Cos(a)+0.5)
|
||||
y := cy + int(float64(radius)*math.Sin(a)+0.5)
|
||||
setPx(img, x, y, col)
|
||||
}
|
||||
}
|
||||
|
||||
// strokeDirs 白色描边的 12 方向偏移(半径 2px 圆周均匀采样,叠出圆润粗描边)
|
||||
var strokeDirs []image.Point
|
||||
|
||||
func init() {
|
||||
for i := 0; i < 12; i++ {
|
||||
a := float64(i) * math.Pi / 6
|
||||
strokeDirs = append(strokeDirs, image.Point{
|
||||
int(math.Round(2 * math.Cos(a))),
|
||||
int(math.Round(2 * math.Sin(a))),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// drawStickerChar 以 (cx,cy) 为中心绘制“贴纸风”字符:
|
||||
// Sour Gummy 圆润字形 + 12 方向白色粗描边(贴纸效果)+ 糖果色填充,
|
||||
// 再按 angleDeg 旋转后以 alpha 混合贴到底图。
|
||||
// 按字形实际包围盒(而非 ascent/descent 行高)在临时画布中精确居中——
|
||||
// 数字无下降部,若按行高定位会整体偏上、下方留白偏大。
|
||||
func drawStickerChar(dst *image.RGBA, face font.Face, cx, cy int, char string, col color.RGBA, angleDeg float64) {
|
||||
// 测量字形包围盒(相对绘制原点 Dot 的 26.6 定点坐标)
|
||||
gb, _, _, _, ok := face.Glyph(fixed.Point26_6{}, []rune(char)[0])
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for i := 0; i <= steps; i++ {
|
||||
x := x1 + dx*i/steps
|
||||
y := y1 + dy*i/steps
|
||||
if x >= 0 && x < img.Bounds().Max.X && y >= 0 && y < img.Bounds().Max.Y {
|
||||
img.Set(x, y, col)
|
||||
glyphW := gb.Dx()
|
||||
glyphH := gb.Dy()
|
||||
|
||||
pad := 4 // 描边 + 旋转余量
|
||||
tmpW, tmpH := glyphW+pad*2, glyphH+pad*2
|
||||
tmp := image.NewRGBA(image.Rect(0, 0, tmpW, tmpH))
|
||||
|
||||
// 平移 Dot 使字形包围盒左上角恰好落在 (pad,pad),即字形在画布中精确居中
|
||||
baseDX := fixed.I(pad - gb.Min.X)
|
||||
baseDY := fixed.I(pad - gb.Min.Y)
|
||||
|
||||
// 白色描边:12 方向偏移叠加
|
||||
white := image.NewUniform(color.RGBA{255, 255, 255, 255})
|
||||
for _, off := range strokeDirs {
|
||||
fd := &font.Drawer{
|
||||
Dst: tmp, Src: white, Face: face,
|
||||
Dot: fixed.Point26_6{X: baseDX + fixed.I(off.X), Y: baseDY + fixed.I(off.Y)},
|
||||
}
|
||||
fd.DrawString(char)
|
||||
}
|
||||
// 糖果色主体
|
||||
fd := &font.Drawer{
|
||||
Dst: tmp, Src: image.NewUniform(col), Face: face,
|
||||
Dot: fixed.Point26_6{X: baseDX, Y: baseDY},
|
||||
}
|
||||
fd.DrawString(char)
|
||||
|
||||
rotateOverlay(dst, tmp, cx, cy, angleDeg)
|
||||
}
|
||||
|
||||
// rotateOverlay 将透明背景的 src 以 (cx,cy) 为中心旋转 angleDeg 后混合到 dst。
|
||||
// 反向映射 + 双线性采样:1:1 旋转下无空洞、边缘平滑无锯齿。
|
||||
func rotateOverlay(dst, src *image.RGBA, cx, cy int, angleDeg float64) {
|
||||
a := angleDeg * math.Pi / 180
|
||||
cos, sin := math.Cos(a), math.Sin(a)
|
||||
srcCx := float64(src.Bounds().Dx()) / 2
|
||||
srcCy := float64(src.Bounds().Dy()) / 2
|
||||
|
||||
radius := int(math.Hypot(srcCx, srcCy)) + 1
|
||||
db := dst.Bounds()
|
||||
for y := cy - radius; y <= cy+radius; y++ {
|
||||
if y < db.Min.Y || y >= db.Max.Y {
|
||||
continue
|
||||
}
|
||||
for x := cx - radius; x <= cx+radius; x++ {
|
||||
if x < db.Min.X || x >= db.Max.X {
|
||||
continue
|
||||
}
|
||||
dx, dy := float64(x-cx), float64(y-cy)
|
||||
sx := cos*dx + sin*dy + srcCx
|
||||
sy := -sin*dx + cos*dy + srcCy
|
||||
sr, sg, sb, sa := sampleBilinear(src, sx, sy)
|
||||
if sa <= 0 {
|
||||
continue
|
||||
}
|
||||
// 预乘 alpha 域的 over 混合:out = src + dst*(1-α)
|
||||
af := sa / 255
|
||||
dr, dg, dbb, da := dst.At(x, y).RGBA()
|
||||
nr := sr + float64(dr>>8)*(1-af)
|
||||
ng := sg + float64(dg>>8)*(1-af)
|
||||
nb := sb + float64(dbb>>8)*(1-af)
|
||||
na := sa + float64(da>>8)*(1-af)
|
||||
dst.Set(x, y, color.RGBA{uint8(nr), uint8(ng), uint8(nb), uint8(na)})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sampleBilinear 对预乘 alpha 的 RGBA 图做双线性采样,返回 0-255 范围的预乘 RGBA
|
||||
func sampleBilinear(src *image.RGBA, sx, sy float64) (r, g, b, a float64) {
|
||||
bnd := src.Bounds()
|
||||
x0, y0 := int(math.Floor(sx)), int(math.Floor(sy))
|
||||
fx, fy := sx-float64(x0), sy-float64(y0)
|
||||
if sx < 0 || sy < 0 || sx >= float64(bnd.Max.X) || sy >= float64(bnd.Max.Y) {
|
||||
return 0, 0, 0, 0
|
||||
}
|
||||
for dy := 0; dy <= 1; dy++ {
|
||||
for dx := 0; dx <= 1; dx++ {
|
||||
px, py := x0+dx, y0+dy
|
||||
if px < bnd.Min.X || px >= bnd.Max.X || py < bnd.Min.Y || py >= bnd.Max.Y {
|
||||
continue
|
||||
}
|
||||
wx := 1 - fx
|
||||
if dx == 1 {
|
||||
wx = fx
|
||||
}
|
||||
wy := 1 - fy
|
||||
if dy == 1 {
|
||||
wy = fy
|
||||
}
|
||||
w := wx * wy
|
||||
if w == 0 {
|
||||
continue
|
||||
}
|
||||
c := src.RGBAAt(px, py)
|
||||
r += float64(c.R) * w
|
||||
g += float64(c.G) * w
|
||||
b += float64(c.B) * w
|
||||
a += float64(c.A) * w
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 画粗线(绘制多条平行线模拟粗线)
|
||||
|
||||
// 绘制半透明圆圈
|
||||
func drawCircle(img *image.RGBA, cx, cy, radius int, col color.Color) {
|
||||
for dy := -radius; dy <= radius; dy++ {
|
||||
@@ -399,165 +586,6 @@ func drawCircle(img *image.RGBA, cx, cy, radius int, col color.Color) {
|
||||
}
|
||||
}
|
||||
|
||||
// 绘制小星星闪光点
|
||||
func drawStarDot(img *image.RGBA, x, y int, col color.Color) {
|
||||
offsets := [][2]int{
|
||||
{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1},
|
||||
{1, 1}, {-1, -1}, {1, -1}, {-1, 1},
|
||||
}
|
||||
for _, off := range offsets {
|
||||
px := x + off[0]
|
||||
py := y + off[1]
|
||||
if px >= 0 && px < img.Bounds().Max.X && py >= 0 && py < img.Bounds().Max.Y {
|
||||
img.Set(px, py, col)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 使用 7x9 点阵绘制大号字符(带倾斜 shear 效果)
|
||||
func drawCharLarge(img *image.RGBA, x, y int, char string, col color.Color, pixelSize int, shear int) {
|
||||
// 7x9 数字点阵映射
|
||||
charMaps := map[string][][]int{
|
||||
"0": {
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
"1": {
|
||||
{0, 0, 0, 1, 0, 0, 0},
|
||||
{0, 0, 1, 1, 0, 0, 0},
|
||||
{0, 1, 1, 1, 0, 0, 0},
|
||||
{0, 0, 0, 1, 0, 0, 0},
|
||||
{0, 0, 0, 1, 0, 0, 0},
|
||||
{0, 0, 0, 1, 0, 0, 0},
|
||||
{0, 0, 0, 1, 0, 0, 0},
|
||||
{0, 0, 0, 1, 0, 0, 0},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
"2": {
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 0, 0, 0, 0, 0},
|
||||
{1, 1, 0, 0, 0, 0, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
"3": {
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
"4": {
|
||||
{0, 0, 0, 0, 1, 1, 0},
|
||||
{0, 0, 0, 1, 1, 1, 0},
|
||||
{0, 0, 1, 1, 1, 1, 0},
|
||||
{0, 1, 1, 0, 1, 1, 0},
|
||||
{1, 1, 0, 0, 1, 1, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 0, 0, 0, 1, 1, 0},
|
||||
{0, 0, 0, 0, 1, 1, 0},
|
||||
{0, 0, 0, 0, 1, 1, 0},
|
||||
},
|
||||
"5": {
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{1, 1, 0, 0, 0, 0, 0},
|
||||
{1, 1, 0, 0, 0, 0, 0},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
"6": {
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{1, 1, 0, 0, 0, 0, 0},
|
||||
{1, 1, 0, 0, 0, 0, 0},
|
||||
{1, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
"7": {
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 0, 0, 0, 1, 1, 0},
|
||||
{0, 0, 0, 1, 1, 0, 0},
|
||||
{0, 0, 1, 1, 0, 0, 0},
|
||||
{0, 0, 1, 1, 0, 0, 0},
|
||||
{0, 0, 1, 1, 0, 0, 0},
|
||||
},
|
||||
"8": {
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
"9": {
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{1, 1, 0, 0, 0, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{0, 0, 0, 0, 0, 1, 1},
|
||||
{1, 1, 1, 1, 1, 1, 1},
|
||||
{0, 1, 1, 1, 1, 1, 0},
|
||||
},
|
||||
}
|
||||
|
||||
pattern, ok := charMaps[char]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// shear: 每行相对中心行(4)的水平偏移
|
||||
// shear=1: 行0偏移-4, 行8偏移+4 → 右倾
|
||||
// shear=-1: 行0偏移+4, 行8偏移-4 → 左倾
|
||||
for py, row := range pattern {
|
||||
// 行偏移量 = (py - 4) * shear
|
||||
rowShear := (py - 4) * shear
|
||||
|
||||
for px, v := range row {
|
||||
if v == 1 {
|
||||
ix := x + px*pixelSize + rowShear
|
||||
iy := y + py*pixelSize
|
||||
for dx := 0; dx < pixelSize; dx++ {
|
||||
for dy := 0; dy < pixelSize; dy++ {
|
||||
if ix+dx < img.Bounds().Max.X && iy+dy < img.Bounds().Max.Y {
|
||||
img.Set(ix+dx, iy+dy, col)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func abs(x int) int {
|
||||
if x < 0 {
|
||||
return -x
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// simpleCookieJar 简化的 CookieJar 实现
|
||||
@@ -29,6 +30,20 @@ func (j *simpleCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
|
||||
cookieMap[c.Name] = c
|
||||
}
|
||||
for _, c := range cookies {
|
||||
// 删除指令(Max-Age<=0 或 Expires 已过)或空值:一律跳过,既不入库也不删除
|
||||
// 已有同名 cookie。simpleCookieJar 不记录 Path/Domain,无法按 RFC 6265 精确
|
||||
// 匹配删除指令的作用域。云大 CAS 登录 POST 成功后先发
|
||||
// CASTGC=TGT-...; Path=/authserver
|
||||
// 再发删除指令
|
||||
// CASTGC=; Max-Age=0; path=/authserver/ (注意尾部斜杠,与 TGT 的 Path 不同)
|
||||
// 浏览器依 RFC 6265 不会删除 TGT,后续 MFA 页面(reAuthLoginView.do)依赖该
|
||||
// TGT 判定 SSO 会话;若按名字粗暴删除 TGT,MFA 页会被 302 踢回登录页。
|
||||
// 若把空值 CASTGC 存进 jar 发送空值,同样会被判定会话异常(历史 bug)。
|
||||
// 跳过删除指令可同时避免这两种问题;同名残留会在下次登录时被 CAS 重新
|
||||
// Set-Cookie 覆盖,无实际副作用。
|
||||
if c.MaxAge < 0 || (!c.Expires.IsZero() && c.Expires.Before(time.Now())) || c.Value == "" {
|
||||
continue
|
||||
}
|
||||
cookieMap[c.Name] = c
|
||||
}
|
||||
|
||||
@@ -67,3 +82,18 @@ func (j *simpleCookieJar) AllCookies() []*http.Cookie {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// AllCookiesByHost 按域名分组返回所有 cookie(MFA 会话暂存用,保留域结构以便恢复)
|
||||
func (j *simpleCookieJar) AllCookiesByHost() map[string][]*http.Cookie {
|
||||
j.mu.RLock()
|
||||
defer j.mu.RUnlock()
|
||||
result := make(map[string][]*http.Cookie, len(j.cookies))
|
||||
for host, cookies := range j.cookies {
|
||||
if len(cookies) > 0 {
|
||||
cp := make([]*http.Cookie, len(cookies))
|
||||
copy(cp, cookies)
|
||||
result[host] = cp
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -3,10 +3,13 @@ package cpdaily
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/textproto"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
@@ -14,11 +17,12 @@ import (
|
||||
|
||||
// CpImageUploadPolicy 今日校园 OBS 上传策略
|
||||
type CpImageUploadPolicy struct {
|
||||
AccessId string `json:"accessid"`
|
||||
FileName string `json:"fileName"`
|
||||
Policy string `json:"policy"`
|
||||
Host string `json:"host"`
|
||||
Signature string `json:"signature"`
|
||||
AccessId string `json:"accessid"`
|
||||
FileName string `json:"fileName"`
|
||||
Policy string `json:"policy"`
|
||||
Host string `json:"host"`
|
||||
Signature string `json:"signature"`
|
||||
FormData map[string]string `json:"formData"`
|
||||
}
|
||||
|
||||
// getImageUrlPrefix 根据任务类型返回图片上传的 URL 前缀
|
||||
@@ -26,6 +30,9 @@ func getImageUrlPrefix(taskType TaskType) string {
|
||||
switch taskType {
|
||||
case TaskTypeSleepCheck:
|
||||
return "/wec-counselor-attendance-apps/student/attendance"
|
||||
case TaskTypeLeave:
|
||||
// 销假图片上传走请假模块
|
||||
return "/wec-counselor-leave-apps/leave"
|
||||
case TaskTypeSign:
|
||||
return "/wec-counselor-sign-apps/stu"
|
||||
default:
|
||||
@@ -65,7 +72,7 @@ func GetUploadPolicy(cookieMap map[string]string, host string, taskType TaskType
|
||||
ErrMsg string `json:"errMsg"`
|
||||
Datas *CpImageUploadPolicy `json:"datas"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析上传策略失败: %w", err)
|
||||
}
|
||||
if result.ErrCode != 0 || result.Datas == nil {
|
||||
@@ -75,7 +82,11 @@ func GetUploadPolicy(cookieMap map[string]string, host string, taskType TaskType
|
||||
return result.Datas, nil
|
||||
}
|
||||
|
||||
// uploadToOBS 将文件上传到今日校园的 OBS
|
||||
// uploadToOBS 将文件上传到今日校园的 OBS。
|
||||
// 优先使用接口返回的 formData 字段集原样提交:不同任务类型的表单字段不同
|
||||
// (查寝:AccessKeyId/signature/x-obs-acl;签到:q-ak/q-key-time/q-signature 等),
|
||||
// 按旧方式自行拼装字段会导致签到类型上传被 OBS 拒绝(AccessDenied)。
|
||||
// 仅当接口未返回 formData 时回退到通用字段拼装。
|
||||
func uploadToOBS(policy *CpImageUploadPolicy, fileData []byte, contentType string) error {
|
||||
client := resty.New().SetTimeout(30 * time.Second).SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
|
||||
|
||||
@@ -87,15 +98,26 @@ func uploadToOBS(policy *CpImageUploadPolicy, fileData []byte, contentType strin
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
|
||||
writer.WriteField("x-obs-acl", "public-read")
|
||||
writer.WriteField("AccessKeyId", policy.AccessId)
|
||||
writer.WriteField("key", policy.FileName)
|
||||
writer.WriteField("signature", policy.Signature)
|
||||
writer.WriteField("policy", policy.Policy)
|
||||
writer.WriteField("content-type", contentType)
|
||||
if len(policy.FormData) > 0 {
|
||||
for k, v := range policy.FormData {
|
||||
writer.WriteField(k, v)
|
||||
}
|
||||
header := make(textproto.MIMEHeader)
|
||||
header.Set("Content-Disposition", `form-data; name="file"; filename="file.jpg"`)
|
||||
header.Set("Content-Type", contentType)
|
||||
part, _ := writer.CreatePart(header)
|
||||
part.Write(fileData)
|
||||
} else {
|
||||
writer.WriteField("x-obs-acl", "public-read")
|
||||
writer.WriteField("AccessKeyId", policy.AccessId)
|
||||
writer.WriteField("key", policy.FileName)
|
||||
writer.WriteField("signature", policy.Signature)
|
||||
writer.WriteField("policy", policy.Policy)
|
||||
writer.WriteField("content-type", contentType)
|
||||
|
||||
part, _ := writer.CreateFormFile("file", "file")
|
||||
part.Write(fileData)
|
||||
part, _ := writer.CreateFormFile("file", "file")
|
||||
part.Write(fileData)
|
||||
}
|
||||
writer.Close()
|
||||
|
||||
resp, err := client.R().
|
||||
@@ -123,6 +145,9 @@ func GetPreviewUrl(cookieMap map[string]string, host string, taskType TaskType,
|
||||
switch taskType {
|
||||
case TaskTypeSleepCheck:
|
||||
apiPath = "/previewAttachment"
|
||||
case TaskTypeLeave:
|
||||
// 销假图片预览走请假模块 OBS 接口
|
||||
apiPath = "/obs/previewAttachment"
|
||||
case TaskTypeSign:
|
||||
apiPath = "/sign/previewAttachment"
|
||||
default:
|
||||
@@ -145,15 +170,33 @@ func GetPreviewUrl(cookieMap map[string]string, host string, taskType TaskType,
|
||||
body, _ := io.ReadAll(resp.RawBody())
|
||||
var result struct {
|
||||
ErrCode int `json:"errCode"`
|
||||
Code json.RawMessage `json:"code"`
|
||||
ErrMsg string `json:"errMsg"`
|
||||
Message string `json:"message"`
|
||||
Datas json.RawMessage `json:"datas"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return "", fmt.Errorf("解析预览 URL 响应失败: %w", err)
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return "", fmt.Errorf("解析预览 URL 响应失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
return "", fmt.Errorf("获取预览 URL 错误(%d): %s", result.ErrCode, result.ErrMsg)
|
||||
}
|
||||
// 部分学校(如 cyprxy 代理域)返回 {"code":"0",...} 方言
|
||||
if len(result.Code) > 0 {
|
||||
var codeStr string
|
||||
if json.Unmarshal(result.Code, &codeStr) == nil {
|
||||
if codeStr != "" && codeStr != "0" {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = result.ErrMsg
|
||||
}
|
||||
return "", fmt.Errorf("获取预览 URL 错误(%s): %s", codeStr, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(result.Datas) == 0 || string(result.Datas) == "null" {
|
||||
return "", fmt.Errorf("获取预览 URL 为空(body: %.200s)", string(body))
|
||||
}
|
||||
|
||||
var previewUrl string
|
||||
if err := json.Unmarshal(result.Datas, &previewUrl); err != nil {
|
||||
@@ -164,6 +207,7 @@ func GetPreviewUrl(cookieMap map[string]string, host string, taskType TaskType,
|
||||
}
|
||||
|
||||
// UploadImage 完整的图片上传流程:获取策略 → 上传 OBS → 获取预览 URL
|
||||
// 预览接口偶发返回空响应,做少量重试避免误判失败
|
||||
func UploadImage(cookieMap map[string]string, host string, taskType TaskType, fileData []byte, contentType string) (string, error) {
|
||||
policy, err := GetUploadPolicy(cookieMap, host, taskType)
|
||||
if err != nil {
|
||||
@@ -174,17 +218,47 @@ func UploadImage(cookieMap map[string]string, host string, taskType TaskType, fi
|
||||
return "", err
|
||||
}
|
||||
|
||||
previewUrl, err := GetPreviewUrl(cookieMap, host, taskType, policy.FileName)
|
||||
if err != nil {
|
||||
return "", err
|
||||
var previewUrl string
|
||||
var lastErr error
|
||||
for i := 0; i < 3; i++ {
|
||||
if i > 0 {
|
||||
time.Sleep(time.Duration(i) * time.Second)
|
||||
}
|
||||
previewUrl, lastErr = GetPreviewUrl(cookieMap, host, taskType, policy.FileName)
|
||||
if lastErr == nil {
|
||||
return previewUrl, nil
|
||||
}
|
||||
// 业务性错误(错误码/数据为空)无需重试,仅空响应类瞬时错误重试
|
||||
if !strings.Contains(lastErr.Error(), "解析预览 URL 响应失败") && !strings.Contains(lastErr.Error(), "获取预览 URL 为空") {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return previewUrl, nil
|
||||
return "", lastErr
|
||||
}
|
||||
|
||||
// IsDataURIImage 判断内容是否为 base64 图片(前端本地预览,尚未成功上传到 OBS)
|
||||
func IsDataURIImage(content string) bool {
|
||||
return strings.HasPrefix(content, "data:image")
|
||||
}
|
||||
|
||||
// UploadDataURIImage 将 base64 图片解码后走正常 OBS 上传流程,返回正式预览 URL。
|
||||
// 用于执行时自动修复历史表单中残留的 base64 照片(用户上传失败时保存的内容)。
|
||||
func UploadDataURIImage(cookieMap map[string]string, host string, taskType TaskType, dataURI string) (string, error) {
|
||||
idx := strings.Index(dataURI, ",")
|
||||
if idx < 0 {
|
||||
return "", fmt.Errorf("图片数据格式不正确")
|
||||
}
|
||||
imgBytes, err := base64.StdEncoding.DecodeString(dataURI[idx+1:])
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("解码图片失败: %w", err)
|
||||
}
|
||||
return UploadImage(cookieMap, host, taskType, imgBytes, "image/jpeg")
|
||||
}
|
||||
|
||||
func newImgClient() *resty.Client {
|
||||
return resty.New().
|
||||
SetTimeout(30*time.Second).
|
||||
SetTimeout(30 * time.Second).
|
||||
SetDoNotParseResponse(true).
|
||||
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 销假(请假销假)功能。
|
||||
// 对应今日校园 wec-counselor-leave-apps 模块:
|
||||
//
|
||||
// 待销假列表:POST {host}/wec-counselor-leave-apps/leave/stu/listOther
|
||||
// 请假详情: POST {host}/wec-counselor-leave-apps/leave/stu/detailOther
|
||||
// 审批人列表:POST {host}/wec-counselor-leave-apps/leave/stu/obtainApproveFlow
|
||||
// 提交销假: POST {host}/wec-counselor-leave-apps/leave/report
|
||||
const leaveAPIBase = "/wec-counselor-leave-apps/leave"
|
||||
|
||||
// LeaveReportPlace 学校规定的销假位置(详情 reportPlaces 元素)。
|
||||
// 销假提交的位置应在其中一个位置的 radius(米)范围内;
|
||||
// 老版本取 leaveExtends[0](续假位置)或 detail.applyLocation(请假提交时定位),
|
||||
// 均非学校规定的销假位置,已按真实接口修正为 reportPlaces。
|
||||
type LeaveReportPlace struct {
|
||||
Wid string `json:"wid"`
|
||||
Address string `json:"address"`
|
||||
Longitude string `json:"longitude"`
|
||||
Latitude string `json:"latitude"`
|
||||
Radius string `json:"radius"` // 允许范围半径(米)
|
||||
CounName string `json:"counName"` // 位置设置人
|
||||
}
|
||||
|
||||
// LeaveApprover 销假可选审批人(leaveType.reportApplyFlow=1 时需要)
|
||||
type LeaveApprover struct {
|
||||
UserWid string `json:"userWid"`
|
||||
UserId string `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
}
|
||||
|
||||
// LeaveItem 待销假记录(列表展示 + 销假表单所需开关/规定位置)
|
||||
type LeaveItem struct {
|
||||
ID string `json:"id"` // 请假记录 ID
|
||||
LeaveType string `json:"leaveType"` // 请假类型名称(如 事假/病假)
|
||||
Reason string `json:"reason"` // 请假原因
|
||||
CreateTime string `json:"createTime"` // 请假提交时间
|
||||
ActEndTime string `json:"actEndTime"` // 预计结束时间
|
||||
Status string `json:"status"` // 系统请假状态码(4=已完成,已过滤)
|
||||
// 状态文案(新套有明确文案映射;旧套为空,前端回退本地映射)
|
||||
StatusText string `json:"statusText,omitempty"`
|
||||
// 学校规定的销假位置(详情 reportPlaces)。有值时前端展示可选列表并预填经纬度;
|
||||
// 无值时提示用户手动填写
|
||||
ReportPlaces []LeaveReportPlace `json:"reportPlaces"`
|
||||
// 销假是否需要选择审批人(leaveType.reportApplyFlow=1)
|
||||
ReportApplyFlow bool `json:"reportApplyFlow"`
|
||||
// 销假是否允许上传图片(leaveType.enableAttach=1)
|
||||
EnableAttach bool `json:"enableAttach"`
|
||||
}
|
||||
|
||||
// LeaveDetail 请假详情(提交销假所需字段)
|
||||
type LeaveDetail struct {
|
||||
ReportID string // datas.detail.id,提交表单的 id 字段
|
||||
LeaveType string // datas.leaveType.name
|
||||
LeaveCode string // datas.leaveType.code,提交表单 leaveType 字段(接口返回为数字,统一转纯文本)
|
||||
LeaveCodeNum int // datas.leaveType.code 数字形式(obtainApproveFlow 请求用)
|
||||
StartTime string // datas.detail.startDate(审批流请求用,提交前补秒)
|
||||
EndTime string // datas.detail.endDate
|
||||
ReportApplyFlow bool // 销假需要选择审批人
|
||||
EnableAttach bool // 销假允许上传图片
|
||||
ReportPlaces []LeaveReportPlace
|
||||
}
|
||||
|
||||
// leaveAnyStr 将 interface{} 值转为纯文本字符串(数字类型避免科学计数法)
|
||||
func leaveAnyStr(v interface{}) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
switch t := v.(type) {
|
||||
case string:
|
||||
return t
|
||||
case float64:
|
||||
return strconv.FormatFloat(t, 'f', -1, 64)
|
||||
case json.Number:
|
||||
return t.String()
|
||||
case bool:
|
||||
return strconv.FormatBool(t)
|
||||
default:
|
||||
return fmt.Sprintf("%v", v)
|
||||
}
|
||||
}
|
||||
|
||||
// leaveAnyBool 将 interface{} 值转为布尔(兼容数字/字符串/布尔三种返回风格)
|
||||
func leaveAnyBool(v interface{}) bool {
|
||||
switch t := v.(type) {
|
||||
case bool:
|
||||
return t
|
||||
case float64:
|
||||
return t != 0
|
||||
case json.Number:
|
||||
n, _ := t.Int64()
|
||||
return n != 0
|
||||
case string:
|
||||
return t == "1" || strings.EqualFold(t, "true")
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// leaveAnyInt 将 interface{} 值转为整数(兼容数字/字符串两种返回风格)
|
||||
func leaveAnyInt(v interface{}) int {
|
||||
switch t := v.(type) {
|
||||
case float64:
|
||||
return int(t)
|
||||
case json.Number:
|
||||
n, _ := t.Int64()
|
||||
return int(n)
|
||||
case string:
|
||||
n, _ := strconv.Atoi(strings.TrimSpace(t))
|
||||
return n
|
||||
case bool:
|
||||
if t {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// leaveMapStr 从 map 中取字符串值
|
||||
func leaveMapStr(m map[string]interface{}, key string) string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
return leaveAnyStr(m[key])
|
||||
}
|
||||
|
||||
// leaveTimeWithSeconds 将 "2025-10-24 20:45" 补秒为审批流接口要求的 "2025-10-24 20:45:00"
|
||||
func leaveTimeWithSeconds(t string) string {
|
||||
t = strings.TrimSpace(t)
|
||||
if len(t) == 16 { // yyyy-MM-dd HH:mm
|
||||
return t + ":00"
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// leavePost 通用 POST 请求(带移动端 UA 与 Cookie),返回响应 body;
|
||||
// extension 非空时额外携带 Cpdaily-Extension 签名头(销假提交用)
|
||||
func leavePost(cookieMap map[string]string, url string, body interface{}, extension string) ([]byte, error) {
|
||||
client := newTaskClient()
|
||||
req := client.R().
|
||||
SetHeader("User-Agent", "Mozilla/5.0 (Linux; Android 15; Redmi Note 8 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.81 Mobile Safari/537.36 cpdaily/9.9.6 wisedu/9.9.6").
|
||||
SetHeader("CpdailyClientType", "CPDAILY").
|
||||
SetHeader("Content-Type", "application/json; charset=UTF-8").
|
||||
SetHeader("Cookie", cookiesToStr(cookieMap))
|
||||
if extension != "" {
|
||||
req = req.SetHeader("Cpdaily-Extension", extension)
|
||||
}
|
||||
resp, err := req.SetBody(body).Post(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.RawBody().Close()
|
||||
respBody, err := io.ReadAll(resp.RawBody())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// HTTP 状态码异常:学校网关/WAF 拦截或上游故障常返回无 body 的 4xx/5xx,
|
||||
// 若不在这里拦截,上层会把空 body 报成无意义的 JSON 解析错误。
|
||||
if code := resp.StatusCode(); code < 200 || code >= 300 {
|
||||
return respBody, fmt.Errorf("学校服务端响应异常(HTTP %d): %s", code, strings.TrimSpace(string(respBody)))
|
||||
}
|
||||
// 状态码正常但 body 为空:多见于重复提交触发风控或网关瞬时故障
|
||||
if len(respBody) == 0 {
|
||||
return respBody, fmt.Errorf("学校服务端返回空响应(HTTP %d),可能触发风控或瞬时故障,请稍后重试", resp.StatusCode())
|
||||
}
|
||||
return respBody, nil
|
||||
}
|
||||
|
||||
// FetchLeaveList 获取今日校园待销假列表。
|
||||
// 过滤已完成(status=4)的记录;每条记录附带详情中的规定销假位置(reportPlaces)
|
||||
// 与开关(reportApplyFlow/enableAttach)。
|
||||
// 详情获取失败不阻塞列表展示(仅视为无规定位置、无开关)。
|
||||
func FetchLeaveList(cookieMap map[string]string, host string) ([]LeaveItem, error) {
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/stu/listOther", map[string]interface{}{
|
||||
"pageNumber": 1,
|
||||
"pageSize": 20,
|
||||
"needApproval": 1,
|
||||
}, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取待销假列表失败: %w", err)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
ErrCode int `json:"errCode"`
|
||||
Message string `json:"message"`
|
||||
Datas struct {
|
||||
Rows []map[string]interface{} `json:"rows"`
|
||||
} `json:"datas"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析待销假列表失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
return nil, fmt.Errorf("获取待销假列表错误(%d): %s", result.ErrCode, result.Message)
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
list := make([]LeaveItem, 0, len(result.Datas.Rows))
|
||||
for _, row := range result.Datas.Rows {
|
||||
status := leaveMapStr(row, "status")
|
||||
// 待销假列表只保留可销假的记录:
|
||||
// 4=已完成、3=已驳回、10=逾期自动驳回 均无需(也不应)销假,直接过滤。
|
||||
// 注:驳回状态若不过滤,已驳回的请假会出现在待销假列表中(用户无法对其销假)。
|
||||
if status == "4" || status == "3" || status == "10" {
|
||||
continue
|
||||
}
|
||||
id := leaveMapStr(row, "id")
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
item := LeaveItem{
|
||||
ID: id,
|
||||
LeaveType: leaveMapStr(row, "leaveType"),
|
||||
Reason: leaveMapStr(row, "leaveReason"),
|
||||
CreateTime: leaveMapStr(row, "createTime"),
|
||||
ActEndTime: leaveMapStr(row, "actEndTime"),
|
||||
Status: status,
|
||||
}
|
||||
// 补充规定销假位置与开关(来自详情 reportPlaces / leaveType)
|
||||
if d, err := FetchLeaveDetail(cookieMap, host, id); err == nil {
|
||||
item.ReportPlaces = d.ReportPlaces
|
||||
item.ReportApplyFlow = d.ReportApplyFlow
|
||||
item.EnableAttach = d.EnableAttach
|
||||
} else {
|
||||
slog.Warn("获取请假详情失败,规定销假位置与开关视为空", "leaveId", id, "error", err)
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// FetchLeaveDetail 获取请假详情(提交销假所需字段 + 规定销假位置与开关)
|
||||
func FetchLeaveDetail(cookieMap map[string]string, host, leaveID string) (*LeaveDetail, error) {
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/stu/detailOther", map[string]interface{}{
|
||||
"id": leaveID,
|
||||
"needApproval": 1,
|
||||
"uaIsCpadaily": "true",
|
||||
}, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取请假详情失败: %w", err)
|
||||
}
|
||||
|
||||
// 注意:leaveType.code 真实返回为数字(如 3/12),必须用 interface{} 承接
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
ErrCode int `json:"errCode"`
|
||||
Message string `json:"message"`
|
||||
Datas struct {
|
||||
Detail struct {
|
||||
ID string `json:"id"`
|
||||
StartDate string `json:"startDate"`
|
||||
EndDate string `json:"endDate"`
|
||||
} `json:"detail"`
|
||||
LeaveType struct {
|
||||
Code interface{} `json:"code"`
|
||||
Name string `json:"name"`
|
||||
ReportApplyFlow interface{} `json:"reportApplyFlow"`
|
||||
EnableAttach interface{} `json:"enableAttach"`
|
||||
} `json:"leaveType"`
|
||||
ReportPlaces []struct {
|
||||
Wid interface{} `json:"wid"`
|
||||
Address string `json:"address"`
|
||||
Longitude interface{} `json:"longitude"`
|
||||
Latitude interface{} `json:"latitude"`
|
||||
Radius interface{} `json:"radius"`
|
||||
CounName string `json:"counName"`
|
||||
} `json:"reportPlaces"`
|
||||
} `json:"datas"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析请假详情失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
return nil, fmt.Errorf("获取请假详情错误(%d): %s", result.ErrCode, result.Message)
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
if result.Datas.Detail.ID == "" {
|
||||
return nil, fmt.Errorf("没有获取到请假详情信息")
|
||||
}
|
||||
|
||||
codeStr := leaveAnyStr(result.Datas.LeaveType.Code)
|
||||
codeNum, _ := strconv.Atoi(codeStr)
|
||||
d := &LeaveDetail{
|
||||
ReportID: result.Datas.Detail.ID,
|
||||
LeaveType: result.Datas.LeaveType.Name,
|
||||
LeaveCode: codeStr,
|
||||
LeaveCodeNum: codeNum,
|
||||
StartTime: result.Datas.Detail.StartDate,
|
||||
EndTime: result.Datas.Detail.EndDate,
|
||||
ReportApplyFlow: leaveAnyBool(result.Datas.LeaveType.ReportApplyFlow),
|
||||
EnableAttach: leaveAnyBool(result.Datas.LeaveType.EnableAttach),
|
||||
}
|
||||
for _, p := range result.Datas.ReportPlaces {
|
||||
d.ReportPlaces = append(d.ReportPlaces, LeaveReportPlace{
|
||||
Wid: leaveAnyStr(p.Wid),
|
||||
Address: p.Address,
|
||||
Longitude: leaveAnyStr(p.Longitude),
|
||||
Latitude: leaveAnyStr(p.Latitude),
|
||||
Radius: leaveAnyStr(p.Radius),
|
||||
CounName: p.CounName,
|
||||
})
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// FetchReportApprovers 获取销假可选审批人(leaveType.reportApplyFlow=1 的请假类型使用)。
|
||||
// 复用请假申请的审批流接口;时间必须精确到秒(yyyy-MM-dd HH:mm:ss)。
|
||||
// 优先取 datas.approvers(首节点可选审批人),为空时兜底展开 approveNodes 中的全部审批人。
|
||||
func FetchReportApprovers(cookieMap map[string]string, host string, leaveCodeNum int, startTime, endTime string) ([]LeaveApprover, error) {
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/stu/obtainApproveFlow", map[string]interface{}{
|
||||
"leaveType": leaveCodeNum,
|
||||
"startTime": leaveTimeWithSeconds(startTime),
|
||||
"endTime": leaveTimeWithSeconds(endTime),
|
||||
}, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取销假审批人失败: %w", err)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Datas struct {
|
||||
Approvers []LeaveApprover `json:"approvers"`
|
||||
ApproveNodes []struct {
|
||||
ApproveNode []struct {
|
||||
NodeName string `json:"nodeName"`
|
||||
Approvers []LeaveApprover `json:"approvers"`
|
||||
} `json:"approveNode"`
|
||||
} `json:"approveNodes"`
|
||||
} `json:"datas"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析销假审批人失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
list := make([]LeaveApprover, 0, len(result.Datas.Approvers))
|
||||
seen := make(map[string]bool)
|
||||
for _, a := range result.Datas.Approvers {
|
||||
if a.UserWid == "" || seen[a.UserWid] {
|
||||
continue
|
||||
}
|
||||
seen[a.UserWid] = true
|
||||
list = append(list, a)
|
||||
}
|
||||
if len(list) == 0 {
|
||||
for _, n := range result.Datas.ApproveNodes {
|
||||
for _, node := range n.ApproveNode {
|
||||
for _, a := range node.Approvers {
|
||||
if a.UserWid == "" || seen[a.UserWid] {
|
||||
continue
|
||||
}
|
||||
seen[a.UserWid] = true
|
||||
list = append(list, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// BuildLeaveReportForm 构造销假提交表单(bodyString 内容)。
|
||||
// reportLocation 为用户选择/填写的销假地址,为空时兜底第一个规定销假位置地址;
|
||||
// approverWid 为所选审批人(reportApplyFlow=1 时必填,其余传空)。
|
||||
func BuildLeaveReportForm(d *LeaveDetail, address, imageUrl, approverWid string) map[string]interface{} {
|
||||
if address == "" && len(d.ReportPlaces) > 0 {
|
||||
address = d.ReportPlaces[0].Address
|
||||
}
|
||||
form := map[string]interface{}{
|
||||
"id": d.ReportID,
|
||||
"needApproval": 1,
|
||||
"leaveType": d.LeaveCode,
|
||||
"reportLocation": address,
|
||||
"approverWid": approverWid,
|
||||
"reportApplyExplain": nil,
|
||||
"uaIsCpadaily": true,
|
||||
}
|
||||
if imageUrl != "" {
|
||||
form["reportAttach"] = []map[string]interface{}{
|
||||
{"type": 1, "url": imageUrl},
|
||||
}
|
||||
} else {
|
||||
form["reportAttach"] = []interface{}{}
|
||||
}
|
||||
return form
|
||||
}
|
||||
|
||||
// SubmitLeaveReport 提交销假(bodyString 加密 + Cpdaily-Extension 签名,与签到提交同构)
|
||||
func SubmitLeaveReport(cookieMap map[string]string, host string, form map[string]interface{}, lon, lat, deviceId, username string) error {
|
||||
bodyString := GetBodyString(form)
|
||||
extensionString := GetExtensionString(lat, lon, deviceId, username)
|
||||
|
||||
submitData := map[string]interface{}{
|
||||
"lon": lon,
|
||||
"version": "first_v4",
|
||||
"calVersion": "first_v4",
|
||||
"deviceId": deviceId,
|
||||
"systemName": "android",
|
||||
"bodyString": bodyString,
|
||||
"lat": lat,
|
||||
"systemVersion": "15",
|
||||
"appVersion": "9.9.6",
|
||||
"model": "cpdaily",
|
||||
}
|
||||
submitData["userId"] = username
|
||||
submitData["sign"] = GetSubmitSign(submitData)
|
||||
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/report", submitData, extensionString)
|
||||
if err != nil {
|
||||
return fmt.Errorf("提交销假请求失败: %w", err)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return fmt.Errorf("解析销假响应失败: %w, body: %s", err, string(body))
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
slog.Info("leave/report 响应", "code", result.Code.String(), "message", result.Message, "body", string(body))
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
// 2210990000:学校要求销假必须上传附件。enableAttach 字段在旧套不可靠
|
||||
// (实测多所旧套学校恒为 0),无法提交前拦截,只能在此识别并引导用户。
|
||||
if code == 2210990000 {
|
||||
msg = "该请假销假需要上传附件图片,请上传附件后重试"
|
||||
}
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// 请假申请功能(与销假同属 wec-counselor-leave-apps 模块):
|
||||
//
|
||||
// 请假类型列表:POST {host}/wec-counselor-leave-apps/leave/queryLeaveTypes
|
||||
// 类型详细配置:POST {host}/wec-counselor-leave-apps/leave/stu/queryLeaveTypeCfg
|
||||
// 可请假检查: POST {host}/wec-counselor-leave-apps/leave/stu/checkOnceLeave
|
||||
// 审批人列表: POST {host}/wec-counselor-leave-apps/leave/stu/obtainApproveFlow
|
||||
// 提交请假: POST {host}/wec-counselor-leave-apps/leave/apply
|
||||
//
|
||||
// 注意:真实接口中 queryLeaveTypes 只返回基础信息(needApproval/enableAttach 等
|
||||
// 均为 null),权威开关全部来自 queryLeaveTypeCfg,故列表接口会把两者合并后返回。
|
||||
|
||||
// LeaveType 请假类型(queryLeaveTypes + queryLeaveTypeCfg 合并后的完整信息)
|
||||
type LeaveType struct {
|
||||
Code int `json:"code"` // 类型编码(提交与查询都用它)
|
||||
Name string `json:"name"` // 类型名称
|
||||
MustOut int `json:"mustOut"` // 1=必须离校(离校开关强制打开且不可改)
|
||||
NeedApproval int `json:"needApproval"` // 1=需要选择审批人
|
||||
EnableAttach int `json:"enableAttach"` // 1=允许上传图片附件
|
||||
ReasonWordLimit int `json:"reasonWordLimit"` // 请假原因最少字数
|
||||
AttachmentNumberLimit int `json:"attachmentNumberLimit"` // 附件数量上限
|
||||
ChooseAttendance int `json:"chooseAttendance"` // 1=需要打卡相关核验(透传)
|
||||
DisableTime int `json:"disableTime"` // 1=当前类型不可用
|
||||
LimitDay int `json:"limitDay"` // 单次最长可请假天数(0=不限)
|
||||
RequireSign int `json:"requireSign"` // 1=需先手写承诺书签名后提交
|
||||
}
|
||||
|
||||
// CheckOnceLeave 检查是否允许请假(学校可能配置同一时间仅一条请假单等限制)
|
||||
func CheckOnceLeave(cookieMap map[string]string, host string) error {
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/stu/checkOnceLeave", map[string]interface{}{}, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("检查请假资格失败: %w", err)
|
||||
}
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return fmt.Errorf("解析请假资格响应失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "当前不可请假"
|
||||
}
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FetchLeaveTypes 获取请假类型列表(已合并 queryLeaveTypeCfg 的权威开关)。
|
||||
// 单个类型的 cfg 查询失败不阻塞整体列表(该类型保留基础信息,开关取保守默认值)。
|
||||
func FetchLeaveTypes(cookieMap map[string]string, host string) ([]LeaveType, error) {
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/queryLeaveTypes", map[string]interface{}{}, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取请假类型失败: %w", err)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Datas struct {
|
||||
LeaveType []struct {
|
||||
Code interface{} `json:"code"`
|
||||
Name string `json:"name"`
|
||||
MustOut interface{} `json:"mustOut"`
|
||||
ReasonWordLimit interface{} `json:"reasonWordLimit"`
|
||||
AttachmentNumberLimit interface{} `json:"attachmentNumberLimit"`
|
||||
} `json:"leaveType"`
|
||||
} `json:"datas"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析请假类型失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
list := make([]LeaveType, 0, len(result.Datas.LeaveType))
|
||||
for _, lt := range result.Datas.LeaveType {
|
||||
codeNum, _ := strconv.Atoi(leaveAnyStr(lt.Code))
|
||||
item := LeaveType{
|
||||
Code: codeNum,
|
||||
Name: lt.Name,
|
||||
MustOut: leaveAnyInt(lt.MustOut),
|
||||
ReasonWordLimit: leaveAnyInt(lt.ReasonWordLimit),
|
||||
AttachmentNumberLimit: leaveAnyInt(lt.AttachmentNumberLimit),
|
||||
}
|
||||
if cfg, err := FetchLeaveTypeCfg(cookieMap, host, codeNum); err == nil {
|
||||
item.MustOut = cfg.MustOut
|
||||
item.NeedApproval = cfg.NeedApproval
|
||||
item.EnableAttach = cfg.EnableAttach
|
||||
item.ReasonWordLimit = cfg.ReasonWordLimit
|
||||
item.AttachmentNumberLimit = cfg.AttachmentNumberLimit
|
||||
item.ChooseAttendance = cfg.ChooseAttendance
|
||||
item.DisableTime = cfg.DisableTime
|
||||
item.LimitDay = cfg.LimitDay
|
||||
if cfg.Name != "" {
|
||||
item.Name = cfg.Name
|
||||
}
|
||||
} else {
|
||||
slog.Warn("获取请假类型配置失败,使用基础信息", "code", codeNum, "error", err)
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// FetchLeaveTypeCfg 获取请假类型详细配置(needApproval/enableAttach 等权威开关)
|
||||
func FetchLeaveTypeCfg(cookieMap map[string]string, host string, code int) (*LeaveType, error) {
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/stu/queryLeaveTypeCfg", map[string]interface{}{
|
||||
"code": code,
|
||||
}, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取请假类型配置失败: %w", err)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Datas struct {
|
||||
Code interface{} `json:"code"`
|
||||
Name string `json:"name"`
|
||||
MustOut interface{} `json:"mustOut"`
|
||||
NeedApproval interface{} `json:"needApproval"`
|
||||
EnableAttach interface{} `json:"enableAttach"`
|
||||
ReasonWordLimit interface{} `json:"reasonWordLimit"`
|
||||
AttachmentNumberLimit interface{} `json:"attachmentNumberLimit"`
|
||||
ChooseAttendance interface{} `json:"chooseAttendance"`
|
||||
DisableTime interface{} `json:"disableTime"`
|
||||
LimitDay interface{} `json:"limitDay"`
|
||||
} `json:"datas"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析请假类型配置失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
codeVal, _ := result.Code.Int64()
|
||||
if codeVal != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
return &LeaveType{
|
||||
Code: leaveAnyInt(result.Datas.Code),
|
||||
Name: result.Datas.Name,
|
||||
MustOut: leaveAnyInt(result.Datas.MustOut),
|
||||
NeedApproval: leaveAnyInt(result.Datas.NeedApproval),
|
||||
EnableAttach: leaveAnyInt(result.Datas.EnableAttach),
|
||||
ReasonWordLimit: leaveAnyInt(result.Datas.ReasonWordLimit),
|
||||
AttachmentNumberLimit: leaveAnyInt(result.Datas.AttachmentNumberLimit),
|
||||
ChooseAttendance: leaveAnyInt(result.Datas.ChooseAttendance),
|
||||
DisableTime: leaveAnyInt(result.Datas.DisableTime),
|
||||
LimitDay: leaveAnyInt(result.Datas.LimitDay),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LeaveApplyParams 请假申请提交参数
|
||||
type LeaveApplyParams struct {
|
||||
LeaveType int // 类型编码
|
||||
StartTime string // yyyy-MM-dd HH:mm:ss
|
||||
EndTime string // yyyy-MM-dd HH:mm:ss
|
||||
LeaveReason string // 请假原因
|
||||
OutStatus bool // 是否离校
|
||||
UrgencyMobile string // 紧急联系人手机号(离校必填)
|
||||
Address string // 目的地(离校必填,如 xx省/xx市/xx区)
|
||||
DetailAddress string // 详细地址(离校必填)
|
||||
Longitude string // 定位经度
|
||||
Latitude string // 定位纬度
|
||||
LocationAddr string // 定位地址
|
||||
ImageURLs []string // 附件图片 URL 列表(可选,最多 4 张且不超学校上限)
|
||||
ApproverWid string // 审批人 userWid(needApproval=1 且学校配置了候选审批人时必填;候选为空可不选)
|
||||
ApproverId string // 审批人 userId
|
||||
ApproverName string // 审批人姓名
|
||||
CcUsers []LeaveApprover // 抄送人(非必填;候选取自审批人列表)
|
||||
}
|
||||
|
||||
// LeaveMaxAttachCount 附件数量上限:学校配置为准,但产品上限 4 张。
|
||||
// limit<=0(学校未配置)按 4;limit>4 收敛为 4;否则取学校值。
|
||||
func LeaveMaxAttachCount(schoolLimit int) int {
|
||||
if schoolLimit <= 0 || schoolLimit > 4 {
|
||||
return 4
|
||||
}
|
||||
return schoolLimit
|
||||
}
|
||||
|
||||
// BuildLeaveCcInfo 构造抄送人信息(ccInfo)。
|
||||
// 官方结构:{totalSize, teachers:[], students:[]},人员含 personType(0=老师 1=学生)。
|
||||
// 审批人接口不返回 personType,按 userId 是否纯数字推断(学号纯数字,教师工号常含字母)。
|
||||
func BuildLeaveCcInfo(users []LeaveApprover) map[string]interface{} {
|
||||
teachers := make([]interface{}, 0, len(users))
|
||||
students := make([]interface{}, 0, len(users))
|
||||
for _, u := range users {
|
||||
if u.UserWid == "" {
|
||||
continue
|
||||
}
|
||||
personType := 1 // 默认学生
|
||||
if u.UserId == "" {
|
||||
personType = 0
|
||||
} else {
|
||||
for _, ch := range u.UserId {
|
||||
if ch < '0' || ch > '9' {
|
||||
personType = 0 // 含非数字字符 → 教师
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
person := map[string]interface{}{
|
||||
"userWid": u.UserWid,
|
||||
"userId": u.UserId,
|
||||
"userName": u.UserName,
|
||||
"name2Id": u.UserName + "/" + u.UserId,
|
||||
"personType": personType,
|
||||
"dept": nil,
|
||||
"sex": nil,
|
||||
"teacherName": u.UserName,
|
||||
}
|
||||
if personType == 0 {
|
||||
teachers = append(teachers, person)
|
||||
} else {
|
||||
students = append(students, person)
|
||||
}
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"totalSize": len(teachers) + len(students),
|
||||
"teachers": teachers,
|
||||
"students": students,
|
||||
}
|
||||
}
|
||||
|
||||
// BuildLeaveApplyForm 构造请假申请表单(/leave/apply 的明文 JSON body,
|
||||
// 与销假的 bodyString 加密不同:该接口只携带 Cpdaily-Extension 头)。
|
||||
func BuildLeaveApplyForm(p LeaveApplyParams, deviceId, systemVersion, appVersion string) map[string]interface{} {
|
||||
urgencyMobile := p.UrgencyMobile
|
||||
address := p.Address
|
||||
detailAddress := p.DetailAddress
|
||||
destination := ""
|
||||
if p.OutStatus {
|
||||
destination = address
|
||||
if detailAddress != "" {
|
||||
if destination != "" {
|
||||
destination += "/"
|
||||
}
|
||||
destination += detailAddress
|
||||
}
|
||||
} else {
|
||||
urgencyMobile = ""
|
||||
address = ""
|
||||
detailAddress = ""
|
||||
}
|
||||
|
||||
form := map[string]interface{}{
|
||||
"leaveType": p.LeaveType,
|
||||
"startTime": p.StartTime,
|
||||
"endTime": p.EndTime,
|
||||
"urgencyMobile": urgencyMobile,
|
||||
"leaveReason": p.LeaveReason,
|
||||
"isAttendance": nil,
|
||||
"outStatus": p.OutStatus,
|
||||
"address": address,
|
||||
"detailAddress": detailAddress,
|
||||
"destination": destination,
|
||||
"holidayAutoDefineVos": []interface{}{},
|
||||
"appVersion": appVersion,
|
||||
"deviceId": deviceId,
|
||||
"ccInfo": BuildLeaveCcInfo(p.CcUsers),
|
||||
"cheatType": nil,
|
||||
"source": 1,
|
||||
"location": map[string]interface{}{
|
||||
"deviceId": deviceId,
|
||||
"systemName": "Android",
|
||||
"systemVersion": systemVersion,
|
||||
"model": "cpdaily",
|
||||
"address": p.LocationAddr,
|
||||
"latitude": p.Latitude,
|
||||
"longitude": p.Longitude,
|
||||
},
|
||||
"locationType": 0,
|
||||
"disclaimers": "本人承诺填写的信息真实有效,并对本次提交请假申请的信息真实性负责。",
|
||||
"uaIsCpadaily": "true",
|
||||
"leaveApplyExplain": nil,
|
||||
}
|
||||
if p.ApproverWid != "" {
|
||||
form["approverWid"] = p.ApproverWid
|
||||
form["approverId"] = p.ApproverId
|
||||
form["approverName"] = p.ApproverName
|
||||
}
|
||||
if len(p.ImageURLs) > 0 {
|
||||
attachs := make([]map[string]interface{}, 0, len(p.ImageURLs))
|
||||
for _, u := range p.ImageURLs {
|
||||
if u == "" {
|
||||
continue
|
||||
}
|
||||
attachs = append(attachs, map[string]interface{}{"type": 1, "url": u})
|
||||
}
|
||||
if len(attachs) > 0 {
|
||||
form["applyAttach"] = attachs
|
||||
} else {
|
||||
form["applyAttach"] = []interface{}{}
|
||||
}
|
||||
} else {
|
||||
form["applyAttach"] = []interface{}{}
|
||||
}
|
||||
return form
|
||||
}
|
||||
|
||||
// SubmitLeaveApply 提交请假申请(明文 JSON body + Cpdaily-Extension 头)
|
||||
func SubmitLeaveApply(cookieMap map[string]string, host string, form map[string]interface{}, lon, lat, deviceId, username string) error {
|
||||
extensionString := GetExtensionString(lat, lon, deviceId, username)
|
||||
|
||||
body, err := leavePost(cookieMap, host+leaveAPIBase+"/apply", form, extensionString)
|
||||
if err != nil {
|
||||
return fmt.Errorf("提交请假请求失败: %w", err)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return fmt.Errorf("解析请假响应失败: %w, body: %s", err, string(body))
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
slog.Info("leave/apply 响应", "code", result.Code.String(), "message", result.Message)
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
msg = "未知错误"
|
||||
}
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mock 请假申请接口:queryLeaveTypes 返回基础信息(开关全 null,复刻真实返回),
|
||||
// queryLeaveTypeCfg 返回权威开关,checkOnceLeave 返回成功。
|
||||
func newLeaveApplyMockServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/wec-counselor-leave-apps/leave/queryLeaveTypes":
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": "0",
|
||||
"datas": map[string]interface{}{
|
||||
"leaveType": []map[string]interface{}{
|
||||
{
|
||||
"id": "4443", "code": 3, "name": "外出申请(省内)", "mustOut": 1,
|
||||
"needApproval": nil, "enableAttach": nil, "reasonWordLimit": 10, "attachmentNumberLimit": 4,
|
||||
},
|
||||
{
|
||||
"id": "1225", "code": 1, "name": "事假", "mustOut": 0,
|
||||
"needApproval": nil, "enableAttach": nil, "reasonWordLimit": 10, "attachmentNumberLimit": 4,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
case "/wec-counselor-leave-apps/leave/stu/queryLeaveTypeCfg":
|
||||
var body map[string]interface{}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
code := leaveAnyInt(body["code"])
|
||||
// code=3:需要审批人 + 允许附件;code=1:均不需要(复刻实测差异)
|
||||
needApproval, enableAttach := 0, 0
|
||||
if code == 3 {
|
||||
needApproval, enableAttach = 1, 1
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": "0",
|
||||
"datas": map[string]interface{}{
|
||||
"wid": "4443", "code": code, "name": "外出申请(省内)",
|
||||
"mustOut": 1, "needApproval": needApproval, "enableAttach": enableAttach,
|
||||
"reasonWordLimit": 10, "attachmentNumberLimit": 4, "chooseAttendance": 0,
|
||||
"disableTime": 0, "limitDay": 90,
|
||||
},
|
||||
})
|
||||
case "/wec-counselor-leave-apps/leave/stu/checkOnceLeave":
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": "0", "message": "SUCCESS", "datas": nil})
|
||||
case "/wec-counselor-leave-apps/leave/apply":
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": "0", "message": "SUCCESS"})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func TestFetchLeaveTypesMergesTypeCfg(t *testing.T) {
|
||||
srv := newLeaveApplyMockServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
list, err := FetchLeaveTypes(map[string]string{}, srv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchLeaveTypes 返回错误: %v", err)
|
||||
}
|
||||
if len(list) != 2 {
|
||||
t.Fatalf("期望 2 个请假类型,实际 %d 个", len(list))
|
||||
}
|
||||
// code=3:权威开关来自 cfg(needApproval=1 / enableAttach=1)
|
||||
var out LeaveType
|
||||
var personal LeaveType
|
||||
for _, lt := range list {
|
||||
if lt.Code == 3 {
|
||||
out = lt
|
||||
}
|
||||
if lt.Code == 1 {
|
||||
personal = lt
|
||||
}
|
||||
}
|
||||
if out.Name != "外出申请(省内)" || out.NeedApproval != 1 || out.EnableAttach != 1 || out.MustOut != 1 {
|
||||
t.Errorf("类型合并结果错误: %+v", out)
|
||||
}
|
||||
if out.ReasonWordLimit != 10 || out.LimitDay != 90 {
|
||||
t.Errorf("字数/天数限制错误: %+v", out)
|
||||
}
|
||||
if personal.NeedApproval != 0 || personal.EnableAttach != 0 {
|
||||
t.Errorf("事假不应需要审批/附件: %+v", personal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckOnceLeave(t *testing.T) {
|
||||
srv := newLeaveApplyMockServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
if err := CheckOnceLeave(map[string]string{}, srv.URL); err != nil {
|
||||
t.Errorf("checkOnceLeave 应通过: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildLeaveApplyForm(t *testing.T) {
|
||||
// 离校:紧急联系人/目的地/详细地址均保留,destination 由地址拼接
|
||||
p := LeaveApplyParams{
|
||||
LeaveType: 3,
|
||||
StartTime: "2026-09-15 08:00:00",
|
||||
EndTime: "2026-09-16 20:00:00",
|
||||
LeaveReason: "回家处理家庭事务",
|
||||
OutStatus: true,
|
||||
UrgencyMobile: "13800000000",
|
||||
Address: "福建省/厦门市/思明区",
|
||||
DetailAddress: "某某路 1 号",
|
||||
Longitude: "118.1",
|
||||
Latitude: "24.6",
|
||||
LocationAddr: "福建省厦门市思明区",
|
||||
ImageURLs: []string{"https://obs.example.com/a.jpg", "https://obs.example.com/b.jpg"},
|
||||
ApproverWid: "93458825",
|
||||
ApproverId: "20220109",
|
||||
ApproverName: "罗亭",
|
||||
}
|
||||
form := BuildLeaveApplyForm(p, "device-1", "15", "9.9.6")
|
||||
|
||||
if form["leaveType"] != 3 || form["startTime"] != "2026-09-15 08:00:00" || form["outStatus"] != true {
|
||||
t.Errorf("基础字段错误: %+v", form)
|
||||
}
|
||||
if form["destination"] != "福建省/厦门市/思明区/某某路 1 号" {
|
||||
t.Errorf("destination 拼接错误: %v", form["destination"])
|
||||
}
|
||||
if form["approverWid"] != "93458825" || form["approverId"] != "20220109" || form["approverName"] != "罗亭" {
|
||||
t.Errorf("审批人字段错误: %v/%v/%v", form["approverWid"], form["approverId"], form["approverName"])
|
||||
}
|
||||
attach, ok := form["applyAttach"].([]map[string]interface{})
|
||||
if !ok || len(attach) != 2 || attach[0]["url"] != "https://obs.example.com/a.jpg" || attach[1]["url"] != "https://obs.example.com/b.jpg" {
|
||||
t.Errorf("多附件结构错误: %v", form["applyAttach"])
|
||||
}
|
||||
if attach[0]["type"] != 1 || attach[1]["type"] != 1 {
|
||||
t.Errorf("附件 type 应为 1: %v", attach)
|
||||
}
|
||||
loc, ok := form["location"].(map[string]interface{})
|
||||
if !ok || loc["longitude"] != "118.1" || loc["latitude"] != "24.6" || loc["address"] != "福建省厦门市思明区" {
|
||||
t.Errorf("location 结构错误: %v", form["location"])
|
||||
}
|
||||
|
||||
// 不离校:紧急联系人/地址字段清空、destination 为空、无审批人/无附件
|
||||
p2 := LeaveApplyParams{
|
||||
LeaveType: 1,
|
||||
StartTime: "2026-09-15 08:00:00",
|
||||
EndTime: "2026-09-15 18:00:00",
|
||||
LeaveReason: "身体不适需休息",
|
||||
OutStatus: false,
|
||||
UrgencyMobile: "13800000000", // 故意传入,应被清空
|
||||
Address: "福建省/厦门市",
|
||||
DetailAddress: "某某路",
|
||||
Longitude: "118.1",
|
||||
Latitude: "24.6",
|
||||
LocationAddr: "校内",
|
||||
}
|
||||
form2 := BuildLeaveApplyForm(p2, "device-1", "15", "9.9.6")
|
||||
if form2["urgencyMobile"] != "" || form2["address"] != "" || form2["detailAddress"] != "" {
|
||||
t.Errorf("不离校时地址字段应清空: %v/%v/%v", form2["urgencyMobile"], form2["address"], form2["detailAddress"])
|
||||
}
|
||||
if form2["destination"] != "" {
|
||||
t.Errorf("不离校时 destination 应为空: %v", form2["destination"])
|
||||
}
|
||||
if _, ok := form2["approverWid"]; ok {
|
||||
t.Errorf("未选审批人时不应携带 approverWid")
|
||||
}
|
||||
if attach, ok := form2["applyAttach"].([]interface{}); !ok || len(attach) != 0 {
|
||||
t.Errorf("无附件时 applyAttach 应为空数组: %v", form2["applyAttach"])
|
||||
}
|
||||
// 无抄送人:ccInfo 仍必须存在且为空结构
|
||||
cc, ok := form2["ccInfo"].(map[string]interface{})
|
||||
if !ok || cc["totalSize"] != 0 {
|
||||
t.Errorf("无抄送人时 ccInfo 应为空结构: %v", form2["ccInfo"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildLeaveCcInfo(t *testing.T) {
|
||||
// 学生(纯数字 userId)+ 教师(含字母 userId)分组
|
||||
users := []LeaveApprover{
|
||||
{UserWid: "92274797", UserId: "02727", UserName: "王欣然"}, // 纯数字 → students
|
||||
{UserWid: "915560902", UserId: "kjxy0003", UserName: "杨瑚"}, // 含字母 → teachers
|
||||
}
|
||||
cc := BuildLeaveCcInfo(users)
|
||||
if cc["totalSize"] != 2 {
|
||||
t.Errorf("totalSize 应为 2,实际 %v", cc["totalSize"])
|
||||
}
|
||||
students, _ := cc["students"].([]interface{})
|
||||
teachers, _ := cc["teachers"].([]interface{})
|
||||
if len(students) != 1 || len(teachers) != 1 {
|
||||
t.Fatalf("分组错误: students=%d teachers=%d", len(students), len(teachers))
|
||||
}
|
||||
st, _ := students[0].(map[string]interface{})
|
||||
if st["userWid"] != "92274797" || st["name2Id"] != "王欣然/02727" || st["personType"] != 1 {
|
||||
t.Errorf("学生抄送人字段错误: %v", st)
|
||||
}
|
||||
tc, _ := teachers[0].(map[string]interface{})
|
||||
if tc["userWid"] != "915560902" || tc["personType"] != 0 {
|
||||
t.Errorf("教师抄送人字段错误: %v", tc)
|
||||
}
|
||||
|
||||
// 空列表:结构完整但 totalSize=0
|
||||
empty := BuildLeaveCcInfo(nil)
|
||||
if empty["totalSize"] != 0 {
|
||||
t.Errorf("空抄送人 totalSize 应为 0: %v", empty["totalSize"])
|
||||
}
|
||||
if arr, ok := empty["teachers"].([]interface{}); !ok || len(arr) != 0 {
|
||||
t.Errorf("空抄送人 teachers 应为空数组: %v", empty["teachers"])
|
||||
}
|
||||
|
||||
// 提交表单携带抄送人
|
||||
form := BuildLeaveApplyForm(LeaveApplyParams{
|
||||
LeaveType: 1, StartTime: "2026-09-15 08:00:00", EndTime: "2026-09-15 18:00:00",
|
||||
LeaveReason: "身体不适需休息", Longitude: "118.1", Latitude: "24.6", LocationAddr: "校内",
|
||||
CcUsers: users,
|
||||
}, "device-1", "15", "9.9.6")
|
||||
fcc, _ := form["ccInfo"].(map[string]interface{})
|
||||
if fcc == nil || fcc["totalSize"] != 2 {
|
||||
t.Errorf("表单 ccInfo 应包含 2 名抄送人: %v", form["ccInfo"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitLeaveApply(t *testing.T) {
|
||||
srv := newLeaveApplyMockServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
form := BuildLeaveApplyForm(LeaveApplyParams{
|
||||
LeaveType: 1, StartTime: "2026-09-15 08:00:00", EndTime: "2026-09-15 18:00:00",
|
||||
LeaveReason: "身体不适需休息", Longitude: "118.1", Latitude: "24.6", LocationAddr: "校内",
|
||||
}, "device-1", "15", "9.9.6")
|
||||
|
||||
if err := SubmitLeaveApply(map[string]string{}, srv.URL, form, "118.1", "24.6", "device-1", "20251960205"); err != nil {
|
||||
t.Errorf("SubmitLeaveApply 应成功: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLeaveMaxAttachCount 附件数量上限:学校未配置/超 4 张收敛为 4,否则取学校值
|
||||
func TestLeaveMaxAttachCount(t *testing.T) {
|
||||
cases := []struct {
|
||||
schoolLimit int
|
||||
want int
|
||||
}{
|
||||
{0, 4}, // 未配置
|
||||
{-1, 4}, // 异常值
|
||||
{2, 2},
|
||||
{4, 4},
|
||||
{9, 4}, // 超产品上限
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := LeaveMaxAttachCount(c.schoolLimit); got != c.want {
|
||||
t.Errorf("LeaveMaxAttachCount(%d) = %d, want %d", c.schoolLimit, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildLeaveApplyFormEmptyAttachURLs 多图字段中的空串应被剔除,全空时仍输出空数组
|
||||
func TestBuildLeaveApplyFormEmptyAttachURLs(t *testing.T) {
|
||||
form := BuildLeaveApplyForm(LeaveApplyParams{
|
||||
LeaveType: 1, StartTime: "2026-09-15 08:00:00", EndTime: "2026-09-15 18:00:00",
|
||||
LeaveReason: "身体不适需休息", Longitude: "118.1", Latitude: "24.6", LocationAddr: "校内",
|
||||
ImageURLs: []string{"", "https://obs.example.com/only.jpg", ""},
|
||||
}, "device-1", "15", "9.9.6")
|
||||
attach, ok := form["applyAttach"].([]map[string]interface{})
|
||||
if !ok || len(attach) != 1 || attach[0]["url"] != "https://obs.example.com/only.jpg" {
|
||||
t.Errorf("空串应被剔除: %v", form["applyAttach"])
|
||||
}
|
||||
|
||||
form2 := BuildLeaveApplyForm(LeaveApplyParams{
|
||||
LeaveType: 1, StartTime: "2026-09-15 08:00:00", EndTime: "2026-09-15 18:00:00",
|
||||
LeaveReason: "身体不适需休息", Longitude: "118.1", Latitude: "24.6", LocationAddr: "校内",
|
||||
ImageURLs: []string{"", ""},
|
||||
}, "device-1", "15", "9.9.6")
|
||||
if attach2, ok := form2["applyAttach"].([]interface{}); !ok || len(attach2) != 0 {
|
||||
t.Errorf("全空时应为空数组: %v", form2["applyAttach"])
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,165 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestLeaveNewObsKeyOf 验证 obsKey 推导(与官方前端 AA 函数一致)
|
||||
func TestLeaveNewObsKeyOf(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
url string
|
||||
want string
|
||||
}{
|
||||
{"普通路径", "https://counselor-cos-wecres.campusphere.net/counselor/leave/1020385267004784/attachment/abc.jpeg?sign=xxx", "/counselor/leave/1020385267004784/attachment/abc.jpeg"},
|
||||
{"newBucket形态", "https://cdn.example.com/foo/newBucket/leave/abc.png", "newBucket/leave/abc.png"},
|
||||
{"空URL", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := LeaveNewObsKeyOf(c.url); got != c.want {
|
||||
t.Errorf("LeaveNewObsKeyOf(%q) = %q, want %q", c.url, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLeaveAppFlavorFromApps 验证应用列表 → 套件判定
|
||||
func TestLeaveNewCanReport(t *testing.T) {
|
||||
cases := []struct {
|
||||
status, reportMode string
|
||||
want bool
|
||||
}{
|
||||
{"3", "1", true},
|
||||
{"4", "1", true},
|
||||
{"3", "2", true},
|
||||
{"4", "2", true},
|
||||
{"3", "0", false},
|
||||
{"4", "3", false},
|
||||
{"2", "1", false},
|
||||
{"7", "1", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := leaveNewCanReport(LeaveNewItem{Status: c.status, ReportMode: c.reportMode})
|
||||
if got != c.want {
|
||||
t.Errorf("canReport(status=%s, reportMode=%s) = %v, want %v", c.status, c.reportMode, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLeaveNewStatusText 验证状态文案映射完整
|
||||
func TestLeaveNewStatusText(t *testing.T) {
|
||||
for _, code := range []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"} {
|
||||
if LeaveNewStatusText[code] == "" {
|
||||
t.Errorf("status %s 缺少文案映射", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildLeaveNewReportForm 验证销假表单结构(含确认人与附件)
|
||||
func TestBuildLeaveNewReportForm(t *testing.T) {
|
||||
approver := &LeaveNewApprover{UserWid: "92271929", UserId: "2022110006", UserName: "张文烨", RoleCode: "1003", RoleName: "辅导员", DeptName: "智能制造学院"}
|
||||
form := BuildLeaveNewReportForm(LeaveNewReportParams{
|
||||
LeaveID: "e1529da9d4c94341b0b1f7f2278eb2ab",
|
||||
Address: "泰州学院",
|
||||
Longitude: "119.948267",
|
||||
Latitude: "32.474102",
|
||||
Approver: approver,
|
||||
})
|
||||
if form["leaveId"] != "e1529da9d4c94341b0b1f7f2278eb2ab" {
|
||||
t.Errorf("leaveId 缺失: %v", form["leaveId"])
|
||||
}
|
||||
loc, ok := form["location"].(map[string]interface{})
|
||||
if !ok || loc["address"] != "泰州学院" {
|
||||
t.Errorf("location 结构错误: %v", form["location"])
|
||||
}
|
||||
if form["approverWid"] != "92271929" || form["approverRoleCode"] != "1003" {
|
||||
t.Errorf("确认人字段错误: approverWid=%v approverRoleCode=%v", form["approverWid"], form["approverRoleCode"])
|
||||
}
|
||||
if attachs, ok := form["attachs"].([]interface{}); !ok || len(attachs) != 0 {
|
||||
t.Errorf("无附件时 attachs 应为空数组: %v", form["attachs"])
|
||||
}
|
||||
|
||||
form2 := BuildLeaveNewReportForm(LeaveNewReportParams{
|
||||
LeaveID: "x", Address: "a", Longitude: "1", Latitude: "2",
|
||||
ImageURL: "https://cos.example.com/counselor/leave/1/attachment/a.jpeg?sign=1",
|
||||
})
|
||||
attachs2 := form2["attachs"].([]map[string]interface{})
|
||||
if len(attachs2) != 1 || attachs2[0]["obsKey"] != "/counselor/leave/1/attachment/a.jpeg" {
|
||||
t.Errorf("附件结构错误: %v", attachs2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildLeaveNewApplyForm 验证请假表单结构(离校/不离校两分支 + 抄送人)
|
||||
func TestBuildLeaveNewApplyForm(t *testing.T) {
|
||||
approver := &LeaveNewApprover{UserWid: "92271929", UserId: "2022110006", UserName: "张文烨"}
|
||||
form := BuildLeaveNewApplyForm(LeaveNewApplyParams{
|
||||
TypeWid: 8214,
|
||||
BeginTime: "2026-09-16 08:00",
|
||||
EndTime: "2026-09-16 18:00",
|
||||
LeaveReason: "测试原因",
|
||||
LocationAddr: "泰州学院",
|
||||
Longitude: "119.9",
|
||||
Latitude: "32.4",
|
||||
IsLeaveOut: 1,
|
||||
Destination: "江苏省/南京市/玄武区",
|
||||
Detail: "某地",
|
||||
EmergencyName: "张三",
|
||||
EmergencyMobile: "13800000000",
|
||||
Approver: approver,
|
||||
CcUsers: []LeaveNewApprover{{UserWid: "1", UserId: "s1", UserName: "李四", RoleCode: "1003"}},
|
||||
ImageURLs: []string{
|
||||
"https://cos.example.com/counselor/leave/1/attachment/a.jpeg?sign=1",
|
||||
"https://cos.example.com/counselor/leave/1/attachment/b.png?sign=2",
|
||||
},
|
||||
})
|
||||
if form["typeWid"] != 8214 {
|
||||
t.Errorf("typeWid 错误: %v", form["typeWid"])
|
||||
}
|
||||
attachs := form["attachs"].([]map[string]interface{})
|
||||
if len(attachs) != 2 {
|
||||
t.Fatalf("多附件应为 2 张: %v", attachs)
|
||||
}
|
||||
if attachs[0]["attachUrl"] != "https://cos.example.com/counselor/leave/1/attachment/a.jpeg?sign=1" ||
|
||||
attachs[0]["obsKey"] != "/counselor/leave/1/attachment/a.jpeg" {
|
||||
t.Errorf("第 1 张附件结构错误: %v", attachs[0])
|
||||
}
|
||||
if attachs[1]["attachUrl"] != "https://cos.example.com/counselor/leave/1/attachment/b.png?sign=2" ||
|
||||
attachs[1]["obsKey"] != "/counselor/leave/1/attachment/b.png" {
|
||||
t.Errorf("第 2 张附件结构错误: %v", attachs[1])
|
||||
}
|
||||
if attachs[0]["attachType"] != 1 || attachs[1]["attachType"] != 1 {
|
||||
t.Errorf("attachType 应为 1: %v", attachs)
|
||||
}
|
||||
lo := form["leaveOutInfo"].(map[string]interface{})
|
||||
if lo["isLeaveOut"] != 1 || lo["destination"] != "江苏省/南京市/玄武区" || lo["emergencyConcat"] != "张三" {
|
||||
t.Errorf("leaveOutInfo 错误: %v", lo)
|
||||
}
|
||||
cc := form["ccObjects"].([]map[string]interface{})
|
||||
if len(cc) != 1 || cc[0]["userWid"] != "1" || cc[0]["source"] != "2" {
|
||||
t.Errorf("ccObjects 错误: %v", cc)
|
||||
}
|
||||
|
||||
// 不离校分支:离校字段应清空
|
||||
form2 := BuildLeaveNewApplyForm(LeaveNewApplyParams{TypeWid: 8216, IsLeaveOut: 0, Destination: "不该出现", EmergencyMobile: "138"})
|
||||
lo2 := form2["leaveOutInfo"].(map[string]interface{})
|
||||
if lo2["destination"] != "" || lo2["emergencyMobile"] != "" {
|
||||
t.Errorf("不离校时离校字段应清空: %v", lo2)
|
||||
}
|
||||
if attachs2, ok := form2["attachs"].([]map[string]interface{}); !ok || len(attachs2) != 0 {
|
||||
t.Errorf("无附件时 attachs 应为空数组: %v", form2["attachs"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestLeaveNewResultErr 验证响应码解析(code 为字符串 "0")
|
||||
func TestLeaveNewResultErr(t *testing.T) {
|
||||
if _, err := leaveNewResultErr([]byte(`{"code":"0","message":"SUCCESS","datas":{}}`), "测试"); err != nil {
|
||||
t.Errorf("code=0 不应报错: %v", err)
|
||||
}
|
||||
if _, err := leaveNewResultErr([]byte(`{"code":"-1","message":"参数错误"}`), "测试"); err == nil || err.Error() != "参数错误" {
|
||||
t.Errorf("非 0 应返回 message: %v", err)
|
||||
}
|
||||
if _, err := leaveNewResultErr([]byte(`<html>404</html>`), "测试"); err == nil {
|
||||
t.Error("非 JSON 应报错")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ========== 节假日离返校(wec-counselor-leave-return-apps)返校登记 ==========
|
||||
//
|
||||
// 该应用为部分学校(如合肥大学)的"节假日离返校"应用,学生端流程为:
|
||||
// 离校登记(登记假期去向)→ 假期结束返校时「返校登记 / 确认到达」(提交返校位置)。
|
||||
// 本文件只覆盖「返校登记/确认到达」:列出待办 + 提交返校位置。
|
||||
//
|
||||
// 接口(明文 JSON,Header 与签到一致:CpdailyClientType: CPDAILY):
|
||||
// POST /stu/leave/queryReturnConfigList 返校确认位置配置(校区坐标 + 半径)
|
||||
// POST /stu/leave/queryStuRegisterList 登记列表(hasHistory=false 取当前待办)
|
||||
// POST /stu/leave/submitStuReturnRegisterInfo 提交返校登记
|
||||
//
|
||||
// 待办判定:status=="1"(返校登记阶段)且 returnRegisterInfo==null(尚未登记返校)。
|
||||
|
||||
const leaveReturnAPIBase = "/wec-counselor-leave-return-apps"
|
||||
|
||||
// LeaveReturnPlace 返校确认位置(校区坐标 + 允许半径)
|
||||
type LeaveReturnPlace struct {
|
||||
Wid int `json:"wid"`
|
||||
Address string `json:"address"`
|
||||
Longitude string `json:"longitude"`
|
||||
Latitude string `json:"latitude"`
|
||||
Scope float64 `json:"scope"` // 允许半径(米)
|
||||
}
|
||||
|
||||
// LeaveReturnTask 待办返校登记(一名学生在一期离返校任务中的返校登记)
|
||||
type LeaveReturnTask struct {
|
||||
TaskWid int `json:"taskWid"`
|
||||
StuWid int `json:"stuWid"`
|
||||
LeaveName string `json:"leaveName"` // 如「2026年中秋节离返校」
|
||||
StartTime string `json:"startTime"` // 假期开始
|
||||
EndTime string `json:"endTime"` // 假期结束
|
||||
SignType int `json:"signType"` // 1=范围内 2=范围外(提交时按坐标计算)
|
||||
Disclaimer string `json:"disclaimer"` // 承诺书文案(透传给前端展示)
|
||||
}
|
||||
|
||||
// leaveReturnPost 通用 POST(明文 JSON,与签到同 Header)
|
||||
func leaveReturnPost(cookieMap map[string]string, url string, body interface{}) ([]byte, error) {
|
||||
client := newTaskClient()
|
||||
resp, err := client.R().
|
||||
SetHeader("User-Agent", "Mozilla/5.0 (Linux; Android 15; Redmi Note 8 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.81 Mobile Safari/537.36 cpdaily/9.9.6 wisedu/9.9.6").
|
||||
SetHeader("CpdailyClientType", "CPDAILY").
|
||||
SetHeader("Content-Type", "application/json; charset=UTF-8").
|
||||
SetHeader("Cookie", cookiesToStr(cookieMap)).
|
||||
SetBody(body).
|
||||
Post(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.RawBody().Close()
|
||||
respBody, err := io.ReadAll(resp.RawBody())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if code := resp.StatusCode(); code < 200 || code >= 300 {
|
||||
return respBody, fmt.Errorf("学校服务端响应异常(HTTP %d): %s", code, strings.TrimSpace(string(respBody)))
|
||||
}
|
||||
if len(respBody) == 0 {
|
||||
return respBody, fmt.Errorf("学校服务端返回空响应(HTTP %d)", resp.StatusCode())
|
||||
}
|
||||
return respBody, nil
|
||||
}
|
||||
|
||||
// FetchLeaveReturnPlaces 返校确认位置配置(取第一条;该校通常一个校区)
|
||||
func FetchLeaveReturnPlaces(cookieMap map[string]string, host string) ([]LeaveReturnPlace, error) {
|
||||
body, err := leaveReturnPost(cookieMap, host+leaveReturnAPIBase+"/stu/leave/queryReturnConfigList", map[string]interface{}{
|
||||
"pageNumber": 1,
|
||||
"pageSize": 20,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取返校位置配置失败: %w", err)
|
||||
}
|
||||
var result struct {
|
||||
Code string `json:"code"`
|
||||
Datas struct {
|
||||
Rows []LeaveReturnPlace `json:"rows"`
|
||||
} `json:"datas"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析返校位置配置失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
if result.Code != "0" {
|
||||
return nil, fmt.Errorf("返校位置配置接口返回异常(code=%s)", result.Code)
|
||||
}
|
||||
return result.Datas.Rows, nil
|
||||
}
|
||||
|
||||
// leaveReturnListRow queryStuRegisterList 行
|
||||
type leaveReturnListRow struct {
|
||||
TaskWid int `json:"taskWid"`
|
||||
StuWid int `json:"stuWid"`
|
||||
Status string `json:"status"`
|
||||
LeaveName string `json:"leaveName"`
|
||||
StartTime string `json:"startTime"`
|
||||
EndTime string `json:"endTime"`
|
||||
ReturnSignType string `json:"returnSignType"`
|
||||
Disclaimer string `json:"disclaimer"`
|
||||
ReturnRegisterInfo json.RawMessage `json:"returnRegisterInfo"`
|
||||
}
|
||||
|
||||
// FetchLeaveReturnPending 待办返校登记:status=="1" 且 returnRegisterInfo 为空的行。
|
||||
// hasHistory=false 表示只取当前(未归档)任务。
|
||||
func FetchLeaveReturnPending(cookieMap map[string]string, host string) ([]LeaveReturnTask, error) {
|
||||
body, err := leaveReturnPost(cookieMap, host+leaveReturnAPIBase+"/stu/leave/queryStuRegisterList", map[string]interface{}{
|
||||
"hasHistory": false,
|
||||
"pageNumber": 1,
|
||||
"pageSize": 20,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取返校登记列表失败: %w", err)
|
||||
}
|
||||
var result struct {
|
||||
Code string `json:"code"`
|
||||
Datas struct {
|
||||
Rows []leaveReturnListRow `json:"rows"`
|
||||
} `json:"datas"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析返校登记列表失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
if result.Code != "0" {
|
||||
return nil, fmt.Errorf("返校登记列表接口返回异常(code=%s)", result.Code)
|
||||
}
|
||||
return leaveReturnTasksFromRows(result.Datas.Rows), nil
|
||||
}
|
||||
|
||||
// leaveReturnTasksFromRows 从列表行中筛出待办返校登记:
|
||||
// status=="1"(返校登记阶段)且 returnRegisterInfo 为空(尚未登记返校)。
|
||||
func leaveReturnTasksFromRows(rows []leaveReturnListRow) []LeaveReturnTask {
|
||||
out := make([]LeaveReturnTask, 0)
|
||||
for _, r := range rows {
|
||||
if r.Status != "1" {
|
||||
continue
|
||||
}
|
||||
ri := strings.TrimSpace(string(r.ReturnRegisterInfo))
|
||||
if ri != "" && ri != "null" {
|
||||
continue // 已登记返校
|
||||
}
|
||||
signType := 1
|
||||
if strings.TrimSpace(r.ReturnSignType) == "2" {
|
||||
signType = 2
|
||||
}
|
||||
out = append(out, LeaveReturnTask{
|
||||
TaskWid: r.TaskWid,
|
||||
StuWid: r.StuWid,
|
||||
LeaveName: r.LeaveName,
|
||||
StartTime: r.StartTime,
|
||||
EndTime: r.EndTime,
|
||||
SignType: signType,
|
||||
Disclaimer: r.Disclaimer,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LeaveReturnSignWidOf 从返校登记任务派生 SignWid("taskWid:stuWid",供统一任务体系存取)
|
||||
func LeaveReturnSignWidOf(taskWid, stuWid int) string {
|
||||
return fmt.Sprintf("%d:%d", taskWid, stuWid)
|
||||
}
|
||||
|
||||
// ParseLeaveReturnSignWid 解析 SignWid → (taskWid, stuWid)
|
||||
func ParseLeaveReturnSignWid(signWid string) (int, int, error) {
|
||||
parts := strings.SplitN(strings.TrimSpace(signWid), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return 0, 0, fmt.Errorf("返校登记标识格式错误: %q", signWid)
|
||||
}
|
||||
taskWid, err1 := strconv.Atoi(parts[0])
|
||||
stuWid, err2 := strconv.Atoi(parts[1])
|
||||
if err1 != nil || err2 != nil {
|
||||
return 0, 0, fmt.Errorf("返校登记标识解析失败: %q", signWid)
|
||||
}
|
||||
return taskWid, stuWid, nil
|
||||
}
|
||||
|
||||
// FetchReturnRegisterTasks 返校登记待办 → 统一任务项(供打卡任务标题来源)。
|
||||
// TaskName=假期名;SignWid="taskWid:stuWid"。
|
||||
func FetchReturnRegisterTasks(cookieMap map[string]string, host string) ([]TodayTaskInfo, error) {
|
||||
pending, err := FetchLeaveReturnPending(cookieMap, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]TodayTaskInfo, 0, len(pending))
|
||||
for _, t := range pending {
|
||||
out = append(out, TodayTaskInfo{
|
||||
TaskName: t.LeaveName,
|
||||
SignWid: LeaveReturnSignWidOf(t.TaskWid, t.StuWid),
|
||||
IsSigned: false,
|
||||
TaskType: string(TaskTypeReturnRegister),
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SubmitLeaveReturnRegister 提交返校登记(确认到达)
|
||||
// taskWid/stuWid 取自列表;address/longitude/latitude 为返校位置。
|
||||
// 范围内使用配置坐标(signType=1);范围外(signType=2)须填原因。
|
||||
func SubmitLeaveReturnRegister(cookieMap map[string]string, host string, taskWid, stuWid int, address, longitude, latitude string, signType int, outsideReason string) error {
|
||||
payload := map[string]interface{}{
|
||||
"taskWid": taskWid,
|
||||
"stuWid": stuWid,
|
||||
"returnAddress": address,
|
||||
"returnLongitude": longitude,
|
||||
"returnLatitude": latitude,
|
||||
"returnSignType": fmt.Sprintf("%d", signType),
|
||||
}
|
||||
if signType == 2 {
|
||||
payload["outsideSignReason"] = outsideReason
|
||||
}
|
||||
body, err := leaveReturnPost(cookieMap, host+leaveReturnAPIBase+"/stu/leave/submitStuReturnRegisterInfo", payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("提交返校登记失败: %w", err)
|
||||
}
|
||||
var result struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return fmt.Errorf("解析返校登记响应失败: %w (body: %.300s)", err, string(body))
|
||||
}
|
||||
slog.Info("leave-return/submit 响应", "code", result.Code, "message", result.Message)
|
||||
if result.Code != "0" {
|
||||
msg := strings.TrimSpace(result.Message)
|
||||
if msg == "" || msg == "failed" {
|
||||
msg = "返校登记失败,请稍后重试"
|
||||
}
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package cpdaily
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestLeaveReturnSignWidRoundTrip 任务标识 "taskWid:stuWid" 编解码
|
||||
func TestLeaveReturnSignWidRoundTrip(t *testing.T) {
|
||||
s := LeaveReturnSignWidOf(25, 471179)
|
||||
if s != "25:471179" {
|
||||
t.Fatalf("LeaveReturnSignWidOf = %q", s)
|
||||
}
|
||||
tw, sw, err := ParseLeaveReturnSignWid(s)
|
||||
if err != nil || tw != 25 || sw != 471179 {
|
||||
t.Fatalf("ParseLeaveReturnSignWid(%q) = %d,%d,%v", s, tw, sw, err)
|
||||
}
|
||||
if _, _, err := ParseLeaveReturnSignWid("bad"); err == nil {
|
||||
t.Fatalf("非法标识应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLeaveReturnTasksFromRows 待办筛选:仅 status=1 且 returnRegisterInfo 为空才算待办。
|
||||
func TestLeaveReturnTasksFromRows(t *testing.T) {
|
||||
rows := []leaveReturnListRow{
|
||||
{TaskWid: 25, StuWid: 471179, Status: "1", LeaveName: "2026年中秋节离返校", ReturnRegisterInfo: []byte("null")}, // 待办
|
||||
{TaskWid: 25, StuWid: 471179, Status: "0", LeaveName: "2026年中秋节离返校"}, // 非返校阶段
|
||||
{TaskWid: 24, StuWid: 455702, Status: "1", LeaveName: "26年暑假离返校",
|
||||
ReturnRegisterInfo: []byte(`{"returnTime":"2026-09-04 11:21"}`)}, // 已登记
|
||||
{TaskWid: 22, StuWid: 1, Status: "1", LeaveName: "五一离返校",
|
||||
ReturnSignType: "2"}, // 待办,范围外
|
||||
}
|
||||
got := leaveReturnTasksFromRows(rows)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("期望 2 条待办, got %d: %+v", len(got), got)
|
||||
}
|
||||
if got[0].TaskWid != 25 || got[0].StuWid != 471179 || got[0].SignType != 1 {
|
||||
t.Errorf("第 1 条待办不符: %+v", got[0])
|
||||
}
|
||||
if got[1].TaskWid != 22 || got[1].SignType != 2 {
|
||||
t.Errorf("第 2 条待办(范围外)不符: %+v", got[1])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mock 销假模块接口:listOther 返回两行(一行待销假、一行已完成),
|
||||
// detailOther 返回规定销假位置(reportPlaces)与开关(reportApplyFlow/enableAttach)。
|
||||
// leaveType.code 故意用数字,复刻真实接口(此前声明为 string 导致解析失败)。
|
||||
func newLeaveMockServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/wec-counselor-leave-apps/leave/stu/listOther":
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": "0",
|
||||
"datas": map[string]interface{}{
|
||||
"rows": []map[string]interface{}{
|
||||
{
|
||||
"id": "301",
|
||||
"leaveType": "事假",
|
||||
"leaveReason": "回家",
|
||||
"createTime": "2026-09-13 10:00",
|
||||
"actEndTime": "2026-09-14 08:00",
|
||||
"status": "8",
|
||||
},
|
||||
{
|
||||
"id": "302",
|
||||
"leaveType": "病假",
|
||||
"status": "4", // 已完成,应被过滤
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
case "/wec-counselor-leave-apps/leave/stu/detailOther":
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": "0",
|
||||
"datas": map[string]interface{}{
|
||||
"detail": map[string]interface{}{
|
||||
"id": "301",
|
||||
"startDate": "2026-09-13 10:00",
|
||||
"endDate": "2026-09-14 08:00",
|
||||
},
|
||||
"leaveType": map[string]interface{}{
|
||||
"code": 1, // 数字,复刻真实返回
|
||||
"name": "事假",
|
||||
"reportApplyFlow": 1,
|
||||
"enableAttach": 1,
|
||||
},
|
||||
"reportPlaces": []map[string]interface{}{
|
||||
{
|
||||
"wid": "1184",
|
||||
"address": "云南大学东二院",
|
||||
"longitude": 102.70567818032221,
|
||||
"latitude": "25.059769487255817",
|
||||
"radius": "360",
|
||||
"counName": "ampadmin",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
case "/wec-counselor-leave-apps/leave/stu/obtainApproveFlow":
|
||||
var body map[string]interface{}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
// 时间必须带秒,否则真实服务端返回"日期时间格式错误"
|
||||
start, _ := body["startTime"].(string)
|
||||
end, _ := body["endTime"].(string)
|
||||
if len(start) != 19 || len(end) != 19 {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": "2210990000", "message": "日期时间格式错误",
|
||||
})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": "0",
|
||||
"datas": map[string]interface{}{
|
||||
"approvers": []map[string]interface{}{
|
||||
{"userWid": "93458825", "userId": "20220109", "userName": "罗亭"},
|
||||
{"userWid": "1246664953", "userId": "12024206007", "userName": "曾伟"},
|
||||
},
|
||||
},
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func TestFetchLeaveListFiltersCompletedAndParsesReportPlaces(t *testing.T) {
|
||||
srv := newLeaveMockServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
items, err := FetchLeaveList(map[string]string{"MOD_AUTH_CAS": "test"}, srv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchLeaveList 返回错误: %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("期望过滤后剩 1 条待销假记录,实际 %d 条: %+v", len(items), items)
|
||||
}
|
||||
item := items[0]
|
||||
if item.ID != "301" || item.LeaveType != "事假" || item.Reason != "回家" {
|
||||
t.Errorf("列表字段解析错误: %+v", item)
|
||||
}
|
||||
if len(item.ReportPlaces) != 1 {
|
||||
t.Fatalf("期望解析出 1 个规定销假位置,实际 %d 个", len(item.ReportPlaces))
|
||||
}
|
||||
p := item.ReportPlaces[0]
|
||||
// 数字型经纬度应转为纯文本(避免科学计数法)
|
||||
if p.Longitude != "102.70567818032221" || p.Latitude != "25.059769487255817" || p.Address != "云南大学东二院" || p.Radius != "360" {
|
||||
t.Errorf("规定销假位置解析错误: %+v", p)
|
||||
}
|
||||
if !item.ReportApplyFlow || !item.EnableAttach {
|
||||
t.Errorf("开关解析错误: reportApplyFlow=%v enableAttach=%v", item.ReportApplyFlow, item.EnableAttach)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchLeaveDetailParsesSubmitFields(t *testing.T) {
|
||||
srv := newLeaveMockServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
d, err := FetchLeaveDetail(map[string]string{}, srv.URL, "301")
|
||||
if err != nil {
|
||||
t.Fatalf("FetchLeaveDetail 返回错误: %v", err)
|
||||
}
|
||||
if d.ReportID != "301" {
|
||||
t.Errorf("ReportID = %q, 期望 301", d.ReportID)
|
||||
}
|
||||
// 数字型 code 应转为纯文本 + 数字双形式
|
||||
if d.LeaveCode != "1" {
|
||||
t.Errorf("LeaveCode = %q, 期望 1", d.LeaveCode)
|
||||
}
|
||||
if d.LeaveCodeNum != 1 {
|
||||
t.Errorf("LeaveCodeNum = %d, 期望 1", d.LeaveCodeNum)
|
||||
}
|
||||
if d.LeaveType != "事假" {
|
||||
t.Errorf("LeaveType = %q, 期望 事假", d.LeaveType)
|
||||
}
|
||||
if !d.ReportApplyFlow || !d.EnableAttach {
|
||||
t.Errorf("开关解析错误: reportApplyFlow=%v enableAttach=%v", d.ReportApplyFlow, d.EnableAttach)
|
||||
}
|
||||
if d.StartTime != "2026-09-13 10:00" || d.EndTime != "2026-09-14 08:00" {
|
||||
t.Errorf("起止时间解析错误: %q ~ %q", d.StartTime, d.EndTime)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchReportApprovers(t *testing.T) {
|
||||
srv := newLeaveMockServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
list, err := FetchReportApprovers(map[string]string{}, srv.URL, 1, "2026-09-13 10:00", "2026-09-14 08:00")
|
||||
if err != nil {
|
||||
t.Fatalf("FetchReportApprovers 返回错误: %v", err)
|
||||
}
|
||||
if len(list) != 2 || list[0].UserName != "罗亭" || list[0].UserWid != "93458825" {
|
||||
t.Errorf("审批人解析错误: %+v", list)
|
||||
}
|
||||
|
||||
// 秒级时间:入参已含秒时原样透传
|
||||
if got := leaveTimeWithSeconds("2026-09-13 10:00:30"); got != "2026-09-13 10:00:30" {
|
||||
t.Errorf("已含秒时间不应改动,实际 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildLeaveReportForm(t *testing.T) {
|
||||
d := &LeaveDetail{
|
||||
ReportID: "301",
|
||||
LeaveCode: "1",
|
||||
ReportPlaces: []LeaveReportPlace{
|
||||
{Address: "规定位置地址", Longitude: "118.1", Latitude: "24.6"},
|
||||
},
|
||||
}
|
||||
|
||||
// 无用户地址:兜底使用第一个规定销假位置地址;无图片:reportAttach 为空数组
|
||||
form := BuildLeaveReportForm(d, "", "", "")
|
||||
if form["reportLocation"] != "规定位置地址" {
|
||||
t.Errorf("reportLocation 应兜底规定位置地址,实际 %v", form["reportLocation"])
|
||||
}
|
||||
if attach, ok := form["reportAttach"].([]interface{}); !ok || len(attach) != 0 {
|
||||
t.Errorf("无图片时 reportAttach 应为空数组,实际 %v", form["reportAttach"])
|
||||
}
|
||||
if form["approverWid"] != "" {
|
||||
t.Errorf("未选审批人时 approverWid 应为空字符串,实际 %v", form["approverWid"])
|
||||
}
|
||||
if form["id"] != "301" || form["leaveType"] != "1" {
|
||||
t.Errorf("id/leaveType 字段错误: %v / %v", form["id"], form["leaveType"])
|
||||
}
|
||||
|
||||
// 用户地址优先 + 有图片 + 选择了审批人
|
||||
form2 := BuildLeaveReportForm(d, "用户填写地址", "https://obs.example.com/a.jpg", "93458825")
|
||||
if form2["reportLocation"] != "用户填写地址" {
|
||||
t.Errorf("用户填写的地址应优先,实际 %v", form2["reportLocation"])
|
||||
}
|
||||
if form2["approverWid"] != "93458825" {
|
||||
t.Errorf("应携带所选审批人,实际 %v", form2["approverWid"])
|
||||
}
|
||||
attach, ok := form2["reportAttach"].([]map[string]interface{})
|
||||
if !ok || len(attach) != 1 || attach[0]["type"] != 1 || attach[0]["url"] != "https://obs.example.com/a.jpg" {
|
||||
t.Errorf("有图片时 reportAttach 结构错误: %v", form2["reportAttach"])
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,23 @@ func newSessionClient() *sessionClient {
|
||||
}).
|
||||
SetHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1")
|
||||
client.SetCookieJar(jar)
|
||||
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
|
||||
|
||||
// 自定义重定向策略:与 resty 默认 FlexibleRedirectPolicy 行为一致(最多 20 跳),
|
||||
// 但跨 host 重定向时保留原 User-Agent。resty 默认策略会把跨 host 请求的 UA 换成
|
||||
// "go-resty/2.x"(见 resty redirect.go checkHostAndAddHeaders),而 wisedu 定制 CAS
|
||||
// 按请求 UA 渲染移动端/PC 模板。云南大学等学校从 campusphere 网关跨域跳到 CAS 时
|
||||
// UA 被替换,CAS 渲染 PC 模板导致后续 MFA 页面(reAuthLoginView.do)校验失败被
|
||||
// 302 踢回登录页,无法解析 reAuthType。保留 UA 后移动端模板正常渲染。
|
||||
client.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 20 {
|
||||
return fmt.Errorf("stopped after %d redirects", 20)
|
||||
}
|
||||
if len(via) > 0 && !strings.EqualFold(getHostnameForRedirect(req.URL.Host), getHostnameForRedirect(via[0].URL.Host)) {
|
||||
if ua := via[0].Header.Get("User-Agent"); ua != "" {
|
||||
req.Header.Set("User-Agent", ua)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
return &sessionClient{
|
||||
Client: client,
|
||||
jar: jar,
|
||||
@@ -52,7 +67,15 @@ func readBody(resp *resty.Response) []byte {
|
||||
return resp.Body()
|
||||
}
|
||||
|
||||
func casLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, error) {
|
||||
// getHostnameForRedirect 去掉端口后返回小写主机名(重定向跨域判断用)
|
||||
func getHostnameForRedirect(host string) string {
|
||||
if i := strings.Index(host, ":"); i > 0 {
|
||||
host = host[:i]
|
||||
}
|
||||
return strings.ToLower(host)
|
||||
}
|
||||
|
||||
func casLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, *MFAContext, error) {
|
||||
sc := newSessionClient()
|
||||
|
||||
// 1. 获取合法的登录 URL
|
||||
@@ -65,7 +88,7 @@ func casLogin(ctx context.Context, school *SchoolDetailInfo, username, password
|
||||
|
||||
loginPageResp, err := sc.R().SetContext(loginCtx).Get(loginUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求登录页面失败: %w", err)
|
||||
return nil, nil, fmt.Errorf("请求登录页面失败: %w", err)
|
||||
}
|
||||
|
||||
loginPageBytes := readBody(loginPageResp)
|
||||
@@ -83,13 +106,25 @@ func casLogin(ctx context.Context, school *SchoolDetailInfo, username, password
|
||||
needCaptcha, loginType := detectCaptcha(ctx, loginResponseUrl, username, sc.Client)
|
||||
slog.Info("CAS验证码检测", "needCaptcha", needCaptcha, "loginType", loginType)
|
||||
if needCaptcha {
|
||||
captchaCode := resolveOcrCaptcha(ctx, loginResponseUrl, loginType, sc.Client)
|
||||
slog.Info("CAS验证码OCR", "code", captchaCode)
|
||||
switch loginType {
|
||||
case 0:
|
||||
allInputs["captchaResponse"] = captchaCode
|
||||
default:
|
||||
allInputs["captcha"] = captchaCode
|
||||
if isSliderCaptchaSchool(school.ID) {
|
||||
// 滑块验证码学校(wisedu 定制 CAS 滑块,如华侨大学):
|
||||
// openSliderCaptcha 取图 → 打码平台识别 → 等激活窗口 → sign 协议提交 verifySliderCaptcha
|
||||
//(提交打码值 v、v+1、v-1,失败换图重试,详见 slider.go),
|
||||
// 通过后 captcha 字段留空提交
|
||||
casBase := fmt.Sprintf("%s://%s/authserver", loginResponseUrl.Scheme, loginResponseUrl.Host)
|
||||
if err := resolveWiseduSliderCaptcha(loginCtx, casBase, loginResponseUrl.String(), sc.Client); err != nil {
|
||||
return nil, nil, fmt.Errorf("滑块验证失败: %w", err)
|
||||
}
|
||||
slog.Info("CAS滑块验证通过")
|
||||
} else {
|
||||
captchaCode := resolveOcrCaptcha(ctx, loginResponseUrl, loginType, sc.Client)
|
||||
slog.Info("CAS验证码OCR", "code", captchaCode)
|
||||
switch loginType {
|
||||
case 0:
|
||||
allInputs["captchaResponse"] = captchaCode
|
||||
default:
|
||||
allInputs["captcha"] = captchaCode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +138,7 @@ func casLogin(ctx context.Context, school *SchoolDetailInfo, username, password
|
||||
if loginResp != nil && loginResp.StatusCode() == 302 {
|
||||
slog.Info("CAS登录重定向(登录成功)", "location", loginResp.Header().Get("Location"))
|
||||
} else {
|
||||
return nil, fmt.Errorf("提交登录失败: %w", err)
|
||||
return nil, nil, fmt.Errorf("提交登录失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,8 +147,20 @@ func casLogin(ctx context.Context, school *SchoolDetailInfo, username, password
|
||||
// 7. 处理响应
|
||||
switch loginResp.StatusCode() {
|
||||
case 302:
|
||||
slog.Info("CAS登录成功", "redirect", loginResp.Header().Get("Location"))
|
||||
return handleCasLoginSuccess(ctx, loginResp, school, sc)
|
||||
location := loginResp.Header().Get("Location")
|
||||
// 多因子认证:302 到 reAuthCheck/reAuthLoginView.do?isMultifactor=true&service=...
|
||||
// 此时 CAS 会话有效但未签发票据,需自动发送验证码并等待用户提交
|
||||
if strings.Contains(location, "isMultifactor=true") || strings.Contains(location, "reAuthCheck") {
|
||||
slog.Info("CAS触发多因子认证(MFA)", "location", location)
|
||||
mfa, err := handleMFATriggered(ctx, loginResp, school, sc)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, mfa, ErrMFARequired
|
||||
}
|
||||
slog.Info("CAS登录成功", "redirect", location)
|
||||
cookies, err := handleCasLoginSuccess(ctx, loginResp, school, sc)
|
||||
return cookies, nil, err
|
||||
case 200, 401:
|
||||
body := readBody(loginResp)
|
||||
slog.Info("CAS登录失败响应体", "body", string(body[:min(len(body), 2000)]))
|
||||
@@ -121,15 +168,16 @@ func casLogin(ctx context.Context, school *SchoolDetailInfo, username, password
|
||||
if err == nil && isCasNeedKickOut(doc) {
|
||||
slog.Info("CAS需要踢下线")
|
||||
kickResp := submitCasKickOut(ctx, loginResponseUrl.String(), doc, sc.Client)
|
||||
return handleCasLoginSuccess(ctx, kickResp, school, sc)
|
||||
cookies, err := handleCasLoginSuccess(ctx, kickResp, school, sc)
|
||||
return cookies, nil, err
|
||||
}
|
||||
msg := getCasErrorMessage(doc)
|
||||
if msg == "" {
|
||||
msg = "登录失败,请检查账号密码"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
return nil, nil, fmt.Errorf("%s", msg)
|
||||
default:
|
||||
return nil, fmt.Errorf("登录返回异常状态码: %d", loginResp.StatusCode())
|
||||
return nil, nil, fmt.Errorf("登录返回异常状态码: %d", loginResp.StatusCode())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,8 +212,10 @@ func parseLoginForm(page []byte, username, password string) map[string]string {
|
||||
return inputs
|
||||
}
|
||||
|
||||
// 优先选择密码登录表单(pwdFromId),其次是其他已知CAS表单ID
|
||||
selectors := []string{"#pwdFromId", "#phoneFromId", "#casLoginForm", "#loginFromId", "#fm1", "form"}
|
||||
// 优先选择密码登录表单(pwdFromId/pwdLoginDiv),其次是其他已知CAS表单ID。
|
||||
// pwdLoginDiv 为 wisedu 定制 CAS 的账密区域(如华侨大学登录页含 3 个 id 均为
|
||||
// loginFromId 的表单 fido/动态码/账密,账密字段位于 #pwdLoginDiv 内)
|
||||
selectors := []string{"#pwdFromId", "#phoneFromId", "#casLoginForm", "#pwdLoginDiv", "#loginFromId", "#fm1", "form"}
|
||||
var formSel *goquery.Selection
|
||||
for _, sel := range selectors {
|
||||
formSel = doc.Find(sel)
|
||||
|
||||
@@ -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 "登录失败,请检查账号密码或稍后重试"
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ========== 辽宁工程技术大学(lntu)单独适配 ==========
|
||||
|
||||
// LntuSchoolId 辽宁工程技术大学 tenant id
|
||||
const LntuSchoolId = "lntu"
|
||||
|
||||
// lntuCasLoginEntry 计算辽宁工程技术大学 CAS 登录入口:
|
||||
// 网关域 fdm.lntu.edu.cn 的 /iap(school.IdsUrl)会 302 到学校 CAS
|
||||
// (authserver.lntu.edu.cn/authserver/login),service 参数携带网关回调
|
||||
// /iap/loginSuccess?sessionToken=...;走完 CAS 账密后回调该地址,
|
||||
// cookie 才能正确落在 fdm.lntu.edu.cn 域(wec-* 任务接口所在域)。
|
||||
func lntuCasLoginEntry(school *SchoolDetailInfo) string {
|
||||
if school == nil {
|
||||
return ""
|
||||
}
|
||||
if school.IdsUrl != "" && strings.Contains(school.IdsUrl, "/iap") {
|
||||
return school.IdsUrl
|
||||
}
|
||||
if school.WecloudUrl != "" {
|
||||
return strings.TrimSuffix(school.WecloudUrl, "/") + "/iap"
|
||||
}
|
||||
return school.AmpUrl
|
||||
}
|
||||
|
||||
// lntuCasLogin 辽宁工程技术大学强制走 CAS:
|
||||
// 平台接口返回 joinType=CLOUD(IsIap()=true),但网关 /iap/doLogin 不存在(HTTP 405),
|
||||
// IAP 账密提交必然失败并报 FAIL_UPNOTMATCH("用户名或密码不匹配",误导用户);
|
||||
// 实际链路为 IAP 入口(fdm.lntu.edu.cn/iap)302 → 学校 CAS 账密 → 回调
|
||||
// /iap/loginSuccess 建立网关会话。因此强制走 CAS 流程(同许昌学院 xcu 模式)。
|
||||
func lntuCasLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, *MFAContext, error) {
|
||||
lntu := *school
|
||||
if entry := lntuCasLoginEntry(school); entry != "" {
|
||||
lntu.AmpUrl = entry
|
||||
}
|
||||
return casLogin(ctx, &lntu, username, password)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package cpdaily
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestLntuCasLoginEntry 覆盖辽宁工程技术大学 CAS 登录入口计算逻辑
|
||||
func TestLntuCasLoginEntry(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
school *SchoolDetailInfo
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "正常idsUrl(/iap 网关入口)",
|
||||
school: &SchoolDetailInfo{IdsUrl: "https://fdm.lntu.edu.cn/iap"},
|
||||
want: "https://fdm.lntu.edu.cn/iap",
|
||||
},
|
||||
{
|
||||
name: "idsUrl缺失回退wecloud+/iap",
|
||||
school: &SchoolDetailInfo{WecloudUrl: "https://fdm.lntu.edu.cn"},
|
||||
want: "https://fdm.lntu.edu.cn/iap",
|
||||
},
|
||||
{
|
||||
name: "wecloud带尾斜杠",
|
||||
school: &SchoolDetailInfo{WecloudUrl: "https://fdm.lntu.edu.cn/"},
|
||||
want: "https://fdm.lntu.edu.cn/iap",
|
||||
},
|
||||
{
|
||||
name: "idsUrl非iap路径回退wecloud",
|
||||
school: &SchoolDetailInfo{IdsUrl: "https://ids.lntu.edu.cn/authserver", WecloudUrl: "https://fdm.lntu.edu.cn"},
|
||||
want: "https://fdm.lntu.edu.cn/iap",
|
||||
},
|
||||
{
|
||||
name: "均缺失回退ampUrl",
|
||||
school: &SchoolDetailInfo{AmpUrl: "https://fdm.lntu.edu.cn/wec-portal-mobile/client"},
|
||||
want: "https://fdm.lntu.edu.cn/wec-portal-mobile/client",
|
||||
},
|
||||
{
|
||||
name: "均为空",
|
||||
school: &SchoolDetailInfo{},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "nil学校",
|
||||
school: nil,
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := lntuCasLoginEntry(c.school); got != c.want {
|
||||
t.Errorf("lntuCasLoginEntry() = %q, want %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLntuCasLoginEntryOverridesAmpUrl 确认 lntuCasLogin 用网关入口覆盖 ampUrl 后走 CAS 流程
|
||||
func TestLntuCasLoginEntryOverridesAmpUrl(t *testing.T) {
|
||||
school := &SchoolDetailInfo{
|
||||
ID: LntuSchoolId,
|
||||
Name: "辽宁工程技术大学",
|
||||
JoinType: "CLOUD", // 平台标记为 CLOUD,但 IAP 不可用,需强制 CAS
|
||||
IdsUrl: "https://fdm.lntu.edu.cn/iap",
|
||||
WecloudUrl: "https://fdm.lntu.edu.cn",
|
||||
AmpUrl: "https://fdm.lntu.edu.cn/wec-portal-mobile/client",
|
||||
}
|
||||
// 模拟 lntuCasLogin 内部的入口覆盖(不发起网络请求)
|
||||
clone := *school
|
||||
clone.AmpUrl = lntuCasLoginEntry(school)
|
||||
if got := getCasValidLoginUrl(&clone); got != "https://fdm.lntu.edu.cn/iap" {
|
||||
t.Errorf("getCasValidLoginUrl() = %q, want 网关 /iap 入口", got)
|
||||
}
|
||||
// 原对象不被修改
|
||||
if school.AmpUrl != "https://fdm.lntu.edu.cn/wec-portal-mobile/client" {
|
||||
t.Errorf("原 school 对象 ampUrl 被意外修改: %q", school.AmpUrl)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLntuIsSliderCaptchaSchool 确认 lntu 归入滑块验证码学校需通过配置声明
|
||||
// (captchaSwitch=2 + createSliderCaptcha → /common/toSliderCaptcha.htl,与 hqdx 同协议)
|
||||
func TestLntuSliderProtocolSameAsHqu(t *testing.T) {
|
||||
// 协议一致性由配置驱动:lntu 与 hqdx 共用 resolveWiseduSliderCaptcha
|
||||
//(openSliderCaptcha.htl 取图 → 打码 → verifySliderCaptcha.htl sign 提交)。
|
||||
// 此处仅断言常量存在且不与其他学校 ID 冲突。
|
||||
if LntuSchoolId == "" || LntuSchoolId != "lntu" {
|
||||
t.Errorf("LntuSchoolId = %q, want lntu", LntuSchoolId)
|
||||
}
|
||||
if HquSchoolId == LntuSchoolId {
|
||||
t.Errorf("lntu 与 hqdx 学校 ID 冲突")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// ========== CAS 多因子认证(MFA / reAuth)==========
|
||||
|
||||
// 今日校园定制 CAS 的多因子认证扩展(reAuthCheck)。
|
||||
// 触发场景:CAS 账密提交成功后不是直接签发 ST 票据,而是 302 到
|
||||
// {base}/authserver/reAuthCheck/reAuthLoginView.do?isMultifactor=true&service=<encoded>
|
||||
// 该页面渲染当前用户全部可用的二次认证方式(Tab / 更多菜单 / 旧版列表),
|
||||
// 调用方应把方式列表返回给用户选择;用户选定后调用发码接口(按需先 changeReAuthType.do
|
||||
// 切换服务端会话方式),用户取得验证码后再提交 reAuthSubmit.do 完成认证,
|
||||
// 最后访问 /login?service= 完成票据交换。
|
||||
|
||||
// ErrMFARequired 表示本次登录触发了多因子认证,
|
||||
// 调用方应为返回的 MFAContext 暂存并引导用户选择验证方式、获取验证码并提交。
|
||||
var ErrMFARequired = fmt.Errorf("mfa_required")
|
||||
|
||||
// ErrMFASessionExpired 表示 MFA 中间会话已失效(Redis 过期 / reAuth_unauthorized / 会话被服务端作废),
|
||||
// 调用方应引导用户重新登录(可用 errors.Is 判断)。
|
||||
var ErrMFASessionExpired = fmt.Errorf("mfa_session_expired")
|
||||
|
||||
// MFAAuthMethod 一种可用的多因子验证方式(来自 MFA 页面渲染的可用方式列表)
|
||||
type MFAAuthMethod struct {
|
||||
Type string `json:"type"` // reAuthType 数字编码(3=短信 4=企业微信 5=今日校园 11=邮箱 12=钉钉 13=WeLink 15=公众号)
|
||||
Name string `json:"name"` // 展示名(优先页面文案,缺省用内置映射)
|
||||
Default bool `json:"default,omitempty"` // 页面默认选中项
|
||||
}
|
||||
|
||||
// MFAContext 触发 MFA 后的中间会话状态(可 JSON 序列化存 Redis,TTL 内有效)
|
||||
type MFAContext struct {
|
||||
BaseURL string `json:"baseUrl"` // CAS 根地址,如 http://ids.hfpec.edu.cn
|
||||
ContextPath string `json:"contextPath"` // CAS 上下文路径,默认 /authserver
|
||||
Service string `json:"service"` // reAuth service(含 sessionToken)
|
||||
ReAuthType string `json:"reAuthType"` // 当前/用户最后选定的方式:2=密码 3=短信 5=今日校园 11=邮箱 12=钉钉 13=WeLink 15=公众号
|
||||
UserID string `json:"userId"` // 学工号
|
||||
AuthMethods []MFAAuthMethod `json:"authMethods,omitempty"` // 页面支持的全部可用验证方式
|
||||
WecloudUrl string `json:"wecloudUrl"` // 完成登录后 activateSession 所需
|
||||
CookiesByHost map[string][]*http.Cookie `json:"cookiesByHost"` // CAS 阶段会话(按域保存)
|
||||
}
|
||||
|
||||
// MFASendResult 发送 MFA 验证码的结果
|
||||
type MFASendResult struct {
|
||||
Mobile string `json:"mobile,omitempty"` // 收码目标(手机号等,可能带掩码)
|
||||
CodeTime int `json:"codeTime,omitempty"` // 可再次发送的倒计时秒数(0 表示不限制/未提供)
|
||||
Message string `json:"message,omitempty"` // 服务端提示文案
|
||||
}
|
||||
|
||||
// reAuthType → 发码接口的 authCodeTypeName 映射(源自 mobile-reAuth.js sendDynamicCodeByPhone)
|
||||
var reAuthCodeTypeNames = map[string]string{
|
||||
"3": "reAuthDynamicCodeType", // 手机短信
|
||||
"4": "reAuthWChatDynamicCodeType", // 企业微信
|
||||
"5": "reAuthCpdailyDynamicCodeType", // 今日校园
|
||||
"11": "reAuthEmailDynamicCodeType", // 邮箱
|
||||
"12": "reAuthDingTalkDynamicCodeType", // 钉钉
|
||||
"13": "reAuthWeLinkDynamicCodeType", // WeLink
|
||||
"15": "reAuthWeChatServiceDynamicCodeType", // 微信公众号
|
||||
}
|
||||
|
||||
// reAuthType → 默认展示名(页面 Tab 无文案时兜底)
|
||||
var reAuthTypeNames = map[string]string{
|
||||
"2": "密码验证",
|
||||
"3": "短信验证码",
|
||||
"4": "企业微信验证码",
|
||||
"5": "今日校园验证码",
|
||||
"6": "实人认证",
|
||||
"7": "安全问题",
|
||||
"9": "QQ扫码",
|
||||
"10": "安全令牌OTP",
|
||||
"11": "邮箱验证",
|
||||
"12": "钉钉验证码",
|
||||
"13": "WeLink验证码",
|
||||
"15": "公众号验证码",
|
||||
}
|
||||
|
||||
// 需要发送动态码的 reAuthType 集合(密码/人脸/密保问题等类型不走发码接口)
|
||||
func reAuthTypeNeedsDynamicCode(reAuthType string) bool {
|
||||
_, ok := reAuthCodeTypeNames[reAuthType]
|
||||
return ok
|
||||
}
|
||||
|
||||
var (
|
||||
reAuthParamsBlockRegexp = regexp.MustCompile(`var\s+reAuthParams\s*=\s*\{([\s\S]*?)\n\s*\}`)
|
||||
reAuthTypeRegexp = regexp.MustCompile(`"reAuthType"\s*:\s*"([^"]*)"`)
|
||||
reAuthServiceRegexp = regexp.MustCompile(`"service"\s*:\s*"([^"]*)"`)
|
||||
reAuthUserIdRegexp = regexp.MustCompile(`"reAuthUserId"\s*:\s*"([^"]*)"`)
|
||||
contextPathRegexp = regexp.MustCompile(`contextPath\s*=\s*"([^"]*)"`)
|
||||
trailingDigitsRegexp = regexp.MustCompile(`(\d+)$`)
|
||||
)
|
||||
|
||||
// 页面可用验证方式选择器(兼容历代模板;注释块内的元素不会被 goquery 匹配):
|
||||
// .mobile-reauth-tab-item[data-type] 移动端 Tab(如 id="mobile_tab_5")
|
||||
// .reauth-tab-item[data-type] 新版统一模板 Tab(如 id="tab_13")
|
||||
// .reauth-tab-more-item[id] "更多"菜单(id 即编号)
|
||||
// .changeReAuthTypes[id] 旧版列表(id 即编号)
|
||||
// .other_type_button[id] "选择认证方式"弹窗按钮(如许昌学院 xcuTheme,id 即编号)
|
||||
const mfaMethodSelectors = ".mobile-reauth-tab-item, .reauth-tab-item, .reauth-tab-more-item, .changeReAuthTypes, .other_type_button"
|
||||
|
||||
// parseMFAAuthMethods 从 MFA 页面解析全部可用验证方式(返回页面渲染顺序)
|
||||
func parseMFAAuthMethods(page string) []MFAAuthMethod {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(page))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var methods []MFAAuthMethod
|
||||
seen := make(map[string]bool)
|
||||
doc.Find(mfaMethodSelectors).Each(func(_ int, s *goquery.Selection) {
|
||||
reAuthType := strings.TrimSpace(s.AttrOr("data-type", ""))
|
||||
if reAuthType == "" {
|
||||
// 无 data-type 时从 id 提取尾部数字:mobile_tab_5 / tab_13 / 5 均可
|
||||
reAuthType = trailingDigitsRegexp.FindString(s.AttrOr("id", ""))
|
||||
}
|
||||
if reAuthType == "" || seen[reAuthType] {
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(s.Find(".mobile-reauth-tab-text").Text())
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(s.Text())
|
||||
}
|
||||
if name == "" {
|
||||
name = reAuthTypeNames[reAuthType]
|
||||
}
|
||||
if name == "" {
|
||||
name = "验证方式" + reAuthType
|
||||
}
|
||||
seen[reAuthType] = true
|
||||
methods = append(methods, MFAAuthMethod{
|
||||
Type: reAuthType,
|
||||
Name: name,
|
||||
Default: s.HasClass("mobile-reauth-tab-active") || s.HasClass("reauth-tab-active"),
|
||||
})
|
||||
})
|
||||
return methods
|
||||
}
|
||||
|
||||
// normalizeMFAAuthMethods 规范化可用验证方式列表:
|
||||
// 1. 仅保留能接收动态码、本流程可完成的方式(短信/企业微信/今日校园/邮箱/钉钉/WeLink/公众号);
|
||||
// 2. 过滤后为空时保留原列表(页面异常时前端仍能看到可选方式,发码时会得到明确提示);
|
||||
// 3. 列表整体为空(页面无 Tab / 解析失败)且当前方式支持动态码时,用当前方式兜底为唯一选项,
|
||||
// 避免前端「选择验证方式」无项可选、流程走不通;
|
||||
// 4. 页面未标记默认项时,按 defaultType 标记,最后兜底标记首项。
|
||||
func normalizeMFAAuthMethods(methods []MFAAuthMethod, defaultType string) []MFAAuthMethod {
|
||||
var supported []MFAAuthMethod
|
||||
for _, m := range methods {
|
||||
if reAuthTypeNeedsDynamicCode(m.Type) {
|
||||
supported = append(supported, m)
|
||||
}
|
||||
}
|
||||
if len(supported) > 0 {
|
||||
methods = supported
|
||||
}
|
||||
if len(methods) == 0 {
|
||||
if !reAuthTypeNeedsDynamicCode(defaultType) {
|
||||
return methods
|
||||
}
|
||||
// 页面无 Tab(解析失败或旧版模板):用当前 reAuthType 兜底为唯一方式
|
||||
name := reAuthTypeNames[defaultType]
|
||||
if name == "" {
|
||||
name = "验证方式" + defaultType
|
||||
}
|
||||
return []MFAAuthMethod{{Type: defaultType, Name: name, Default: true}}
|
||||
}
|
||||
if !hasDefaultMFAMethod(methods) {
|
||||
for i := range methods {
|
||||
if methods[i].Type == defaultType {
|
||||
methods[i].Default = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !hasDefaultMFAMethod(methods) {
|
||||
methods[0].Default = true
|
||||
}
|
||||
return methods
|
||||
}
|
||||
|
||||
// hasDefaultMFAMethod 列表内是否已有默认项
|
||||
func hasDefaultMFAMethod(methods []MFAAuthMethod) bool {
|
||||
for _, m := range methods {
|
||||
if m.Default {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// handleMFATriggered 处理 CAS 登录后 302 到 MFA 页面的情况:
|
||||
// 解析 MFA 页面参数与全部可用验证方式,返回 MFAContext 供用户选择方式、发送并提交验证码。
|
||||
func handleMFATriggered(ctx context.Context, resp *resty.Response, school *SchoolDetailInfo, sc *sessionClient) (*MFAContext, error) {
|
||||
location, err := resp.RawResponse.Location()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取MFA重定向地址失败: %w", err)
|
||||
}
|
||||
|
||||
// 恢复自动重定向(后续请求页面需要跟随)
|
||||
sc.SetRedirectPolicy(resty.FlexibleRedirectPolicy(10))
|
||||
pageResp, err := sc.R().SetContext(ctx).Get(location.String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求MFA页面失败: %w", err)
|
||||
}
|
||||
page := string(readBody(pageResp))
|
||||
slog.Info("MFA页面获取", "url", location.String(), "bodyLen", len(page))
|
||||
|
||||
mfa := &MFAContext{
|
||||
WecloudUrl: school.WecloudUrl,
|
||||
}
|
||||
|
||||
// CAS 根地址与上下文路径
|
||||
if u, err := url.Parse(location.String()); err == nil {
|
||||
mfa.BaseURL = u.Scheme + "://" + u.Host
|
||||
}
|
||||
mfa.ContextPath = "/authserver"
|
||||
if m := contextPathRegexp.FindStringSubmatch(page); len(m) > 1 {
|
||||
mfa.ContextPath = strings.ReplaceAll(m[1], `\/`, "/")
|
||||
}
|
||||
|
||||
// 解析 reAuthParams 块内的关键字段
|
||||
block := reAuthParamsBlockRegexp.FindStringSubmatch(page)
|
||||
if len(block) > 1 {
|
||||
params := block[1]
|
||||
if m := reAuthTypeRegexp.FindStringSubmatch(params); len(m) > 1 {
|
||||
mfa.ReAuthType = m[1]
|
||||
}
|
||||
if m := reAuthServiceRegexp.FindStringSubmatch(params); len(m) > 1 {
|
||||
mfa.Service = strings.ReplaceAll(m[1], `\/`, "/")
|
||||
}
|
||||
if m := reAuthUserIdRegexp.FindStringSubmatch(params); len(m) > 1 {
|
||||
mfa.UserID = m[1]
|
||||
}
|
||||
}
|
||||
// 兜底:service 从 302 Location 的 query 取
|
||||
if mfa.Service == "" {
|
||||
mfa.Service = location.Query().Get("service")
|
||||
}
|
||||
if mfa.ReAuthType == "" {
|
||||
mfa.ReAuthType = "5"
|
||||
slog.Warn("MFA页面未解析到reAuthType,按动态码处理", "base", mfa.BaseURL)
|
||||
}
|
||||
|
||||
// 解析页面全部可用验证方式(Tab / 更多菜单 / 旧版列表)
|
||||
mfa.AuthMethods = normalizeMFAAuthMethods(parseMFAAuthMethods(page), mfa.ReAuthType)
|
||||
slog.Info("MFA参数解析", "reAuthType", mfa.ReAuthType, "userId", mfa.UserID,
|
||||
"service", mfa.Service, "methods", len(mfa.AuthMethods))
|
||||
|
||||
// 不再自动发送验证码:由用户在前端选择验证方式后调用 SendMFADynamicCode 发送
|
||||
if !reAuthTypeNeedsDynamicCode(mfa.ReAuthType) {
|
||||
slog.Warn("MFA默认验证方式非动态码类型,需用户选择其他方式", "reAuthType", mfa.ReAuthType)
|
||||
}
|
||||
|
||||
// 保存当前 CAS 会话(按域)
|
||||
mfa.CookiesByHost = sc.jar.AllCookiesByHost()
|
||||
|
||||
return mfa, nil
|
||||
}
|
||||
|
||||
// restoreMFACasSession 把触发 MFA 时保存的 CAS 会话恢复到新的会话客户端
|
||||
func restoreMFACasSession(sc *sessionClient, mfa *MFAContext) {
|
||||
for host, cookies := range mfa.CookiesByHost {
|
||||
u := &url.URL{Scheme: "http", Host: host}
|
||||
if strings.HasPrefix(mfa.BaseURL, "https://") {
|
||||
u.Scheme = "https"
|
||||
}
|
||||
sc.jar.SetCookies(u, cookies)
|
||||
}
|
||||
}
|
||||
|
||||
// changeMFAAuthType 调用 changeReAuthType.do 把服务端 MFA 会话切换到指定验证方式
|
||||
// POST {base}{contextPath}/reAuthCheck/changeReAuthType.do
|
||||
func changeMFAAuthType(ctx context.Context, client *resty.Client, mfa *MFAContext, reAuthType string) error {
|
||||
changeUrl := mfa.BaseURL + mfa.ContextPath + "/reAuthCheck/changeReAuthType.do"
|
||||
resp, err := client.R().SetContext(ctx).
|
||||
SetFormData(map[string]string{
|
||||
"isMultifactor": "true",
|
||||
"reAuthType": reAuthType,
|
||||
"service": mfa.Service,
|
||||
}).
|
||||
Post(changeUrl)
|
||||
if err != nil {
|
||||
return fmt.Errorf("切换MFA验证方式失败: %w", err)
|
||||
}
|
||||
body := readBody(resp)
|
||||
slog.Info("MFA切换验证方式响应", "status", resp.StatusCode(), "reAuthType", reAuthType,
|
||||
"body", string(body[:min(len(body), 500)]))
|
||||
|
||||
// code 兼容数字 1 与字符串 "1"(不同学校版本返回类型不一致)
|
||||
var result struct {
|
||||
Code interface{} `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return fmt.Errorf("切换MFA验证方式响应解析失败: %w", err)
|
||||
}
|
||||
if fmt.Sprintf("%v", result.Code) != "1" {
|
||||
return fmt.Errorf("%s", orDefault(result.Message, "该验证方式暂不可用,请选择其他方式"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendReAuthDynamicCodeResult 发码接口响应
|
||||
type sendReAuthDynamicCodeResult struct {
|
||||
Res string `json:"res"` // success/cpdaily_success/wechat_success/other_success/code_time_fail
|
||||
ReturnMessage string `json:"returnMessage"` // 服务端提示文案
|
||||
Mobile string `json:"mobile"` // 收码目标(手机号等)
|
||||
CodeTime int `json:"codeTime"` // 可再次发送的倒计时秒数
|
||||
ErrCode string `json:"errCode"` // 错误码(如 206302 会话失效)
|
||||
}
|
||||
|
||||
// postReAuthDynamicCode 调用 CAS 发码接口发送验证码
|
||||
// POST {base}{contextPath}/dynamicCode/getDynamicCodeByReauth.do
|
||||
func postReAuthDynamicCode(ctx context.Context, client *resty.Client, mfa *MFAContext, authCodeTypeName string) (*sendReAuthDynamicCodeResult, error) {
|
||||
sendUrl := mfa.BaseURL + mfa.ContextPath + "/dynamicCode/getDynamicCodeByReauth.do"
|
||||
resp, err := client.R().SetContext(ctx).
|
||||
SetFormData(map[string]string{
|
||||
"userName": mfa.UserID,
|
||||
"authCodeTypeName": authCodeTypeName,
|
||||
}).
|
||||
Post(sendUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("发送MFA验证码失败: %w", err)
|
||||
}
|
||||
body := readBody(resp)
|
||||
slog.Info("MFA验证码发送响应", "status", resp.StatusCode(), "body", string(body[:min(len(body), 500)]))
|
||||
|
||||
var result sendReAuthDynamicCodeResult
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("发送MFA验证码响应解析失败: %w", err)
|
||||
}
|
||||
// 206302:服务端 MFA 会话已失效
|
||||
if result.ErrCode == "206302" {
|
||||
return nil, fmt.Errorf("%w: 验证会话已失效,请重新登录", ErrMFASessionExpired)
|
||||
}
|
||||
|
||||
switch result.Res {
|
||||
case "success", "cpdaily_success", "wechat_success", "other_success", "code_time_fail":
|
||||
// 发送成功(code_time_fail 为倒计时未结束,验证码此前已发出)
|
||||
return &result, nil
|
||||
default:
|
||||
msg := result.ReturnMessage
|
||||
if msg == "" {
|
||||
msg = "发送验证码失败,请稍后重试"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// SendMFADynamicCode 用户选定验证方式后发送动态验证码:
|
||||
// 与当前方式不同时先调用 changeReAuthType.do 切换服务端会话,再调用发码接口;
|
||||
// 成功后同步 mfa.ReAuthType,供后续 reAuthSubmit.do 提交使用。
|
||||
func SendMFADynamicCode(ctx context.Context, mfa *MFAContext, reAuthType string) (*MFASendResult, error) {
|
||||
if mfa == nil || len(mfa.CookiesByHost) == 0 {
|
||||
return nil, fmt.Errorf("%w: 验证会话不存在,请重新登录", ErrMFASessionExpired)
|
||||
}
|
||||
if reAuthType == "" {
|
||||
reAuthType = mfa.ReAuthType
|
||||
}
|
||||
if len(mfa.AuthMethods) > 0 && !mfaHasAuthMethod(mfa.AuthMethods, reAuthType) {
|
||||
return nil, fmt.Errorf("不支持的验证方式,请选择其他方式")
|
||||
}
|
||||
if !reAuthTypeNeedsDynamicCode(reAuthType) {
|
||||
name := reAuthTypeNames[reAuthType]
|
||||
if name == "" {
|
||||
name = "验证方式" + reAuthType
|
||||
}
|
||||
return nil, fmt.Errorf("「%s」暂不支持发送验证码,请选择其他方式", name)
|
||||
}
|
||||
|
||||
loginCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
sc := newSessionClient()
|
||||
restoreMFACasSession(sc, mfa)
|
||||
|
||||
// 与当前会话方式不同时先切换(与官方页面 Tab 切换行为一致)
|
||||
if reAuthType != mfa.ReAuthType {
|
||||
if err := changeMFAAuthType(loginCtx, sc.Client, mfa, reAuthType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mfa.ReAuthType = reAuthType
|
||||
slog.Info("MFA验证方式已切换", "reAuthType", reAuthType)
|
||||
}
|
||||
|
||||
result, err := postReAuthDynamicCode(loginCtx, sc.Client, mfa, reAuthCodeTypeNames[reAuthType])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &MFASendResult{
|
||||
Mobile: result.Mobile,
|
||||
CodeTime: result.CodeTime,
|
||||
Message: orDefault(result.ReturnMessage, "验证码已发送"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// mfaHasAuthMethod 判断方式编号是否在可用列表中
|
||||
func mfaHasAuthMethod(methods []MFAAuthMethod, reAuthType string) bool {
|
||||
for _, m := range methods {
|
||||
if m.Type == reAuthType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CompleteMFALogin 提交用户输入的验证码,完成 MFA 认证并走完 CAS 票据交换,
|
||||
// 返回登录成功后的全部 cookies。
|
||||
func CompleteMFALogin(ctx context.Context, mfa *MFAContext, code string) ([]*http.Cookie, error) {
|
||||
if mfa == nil || len(mfa.CookiesByHost) == 0 {
|
||||
return nil, fmt.Errorf("%w: 验证会话不存在,请重新登录", ErrMFASessionExpired)
|
||||
}
|
||||
|
||||
loginCtx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
sc := newSessionClient()
|
||||
// 恢复 CAS 阶段会话
|
||||
restoreMFACasSession(sc, mfa)
|
||||
|
||||
// 1. 提交验证码(reAuthSubmit.do 返回 JSON,不涉及重定向)
|
||||
submitUrl := mfa.BaseURL + mfa.ContextPath + "/reAuthCheck/reAuthSubmit.do"
|
||||
submitResp, err := sc.R().SetContext(loginCtx).
|
||||
SetFormData(map[string]string{
|
||||
"service": mfa.Service,
|
||||
"reAuthType": mfa.ReAuthType,
|
||||
"isMultifactor": "true",
|
||||
"password": "",
|
||||
"dynamicCode": code,
|
||||
"uuid": "",
|
||||
"answer1": "",
|
||||
"answer2": "",
|
||||
"otpCode": "",
|
||||
}).
|
||||
Post(submitUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("提交MFA验证码失败: %w", err)
|
||||
}
|
||||
body := readBody(submitResp)
|
||||
slog.Info("MFA验证码提交响应", "status", submitResp.StatusCode(), "body", string(body[:min(len(body), 500)]))
|
||||
|
||||
var result struct {
|
||||
Code string `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &result)
|
||||
switch result.Code {
|
||||
case "reAuth_failed":
|
||||
return nil, fmt.Errorf("%s", orDefault(result.Msg, "验证码错误或已过期"))
|
||||
case "reAuth_unauthorized":
|
||||
return nil, fmt.Errorf("%w: %s", ErrMFASessionExpired, orDefault(result.Msg, "验证会话已失效,请重新登录"))
|
||||
}
|
||||
|
||||
// 2. 完成 CAS 票据交换:GET /login?service=... → 302(service?ticket=) → wecloud /iap/loginSuccess
|
||||
exchangeUrl := mfa.BaseURL + mfa.ContextPath + "/login?service=" + url.QueryEscape(mfa.Service)
|
||||
sc.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
|
||||
exchangeResp, err := sc.R().SetContext(loginCtx).Get(exchangeUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MFA票据交换失败: %w", err)
|
||||
}
|
||||
_ = exchangeResp
|
||||
|
||||
// 3. 激活 wecloud 会话
|
||||
activateSession(loginCtx, mfa.WecloudUrl, sc.Client)
|
||||
|
||||
cookies := sc.jar.AllCookies()
|
||||
return cookies, nil
|
||||
}
|
||||
|
||||
// orDefault 空串时取默认值
|
||||
func orDefault(s, def string) string {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return def
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// ========== MFA 页面「可用验证方式」解析测试 ==========
|
||||
|
||||
// 移动端模板样本(结构取自真实 MFA 页面,已脱敏)
|
||||
const mfaMobilePageSample = `<!DOCTYPE html><html><body>
|
||||
<script>var reAuthParams = {
|
||||
"reAuthType":"5",
|
||||
"isMultifactor":"true",
|
||||
"service":"https:\/\/school.campusphere.net\/iap\/loginSuccess?sessionToken=test-token",
|
||||
"reAuthUserId":"20220000000"
|
||||
};</script>
|
||||
<div class="mobile-reauth-tab-list" id="mobileTabList">
|
||||
<div class="mobile-reauth-tab-item mobile-reauth-tab-active" id="mobile_tab_5"
|
||||
onclick="handleMobileTabClick(this)" data-type="5" data-index="0">
|
||||
<span class="mobile-reauth-tab-text" title="今日校园验证码">今日校园验证码</span>
|
||||
</div>
|
||||
<div class="mobile-reauth-tab-item" id="mobile_tab_11" onclick="handleMobileTabClick(this)" data-type="11" data-index="1">
|
||||
<span class="mobile-reauth-tab-text" title="邮箱验证">邮箱验证</span>
|
||||
</div>
|
||||
</div>
|
||||
</body></html>`
|
||||
|
||||
func TestParseMFAAuthMethodsMobileTabs(t *testing.T) {
|
||||
methods := parseMFAAuthMethods(mfaMobilePageSample)
|
||||
if len(methods) != 2 {
|
||||
t.Fatalf("期望解析出 2 个方式,实际 %d: %+v", len(methods), methods)
|
||||
}
|
||||
if methods[0].Type != "5" || methods[0].Name != "今日校园验证码" || !methods[0].Default {
|
||||
t.Errorf("第 1 项解析错误: %+v", methods[0])
|
||||
}
|
||||
if methods[1].Type != "11" || methods[1].Name != "邮箱验证" || methods[1].Default {
|
||||
t.Errorf("第 2 项解析错误: %+v", methods[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMFAAuthMethodsNewLayoutWithMoreMenu(t *testing.T) {
|
||||
page := `<html><body>
|
||||
<div class="reauth-tab-item reauth-tab-active" id="tab_13" data-type="13"></div>
|
||||
<div class="reauth-tab-item" id="tab_3" data-type="3"></div>
|
||||
<a class="reauth-tab-more-item" id="10">OTP</a>
|
||||
</body></html>`
|
||||
methods := parseMFAAuthMethods(page)
|
||||
if len(methods) != 3 {
|
||||
t.Fatalf("期望解析出 3 个方式,实际 %d: %+v", len(methods), methods)
|
||||
}
|
||||
if methods[0].Type != "13" || !methods[0].Default || methods[0].Name != "WeLink验证码" {
|
||||
t.Errorf("第 1 项解析错误(应取 data-type、active 标记、兜底名): %+v", methods[0])
|
||||
}
|
||||
if methods[1].Type != "3" || methods[1].Name != "短信验证码" {
|
||||
t.Errorf("第 2 项解析错误: %+v", methods[1])
|
||||
}
|
||||
if methods[2].Type != "10" || methods[2].Name != "OTP" {
|
||||
t.Errorf("更多菜单项解析错误(id 即编号、文本即名字): %+v", methods[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMFAAuthMethodsLegacyLayout(t *testing.T) {
|
||||
page := `<html><body>
|
||||
<div class="changeReAuthTypes" id="3"></div>
|
||||
<div class="changeReAuthTypes" id="10"></div>
|
||||
</body></html>`
|
||||
methods := parseMFAAuthMethods(page)
|
||||
if len(methods) != 2 {
|
||||
t.Fatalf("期望解析出 2 个方式,实际 %d: %+v", len(methods), methods)
|
||||
}
|
||||
if methods[0].Type != "3" || methods[1].Type != "10" {
|
||||
t.Errorf("旧版列表解析错误: %+v", methods)
|
||||
}
|
||||
}
|
||||
|
||||
// 许昌学院 xcuTheme:「选择认证方式」弹窗(结构取自真实 MFA 页面,已脱敏)
|
||||
const mfaOtherTypeDialogPageSample = `<html><body>
|
||||
<script>var reAuthParams = {
|
||||
"reAuthType":"3",
|
||||
"isMultifactor":"true",
|
||||
"service":"https:\/\/xcu.campusphere.net\/iap\/loginSuccess?sessionToken=test-token",
|
||||
"reAuthUserId":"5810260823"
|
||||
};</script>
|
||||
<div id="other_dialog">
|
||||
<div class="mask changeOtherType"></div>
|
||||
<div class="dialog-reAuth changeOtherType" id="changeOtherType">
|
||||
<div class="other_type_title other_type_header_title">选择认证方式</div>
|
||||
<div id="3" class="other_type_button" onclick="changeMobileReAuthType(this)">短信验证码</div>
|
||||
<div class="other_type_title cancel_bottom_btn" onclick="mobileChangeTypeCancel();">取消</div>
|
||||
</div>
|
||||
</div>
|
||||
</body></html>`
|
||||
|
||||
func TestParseMFAAuthMethodsOtherTypeDialog(t *testing.T) {
|
||||
methods := parseMFAAuthMethods(mfaOtherTypeDialogPageSample)
|
||||
if len(methods) != 1 {
|
||||
t.Fatalf("弹窗方式列表应解析出 1 个方式,实际 %d: %+v", len(methods), methods)
|
||||
}
|
||||
if methods[0].Type != "3" || methods[0].Name != "短信验证码" {
|
||||
t.Errorf("弹窗方式解析错误(id 即编号、文本即名字): %+v", methods[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMFAAuthMethodsOtherTypeDialogMulti(t *testing.T) {
|
||||
// 多方式弹窗:标题不应被误解析,仅 .other_type_button 计入
|
||||
page := `<html><body>
|
||||
<div class="dialog-reAuth changeOtherType" id="changeOtherType">
|
||||
<div class="other_type_title other_type_header_title">选择认证方式</div>
|
||||
<div id="3" class="other_type_button">短信验证码</div>
|
||||
<div id="11" class="other_type_button">邮箱验证</div>
|
||||
<div class="other_type_title cancel_bottom_btn">取消</div>
|
||||
</div>
|
||||
</body></html>`
|
||||
methods := parseMFAAuthMethods(page)
|
||||
if len(methods) != 2 {
|
||||
t.Fatalf("期望解析出 2 个方式,实际 %d: %+v", len(methods), methods)
|
||||
}
|
||||
if methods[0].Type != "3" || methods[0].Name != "短信验证码" || methods[1].Type != "11" || methods[1].Name != "邮箱验证" {
|
||||
t.Errorf("多方式弹窗解析错误: %+v", methods)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMFAAuthMethodsDedupeAcrossLayouts(t *testing.T) {
|
||||
// 同一方式同时出现在 Tab 与弹窗时应去重(保留先出现项)
|
||||
page := `<html><body>
|
||||
<div class="reauth-tab-item" id="tab_3" data-type="3"></div>
|
||||
<div class="other_type_button" id="3">短信验证码</div>
|
||||
</body></html>`
|
||||
methods := parseMFAAuthMethods(page)
|
||||
if len(methods) != 1 || methods[0].Type != "3" {
|
||||
t.Fatalf("跨布局重复方式应去重,实际: %+v", methods)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMFAAuthMethodsIgnoresComments(t *testing.T) {
|
||||
page := `<html><body>
|
||||
<!-- <div class="mobile-reauth-tab-item" data-type="9"><span class="mobile-reauth-tab-text">QQ扫码</span></div> -->
|
||||
<div class="mobile-reauth-tab-item" data-type="5"><span class="mobile-reauth-tab-text">今日校园验证码</span></div>
|
||||
</body></html>`
|
||||
methods := parseMFAAuthMethods(page)
|
||||
if len(methods) != 1 || methods[0].Type != "5" {
|
||||
t.Fatalf("注释块内的方式不应被解析,实际: %+v", methods)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMFAAuthMethodsEmptyPage(t *testing.T) {
|
||||
if methods := parseMFAAuthMethods("<html><body><p>no tabs</p></body></html>"); len(methods) != 0 {
|
||||
t.Fatalf("无方式列表的页面应返回空,实际: %+v", methods)
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 方式列表规范化测试 ==========
|
||||
|
||||
func TestNormalizeMFAAuthMethodsFiltersNonDynamicCode(t *testing.T) {
|
||||
in := []MFAAuthMethod{
|
||||
{Type: "2", Name: "密码验证"},
|
||||
{Type: "5", Name: "今日校园验证码"},
|
||||
{Type: "11", Name: "邮箱验证"},
|
||||
{Type: "10", Name: "安全令牌OTP"},
|
||||
}
|
||||
out := normalizeMFAAuthMethods(in, "5")
|
||||
if len(out) != 2 || out[0].Type != "5" || out[1].Type != "11" {
|
||||
t.Fatalf("应过滤到仅动态码方式 [5,11],实际: %+v", out)
|
||||
}
|
||||
if !out[0].Default || out[1].Default {
|
||||
t.Errorf("默认项标记错误: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeMFAAuthMethodsKeepsAllWhenNoDynamicCode(t *testing.T) {
|
||||
in := []MFAAuthMethod{
|
||||
{Type: "2", Name: "密码验证"},
|
||||
{Type: "6", Name: "实人认证"},
|
||||
}
|
||||
out := normalizeMFAAuthMethods(in, "2")
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("全为非动态码时应保留原列表,实际: %+v", out)
|
||||
}
|
||||
if !out[0].Default {
|
||||
t.Errorf("应按 defaultType 标记默认项: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeMFAAuthMethodsDefaultFallbacks(t *testing.T) {
|
||||
// 页面未标记默认 + defaultType 匹配第二项
|
||||
in := []MFAAuthMethod{
|
||||
{Type: "5", Name: "Today"},
|
||||
{Type: "11", Name: "Email"},
|
||||
}
|
||||
out := normalizeMFAAuthMethods(in, "11")
|
||||
if !out[1].Default || out[0].Default {
|
||||
t.Fatalf("defaultType=11 应标记第二项: %+v", out)
|
||||
}
|
||||
// defaultType 不在列表时标记首项
|
||||
in2 := []MFAAuthMethod{
|
||||
{Type: "5", Name: "Today"},
|
||||
{Type: "3", Name: "SMS"},
|
||||
}
|
||||
out2 := normalizeMFAAuthMethods(in2, "9")
|
||||
if !out2[0].Default {
|
||||
t.Fatalf("defaultType 不在列表时应标记首项: %+v", out2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeMFAAuthMethodsEmptyListFallback(t *testing.T) {
|
||||
// 页面无 Tab / 解析失败且当前方式支持动态码:用当前方式兜底为唯一选项,避免前端无可选
|
||||
out := normalizeMFAAuthMethods(nil, "5")
|
||||
if len(out) != 1 || out[0].Type != "5" || out[0].Name != "今日校园验证码" || !out[0].Default {
|
||||
t.Fatalf("空列表应按 reAuthType=5 兜底为唯一选项,实际: %+v", out)
|
||||
}
|
||||
// 当前方式不支持动态码(如实人认证)时不造选项,保持空
|
||||
if out := normalizeMFAAuthMethods(nil, "6"); len(out) != 0 {
|
||||
t.Fatalf("非动态码方式不应兜底,实际: %+v", out)
|
||||
}
|
||||
// defaultType 为空同样不猜测
|
||||
if out := normalizeMFAAuthMethods(nil, ""); len(out) != 0 {
|
||||
t.Fatalf("defaultType 为空不应兜底,实际: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// ========== SendMFADynamicCode 全流程测试(mock CAS 服务器) ==========
|
||||
|
||||
func TestSendMFADynamicCode(t *testing.T) {
|
||||
var (
|
||||
changeCalled bool
|
||||
changeForm map[string]string
|
||||
codeForm map[string]string
|
||||
changeResp = `{"code":1,"data":{"reAuthType":"11"}}`
|
||||
codeResp = `{"res":"other_success","returnMessage":"验证码已发送成功!","mobile":"138****0000","codeTime":120}`
|
||||
)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/authserver/reAuthCheck/changeReAuthType.do":
|
||||
changeCalled = true
|
||||
_ = r.ParseForm()
|
||||
changeForm = map[string]string{
|
||||
"isMultifactor": r.Form.Get("isMultifactor"),
|
||||
"reAuthType": r.Form.Get("reAuthType"),
|
||||
"service": r.Form.Get("service"),
|
||||
}
|
||||
_, _ = w.Write([]byte(changeResp))
|
||||
case "/authserver/dynamicCode/getDynamicCodeByReauth.do":
|
||||
_ = r.ParseForm()
|
||||
codeForm = map[string]string{
|
||||
"userName": r.Form.Get("userName"),
|
||||
"authCodeTypeName": r.Form.Get("authCodeTypeName"),
|
||||
}
|
||||
_, _ = w.Write([]byte(codeResp))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
host := strings.TrimPrefix(server.URL, "http://")
|
||||
|
||||
newMFA := func() *MFAContext {
|
||||
return &MFAContext{
|
||||
BaseURL: server.URL,
|
||||
ContextPath: "/authserver",
|
||||
Service: "https://school.campusphere.net/iap/loginSuccess?sessionToken=t",
|
||||
ReAuthType: "5",
|
||||
UserID: "20220000000",
|
||||
AuthMethods: []MFAAuthMethod{
|
||||
{Type: "5", Name: "今日校园验证码", Default: true},
|
||||
{Type: "11", Name: "邮箱验证"},
|
||||
},
|
||||
CookiesByHost: map[string][]*http.Cookie{
|
||||
host: {{Name: "CASTGC", Value: "TGT-test"}},
|
||||
},
|
||||
}
|
||||
}
|
||||
reset := func() {
|
||||
changeCalled = false
|
||||
changeForm = nil
|
||||
codeForm = nil
|
||||
changeResp = `{"code":1,"data":{"reAuthType":"11"}}`
|
||||
codeResp = `{"res":"other_success","returnMessage":"验证码已发送成功!","mobile":"138****0000","codeTime":120}`
|
||||
}
|
||||
|
||||
t.Run("切换到新方式并发送", func(t *testing.T) {
|
||||
reset()
|
||||
mfa := newMFA()
|
||||
result, err := SendMFADynamicCode(context.Background(), mfa, "11")
|
||||
if err != nil {
|
||||
t.Fatalf("发送失败: %v", err)
|
||||
}
|
||||
if !changeCalled {
|
||||
t.Error("选择了与默认不同的方式,应先调用 changeReAuthType.do")
|
||||
}
|
||||
if changeForm["isMultifactor"] != "true" || changeForm["reAuthType"] != "11" || changeForm["service"] != mfa.Service {
|
||||
t.Errorf("切换参数错误: %+v", changeForm)
|
||||
}
|
||||
if codeForm["authCodeTypeName"] != "reAuthEmailDynamicCodeType" || codeForm["userName"] != "20220000000" {
|
||||
t.Errorf("发码参数错误: %+v", codeForm)
|
||||
}
|
||||
if result.Mobile != "138****0000" || result.CodeTime != 120 || result.Message != "验证码已发送成功!" {
|
||||
t.Errorf("发码结果解析错误: %+v", result)
|
||||
}
|
||||
if mfa.ReAuthType != "11" {
|
||||
t.Errorf("发送成功后应同步 ReAuthType=11,实际 %s", mfa.ReAuthType)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("沿用默认方式不切换", func(t *testing.T) {
|
||||
reset()
|
||||
mfa := newMFA()
|
||||
_, err := SendMFADynamicCode(context.Background(), mfa, "5")
|
||||
if err != nil {
|
||||
t.Fatalf("发送失败: %v", err)
|
||||
}
|
||||
if changeCalled {
|
||||
t.Error("选择与默认相同的方式不应调用 changeReAuthType.do")
|
||||
}
|
||||
if codeForm["authCodeTypeName"] != "reAuthCpdailyDynamicCodeType" {
|
||||
t.Errorf("发码参数错误: %+v", codeForm)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("切换响应 code 为字符串1也兼容", func(t *testing.T) {
|
||||
reset()
|
||||
changeResp = `{"code":"1","data":{"reAuthType":"11"}}`
|
||||
mfa := newMFA()
|
||||
if _, err := SendMFADynamicCode(context.Background(), mfa, "11"); err != nil {
|
||||
t.Fatalf("字符串 code=1 应视为切换成功,实际报错: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("不在可用列表的方式被拒绝", func(t *testing.T) {
|
||||
reset()
|
||||
mfa := newMFA()
|
||||
if _, err := SendMFADynamicCode(context.Background(), mfa, "2"); err == nil {
|
||||
t.Fatal("不在列表中的方式应报错")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("列表内非动态码方式被拒绝", func(t *testing.T) {
|
||||
reset()
|
||||
mfa := newMFA()
|
||||
mfa.AuthMethods = append(mfa.AuthMethods, MFAAuthMethod{Type: "6", Name: "实人认证"})
|
||||
_, err := SendMFADynamicCode(context.Background(), mfa, "6")
|
||||
if err == nil || !strings.Contains(err.Error(), "暂不支持发送验证码") {
|
||||
t.Fatalf("非动态码方式应明确报错,实际: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("会话缺失返回过期错误", func(t *testing.T) {
|
||||
reset()
|
||||
mfa := newMFA()
|
||||
mfa.CookiesByHost = nil
|
||||
_, err := SendMFADynamicCode(context.Background(), mfa, "5")
|
||||
if !errors.Is(err, ErrMFASessionExpired) {
|
||||
t.Fatalf("会话缺失应返回 ErrMFASessionExpired,实际: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("发码失败透传服务端文案", func(t *testing.T) {
|
||||
reset()
|
||||
codeResp = `{"res":"fail","returnMessage":"发送过于频繁,请稍后再试"}`
|
||||
mfa := newMFA()
|
||||
_, err := SendMFADynamicCode(context.Background(), mfa, "5")
|
||||
if err == nil || !strings.Contains(err.Error(), "发送过于频繁") {
|
||||
t.Fatalf("应透传服务端失败文案,实际: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("倒计时未结束视为已发送", func(t *testing.T) {
|
||||
reset()
|
||||
codeResp = `{"res":"code_time_fail","returnMessage":"验证码已发送,请勿重复获取","codeTime":60}`
|
||||
mfa := newMFA()
|
||||
result, err := SendMFADynamicCode(context.Background(), mfa, "5")
|
||||
if err != nil {
|
||||
t.Fatalf("code_time_fail 应视为发送成功: %v", err)
|
||||
}
|
||||
if result.CodeTime != 60 {
|
||||
t.Errorf("应回传倒计时秒数,实际: %+v", result)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("会话失效错误码映射为过期", func(t *testing.T) {
|
||||
reset()
|
||||
codeResp = `{"res":"fail","errCode":"206302","returnMessage":"会话失效"}`
|
||||
mfa := newMFA()
|
||||
_, err := SendMFADynamicCode(context.Background(), mfa, "5")
|
||||
if !errors.Is(err, ErrMFASessionExpired) {
|
||||
t.Fatalf("errCode=206302 应映射为 ErrMFASessionExpired,实际: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ========== 许昌学院(xcu)单独适配 ==========
|
||||
|
||||
// XcuSchoolId 许昌学院 tenant id
|
||||
const XcuSchoolId = "xcu"
|
||||
|
||||
// xcuCasLoginEntry 计算许昌学院 CAS 登录入口:
|
||||
// 校园网关的 /portal/login 会 302 到学校 CAS(authserver.xcu.edu.cn),并在 service 中
|
||||
// 携带网关回调(/iap/loginSuccess?sessionToken=...);走完 CAS 账密 + MFA 后回调该地址,
|
||||
// cookie 才能正确落在 xcu.campusphere.net 域(wec-* 任务接口所在域,activateSession 依赖)。
|
||||
// WecloudUrl 缺失时回退用学校 ampUrl(仅保证能走通 CAS 账密 + MFA)。
|
||||
func xcuCasLoginEntry(school *SchoolDetailInfo) string {
|
||||
if school == nil {
|
||||
return ""
|
||||
}
|
||||
if school.WecloudUrl != "" {
|
||||
return strings.TrimSuffix(school.WecloudUrl, "/") + "/portal/login"
|
||||
}
|
||||
return school.AmpUrl
|
||||
}
|
||||
|
||||
// xcuCasLogin 许昌学院强制走 CAS:
|
||||
// 平台接口返回 joinType=CLOUD(IsIap()=true),但其 IAP 账密接口 /iap/doLogin 与通用
|
||||
// IAP 密码加密格式不兼容(实测 RSA hex/base64 等多种编码均返回 FAIL_UPNOTMATCH);
|
||||
// 实际登录链路为 IAP 入口 302 → 学校 CAS 账密 → MFA → 回调 /iap/loginSuccess 建立网关会话。
|
||||
// 因此不走通用 IAP 流程,强制用 CAS 流程并从校园网关入口进入(详见 xcuCasLoginEntry)。
|
||||
func xcuCasLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, *MFAContext, error) {
|
||||
xcu := *school
|
||||
if entry := xcuCasLoginEntry(school); entry != "" {
|
||||
xcu.AmpUrl = entry
|
||||
}
|
||||
return casLogin(ctx, &xcu, username, password)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package cpdaily
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestXcuCasLoginEntry 覆盖许昌学院 CAS 登录入口计算逻辑
|
||||
func TestXcuCasLoginEntry(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
school *SchoolDetailInfo
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "正常wecloud",
|
||||
school: &SchoolDetailInfo{WecloudUrl: "https://xcu.campusphere.net"},
|
||||
want: "https://xcu.campusphere.net/portal/login",
|
||||
},
|
||||
{
|
||||
name: "wecloud带尾斜杠",
|
||||
school: &SchoolDetailInfo{WecloudUrl: "https://xcu.campusphere.net/"},
|
||||
want: "https://xcu.campusphere.net/portal/login",
|
||||
},
|
||||
{
|
||||
name: "wecloud缺失回退ampUrl",
|
||||
school: &SchoolDetailInfo{
|
||||
AmpUrl: "https://casp.xcu.edu.cn/newmobile/client",
|
||||
},
|
||||
want: "https://casp.xcu.edu.cn/newmobile/client",
|
||||
},
|
||||
{
|
||||
name: "均为空",
|
||||
school: &SchoolDetailInfo{},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "nil学校",
|
||||
school: nil,
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := xcuCasLoginEntry(c.school); got != c.want {
|
||||
t.Errorf("xcuCasLoginEntry() = %q, want %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestXcuCasLoginEntryOverridesAmpUrl 确认 xcuCasLogin 用网关入口覆盖 ampUrl 后走 CAS 流程
|
||||
func TestXcuCasLoginEntryOverridesAmpUrl(t *testing.T) {
|
||||
school := &SchoolDetailInfo{
|
||||
ID: XcuSchoolId,
|
||||
Name: "许昌学院",
|
||||
JoinType: "CLOUD",
|
||||
IdsUrl: "https://authserver.xcu.edu.cn/authserver",
|
||||
WecloudUrl: "https://xcu.campusphere.net",
|
||||
AmpUrl: "https://casp.xcu.edu.cn/newmobile/client",
|
||||
}
|
||||
// 模拟 xcuCasLogin 内部的入口覆盖(不发起网络请求)
|
||||
clone := *school
|
||||
clone.AmpUrl = xcuCasLoginEntry(school)
|
||||
if got := getCasValidLoginUrl(&clone); got != "https://xcu.campusphere.net/portal/login" {
|
||||
t.Errorf("getCasValidLoginUrl() = %q, want 网关入口", got)
|
||||
}
|
||||
// 原对象不被修改
|
||||
if school.AmpUrl != "https://casp.xcu.edu.cn/newmobile/client" {
|
||||
t.Errorf("原 school 对象 ampUrl 被意外修改: %q", school.AmpUrl)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// ========== 西藏民族大学(xzmy)单独适配 ==========
|
||||
|
||||
// XzmySchoolId 西藏民族大学 tenant id
|
||||
const XzmySchoolId = "1019389288913029"
|
||||
|
||||
// 该校统一身份认证平台公钥(来自 cas.xzmu.edu.cn 前端 app.js 的 config 对象)
|
||||
const (
|
||||
xzmyRsaModulusHex = "00b5eeb166e069920e80bebd1fea4829d3d1f3216f2aabe79b6c47a3c18dcee5fd22c2e7ac519cab59198ece036dcf289ea8201e2a0b9ded307f8fb704136eaeb670286f5ad44e691005ba9ea5af04ada5367cd724b5a26fdb5120cc95b6431604bd219c6b7d83a6f8f24b43918ea988a76f93c333aa5a20991493d4eb1117e7b1"
|
||||
xzmyRsaExpHex = "010001"
|
||||
)
|
||||
|
||||
// xzmyCasEntry 该校 CAS 登录入口:wecloud 网关的 /iap 会 302 到学校 CAS
|
||||
// (cas.xzmu.edu.cn/lyuapServer/login),service 携带网关回调
|
||||
// /iap/loginSuccess?sessionToken=...;从网关入口进入才能让回调后 cookie 落在
|
||||
// xzmy.campusphere.net 域(wec-* 任务接口所在域)。
|
||||
func xzmyCasEntry(school *SchoolDetailInfo) string {
|
||||
if school == nil {
|
||||
return ""
|
||||
}
|
||||
if school.WecloudUrl != "" {
|
||||
return strings.TrimSuffix(school.WecloudUrl, "/") + "/iap"
|
||||
}
|
||||
if school.IdsUrl != "" {
|
||||
return school.IdsUrl
|
||||
}
|
||||
return school.AmpUrl
|
||||
}
|
||||
|
||||
// xzmyEncryptPassword 该校(Leyan/lyuapServer 定制 CAS)密码加密:
|
||||
// 教科书式 RSA(无填充)——明文按字符铺入 chunkSize 字节块(小端序),
|
||||
// m^e mod n 后输出小写 hex。与通用 wisedu 的 PKCS#1 v1.5(crypto/rsa.EncryptPKCS1v15)
|
||||
// 完全不同:该校后端按小端 hex 解出原文,用 PKCS#1 填充会解成乱码 → PASSERROR。
|
||||
// 对应前端库 app.js 模块 24 的加密函数 W(barrett.powMod(m, e) → hex)。
|
||||
func xzmyEncryptPassword(password string) (string, error) {
|
||||
modBytes, err := hex.DecodeString(xzmyRsaModulusHex)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("解析公钥 modulus 失败: %w", err)
|
||||
}
|
||||
n := new(big.Int).SetBytes(modBytes)
|
||||
chunkSize := (n.BitLen() + 7) / 8
|
||||
block := make([]byte, chunkSize)
|
||||
copy(block, []byte(password))
|
||||
// 小端序组装明文块
|
||||
m := new(big.Int)
|
||||
for i := chunkSize - 1; i >= 0; i-- {
|
||||
m.Lsh(m, 8)
|
||||
m.Or(m, big.NewInt(int64(block[i])))
|
||||
}
|
||||
expBytes, _ := hex.DecodeString(xzmyRsaExpHex)
|
||||
e := new(big.Int).SetBytes(expBytes)
|
||||
c := new(big.Int).Exp(m, e, n)
|
||||
return c.Text(16), nil
|
||||
}
|
||||
|
||||
// xzmyCasLogin 西藏民族大学强制走其定制 CAS:
|
||||
// 平台接口返回 joinType=CLOUD(IsIap()=true),但网关 /iap/doLogin 实际不可用,
|
||||
// IAP 账密提交报 FAIL_UPNOTMATCH(误导为"密码错误");
|
||||
// 真实链路为 /iap 302 → cas.xzmu.edu.cn/lyuapServer/login →(表单 POST
|
||||
// /lyuapServer/v1/tickets,密码=教科书RSA小端hex)→ 得 TGT/ST →
|
||||
// 回调 /iap/loginSuccess?sessionToken=...&ticket=ST 建立网关会话(MOD_AUTH_CAS)。
|
||||
func xzmyCasLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, *MFAContext, error) {
|
||||
entry := xzmyCasEntry(school)
|
||||
if entry == "" {
|
||||
return nil, nil, fmt.Errorf("西藏民族大学登录入口缺失")
|
||||
}
|
||||
|
||||
sc := newSessionClient()
|
||||
|
||||
// 1. 从网关 /iap 进入,302 到 CAS,拿到带 service 的登录页地址
|
||||
pageResp, err := sc.R().SetContext(ctx).Get(entry)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("请求登录入口失败: %w", err)
|
||||
}
|
||||
loginURL := pageResp.RawResponse.Request.URL.String()
|
||||
if !strings.Contains(loginURL, "/lyuapServer/login") {
|
||||
// 未落到 CAS 登录页(网关异常),退回通用 CAS 流程兜底
|
||||
return casLogin(ctx, school, username, password)
|
||||
}
|
||||
casBase := fmt.Sprintf("%s://%s/lyuapServer", pageResp.RawResponse.Request.URL.Scheme, pageResp.RawResponse.Request.URL.Host)
|
||||
service := ""
|
||||
if u, perr := url.Parse(loginURL); perr == nil {
|
||||
service = u.Query().Get("service")
|
||||
}
|
||||
if service == "" {
|
||||
return nil, nil, fmt.Errorf("未获取到登录回调 service")
|
||||
}
|
||||
|
||||
encPwd, err := xzmyEncryptPassword(password)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// 2. 提交账密到 /lyuapServer/v1/tickets(表单编码)
|
||||
ticketResp, err := sc.R().SetContext(ctx).
|
||||
SetHeader("Content-Type", "application/x-www-form-urlencoded").
|
||||
SetFormData(map[string]string{
|
||||
"username": username,
|
||||
"password": encPwd,
|
||||
"service": service,
|
||||
"loginType": "",
|
||||
"id": "",
|
||||
"code": "",
|
||||
}).
|
||||
Post(casBase + "/v1/tickets")
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("提交登录失败: %w", err)
|
||||
}
|
||||
respBody := readBody(ticketResp)
|
||||
tkt := parseXzmyTicket(string(respBody))
|
||||
if tkt.ticket == "" {
|
||||
// 有业务码则翻译为可读错误(NOAUTH/PASSERROR 等)
|
||||
if msg := xzmyLoginError(string(respBody)); msg != "" {
|
||||
return nil, nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
return nil, nil, fmt.Errorf("登录失败,请检查账号密码")
|
||||
}
|
||||
|
||||
// 3. 回调 service + ticket 建立网关会话
|
||||
sep := "&"
|
||||
if !strings.Contains(service, "?") {
|
||||
sep = "?"
|
||||
}
|
||||
sc.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
|
||||
cbResp, err := sc.R().SetContext(ctx).Get(service + sep + "ticket=" + tkt.ticket)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("回调建立会话失败: %w", err)
|
||||
}
|
||||
_ = cbResp
|
||||
|
||||
activateSession(ctx, school.WecloudUrl, sc.Client)
|
||||
|
||||
cookies := sc.jar.AllCookies()
|
||||
hasMOD := false
|
||||
for _, ck := range cookies {
|
||||
if strings.HasPrefix(ck.Name, "MOD_") {
|
||||
hasMOD = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasMOD {
|
||||
return nil, nil, fmt.Errorf("登录失败,未获取到有效的认证信息")
|
||||
}
|
||||
return cookies, nil, nil
|
||||
}
|
||||
|
||||
// xzmyTicketResult v1/tickets 成功响应
|
||||
type xzmyTicketResult struct {
|
||||
tgt string
|
||||
ticket string
|
||||
}
|
||||
|
||||
// parseXzmyTicket 解析 {"tgt":"...","ticket":"..."}
|
||||
func parseXzmyTicket(body string) xzmyTicketResult {
|
||||
return xzmyTicketResult{
|
||||
tgt: jsonStrField(body, "tgt"),
|
||||
ticket: jsonStrField(body, "ticket"),
|
||||
}
|
||||
}
|
||||
|
||||
// xzmyLoginError 解析登录失败的 meta.message / data.code,返回可读错误(无则空串)
|
||||
func xzmyLoginError(body string) string {
|
||||
if code := jsonStrField(body, "code"); code != "" {
|
||||
switch code {
|
||||
case "PASSERROR", "PWDERROR", "PASSWORDERROR":
|
||||
return "用户名或密码不匹配,请检查后重试"
|
||||
case "NOAUTH", "USERNOTFOUND", "NOUSER":
|
||||
return "账号不存在或未注册统一身份认证"
|
||||
case "CODEFALSE":
|
||||
return "验证码错误"
|
||||
}
|
||||
return code
|
||||
}
|
||||
if msg := jsonStrField(body, "message"); msg != "" && msg != "ok" {
|
||||
return msg
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// jsonStrField 从(可能嵌套的)JSON 文本中提取指定 key 的字符串值(简化实现,够用即止)
|
||||
func jsonStrField(body, key string) string {
|
||||
needle := "\"" + key + "\":\""
|
||||
i := strings.Index(body, needle)
|
||||
if i < 0 {
|
||||
return ""
|
||||
}
|
||||
i += len(needle)
|
||||
j := strings.Index(body[i:], "\"")
|
||||
if j < 0 {
|
||||
return ""
|
||||
}
|
||||
return body[i : i+j]
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"math/big"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestXzmyEncryptPassword 西藏民族大学密码加密:
|
||||
// 教科书式 RSA(无填充)+ 小端序零填充 + 小写 hex,与站点前端库一致。
|
||||
func TestXzmyEncryptPassword(t *testing.T) {
|
||||
got, err := xzmyEncryptPassword("zzynb666")
|
||||
if err != nil {
|
||||
t.Fatalf("加密失败: %v", err)
|
||||
}
|
||||
// 金标准:由同一算法对 "zzynb666" 计算得到(该校 RSA 无填充,结果确定)
|
||||
const golden = "1605e4173d74759db8ed176c1ba5c2e7a1fed2e1e9fb081977e1debb659868c6287c563b8baa74274339618bae9806defd96b3c4e779ac09f5e26ce03d593057998e212e271dacf547e5c53fded7d912113f8cbb52b8fc1f7ecbfda4ba0fd30d2f812ba4f667c29a1d8082169b5c9261babdeb56f7a255d1a27968e99a66083d"
|
||||
if got != golden {
|
||||
t.Fatalf("密文与预期不符\n got=%s\nwant=%s", got, golden)
|
||||
}
|
||||
// 复原:密文按公钥长度应为 chunkSize(=modulus 字节数) 的 hex(无前导零时位数可少)
|
||||
modBytes, _ := hex.DecodeString(xzmyRsaModulusHex)
|
||||
n := new(big.Int).SetBytes(modBytes)
|
||||
if len(got) == 0 || len(got) > 2*((n.BitLen()+7)/8) {
|
||||
t.Fatalf("密文长度异常: %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestXzmyTicketParse 票据解析
|
||||
func TestXzmyTicketParse(t *testing.T) {
|
||||
body := `{"tgt":"TGT-1-abc","ticket":"ST-1-xyz"}`
|
||||
r := parseXzmyTicket(body)
|
||||
if r.tgt != "TGT-1-abc" || r.ticket != "ST-1-xyz" {
|
||||
t.Fatalf("解析错误: %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
// TestXzmyLoginError 登录失败业务码翻译
|
||||
func TestXzmyLoginError(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`{"meta":{"success":true,"statusCode":200,"message":"ok"},"data":{"code":"PASSERROR","data":"5,1","userId":"1"}}`: "用户名或密码不匹配,请检查后重试",
|
||||
`{"meta":{"success":true,"statusCode":200,"message":"ok"},"data":{"code":"NOAUTH"}}`: "账号不存在或未注册统一身份认证",
|
||||
`{"meta":{"success":true,"statusCode":200,"message":"ok"},"data":{"code":"CODEFALSE"}}`: "验证码错误",
|
||||
}
|
||||
for body, want := range cases {
|
||||
if got := xzmyLoginError(body); got != want {
|
||||
t.Fatalf("xzmyLoginError(%s) = %q, want %q", body, got, want)
|
||||
}
|
||||
}
|
||||
// 成功响应应返回空串(不误判为错误)
|
||||
if got := xzmyLoginError(`{"tgt":"T","ticket":"ST"}`); got != "" {
|
||||
t.Fatalf("成功响应不应报错, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func fetchFromWecloud(wecloudUrl string, cookieMap map[string]string) (*CpdailyU
|
||||
MobilePhone string `json:"mobilePhone"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析 wecloud 用户信息失败: %w", err)
|
||||
}
|
||||
if result.ErrCode != 0 || result.Data == nil {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// qrUuidPattern 匹配二维码内容中的 uuid 参数(如 ...?uuid=1583a6...&isNeedExtra=0)
|
||||
var qrUuidPattern = regexp.MustCompile(`uuid=([0-9a-zA-Z_-]+)`)
|
||||
|
||||
// bareUuidPattern 匹配纯 uuid(32 位十六进制字符串,如 1583a66272854585833eb13b56fc1937)
|
||||
var bareUuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{32}$`)
|
||||
|
||||
// bareTokenPattern 匹配"整串即 uuid 的裸值",用于存库后回读的场景。
|
||||
// 链接里的 uuid 允许 [0-9a-zA-Z_-]+(见 qrUuidPattern),并非都是 32 位 hex,
|
||||
// 因此仅靠 bareUuidPattern 无法反解非 hex 的 uuid,会导致签到失败。
|
||||
// 长度限制 8~64 且不含空白/URL 符号,避免把普通文本误判为 uuid。
|
||||
var bareTokenPattern = regexp.MustCompile(`^[0-9a-zA-Z_-]{8,64}$`)
|
||||
|
||||
// ExtractQrUuid 从二维码文本内容中提取签到二维码 uuid。
|
||||
// 支持三种形式:完整链接(取 uuid= 参数值)、32 位 hex 裸 uuid、其它形式的裸 uuid token。
|
||||
//
|
||||
// 二维码图片的识别在前端完成(jsQR),后端只接收解析后的 uuid 文本,故此处不涉及图片解码。
|
||||
func ExtractQrUuid(text string) string {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
if m := qrUuidPattern.FindStringSubmatch(text); len(m) == 2 {
|
||||
return m[1]
|
||||
}
|
||||
if bareUuidPattern.MatchString(text) {
|
||||
return strings.ToLower(text)
|
||||
}
|
||||
if bareTokenPattern.MatchString(text) {
|
||||
return text
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testQrUuid = "1583a66272854585833eb13b56fc1937"
|
||||
|
||||
func TestExtractQrUuid(t *testing.T) {
|
||||
cases := []struct{ in, want string }{
|
||||
{"https://ynu.campusphere.net/wec-counselor-sign-apps/stu/qrsign/index.html?uuid=1583a66272854585833eb13b56fc1937&isNeedExtra=0&schoolId=1018615911902606", "1583a66272854585833eb13b56fc1937"},
|
||||
{"1583a66272854585833eb13b56fc1937", "1583a66272854585833eb13b56fc1937"},
|
||||
{" xxxxx?uuid=abc123XYZ&y=1 ", "abc123XYZ"},
|
||||
{"no uuid here", ""},
|
||||
{"", ""},
|
||||
// 裸 uuid 回读(formData 只存 uuid 后的解析路径)
|
||||
{"abc123XYZ", "abc123XYZ"}, // 非 32-hex 的裸 uuid
|
||||
{"1583a66272854585833eb13b56fc1937", "1583a66272854585833eb13b56fc1937"}, // 32-hex
|
||||
{"uuid_with-dash", "uuid_with-dash"}, // 含 _ 和 -
|
||||
{"ab", ""}, // 太短,不认为是 uuid
|
||||
{"has space x", ""}, // 含空白,不认为是 uuid
|
||||
{"https://x.edu.cn/a/b", ""}, // URL 含符号,不走裸 token 分支
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := ExtractQrUuid(c.in); got != c.want {
|
||||
t.Errorf("ExtractQrUuid(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,44 @@ import (
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// ========== 登录态失效的统一识别 ==========
|
||||
|
||||
// ErrCookieExpired 表示今日校园的登录态(cookie)已失效:
|
||||
// 请求被重定向到统一身份认证登录页,返回 HTML 而非接口 JSON。
|
||||
// handler 层据此触发 cookie 续期(raw_password 重登 或 长期凭证换取),
|
||||
// 续期失败则引导用户重新登录,而不是把「解析失败」这种模糊错误抛给用户。
|
||||
var ErrCookieExpired = fmt.Errorf("cpdaily_cookie_expired")
|
||||
|
||||
// looksLikeHTML 判断响应体是否为一个 HTML 页面(而非接口 JSON)。
|
||||
// 登录态失效时,今日校园会把请求 302 到 authserver 登录页,响应体是 HTML。
|
||||
func looksLikeHTML(body []byte) bool {
|
||||
head := body
|
||||
if len(head) > 512 {
|
||||
head = head[:512]
|
||||
}
|
||||
trimmed := strings.TrimSpace(string(head))
|
||||
if trimmed == "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(trimmed, "<") {
|
||||
return true
|
||||
}
|
||||
lower := strings.ToLower(trimmed)
|
||||
return strings.Contains(lower, "<!doctype html") ||
|
||||
strings.Contains(lower, "<html")
|
||||
}
|
||||
|
||||
// unmarshalBody 解析接口 JSON 响应体。
|
||||
// 若响应体是 HTML(登录态失效被重定向到认证页),返回 ErrCookieExpired,
|
||||
// 以便上层触发 cookie 续期或引导重新登录,而不是抛出难以理解的
|
||||
// "invalid character '<' looking for beginning of value"。
|
||||
func unmarshalBody(body []byte, v interface{}) error {
|
||||
if looksLikeHTML(body) {
|
||||
return ErrCookieExpired
|
||||
}
|
||||
return json.Unmarshal(body, v)
|
||||
}
|
||||
|
||||
// ========== HTTP 客户端 ==========
|
||||
|
||||
var httpClient *resty.Client
|
||||
@@ -157,22 +195,53 @@ func hasUsableLoginUrl(school *SchoolDetailInfo) bool {
|
||||
}
|
||||
|
||||
// CpdailyLogin 执行 cpdaily 登录
|
||||
// 返回登录成功后的所有 cookies
|
||||
func CpdailyLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, error) {
|
||||
// 返回登录成功后的所有 cookies;若触发多因子认证(MFA),返回 (nil, mfaCtx, ErrMFARequired),
|
||||
// 调用方应暂存 mfaCtx 并引导用户完成验证码校验(CompleteMFALogin)。
|
||||
func CpdailyLogin(ctx context.Context, school *SchoolDetailInfo, username, password string) ([]*http.Cookie, *MFAContext, error) {
|
||||
// 南昌理工学院:自研 CAS→IAP 混合认证,与通用 IAP/CAS 流程均不兼容,单独适配
|
||||
if school.ID == NutSchoolId {
|
||||
return nutCasIapLogin(ctx, school, username, password)
|
||||
cookies, err := nutCasIapLogin(ctx, school, username, password)
|
||||
return cookies, nil, err
|
||||
}
|
||||
// 合肥师范学院:学校统一身份认证 SSO 会拒绝单点登录跳转("系统拒绝单点登录跳转"),
|
||||
// 但其 wecloud 网关(hfnu.campusphere.net)支持标准 IAP 账密登录,单独走 IAP
|
||||
if school.ID == HfnuSchoolId {
|
||||
cookies, err := iapLogin(ctx, school, username, password)
|
||||
return cookies, nil, err
|
||||
}
|
||||
// 许昌学院:平台配置 joinType=CLOUD(IsIap=true),但 IAP 账密登录实际不兼容;
|
||||
// 学校真实链路为 CAS 账密 + MFA + /iap/loginSuccess 回调,单独强制走 CAS(详见 login_xcu.go)
|
||||
if school.ID == XcuSchoolId {
|
||||
return xcuCasLogin(ctx, school, username, password)
|
||||
}
|
||||
// 辽宁工程技术大学:平台配置 joinType=CLOUD(IsIap=true),但网关 /iap/doLogin 不存在(405),
|
||||
// IAP 提交报 FAIL_UPNOTMATCH 误导为"密码错误";实际链路为 /iap 302 → 学校 CAS(authserver.lntu.edu.cn)
|
||||
// → 回调 /iap/loginSuccess 建立网关会话,同 xcu 模式单独强制走 CAS(详见 login_lntu.go)
|
||||
if school.ID == LntuSchoolId {
|
||||
return lntuCasLogin(ctx, school, username, password)
|
||||
}
|
||||
// 西藏民族大学:平台配置 joinType=CLOUD(IsIap=true),但网关 IAP 账密不可用,
|
||||
// IAP 提交报 FAIL_UPNOTMATCH("密码错误");实际为定制 CAS(cas.xzmu.edu.cn/lyuapServer,
|
||||
// 密码=教科书RSA小端hex,POST /v1/tickets),单独适配(详见 login_xzmy.go)
|
||||
if school.ID == XzmySchoolId {
|
||||
return xzmyCasLogin(ctx, school, username, password)
|
||||
}
|
||||
// 华侨大学:写死强制走通用 CAS 流程——CAS 账密登录需 wisedu 定制滑块验证码
|
||||
//(casLogin 内按 sliderIds 配置分流,见 slider.go),IAP 账密接口不兼容(FAIL_UPNOTMATCH)
|
||||
if school.ID == HquSchoolId {
|
||||
return casLogin(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 nil, nil, fmt.Errorf("该校登录配置不完整(缺少登录地址),暂不支持自动登录,请稍后重试或提交待适配反馈")
|
||||
}
|
||||
return iapLogin(ctx, school, username, password)
|
||||
cookies, err := iapLogin(ctx, school, username, password)
|
||||
return cookies, nil, err
|
||||
}
|
||||
if !hasUsableLoginUrl(school) {
|
||||
slog.Warn("CAS学校缺少登录地址", "school", school.Name, "schoolId", school.ID)
|
||||
return nil, fmt.Errorf("该校暂未开放自动登录(待适配),请稍后重试或提交待适配反馈")
|
||||
return nil, nil, fmt.Errorf("该校暂未开放自动登录(待适配),请稍后重试或提交待适配反馈")
|
||||
}
|
||||
return casLogin(ctx, school, username, password)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/config"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// HquSchoolId 华侨大学 tenant id(CAS 登录需 wisedu 滑块验证码,IAP 账密接口不兼容)
|
||||
const HquSchoolId = "hqdx"
|
||||
|
||||
// isSliderCaptchaSchool 判断学校是否为滑块验证码学校(wisedu 定制 CAS 滑块)。
|
||||
// 学校列表来自配置 [cpdaily] sliderIds(与老版一致:1018764144934965/sdhyxy/hqdx)。
|
||||
func isSliderCaptchaSchool(schoolID string) bool {
|
||||
for _, id := range config.Global.Cpdaily.SliderIds {
|
||||
if id == schoolID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ========== 滑块验证码识别(通用方案) ==========
|
||||
//
|
||||
// 与图片验证码 OCR(captchaOCR)对等的通用识别入口:sliderGapOCR。
|
||||
// 打码平台 /slider 接口(与 /classifier 等共用同一个 X-Api-Key):
|
||||
//
|
||||
// POST {captchaBaseUrl}/slider JSON: {"big_image": "<b64>", "small_image": "<b64>"}
|
||||
// 响应: {"code":200,"msg":"success","data":152}
|
||||
// data = 滑块需横向移动的像素距离(wisedu 口径,与服务端 verifySliderCaptcha 期望值同尺度)
|
||||
|
||||
// sliderGapOCR 识别滑块缺口横向位置(通用入口)。
|
||||
// bigImageB64/smallImageB64 为背景大图与滑块小图的 base64(不带 data: 前缀)。
|
||||
// 返回滑块需横向移动的像素距离。
|
||||
func sliderGapOCR(bigImageB64, smallImageB64 string) (int, error) {
|
||||
cfg := config.Global.Cpdaily
|
||||
resp, err := resty.New().
|
||||
SetTimeout(15*time.Second).
|
||||
R().
|
||||
SetHeader("X-Api-Key", cfg.CaptchaApiKey).
|
||||
SetHeader("Content-Type", "application/json").
|
||||
SetBody(map[string]string{
|
||||
"big_image": bigImageB64,
|
||||
"small_image": smallImageB64,
|
||||
}).
|
||||
Post(strings.TrimSuffix(cfg.CaptchaBaseUrl, "/") + "/slider")
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("滑块识别请求失败: %w", err)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Code int `json:"code"`
|
||||
Data int `json:"data"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
bodyStr := resp.String()
|
||||
if err := json.Unmarshal([]byte(bodyStr), &result); err != nil {
|
||||
return 0, fmt.Errorf("滑块识别响应解析失败: %w, body: %s", err, bodyStr)
|
||||
}
|
||||
if result.Code != 200 {
|
||||
return 0, fmt.Errorf("滑块识别失败: code=%d msg=%s", result.Code, result.Msg)
|
||||
}
|
||||
if result.Data <= 0 {
|
||||
return 0, fmt.Errorf("滑块识别结果无效: %d", result.Data)
|
||||
}
|
||||
return result.Data, nil
|
||||
}
|
||||
|
||||
// ========== wisedu CAS 滑块验证码(如华侨大学 id.hqu.edu.cn) ==========
|
||||
//
|
||||
// 前端协议(longbow sliderCaptcha v2.0 + encrypt.js,2026-02 逆向并实测调通):
|
||||
//
|
||||
// 1. GET {cas}/common/openSliderCaptcha.htl
|
||||
// → {"bigImage":"<b64>","smallImage":"<b64>","tagWidth":..,"yHeight":..}
|
||||
// 2. safeSecure = window.atob(smallImage) 末 16 字节(latin1→UTF-8 字符串,trim 后作 AES key)
|
||||
// 3. 拖动结束后 POST {cas}/common/verifySliderCaptcha.htl,表单仅一个字段 sign:
|
||||
// sign = encryptPassword(JSON.stringify({canvasLength,moveLength,tracks}), safeSecure)
|
||||
// encryptPassword(data,key) = AES-128-CBC-PKCS7(key=Utf8(key.trim()),
|
||||
// iv=randomString(16),明文=randomString(64)+data),输出标准 base64
|
||||
// 4. 响应 {"errorCode":1,"errorMsg":"success"} = 通过;{"errorCode":0} = 失败
|
||||
//
|
||||
// 服务端校验特性(实测修正,推翻此前「无容差 + ±12 扫描」结论):
|
||||
// - open 后存在约 1.3~1.7s 的激活延迟:延迟内提交任何值(含真值)都返回失败;
|
||||
// - 激活后服务端接受以真值为中心的宽区间(实测上缘 +8、下缘 -6~-8,相对打码值),
|
||||
// 打码平台返回值即为区间中心附近(误差 0±1),故等待激活后提交打码值本身即可通过;
|
||||
// - 失败不消费图片,可在同一张图上反复提交;仅验证成功才作废该图;
|
||||
// - 早期观察到的「打码偏差 -8~+9」为快速扫描跨过激活窗口的落点伪影(非真实识别误差)。
|
||||
|
||||
// wiseduSliderVerifyWidth 前端滑块容器宽度(canvasLength 固定上报值)
|
||||
const wiseduSliderVerifyWidth = 280
|
||||
|
||||
// wiseduAesChars encrypt.js 随机字符集(用于 64 位随机前缀与 16 位随机 IV)
|
||||
const wiseduAesChars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
|
||||
|
||||
// wiseduSliderMaxRounds 换图重试上限(每张图内先提交窄候选序列)
|
||||
const wiseduSliderMaxRounds = 5
|
||||
|
||||
// wiseduSliderActivateWait 服务端激活延迟等待时长:从 openSliderCaptcha 响应完成起算。
|
||||
// 实测激活点约在 open 后 1.3~1.7s(期间提交任何值都被拒),2.5s 留足抖动裕度。
|
||||
// 测试可替换为零。
|
||||
var wiseduSliderActivateWait = 2500 * time.Millisecond
|
||||
|
||||
// wiseduSliderSubmitGap 同图候选值之间的提交间隔,进一步吸收激活窗口抖动。
|
||||
// 测试可替换为零。
|
||||
var wiseduSliderSubmitGap = 350 * time.Millisecond
|
||||
|
||||
// wiseduSliderCandidates 同图候选值偏移序列:以打码值本身为中心(贴合接受区间中心),
|
||||
// ±1 仅作识别误差/激活抖动的兜底(激活后接受 ±8 宽区间,通常首个候选即命中)。
|
||||
var wiseduSliderCandidates = []int{0, 1, -1}
|
||||
|
||||
// wiseduSliderRetryDelay 换图重试等待时长(测试可替换为零延迟)
|
||||
var wiseduSliderRetryDelay = func(round int) time.Duration {
|
||||
return time.Duration(500+round*300) * time.Millisecond
|
||||
}
|
||||
|
||||
// wiseduSliderTrack 前端 tracks 元素(a=横向位移、b=纵向偏移、c=累计时间ms)
|
||||
type wiseduSliderTrack struct {
|
||||
A int `json:"a"`
|
||||
B int `json:"b"`
|
||||
C int `json:"c"`
|
||||
}
|
||||
|
||||
// wiseduSliderTrackPayload verifySliderCaptcha 加密前的 JSON 载荷
|
||||
type wiseduSliderTrackPayload struct {
|
||||
CanvasLength int `json:"canvasLength"`
|
||||
MoveLength int `json:"moveLength"`
|
||||
Tracks []wiseduSliderTrack `json:"tracks"`
|
||||
}
|
||||
|
||||
// resolveWiseduSliderCaptcha 完成 wisedu CAS 滑块验证(自动换图重试)。
|
||||
// casBase 为 CAS 根路径(如 https://id.hqu.edu.cn/authserver);
|
||||
// referer 为当前登录页 URL(模拟浏览器请求头);
|
||||
// client 须与登录页共用同一会话(cookie jar)。
|
||||
func resolveWiseduSliderCaptcha(ctx context.Context, casBase, referer string, client *resty.Client) error {
|
||||
return resolveWiseduSliderCaptchaFn(ctx, casBase, referer, client, sliderGapOCR)
|
||||
}
|
||||
|
||||
// resolveWiseduSliderCaptchaFn 允许注入缺口识别函数(测试用)
|
||||
func resolveWiseduSliderCaptchaFn(ctx context.Context, casBase, referer string, client *resty.Client,
|
||||
gapFn func(bigImageB64, smallImageB64 string) (int, error)) error {
|
||||
base := strings.TrimSuffix(casBase, "/")
|
||||
var lastErr error
|
||||
for round := 0; round < wiseduSliderMaxRounds; round++ {
|
||||
if round > 0 {
|
||||
time.Sleep(wiseduSliderRetryDelay(round))
|
||||
}
|
||||
lastErr = wiseduSliderOnce(ctx, base, referer, client, gapFn, round)
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
slog.Info("wisedu滑块本轮失败,换图重试", "round", round+1, "err", lastErr.Error())
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
// wiseduSliderOnce 单轮滑块验证:取图 → 打码 → 等激活窗口 → 提交窄候选序列(v、v+1、v-1)
|
||||
func wiseduSliderOnce(ctx context.Context, base, referer string, client *resty.Client,
|
||||
gapFn func(string, string) (int, error), round int) error {
|
||||
// 1. 获取滑块图片(同会话换图)
|
||||
resp, err := client.R().SetContext(ctx).
|
||||
SetHeader("X-Requested-With", "XMLHttpRequest").
|
||||
SetHeader("Referer", referer).
|
||||
Get(base + "/common/openSliderCaptcha.htl")
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取滑块图片失败: %w", err)
|
||||
}
|
||||
openedAt := time.Now()
|
||||
var slider struct {
|
||||
BigImage string `json:"bigImage"`
|
||||
SmallImage string `json:"smallImage"`
|
||||
}
|
||||
body := readBody(resp)
|
||||
if err := json.Unmarshal(body, &slider); err != nil || slider.BigImage == "" || slider.SmallImage == "" {
|
||||
return fmt.Errorf("解析滑块图片响应失败: %v, body: %s", err, string(body[:min(len(body), 200)]))
|
||||
}
|
||||
|
||||
// 2. safeSecure(小图末 16 字节)与打码识别
|
||||
safeSecure, err := sliderSafeSecure(slider.SmallImage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gapX, err := gapFn(slider.BigImage, slider.SmallImage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. 等待服务端激活窗口:激活前提交任何值(含真值)都会被拒
|
||||
if wait := wiseduSliderActivateWait - time.Since(openedAt); wait > 0 {
|
||||
slog.Info("wisedu滑块等待激活窗口", "round", round+1, "wait", wait.String())
|
||||
time.Sleep(wait)
|
||||
}
|
||||
|
||||
// 4. 提交窄候选序列:打码值本身(接受区间中心),v±1 兜底激活抖动/识别误差
|
||||
for i, off := range wiseduSliderCandidates {
|
||||
if i > 0 && wiseduSliderSubmitGap > 0 {
|
||||
time.Sleep(wiseduSliderSubmitGap)
|
||||
}
|
||||
moveLength := gapX + off
|
||||
if moveLength <= 0 {
|
||||
continue
|
||||
}
|
||||
payload, err := json.Marshal(wiseduSliderTrackPayload{
|
||||
CanvasLength: wiseduSliderVerifyWidth,
|
||||
MoveLength: moveLength,
|
||||
Tracks: wiseduSliderTracks(moveLength),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sign, err := encryptSliderSign(string(payload), safeSecure)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
vResp, err := client.R().SetContext(ctx).
|
||||
SetHeader("X-Requested-With", "XMLHttpRequest").
|
||||
SetHeader("Referer", referer).
|
||||
SetFormData(map[string]string{"sign": sign}).
|
||||
Post(base + "/common/verifySliderCaptcha.htl")
|
||||
if err != nil {
|
||||
return fmt.Errorf("提交滑块校验失败: %w", err)
|
||||
}
|
||||
var vResult struct {
|
||||
ErrorCode int `json:"errorCode"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
}
|
||||
vBody := readBody(vResp)
|
||||
_ = json.Unmarshal(vBody, &vResult)
|
||||
slog.Info("wisedu滑块校验", "round", round+1, "gapX", gapX, "offset", off,
|
||||
"moveLength", moveLength, "errorCode", vResult.ErrorCode)
|
||||
if vResult.ErrorCode == 1 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("本张图候选值全部未通过(打码值 %d)", gapX)
|
||||
}
|
||||
|
||||
// sliderSafeSecure 取小图 base64 解码后的末 16 字节作为 safeSecure。
|
||||
// 前端 ids-sliderCaptcha.js 中 safeSecure.value 由 atob(smallImage) 的末 16 个
|
||||
// charCode 逐字节拼成;encrypt.js 使用时先 trim 再作 AES key(Utf8 编码)。
|
||||
func sliderSafeSecure(smallImageB64 string) (string, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(smallImageB64)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("小图 base64 解码失败: %w", err)
|
||||
}
|
||||
if len(raw) < 16 {
|
||||
return "", fmt.Errorf("小图数据不足 16 字节: %d", len(raw))
|
||||
}
|
||||
var sb strings.Builder
|
||||
for _, c := range raw[len(raw)-16:] {
|
||||
sb.WriteRune(rune(c))
|
||||
}
|
||||
// 复刻 JS 正则 /(^\s+)|(\s+$)/g 的 trim(字节码点 ≤255,空白字符集有限)
|
||||
return strings.Trim(sb.String(), "\t\n\v\f\r \u00a0"), nil
|
||||
}
|
||||
|
||||
// encryptSliderSign 复刻 encrypt.js encryptPassword(data, key):
|
||||
// AES-128-CBC-PKCS7,key=Utf8(key.trim()),iv=randomString(16),
|
||||
// 明文=randomString(64)+data,输出标准 base64(仅密文,IV 不外传,与 CryptoJS 一致)。
|
||||
//
|
||||
// IV 随机且不随请求发送是安全的:CBC 解密时 IV 只影响第一块(16 字节)明文,
|
||||
// 而首块落在 64 位随机前缀内部;服务端剥离前缀后从固定偏移解析 JSON,不受影响
|
||||
// (已用真实 CryptoJS 输出 + openssl/node 解密交叉验证)。
|
||||
func encryptSliderSign(data, safeSecure string) (string, error) {
|
||||
key := []byte(safeSecure)
|
||||
switch len(key) {
|
||||
case 16, 24, 32:
|
||||
default:
|
||||
return "", fmt.Errorf("safeSecure 长度非法(%d 字节,须为 16/24/32)", len(key))
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
padded := pkcs7Pad([]byte(randomAesChars(64)+data), block.BlockSize())
|
||||
iv := []byte(randomAesChars(aes.BlockSize))
|
||||
ciphertext := make([]byte, len(padded))
|
||||
cipher.NewCBCEncrypter(block, iv).CryptBlocks(ciphertext, padded)
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
// wiseduSliderTracks 生成拟人化拖动轨迹,模拟 longbow.js 采集的 {a,b,c} 采样点:
|
||||
// 首个点为 {0,0,0},随后按比例推进并带轻微抖动,最后一点精确对齐 moveLength
|
||||
// (对应前端 mouseup 时的最终位移)。
|
||||
func wiseduSliderTracks(move int) []wiseduSliderTrack {
|
||||
steps := 8 + randSmallN(5) // 8~12 个中间采样点
|
||||
tracks := make([]wiseduSliderTrack, 0, steps+2)
|
||||
tracks = append(tracks, wiseduSliderTrack{A: 0, B: 0, C: 0})
|
||||
a, c := 0, 0
|
||||
for i := 1; i <= steps; i++ {
|
||||
target := move * i / steps
|
||||
if target <= a {
|
||||
target = a + 1
|
||||
}
|
||||
if target > move {
|
||||
target = move
|
||||
}
|
||||
a = target + randSmallN(3) - 1 // ±1 抖动
|
||||
if a > move {
|
||||
a = move
|
||||
}
|
||||
if a < 0 {
|
||||
a = 0
|
||||
}
|
||||
c += 20 + randSmallN(45)
|
||||
tracks = append(tracks, wiseduSliderTrack{A: a, B: randSmallN(3) - 1, C: c})
|
||||
}
|
||||
c += 30 + randSmallN(40)
|
||||
tracks = append(tracks, wiseduSliderTrack{A: move, B: 0, C: c})
|
||||
return tracks
|
||||
}
|
||||
|
||||
// randomAesChars 生成 n 个 wiseduAesChars 字符集的随机字符(对应 encrypt.js randomString)
|
||||
func randomAesChars(n int) string {
|
||||
buf := make([]byte, n)
|
||||
_, _ = rand.Read(buf)
|
||||
for i, c := range buf {
|
||||
buf[i] = wiseduAesChars[int(c)%len(wiseduAesChars)]
|
||||
}
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
// randSmallN 返回 [0,n) 的伪随机数(仅用于轨迹/时间的拟人化抖动,无安全要求)
|
||||
func randSmallN(n int) int {
|
||||
if n <= 0 {
|
||||
return 0
|
||||
}
|
||||
b := make([]byte, 1)
|
||||
_, _ = rand.Read(b)
|
||||
return int(b[0]) % n
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/config"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// ========== isSliderCaptchaSchool ==========
|
||||
|
||||
func TestIsSliderCaptchaSchool(t *testing.T) {
|
||||
old := config.Global.Cpdaily.SliderIds
|
||||
defer func() { config.Global.Cpdaily.SliderIds = old }()
|
||||
config.Global.Cpdaily.SliderIds = []string{"1018764144934965", "sdhyxy", "hqdx"}
|
||||
|
||||
for _, id := range []string{"hqdx", "sdhyxy", "1018764144934965"} {
|
||||
if !isSliderCaptchaSchool(id) {
|
||||
t.Errorf("%s 应为滑块学校", id)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{"xcu", "nut", "hfnu", ""} {
|
||||
if isSliderCaptchaSchool(id) {
|
||||
t.Errorf("%s 不应为滑块学校", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== safeSecure / sign 加密(encrypt.js 协议) ==========
|
||||
|
||||
// mockSliderSafe 模拟小图末 16 字节(hqu 实测为 ASCII 串)
|
||||
const mockSliderSafe = "Ta1PFklnamXPYqZX"
|
||||
|
||||
// mockSmallImageB64 构造以 mockSliderSafe 结尾的 base64 小图
|
||||
func mockSmallImageB64() string {
|
||||
raw := append([]byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x01}, []byte(mockSliderSafe)...)
|
||||
return base64.StdEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func TestSliderSafeSecure(t *testing.T) {
|
||||
got, err := sliderSafeSecure(mockSmallImageB64())
|
||||
if err != nil {
|
||||
t.Fatalf("sliderSafeSecure: %v", err)
|
||||
}
|
||||
if got != mockSliderSafe {
|
||||
t.Fatalf("safeSecure=%q, want %q", got, mockSliderSafe)
|
||||
}
|
||||
|
||||
// 首尾空白应被 trim(复刻 encrypt.js 的 key.replace 正则)
|
||||
trimmed := base64.StdEncoding.EncodeToString([]byte("\tTa1PFklnamXPYqZ\n"))
|
||||
if got, err := sliderSafeSecure(trimmed); err != nil || got != "Ta1PFklnamXPYqZ" {
|
||||
t.Fatalf("trim 后 safeSecure=%q err=%v", got, err)
|
||||
}
|
||||
|
||||
// 不足 16 字节应报错
|
||||
short := base64.StdEncoding.EncodeToString([]byte("short"))
|
||||
if _, err := sliderSafeSecure(short); err == nil {
|
||||
t.Fatal("小图不足 16 字节应报错")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptSliderSign(t *testing.T) {
|
||||
const key = "0123456789abcdef"
|
||||
plain := `{"canvasLength":280,"moveLength":99,"tracks":[{"a":0,"b":0,"c":0}]}`
|
||||
|
||||
sign, err := encryptSliderSign(plain, key)
|
||||
if err != nil {
|
||||
t.Fatalf("encryptSliderSign: %v", err)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(sign)
|
||||
if err != nil || len(raw)%aes.BlockSize != 0 {
|
||||
t.Fatalf("sign base64/长度异常: err=%v len=%d", err, len(raw))
|
||||
}
|
||||
|
||||
// 用零 IV 解密(IV 只影响首块 16 字节,落于前缀内,不影响前缀后半段与载荷)
|
||||
block, _ := aes.NewCipher([]byte(key))
|
||||
pt := make([]byte, len(raw))
|
||||
cipher.NewCBCDecrypter(block, make([]byte, aes.BlockSize)).CryptBlocks(pt, raw)
|
||||
pt = pkcs7Unpad(pt)
|
||||
|
||||
if len(pt) != 64+len(plain) {
|
||||
t.Fatalf("解密明文长度=%d, want %d", len(pt), 64+len(plain))
|
||||
}
|
||||
if string(pt[64:]) != plain {
|
||||
t.Fatalf("解密明文=%q, want %q", string(pt[64:]), plain)
|
||||
}
|
||||
// 首块因 IV 未知为乱码,第 16~63 字节应为合法前缀字符(48 个)
|
||||
for _, c := range string(pt[16:64]) {
|
||||
if !strings.ContainsRune(wiseduAesChars, c) {
|
||||
t.Fatalf("随机前缀包含非法字符 %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 真实 CryptoJS(/tmp/hqu_encrypt.js encryptPassword)产出的 sign 夹具:
|
||||
// key=Ta1PFklnamXPYqZX,明文载荷为 canvasLength=280/moveLength=65/2 个 tracks 采样点。
|
||||
// 用于锁定与前端 CryptoJS 的互通性(前缀长度、填充、base64、载荷可解析)。
|
||||
const realCryptoJSSignFixture = "+vjAgkLevuKAVqM/x6dCJJwlR5xLcrJ0yW6tqTmeu8MXCCBJvY4rttiA4ouUBHYdCP2zjYzbGgKDyTvTQdmvPnOV6DlSiQvCIhtaQcBksVFjYsMi2i7hCaKu3sfA9SszYZVs/8AvSqPPcvr+MlvarV7fSPaJdtPpbI1lYSU30MiFHBTl5V8cZMdlA+Zj290xoQlg3niG2V3f0sLzEQ4Wrg=="
|
||||
|
||||
func TestDecryptRealCryptoJSFixture(t *testing.T) {
|
||||
pt, err := decryptMockSign(realCryptoJSSignFixture)
|
||||
if err != nil {
|
||||
t.Fatalf("解密真实 CryptoJS sign 失败: %v", err)
|
||||
}
|
||||
p := mockDecryptSign(t, realCryptoJSSignFixture)
|
||||
if p.CanvasLength != 280 || p.MoveLength != 65 {
|
||||
t.Fatalf("载荷字段错误: %+v", p)
|
||||
}
|
||||
if len(p.Tracks) != 2 || p.Tracks[1].A != 65 {
|
||||
t.Fatalf("tracks 错误: %+v", p.Tracks)
|
||||
}
|
||||
// 第 16~63 字节为合法前缀字符(48 个)
|
||||
for _, c := range string(pt[16:64]) {
|
||||
if !strings.ContainsRune(wiseduAesChars, c) {
|
||||
t.Fatalf("随机前缀包含非法字符 %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWiseduSliderTracks(t *testing.T) {
|
||||
tracks := wiseduSliderTracks(65)
|
||||
if len(tracks) < 2 {
|
||||
t.Fatalf("tracks 采样点过少: %d", len(tracks))
|
||||
}
|
||||
if first := tracks[0]; first.A != 0 || first.B != 0 || first.C != 0 {
|
||||
t.Fatalf("首个采样点应为 {0,0,0}: %+v", first)
|
||||
}
|
||||
if last := tracks[len(tracks)-1]; last.A != 65 {
|
||||
t.Fatalf("末点 a=%d, want 65(对齐 moveLength)", last.A)
|
||||
}
|
||||
prevC := 0
|
||||
for i, p := range tracks {
|
||||
if p.C < prevC {
|
||||
t.Fatalf("第 %d 点时间回退: %+v", i, p)
|
||||
}
|
||||
if p.A < 0 || p.A > 65 {
|
||||
t.Fatalf("第 %d 点位移越界: %+v", i, p)
|
||||
}
|
||||
prevC = p.C
|
||||
}
|
||||
}
|
||||
|
||||
// ========== wisedu CAS 滑块流程(httptest mock,sign 协议) ==========
|
||||
|
||||
// disableSliderDelays 将换图重试延迟、激活等待与候选间隔全部置零(加速测试)
|
||||
func disableSliderDelays(t *testing.T) {
|
||||
t.Helper()
|
||||
oldDelay := wiseduSliderRetryDelay
|
||||
oldWait := wiseduSliderActivateWait
|
||||
oldGap := wiseduSliderSubmitGap
|
||||
wiseduSliderRetryDelay = func(int) time.Duration { return 0 }
|
||||
wiseduSliderActivateWait = 0
|
||||
wiseduSliderSubmitGap = 0
|
||||
t.Cleanup(func() {
|
||||
wiseduSliderRetryDelay = oldDelay
|
||||
wiseduSliderActivateWait = oldWait
|
||||
wiseduSliderSubmitGap = oldGap
|
||||
})
|
||||
}
|
||||
|
||||
// mockDecryptSign 用 mockSliderSafe 解密并解析 sign 载荷(模拟服务端行为)。
|
||||
// 加密端 IV 随机且不外传:CBC 中 IV 只影响解密后第一块(16 字节),而该 16 字节
|
||||
// 落在 64 位随机前缀内部,服务端剥掉前缀后解析 JSON 不受任何影响,故此处 IV 取
|
||||
// 零向量即可,解密结果第 16 字节起与前端一致(已用真实 CryptoJS 输出交叉验证)。
|
||||
func mockDecryptSign(t *testing.T, sign string) wiseduSliderTrackPayload {
|
||||
t.Helper()
|
||||
pt, err := decryptMockSign(sign)
|
||||
if err != nil {
|
||||
t.Fatalf("解密 sign 失败: %v", err)
|
||||
}
|
||||
var p wiseduSliderTrackPayload
|
||||
if err := json.Unmarshal(pt[64:], &p); err != nil {
|
||||
t.Fatalf("解密载荷 JSON 解析失败: %v, prefix64=%q body=%s", err, string(pt[:64]), string(pt[64:]))
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// decryptMockSign 用 mockSliderSafe 解密 sign(零 IV),返回去除 PKCS7 填充后的明文
|
||||
func decryptMockSign(sign string) ([]byte, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(sign)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw) < 32 || len(raw)%aes.BlockSize != 0 {
|
||||
return nil, fmt.Errorf("sign 长度异常: %d", len(raw))
|
||||
}
|
||||
block, err := aes.NewCipher([]byte(mockSliderSafe))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pt := make([]byte, len(raw))
|
||||
cipher.NewCBCDecrypter(block, make([]byte, aes.BlockSize)).CryptBlocks(pt, raw)
|
||||
pt = pkcs7Unpad(pt)
|
||||
if len(pt) < 64 {
|
||||
return nil, fmt.Errorf("解密后明文过短: %d", len(pt))
|
||||
}
|
||||
return pt, nil
|
||||
}
|
||||
|
||||
// mockSliderServer 起一个 wisedu CAS 滑块 mock:
|
||||
// verify 接受 accept 集合中的 moveLength(errorCode=1),其余一律 errorCode=0
|
||||
func mockSliderServer(t *testing.T, accept map[int]bool, wantGapX int,
|
||||
openCalls, verifyCalls *int) *httptest.Server {
|
||||
t.Helper()
|
||||
small := mockSmallImageB64()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/authserver/common/openSliderCaptcha.htl", func(w http.ResponseWriter, r *http.Request) {
|
||||
*openCalls++
|
||||
if r.Header.Get("X-Requested-With") != "XMLHttpRequest" {
|
||||
t.Errorf("open 缺少 X-Requested-With 头")
|
||||
}
|
||||
if r.Header.Get("Referer") == "" {
|
||||
t.Errorf("open 缺少 Referer 头")
|
||||
}
|
||||
writeJSON(w, map[string]string{"bigImage": "ZmFrZWJpZw==", "smallImage": small})
|
||||
})
|
||||
mux.HandleFunc("/authserver/common/verifySliderCaptcha.htl", func(w http.ResponseWriter, r *http.Request) {
|
||||
*verifyCalls++
|
||||
if r.Header.Get("X-Requested-With") != "XMLHttpRequest" {
|
||||
t.Errorf("verify 缺少 X-Requested-With 头")
|
||||
}
|
||||
_ = r.ParseForm()
|
||||
p := mockDecryptSign(t, r.PostFormValue("sign"))
|
||||
if p.CanvasLength != 280 {
|
||||
t.Errorf("canvasLength=%d, want 280", p.CanvasLength)
|
||||
}
|
||||
if len(p.Tracks) < 2 {
|
||||
t.Errorf("tracks 采样点过少: %d", len(p.Tracks))
|
||||
}
|
||||
if last := p.Tracks[len(p.Tracks)-1]; last.A != p.MoveLength {
|
||||
t.Errorf("tracks 末点 a=%d 应等于 moveLength=%d", last.A, p.MoveLength)
|
||||
}
|
||||
if accept[p.MoveLength] {
|
||||
writeJSON(w, map[string]int{"errorCode": 1})
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]int{"errorCode": 0})
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
t.Cleanup(ts.Close)
|
||||
return ts
|
||||
}
|
||||
|
||||
// 打码值直接命中:1 次 open + 1 次 verify
|
||||
func TestResolveWiseduSliderCaptchaMock(t *testing.T) {
|
||||
disableSliderDelays(t)
|
||||
var openCalls, verifyCalls int
|
||||
ts := mockSliderServer(t, map[int]bool{65: true}, 65, &openCalls, &verifyCalls)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := resolveWiseduSliderCaptchaFn(ctx, ts.URL+"/authserver", ts.URL+"/login", newTestRestyClient(),
|
||||
func(string, string) (int, error) { return 65, nil })
|
||||
if err != nil {
|
||||
t.Fatalf("滑块流程失败: %v", err)
|
||||
}
|
||||
if openCalls != 1 || verifyCalls != 1 {
|
||||
t.Fatalf("open=%d verify=%d, want 1/1", openCalls, verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 打码值略偏(真值=打码值+1):同一张图第 2 个候选即命中,不应换图
|
||||
func TestResolveWiseduSliderCaptchaCandidateHit(t *testing.T) {
|
||||
disableSliderDelays(t)
|
||||
var openCalls, verifyCalls int
|
||||
ts := mockSliderServer(t, map[int]bool{66: true}, 65, &openCalls, &verifyCalls)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := resolveWiseduSliderCaptchaFn(ctx, ts.URL+"/authserver", ts.URL+"/login", newTestRestyClient(),
|
||||
func(string, string) (int, error) { return 65, nil })
|
||||
if err != nil {
|
||||
t.Fatalf("滑块流程失败: %v", err)
|
||||
}
|
||||
// 失败不换图(±1 由同图候选覆盖),成功即止
|
||||
if openCalls != 1 {
|
||||
t.Fatalf("open=%d, want 1(同图候选不应换图)", openCalls)
|
||||
}
|
||||
if verifyCalls != 2 {
|
||||
t.Fatalf("verify=%d, want 2(65 失败后 66 命中)", verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 真值=打码值-1:第 3 个候选(65,66,64 中 64)命中
|
||||
func TestResolveWiseduSliderCaptchaCandidateHitBelow(t *testing.T) {
|
||||
disableSliderDelays(t)
|
||||
var openCalls, verifyCalls int
|
||||
ts := mockSliderServer(t, map[int]bool{64: true}, 65, &openCalls, &verifyCalls)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := resolveWiseduSliderCaptchaFn(ctx, ts.URL+"/authserver", ts.URL+"/login", newTestRestyClient(),
|
||||
func(string, string) (int, error) { return 65, nil })
|
||||
if err != nil {
|
||||
t.Fatalf("滑块流程失败: %v", err)
|
||||
}
|
||||
if openCalls != 1 || verifyCalls != 3 {
|
||||
t.Fatalf("open=%d verify=%d, want 1/3(65,66 失败后 64 命中)", openCalls, verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 5 张图全失败:每图 3 个候选值(0,+1,-1),共 15 次 verify 后报错
|
||||
func TestResolveWiseduSliderCaptchaExhausted(t *testing.T) {
|
||||
disableSliderDelays(t)
|
||||
var openCalls, verifyCalls int
|
||||
ts := mockSliderServer(t, map[int]bool{}, 65, &openCalls, &verifyCalls)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
err := resolveWiseduSliderCaptchaFn(ctx, ts.URL+"/authserver", ts.URL+"/login", newTestRestyClient(),
|
||||
func(string, string) (int, error) { return 65, nil })
|
||||
if err == nil {
|
||||
t.Fatal("持续失败应返回错误")
|
||||
}
|
||||
if openCalls != 5 {
|
||||
t.Fatalf("open=%d, want 5", openCalls)
|
||||
}
|
||||
if verifyCalls != 3*5 {
|
||||
t.Fatalf("verify=%d, want %d", verifyCalls, 3*5)
|
||||
}
|
||||
}
|
||||
|
||||
// 取图失败(非 JSON 响应)应报错并换图重试
|
||||
func TestResolveWiseduSliderCaptchaBadResponse(t *testing.T) {
|
||||
disableSliderDelays(t)
|
||||
var openCalls, verifyCalls int
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/authserver/common/openSliderCaptcha.htl", func(w http.ResponseWriter, r *http.Request) {
|
||||
openCalls++
|
||||
_, _ = w.Write([]byte("<html>error</html>"))
|
||||
})
|
||||
mux.HandleFunc("/authserver/common/verifySliderCaptcha.htl", func(w http.ResponseWriter, r *http.Request) {
|
||||
verifyCalls++
|
||||
t.Error("取图失败时不应调用 verify")
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
if err := resolveWiseduSliderCaptchaFn(ctx, ts.URL+"/authserver", ts.URL+"/login", newTestRestyClient(),
|
||||
func(string, string) (int, error) { return 65, nil }); err == nil {
|
||||
t.Fatal("应返回错误")
|
||||
}
|
||||
if openCalls != 5 {
|
||||
t.Fatalf("open=%d, want 5", openCalls)
|
||||
}
|
||||
if verifyCalls != 0 {
|
||||
t.Fatalf("verify=%d, want 0", verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 服务端激活延迟:mock 在 open 后 300ms 内拒绝一切值(复刻实测 1.3~1.7s 激活窗口),
|
||||
// 等待逻辑(此处缩短为 400ms)应保证首个候选即命中:open=1、verify=1。
|
||||
// 若等待缺失,首个候选会落在拒绝窗口内而多提交一轮,verify 数与 open 数都会变化。
|
||||
func TestResolveWiseduSliderCaptchaActivationWait(t *testing.T) {
|
||||
oldWait := wiseduSliderActivateWait
|
||||
oldGap := wiseduSliderSubmitGap
|
||||
oldDelay := wiseduSliderRetryDelay
|
||||
wiseduSliderActivateWait = 400 * time.Millisecond
|
||||
wiseduSliderSubmitGap = 0
|
||||
wiseduSliderRetryDelay = func(int) time.Duration { return 0 }
|
||||
t.Cleanup(func() {
|
||||
wiseduSliderActivateWait = oldWait
|
||||
wiseduSliderSubmitGap = oldGap
|
||||
wiseduSliderRetryDelay = oldDelay
|
||||
})
|
||||
|
||||
const rejectWithin = 300 * time.Millisecond
|
||||
var openCalls, verifyCalls int
|
||||
var openAt time.Time
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/authserver/common/openSliderCaptcha.htl", func(w http.ResponseWriter, r *http.Request) {
|
||||
openCalls++
|
||||
openAt = time.Now()
|
||||
writeJSON(w, map[string]string{"bigImage": "ZmFrZWJpZw==", "smallImage": mockSmallImageB64()})
|
||||
})
|
||||
mux.HandleFunc("/authserver/common/verifySliderCaptcha.htl", func(w http.ResponseWriter, r *http.Request) {
|
||||
verifyCalls++
|
||||
_ = r.ParseForm()
|
||||
p := mockDecryptSign(t, r.PostFormValue("sign"))
|
||||
if time.Since(openAt) >= rejectWithin && p.MoveLength == 65 {
|
||||
writeJSON(w, map[string]int{"errorCode": 1})
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]int{"errorCode": 0})
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := resolveWiseduSliderCaptchaFn(ctx, ts.URL+"/authserver", ts.URL+"/login", newTestRestyClient(),
|
||||
func(string, string) (int, error) { return 65, nil })
|
||||
if err != nil {
|
||||
t.Fatalf("滑块流程失败: %v", err)
|
||||
}
|
||||
if openCalls != 1 || verifyCalls != 1 {
|
||||
t.Fatalf("open=%d verify=%d, want 1/1(激活等待后首个候选应命中)", openCalls, verifyCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// ========== parseLoginForm 表单选择(#pwdLoginDiv 优先级) ==========
|
||||
|
||||
// 模拟华侨大学登录页:3 个 form(fido/动态码/账密),账密字段位于 #pwdLoginDiv
|
||||
func TestParseLoginFormPwdLoginDiv(t *testing.T) {
|
||||
inputs := parseLoginForm([]byte(hquLoginPageHTML), "2523132014", "testpwd123")
|
||||
|
||||
if inputs["cllt"] != "userNameLogin" {
|
||||
t.Fatalf("应选中 #pwdLoginDiv 账密表单, cllt=%s", inputs["cllt"])
|
||||
}
|
||||
if inputs["username"] != "2523132014" {
|
||||
t.Fatalf("username 错误: %s", inputs["username"])
|
||||
}
|
||||
if inputs["execution"] != "e1s1" {
|
||||
t.Fatalf("execution 错误: %s", inputs["execution"])
|
||||
}
|
||||
// 密码应被 AES 加密(含 pwdEncryptSalt)
|
||||
if inputs["password"] == "" || inputs["password"] == "testpwd123" {
|
||||
t.Fatalf("password 应被加密: %q", inputs["password"])
|
||||
}
|
||||
// userPassword(明文框)应被删除
|
||||
if _, ok := inputs["userPassword"]; ok {
|
||||
t.Fatal("userPassword 字段应被删除")
|
||||
}
|
||||
// captcha 留空(滑块通过后提交)
|
||||
if v, ok := inputs["captcha"]; !ok || v != "" {
|
||||
t.Fatalf("captcha 应保留空值: %q %v", v, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 辅助 ==========
|
||||
|
||||
func writeJSON(w http.ResponseWriter, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func newTestRestyClient() *resty.Client {
|
||||
// 与 sessionClient 保持一致:DoNotParseResponse 模式(readBody 依赖 RawBody)
|
||||
jar, _ := cookiejar.New(nil)
|
||||
return resty.New().
|
||||
SetTimeout(5*time.Second).
|
||||
SetDoNotParseResponse(true).
|
||||
SetCookieJar(jar).
|
||||
SetHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)")
|
||||
}
|
||||
|
||||
// 模拟华侨大学登录页 HTML(账密字段位于 #pwdLoginDiv,含 pwdEncryptSalt)
|
||||
const hquLoginPageHTML = `<!DOCTYPE html>
|
||||
<html><body>
|
||||
<form method="post" id="loginFromId_fido" class="loginFromClass_fido" action="/authserver/login">
|
||||
<input type="hidden" name="_eventId" value="submit"/>
|
||||
<input type="text" name="username" value=""/>
|
||||
<input type="hidden" name="responseJson" value=""/>
|
||||
<input type="hidden" id="cllt" name="cllt" value="userNameLoginFido"/>
|
||||
<input type="hidden" name="dllt" value="generalLogin"/>
|
||||
<input type="hidden" id="lt" name="lt" value=""/>
|
||||
<input type="hidden" name="execution" value="e1s1"/>
|
||||
</form>
|
||||
<form method="post" id="loginFromId" class="loginFromClass" action="/authserver/login">
|
||||
<input type="text" name="username" value=""/>
|
||||
<input type="text" id="captcha" name="captcha" placeholder="请输入验证码"/>
|
||||
<input type="text" name="dynamicCode" value=""/>
|
||||
<input type="hidden" name="_eventId" value="submit"/>
|
||||
<input type="hidden" id="lt" name="lt" value=""/>
|
||||
<input type="hidden" id="cllt" name="cllt" value="dynamicLogin"/>
|
||||
<input type="hidden" name="dllt" value="generalLogin"/>
|
||||
<input type="hidden" name="execution" value="e1s1"/>
|
||||
</form>
|
||||
<form method="post" id="loginFromId" class="loginFromClass" action="/authserver/login">
|
||||
<div id="pwdLoginDiv">
|
||||
<input type="text" name="username" value=""/>
|
||||
<input type="password" name="userPassword" value=""/>
|
||||
<input type="hidden" name="password" value=""/>
|
||||
<input type="text" id="captcha" name="captcha" placeholder="请输入验证码"/>
|
||||
<input type="hidden" name="_eventId" value="submit"/>
|
||||
<input type="hidden" id="lt" name="lt" value=""/>
|
||||
<input type="hidden" id="cllt" name="cllt" value="userNameLogin"/>
|
||||
<input type="hidden" name="dllt" value="generalLogin"/>
|
||||
<input type="hidden" name="execution" value="e1s1"/>
|
||||
</div>
|
||||
</form>
|
||||
<input type="hidden" id="pwdEncryptSalt" value="sQJL9rnqFD65soWK"/>
|
||||
</body></html>`
|
||||
@@ -0,0 +1,352 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
// ========== 手机号验证码登录(无需选择学校) ==========
|
||||
//
|
||||
// 与 CAS 登录的差别:直接调用今日校园移动端鉴权接口,登录成功后响应里就带有
|
||||
// tenantId(学校租户)与 openId(学工号),因此**无需用户先选择学校**。
|
||||
//
|
||||
// 流程(对标旧项目 likedream-go login/sms.go):
|
||||
// 1. SendSmsCode(phone) → 今日校园下发短信验证码
|
||||
// 2. MobileLoginByCode(phone, code) → 返回 tenantId/openId/sessionToken/tgc(CASTGC)
|
||||
// 3. ExchangeCasCookie(loginData) → 用 sessionToken 换取学校 CAS cookie(含 MOD_AUTH_CAS)
|
||||
//
|
||||
// 该 cookie(含 CASTGC,长期有效)后续可反复换取 CAS cookie,即「长期凭证」。
|
||||
// 加密方式与项目既有 crypto.go 一致(AES-128-CBC / DES-CBC,PKCS7)。
|
||||
|
||||
const (
|
||||
smsSendURL = "https://mobile.campushoy.com/app/auth/authentication/mobile/messageCode/v-8222"
|
||||
smsLoginURL = "https://mobile.campushoy.com/app/auth/authentication/mobileLogin/v-8222"
|
||||
encryptVerion = "first_v4"
|
||||
)
|
||||
|
||||
// SmsSendResult 发送短信验证码结果
|
||||
type SmsSendResult struct {
|
||||
Countdown int `json:"countdown"` // 可再次发送的倒计时(秒)
|
||||
TipMsg string `json:"tipMsg"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
// SmsLoginResult 手机号验证码登录结果(mobileLogin 响应解密后)
|
||||
type SmsLoginResult struct {
|
||||
AuthID string `json:"authId"`
|
||||
AuthStatus string `json:"authStatus"`
|
||||
CompleteUserInfoStatus string `json:"completeUserInfoStatus"`
|
||||
DeviceExceptionMsg string `json:"deviceExceptionMsg"`
|
||||
DeviceStatus string `json:"deviceStatus"`
|
||||
FirstLogin bool `json:"firstLogin"`
|
||||
Mobile string `json:"mobile"`
|
||||
MsgTip string `json:"msgTip"`
|
||||
Name string `json:"name"`
|
||||
OpenID string `json:"openId"` // 学工号
|
||||
PersonID string `json:"personId"`
|
||||
SessionToken string `json:"sessionToken"`
|
||||
Status string `json:"status"`
|
||||
TenantID string `json:"tenantId"` // 学校租户 ID(= sys_user.school_id)
|
||||
TenantName string `json:"tenantName"`
|
||||
Tgc string `json:"tgc"` // CASTGC(长期凭证)
|
||||
TgcStatus string `json:"tgcStatus"`
|
||||
UserID string `json:"userId"` // 今日校园内部用户 ID(非学工号)
|
||||
UserType string `json:"userType"`
|
||||
}
|
||||
|
||||
// smsCommonResponse 今日校园短信接口通用响应
|
||||
type smsCommonResponse[T any] struct {
|
||||
ErrCode int `json:"errCode"`
|
||||
ErrMsg string `json:"errMsg"`
|
||||
Data T `json:"data"`
|
||||
}
|
||||
|
||||
func newSmsClient() *resty.Client {
|
||||
c := resty.New().
|
||||
SetTimeout(20*time.Second).
|
||||
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
|
||||
// resty 默认 http.Client 无 CookieJar,需显式设置,否则 Set-Cookie 不会被保存
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c.SetCookieJar(jar)
|
||||
return c
|
||||
}
|
||||
|
||||
// setSmsHeaders 设置短信接口所需的公共请求头(deviceId 可空)
|
||||
func setSmsHeaders(req *resty.Request, deviceID, sessionToken string) {
|
||||
if sessionToken != "" {
|
||||
enc := base64.StdEncoding.EncodeToString(DesEncryptForCat([]byte(sessionToken)))
|
||||
req.SetHeader("SessionToken", enc)
|
||||
req.SetHeader("sessionTokenKey", enc)
|
||||
}
|
||||
|
||||
cpdailyInfo := map[string]interface{}{
|
||||
"deviceId": deviceID,
|
||||
"systemName": "android",
|
||||
"userId": "",
|
||||
"appVersion": "9.8.8",
|
||||
"model": "Unknown",
|
||||
"lon": "0",
|
||||
"lat": "0",
|
||||
"cpdailyVersion": "9.8.8",
|
||||
"systemVersion": "11",
|
||||
}
|
||||
infoBytes, _ := json.Marshal(cpdailyInfo)
|
||||
encodedInfo := base64.StdEncoding.EncodeToString(DesEncryptForCat(infoBytes))
|
||||
|
||||
req.SetHeaders(map[string]string{
|
||||
"clientType": "cpdaily_student",
|
||||
"deviceType": "1",
|
||||
"CpdailyClientType": "CPDAILY",
|
||||
"CpdailyStandAlone": "0",
|
||||
"User-Agent": "Mozilla/5.0 (Linux; Android 11; Redmi Note 8 Pro Build/RP1A.230805.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36 cpdaily/9.8.8 wisedu/9.8.8",
|
||||
"CpdailyInfo": encodedInfo,
|
||||
})
|
||||
}
|
||||
|
||||
// CreateDeviceID 生成一个今日校园设备码(用于短信登录,避免设备异常校验)
|
||||
func CreateDeviceID() string {
|
||||
s := fmt.Sprintf("%x", time.Now().UnixNano())
|
||||
if len(s) < 32 {
|
||||
s = s + strings.Repeat("0", 32-len(s))
|
||||
}
|
||||
return s[0:8] + "-" + s[8:12] + "-" + s[12:16] + "-" + s[16:20]
|
||||
}
|
||||
|
||||
// SendSmsCode 发送手机短信验证码
|
||||
func SendSmsCode(ctx context.Context, phone string) (*SmsSendResult, error) {
|
||||
phoneEncrypted := base64.StdEncoding.EncodeToString(AesEncrypt([]byte(phone)))
|
||||
|
||||
client := newSmsClient()
|
||||
req := client.R().
|
||||
SetContext(ctx).
|
||||
SetBody(map[string]string{
|
||||
"a": phoneEncrypted,
|
||||
"b": encryptVerion,
|
||||
})
|
||||
setSmsHeaders(req, "", "")
|
||||
|
||||
resp, err := req.Post(smsSendURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("发送验证码请求失败: %w", err)
|
||||
}
|
||||
body := resp.Body()
|
||||
|
||||
var result smsCommonResponse[SmsSendResult]
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析发送验证码响应失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
return nil, fmt.Errorf("%s", result.ErrMsg)
|
||||
}
|
||||
return &result.Data, nil
|
||||
}
|
||||
|
||||
// MobileLoginByCode 手机号 + 短信验证码登录,返回 tenantId/openId/sessionToken/tgc 等
|
||||
func MobileLoginByCode(ctx context.Context, phone, code string) (*SmsLoginResult, error) {
|
||||
payload := map[string]any{
|
||||
"d": code,
|
||||
"e": "CPDAILY",
|
||||
"c": phone,
|
||||
"f": "86",
|
||||
}
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
encodedPayload := base64.StdEncoding.EncodeToString(AesEncrypt(payloadBytes))
|
||||
|
||||
client := newSmsClient()
|
||||
req := client.R().
|
||||
SetContext(ctx).
|
||||
SetBody(map[string]any{
|
||||
"a": encodedPayload,
|
||||
"b": encryptVerion,
|
||||
})
|
||||
setSmsHeaders(req, "", "")
|
||||
|
||||
resp, err := req.Post(smsLoginURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("登录请求失败: %w", err)
|
||||
}
|
||||
body := resp.Body()
|
||||
|
||||
var result smsCommonResponse[string]
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析登录响应失败: %w (body: %.200s)", err, string(body))
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
return nil, fmt.Errorf("%s", result.ErrMsg)
|
||||
}
|
||||
|
||||
// data 为 base64(AES(json))
|
||||
decoded, err := base64.StdEncoding.DecodeString(result.Data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("登录数据 base64 解码失败: %w", err)
|
||||
}
|
||||
plain := AesDecrypt(decoded)
|
||||
|
||||
var loginData SmsLoginResult
|
||||
if err := json.Unmarshal(plain, &loginData); err != nil {
|
||||
return nil, fmt.Errorf("登录数据解析失败: %w (raw: %.200s)", err, string(plain))
|
||||
}
|
||||
if loginData.TenantID == "" {
|
||||
return nil, fmt.Errorf("登录响应缺少 tenantId")
|
||||
}
|
||||
return &loginData, nil
|
||||
}
|
||||
|
||||
// ExchangeCasCookie 用短信登录得到的 sessionToken 换取学校 CAS cookie(含 MOD_AUTH_CAS)。
|
||||
// 返回可直接序列化保存的 cookie 列表;其中 CASTGC(loginData.Tgc)为长期凭证。
|
||||
func ExchangeCasCookie(ctx context.Context, school *SchoolDetailInfo, loginData *SmsLoginResult, deviceID string) ([]*http.Cookie, error) {
|
||||
if school.WecloudUrl == "" {
|
||||
return nil, fmt.Errorf("学校无可用域名")
|
||||
}
|
||||
host := strings.TrimSuffix(school.WecloudUrl, "/")
|
||||
|
||||
// AmpCookies 头:DES 加密后的 {AMP1,AMP2:[{name:sessionToken,value:...}]}
|
||||
ampCookieMap := map[string]any{
|
||||
"AMP2": []map[string]any{
|
||||
{"path": "/", "value": loginData.SessionToken, "domain": "", "name": "sessionToken"},
|
||||
},
|
||||
"AMP1": []map[string]any{
|
||||
{"path": "/", "value": loginData.SessionToken, "domain": "", "name": "sessionToken"},
|
||||
},
|
||||
}
|
||||
ampBytes, _ := json.Marshal(ampCookieMap)
|
||||
ampToken := base64.StdEncoding.EncodeToString(DesEncryptForCat(ampBytes))
|
||||
|
||||
client := newSmsClient()
|
||||
// 不复制 Cookie 头,交由 resty 默认 cookie jar 管理(避免重定向时旧 cookie 覆盖新 cookie)
|
||||
client.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 50 {
|
||||
return fmt.Errorf("重定向次数过多")
|
||||
}
|
||||
for key, val := range via[0].Header {
|
||||
if !strings.EqualFold(key, "Cookie") {
|
||||
req.Header[key] = val
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
|
||||
// 预置基础 cookie(clientType/tenantId/standAlone/sessionToken;CASTGC 为长期凭证)
|
||||
presetCookies := map[string]string{
|
||||
"clientType": "cpdaily_student",
|
||||
"tenantId": school.ID,
|
||||
"standAlone": "0",
|
||||
"sessionToken": loginData.SessionToken,
|
||||
}
|
||||
if loginData.Tgc != "" {
|
||||
presetCookies["CASTGC"] = loginData.Tgc
|
||||
}
|
||||
targetSchoolURL, err := url.Parse(host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析学校地址失败: %w", err)
|
||||
}
|
||||
targetAPIURL, _ := url.Parse("https://api.campushoy.com")
|
||||
for name, value := range presetCookies {
|
||||
c := &http.Cookie{Name: name, Value: value}
|
||||
if jar := client.GetClient().Jar; jar != nil {
|
||||
jar.SetCookies(targetSchoolURL, []*http.Cookie{c})
|
||||
if targetAPIURL != nil {
|
||||
jar.SetCookies(targetAPIURL, []*http.Cookie{c})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
req := client.R().
|
||||
SetContext(ctx).
|
||||
SetHeader("AmpCookies", ampToken)
|
||||
setSmsHeaders(req, deviceID, loginData.SessionToken)
|
||||
|
||||
resp, err := req.Get(host + "/wec-im-group/group/imUserToken/getImUserToken")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("换取 CAS cookie 请求失败: %w", err)
|
||||
}
|
||||
|
||||
var common smsCommonResponse[json.RawMessage]
|
||||
if err := json.Unmarshal(resp.Body(), &common); err != nil {
|
||||
return nil, fmt.Errorf("解析换取 cookie 响应失败: %w (body: %.200s)", err, string(resp.Body()))
|
||||
}
|
||||
if common.ErrCode != 0 {
|
||||
return nil, fmt.Errorf("换取 CAS cookie 失败: %s", common.ErrMsg)
|
||||
}
|
||||
|
||||
// 从 jar 收集所有 cookie
|
||||
var cookies []*http.Cookie
|
||||
seen := map[string]bool{}
|
||||
hosts := []string{host, "https://api.campushoy.com"}
|
||||
for _, h := range hosts {
|
||||
u, err := url.Parse(h)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, c := range client.GetClient().Jar.Cookies(u) {
|
||||
if c.Name == "" || seen[c.Name] {
|
||||
continue
|
||||
}
|
||||
seen[c.Name] = true
|
||||
cookies = append(cookies, c)
|
||||
}
|
||||
}
|
||||
if len(cookies) == 0 {
|
||||
return nil, fmt.Errorf("未获取到有效 cookie")
|
||||
}
|
||||
return cookies, nil
|
||||
}
|
||||
|
||||
// RefreshCasCookie 用已保存的长期 cookie(含 CASTGC/sessionToken)重新换取 CAS cookie。
|
||||
// 适用于 cookie 过期时自动续期,避免要求用户重新登录。
|
||||
func RefreshCasCookie(ctx context.Context, cookieMap map[string]string, host string, deviceID string) ([]*http.Cookie, error) {
|
||||
sessionToken := cookieMap["sessionToken"]
|
||||
if sessionToken == "" {
|
||||
return nil, fmt.Errorf("缺少 sessionToken,无法续期")
|
||||
}
|
||||
|
||||
client := newSmsClient()
|
||||
|
||||
ampCookieMap := map[string]any{
|
||||
"AMP2": []map[string]any{
|
||||
{"path": "/", "value": sessionToken, "domain": "", "name": "sessionToken"},
|
||||
},
|
||||
"AMP1": []map[string]any{
|
||||
{"path": "/", "value": sessionToken, "domain": "", "name": "sessionToken"},
|
||||
},
|
||||
}
|
||||
ampBytes, _ := json.Marshal(ampCookieMap)
|
||||
ampToken := base64.StdEncoding.EncodeToString(DesEncryptForCat(ampBytes))
|
||||
|
||||
req := client.R().
|
||||
SetContext(ctx).
|
||||
SetHeader("AmpCookies", ampToken)
|
||||
setSmsHeaders(req, deviceID, sessionToken)
|
||||
|
||||
resp, err := req.Get(strings.TrimSuffix(host, "/") + "/wec-im-group/group/imUserToken/getImUserToken")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("续期请求失败: %w", err)
|
||||
}
|
||||
var common smsCommonResponse[json.RawMessage]
|
||||
if err := json.Unmarshal(resp.Body(), &common); err != nil {
|
||||
return nil, fmt.Errorf("解析续期响应失败: %w", err)
|
||||
}
|
||||
if common.ErrCode != 0 {
|
||||
return nil, fmt.Errorf("续期失败: %s", common.ErrMsg)
|
||||
}
|
||||
|
||||
var cookies []*http.Cookie
|
||||
u, err := url.Parse(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range client.GetClient().Jar.Cookies(u) {
|
||||
cookies = append(cookies, c)
|
||||
}
|
||||
return cookies, nil
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -98,7 +97,7 @@ func (r *submitCaptchaResolver) GetValidationInfo() (*ValidationInfo, error) {
|
||||
body, _ := io.ReadAll(resp.RawBody())
|
||||
|
||||
var apiResp apiResponse
|
||||
if err := json.Unmarshal(body, &apiResp); err != nil {
|
||||
if err := unmarshalBody(body, &apiResp); err != nil {
|
||||
return nil, fmt.Errorf("解析验证信息响应失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -141,25 +140,22 @@ func (r *submitCaptchaResolver) GetCaptchaTicket(info *ValidationInfo) (string,
|
||||
return ticket, nil
|
||||
}
|
||||
|
||||
// createCaptcha 创建验证码(JSON body)
|
||||
// createCaptcha 创建验证码(必须用 multipart,JSON body 会返回空壳响应导致验证码识别为空)
|
||||
func (r *submitCaptchaResolver) createCaptcha(info *ValidationInfo) (*CpSubmitCaptcha, error) {
|
||||
baseURL := strings.TrimSuffix(r.host, "/")
|
||||
url := baseURL + "/captcha-open-api/v1/captcha/create/scenesImage"
|
||||
|
||||
client := newTaskClient()
|
||||
|
||||
reqData := map[string]string{
|
||||
"accountKey": info.AccountKey,
|
||||
"sceneCode": info.SceneCode,
|
||||
"tenantId": info.TenantId,
|
||||
"userId": info.UserId,
|
||||
}
|
||||
|
||||
resp, err := client.R().
|
||||
SetHeader("Cookie", r.cookieStr).
|
||||
SetHeader("deviceId", r.deviceId).
|
||||
SetHeader("Content-Type", "application/json; charset=UTF-8").
|
||||
SetBody(reqData).
|
||||
SetMultipartFormData(map[string]string{
|
||||
"accountKey": info.AccountKey,
|
||||
"sceneCode": info.SceneCode,
|
||||
"tenantId": info.TenantId,
|
||||
"userId": info.UserId,
|
||||
}).
|
||||
Post(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建验证码请求失败: %w", err)
|
||||
@@ -169,7 +165,7 @@ func (r *submitCaptchaResolver) createCaptcha(info *ValidationInfo) (*CpSubmitCa
|
||||
body, _ := io.ReadAll(resp.RawBody())
|
||||
|
||||
var apiResp apiResponse
|
||||
if err := json.Unmarshal(body, &apiResp); err != nil {
|
||||
if err := unmarshalBody(body, &apiResp); err != nil {
|
||||
return nil, fmt.Errorf("解析创建验证码响应失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -229,12 +225,11 @@ func (r *submitCaptchaResolver) getResultFromItStar(rawResponse json.RawMessage)
|
||||
return itResp.Data, nil
|
||||
}
|
||||
|
||||
// submitCaptcha 提交验证码结果(application/x-www-form-urlencoded)
|
||||
// submitCaptcha 提交验证码结果(multipart,与旧版一致)
|
||||
func (r *submitCaptchaResolver) submitCaptcha(info *ValidationInfo, captchaInfo *CpSubmitCaptcha, codes []string) (string, error) {
|
||||
baseURL := strings.TrimSuffix(r.host, "/")
|
||||
targetURL := baseURL + "/captcha-open-api/v1/captcha/validate/scenesImage"
|
||||
|
||||
// 构建 URL-encoded 表单数据
|
||||
if captchaInfo.Code == "" {
|
||||
return "", fmt.Errorf("创建验证码返回的场景码为空")
|
||||
}
|
||||
@@ -242,23 +237,22 @@ func (r *submitCaptchaResolver) submitCaptcha(info *ValidationInfo, captchaInfo
|
||||
return "", fmt.Errorf("验证码识别结果为空,不提交空验证码")
|
||||
}
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("accountKey", info.AccountKey)
|
||||
form.Set("sceneCode", info.SceneCode)
|
||||
form.Set("tenantId", info.TenantId)
|
||||
form.Set("userId", info.UserId)
|
||||
form.Set("scenesImageCode", captchaInfo.Code)
|
||||
for _, code := range codes {
|
||||
form.Add("scenesImageCodes", code)
|
||||
}
|
||||
|
||||
client := newTaskClient()
|
||||
resp, err := client.R().
|
||||
req := client.R().
|
||||
SetHeader("Cookie", r.cookieStr).
|
||||
SetHeader("deviceId", r.deviceId).
|
||||
SetHeader("Content-Type", "application/x-www-form-urlencoded").
|
||||
SetBody(form.Encode()).
|
||||
Post(targetURL)
|
||||
SetMultipartFormData(map[string]string{
|
||||
"accountKey": info.AccountKey,
|
||||
"sceneCode": info.SceneCode,
|
||||
"tenantId": info.TenantId,
|
||||
"userId": info.UserId,
|
||||
"scenesImageCode": captchaInfo.Code,
|
||||
})
|
||||
for _, code := range codes {
|
||||
req = req.SetMultipartField("scenesImageCodes", "", "", strings.NewReader(code))
|
||||
}
|
||||
|
||||
resp, err := req.Post(targetURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("提交验证码请求失败: %w", err)
|
||||
}
|
||||
@@ -267,7 +261,7 @@ func (r *submitCaptchaResolver) submitCaptcha(info *ValidationInfo, captchaInfo
|
||||
body, _ := io.ReadAll(resp.RawBody())
|
||||
|
||||
var apiResp apiResponse
|
||||
if err := json.Unmarshal(body, &apiResp); err != nil {
|
||||
if err := unmarshalBody(body, &apiResp); err != nil {
|
||||
return "", fmt.Errorf("解析提交验证码响应失败: %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,9 @@ type TaskType string
|
||||
const (
|
||||
TaskTypeSign TaskType = "sign"
|
||||
TaskTypeSleepCheck TaskType = "sleep_check"
|
||||
TaskTypeLeave TaskType = "leave" // 销假(请假销假)图片上传使用
|
||||
// TaskTypeReturnRegister 节假日离返校的返校登记(确认到达)
|
||||
TaskTypeReturnRegister TaskType = "return_register"
|
||||
)
|
||||
|
||||
// 各任务类型的 API 基础路径
|
||||
@@ -160,7 +163,7 @@ func fetchTasksByEndpoint(cookieMap map[string]string, host string, taskType Tas
|
||||
ErrMsg string `json:"errMsg"`
|
||||
Datas map[string]interface{} `json:"datas"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析任务列表响应失败: %w", err)
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
@@ -240,8 +243,11 @@ func parseTasksFromDatas(datas map[string]interface{}) []TodayTaskInfo {
|
||||
return tasks
|
||||
}
|
||||
|
||||
// FetchAllRecentTasks 并发查询 sign + sleep_check 两种任务类型,聚合去重后返回
|
||||
func FetchAllRecentTasks(cookieMap map[string]string, host string) []TodayTaskInfo {
|
||||
// FetchAllRecentTasks 并发查询 sign + sleep_check 两种签到类任务;
|
||||
// 若启用返校登记(GetReturnRegisterTasks 提供),额外聚合其待办。去重后返回。
|
||||
// 若签到/查寝两类查询都失败则返回错误(供上层识别登录态失效并续期重试);
|
||||
// 只要有一类成功就返回结果(另一类失败仅记录日志)。
|
||||
func FetchAllRecentTasks(cookieMap map[string]string, host string) ([]TodayTaskInfo, error) {
|
||||
type result struct {
|
||||
tasks []TodayTaskInfo
|
||||
err error
|
||||
@@ -266,9 +272,18 @@ func FetchAllRecentTasks(cookieMap map[string]string, host string) []TodayTaskIn
|
||||
|
||||
seen := map[string]bool{}
|
||||
var all []TodayTaskInfo
|
||||
var firstErr error
|
||||
successCount := 0
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
r := <-ch
|
||||
if r.err != nil {
|
||||
if firstErr == nil {
|
||||
firstErr = r.err
|
||||
}
|
||||
} else {
|
||||
successCount++
|
||||
}
|
||||
for _, t := range r.tasks {
|
||||
key := t.TaskName + "|" + t.TaskType
|
||||
if !seen[key] {
|
||||
@@ -278,10 +293,28 @@ func FetchAllRecentTasks(cookieMap map[string]string, host string) []TodayTaskIn
|
||||
}
|
||||
}
|
||||
|
||||
if len(all) == 0 {
|
||||
return []TodayTaskInfo{}
|
||||
// 两类都失败:返回错误(cookie 失效等场景由上层续期重试)
|
||||
if successCount == 0 && firstErr != nil {
|
||||
return nil, firstErr
|
||||
}
|
||||
return all
|
||||
|
||||
// 返校登记待办(节假日离返校应用;接口失败不影响签到类任务)
|
||||
if rr, rerr := FetchReturnRegisterTasks(cookieMap, host); rerr == nil {
|
||||
for _, t := range rr {
|
||||
key := t.TaskName + "|" + t.TaskType
|
||||
if !seen[key] {
|
||||
seen[key] = true
|
||||
all = append(all, t)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
slog.Warn("获取返校登记待办失败", "host", host, "error", rerr)
|
||||
}
|
||||
|
||||
if len(all) == 0 {
|
||||
return []TodayTaskInfo{}, nil
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
func fetchTasksByYearMonth(cookieMap map[string]string, host string, taskType TaskType, year, month string) ([]TodayTaskInfo, error) {
|
||||
yearMonth := fmt.Sprintf("%s-%s", year, month)
|
||||
@@ -326,7 +359,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
|
||||
}
|
||||
@@ -341,7 +374,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
|
||||
}
|
||||
@@ -365,60 +398,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) {
|
||||
return fetchTaskDetail(cookieMap, host, taskType, signWid, signInstanceWid, title, true)
|
||||
// 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)
|
||||
}
|
||||
|
||||
// findLatestTaskInstance 查找同名任务的最新可用实例
|
||||
// 优先当天/近期列表中未签到的实例(循环任务当天实例,可正常提交);
|
||||
// 否则回退到已签到实例(用于还原表单结构与历史默认值)
|
||||
func findLatestTaskInstance(cookieMap map[string]string, host string, taskType TaskType, title, excludeInstanceWid string) (TodayTaskInfo, bool) {
|
||||
collect := func(yearMonth string) ([]TodayTaskInfo, error) {
|
||||
if yearMonth == "" {
|
||||
return fetchTasksByEndpoint(cookieMap, host, taskType, "")
|
||||
}
|
||||
return fetchTasksByYearMonth(cookieMap, host, taskType, yearMonth[:4], yearMonth[5:])
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 依次:当天列表、本月列表、上月列表
|
||||
now := time.Now()
|
||||
months := []string{"", now.Format("2006-01"), now.AddDate(0, -1, 0).Format("2006-01")}
|
||||
seen := map[string]bool{}
|
||||
for _, ym := range months {
|
||||
tasks, err := collect(ym)
|
||||
if err != nil || len(tasks) == 0 {
|
||||
var signed, target *TodayTaskInfo
|
||||
for i := range tasks {
|
||||
t := tasks[i]
|
||||
if !globMatch(t.TaskName, title) || t.SignInstanceWid == "" {
|
||||
continue
|
||||
}
|
||||
var signedFallback *TodayTaskInfo
|
||||
for i := range tasks {
|
||||
t := tasks[i]
|
||||
if !globMatch(t.TaskName, title) || t.SignInstanceWid == "" || t.SignInstanceWid == excludeInstanceWid {
|
||||
continue
|
||||
}
|
||||
if seen[t.SignInstanceWid] {
|
||||
continue
|
||||
}
|
||||
seen[t.SignInstanceWid] = true
|
||||
if !t.IsSigned {
|
||||
// 未签到实例优先(当天循环任务可正常提交)
|
||||
return t, true
|
||||
}
|
||||
if signedFallback == nil {
|
||||
s := t
|
||||
signedFallback = &s
|
||||
}
|
||||
if !t.IsSigned {
|
||||
target = &t
|
||||
break
|
||||
}
|
||||
if signedFallback != nil {
|
||||
return *signedFallback, true
|
||||
if signed == nil {
|
||||
s := t
|
||||
signed = &s
|
||||
}
|
||||
}
|
||||
return TodayTaskInfo{}, false
|
||||
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
|
||||
}
|
||||
|
||||
// fetchTaskDetail 拉取任务详情;allowFallback 为 true 且实例已过期(datas 为空)时自动匹配最新实例重试一次
|
||||
func fetchTaskDetail(cookieMap map[string]string, host string, taskType TaskType, signWid, signInstanceWid, title string, allowFallback bool) (*TaskFormDetail, error) {
|
||||
// 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)
|
||||
@@ -445,7 +471,7 @@ func fetchTaskDetail(cookieMap map[string]string, host string, taskType TaskType
|
||||
ErrMsg string `json:"errMsg"`
|
||||
Datas map[string]interface{} `json:"datas"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("解析任务详情响应失败: %w", err)
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
@@ -453,13 +479,6 @@ func fetchTaskDetail(cookieMap map[string]string, host string, taskType TaskType
|
||||
}
|
||||
|
||||
rows := result.Datas
|
||||
if rows == nil && allowFallback {
|
||||
// 实例已过期/当天实例未发布导致详情为空,自动匹配同名任务的最新可用实例重试
|
||||
slog.Info("任务详情数据为空,自动匹配最新实例", "title", title, "signInstanceWid", signInstanceWid, "taskType", taskType)
|
||||
if alt, ok := findLatestTaskInstance(cookieMap, host, taskType, title, signInstanceWid); ok {
|
||||
return fetchTaskDetail(cookieMap, host, taskType, alt.SignWid, alt.SignInstanceWid, alt.TaskName, false)
|
||||
}
|
||||
}
|
||||
|
||||
detail := &TaskFormDetail{
|
||||
Rows: rows,
|
||||
@@ -499,6 +518,11 @@ func ParseTaskForm(detail *TaskFormDetail, historyRows map[string]interface{}) [
|
||||
histRows = historyRows
|
||||
}
|
||||
|
||||
// 扫码签到任务(signMode=2):只需要签到二维码(可选照片/额外字段),不需要定位信息
|
||||
if isScanMode(rows) {
|
||||
return parseScanTaskForm(detail, histRows)
|
||||
}
|
||||
|
||||
// 提取历史值(与旧版系统格式一致:lon/lat/address 分开存储)
|
||||
histLon := ""
|
||||
histLat := ""
|
||||
@@ -506,47 +530,59 @@ func ParseTaskForm(detail *TaskFormDetail, historyRows map[string]interface{}) [
|
||||
histSignPhotoUrl := ""
|
||||
histIsMalposition := ""
|
||||
|
||||
// 优先从 signPlaceSelected 提取(学校配置的签到范围点,cpdaily 返回 JSON 字符串或数组两种格式)
|
||||
// 有历史表单时是历史已选地点,无历史表单时是学校设置的默认签到范围,用于兜底填充
|
||||
if sps, ok := histRows["signPlaceSelected"]; ok {
|
||||
var places []map[string]interface{}
|
||||
switch v := sps.(type) {
|
||||
case string:
|
||||
if v != "" && v != "[]" {
|
||||
if err := json.Unmarshal([]byte(v), &places); err != nil {
|
||||
places = nil
|
||||
}
|
||||
}
|
||||
case []interface{}:
|
||||
for _, p := range v {
|
||||
if m, ok := p.(map[string]interface{}); ok {
|
||||
places = append(places, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(places) > 0 {
|
||||
// 取第一个签到范围点(主校区);无历史记录时作为默认坐标兜底
|
||||
if lng := mapValueStr(places[0], "longitude"); lng != "" {
|
||||
histLon = lng
|
||||
}
|
||||
if lat := mapValueStr(places[0], "latitude"); lat != "" {
|
||||
histLat = lat
|
||||
}
|
||||
if addr := mapValueStr(places[0], "address"); addr != "" {
|
||||
histAddress = addr
|
||||
}
|
||||
}
|
||||
// 签到范围点(校验坐标是否在打卡范围内):优先当前任务详情,其次历史详情
|
||||
rangePlaces := parseSignPlaces(rows)
|
||||
if len(rangePlaces) == 0 {
|
||||
rangePlaces = parseSignPlaces(histRows)
|
||||
}
|
||||
// 降级到 histRows 中的 longitude/latitude
|
||||
|
||||
// 优先使用历史记录中的真实签到位置(坐标 + 地址),
|
||||
// 但坐标必须仍落在打卡范围内——超出范围的坐标提交会被服务端以「位置不在签到范围内」拒绝,
|
||||
// 此时丢弃历史坐标,改由下方回退到学校配置的签到范围点。
|
||||
histLon = mapValueStr(histRows, "longitude")
|
||||
histLat = mapValueStr(histRows, "latitude")
|
||||
if histLon != "" && histLat != "" && coordsWithinSignRange(histLat, histLon, rangePlaces) {
|
||||
histAddress = mapValueStr(histRows, "signAddress")
|
||||
if histAddress == "" {
|
||||
histAddress = mapValueStr(histRows, "position")
|
||||
}
|
||||
} else {
|
||||
// 历史坐标缺失或超出范围:不采用历史坐标(地址一并丢弃,保持与坐标同源)
|
||||
histLon, histLat = "", ""
|
||||
}
|
||||
|
||||
// 回退:学校配置的签到范围点(signPlaceSelected[0],主校区),无历史记录时作为默认坐标
|
||||
if histLon == "" || histLat == "" {
|
||||
if lon, ok := histRows["longitude"]; ok && lon != nil {
|
||||
histLon = fmt.Sprintf("%v", lon)
|
||||
}
|
||||
if lat, ok := histRows["latitude"]; ok && lat != nil {
|
||||
histLat = fmt.Sprintf("%v", lat)
|
||||
if sps, ok := histRows["signPlaceSelected"]; ok {
|
||||
var places []map[string]interface{}
|
||||
switch v := sps.(type) {
|
||||
case string:
|
||||
if v != "" && v != "[]" {
|
||||
if err := json.Unmarshal([]byte(v), &places); err != nil {
|
||||
places = nil
|
||||
}
|
||||
}
|
||||
case []interface{}:
|
||||
for _, p := range v {
|
||||
if m, ok := p.(map[string]interface{}); ok {
|
||||
places = append(places, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(places) > 0 {
|
||||
if lng := mapValueStr(places[0], "longitude"); lng != "" {
|
||||
histLon = lng
|
||||
}
|
||||
if lat := mapValueStr(places[0], "latitude"); lat != "" {
|
||||
histLat = lat
|
||||
}
|
||||
if addr := mapValueStr(places[0], "address"); addr != "" {
|
||||
histAddress = addr
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 如果还是空的,再降级到当前表单中的 longitude/latitude(任务默认坐标)
|
||||
// 再降级到当前表单中的 longitude/latitude(任务默认坐标)
|
||||
if histLon == "" || histLat == "" {
|
||||
if lon, ok := rows["longitude"]; ok && lon != nil {
|
||||
histLon = fmt.Sprintf("%v", lon)
|
||||
@@ -555,7 +591,7 @@ func ParseTaskForm(detail *TaskFormDetail, historyRows map[string]interface{}) [
|
||||
histLat = fmt.Sprintf("%v", lat)
|
||||
}
|
||||
}
|
||||
// 地址降级链:signPlaceSelected[].address → histRows.position → histRows.signAddress → rows.position → rows.signAddress
|
||||
// 地址兜底链:histRows.position → histRows.signAddress → rows.position → rows.signAddress
|
||||
if histAddress == "" {
|
||||
if pos, ok := histRows["position"]; ok && pos != nil {
|
||||
histAddress = fmt.Sprintf("%v", pos)
|
||||
@@ -733,8 +769,233 @@ func ParseTaskForm(detail *TaskFormDetail, historyRows map[string]interface{}) [
|
||||
return list
|
||||
}
|
||||
|
||||
// extractScanPosition 提取扫码签到的经纬度与地址,供表单预填与提交使用。
|
||||
// 取值优先级与普通签到一致:signPlaceSelected[0](学校配置/历史已选范围点)
|
||||
// → 历史表单 / 详情的 longitude|latitude → 详情的 position|signAddress(地址)。
|
||||
// 扫码签到若不带定位,服务端会因经度/纬度为空串而拒绝提交(报 "empty String")。
|
||||
func extractScanPosition(detail *TaskFormDetail, histRows map[string]interface{}) (lon, lat, address string) {
|
||||
rows := detail.Rows
|
||||
|
||||
if histRows != nil {
|
||||
if sps, ok := histRows["signPlaceSelected"]; ok {
|
||||
var places []map[string]interface{}
|
||||
switch v := sps.(type) {
|
||||
case string:
|
||||
if v != "" && v != "[]" {
|
||||
if err := json.Unmarshal([]byte(v), &places); err != nil {
|
||||
places = nil
|
||||
}
|
||||
}
|
||||
case []interface{}:
|
||||
for _, p := range v {
|
||||
if m, ok := p.(map[string]interface{}); ok {
|
||||
places = append(places, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(places) > 0 {
|
||||
lon = mapValueStr(places[0], "longitude")
|
||||
lat = mapValueStr(places[0], "latitude")
|
||||
address = mapValueStr(places[0], "address")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 降级:历史表单里的 longitude/latitude
|
||||
if histRows != nil {
|
||||
if lon == "" {
|
||||
lon = mapValueStr(histRows, "longitude")
|
||||
}
|
||||
if lat == "" {
|
||||
lat = mapValueStr(histRows, "latitude")
|
||||
}
|
||||
}
|
||||
// 再降级:当前任务详情里的 longitude/latitude(学校默认坐标)
|
||||
if lon == "" {
|
||||
lon = mapValueStr(rows, "longitude")
|
||||
}
|
||||
if lat == "" {
|
||||
lat = mapValueStr(rows, "latitude")
|
||||
}
|
||||
|
||||
// 地址降级链
|
||||
if address == "" && histRows != nil {
|
||||
address = mapValueStr(histRows, "position")
|
||||
}
|
||||
if address == "" && histRows != nil {
|
||||
address = mapValueStr(histRows, "signAddress")
|
||||
}
|
||||
if address == "" {
|
||||
address = mapValueStr(rows, "position")
|
||||
}
|
||||
if address == "" {
|
||||
address = mapValueStr(rows, "signAddress")
|
||||
}
|
||||
return lon, lat, address
|
||||
}
|
||||
|
||||
// parseScanTaskForm 生成扫码签到任务(signMode=2)的表单项:
|
||||
// 经纬度/地址 + 可选签到照片 + 可选额外字段 + 签到二维码(放最后)。
|
||||
// 字段顺序与普通签到保持一致(定位在前),二维码作为扫码任务特有项置于末尾。
|
||||
func parseScanTaskForm(detail *TaskFormDetail, histRows map[string]interface{}) []cpdmodel.CpTaskFormItem {
|
||||
rows := detail.Rows
|
||||
var list []cpdmodel.CpTaskFormItem
|
||||
|
||||
// 二维码ID(uuid):历史值若为可解析的链接/文本,统一归一化为 uuid 存储,
|
||||
// 避免把整条链接(乃至 base64 图片)写进 formData。
|
||||
histQr := ""
|
||||
if histRows != nil {
|
||||
if v, ok := histRows["qrCode"]; ok && v != nil {
|
||||
raw := fmt.Sprintf("%v", v)
|
||||
if uuid := ExtractQrUuid(raw); uuid != "" {
|
||||
histQr = uuid
|
||||
} else if !IsDataURIImage(raw) {
|
||||
histQr = raw
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 经纬度与地址:扫码签到接口同样要求提交定位(缺省会因空串被服务端拒绝,
|
||||
// 报 "empty String"),且用户可在表单中选择签到范围点,故与普通签到保持一致的字段。
|
||||
scanLon, scanLat, scanAddress := extractScanPosition(detail, histRows)
|
||||
list = append(list, cpdmodel.CpTaskFormItem{
|
||||
Title: "经度",
|
||||
ColName: "lon",
|
||||
Type: cpdmodel.ItemTypeInput,
|
||||
Required: true,
|
||||
Content: scanLon,
|
||||
Default: scanLon,
|
||||
Show: true,
|
||||
Tip: "签到地点经度坐标",
|
||||
})
|
||||
list = append(list, cpdmodel.CpTaskFormItem{
|
||||
Title: "纬度",
|
||||
ColName: "lat",
|
||||
Type: cpdmodel.ItemTypeInput,
|
||||
Required: true,
|
||||
Content: scanLat,
|
||||
Default: scanLat,
|
||||
Show: true,
|
||||
Tip: "签到地点纬度坐标",
|
||||
})
|
||||
list = append(list, cpdmodel.CpTaskFormItem{
|
||||
Title: "签到具体地址",
|
||||
ColName: "address",
|
||||
Type: cpdmodel.ItemTypeInput,
|
||||
Required: true,
|
||||
Content: scanAddress,
|
||||
Default: scanAddress,
|
||||
Show: true,
|
||||
Tip: "签到完毕后查看时最底部那个最详细的地址信息",
|
||||
})
|
||||
|
||||
// 签到照片(任务要求时保留)
|
||||
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 {
|
||||
histSignPhotoUrl := ""
|
||||
if histRows != nil {
|
||||
if photo, ok := histRows["signPhotoUrl"]; ok && photo != nil {
|
||||
histSignPhotoUrl = fmt.Sprintf("%v", photo)
|
||||
}
|
||||
}
|
||||
if histSignPhotoUrl == "" {
|
||||
if photo, ok := rows["signPhotoUrl"]; ok && photo != nil {
|
||||
histSignPhotoUrl = fmt.Sprintf("%v", photo)
|
||||
}
|
||||
}
|
||||
list = append(list, cpdmodel.CpTaskFormItem{
|
||||
Title: "签到照片",
|
||||
ColName: "signImg",
|
||||
Type: cpdmodel.ItemTypeImage,
|
||||
Required: true,
|
||||
Content: histSignPhotoUrl,
|
||||
Default: histSignPhotoUrl,
|
||||
Show: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 额外字段
|
||||
if detail.IsNeedExtra {
|
||||
for i, field := range detail.ExtraField {
|
||||
fm, ok := field.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
extraTitle, _ := fm["title"].(string)
|
||||
isReq, _ := fm["isRequired"].(bool)
|
||||
hasOther, _ := fm["hasOtherItems"].(bool)
|
||||
|
||||
item := cpdmodel.CpTaskFormItem{
|
||||
Title: extraTitle,
|
||||
ColName: extraTitle,
|
||||
Type: cpdmodel.ItemTypeSingle,
|
||||
Number: uint(i + 1),
|
||||
Required: isReq,
|
||||
IsOther: hasOther,
|
||||
Show: true,
|
||||
}
|
||||
if items, ok := fm["extraFieldItems"].([]interface{}); ok {
|
||||
for _, it := range items {
|
||||
if im, ok := it.(map[string]interface{}); ok {
|
||||
content, _ := im["content"].(string)
|
||||
otherItems, _ := im["isOtherItems"].(bool)
|
||||
item.Options = append(item.Options, cpdmodel.CpTaskFormOption{
|
||||
Content: content,
|
||||
IsOtherItems: otherItems,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
}
|
||||
|
||||
// 二维码ID(uuid)放最后:扫码任务特有项,置于定位/照片/额外字段之后
|
||||
list = append(list, cpdmodel.CpTaskFormItem{
|
||||
Title: "二维码ID",
|
||||
ColName: "uuid",
|
||||
Type: cpdmodel.ItemTypeImage,
|
||||
Required: true,
|
||||
Content: histQr,
|
||||
Show: true,
|
||||
Tip: "上传现场签到二维码图片,自动解析并保存二维码ID(uuid)",
|
||||
})
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
// FillSubmitForm 根据用户配置的表单项填充提交表单
|
||||
func FillSubmitForm(rows map[string]interface{}, formItems []cpdmodel.CpTaskFormItem, deviceId string) map[string]interface{} {
|
||||
// isScanMode 判断任务是否为扫码签到类型(signMode=2,兼容数字/字符串/json.Number)
|
||||
func isScanMode(rows map[string]interface{}) bool {
|
||||
if rows == nil {
|
||||
return false
|
||||
}
|
||||
switch v := rows["signMode"].(type) {
|
||||
case float64:
|
||||
return int(v) == 2
|
||||
case int:
|
||||
return v == 2
|
||||
case string:
|
||||
return v == "2"
|
||||
case json.Number:
|
||||
return v.String() == "2"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func FillSubmitForm(rows map[string]interface{}, formItems []cpdmodel.CpTaskFormItem, deviceId string) (map[string]interface{}, error) {
|
||||
// 扫码签到任务(signMode=2):从签到二维码解析 uuid,提交体用 qrUuid 替代 signInstanceWid
|
||||
if isScanMode(rows) {
|
||||
return fillScanSubmitForm(rows, formItems)
|
||||
}
|
||||
|
||||
result := make(map[string]interface{})
|
||||
|
||||
// 提取经纬度和地址(兼容旧版 lon/lat 和新版 latAndLon 两种格式)
|
||||
@@ -807,6 +1068,13 @@ func FillSubmitForm(rows map[string]interface{}, formItems []cpdmodel.CpTaskForm
|
||||
}
|
||||
|
||||
// 额外字段
|
||||
fillExtraFields(rows, formItems, result)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// fillExtraFields 填充任务额外字段(isNeedExtra)到提交表单
|
||||
func fillExtraFields(rows map[string]interface{}, formItems []cpdmodel.CpTaskFormItem, result map[string]interface{}) {
|
||||
isNeedExtra := false
|
||||
if v, ok := rows["isNeedExtra"]; ok {
|
||||
if f, ok := v.(float64); ok && f == 1 {
|
||||
@@ -849,8 +1117,91 @@ func FillSubmitForm(rows map[string]interface{}, formItems []cpdmodel.CpTaskForm
|
||||
} else {
|
||||
result["isNeedExtra"] = 0
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
// fillScanSubmitForm 生成扫码签到(signMode=2)的提交表单:
|
||||
// 取二维码ID(uuid)字段,提取 uuid 后用 qrUuid 替代 signInstanceWid(两者不并存)。
|
||||
// 定位字段与普通签到一致地提交:服务端对扫码签到的提交体同样要求经度/纬度,
|
||||
// 缺失会因空串转数字失败而返回 "empty String",故此处带上 lon/lat/position。
|
||||
// 字段名兼容:新数据为 uuid,历史数据为 qrCode。
|
||||
// 二维码图片的识别在前端完成,这里只处理已解析出的 uuid 文本。
|
||||
func fillScanSubmitForm(rows map[string]interface{}, formItems []cpdmodel.CpTaskFormItem) (map[string]interface{}, error) {
|
||||
qrContent := ""
|
||||
for _, v := range formItems {
|
||||
if v.ColName == "uuid" || v.ColName == "qrCode" {
|
||||
qrContent = strings.TrimSpace(v.Content)
|
||||
break
|
||||
}
|
||||
}
|
||||
uuid := ExtractQrUuid(qrContent)
|
||||
if uuid == "" {
|
||||
return nil, fmt.Errorf("二维码签到任务缺少有效的二维码ID(uuid),请重新上传二维码解析")
|
||||
}
|
||||
|
||||
// 经纬度与地址(与普通签到一致):缺失会被服务端判定为参数为空
|
||||
var scanLon, scanLat, scanAddress string
|
||||
for _, v := range formItems {
|
||||
switch v.ColName {
|
||||
case "lon":
|
||||
scanLon = strings.TrimSpace(v.Content)
|
||||
case "lat":
|
||||
scanLat = strings.TrimSpace(v.Content)
|
||||
case "address":
|
||||
scanAddress = strings.TrimSpace(v.Content)
|
||||
case "latAndLon":
|
||||
parts := strings.Split(v.Content, ",")
|
||||
if len(parts) == 2 {
|
||||
if scanLon == "" {
|
||||
scanLon = strings.TrimSpace(parts[0])
|
||||
}
|
||||
if scanLat == "" {
|
||||
scanLat = strings.TrimSpace(parts[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 表单未提供定位时,回退到任务详情中的学校默认坐标
|
||||
if scanLon == "" {
|
||||
scanLon = mapValueStr(rows, "longitude")
|
||||
}
|
||||
if scanLat == "" {
|
||||
scanLat = mapValueStr(rows, "latitude")
|
||||
}
|
||||
if scanAddress == "" {
|
||||
scanAddress = mapValueStr(rows, "position")
|
||||
}
|
||||
if scanAddress == "" {
|
||||
scanAddress = mapValueStr(rows, "signAddress")
|
||||
}
|
||||
|
||||
result := map[string]interface{}{
|
||||
"qrUuid": uuid,
|
||||
"uaIsCpadaily": true,
|
||||
"longitude": scanLon,
|
||||
"latitude": scanLat,
|
||||
"position": scanAddress,
|
||||
}
|
||||
|
||||
// 签到照片(任务要求时保留,与普通签到一致)
|
||||
isPhoto := false
|
||||
if v, ok := rows["isPhoto"]; ok {
|
||||
if f, ok := v.(float64); ok && f == 1 {
|
||||
isPhoto = true
|
||||
}
|
||||
}
|
||||
if isPhoto {
|
||||
for _, v := range formItems {
|
||||
if v.ColName == "signImg" && v.Content != "" {
|
||||
result["signPhotoUrl"] = v.Content
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 额外字段(与普通签到保持一致的提交结构)
|
||||
fillExtraFields(rows, formItems, result)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SignPlace 查寝组/签到任务配置的签到范围点
|
||||
@@ -922,6 +1273,25 @@ func parseSignPlaces(rows map[string]interface{}) []SignPlace {
|
||||
return places
|
||||
}
|
||||
|
||||
// coordsWithinSignRange 判断坐标是否落在任一签到范围点内。
|
||||
// places 为空(学校未配置范围点)时返回 true——无范围信息则不做限制,沿用历史坐标。
|
||||
func coordsWithinSignRange(latStr, lonStr string, places []SignPlace) bool {
|
||||
if len(places) == 0 {
|
||||
return true
|
||||
}
|
||||
lat, err1 := strconv.ParseFloat(strings.TrimSpace(latStr), 64)
|
||||
lon, err2 := strconv.ParseFloat(strings.TrimSpace(lonStr), 64)
|
||||
if err1 != nil || err2 != nil {
|
||||
return false
|
||||
}
|
||||
for _, p := range places {
|
||||
if haversineMeters(lat, lon, p.LatitudeF, p.LongitudeF) <= p.RadiusMeters {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// haversineMeters 计算两个经纬度坐标之间的球面距离(米)
|
||||
func haversineMeters(lat1, lon1, lat2, lon2 float64) float64 {
|
||||
const earthRadius = 6371000.0
|
||||
@@ -1091,10 +1461,11 @@ func SubmitSign(cookieMap map[string]string, host string, taskType TaskType, sub
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
if err := unmarshalBody(body, &result); err != nil {
|
||||
return fmt.Errorf("解析签到响应失败: %w, body: %s", err, string(body))
|
||||
}
|
||||
code, _ := result.Code.Int64()
|
||||
slog.Info("submitSign 响应", "code", result.Code.String(), "message", result.Message, "body", string(body))
|
||||
if code != 0 {
|
||||
msg := result.Message
|
||||
if msg == "" {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package cpdaily
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
cpdmodel "cpdaily-new/internal/model"
|
||||
)
|
||||
|
||||
// 扫码任务:提交表单必须用 qrUuid 替代 signInstanceWid,并携带经纬度/地址
|
||||
func TestFillScanSubmitForm(t *testing.T) {
|
||||
rows := map[string]interface{}{
|
||||
"signMode": float64(2),
|
||||
"signInstanceWid": "397161",
|
||||
"longitude": "102.7",
|
||||
"latitude": "25.0",
|
||||
"position": "昆明文理学院",
|
||||
}
|
||||
formItems := []cpdmodel.CpTaskFormItem{
|
||||
{Title: "二维码ID", ColName: "uuid", Type: cpdmodel.ItemTypeImage,
|
||||
Content: "https://ynu.campusphere.net/wec-counselor-sign-apps/stu/qrsign/index.html?uuid=1583a66272854585833eb13b56fc1937&isNeedExtra=0"},
|
||||
}
|
||||
form, err := FillSubmitForm(rows, formItems, "device-1")
|
||||
if err != nil {
|
||||
t.Fatalf("FillSubmitForm error: %v", err)
|
||||
}
|
||||
if form["qrUuid"] != "1583a66272854585833eb13b56fc1937" {
|
||||
t.Fatalf("qrUuid = %v", form["qrUuid"])
|
||||
}
|
||||
if _, ok := form["signInstanceWid"]; ok {
|
||||
t.Fatal("scan submit form must NOT contain signInstanceWid")
|
||||
}
|
||||
// 定位字段必须携带(缺失会因空串被服务端拒绝,报 "empty String")
|
||||
if form["longitude"] != "102.7" || form["latitude"] != "25.0" {
|
||||
t.Fatalf("scan form must carry lon/lat, got lon=%v lat=%v", form["longitude"], form["latitude"])
|
||||
}
|
||||
if form["position"] != "昆明文理学院" {
|
||||
t.Fatalf("scan form must carry position, got %v", form["position"])
|
||||
}
|
||||
if form["uaIsCpadaily"] != true {
|
||||
t.Fatal("uaIsCpadaily missing")
|
||||
}
|
||||
|
||||
// 缺少二维码 → 明确报错(不再静默生成会假成功的表单)
|
||||
if _, err := FillSubmitForm(rows, nil, "device-1"); err == nil {
|
||||
t.Fatal("missing uuid should return error")
|
||||
}
|
||||
|
||||
// 只存 uuid 的裸值(新流程):必须能正确解析并提交(含非 32-hex 的 uuid)
|
||||
for _, bare := range []string{"1583a66272854585833eb13b56fc1937", "abc123XYZ"} {
|
||||
items := []cpdmodel.CpTaskFormItem{
|
||||
{Title: "二维码ID", ColName: "uuid", Type: cpdmodel.ItemTypeImage, Content: bare},
|
||||
}
|
||||
f, err := FillSubmitForm(rows, items, "device-1")
|
||||
if err != nil {
|
||||
t.Fatalf("bare uuid %q should resolve, got error: %v", bare, err)
|
||||
}
|
||||
if f["qrUuid"] != bare {
|
||||
t.Fatalf("bare uuid %q → qrUuid = %v", bare, f["qrUuid"])
|
||||
}
|
||||
}
|
||||
|
||||
// 历史数据(colName 仍为 qrCode)继续兼容
|
||||
oldItems := []cpdmodel.CpTaskFormItem{
|
||||
{Title: "签到二维码", ColName: "qrCode", Type: cpdmodel.ItemTypeImage, Content: "1583a66272854585833eb13b56fc1937"},
|
||||
}
|
||||
if f, err := FillSubmitForm(rows, oldItems, "device-1"); err != nil || f["qrUuid"] != "1583a66272854585833eb13b56fc1937" {
|
||||
t.Fatalf("legacy qrCode field should still work: form=%v err=%v", f, err)
|
||||
}
|
||||
|
||||
// 普通任务(无 signMode)不受影响:走原逻辑,且不含 qrUuid
|
||||
normalRows := map[string]interface{}{"signInstanceWid": "123"}
|
||||
normalItems := []cpdmodel.CpTaskFormItem{
|
||||
{ColName: "lat", Content: "24.8"},
|
||||
{ColName: "lon", Content: "102.8"},
|
||||
{ColName: "address", Content: "云南大学"},
|
||||
}
|
||||
normalForm, err := FillSubmitForm(normalRows, normalItems, "device-1")
|
||||
if err != nil {
|
||||
t.Fatalf("normal FillSubmitForm error: %v", err)
|
||||
}
|
||||
if normalForm["latitude"] != "24.8" || normalForm["signInstanceWid"] != "123" {
|
||||
t.Fatalf("normal form mismatch: %v", normalForm)
|
||||
}
|
||||
if _, ok := normalForm["qrUuid"]; ok {
|
||||
t.Fatal("normal form must not contain qrUuid")
|
||||
}
|
||||
}
|
||||
|
||||
// 扫码任务表单项解析:ParseTaskForm 应生成经纬度/地址项 + 「二维码ID」图片项(二维码在最后)
|
||||
func TestParseScanTaskForm(t *testing.T) {
|
||||
detail := &TaskFormDetail{
|
||||
Rows: map[string]interface{}{"signMode": float64(2)},
|
||||
}
|
||||
items := ParseTaskForm(detail, nil)
|
||||
// 经度 + 纬度 + 地址 + 二维码ID
|
||||
if len(items) != 4 {
|
||||
t.Fatalf("scan form items = %d, want 4: %+v", len(items), items)
|
||||
}
|
||||
// 二维码ID 位于最后
|
||||
last := items[len(items)-1]
|
||||
if last.ColName != "uuid" || last.Type != cpdmodel.ItemTypeImage || !last.Required {
|
||||
t.Fatalf("unexpected uuid item (should be last): %+v", last)
|
||||
}
|
||||
wantPos := map[string]bool{"lon": false, "lat": false, "address": false}
|
||||
for _, it := range items[:len(items)-1] {
|
||||
if _, ok := wantPos[it.ColName]; ok {
|
||||
wantPos[it.ColName] = true
|
||||
}
|
||||
}
|
||||
for k, ok := range wantPos {
|
||||
if !ok {
|
||||
t.Fatalf("scan form missing position item %q: %+v", k, items)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 历史行数据里的二维码链接应被归一化为 uuid 存储(不把整条链接写入 formData)
|
||||
func TestParseScanTaskFormNormalizesUuid(t *testing.T) {
|
||||
detail := &TaskFormDetail{Rows: map[string]interface{}{"signMode": float64(2)}}
|
||||
histRows := map[string]interface{}{
|
||||
"qrCode": "https://ynu.campusphere.net/wec-counselor-sign-apps/stu/qrsign/index.html?uuid=1583a66272854585833eb13b56fc1937&isNeedExtra=0",
|
||||
}
|
||||
items := ParseTaskForm(detail, histRows)
|
||||
if len(items) < 1 {
|
||||
t.Fatalf("unexpected items: %+v", items)
|
||||
}
|
||||
uuidItem := items[len(items)-1]
|
||||
if uuidItem.ColName != "uuid" {
|
||||
t.Fatalf("last item should be uuid, got %+v", uuidItem)
|
||||
}
|
||||
if uuidItem.Content != "1583a66272854585833eb13b56fc1937" {
|
||||
t.Fatalf("history link should normalize to uuid, got %q", uuidItem.Content)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,10 @@ type Claims struct {
|
||||
UserID uint `json:"userId"`
|
||||
Username string `json:"username"`
|
||||
SchoolID string `json:"schoolId"`
|
||||
// MFA 标记:通过多因子认证通道登录的用户。此类账号第三方会话无法自动续期
|
||||
// (重新登录需人工输入验证码),JWT 有效期与第三方 Cookie 对齐(短期),
|
||||
// 刷新 token 也不会延长会话。
|
||||
MFA bool `json:"mfa,omitempty"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
@@ -64,6 +68,43 @@ func GenerateTokens(userID uint, username, schoolID string) (*TokenPair, error)
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GenerateShortTokens 生成 MFA 通道登录的短期 token 对:
|
||||
// access 与 refresh 有效期均为 ttl 秒(与第三方 Cookie 有效期对齐,当前默认配置 7200 即 2 小时,
|
||||
// 见 config.JwtConfig.MfaAccessExpire),且携带 MFA 标记——刷新 token 时不会延长会话。
|
||||
func GenerateShortTokens(userID uint, username, schoolID string, ttlSeconds int64) (*TokenPair, error) {
|
||||
now := time.Now()
|
||||
jwtCfg := config.Global.Jwt
|
||||
|
||||
accessClaims := Claims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
SchoolID: schoolID,
|
||||
MFA: true,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttlSeconds) * time.Second)),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
Issuer: "cpdaily-new",
|
||||
},
|
||||
}
|
||||
accessToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims).SignedString([]byte(jwtCfg.Secret))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refreshClaims := accessClaims
|
||||
refreshClaims.Issuer = "cpdaily-new-refresh"
|
||||
refreshToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims).SignedString([]byte(jwtCfg.Secret))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &TokenPair{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
ExpiresIn: ttlSeconds,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ValidateToken(tokenString string) (*Claims, error) {
|
||||
claims := &Claims{}
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
@@ -73,6 +114,17 @@ func ValidateToken(tokenString string) (*Claims, error) {
|
||||
return []byte(config.Global.Jwt.Secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
// MFA access token 服务端校验宽限:MFA 学校第三方会话无法自动续期(重登需人工
|
||||
// 输入验证码),已签发 token 无法修改;当 MfaAccessExpire 调整(如 1h → 2h)时,
|
||||
// 对调整前签发的 MFA access token 按「签发时间 + 当前配置 TTL」放行,使存量用户
|
||||
// 无需重新登录、平滑过渡到新有效期。仅放宽 access(issuer=cpdaily-new):
|
||||
// refresh 严格按自身 exp 校验,避免出现刷新窗口导致会话被滑动静默续期,
|
||||
// 违背 MFA 短会话设计。
|
||||
if errors.Is(err, jwt.ErrTokenExpired) &&
|
||||
claims.MFA && claims.Issuer == "cpdaily-new" && claims.IssuedAt != nil &&
|
||||
time.Now().Before(claims.IssuedAt.Add(time.Duration(config.Global.Jwt.MfaAccessExpire)*time.Second)) {
|
||||
return claims, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !token.Valid {
|
||||
@@ -86,6 +138,10 @@ func RefreshTokens(refreshToken string) (*TokenPair, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("refresh token invalid or expired")
|
||||
}
|
||||
// MFA 通道登录的用户:第三方会话无法自动续期,刷新也不延长有效期
|
||||
if claims.MFA {
|
||||
return GenerateShortTokens(claims.UserID, claims.Username, claims.SchoolID, int64(config.Global.Jwt.MfaAccessExpire))
|
||||
}
|
||||
// 刷新时生成全新 token 对
|
||||
return GenerateTokens(claims.UserID, claims.Username, claims.SchoolID)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cpdaily-new/internal/config"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// 测试配置:MFA TTL 2 小时(与当前生产配置一致)
|
||||
func setupJwtTestConfig() {
|
||||
config.Global.Jwt.Secret = "unit-test-secret"
|
||||
config.Global.Jwt.AccessExpire = 3600
|
||||
config.Global.Jwt.RefreshExpire = 864000
|
||||
config.Global.Jwt.MfaAccessExpire = 7200
|
||||
}
|
||||
|
||||
// signClaims 用手写 Claims 直接签名,模拟不同时期/不同 TTL 签发的 token
|
||||
func signClaims(t *testing.T, secret string, claims Claims) string {
|
||||
t.Helper()
|
||||
s, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
t.Fatalf("签名失败: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// mfaClaims 构造 MFA token Claims:iat 为签发时间,ttl 为签发时的有效期
|
||||
func mfaClaims(issuer string, iat time.Time, ttl time.Duration) Claims {
|
||||
return Claims{
|
||||
UserID: 1066,
|
||||
Username: "ynu-20251960205",
|
||||
SchoolID: "ynu",
|
||||
MFA: true,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(iat),
|
||||
ExpiresAt: jwt.NewNumericDate(iat.Add(ttl)),
|
||||
Issuer: issuer,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 场景1:1h 配置时代签发的 MFA access token 已过期 30 分钟,但在「签发时间+2h」宽限内 → 放行
|
||||
// (杨蕊宁存量 token 场景:部署 v1.2.39 后无需重新登录)
|
||||
func TestMFAOldAccessTokenWithinGrace(t *testing.T) {
|
||||
setupJwtTestConfig()
|
||||
now := time.Now()
|
||||
tokenStr := signClaims(t, config.Global.Jwt.Secret, mfaClaims("cpdaily-new", now.Add(-90*time.Minute), 1*time.Hour))
|
||||
claims, err := ValidateToken(tokenStr)
|
||||
if err != nil {
|
||||
t.Fatalf("宽限窗口内(iat+2h)应放行: %v", err)
|
||||
}
|
||||
if claims.UserID != 1066 || !claims.MFA {
|
||||
t.Fatalf("claims 解析异常: %+v", claims)
|
||||
}
|
||||
}
|
||||
|
||||
// 场景2:MFA access token 超出「签发时间+2h」宽限 → 拒绝
|
||||
func TestMFAOldAccessTokenBeyondGrace(t *testing.T) {
|
||||
setupJwtTestConfig()
|
||||
now := time.Now()
|
||||
tokenStr := signClaims(t, config.Global.Jwt.Secret, mfaClaims("cpdaily-new", now.Add(-150*time.Minute), 1*time.Hour))
|
||||
if _, err := ValidateToken(tokenStr); err == nil {
|
||||
t.Fatal("超出宽限窗口的 MFA access token 必须拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// 场景3:MFA refresh token 已过期 → 拒绝(refresh 不享受宽限,避免滑动续期)
|
||||
func TestMFAOldRefreshTokenNotGraced(t *testing.T) {
|
||||
setupJwtTestConfig()
|
||||
now := time.Now()
|
||||
tokenStr := signClaims(t, config.Global.Jwt.Secret, mfaClaims("cpdaily-new-refresh", now.Add(-90*time.Minute), 1*time.Hour))
|
||||
if _, err := ValidateToken(tokenStr); err == nil {
|
||||
t.Fatal("MFA refresh token 过期后必须拒绝(不得宽限)")
|
||||
}
|
||||
}
|
||||
|
||||
// 场景4:非 MFA 的普通 access token 过期 → 按原逻辑拒绝
|
||||
func TestNormalExpiredAccessTokenRejected(t *testing.T) {
|
||||
setupJwtTestConfig()
|
||||
now := time.Now()
|
||||
claims := Claims{
|
||||
UserID: 1,
|
||||
Username: "normal-user",
|
||||
MFA: false,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(now.Add(-90 * time.Minute)),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(-30 * time.Minute)),
|
||||
Issuer: "cpdaily-new",
|
||||
},
|
||||
}
|
||||
if _, err := ValidateToken(signClaims(t, config.Global.Jwt.Secret, claims)); err == nil {
|
||||
t.Fatal("普通用户过期 access token 必须拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// 场景5:正常有效期内(TTL=2h)的 MFA access token → 放行(常规路径不受影响)
|
||||
func TestMFAAccessTokenValidNormally(t *testing.T) {
|
||||
setupJwtTestConfig()
|
||||
now := time.Now()
|
||||
tokenStr := signClaims(t, config.Global.Jwt.Secret, mfaClaims("cpdaily-new", now.Add(-10*time.Minute), 2*time.Hour))
|
||||
if _, err := ValidateToken(tokenStr); err != nil {
|
||||
t.Fatalf("有效期内 MFA access token 应放行: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 场景6:错误签名 → 拒绝(宽限不得绕过签名校验)
|
||||
func TestMFAOldAccessTokenWrongSignatureRejected(t *testing.T) {
|
||||
setupJwtTestConfig()
|
||||
now := time.Now()
|
||||
tokenStr := signClaims(t, "wrong-secret", mfaClaims("cpdaily-new", now.Add(-90*time.Minute), 1*time.Hour))
|
||||
if _, err := ValidateToken(tokenStr); err == nil {
|
||||
t.Fatal("错误签名必须拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// 场景7:MFA access token 缺少签发时间(iat 缺失)→ 拒绝(无法核定宽限窗口)
|
||||
func TestMFAOldAccessTokenWithoutIssuedAtRejected(t *testing.T) {
|
||||
setupJwtTestConfig()
|
||||
now := time.Now()
|
||||
claims := Claims{
|
||||
UserID: 1066,
|
||||
MFA: true,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(-30 * time.Minute)),
|
||||
Issuer: "cpdaily-new",
|
||||
},
|
||||
}
|
||||
if _, err := ValidateToken(signClaims(t, config.Global.Jwt.Secret, claims)); err == nil {
|
||||
t.Fatal("缺少 iat 的过期 MFA access token 必须拒绝")
|
||||
}
|
||||
}
|
||||
@@ -296,6 +296,22 @@ func NotifySchoolAdapted(contactEmails []string, schoolName string) {
|
||||
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()
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// ClientIP 提取客户端真实 IP。
|
||||
// 生产环境经 nginx 反代,nginx 已配置 proxy_set_header X-Real-IP $remote_addr
|
||||
// 和 X-Forwarded-For $proxy_add_x_forwarded_for,因此优先取 X-Real-IP(nginx 直接写入,
|
||||
// 最可信);其次取 X-Forwarded-For 第一段(多层代理链上最初的客户端 IP);
|
||||
// 都没有时兜底 Fiber 默认的 RemoteAddr(直连场景,如本地开发)。
|
||||
func ClientIP(c *fiber.Ctx) string {
|
||||
if rip := strings.TrimSpace(c.Get("X-Real-IP")); rip != "" {
|
||||
return rip
|
||||
}
|
||||
if xff := strings.TrimSpace(c.Get("X-Forwarded-For")); xff != "" {
|
||||
if idx := strings.IndexByte(xff, ','); idx >= 0 {
|
||||
xff = xff[:idx]
|
||||
}
|
||||
return strings.TrimSpace(xff)
|
||||
}
|
||||
return c.IP()
|
||||
}
|
||||
@@ -6,6 +6,19 @@ import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
// MFA 多因子认证专用业务码:HTTP 200 返回,前端按 code 弹出验证码弹窗而非错误弹窗
|
||||
const (
|
||||
CodeMFARequired = 4281 // 登录触发多因子认证,Data 含 needMFA/mfaToken/expiresIn/authMethods(可用验证方式列表)
|
||||
CodeMFAVerifyFailed = 4282 // MFA 验证码错误或验证失败(弹窗保留可重试)
|
||||
CodeMFAVerifySessionExpired = 4283 // MFA 验证会话不存在或已过期(前端应关闭弹窗引导重新登录)
|
||||
CodeMFASendCodeFailed = 4284 // MFA 验证码发送失败(弹窗保留在选择界面,可重试或更换验证方式)
|
||||
)
|
||||
|
||||
// RespondWithCode 以 HTTP 200 返回指定业务码(MFA 等需要前端精确分支处理的状态)
|
||||
func RespondWithCode(c *fiber.Ctx, code int, msg string, data interface{}) error {
|
||||
return c.JSON(Response{Code: code, Message: msg, Data: data})
|
||||
}
|
||||
|
||||
// FormatFloat 格式化浮点数为字符串保留2位小数
|
||||
func FormatFloat(f float64) string {
|
||||
return fmt.Sprintf("%.2f", f)
|
||||
|
||||
@@ -4,7 +4,41 @@
|
||||
<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, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#f5f5f5" />
|
||||
<title>小助手</title>
|
||||
<script>
|
||||
// 老内核(Chrome 78~92,即微信 XWEB / 国产浏览器)缺失的 ES2022 运行时 API 补齐。
|
||||
// 背景:reka-ui(其弹窗组件)与 @vueuse/shared 内部直接调用 Object.hasOwn
|
||||
// (Chrome 93+),而 esbuild/vite 的 target 只降语法、不降运行时 API,
|
||||
// 构建产物在 Chrome 78 上会在弹窗挂载时抛 TypeError。
|
||||
// 该内联脚本先于 module 产物执行(module 默认 defer),故此处按需补齐即可;
|
||||
// 现代内核因特性检测成立而跳过,零开销。写法保持 ES5,避免老内核解析失败。
|
||||
;(function () {
|
||||
if (typeof Object.hasOwn !== 'function') {
|
||||
Object.defineProperty(Object, 'hasOwn', {
|
||||
value: function (obj, prop) {
|
||||
if (obj === null || obj === undefined) {
|
||||
throw new TypeError('Cannot convert undefined or null to object')
|
||||
}
|
||||
return Object.prototype.hasOwnProperty.call(Object(obj), prop)
|
||||
},
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
}
|
||||
})()
|
||||
</script>
|
||||
<script>
|
||||
// 暗色主题防闪烁:与 composables/useTheme.ts 保持同一时间规则
|
||||
// (18:00–次日 06:00 暗色),在首屏渲染前预设 html.dark 与状态栏色
|
||||
;(function () {
|
||||
var h = new Date().getHours()
|
||||
if (h >= 18 || h < 6) {
|
||||
document.documentElement.classList.add('dark')
|
||||
document.querySelector('meta[name="theme-color"]').setAttribute('content', '#15151f')
|
||||
}
|
||||
})()
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
Generated
+495
-50
@@ -11,8 +11,10 @@
|
||||
"axios": "^1.13.6",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"jsqr": "^1.4.0",
|
||||
"lucide-vue-next": "^1.0.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.4",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"vue": "^3.5.30",
|
||||
"vue-router": "^5.0.4"
|
||||
@@ -22,6 +24,7 @@
|
||||
"@types/node": "^26.0.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^6.0.5",
|
||||
"lightningcss": "^1.33.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^8.0.1",
|
||||
@@ -159,6 +162,79 @@
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/core": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz",
|
||||
"integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==",
|
||||
"dependencies": {
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/dom": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz",
|
||||
"integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==",
|
||||
"dependencies": {
|
||||
"@floating-ui/core": "^1.8.0",
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/utils": {
|
||||
"version": "0.2.12",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz",
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww=="
|
||||
},
|
||||
"node_modules/@floating-ui/vue": {
|
||||
"version": "1.1.11",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/vue/-/vue-1.1.11.tgz",
|
||||
"integrity": "sha512-HzHKCNVxnGS35r9fCHBc3+uCnjw9IWIlCPL683cGgM9Kgj2BiAl8x1mS7vtvP6F9S/e/q4O6MApwSHj8hNLGfw==",
|
||||
"dependencies": {
|
||||
"@floating-ui/dom": "^1.7.6",
|
||||
"@floating-ui/utils": "^0.2.11",
|
||||
"vue-demi": ">=0.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/vue/node_modules/vue-demi": {
|
||||
"version": "0.14.10",
|
||||
"resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz",
|
||||
"integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==",
|
||||
"hasInstallScript": true,
|
||||
"bin": {
|
||||
"vue-demi-fix": "bin/vue-demi-fix.js",
|
||||
"vue-demi-switch": "bin/vue-demi-switch.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@vue/composition-api": "^1.0.0-rc.1",
|
||||
"vue": "^3.0.0-0 || ^2.6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@vue/composition-api": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@internationalized/date": {
|
||||
"version": "3.12.4",
|
||||
"resolved": "https://registry.npmjs.org/@internationalized/date/-/date-3.12.4.tgz",
|
||||
"integrity": "sha512-M1dEn4c1U1HsSlaVR8upZtSqvXrTkHDfv18H01uCSJyjVLDxnBR38v/fMxecmlwXKR4i9HeZcmgQAPE6A+aGJQ==",
|
||||
"dependencies": {
|
||||
"@swc/helpers": "^0.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@internationalized/number": {
|
||||
"version": "3.6.8",
|
||||
"resolved": "https://registry.npmjs.org/@internationalized/number/-/number-3.6.8.tgz",
|
||||
"integrity": "sha512-8UmMFia46DUt+k97zKd9fKWXcWHR+k8ae3eYzILETuT2KbIvLyOfac7zesw+sJdRAAZ7Q9pM1Mk22aXp2LD0Ig==",
|
||||
"dependencies": {
|
||||
"@swc/helpers": "^0.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
@@ -474,6 +550,14 @@
|
||||
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
|
||||
"devOptional": true
|
||||
},
|
||||
"node_modules/@swc/helpers": {
|
||||
"version": "0.5.23",
|
||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
|
||||
"integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.2.tgz",
|
||||
@@ -489,6 +573,255 @@
|
||||
"tailwindcss": "4.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
|
||||
"integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"detect-libc": "^2.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"lightningcss-android-arm64": "1.32.0",
|
||||
"lightningcss-darwin-arm64": "1.32.0",
|
||||
"lightningcss-darwin-x64": "1.32.0",
|
||||
"lightningcss-freebsd-x64": "1.32.0",
|
||||
"lightningcss-linux-arm-gnueabihf": "1.32.0",
|
||||
"lightningcss-linux-arm64-gnu": "1.32.0",
|
||||
"lightningcss-linux-arm64-musl": "1.32.0",
|
||||
"lightningcss-linux-x64-gnu": "1.32.0",
|
||||
"lightningcss-linux-x64-musl": "1.32.0",
|
||||
"lightningcss-win32-arm64-msvc": "1.32.0",
|
||||
"lightningcss-win32-x64-msvc": "1.32.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-android-arm64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",
|
||||
"integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-darwin-arm64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",
|
||||
"integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-darwin-x64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",
|
||||
"integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-freebsd-x64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",
|
||||
"integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm-gnueabihf": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",
|
||||
"integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm64-gnu": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",
|
||||
"integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm64-musl": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",
|
||||
"integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-linux-x64-gnu": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",
|
||||
"integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-linux-x64-musl": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",
|
||||
"integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-win32-arm64-msvc": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",
|
||||
"integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/node/node_modules/lightningcss-win32-x64-msvc": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
|
||||
"integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/parcel"
|
||||
}
|
||||
},
|
||||
"node_modules/@tailwindcss/oxide": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.2.tgz",
|
||||
@@ -731,6 +1064,30 @@
|
||||
"vite": "^5.2.0 || ^6 || ^7 || ^8"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/virtual-core": {
|
||||
"version": "3.17.11",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.17.11.tgz",
|
||||
"integrity": "sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/vue-virtual": {
|
||||
"version": "3.13.39",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/vue-virtual/-/vue-virtual-3.13.39.tgz",
|
||||
"integrity": "sha512-AG8sI+6nfrDvN6ixuHJL9LaJTf3//0V5VITZYW3UOaIuSVexnEzsbMu4LH/JhMfRTxwhUXPnLqkl1DlzkZbRtg==",
|
||||
"dependencies": {
|
||||
"@tanstack/virtual-core": "3.17.11"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^2.7.0 || ^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.3",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
|
||||
@@ -764,6 +1121,11 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/web-bluetooth": {
|
||||
"version": "0.0.21",
|
||||
"resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
|
||||
"integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA=="
|
||||
},
|
||||
"node_modules/@vitejs/plugin-vue": {
|
||||
"version": "6.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.7.tgz",
|
||||
@@ -962,6 +1324,41 @@
|
||||
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.39.tgz",
|
||||
"integrity": "sha512-l1rrBtBfTnmxvtsvdQDXltUUy8S1Y+ZaqdfUzmAnJkTd8Z8rv5v/ytW+TKiqEOWyHPoqtPlNFSs0lhRmYVSHVA=="
|
||||
},
|
||||
"node_modules/@vueuse/core": {
|
||||
"version": "14.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.4.0.tgz",
|
||||
"integrity": "sha512-X4WHz1HlCzCBoYXesUkifzzWBAcZgXG8Fi5iNPQg/epdzOB3gu8Fawj3hvuwYR1nGcXGnvxwYYcUC/71++svtQ==",
|
||||
"dependencies": {
|
||||
"@types/web-bluetooth": "^0.0.21",
|
||||
"@vueuse/metadata": "14.4.0",
|
||||
"@vueuse/shared": "14.4.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vueuse/metadata": {
|
||||
"version": "14.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.4.0.tgz",
|
||||
"integrity": "sha512-swx/255R6JyHZFJhx845iz5CRWDZdCfvkZOpACWc5+c5WHcG24mv8gUT1WIdFQaHt6dq79rvILd9QnCWiyVm9g==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
}
|
||||
},
|
||||
"node_modules/@vueuse/shared": {
|
||||
"version": "14.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.4.0.tgz",
|
||||
"integrity": "sha512-JRgY90Sz8DDtPMsaDflvPMp9xYk69JZAmbuDvAquUVXKr2gEjqtzGNTTthLfckH0BzBqvnu31gb4a8TGLRe79g==",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.17.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
|
||||
@@ -1012,6 +1409,17 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/aria-hidden": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz",
|
||||
"integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/ast-kit": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/ast-kit/-/ast-kit-2.2.0.tgz",
|
||||
@@ -1191,6 +1599,11 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/defu": {
|
||||
"version": "6.1.7",
|
||||
"resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz",
|
||||
"integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
@@ -1542,10 +1955,15 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsqr": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/jsqr/-/jsqr-1.4.0.tgz",
|
||||
"integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A=="
|
||||
},
|
||||
"node_modules/lightningcss": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
|
||||
"integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
|
||||
"integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"detect-libc": "^2.0.3"
|
||||
@@ -1558,23 +1976,23 @@
|
||||
"url": "https://opencollective.com/parcel"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"lightningcss-android-arm64": "1.32.0",
|
||||
"lightningcss-darwin-arm64": "1.32.0",
|
||||
"lightningcss-darwin-x64": "1.32.0",
|
||||
"lightningcss-freebsd-x64": "1.32.0",
|
||||
"lightningcss-linux-arm-gnueabihf": "1.32.0",
|
||||
"lightningcss-linux-arm64-gnu": "1.32.0",
|
||||
"lightningcss-linux-arm64-musl": "1.32.0",
|
||||
"lightningcss-linux-x64-gnu": "1.32.0",
|
||||
"lightningcss-linux-x64-musl": "1.32.0",
|
||||
"lightningcss-win32-arm64-msvc": "1.32.0",
|
||||
"lightningcss-win32-x64-msvc": "1.32.0"
|
||||
"lightningcss-android-arm64": "1.33.0",
|
||||
"lightningcss-darwin-arm64": "1.33.0",
|
||||
"lightningcss-darwin-x64": "1.33.0",
|
||||
"lightningcss-freebsd-x64": "1.33.0",
|
||||
"lightningcss-linux-arm-gnueabihf": "1.33.0",
|
||||
"lightningcss-linux-arm64-gnu": "1.33.0",
|
||||
"lightningcss-linux-arm64-musl": "1.33.0",
|
||||
"lightningcss-linux-x64-gnu": "1.33.0",
|
||||
"lightningcss-linux-x64-musl": "1.33.0",
|
||||
"lightningcss-win32-arm64-msvc": "1.33.0",
|
||||
"lightningcss-win32-x64-msvc": "1.33.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-android-arm64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",
|
||||
"integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
|
||||
"integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1592,9 +2010,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-darwin-arm64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",
|
||||
"integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
|
||||
"integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1612,9 +2030,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-darwin-x64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",
|
||||
"integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
|
||||
"integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1632,9 +2050,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-freebsd-x64": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",
|
||||
"integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
|
||||
"integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1652,9 +2070,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-arm-gnueabihf": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",
|
||||
"integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
|
||||
"integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -1672,9 +2090,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-arm64-gnu": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",
|
||||
"integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
|
||||
"integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1692,9 +2110,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-arm64-musl": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",
|
||||
"integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
|
||||
"integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1712,9 +2130,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-x64-gnu": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",
|
||||
"integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
|
||||
"integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1732,9 +2150,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-linux-x64-musl": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",
|
||||
"integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
|
||||
"integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1752,9 +2170,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-win32-arm64-msvc": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",
|
||||
"integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
|
||||
"integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1772,9 +2190,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss-win32-x64-msvc": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
|
||||
"integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
|
||||
"version": "1.33.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
|
||||
"integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1929,6 +2347,11 @@
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/ohash": {
|
||||
"version": "2.0.12",
|
||||
"resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz",
|
||||
"integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw=="
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
@@ -2098,6 +2521,30 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/reka-ui": {
|
||||
"version": "2.10.4",
|
||||
"resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.10.4.tgz",
|
||||
"integrity": "sha512-kbS5GAbkHkYj0EVKAg5ZPEPndhBjeUFSa1Aq5m5ftQwyHnB1v5tw8X6fcwfKH/ry3StPXblMWM1DW82MVS71cw==",
|
||||
"dependencies": {
|
||||
"@floating-ui/dom": "^1.6.13",
|
||||
"@floating-ui/vue": "^1.1.6",
|
||||
"@internationalized/date": "^3.5.0",
|
||||
"@internationalized/number": "^3.5.0",
|
||||
"@tanstack/vue-virtual": "^3.12.0",
|
||||
"@vueuse/core": "^14.1.0",
|
||||
"@vueuse/shared": "^14.1.0",
|
||||
"aria-hidden": "^1.2.4",
|
||||
"defu": "^6.1.5",
|
||||
"ohash": "^2.0.11"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/zernonia"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": ">= 3.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
@@ -2232,9 +2679,7 @@
|
||||
"node_modules/tslib": {
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"dev": true,
|
||||
"optional": true
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
|
||||
@@ -5,15 +5,17 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build": "vite build && node scripts/postbuild-css.mjs",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.13.6",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"jsqr": "^1.4.0",
|
||||
"lucide-vue-next": "^1.0.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.4",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"vue": "^3.5.30",
|
||||
"vue-router": "^5.0.4"
|
||||
@@ -23,6 +25,7 @@
|
||||
"@types/node": "^26.0.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^6.0.5",
|
||||
"lightningcss": "^1.33.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^8.0.1",
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// 老内核兼容后处理(构建期执行):
|
||||
//
|
||||
// 背景:Tailwind v4 的产物大量使用较新的 CSS 能力,老内核(国产浏览器/微信内置
|
||||
// 内核,实测线上存在 Chrome 78/85/91/97)会丢弃不认识的部分,表现为“只剩基础
|
||||
// 元素、没有样式”。逐项处理如下:
|
||||
//
|
||||
// ① CSS 级联层 @layer(Chrome 99+):老内核不认识该 at-rule,会把整块工具类
|
||||
// 直接丢弃 —— 这是“无样式”的主因,必须剥离;
|
||||
// ② oklch() 颜色(Chrome 111+):降级为十六进制色值(lightningcss);
|
||||
// ③ :where() 选择器(Chrome 88+):其特异性为 0 的设计依赖较新引擎,
|
||||
// 老内核整条规则丢弃;解包为等价选择器(保持原有特异性位置);
|
||||
// ④ JS 语法(可选链等)由 vite build.target 统一降级,不在此处处理。
|
||||
//
|
||||
// 处理顺序:先解包 :where(lightningcss 不处理它),再整体按目标内核降级,
|
||||
// 最后剥离 @layer 并做完整性校验。
|
||||
import { readdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { transform } from 'lightningcss'
|
||||
|
||||
const assetsDir = resolve(process.cwd(), 'dist/assets')
|
||||
|
||||
// lightningcss 目标版本:Chrome 78(微信 XWEB 常见下限,线上真实存在)
|
||||
const TARGETS = {
|
||||
chrome: 78 << 16,
|
||||
safari: 12 << 16,
|
||||
ios_saf: 12 << 16,
|
||||
android: 78 << 16,
|
||||
}
|
||||
|
||||
/** 解包 :where(...) → 内部选择器(老内核不支持 :where,会整条丢弃规则) */
|
||||
function unwrapWhere(css) {
|
||||
let out = ''
|
||||
let i = 0
|
||||
while (i < css.length) {
|
||||
const m = css.indexOf(':where(', i)
|
||||
if (m < 0) {
|
||||
out += css.slice(i)
|
||||
break
|
||||
}
|
||||
// 避免误伤字符串/注释中的 :where(本项目 CSS 产物中无此类内容,保守处理仍做括号配对)
|
||||
out += css.slice(i, m)
|
||||
let depth = 0
|
||||
let end = -1
|
||||
for (let k = m + 6; k < css.length; k++) {
|
||||
if (css[k] === '(') depth++
|
||||
else if (css[k] === ')') {
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
end = k
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (end < 0) {
|
||||
out += css.slice(m)
|
||||
break
|
||||
}
|
||||
out += css.slice(m + 7, end) // 去掉 ":where(" 与末端 ")"
|
||||
i = end + 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 剥离 @layer 包裹:保留块内规则与顺序(层叠仍由源顺序 + 选择器优先级决定) */
|
||||
function unwrapCascadeLayers(css) {
|
||||
let out = css
|
||||
const re = /@layer\s+[A-Za-z0-9_,\s-]+?\{/g
|
||||
|
||||
// 反复处理,兼容理论上的嵌套 @layer
|
||||
for (let pass = 0; pass < 8; pass++) {
|
||||
const heads = []
|
||||
let m
|
||||
re.lastIndex = 0
|
||||
while ((m = re.exec(out)) !== null) {
|
||||
heads.push({ head: m.index, bodyStart: re.lastIndex - 1 })
|
||||
}
|
||||
if (heads.length === 0) break
|
||||
|
||||
for (let i = heads.length - 1; i >= 0; i--) {
|
||||
const { head, bodyStart } = heads[i]
|
||||
let depth = 0
|
||||
let end = -1
|
||||
for (let k = bodyStart; k < out.length; k++) {
|
||||
if (out[k] === '{') depth++
|
||||
else if (out[k] === '}') {
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
end = k
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (end < 0) continue
|
||||
out = out.slice(0, head) + out.slice(bodyStart + 1, end) + out.slice(end + 1)
|
||||
}
|
||||
}
|
||||
|
||||
// 移除裸 @layer 声明语句(如 `@layer components;`)
|
||||
out = out.replace(/@layer\s+[A-Za-z0-9_,\s-]+;/g, '')
|
||||
return out
|
||||
}
|
||||
|
||||
/** 校验:括号闭合(剥离过程中出现异常时立刻失败,避免把坏 CSS 发上线) */
|
||||
function assertBalanced(css, file) {
|
||||
let depth = 0
|
||||
for (const ch of css) {
|
||||
if (ch === '{') depth++
|
||||
else if (ch === '}') {
|
||||
depth--
|
||||
if (depth < 0) throw new Error(`[postbuild-css] ${file} 括号不闭合(出现多余的 })`)
|
||||
}
|
||||
}
|
||||
if (depth !== 0) throw new Error(`[postbuild-css] ${file} 括号不闭合(缺少 ${depth} 个 })`)
|
||||
}
|
||||
|
||||
const files = (await readdir(assetsDir)).filter((f) => f.endsWith('.css'))
|
||||
if (files.length === 0) {
|
||||
throw new Error('[postbuild-css] dist/assets 下未找到 CSS 产物,构建流程异常')
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const path = join(assetsDir, file)
|
||||
const src = await readFile(path)
|
||||
|
||||
// ① 解包 :where()(lightningcss 不会处理它,需先做)
|
||||
let prepared = Buffer.from(unwrapWhere(src.toString('utf8')))
|
||||
const whereCount = (src.toString('utf8').match(/:where\(/g) || []).length
|
||||
|
||||
// ② 按目标内核降级(oklch 等新颜色函数 → 老内核可识别的色值)
|
||||
const { code } = transform({
|
||||
filename: file,
|
||||
code: prepared,
|
||||
minify: true,
|
||||
targets: TARGETS,
|
||||
})
|
||||
let out = code.toString()
|
||||
|
||||
// ③ 剥离 @layer 包裹
|
||||
out = unwrapCascadeLayers(out)
|
||||
|
||||
// ④ 兜底校验:任何一项残留都说明处理逻辑失效,直接失败避免上线残缺样式
|
||||
if (/@layer/.test(out)) throw new Error(`[postbuild-css] ${file} 仍残留 @layer`)
|
||||
if (/oklch\(/.test(out)) throw new Error(`[postbuild-css] ${file} 仍残留 oklch(`)
|
||||
if (/:where\(/.test(out)) throw new Error(`[postbuild-css] ${file} 仍残留 :where(`)
|
||||
assertBalanced(out, file)
|
||||
|
||||
await writeFile(path, out)
|
||||
console.log(
|
||||
`[postbuild-css] ${file}: ${src.length} → ${out.length} bytes` +
|
||||
`(解包 ${whereCount} 处 :where + 降级颜色 + 剥离 @layer)`
|
||||
)
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
import { watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import UpdateChecker from '@/components/UpdateChecker.vue'
|
||||
import ConfirmHost from '@/components/ConfirmHost.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const { toasts, removeToast } = useMessage()
|
||||
@@ -26,9 +28,15 @@ watch(
|
||||
<template>
|
||||
<router-view />
|
||||
|
||||
<!-- 全局新版本检测(无 UI,发现更新时弹窗提示刷新) -->
|
||||
<UpdateChecker />
|
||||
|
||||
<!-- 全局确认/提示弹窗宿主(confirmDialog / alertDialog) -->
|
||||
<ConfirmHost />
|
||||
|
||||
<!-- 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"
|
||||
|
||||
@@ -138,6 +138,10 @@ export interface CDKCode {
|
||||
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
|
||||
@@ -242,6 +246,7 @@ export interface Announcement {
|
||||
targetUserId: number | null
|
||||
forcePopup: boolean
|
||||
loopPopup: boolean
|
||||
isPinned: boolean
|
||||
createdBy: number
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
@@ -261,6 +266,7 @@ export interface CreateAnnouncementParams {
|
||||
targetUserId?: number
|
||||
forcePopup: boolean
|
||||
loopPopup: boolean
|
||||
isPinned: boolean
|
||||
}
|
||||
|
||||
export interface ReadUser {
|
||||
@@ -368,3 +374,45 @@ 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 / leave_apply / leave_report
|
||||
title: string
|
||||
realTitle: string
|
||||
isSuccess: boolean
|
||||
errorMessage: string
|
||||
createdAt: string
|
||||
deleted: boolean // 用户已在客户端删除(软删除),仅后台可见
|
||||
source: number // 1=签到/查寝 2=请假/销假(两表 id 独立自增,列表 key 需组合)
|
||||
}
|
||||
|
||||
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()}`)
|
||||
}
|
||||
|
||||
@@ -33,6 +33,20 @@ export function getUnreadCount() {
|
||||
return api.get<{ data: UnreadCount }>('/announcements/unread-count')
|
||||
}
|
||||
|
||||
// ======== 置顶公告(打卡页顶部横向滚动) ========
|
||||
|
||||
export interface PinnedAnnouncement {
|
||||
id: number
|
||||
title: string
|
||||
content: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/** 获取当前用户可见的置顶公告 */
|
||||
export function getPinnedAnnouncements() {
|
||||
return api.get<{ data: PinnedAnnouncement[] }>('/announcements/pinned')
|
||||
}
|
||||
|
||||
// ======== 公告聚合信息 ========
|
||||
|
||||
export interface PopupAnnouncement {
|
||||
|
||||
@@ -94,6 +94,79 @@ export function login(params: LoginParams) {
|
||||
return api.post<{ data: LoginResult }>('/auth/login', params)
|
||||
}
|
||||
|
||||
/** MFA 可用验证方式(登录返回 4281 后由后端给出) */
|
||||
export interface MFAAuthMethod {
|
||||
/** reAuthType 编码:3=短信 4=企业微信 5=今日校园 11=邮箱 12=钉钉 13=WeLink 15=公众号 */
|
||||
type: string
|
||||
/** 展示名(如「今日校园验证码」) */
|
||||
name: string
|
||||
/** 是否为页面默认选中项 */
|
||||
default?: boolean
|
||||
}
|
||||
|
||||
/** MFA 发送验证码参数(用户选定验证方式后调用) */
|
||||
export interface MFASendCodeParams {
|
||||
mfaToken: string
|
||||
reAuthType: string
|
||||
}
|
||||
|
||||
/** MFA 验证码发送结果 */
|
||||
export interface MFASendCodeResult {
|
||||
/** 收码目标(手机号等,可能带掩码) */
|
||||
mobile?: string
|
||||
/** 可再次发送的倒计时秒数 */
|
||||
codeTime?: number
|
||||
}
|
||||
|
||||
/** 发送多因子认证验证码(用户选择验证方式后调用)
|
||||
* 业务码约定(HTTP 200):0=发送成功进入输入阶段;4283=会话过期需重新登录;4284=发送失败可重试 */
|
||||
export function sendMFACode(params: MFASendCodeParams) {
|
||||
return api.post<{ code: number; message: string; data?: MFASendCodeResult }>(
|
||||
'/auth/login/mfa/send',
|
||||
params
|
||||
)
|
||||
}
|
||||
|
||||
/** MFA 验证码提交参数 */
|
||||
export interface MFAVerifyParams {
|
||||
mfaToken: string
|
||||
code: string
|
||||
}
|
||||
|
||||
/** 提交多因子认证验证码(登录返回 code 4281 后调用)
|
||||
* 业务码约定(HTTP 200):0=成功;4281=需MFA;4282=验证码错误可重试;4283=会话过期需重新登录 */
|
||||
export function verifyMFA(params: MFAVerifyParams) {
|
||||
return api.post<{ code: number; message: string; data?: LoginResult }>('/auth/login/mfa', params)
|
||||
}
|
||||
|
||||
// ---- 手机号验证码登录(无需选择学校:tenantId 由登录响应返回) ----
|
||||
|
||||
/** 发送手机短信验证码(需图片验证码) */
|
||||
export function sendSmsCode(phone: string, captchaId: string, captchaCode: string) {
|
||||
return api.post<{ data: { countdown: number; tipMsg: string } }>('/auth/sms/send', {
|
||||
phone,
|
||||
captchaId,
|
||||
captchaCode,
|
||||
})
|
||||
}
|
||||
|
||||
/** 手机号 + 短信验证码登录(需图片验证码) */
|
||||
export function smsLogin(
|
||||
phone: string,
|
||||
code: string,
|
||||
captchaId: string,
|
||||
captchaCode: string,
|
||||
inviteCode?: string,
|
||||
) {
|
||||
return api.post<{ code: number; message: string; data?: LoginResult }>('/auth/sms/login', {
|
||||
phone,
|
||||
code,
|
||||
captchaId,
|
||||
captchaCode,
|
||||
inviteCode,
|
||||
})
|
||||
}
|
||||
|
||||
/** 刷新 token */
|
||||
export function refreshToken(refreshToken: string) {
|
||||
return api.post<{ data: { accessToken: string; refreshToken: string } }>(
|
||||
@@ -121,6 +194,11 @@ export function getDeviceStatus(token: string) {
|
||||
})
|
||||
}
|
||||
|
||||
/** 随机生成设备码并绑定到当前账号(个人中心「随机」按钮,需连续两次风险确认) */
|
||||
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<{
|
||||
@@ -135,7 +213,7 @@ export function redeemCDK(code: string, captchaId: string, captchaCode: string)
|
||||
|
||||
/** 当前用户 VIP 信息(是否 VIP、到期时间、系统配置单价) */
|
||||
export function getVipInfo() {
|
||||
return api.get<{ data: { isVip: boolean; vipExpireAt: string; vipPrice: string } }>(
|
||||
return api.get<{ data: { isVip: boolean; vipExpireAt: string; vipWeekPrice: string; vipMonthPrice: string; vipPrice: string } }>(
|
||||
'/cdk/vip-info'
|
||||
)
|
||||
}
|
||||
@@ -150,12 +228,15 @@ export interface TaskInfo {
|
||||
realTitle: string
|
||||
signWid: string
|
||||
signInstanceWid: string
|
||||
formData: string
|
||||
/** 列表接口不再返回(可能达 MB 级);需要时走 getTaskSavedForm */
|
||||
formData?: string
|
||||
taskStatus: string
|
||||
errorMessage: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
matchStatus: string
|
||||
/** 服务端预计算的「必填但为空」字段标题,替代前端解析 formData */
|
||||
missingFields?: string[]
|
||||
}
|
||||
|
||||
export interface TaskTitleItem {
|
||||
@@ -191,11 +272,16 @@ export function createTask(params: { taskType: string; title: string; realTitle:
|
||||
return api.post<{ data: TaskInfo }>('/task/create', params)
|
||||
}
|
||||
|
||||
/** 获取任务表单 */
|
||||
/** 获取任务表单(从今日校园重新拉取模板,不含用户已填值) */
|
||||
export function getTaskForm(id: number) {
|
||||
return api.get<{ data: { formItems: FormItem[]; realTitle: string; isPhoto: boolean } }>(`/task/form/${id}`)
|
||||
}
|
||||
|
||||
/** 获取该任务已保存的表单内容(编辑弹窗预填用,避免列表接口携带大字段) */
|
||||
export function getTaskSavedForm(id: number) {
|
||||
return api.get<{ data: { formData: string } }>(`/task/form-data/${id}`)
|
||||
}
|
||||
|
||||
/** 保存任务表单 */
|
||||
export function saveTaskForm(id: number, formData: FormItem[]) {
|
||||
return api.post(`/task/form/${id}`, { formData })
|
||||
|
||||
@@ -69,11 +69,15 @@ api.interceptors.response.use(
|
||||
}
|
||||
|
||||
// 用户端 401 且不是刷新/登录的请求,尝试刷新 token
|
||||
// 注意:登录类接口(含手机号验证码登录 /auth/sms/*)返回的 401 表示「登录凭据错误」,
|
||||
// 与「登录态过期」语义不同,必须排除,否则会被误判为 token 过期 →
|
||||
// 清空登录态并跳回 /login(表现为:登录失败却无任何提示、页面被重置)。
|
||||
if (
|
||||
error.response?.status === 401 &&
|
||||
!originalRequest._retry &&
|
||||
!originalRequest.url?.includes('/auth/refresh') &&
|
||||
!originalRequest.url?.includes('/auth/login') &&
|
||||
!originalRequest.url?.includes('/auth/sms/') &&
|
||||
!originalRequest.url?.includes('/report-failed-login')
|
||||
) {
|
||||
originalRequest._retry = true
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
import api from './index'
|
||||
|
||||
// ======== 类型定义 ========
|
||||
|
||||
/** 学校规定的销假位置(详情 reportPlaces) */
|
||||
export interface LeaveReportPlace {
|
||||
wid: string
|
||||
address: string
|
||||
longitude: string
|
||||
latitude: string
|
||||
/** 允许范围半径(米):销假定位需在该位置半径内 */
|
||||
radius: string
|
||||
/** 位置设置人 */
|
||||
counName: string
|
||||
}
|
||||
|
||||
/** 待销假记录(含规定销假位置与销假开关) */
|
||||
export interface LeaveItem {
|
||||
id: string
|
||||
leaveType: string
|
||||
reason: string
|
||||
createTime: string
|
||||
actEndTime: string
|
||||
status: string
|
||||
/** 状态文案(服务端权威映射,新套学校返回;旧套为空时前端本地映射兜底) */
|
||||
statusText?: string
|
||||
/** 学校规定的销假位置列表;为空时需用户手动输入 */
|
||||
reportPlaces: LeaveReportPlace[]
|
||||
/** 该请假类型销假是否需要选择审批人(leaveType.reportApplyFlow=1) */
|
||||
reportApplyFlow: boolean
|
||||
/** 该请假类型销假是否允许上传图片(leaveType.enableAttach=1) */
|
||||
enableAttach: boolean
|
||||
}
|
||||
|
||||
/** 销假可选审批人 */
|
||||
export interface LeaveApprover {
|
||||
userWid: string
|
||||
userId: string
|
||||
userName: string
|
||||
}
|
||||
|
||||
/** 销假执行参数 */
|
||||
export interface ExecuteLeaveParams {
|
||||
leaveId: string
|
||||
longitude: string
|
||||
latitude: string
|
||||
address: string
|
||||
imageUrl?: string
|
||||
/** reportApplyFlow=true 时必填 */
|
||||
approverWid?: string
|
||||
}
|
||||
|
||||
/** 销假日志 */
|
||||
export interface LeaveLog {
|
||||
id: number
|
||||
userId: number
|
||||
leaveId: string
|
||||
title: string
|
||||
schoolName: string
|
||||
/** report=销假 / apply=请假 */
|
||||
action: string
|
||||
isSuccess: boolean
|
||||
errorMessage: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
/** 请假类型(已合并 queryLeaveTypeCfg 的权威开关) */
|
||||
export interface LeaveType {
|
||||
code: number
|
||||
name: string
|
||||
/** 1=必须离校 */
|
||||
mustOut: number
|
||||
/** 1=需要选择审批人 */
|
||||
needApproval: number
|
||||
/** 1=允许上传图片附件 */
|
||||
enableAttach: number
|
||||
/** 请假原因最少字数 */
|
||||
reasonWordLimit: number
|
||||
/** 附件数量上限 */
|
||||
attachmentNumberLimit: number
|
||||
/** 1=当前类型不可用 */
|
||||
disableTime: number
|
||||
/** 单次最长可请假天数(0=不限) */
|
||||
limitDay: number
|
||||
/** 1=需先手写承诺书签名后提交(新套学校) */
|
||||
requireSign: number
|
||||
}
|
||||
|
||||
/** 请假执行参数 */
|
||||
export interface ExecuteLeaveApplyParams {
|
||||
leaveType: number
|
||||
startTime: string
|
||||
endTime: string
|
||||
leaveReason: string
|
||||
outStatus: boolean
|
||||
urgencyMobile?: string
|
||||
address?: string
|
||||
detailAddress?: string
|
||||
longitude: string
|
||||
latitude: string
|
||||
locationAddr: string
|
||||
/** 附件图片 URL 列表(最多 4 张且不超学校上限;后端兼容旧 imageUrl 单图字段) */
|
||||
imageUrls?: string[]
|
||||
approverWid?: string
|
||||
approverId?: string
|
||||
approverName?: string
|
||||
/** 抄送人(非必填;候选取自审批人列表) */
|
||||
ccUsers?: LeaveApprover[]
|
||||
/** 手写承诺书签名图 URL(requireSign=1 的类型必填) */
|
||||
signatureUrl?: string
|
||||
}
|
||||
|
||||
// ======== API ========
|
||||
|
||||
/** 获取今日校园待销假列表(实时请求,附带规定销假位置与开关) */
|
||||
export function getPendingLeaves() {
|
||||
return api.get<{ data: LeaveItem[] }>('/leave/pending-list')
|
||||
}
|
||||
|
||||
/** 获取销假可选审批人(reportApplyFlow=true 的请假类型使用) */
|
||||
export function getLeaveApprovers(leaveId: string) {
|
||||
return api.post<{ data: LeaveApprover[] }>('/leave/approvers', { leaveId })
|
||||
}
|
||||
|
||||
/** 获取请假类型列表(含权威开关:needApproval/enableAttach/reasonWordLimit 等) */
|
||||
export function getLeaveTypes() {
|
||||
return api.get<{ data: LeaveType[] }>('/leave/types')
|
||||
}
|
||||
|
||||
/** 获取请假可选审批人(needApproval=1 的类型,需先选类型与起止时间) */
|
||||
export function getApplyApprovers(params: { leaveType: number; startTime: string; endTime: string }) {
|
||||
return api.post<{ data: LeaveApprover[] }>('/leave/apply-approvers', params)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行请假申请(POST + SSE 流式事件,与销假执行体验一致)。
|
||||
* 事件流:connecting → submitting → success / task_error
|
||||
*/
|
||||
export function executeLeaveApplySSE(params: ExecuteLeaveApplyParams, callbacks: {
|
||||
onConnecting?: () => void
|
||||
onSubmitting?: () => void
|
||||
onSuccess?: (data: any) => void
|
||||
onError?: (message: string, data?: any) => void
|
||||
}): AbortController {
|
||||
return leaveSSE('/leave/apply', params, callbacks)
|
||||
}
|
||||
|
||||
/** 获取销假日志列表 */
|
||||
export function getLeaveLogs() {
|
||||
return api.get<{ data: LeaveLog[] }>('/leave/logs')
|
||||
}
|
||||
|
||||
/** 删除销假日志 */
|
||||
export function deleteLeaveLog(id: number) {
|
||||
return api.delete(`/leave/logs/${id}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行销假(POST + SSE 流式事件,与打卡执行体验一致)。
|
||||
* 事件流:connecting → fetching_detail → submitting → success / task_error
|
||||
* 返回 AbortController,可用于中断(如关闭弹窗时)。
|
||||
*/
|
||||
export function executeLeaveSSE(params: ExecuteLeaveParams, callbacks: {
|
||||
onConnecting?: () => void
|
||||
onFetchingDetail?: () => void
|
||||
onSubmitting?: () => void
|
||||
onSuccess?: (data: any) => void
|
||||
onError?: (message: string, data?: any) => void
|
||||
}): AbortController {
|
||||
return leaveSSE('/leave/execute', params, callbacks)
|
||||
}
|
||||
|
||||
/**
|
||||
* 请假/销假共用的 SSE 执行封装。
|
||||
* 事件流:connecting → (fetching_detail) → submitting → success / task_error
|
||||
*/
|
||||
function leaveSSE(path: string, params: object, callbacks: {
|
||||
onConnecting?: () => void
|
||||
onFetchingDetail?: () => void
|
||||
onSubmitting?: () => void
|
||||
onSuccess?: (data: any) => void
|
||||
onError?: (message: string, data?: any) => void
|
||||
}): AbortController {
|
||||
const controller = new AbortController()
|
||||
|
||||
;(async () => {
|
||||
let finished = false
|
||||
const finish = (fn?: (...args: any[]) => void, ...args: any[]) => {
|
||||
if (finished) return
|
||||
finished = true
|
||||
fn?.(...args)
|
||||
}
|
||||
try {
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || '/api'
|
||||
const token = localStorage.getItem('access_token') || ''
|
||||
const res = await fetch(`${baseUrl}${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + token,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(params),
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
// HTTP 错误:服务端以 JSON 返回(参数校验/鉴权等,非 SSE 阶段)
|
||||
if (!res.ok || !res.body) {
|
||||
let msg = '连接失败,请检查网络'
|
||||
try {
|
||||
const j = await res.json()
|
||||
if (j?.message) msg = j.message
|
||||
} catch { /* 保留默认提示 */ }
|
||||
finish(callbacks.onError, msg, { message: msg })
|
||||
return
|
||||
}
|
||||
|
||||
const reader = res.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buf = ''
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
buf += decoder.decode(value, { stream: true })
|
||||
|
||||
// 按空行切分 SSE 事件块(event: xxx\ndata: xxx\n\n)
|
||||
let sep: number
|
||||
while ((sep = buf.indexOf('\n\n')) >= 0) {
|
||||
const chunk = buf.slice(0, sep)
|
||||
buf = buf.slice(sep + 2)
|
||||
|
||||
let event = 'message'
|
||||
const dataLines: string[] = []
|
||||
for (const line of chunk.split('\n')) {
|
||||
if (line.startsWith('event:')) {
|
||||
event = line.slice(6).trim()
|
||||
} else if (line.startsWith('data:')) {
|
||||
dataLines.push(line.slice(5).trim())
|
||||
}
|
||||
}
|
||||
let data: any = {}
|
||||
const dataRaw = dataLines.join('\n')
|
||||
try { data = dataRaw ? JSON.parse(dataRaw) : {} } catch { /* 容忍非 JSON data */ }
|
||||
|
||||
switch (event) {
|
||||
case 'connecting':
|
||||
callbacks.onConnecting?.()
|
||||
break
|
||||
case 'fetching_detail':
|
||||
callbacks.onFetchingDetail?.()
|
||||
break
|
||||
case 'submitting':
|
||||
callbacks.onSubmitting?.()
|
||||
break
|
||||
case 'success':
|
||||
finish(callbacks.onSuccess, data)
|
||||
break
|
||||
case 'task_error':
|
||||
finish(callbacks.onError, data?.message || '执行失败', data)
|
||||
break
|
||||
}
|
||||
if (finished) break
|
||||
}
|
||||
if (finished) break
|
||||
}
|
||||
|
||||
// 流结束但未收到任何结果事件:视为异常中断
|
||||
finish(callbacks.onError, '连接中断,请重试')
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'AbortError') return // 主动取消,不回调
|
||||
finish(callbacks.onError, e?.message || '连接失败,请检查网络')
|
||||
}
|
||||
})()
|
||||
|
||||
return controller
|
||||
}
|
||||
@@ -15,6 +15,8 @@ export interface AdminTicketListItem extends TicketListItem {
|
||||
username: string
|
||||
realName: string
|
||||
schoolName: string
|
||||
/** 用户是否已删除该工单(软删除);管理端仍可见 */
|
||||
deleted?: boolean
|
||||
}
|
||||
|
||||
export interface TicketMessageRes {
|
||||
@@ -37,6 +39,8 @@ export interface TicketDetail {
|
||||
schoolName?: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
/** 用户是否已删除该工单(软删除);管理端仍可查看 */
|
||||
deleted?: boolean
|
||||
messages: TicketMessageRes[]
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
/* 基于 class 的暗色变体:html.dark 时启用 dark:* 工具类
|
||||
(切换逻辑见 composables/useTheme.ts,按浏览器系统时间自动切换) */
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme {
|
||||
--color-background: #f5f5f5;
|
||||
--color-foreground: #1a1a1a;
|
||||
@@ -60,3 +64,76 @@ body {
|
||||
box-shadow: none;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
* 暗色主题(html.dark,由 useTheme.ts 按系统时间自动切换)
|
||||
*
|
||||
* Tailwind v4 的颜色工具类均引用 --color-* CSS 变量(bg-white →
|
||||
* var(--color-white)),此处整体覆盖变量即可让全站 1000+ 处硬编码
|
||||
* 颜色类自动适配,无需逐个加 dark: 变体。深彩色(blue-500 等
|
||||
* 品牌/状态色)与遮罩黑保持原值。彩底上的白色元素用类名级规则恢复。
|
||||
* ============================================================ */
|
||||
.dark {
|
||||
/* —— 基础调色板:白与灰阶(越浅的灰在暗色下越亮,保持层次感)—— */
|
||||
--color-white: #1e1e2a;
|
||||
--color-gray-50: #232331;
|
||||
--color-gray-100: #2a2a3a;
|
||||
--color-gray-200: #36364a;
|
||||
--color-gray-300: #474763;
|
||||
--color-gray-400: #8f8fab;
|
||||
--color-gray-500: #a5a5c3;
|
||||
--color-gray-600: #bcbcd6;
|
||||
--color-gray-700: #d4d4e6;
|
||||
--color-gray-800: #e5e5f0;
|
||||
--color-gray-900: #ededf6;
|
||||
--color-gray-950: #f4f4fa;
|
||||
/* —— 彩色浅底 → 对应暗色调 —— */
|
||||
--color-blue-50: #1c2a4d;
|
||||
--color-blue-100: #243660;
|
||||
--color-red-50: #3d1c28;
|
||||
--color-red-100: #522534;
|
||||
--color-rose-50: #3a1c2b;
|
||||
--color-rose-100: #4d2539;
|
||||
--color-green-50: #173224;
|
||||
--color-green-100: #1f4430;
|
||||
--color-amber-50: #3a2f16;
|
||||
--color-amber-100: #4d3f1e;
|
||||
--color-purple-100: #322552;
|
||||
/* —— 语义 token(ui/ 组件与语义类使用)—— */
|
||||
--color-background: #15151f;
|
||||
--color-foreground: #ededf6;
|
||||
--color-card: #1e1e2a;
|
||||
--color-card-foreground: #ededf6;
|
||||
--color-secondary: #262636;
|
||||
--color-secondary-foreground: #d4d4e6;
|
||||
--color-muted: #262636;
|
||||
--color-muted-foreground: #9c9cb8;
|
||||
--color-accent: #262636;
|
||||
--color-accent-foreground: #d4d4e6;
|
||||
--color-border: #33334a;
|
||||
--color-input: #3a3a55;
|
||||
--color-ring: #3b82f6;
|
||||
}
|
||||
|
||||
/* —— 彩底上的白色元素恢复纯白(--color-white 已被覆盖为卡片暗色)—— */
|
||||
.dark .text-white { color: #fff; }
|
||||
.dark .text-white\/95 { color: rgb(255 255 255 / 0.95); }
|
||||
.dark .text-white\/80 { color: rgb(255 255 255 / 0.8); }
|
||||
.dark .text-white\/70 { color: rgb(255 255 255 / 0.7); }
|
||||
.dark .bg-white\/15 { background-color: rgb(255 255 255 / 0.15); }
|
||||
.dark .bg-white\/20 { background-color: rgb(255 255 255 / 0.2); }
|
||||
.dark .bg-white\/25 { background-color: rgb(255 255 255 / 0.25); }
|
||||
.dark .hover\:bg-white\/25:hover { background-color: rgb(255 255 255 / 0.25); }
|
||||
.dark .ring-white\/30 { --tw-ring-color: rgb(255 255 255 / 0.3); }
|
||||
|
||||
/* —— 全局容器暗色 —— */
|
||||
.dark body {
|
||||
background-color: #0d0d14;
|
||||
}
|
||||
.dark #app {
|
||||
background-color: #15151f;
|
||||
box-shadow: 0 0 20px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.dark #app.admin-mode {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
// ConfirmHost —— 全局确认/提示弹窗宿主,挂在 App.vue,全站仅此一个实例。
|
||||
//
|
||||
// 与 useConfirm 的单例状态配合:任何组件 await confirmDialog()/alertDialog() 都会
|
||||
// 反映到这里渲染的 AppDialog 上。视觉对齐 HomeView「确认再次打卡 / 签到次数不足」那类
|
||||
// 居中弹窗(圆形图标底 + 标题 + 灰色说明 + 双按钮)。
|
||||
import AppDialog from '@/components/ui/dialog/AppDialog.vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { AlertTriangle, CircleAlert } from 'lucide-vue-next'
|
||||
import { useConfirm } from '@/composables/useConfirm'
|
||||
|
||||
const { state, respond } = useConfirm()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppDialog
|
||||
:open="state?.open || false"
|
||||
variant="center"
|
||||
z-class="z-[300]"
|
||||
panel-class="w-[85%] sm:max-w-sm"
|
||||
:fade="true"
|
||||
:title="state?.title || '提示'"
|
||||
@update:open="(v: boolean) => { if (!v) respond(false) }"
|
||||
>
|
||||
<div v-if="state" class="p-6 text-center">
|
||||
<div
|
||||
:class="[
|
||||
'w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-4',
|
||||
state.danger ? 'bg-red-100' : 'bg-blue-100',
|
||||
]"
|
||||
>
|
||||
<AlertTriangle v-if="state.danger" class="w-7 h-7 text-red-500" />
|
||||
<CircleAlert v-else class="w-7 h-7 text-blue-500" />
|
||||
</div>
|
||||
<h3 class="text-base font-semibold text-gray-900 mb-2">{{ state.title }}</h3>
|
||||
<p
|
||||
v-if="state.content"
|
||||
class="text-sm text-gray-500 leading-relaxed whitespace-pre-wrap"
|
||||
>
|
||||
{{ state.content }}
|
||||
</p>
|
||||
<div class="mt-5 flex gap-2">
|
||||
<Button
|
||||
v-if="!state.alertOnly"
|
||||
variant="outline"
|
||||
class="flex-1 h-10 text-sm font-medium"
|
||||
@click="respond(false)"
|
||||
>
|
||||
{{ state.cancelText || '取消' }}
|
||||
</Button>
|
||||
<Button
|
||||
:variant="state.danger ? 'destructive' : 'default'"
|
||||
class="flex-1 h-10 text-sm font-medium"
|
||||
@click="respond(true)"
|
||||
>
|
||||
{{ state.confirmText || '确定' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AppDialog>
|
||||
</template>
|
||||
@@ -58,21 +58,28 @@ const steps: GuideStep[] = [
|
||||
'新用户注册即送奖励积分,邀请好友也能赚积分。\n积分满 1 后,点这里「兑换」按钮即可换成签到次数,1 积分 = 1 次签到,可重复兑换。',
|
||||
},
|
||||
{
|
||||
tab: 'home',
|
||||
title: '新建每日签到任务',
|
||||
targets: ['[data-guide="home-create-task"]'],
|
||||
descByKind: () => '点击蓝色的「+ 新的签到任务」按钮,选择任务名称(如 晚签到),然后填好对应签到信息并保存,任务就创建好了。',
|
||||
tab: 'profile',
|
||||
title: '先绑定设备码',
|
||||
targets: ['[data-guide="profile-device-code"]'],
|
||||
descByKind: () =>
|
||||
'签到任务依赖设备码执行。到这一栏点「重新绑定」用手机扫码授权,或点「随机」直接生成设备码。\n注意:随机设备码与真实手机不一致,执行签到时现有手机会提示「频繁切换设备」无法签到,建议优先扫码授权。',
|
||||
},
|
||||
{
|
||||
tab: 'home',
|
||||
title: '执行任务,自动签到',
|
||||
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',
|
||||
@@ -90,6 +97,13 @@ const steps: GuideStep[] = [
|
||||
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])
|
||||
@@ -105,12 +119,40 @@ const resolvedKind = computed(() => {
|
||||
return null
|
||||
})
|
||||
|
||||
const guideDesc = computed(() => current.value.descByKind(resolvedKind.value))
|
||||
const guideDesc = computed(() => {
|
||||
// 第四步命中示例卡自身的执行按钮(mock 场景)时的专属文案
|
||||
const el = curTarget.value
|
||||
if (step.value === 3 && el && resolvedKind.value === 'home-task-exec' && el.closest('.guide-root')) {
|
||||
return '点这张示例卡片右侧的「执行」按钮,即可开始今天的签到,之后每天无需再手动操作。'
|
||||
}
|
||||
return current.value.descByKind(resolvedKind.value)
|
||||
})
|
||||
|
||||
// 无真实任务时(第三步/第四步):展示示例任务卡引导;
|
||||
// 第四步升级命中示例卡自身的执行按钮(位于 guide-root 内)时仍属 mock 场景
|
||||
const mockMode = computed(() => {
|
||||
if (!props.show || (step.value !== 2 && step.value !== 3)) return false
|
||||
if (resolvedKind.value === 'home-task-empty') return true
|
||||
const el = curTarget.value
|
||||
return !!(el && resolvedKind.value === 'home-task-exec' && el.closest('.guide-root'))
|
||||
})
|
||||
// 示例卡锚定在空态区(空态元素 rect);不跟随升级后的按钮 rect,避免卡片随高亮框错位
|
||||
const mockAnchor = ref<{ top: number; left: number; width: number; height: number } | null>(null)
|
||||
|
||||
function syncMockAnchor() {
|
||||
const anchor = document.querySelector('[data-guide="home-task-empty"]')
|
||||
if (anchor) {
|
||||
const r = anchor.getBoundingClientRect()
|
||||
mockAnchor.value = { top: r.top, left: r.left, width: r.width, height: r.height }
|
||||
}
|
||||
}
|
||||
watch(mockMode, (v) => {
|
||||
if (v) syncMockAnchor()
|
||||
else mockAnchor.value = null
|
||||
})
|
||||
|
||||
// 第三步且用户没有任何真实任务(命中空态卡)时:展示一张示例任务卡引导
|
||||
const mockMode = computed(() => props.show && step.value === 2 && resolvedKind.value === 'home-task-empty')
|
||||
const mockCardStyle = computed(() => {
|
||||
const r = holeRect.value
|
||||
const r = mockAnchor.value
|
||||
if (!r) return null
|
||||
return {
|
||||
top: `${Math.max(0, Math.round(r.top + (r.height - 76) / 2))}px`,
|
||||
@@ -321,6 +363,8 @@ function startLayoutPolling() {
|
||||
stopLayoutPolling()
|
||||
pollTimer = window.setInterval(() => {
|
||||
if (!props.show) return
|
||||
// mock 示例卡锚点持续校正(布局/异步数据导致空态区位置变化时卡片跟随)
|
||||
if (mockMode.value) syncMockAnchor()
|
||||
const el = curTarget.value
|
||||
if (el && el.isConnected && document.contains(el)) {
|
||||
measure(el)
|
||||
@@ -491,7 +535,13 @@ const bubbleStyle = computed(() => {
|
||||
<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="执行签到">
|
||||
<button
|
||||
type="button"
|
||||
:data-guide="step === 3 ? 'home-task-exec' : undefined"
|
||||
class="w-8 h-8 flex items-center justify-center rounded-lg bg-blue-500 text-white shadow-sm flex-shrink-0"
|
||||
:class="step === 3 ? 'guide-mock-pulse' : ''"
|
||||
title="执行签到"
|
||||
>
|
||||
<Play class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -577,6 +627,22 @@ const bubbleStyle = computed(() => {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 第四步:示例卡执行按钮脉冲强调(引导点击开始打卡) */
|
||||
.guide-mock-pulse {
|
||||
animation: guide-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
@keyframes guide-pulse {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.55);
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 0 0 8px rgba(59, 130, 246, 0);
|
||||
transform: scale(1.08);
|
||||
}
|
||||
}
|
||||
|
||||
.guide-bubble {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
<script setup lang="ts">
|
||||
// 版本更新检测:定时拉取首页 index.html,比对 JS/CSS 资源文件名。
|
||||
// 后端每次发布都会重新打包,文件名带内容 hash;资源名变化即说明有新版本,
|
||||
// 弹窗提示用户刷新(确认后立即 reload,拿到新 index.html 与新资源)。
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
import AppDialog from '@/components/ui/dialog/AppDialog.vue'
|
||||
|
||||
const CHECK_INTERVAL = 5 * 60 * 1000 // 5 分钟
|
||||
const FIRST_DELAY = 30 * 1000 // 启动 30 秒后首次检查(避免与首屏请求抢占)
|
||||
const DISMISS_KEY = 'xz_update_dismissed_version'
|
||||
|
||||
const showUpdate = ref(false)
|
||||
// 当前页面加载时使用的资源名集合(相对路径)
|
||||
const currentAssets = new Set<string>()
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let stopped = false
|
||||
let prompting = false
|
||||
let pendingVersion = ''
|
||||
|
||||
/** 从 HTML 文本中提取 /assets/ 下的 js/css 资源名 */
|
||||
function extractAssets(html: string): Set<string> {
|
||||
const out = new Set<string>()
|
||||
const re = /\/assets\/[A-Za-z0-9_.-]+\.(?:js|css)/g
|
||||
let m: RegExpExecArray | null
|
||||
while ((m = re.exec(html)) !== null) {
|
||||
out.add(m[0])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 读取当前页面已加载的资源名(由 script/link 标签推导,等同当前构建版本) */
|
||||
function collectCurrentAssets(): Set<string> {
|
||||
const out = new Set<string>()
|
||||
document.querySelectorAll<HTMLScriptElement>('script[src]').forEach((el) => {
|
||||
const m = el.src.match(/\/assets\/[A-Za-z0-9_.-]+\.(?:js|css)/)
|
||||
if (m) out.add(m[0])
|
||||
})
|
||||
document.querySelectorAll<HTMLLinkElement>('link[href]').forEach((el) => {
|
||||
const m = el.href.match(/\/assets\/[A-Za-z0-9_.-]+\.(?:js|css)/)
|
||||
if (m) out.add(m[0])
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
async function checkUpdate() {
|
||||
if (stopped || prompting) return
|
||||
try {
|
||||
// 版本探测必须绕过 HTTP 缓存(后端 index.html 有 1 小时 MaxAge),故带时间戳参数
|
||||
const res = await fetch(`/?_v=${Date.now()}`, {
|
||||
cache: 'no-store',
|
||||
headers: { 'Cache-Control': 'no-cache', Pragma: 'no-cache' },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const html = await res.text()
|
||||
const latest = extractAssets(html)
|
||||
if (latest.size === 0 || currentAssets.size === 0) return
|
||||
|
||||
// 任一新资源名未在当前页面出现 → 有新版本
|
||||
const hasNew = [...latest].some((a) => !currentAssets.has(a))
|
||||
if (!hasNew) return
|
||||
|
||||
const newVersion = [...latest].join(',')
|
||||
if (sessionStorage.getItem(DISMISS_KEY) === newVersion) return // 本会话已提示过
|
||||
|
||||
pendingVersion = newVersion
|
||||
prompting = true
|
||||
showUpdate.value = true
|
||||
} catch {
|
||||
// 网络异常静默跳过,等待下一轮
|
||||
} finally {
|
||||
prompting = false
|
||||
}
|
||||
}
|
||||
|
||||
function schedule(delay: number) {
|
||||
if (stopped) return
|
||||
timer = setTimeout(async () => {
|
||||
await checkUpdate()
|
||||
schedule(CHECK_INTERVAL)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
/** 用户确认刷新:立即重载(拿新版本资源) */
|
||||
function reloadNow() {
|
||||
showUpdate.value = false
|
||||
location.reload()
|
||||
}
|
||||
|
||||
/** 用户选择稍后:记录本次版本,本会话内不再重复提示 */
|
||||
function dismiss() {
|
||||
showUpdate.value = false
|
||||
if (pendingVersion) sessionStorage.setItem(DISMISS_KEY, pendingVersion)
|
||||
}
|
||||
|
||||
/** 弹窗关闭统一入口(按钮 / 点遮罩 / Esc 都走这里),关闭即视为「稍后」 */
|
||||
function onDialogOpenChange(value: boolean) {
|
||||
if (value) {
|
||||
showUpdate.value = true
|
||||
return
|
||||
}
|
||||
dismiss()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
currentAssets.clear()
|
||||
collectCurrentAssets().forEach((a) => currentAssets.add(a))
|
||||
schedule(FIRST_DELAY)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
stopped = true
|
||||
if (timer) clearTimeout(timer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 新版本提示弹窗:标题 + 说明 + 稍后/立即刷新 -->
|
||||
<AppDialog
|
||||
:open="showUpdate"
|
||||
variant="center"
|
||||
z-class="z-[200]"
|
||||
panel-class="w-[86%] max-w-[340px] p-5"
|
||||
title="发现新版本"
|
||||
description="网站已更新,刷新后即可使用最新功能,是否立即刷新?"
|
||||
@update:open="onDialogOpenChange"
|
||||
>
|
||||
<h3 class="text-base font-semibold text-gray-900 mb-2">发现新版本</h3>
|
||||
<p class="text-sm text-gray-500 leading-relaxed mb-5">
|
||||
网站已更新,刷新后即可使用最新功能,是否立即刷新?
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
class="flex-1 py-2.5 rounded-lg border border-gray-200 text-sm text-gray-600 active:bg-gray-50"
|
||||
@click="dismiss"
|
||||
>
|
||||
稍后
|
||||
</button>
|
||||
<button
|
||||
class="flex-1 py-2.5 rounded-lg bg-blue-600 text-white text-sm font-medium active:bg-blue-700"
|
||||
@click="reloadNow"
|
||||
>
|
||||
立即刷新
|
||||
</button>
|
||||
</div>
|
||||
</AppDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,187 @@
|
||||
<script setup lang="ts">
|
||||
// AppDialog —— 全站统一弹窗封装(reka-ui Dialog 底座)。
|
||||
//
|
||||
// 目的:用 Dialog 原语换取焦点捕获、Esc 关闭、body 滚动锁定、aria 语义与 Portal 渲染,
|
||||
// 同时保持与现有手写弹窗一致的视觉(白色卡片 + 圆角 + 遮罩)。
|
||||
//
|
||||
// 结构说明(与 reka 的约定):
|
||||
// - DialogContent(DismissableLayer)本身不带定位样式,只作为焦点/事件容器;
|
||||
// - 真正的「铺满全屏的定位层」是它内部的 div:pointer-events:none 让点击穿透到底下的
|
||||
// DialogOverlay,从而「点遮罩关闭」才能成立(点在自己身上不算 outside,不会关闭);
|
||||
// - 面板单独 pointer-events:auto,恢复可交互。
|
||||
// 这与项目里 MobileLayout 手写弹窗的 pointer-events 处理方式一致。
|
||||
//
|
||||
// 面板基础样式(w-full / bg-white / flex flex-col / overflow-hidden / max-h-[85vh] / shadow-xl)
|
||||
// 与原手写弹窗一致;**原弹窗没有阴影时**必须在 panelClass 里显式传 shadow-none
|
||||
// (经 tailwind-merge 覆盖,实测 cn('shadow-xl','shadow-none') → 'shadow-none'),
|
||||
// 否则会凭空多出阴影(LeaveView 等页面的面板原本无阴影)。
|
||||
//
|
||||
// 形态(variant):
|
||||
// - sheet(默认):移动端贴底、桌面端居中(≈原 items-end sm:items-center),
|
||||
// 面板默认 rounded-t-2xl sm:rounded-2xl,调用方在 panelClass 里给 sm:max-w-sm;
|
||||
// - center:始终居中(≈原 items-center),调用方在 panelClass 里给宽度与内边距。
|
||||
//
|
||||
// 典型用法:
|
||||
// <AppDialog v-model:open="show" variant="center" z-class="z-[200]"
|
||||
// panel-class="w-[86%] max-w-[340px] p-5" title="发现新版本" :description="desc">
|
||||
// <!-- 面板内容(视觉标题由业务自己渲染,组件内的 Title/Description 仅供读屏) -->
|
||||
// </AppDialog>
|
||||
//
|
||||
// 关闭控制:dismissable=false 时拦截遮罩点击与 Esc(对应「执行中不允许关闭」);
|
||||
// 关闭动作统一经 update:open 冒泡,调用方按需守卫。
|
||||
import {
|
||||
DialogRoot,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from 'reka-ui'
|
||||
import type { FocusOutsideEvent, PointerDownOutsideEvent } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
open: boolean
|
||||
/** sheet=移动端贴底/桌面居中;center=始终居中 */
|
||||
variant?: 'sheet' | 'center'
|
||||
/** 层级类(遮罩与定位层同层,如 z-[60]) */
|
||||
zClass?: string
|
||||
/** 遮罩浓度类(默认 bg-black/40,部分弹窗用 /50) */
|
||||
overlayClass?: string
|
||||
/**
|
||||
* 淡入淡出(默认关)。
|
||||
* 注意:reka-ui 的 Presence 只识别 CSS animation(读 computed animation-name),
|
||||
* **不识别 Vue <Transition> 的 class 过渡**,且 DialogContent 根是 fragment
|
||||
* 无法被 <Transition> 包裹。故原手写弹窗的 `<Transition name="fade">`(0.2s 透明度)
|
||||
* 需由本组件的 CSS animation 承接(见文件末尾 style)。
|
||||
*/
|
||||
fade?: boolean
|
||||
/** 定位层附加类(如 px-6 给居中弹窗留边距) */
|
||||
wrapperClass?: string
|
||||
/** 面板附加类(宽度/内边距/圆角等,经 tailwind-merge 合并) */
|
||||
panelClass?: string
|
||||
/** false 时禁止点遮罩与 Esc 关闭(执行中场景) */
|
||||
dismissable?: boolean
|
||||
/** 读屏标题;视觉标题由业务在默认插槽自渲染 */
|
||||
title?: string
|
||||
/** 读屏描述(缺省回退为标题,避免 aria-describedby 指向不存在的节点) */
|
||||
description?: string
|
||||
}>(),
|
||||
{
|
||||
variant: 'sheet',
|
||||
zClass: 'z-50',
|
||||
overlayClass: 'bg-black/40',
|
||||
wrapperClass: '',
|
||||
panelClass: '',
|
||||
dismissable: true,
|
||||
fade: false,
|
||||
title: '提示',
|
||||
description: '',
|
||||
},
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:open', value: boolean): void
|
||||
}>()
|
||||
|
||||
function onOpenChange(value: boolean) {
|
||||
emit('update:open', value)
|
||||
}
|
||||
|
||||
// reka 以 CustomEvent 派发,preventDefault 即阻止 dismiss(见 DismissableLayer 实现)
|
||||
function onInteractOutside(e: PointerDownOutsideEvent | FocusOutsideEvent) {
|
||||
if (!props.dismissable) e.preventDefault()
|
||||
}
|
||||
|
||||
function onEscapeKeyDown(e: KeyboardEvent) {
|
||||
if (!props.dismissable) e.preventDefault()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogRoot :open="props.open" @update:open="onOpenChange">
|
||||
<DialogPortal>
|
||||
<!-- 遮罩:reka 会自动加 pointer-events:auto 并响应「点遮罩关闭」 -->
|
||||
<DialogOverlay
|
||||
:class="cn('fixed inset-0', props.overlayClass, props.zClass, props.fade && 'app-dialog-fade')"
|
||||
/>
|
||||
|
||||
<!-- 事件/焦点容器:本身不承载布局(零尺寸),只作为焦点/事件容器。
|
||||
fade 类必须挂在这里:它会 forward 到 role="dialog" 那个根节点,也就是
|
||||
Presence 追踪的节点;Presence 靠监听该节点自身的 animationend 判断离场
|
||||
结束,动画挂到子节点上则读不到,会直接卸载(瞬间消失)。
|
||||
fade 时额外加 relative + 同层 z:淡入淡出的 opacity<1 会让本节点形成
|
||||
z-index:0 的层叠上下文,届时内部 fixed 面板被困其中,而 overlay(正 z)
|
||||
会在其后绘制、把面板盖住 0.2s 再突然跳回;加上定位与 zClass 后本节点
|
||||
与 overlay 同级且 DOM 在后 → 始终在上。不加 fade 时保持原样(零改动)。 -->
|
||||
<DialogContent
|
||||
:class="cn('outline-none', props.fade && ['relative', props.zClass, 'app-dialog-fade'])"
|
||||
@interact-outside="onInteractOutside"
|
||||
@escape-key-down="onEscapeKeyDown"
|
||||
>
|
||||
<!-- 定位层:铺满全屏但点击穿透(点空白处落到遮罩上才能关闭) -->
|
||||
<div
|
||||
:class="
|
||||
cn(
|
||||
'fixed inset-0 flex justify-center',
|
||||
props.variant === 'sheet' ? 'items-end sm:items-center' : 'items-center',
|
||||
props.wrapperClass,
|
||||
props.zClass,
|
||||
)
|
||||
"
|
||||
style="pointer-events: none"
|
||||
>
|
||||
<!-- 面板:视觉与手写弹窗一致;pointer-events 恢复以便交互 -->
|
||||
<div
|
||||
:class="
|
||||
cn(
|
||||
'relative w-full bg-white flex flex-col overflow-hidden shadow-xl max-h-[85vh]',
|
||||
props.variant === 'sheet' ? 'rounded-t-2xl sm:rounded-2xl' : 'rounded-2xl',
|
||||
props.panelClass,
|
||||
)
|
||||
"
|
||||
style="pointer-events: auto"
|
||||
>
|
||||
<!-- 读屏标题/描述(视觉标题由业务自渲染,这里不重复显示) -->
|
||||
<DialogTitle class="sr-only">{{ props.title }}</DialogTitle>
|
||||
<DialogDescription class="sr-only">{{ props.description || props.title }}</DialogDescription>
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</DialogPortal>
|
||||
</DialogRoot>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
/* 淡入淡出(fade=true 时启用)。
|
||||
*
|
||||
* 为什么不用 <Transition>:reka-ui 的 Presence 通过读取 computed style 的
|
||||
* animation-name 判断「是否正在动画」,只认 CSS animation;Vue 的 <Transition>
|
||||
* 是 class 过渡,Presence 感知不到,会导致离场动画被直接跳过(瞬间消失)。
|
||||
* 因此这里用 CSS animation + reka 输出的 data-state="open|closed" 实现进出场。
|
||||
* 非 scoped:内容经 DialogPortal 传送到 body,且需同时作用于 overlay 与 content。 */
|
||||
.app-dialog-fade[data-state='open'] {
|
||||
animation: app-dialog-fade-in 0.2s ease;
|
||||
}
|
||||
.app-dialog-fade[data-state='closed'] {
|
||||
animation: app-dialog-fade-out 0.2s ease;
|
||||
}
|
||||
@keyframes app-dialog-fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes app-dialog-fade-out {
|
||||
from {
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,76 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
// 全局确认/提示弹窗服务。
|
||||
//
|
||||
// 背景:项目此前用浏览器原生 confirm()/alert()(v1.2.55「弹窗统一化」只迁移了手写
|
||||
// role="dialog" 元素,原生调用不在其扫描范围内,故遗留至今)。这里提供与 useMessage
|
||||
// 同风格的模块级单例服务:任意组件调用 confirmDialog/alertDialog 即弹出统一的 AppDialog。
|
||||
//
|
||||
// 用法:
|
||||
// const ok = await confirmDialog({ title: '删除任务', content: '确定要删除此任务吗?', danger: true })
|
||||
// if (!ok) return
|
||||
// await alertDialog({ title: '保存失败', content: msg })
|
||||
|
||||
export interface ConfirmOptions {
|
||||
/** 标题(同时作为读屏标题) */
|
||||
title: string
|
||||
/** 说明文字(可选,支持换行) */
|
||||
content?: string
|
||||
/** 确认按钮文案,默认「确定」 */
|
||||
confirmText?: string
|
||||
/** 取消按钮文案,默认「取消」 */
|
||||
cancelText?: string
|
||||
/** true 时用警示样式(红色图标 + destructive 确认按钮),用于删除等破坏性操作 */
|
||||
danger?: boolean
|
||||
/** true 时只显示确认按钮(提示框形态,对应原 alert) */
|
||||
alertOnly?: boolean
|
||||
}
|
||||
|
||||
interface ConfirmState extends ConfirmOptions {
|
||||
open: boolean
|
||||
}
|
||||
|
||||
const state = ref<ConfirmState | null>(null)
|
||||
let resolver: ((ok: boolean) => void) | null = null
|
||||
|
||||
/**
|
||||
* 弹出确认框,返回用户是否确认(取消/遮罩/Esc 均为 false)。
|
||||
* 同一时刻只保留一个确认框:若上一个尚未结清,先以 false 结清,避免 Promise 悬挂。
|
||||
*/
|
||||
export function confirmDialog(options: ConfirmOptions): Promise<boolean> {
|
||||
if (resolver) {
|
||||
const prev = resolver
|
||||
resolver = null
|
||||
prev(false)
|
||||
}
|
||||
state.value = { ...options, open: true }
|
||||
return new Promise<boolean>((resolve) => {
|
||||
resolver = resolve
|
||||
})
|
||||
}
|
||||
|
||||
/** 弹出纯提示框(单按钮,对应原 alert),用户关闭后 resolve(true) */
|
||||
export function alertDialog(
|
||||
options: Omit<ConfirmOptions, 'cancelText' | 'alertOnly'>,
|
||||
): Promise<boolean> {
|
||||
return confirmDialog({
|
||||
...options,
|
||||
alertOnly: true,
|
||||
confirmText: options.confirmText || '我知道了',
|
||||
})
|
||||
}
|
||||
|
||||
export function useConfirm() {
|
||||
function respond(ok: boolean) {
|
||||
state.value = state.value ? { ...state.value, open: false } : null
|
||||
const r = resolver
|
||||
resolver = null
|
||||
r?.(ok)
|
||||
// 等离场动画结束再清空内容,避免关闭过程中文字/图标突然消失
|
||||
setTimeout(() => {
|
||||
if (state.value && !state.value.open) state.value = null
|
||||
}, 200)
|
||||
}
|
||||
|
||||
return { state, respond }
|
||||
}
|
||||
@@ -30,6 +30,7 @@ export function useMessage() {
|
||||
success: (msg: string) => addToast('success', msg),
|
||||
error: (msg: string) => addToast('error', msg),
|
||||
info: (msg: string) => addToast('info', msg),
|
||||
warning: (msg: string) => addToast('info', msg),
|
||||
removeToast,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// 亮暗主题:按浏览器系统时间自动切换(18:00–次日 06:00 为暗色,其余亮色)。
|
||||
// 首屏防闪烁由 index.html 内联脚本完成(同一规则,渲染前预设 .dark);
|
||||
// 本模块在应用启动后接管:立即校正一次,并按分钟轮询,跨过时间阈值时自动切换。
|
||||
// 切换载体为 <html> 上的 .dark class,配合 globals.css 中的暗色变量板生效。
|
||||
|
||||
const DARK_START_HOUR = 18
|
||||
const DARK_END_HOUR = 6
|
||||
const THEME_COLOR_LIGHT = '#f5f5f5'
|
||||
const THEME_COLOR_DARK = '#15151f'
|
||||
|
||||
export function isDarkTime(date: Date = new Date()): boolean {
|
||||
const h = date.getHours()
|
||||
return h >= DARK_START_HOUR || h < DARK_END_HOUR
|
||||
}
|
||||
|
||||
/** 应用当前时段对应主题,返回是否处于暗色 */
|
||||
export function applyTheme(): boolean {
|
||||
const dark = isDarkTime()
|
||||
document.documentElement.classList.toggle('dark', dark)
|
||||
document
|
||||
.querySelector('meta[name="theme-color"]')
|
||||
?.setAttribute('content', dark ? THEME_COLOR_DARK : THEME_COLOR_LIGHT)
|
||||
return dark
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
/** 应用入口调用:立即应用主题并启动分钟级自动切换 */
|
||||
export function initTheme(): void {
|
||||
applyTheme()
|
||||
if (timer) return
|
||||
timer = setInterval(applyTheme, 60_000)
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
|
||||
import { ref, computed, watch, onMounted, onUnmounted, provide } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { Home, User, Bell, X, CheckCircle, ChevronDown, MessageSquare } from 'lucide-vue-next'
|
||||
import { CalendarCheck2, CalendarX2, User, Bell, X, CheckCircle, ChevronDown, MessageSquare, Sparkles, BookOpen } from 'lucide-vue-next'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import AppDialog from '@/components/ui/dialog/AppDialog.vue'
|
||||
import GuideOverlay from '@/components/GuideOverlay.vue'
|
||||
import * as authApi from '@/api/auth'
|
||||
import * as announceApi from '@/api/announcement'
|
||||
@@ -19,7 +20,9 @@ const userInfo = ref<UserInfo | null>(null)
|
||||
const avatarFailed = ref(false)
|
||||
|
||||
const tabs = [
|
||||
{ name: 'home', label: '首页', icon: Home },
|
||||
{ name: 'home', label: '打卡', icon: CalendarCheck2 },
|
||||
{ name: 'leave', label: '请/销假', icon: CalendarX2 },
|
||||
{ name: 'course', label: '网课', icon: BookOpen },
|
||||
{ name: 'profile', label: '个人中心', icon: User },
|
||||
]
|
||||
|
||||
@@ -98,6 +101,15 @@ function closeGuide() {
|
||||
}
|
||||
}
|
||||
|
||||
// 个人中心「再次查看引导」入口:重播新手引导。GuideOverlay 对 show 重新置真会自动
|
||||
// 回到第一步;关闭时走 closeGuide 正常上报完成,顺带把未完成账号的引导版本补齐,
|
||||
// 语义与首次观看一致,故不沿用 guideForced 的"关闭不写库"逻辑。
|
||||
function restartGuide() {
|
||||
showGuide.value = true
|
||||
loadInviteRewardRules()
|
||||
}
|
||||
provide('restartGuide', restartGuide)
|
||||
|
||||
/** 数据库判定:guideVersion 未达当前引导版本的用户需展示引导 */
|
||||
function needGuide(user: UserInfo): boolean {
|
||||
return (user.guideVersion || '') !== GUIDE_VERSION
|
||||
@@ -212,10 +224,7 @@ onMounted(async () => {
|
||||
const data = res.data.data
|
||||
userInfo.value = data
|
||||
|
||||
if (!data.mobileCode) {
|
||||
router.replace('/bind-device')
|
||||
return
|
||||
}
|
||||
// 未绑定设备码不再强制跳转绑定页(新建任务时会在入口处弹窗引导)
|
||||
// 新手引导:数据库判定该用户未看过当前版本引导则展示(跨设备一致);
|
||||
// 本次若来自 ?guide=1 强播则优先展示(guideForced 已消费,下次加载不再生效)
|
||||
if (guideForced.value || needGuide(data)) {
|
||||
@@ -245,8 +254,8 @@ onUnmounted(() => {
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- 顶部用户信息栏(仅在首页显示) -->
|
||||
<div v-if="activeTab === 'home'" class="flex-shrink-0 bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 pt-3 pb-3">
|
||||
<!-- 顶部用户信息栏(首页与请/销假页显示,两页保持一致) -->
|
||||
<div v-if="activeTab === 'home' || activeTab === 'leave'" class="flex-shrink-0 bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 pt-3 pb-3">
|
||||
<div v-if="userInfo" class="flex items-center gap-3">
|
||||
<div class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center flex-shrink-0 overflow-hidden">
|
||||
<img v-show="userInfo.avatar && !avatarFailed" :src="userInfo.avatar" class="w-full h-full object-cover" @error="avatarFailed = true" />
|
||||
@@ -256,7 +265,7 @@ onUnmounted(() => {
|
||||
<p class="font-semibold text-sm truncate">{{ userInfo.realName || userInfo.username }}</p>
|
||||
<p class="text-xs text-white/70 truncate">{{ userInfo.schoolName }}</p>
|
||||
</div>
|
||||
<!-- 公告铃铛(仅首页显示) -->
|
||||
<!-- 公告铃铛(首页与请/销假页均显示) -->
|
||||
<button class="relative w-9 h-9 rounded-full bg-white/15 flex items-center justify-center hover:bg-white/25 transition-colors flex-shrink-0" @click="openAnnouncementPanel">
|
||||
<Bell class="w-5 h-5 text-white" />
|
||||
<span v-if="totalUnread > 0" class="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center leading-none">{{ totalUnread > 99 ? '99+' : totalUnread }}</span>
|
||||
@@ -271,8 +280,8 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 中间内容区(可滚动) -->
|
||||
<div class="flex-1 overflow-y-auto bg-[#f5f5f5]">
|
||||
<!-- 中间内容区(可滚动;bg-background 语义类,亮暗主题自动切换) -->
|
||||
<div class="flex-1 overflow-y-auto bg-background">
|
||||
<router-view />
|
||||
</div>
|
||||
|
||||
@@ -290,193 +299,197 @@ onUnmounted(() => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- ======== 公告面板遮罩 ======== -->
|
||||
<transition name="fade">
|
||||
<div v-if="showAnnPanel" class="fixed inset-0 z-50 bg-black/50" @click="showAnnPanel = false" />
|
||||
</transition>
|
||||
<!-- ======== 公告面板(遮罩 + 底部面板) ======== -->
|
||||
<AppDialog
|
||||
:open="showAnnPanel"
|
||||
overlay-class="bg-black/50"
|
||||
panel-class="sm:max-w-sm max-h-[80vh] shadow-2xl"
|
||||
:fade="true"
|
||||
title="通知"
|
||||
@update:open="(v: boolean) => { if (!v) showAnnPanel = false }"
|
||||
>
|
||||
<!-- 拖拽指示条 -->
|
||||
<div class="flex justify-center pt-2.5 pb-1 flex-shrink-0">
|
||||
<div class="w-9 h-1 rounded-full bg-gray-300" />
|
||||
</div>
|
||||
|
||||
<!-- ======== 公告底部面板 ======== -->
|
||||
<transition name="slide-up">
|
||||
<div
|
||||
v-if="showAnnPanel"
|
||||
class="fixed inset-0 z-50 flex items-end sm:items-center justify-center pointer-events-none"
|
||||
>
|
||||
<div class="absolute inset-0 pointer-events-auto" @click="showAnnPanel = false" />
|
||||
<div class="relative w-full sm:max-w-sm max-h-[80vh] bg-white sm:rounded-2xl rounded-t-2xl shadow-2xl flex flex-col overflow-hidden pointer-events-auto">
|
||||
<!-- 拖拽指示条 -->
|
||||
<div class="flex justify-center pt-2.5 pb-1 flex-shrink-0">
|
||||
<div class="w-9 h-1 rounded-full bg-gray-300" />
|
||||
<!-- 标题栏 -->
|
||||
<div class="flex items-center justify-between px-5 py-2 flex-shrink-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-7 h-7 rounded-lg bg-blue-100 flex items-center justify-center">
|
||||
<Bell class="w-4 h-4 text-blue-500" />
|
||||
</div>
|
||||
<span class="font-semibold text-gray-900 text-sm">通知</span>
|
||||
<span v-if="totalUnread > 0" class="text-[10px] px-2 py-0.5 rounded-full bg-red-50 text-red-500 font-medium border border-red-100">{{ totalUnread }} 条未读</span>
|
||||
</div>
|
||||
<button class="w-7 h-7 rounded-full hover:bg-gray-100 flex items-center justify-center transition-colors" @click="showAnnPanel = false">
|
||||
<X class="w-4 h-4 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 标题栏 -->
|
||||
<div class="flex items-center justify-between px-5 py-2 flex-shrink-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-7 h-7 rounded-lg bg-blue-100 flex items-center justify-center">
|
||||
<Bell class="w-4 h-4 text-blue-500" />
|
||||
<!-- 分隔线 -->
|
||||
<div class="mx-5 border-t border-gray-100 flex-shrink-0" />
|
||||
|
||||
<!-- 通知列表 -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-2">
|
||||
<!-- ===== 公告分区 ===== -->
|
||||
<div v-if="announcements.length > 0" class="mb-1">
|
||||
<p class="text-[10px] font-medium text-gray-400 uppercase tracking-wider mb-2 mt-1">公告</p>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-for="item in announcements"
|
||||
:key="'ann-'+item.id"
|
||||
class="rounded-xl p-3.5 transition-all duration-200 cursor-pointer border"
|
||||
:class="item.isRead
|
||||
? 'bg-white border-gray-100 hover:border-gray-200'
|
||||
: 'bg-blue-50/50 border-blue-100 hover:border-blue-200'"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="mt-0.5 flex-shrink-0">
|
||||
<div v-if="!item.isRead" class="w-2.5 h-2.5 rounded-full bg-blue-500 mt-1.5" />
|
||||
<CheckCircle v-else class="w-4 h-4 text-green-400 mt-0.5" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 mb-1">
|
||||
<p class="text-sm font-medium text-gray-900 truncate">{{ item.title }}</p>
|
||||
</div>
|
||||
<p class="text-xs text-gray-500 leading-relaxed line-clamp-1">{{ item.content }}</p>
|
||||
<p class="text-[10px] text-gray-400 mt-1">{{ new Date(item.createdAt).toLocaleString('zh-CN') }}</p>
|
||||
</div>
|
||||
<ChevronDown class="w-4 h-4 text-gray-300 flex-shrink-0 mt-1 -rotate-90" />
|
||||
</div>
|
||||
<span class="font-semibold text-gray-900 text-sm">通知</span>
|
||||
<span v-if="totalUnread > 0" class="text-[10px] px-2 py-0.5 rounded-full bg-red-50 text-red-500 font-medium border border-red-100">{{ totalUnread }} 条未读</span>
|
||||
</div>
|
||||
<button class="w-7 h-7 rounded-full hover:bg-gray-100 flex items-center justify-center transition-colors" @click="showAnnPanel = false">
|
||||
<X class="w-4 h-4 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分隔线 -->
|
||||
<div class="mx-5 border-t border-gray-100 flex-shrink-0" />
|
||||
|
||||
<!-- 通知列表 -->
|
||||
<div class="flex-1 overflow-y-auto px-5 py-2">
|
||||
<!-- ===== 公告分区 ===== -->
|
||||
<div v-if="announcements.length > 0" class="mb-1">
|
||||
<p class="text-[10px] font-medium text-gray-400 uppercase tracking-wider mb-2 mt-1">公告</p>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-for="item in announcements"
|
||||
:key="'ann-'+item.id"
|
||||
class="rounded-xl p-3.5 transition-all duration-200 cursor-pointer border"
|
||||
:class="item.isRead
|
||||
? 'bg-white border-gray-100 hover:border-gray-200'
|
||||
: 'bg-blue-50/50 border-blue-100 hover:border-blue-200'"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="mt-0.5 flex-shrink-0">
|
||||
<div v-if="!item.isRead" class="w-2.5 h-2.5 rounded-full bg-blue-500 mt-1.5" />
|
||||
<CheckCircle v-else class="w-4 h-4 text-green-400 mt-0.5" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 mb-1">
|
||||
<p class="text-sm font-medium text-gray-900 truncate">{{ item.title }}</p>
|
||||
</div>
|
||||
<p class="text-xs text-gray-500 leading-relaxed line-clamp-1">{{ item.content }}</p>
|
||||
<p class="text-[10px] text-gray-400 mt-1">{{ new Date(item.createdAt).toLocaleString('zh-CN') }}</p>
|
||||
</div>
|
||||
<ChevronDown class="w-4 h-4 text-gray-300 flex-shrink-0 mt-1 -rotate-90" />
|
||||
</div>
|
||||
<!-- ===== 工单通知分区 ===== -->
|
||||
<div v-if="ticketNotifications.length > 0" class="mb-1">
|
||||
<div v-if="announcements.length > 0" class="border-t border-gray-100 my-3" />
|
||||
<p class="text-[10px] font-medium text-gray-400 uppercase tracking-wider mb-2">工单通知</p>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-for="n in ticketNotifications"
|
||||
:key="'tkt-'+n.id"
|
||||
class="rounded-xl p-3.5 transition-all duration-200 cursor-pointer border"
|
||||
:class="n.isRead
|
||||
? 'bg-white border-gray-100 hover:border-gray-200'
|
||||
: 'bg-rose-50/50 border-rose-100 hover:border-rose-200'"
|
||||
@click="handleTicketNotifClick(n)"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="mt-0.5 flex-shrink-0">
|
||||
<div v-if="!n.isRead" class="w-2.5 h-2.5 rounded-full bg-rose-500 mt-1.5" />
|
||||
<CheckCircle v-else class="w-4 h-4 text-green-400 mt-0.5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 工单通知分区 ===== -->
|
||||
<div v-if="ticketNotifications.length > 0" class="mb-1">
|
||||
<div v-if="announcements.length > 0" class="border-t border-gray-100 my-3" />
|
||||
<p class="text-[10px] font-medium text-gray-400 uppercase tracking-wider mb-2">工单通知</p>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-for="n in ticketNotifications"
|
||||
:key="'tkt-'+n.id"
|
||||
class="rounded-xl p-3.5 transition-all duration-200 cursor-pointer border"
|
||||
:class="n.isRead
|
||||
? 'bg-white border-gray-100 hover:border-gray-200'
|
||||
: 'bg-rose-50/50 border-rose-100 hover:border-rose-200'"
|
||||
@click="handleTicketNotifClick(n)"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="mt-0.5 flex-shrink-0">
|
||||
<div v-if="!n.isRead" class="w-2.5 h-2.5 rounded-full bg-rose-500 mt-1.5" />
|
||||
<CheckCircle v-else class="w-4 h-4 text-green-400 mt-0.5" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 mb-1">
|
||||
<MessageSquare class="w-3.5 h-3.5 text-rose-500 flex-shrink-0" />
|
||||
<p class="text-sm font-medium text-gray-900 truncate">{{ n.title }}</p>
|
||||
</div>
|
||||
<p class="text-xs text-gray-500 leading-relaxed line-clamp-1">{{ n.content }}</p>
|
||||
<p class="text-[10px] text-gray-400 mt-1">{{ n.createdAt }}</p>
|
||||
</div>
|
||||
<ChevronDown class="w-4 h-4 text-gray-300 flex-shrink-0 mt-1 -rotate-90" />
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5 mb-1">
|
||||
<MessageSquare class="w-3.5 h-3.5 text-rose-500 flex-shrink-0" />
|
||||
<p class="text-sm font-medium text-gray-900 truncate">{{ n.title }}</p>
|
||||
</div>
|
||||
<p class="text-xs text-gray-500 leading-relaxed line-clamp-1">{{ n.content }}</p>
|
||||
<p class="text-[10px] text-gray-400 mt-1">{{ n.createdAt }}</p>
|
||||
</div>
|
||||
<ChevronDown class="w-4 h-4 text-gray-300 flex-shrink-0 mt-1 -rotate-90" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-if="announcements.length === 0 && ticketNotifications.length === 0 && !loadingAnnouncements && !loadingTickets" class="flex flex-col items-center justify-center py-16 text-gray-400">
|
||||
<Bell class="w-10 h-10 mb-3 opacity-30" />
|
||||
<p class="text-sm font-medium">暂无通知</p>
|
||||
<p class="text-xs mt-1">还没有收到任何公告或工单通知</p>
|
||||
</div>
|
||||
<!-- 空状态 -->
|
||||
<div v-if="announcements.length === 0 && ticketNotifications.length === 0 && !loadingAnnouncements && !loadingTickets" class="flex flex-col items-center justify-center py-16 text-gray-400">
|
||||
<Bell class="w-10 h-10 mb-3 opacity-30" />
|
||||
<p class="text-sm font-medium">暂无通知</p>
|
||||
<p class="text-xs mt-1">还没有收到任何公告或工单通知</p>
|
||||
</div>
|
||||
|
||||
<!-- 加载中 -->
|
||||
<div v-if="loadingAnnouncements || loadingTickets" class="space-y-3 py-4">
|
||||
<div v-for="i in 3" :key="i" class="animate-pulse">
|
||||
<div class="h-4 w-32 bg-gray-100 rounded mb-2" />
|
||||
<div class="h-3 w-full bg-gray-100 rounded mb-1" />
|
||||
<div class="h-3 w-3/4 bg-gray-100 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<!-- 加载中 -->
|
||||
<div v-if="loadingAnnouncements || loadingTickets" class="space-y-3 py-4">
|
||||
<div v-for="i in 3" :key="i" class="animate-pulse">
|
||||
<div class="h-4 w-32 bg-gray-100 rounded mb-2" />
|
||||
<div class="h-3 w-full bg-gray-100 rounded mb-1" />
|
||||
<div class="h-3 w-3/4 bg-gray-100 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</AppDialog>
|
||||
|
||||
<!-- ======== 公告详情 Dialog ======== -->
|
||||
<Teleport to="body">
|
||||
<transition name="fade">
|
||||
<div
|
||||
v-if="showDetail && detailItem"
|
||||
class="fixed inset-0 z-[60] flex items-center justify-center px-6"
|
||||
>
|
||||
<div class="absolute inset-0 bg-black/50" @click="showDetail = false" />
|
||||
<div class="relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden">
|
||||
<div class="h-1.5 bg-gradient-to-r from-blue-500 to-blue-400" />
|
||||
<div class="p-6">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
|
||||
<Bell class="w-5 h-5 text-blue-500" />
|
||||
</div>
|
||||
<h3 class="text-base font-bold text-gray-900">{{ detailItem.title }}</h3>
|
||||
</div>
|
||||
<button class="w-7 h-7 rounded-full hover:bg-gray-100 flex items-center justify-center flex-shrink-0" @click="showDetail = false">
|
||||
<X class="w-4 h-4 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 mb-4">
|
||||
<span class="text-[10px] text-gray-400">{{ new Date(detailItem.createdAt).toLocaleString('zh-CN') }}</span>
|
||||
</div>
|
||||
<div class="bg-gray-50 rounded-xl p-4 max-h-[50vh] overflow-y-auto">
|
||||
<p class="text-sm text-gray-600 leading-relaxed whitespace-pre-wrap">{{ detailItem.content }}</p>
|
||||
</div>
|
||||
<Button class="mt-4 w-full h-11 text-sm font-medium rounded-xl" @click="showDetail = false">
|
||||
关闭
|
||||
</Button>
|
||||
<AppDialog
|
||||
:open="showDetail && !!detailItem"
|
||||
variant="center"
|
||||
z-class="z-[60]"
|
||||
overlay-class="bg-black/50"
|
||||
wrapper-class="px-6"
|
||||
panel-class="max-w-sm shadow-2xl"
|
||||
:fade="true"
|
||||
:title="detailItem?.title || '公告详情'"
|
||||
@update:open="(v: boolean) => { if (!v) showDetail = false }"
|
||||
>
|
||||
<div class="h-1.5 bg-gradient-to-r from-blue-500 to-blue-400" />
|
||||
<div class="p-6">
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
|
||||
<Bell class="w-5 h-5 text-blue-500" />
|
||||
</div>
|
||||
<h3 class="text-base font-bold text-gray-900">{{ detailItem?.title }}</h3>
|
||||
</div>
|
||||
<button class="w-7 h-7 rounded-full hover:bg-gray-100 flex items-center justify-center flex-shrink-0" @click="showDetail = false">
|
||||
<X class="w-4 h-4 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
</transition>
|
||||
</Teleport>
|
||||
<div class="flex items-center gap-2 mb-4">
|
||||
<span class="text-[10px] text-gray-400">{{ detailItem ? new Date(detailItem.createdAt).toLocaleString('zh-CN') : '' }}</span>
|
||||
</div>
|
||||
<div class="bg-gray-50 rounded-xl p-4 max-h-[50vh] overflow-y-auto">
|
||||
<p class="text-sm text-gray-600 leading-relaxed whitespace-pre-wrap">{{ detailItem?.content }}</p>
|
||||
</div>
|
||||
<Button class="mt-4 w-full h-11 text-sm font-medium rounded-xl" @click="showDetail = false">
|
||||
关闭
|
||||
</Button>
|
||||
</div>
|
||||
</AppDialog>
|
||||
|
||||
<!-- ======== 强制弹出公告 Dialog ======== -->
|
||||
<Teleport to="body">
|
||||
<transition name="fade">
|
||||
<div
|
||||
v-if="currentForcePopup"
|
||||
class="fixed inset-0 z-[60] flex items-center justify-center px-6"
|
||||
>
|
||||
<div class="absolute inset-0 bg-black/50" @click="handleForcePopupDismiss" />
|
||||
<div class="relative w-full max-w-sm bg-white rounded-2xl shadow-2xl overflow-hidden">
|
||||
<!-- 顶部装饰条 -->
|
||||
<div class="h-1.5 bg-gradient-to-r from-blue-500 to-blue-400" />
|
||||
<div class="p-6">
|
||||
<div class="flex items-center gap-2.5 mb-2">
|
||||
<div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
|
||||
<Bell class="w-5 h-5 text-blue-500" />
|
||||
</div>
|
||||
<h3 class="text-base font-bold text-gray-900">{{ currentForcePopup.title }}</h3>
|
||||
</div>
|
||||
<div class="bg-gray-50 rounded-xl p-4 mb-4">
|
||||
<p class="text-sm text-gray-600 leading-relaxed whitespace-pre-wrap">{{ currentForcePopup.content }}</p>
|
||||
</div>
|
||||
<Button class="w-full h-11 text-sm font-medium rounded-xl" @click="handleForcePopupDismiss">
|
||||
我知道了
|
||||
</Button>
|
||||
<AppDialog
|
||||
:open="!!currentForcePopup"
|
||||
variant="center"
|
||||
z-class="z-[60]"
|
||||
overlay-class="bg-black/50"
|
||||
wrapper-class="px-6"
|
||||
panel-class="max-w-sm shadow-2xl"
|
||||
:fade="true"
|
||||
:title="currentForcePopup?.title || '公告'"
|
||||
@update:open="(v: boolean) => { if (!v) handleForcePopupDismiss() }"
|
||||
>
|
||||
<!-- 顶部装饰条 -->
|
||||
<div class="h-1.5 bg-gradient-to-r from-blue-500 to-blue-400" />
|
||||
<div class="p-6">
|
||||
<div class="flex items-center gap-2.5 mb-2">
|
||||
<div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
|
||||
<Bell class="w-5 h-5 text-blue-500" />
|
||||
</div>
|
||||
<h3 class="text-base font-bold text-gray-900">{{ currentForcePopup?.title }}</h3>
|
||||
</div>
|
||||
<div class="bg-gray-50 rounded-xl p-4 mb-4">
|
||||
<p class="text-sm text-gray-600 leading-relaxed whitespace-pre-wrap">{{ currentForcePopup?.content }}</p>
|
||||
</div>
|
||||
</transition>
|
||||
</Teleport>
|
||||
<Button class="w-full h-11 text-sm font-medium rounded-xl" @click="handleForcePopupDismiss">
|
||||
我知道了
|
||||
</Button>
|
||||
</div>
|
||||
</AppDialog>
|
||||
|
||||
<!-- ======== 新手引导入口(全局:所有布局内页面显示;引导展示期间隐藏) ======== -->
|
||||
<button
|
||||
v-if="!showGuide"
|
||||
class="guide-entry fixed right-3 bottom-20 z-40 flex items-center gap-1.5 rounded-full bg-blue-500/95 pl-3 pr-3.5 py-2 text-white text-xs font-medium shadow-lg shadow-blue-500/30 hover:bg-blue-600 active:scale-95 transition-all"
|
||||
@click="restartGuide"
|
||||
>
|
||||
<Sparkles class="w-3.5 h-3.5 flex-shrink-0" />
|
||||
忘记操作?再次查看引导
|
||||
</button>
|
||||
|
||||
<!-- ======== 首次登录新手引导(最高层:遮罩高亮真实页面元素 + 气泡推进) ======== -->
|
||||
<GuideOverlay
|
||||
@@ -490,21 +503,12 @@ onUnmounted(() => {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.25s ease;
|
||||
/* 引导入口气泡:上下浮动跳动,吸引注意但不刺眼 */
|
||||
@keyframes guide-bob {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-6px); }
|
||||
}
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.slide-up-enter-active,
|
||||
.slide-up-leave-active {
|
||||
transition: transform 0.3s cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
.slide-up-enter-from,
|
||||
.slide-up-leave-to {
|
||||
transition: translateY(100%);
|
||||
.guide-entry {
|
||||
animation: guide-bob 1.5s ease-in-out infinite;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -2,6 +2,11 @@ import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import './assets/styles/globals.css'
|
||||
import { initTheme } from './composables/useTheme'
|
||||
|
||||
// 亮暗主题自动切换(18:00–次日 06:00 暗色);首屏已由 index.html 内联脚本预设,
|
||||
// 这里立即校正一次并启动分钟级轮询,跨过时间阈值时无刷新自动切换
|
||||
initTheme()
|
||||
|
||||
// 测试入口:URL 带 ?guide=1 强制重播新手引导(不受本地完成标记影响)。
|
||||
// 立即把标记落入 sessionStorage 并移除 URL 参数(登录跳转会丢失 query,故不能等到 MobileLayout)
|
||||
|
||||
@@ -2,6 +2,8 @@ import { createRouter, createWebHistory } from 'vue-router'
|
||||
import LoginView from '@/views/login/LoginView.vue'
|
||||
import HomeView from '@/views/home/HomeView.vue'
|
||||
import ProfileView from '@/views/profile/ProfileView.vue'
|
||||
import LeaveView from '@/views/leave/LeaveView.vue'
|
||||
import CourseView from '@/views/course/CourseView.vue'
|
||||
import BindDeviceView from '@/views/bind/BindDeviceView.vue'
|
||||
import MobileLayout from '@/layouts/MobileLayout.vue'
|
||||
import BrowserGuideView from '@/views/guide/BrowserGuideView.vue'
|
||||
@@ -66,31 +68,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,
|
||||
},
|
||||
],
|
||||
@@ -139,6 +147,16 @@ const router = createRouter({
|
||||
name: 'home',
|
||||
component: HomeView,
|
||||
},
|
||||
{
|
||||
path: 'leave',
|
||||
name: 'leave',
|
||||
component: LeaveView,
|
||||
},
|
||||
{
|
||||
path: 'course',
|
||||
name: 'course',
|
||||
component: CourseView,
|
||||
},
|
||||
{
|
||||
path: 'profile',
|
||||
name: 'profile',
|
||||
@@ -235,6 +253,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,66 @@
|
||||
/**
|
||||
* 复制文本到剪贴板(兼容 HTTP / HTTPS / 移动端 WebView)
|
||||
*
|
||||
* 执行顺序刻意为先同步 execCommand:
|
||||
* document.execCommand('copy') 必须在「用户手势调用栈」内同步执行才可靠,
|
||||
* 若先 await Clipboard API 被拒(移动端 WebView 常见 NotAllowedError),
|
||||
* 手势上下文已丢失,后续 execCommand 会静默失败(返回 false 但剪贴板无内容)。
|
||||
*
|
||||
* 弹窗内复制的坑:AppDialog(reka-ui)会用 FocusScope 锁定焦点——
|
||||
* document 上的 focusin 监听发现焦点跑到 dialog 容器之外时会立即抢回。
|
||||
* 若把临时 textarea 挂到 document.body(容器外),ta.focus() 会立刻被抢走,
|
||||
* 选区失效,execCommand('copy') 仍返回 true 但复制的是空内容
|
||||
*(表现为「提示已复制,实际粘贴不出东西」,且只发生在弹窗内的复制按钮)。
|
||||
* 因此:优先挂到当前打开的 dialog 容器内;并显式校验选区是否真的取到文本。
|
||||
*
|
||||
* 返回是否复制成功
|
||||
*/
|
||||
function findActiveDialogContainer(): HTMLElement | null {
|
||||
const dialogs = document.querySelectorAll<HTMLElement>('[role="dialog"]')
|
||||
// 取最后一次渲染(DOM 中靠后)且可见的那个
|
||||
for (let i = dialogs.length - 1; i >= 0; i--) {
|
||||
const el = dialogs[i]
|
||||
if (el && el.offsetParent !== null) return el
|
||||
}
|
||||
return dialogs.length > 0 ? dialogs[dialogs.length - 1] : null
|
||||
}
|
||||
|
||||
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', '')
|
||||
// 关键:挂到 dialog 容器内(若有弹窗打开),否则焦点会被 FocusScope 抢回导致为空复制
|
||||
const host: HTMLElement = findActiveDialogContainer() || document.body
|
||||
host.appendChild(ta)
|
||||
let ok = false
|
||||
try {
|
||||
ta.focus()
|
||||
ta.select()
|
||||
ta.setSelectionRange(0, text.length)
|
||||
// 校验选区确实落在本 textarea 上(焦点被抢时 selectionStart/End 会异常)
|
||||
const selectionValid =
|
||||
ta.selectionStart === 0 && ta.selectionEnd === text.length && document.activeElement === ta
|
||||
if (selectionValid) {
|
||||
ok = document.execCommand('copy')
|
||||
}
|
||||
} catch {
|
||||
ok = false
|
||||
}
|
||||
if (ta.parentNode) ta.parentNode.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
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { } from '@/components/ui/card'
|
||||
import AppDialog from '@/components/ui/dialog/AppDialog.vue'
|
||||
import { useMessage } from '@/composables/useMessage'
|
||||
import * as adminApi from '@/api/admin'
|
||||
|
||||
@@ -294,149 +294,157 @@ async function handleToggleStatus(agent: adminApi.AgentUser) {
|
||||
</div>
|
||||
|
||||
<!-- 创建代理弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="showCreateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="showCreateModal = false">
|
||||
<div class="bg-white rounded-xl shadow-xl w-full max-w-md mx-4 p-6">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-lg font-semibold text-gray-900">创建下级代理</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showCreateModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<AppDialog
|
||||
:open="showCreateModal"
|
||||
variant="center"
|
||||
panel-class="rounded-xl max-w-md mx-4 p-6"
|
||||
title="创建下级代理"
|
||||
@update:open="(v: boolean) => { if (!v) showCreateModal = false }"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-lg font-semibold text-gray-900">创建下级代理</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showCreateModal = 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="createForm.username" placeholder="代理登录名" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">密码</Label>
|
||||
<Input v-model="createForm.password" type="password" placeholder="至少6位" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">费率倍率</Label>
|
||||
<Input v-model="createForm.rate" type="number" step="0.1" min="1" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">初始充值金额(元)</Label>
|
||||
<Input v-model="createForm.balance" type="number" step="10" min="0" class="h-10 text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showCreateModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="createLoading" @click="handleCreateAgent">
|
||||
<LoaderCircle v-if="createLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
创建
|
||||
</Button>
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">用户名</Label>
|
||||
<Input v-model="createForm.username" placeholder="代理登录名" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">密码</Label>
|
||||
<Input v-model="createForm.password" type="password" placeholder="至少6位" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">费率倍率</Label>
|
||||
<Input v-model="createForm.rate" type="number" step="0.1" min="1" class="h-10 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">初始充值金额(元)</Label>
|
||||
<Input v-model="createForm.balance" type="number" step="10" min="0" class="h-10 text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showCreateModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="createLoading" @click="handleCreateAgent">
|
||||
<LoaderCircle v-if="createLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
创建
|
||||
</Button>
|
||||
</div>
|
||||
</AppDialog>
|
||||
|
||||
<!-- 充值弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="showRechargeModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="showRechargeModal = 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">
|
||||
充值 - {{ rechargeTarget?.username }}
|
||||
<span class="text-sm font-normal text-gray-500 ml-2">当前余额: {{ rechargeTarget?.balance.toFixed(2) }}</span>
|
||||
</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showRechargeModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">充值金额(元)</Label>
|
||||
<Input v-model.number="rechargeAmount" type="number" step="10" min="0" class="h-10 text-sm" />
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showRechargeModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="rechargeLoading || rechargeAmount <= 0" @click="handleRecharge">
|
||||
<LoaderCircle v-if="rechargeLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
充值
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<AppDialog
|
||||
:open="showRechargeModal"
|
||||
variant="center"
|
||||
panel-class="rounded-xl max-w-sm mx-4 p-6"
|
||||
title="充值"
|
||||
@update:open="(v: boolean) => { if (!v) showRechargeModal = false }"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-lg font-semibold text-gray-900">
|
||||
充值 - {{ rechargeTarget?.username }}
|
||||
<span class="text-sm font-normal text-gray-500 ml-2">当前余额: {{ rechargeTarget?.balance.toFixed(2) }}</span>
|
||||
</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showRechargeModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">充值金额(元)</Label>
|
||||
<Input v-model.number="rechargeAmount" type="number" step="10" min="0" class="h-10 text-sm" />
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showRechargeModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="rechargeLoading || rechargeAmount <= 0" @click="handleRecharge">
|
||||
<LoaderCircle v-if="rechargeLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
充值
|
||||
</Button>
|
||||
</div>
|
||||
</AppDialog>
|
||||
|
||||
<!-- 修改费率弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="showRateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="showRateModal = 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">
|
||||
修改费率 - {{ rateTarget?.username }}
|
||||
<span class="text-sm font-normal text-gray-500 ml-2">当前: {{ rateTarget ? (rateTarget.rate * 100).toFixed(0) + '%' : '' }}</span>
|
||||
</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showRateModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">新费率倍率</Label>
|
||||
<Input v-model.number="rateValue" type="number" step="0.1" min="1" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">不得低于自身费率</p>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showRateModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="rateLoading || rateValue <= 0" @click="handleUpdateRate">
|
||||
<LoaderCircle v-if="rateLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<AppDialog
|
||||
:open="showRateModal"
|
||||
variant="center"
|
||||
panel-class="rounded-xl max-w-sm mx-4 p-6"
|
||||
title="修改费率"
|
||||
@update:open="(v: boolean) => { if (!v) showRateModal = false }"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-lg font-semibold text-gray-900">
|
||||
修改费率 - {{ rateTarget?.username }}
|
||||
<span class="text-sm font-normal text-gray-500 ml-2">当前: {{ rateTarget ? (rateTarget.rate * 100).toFixed(0) + '%' : '' }}</span>
|
||||
</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showRateModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">新费率倍率</Label>
|
||||
<Input v-model.number="rateValue" type="number" step="0.1" min="1" class="h-10 text-sm" />
|
||||
<p class="text-xs text-gray-400 mt-1">不得低于自身费率</p>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showRateModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="rateLoading || rateValue <= 0" @click="handleUpdateRate">
|
||||
<LoaderCircle v-if="rateLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</AppDialog>
|
||||
|
||||
<!-- 修改密码弹窗 (admin only) -->
|
||||
<Teleport to="body">
|
||||
<div v-if="showPasswordModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="showPasswordModal = 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">
|
||||
修改密码 - {{ passwordTarget?.username }}
|
||||
</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showPasswordModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<AppDialog
|
||||
:open="showPasswordModal"
|
||||
variant="center"
|
||||
panel-class="rounded-xl max-w-sm mx-4 p-6"
|
||||
title="修改密码"
|
||||
@update:open="(v: boolean) => { if (!v) showPasswordModal = false }"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-lg font-semibold text-gray-900">
|
||||
修改密码 - {{ passwordTarget?.username }}
|
||||
</h2>
|
||||
<button class="text-gray-400 hover:text-gray-600" @click="showPasswordModal = false">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">新密码</Label>
|
||||
<div class="relative">
|
||||
<Input
|
||||
:type="showNewPassword ? 'text' : 'password'"
|
||||
v-model="newPassword"
|
||||
placeholder="至少6位"
|
||||
class="h-10 text-sm pr-9"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
|
||||
@click="showNewPassword = !showNewPassword"
|
||||
>
|
||||
<Eye v-if="showNewPassword" class="h-4 w-4" />
|
||||
<EyeOff v-else class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showPasswordModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="passwordLoading || !newPassword || newPassword.length < 6" @click="handleUpdatePassword">
|
||||
<LoaderCircle v-if="passwordLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
确认修改
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="mb-1 block text-sm text-gray-600">新密码</Label>
|
||||
<div class="relative">
|
||||
<Input
|
||||
:type="showNewPassword ? 'text' : 'password'"
|
||||
v-model="newPassword"
|
||||
placeholder="至少6位"
|
||||
class="h-10 text-sm pr-9"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
|
||||
@click="showNewPassword = !showNewPassword"
|
||||
>
|
||||
<Eye v-if="showNewPassword" class="h-4 w-4" />
|
||||
<EyeOff v-else class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<div class="flex gap-2 mt-6">
|
||||
<Button variant="outline" class="flex-1 h-10" @click="showPasswordModal = false">取消</Button>
|
||||
<Button class="flex-1 h-10" :disabled="passwordLoading || !newPassword || newPassword.length < 6" @click="handleUpdatePassword">
|
||||
<LoaderCircle v-if="passwordLoading" class="w-4 h-4 animate-spin mr-1" />
|
||||
确认修改
|
||||
</Button>
|
||||
</div>
|
||||
</AppDialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user