sceneContext(@RequestParam String scene,
+ HttpServletRequest request) {
+ return ApiResult.ok(mpSceneService.resolve(scene, clientIp(request)));
+ }
+
+ /**
+ * 取调用方 IP 用于限流。
+ *
+ * 优先取 {@code X-Forwarded-For} 的第一段:上线后请求会经过 Nginx,
+ * 那时 {@code getRemoteAddr()} 是 Nginx 的地址,所有人共用一个限额 ——
+ * 限流会变成"把所有人一起限掉",而不是挡住单个刷接口的人。
+ */
+ private static String clientIp(HttpServletRequest request) {
+ String forwarded = request.getHeader("X-Forwarded-For");
+ if (forwarded != null && !forwarded.isBlank()) {
+ int comma = forwarded.indexOf(',');
+ return (comma > 0 ? forwarded.substring(0, comma) : forwarded).trim();
+ }
+ String realIp = request.getHeader("X-Real-IP");
+ if (realIp != null && !realIp.isBlank()) {
+ return realIp.trim();
+ }
+ return request.getRemoteAddr();
+ }
+}
diff --git a/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/dto/SceneContextVO.java b/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/dto/SceneContextVO.java
new file mode 100644
index 0000000..0335e1a
--- /dev/null
+++ b/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/dto/SceneContextVO.java
@@ -0,0 +1,59 @@
+package cn.tianbaotong.fill.module.mp.dto;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * 扫码落地页的上下文(登录前查询)。
+ *
+ *
为什么需要它:学生扫开小程序的第一屏,必须能回答三个问题 ——
+ * 「这是哪个学校的收集」「是要我填什么」「现在能不能填」。
+ * 这三个问题都要在登录之前回答(学生还没绑定身份),
+ * 所以它必然是一个匿名接口。
+ *
+ *
⚠️ 匿名 + scene 可枚举 = 有信息泄露面。scene 形如 {@code t1-k17},
+ * 是可以穷举的。所以这里刻意只放落地页必须的最少信息:
+ *
+ * - 不放学生相关的任何东西(名册人数、已交人数、截止具体时间、班主任姓名)
+ * - 不放租户联系方式(与"系统内不展示班主任/管理员联系方式"是同一条铁律)
+ * - 并配了限流,见 {@code MpSceneService}
+ *
+ * 更进一步的做法是"先 login 再取任务信息"(契约 §5.x 的 {@code /mp/login} 就带 scene),
+ * 那样完全不需要匿名查询 —— 但登录要先换 openid,属 M3 的填报主流程,
+ * 而落地页在登录前就要显示,所以这一步的匿名查询是必要的。
+ */
+@Getter
+@Setter
+@Schema(description = "扫码落地页上下文")
+public class SceneContextVO {
+
+ /** scene 是否合法。不合法时 {@code message} 说明原因。 */
+ private Boolean valid;
+
+ /** scene 原文,便于小程序端排查。 */
+ private String scene;
+
+ /** 租户(学校)名称 —— FR-105「统一小程序 + scene 识别租户」,学生要能确认扫对了地方。 */
+ private String tenantName;
+
+ private Long taskId;
+
+ private String taskName;
+
+ /** 任务状态:0 草稿 / 1 收集中 / 2 已截止 / 3 已归档 / 4 已暂停。 */
+ private Integer taskStatus;
+
+ private String taskStatusText;
+
+ /** 当前是否可提交。落地页据此决定显不显示"开始填报"。 */
+ private Boolean canSubmit;
+
+ /** 带班级的码才有;用于落地页显示"你属于 XX 班"。 */
+ private Long orgId;
+
+ private String orgName;
+
+ /** 给学生的提示语。不能填报时这里是原因(如「本次收集已截止」)。 */
+ private String message;
+}
diff --git a/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/mapper/MpSceneMapper.java b/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/mapper/MpSceneMapper.java
new file mode 100644
index 0000000..ed8b8b2
--- /dev/null
+++ b/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/mapper/MpSceneMapper.java
@@ -0,0 +1,63 @@
+package cn.tianbaotong.fill.module.mp.mapper;
+
+import cn.tianbaotong.fill.module.org.entity.SysOrg;
+import cn.tianbaotong.fill.module.task.entity.CollectTask;
+import cn.tianbaotong.fill.module.task.entity.CollectTaskOrg;
+import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+
+/**
+ * 扫码落地页的匿名查询({@code /mp/scene-context})。
+ *
+ * ⚠️ 这个接口是匿名的,而多租户拦截器在匿名请求下"默认拒绝"
+ * ({@code FillTenantLineHandler.getTenantId()} 直接抛 {@code 40101})。
+ * 所以这里的每一条查询都必须:
+ *
+ * - 加 {@code @InterceptorIgnore(tenantLine = "true")} 关掉拦截器;
+ * - 自己显式带上 {@code tenant_id} —— 关掉拦截器就没人替你把关了。
+ *
+ * 项目注释把"必须显式加 {@code @InterceptorIgnore}"称为一次代码审查点,
+ * 正是因为它把"租户隔离"从"框架自动做"变成了"人来保证"。
+ * 把这几条集中在一个文件里(而不是散在各处),就是为了让这次审查有地方做:
+ * 改动这个文件时,逐条确认 tenant_id 还在。
+ *
+ * 只暴露落地页需要的最小字段语义:任务名/状态、租户名、班级名。
+ * 不要往这里加"顺带能查出来"的东西(名册人数、已交人数、联系方式)——
+ * scene 是可穷举的({@code t1-k1}、{@code t1-k2}…),加什么就等于公开什么。
+ */
+public interface MpSceneMapper {
+
+ /** 按 (tenantId, taskId) 取任务。跨租户或已删除时返回 null。 */
+ @InterceptorIgnore(tenantLine = "true")
+ @Select("""
+ SELECT * FROM collect_task
+ WHERE id = #{taskId} AND tenant_id = #{tenantId} AND deleted = 0
+ """)
+ CollectTask selectTask(@Param("tenantId") Long tenantId, @Param("taskId") Long taskId);
+
+ /**
+ * 取任务下的班级覆盖关系(只取生效的)。
+ *
+ *
{@code collect_task_org} 没有 deleted 列,所以这里只能按 {@code status} 过滤,
+ * 不要照抄别的表的 {@code deleted = 0}。
+ */
+ @InterceptorIgnore(tenantLine = "true")
+ @Select("""
+ SELECT * FROM collect_task_org
+ WHERE task_id = #{taskId} AND org_id = #{orgId}
+ AND tenant_id = #{tenantId} AND status = 1
+ LIMIT 1
+ """)
+ CollectTaskOrg selectOrgLink(@Param("tenantId") Long tenantId,
+ @Param("taskId") Long taskId,
+ @Param("orgId") Long orgId);
+
+ /** 取班级名。 */
+ @InterceptorIgnore(tenantLine = "true")
+ @Select("""
+ SELECT * FROM sys_org
+ WHERE id = #{orgId} AND tenant_id = #{tenantId} AND deleted = 0
+ """)
+ SysOrg selectOrg(@Param("tenantId") Long tenantId, @Param("orgId") Long orgId);
+}
diff --git a/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/service/MpSceneService.java b/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/service/MpSceneService.java
new file mode 100644
index 0000000..bff8bad
--- /dev/null
+++ b/backend/xt-server/src/main/java/cn/tianbaotong/fill/module/mp/service/MpSceneService.java
@@ -0,0 +1,174 @@
+package cn.tianbaotong.fill.module.mp.service;
+
+import cn.tianbaotong.fill.common.api.ErrorCode;
+import cn.tianbaotong.fill.common.exception.BizException;
+import cn.tianbaotong.fill.module.mp.dto.SceneContextVO;
+import cn.tianbaotong.fill.module.mp.mapper.MpSceneMapper;
+import cn.tianbaotong.fill.module.org.entity.SysOrg;
+import cn.tianbaotong.fill.module.task.entity.CollectTask;
+import cn.tianbaotong.fill.module.task.entity.CollectTaskOrg;
+import cn.tianbaotong.fill.module.tenant.entity.SysTenant;
+import cn.tianbaotong.fill.module.tenant.mapper.TenantMapper;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.time.Duration;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 扫码场景值的解析与落地页上下文(FR-105:统一小程序 + 扫码带参 scene 识别租户)。
+ *
+ *
scene 格式(与 M0 开通租户时约定的 {@code miniProgramScene} 同一套前缀):
+ *
+ * t{tenantId} 租户级码(学校大屏/公众号菜单用)
+ * t{tenantId}-k{taskId} 任务级码
+ * t{tenantId}-k{taskId}-o{orgId} 带班级的码,落地页能直接说出"你属于哪个班"
+ *
+ *
+ * ⚠️ 这是匿名接口,必须限流。scene 可以穷举({@code t1-k1}、{@code t1-k2}…),
+ * 不限流的话,一个人用一句脚本就能把所有学校的所有任务名与状态扫一遍 ——
+ * 那些信息本来是要登录才能看到的。限流不是"防黑客",是别让"需要登录才能看到的东西"
+ * 变成"一条 curl 就能拉全表"。
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class MpSceneService {
+
+ private static final Pattern SCENE = Pattern.compile("^t(\\d+)(?:-k(\\d+))?(?:-o(\\d+))?$");
+
+ /** 同一 IP 每分钟最多查多少次。正常学生一次扫描只会调 1~2 次(含重试)。 */
+ private static final int RATE_LIMIT_PER_MINUTE = 20;
+
+ private static final String RATE_KEY = "xt:mp:scene:rate:";
+
+ private final TenantMapper tenantMapper;
+ private final MpSceneMapper sceneMapper;
+ private final StringRedisTemplate redis;
+
+ /**
+ * 解析 scene 并返回落地页上下文。
+ *
+ * @param scene 小程序码里的场景值
+ * @param clientIp 调用方 IP,用于限流
+ */
+ public SceneContextVO resolve(String scene, String clientIp) {
+ rateLimit(clientIp);
+
+ SceneContextVO vo = new SceneContextVO();
+ vo.setScene(scene);
+ vo.setCanSubmit(false);
+
+ Matcher m = scene == null ? null : SCENE.matcher(scene.trim());
+ if (m == null || !m.matches()) {
+ vo.setValid(false);
+ vo.setMessage("这个二维码不是本系统生成的,请向班主任确认");
+ return vo;
+ }
+
+ long tenantId = Long.parseLong(m.group(1));
+ Long taskId = m.group(2) == null ? null : Long.parseLong(m.group(2));
+ Long orgId = m.group(3) == null ? null : Long.parseLong(m.group(3));
+
+ // ⚠️ 下面几个查询都关掉了租户拦截器(匿名请求下拦截器是"默认拒绝"的),
+ // 所以每一条都必须**显式带上 tenant_id** —— 漏一个就会跨租户读到别人的数据。
+ SysTenant tenant = tenantMapper.selectById(tenantId);
+ if (tenant == null) {
+ vo.setValid(false);
+ vo.setMessage("这个二维码对应的单位不存在或已停用");
+ return vo;
+ }
+ vo.setValid(true);
+ vo.setTenantName(tenant.getTenantName());
+
+ if (taskId == null) {
+ vo.setMessage("请扫描班主任发的「填报二维码」");
+ return vo;
+ }
+
+ // ⚠️ 必须用 MpSceneMapper(显式带 tenant_id + 关掉拦截器),
+ // 不能用 taskMapper.selectById —— 匿名请求下拦截器会直接抛 40101
+ CollectTask task = sceneMapper.selectTask(tenantId, taskId);
+ if (task == null) {
+ vo.setValid(false);
+ vo.setMessage("这个二维码对应的任务不存在或已删除");
+ return vo;
+ }
+ vo.setTaskId(task.getId());
+ vo.setTaskName(task.getTaskName());
+ vo.setTaskStatus(task.getStatus());
+ vo.setTaskStatusText(statusText(task.getStatus()));
+ vo.setCanSubmit(task.getStatus() != null && task.getStatus() == CollectTask.STATUS_COLLECTING);
+ vo.setMessage(submitMessage(task.getStatus()));
+
+ if (orgId != null) {
+ CollectTaskOrg link = sceneMapper.selectOrgLink(tenantId, taskId, orgId);
+ if (link != null) {
+ SysOrg org = sceneMapper.selectOrg(tenantId, orgId);
+ vo.setOrgId(orgId);
+ vo.setOrgName(org == null ? null : org.getOrgName());
+ }
+ }
+ return vo;
+ }
+
+ /**
+ * 按 IP 限流。
+ *
+ *
用 Redis 的 INCR + EXPIRE:第一次请求建键并设 60 秒过期,
+ * 之后每次自增。超限就拒绝。不引额外的限流组件 —— 这个接口的调用量很小
+ * (每个学生扫码 1~2 次),一个计数器足够。
+ */
+ private void rateLimit(String clientIp) {
+ if (clientIp == null || clientIp.isBlank()) {
+ return;
+ }
+ String key = RATE_KEY + clientIp;
+ Long count = redis.opsForValue().increment(key);
+ if (count != null && count == 1L) {
+ redis.expire(key, Duration.ofMinutes(1));
+ }
+ if (count != null && count > RATE_LIMIT_PER_MINUTE) {
+ throw new BizException(ErrorCode.GATE_RATE_LIMITED);
+ }
+ }
+
+ private static String statusText(Integer status) {
+ if (status == null) {
+ return "未知";
+ }
+ return switch (status) {
+ case CollectTask.STATUS_DRAFT -> "尚未发布";
+ case CollectTask.STATUS_COLLECTING -> "收集中";
+ case CollectTask.STATUS_CLOSED -> "已截止";
+ case CollectTask.STATUS_ARCHIVED -> "已结束";
+ case CollectTask.STATUS_PAUSED -> "已暂停";
+ default -> "未知";
+ };
+ }
+
+ /**
+ * 不能填报时给学生的提示。
+ *
+ *
§7.12 写明:「任务截止后扫码进入提示"已截止",不做失效」——
+ * 所以码永远有效,靠这句话告诉学生现在的状态。
+ * 五句话分开写而不是合并成"当前不可填报",是因为学生的下一步动作完全不同:
+ * "已截止"要找班主任,"已暂停"要等通知,"尚未发布"是根本不该现在扫。
+ */
+ private static String submitMessage(Integer status) {
+ if (status == null) {
+ return "任务状态异常,请联系班主任";
+ }
+ return switch (status) {
+ case CollectTask.STATUS_COLLECTING -> "请核对信息后开始填报";
+ case CollectTask.STATUS_DRAFT -> "本次收集尚未开始,请留意班主任通知";
+ case CollectTask.STATUS_PAUSED -> "本次收集暂时暂停,请等待恢复通知";
+ case CollectTask.STATUS_CLOSED -> "本次收集已截止,如需补交请联系班主任";
+ case CollectTask.STATUS_ARCHIVED -> "本次收集已结束,材料已归档";
+ default -> "当前不可填报";
+ };
+ }
+}
diff --git a/docs/交接摘要.md b/docs/交接摘要.md
index 5039330..895f8a9 100644
--- a/docs/交接摘要.md
+++ b/docs/交接摘要.md
@@ -52,8 +52,9 @@
| **M1-04 材料项定义** | ✅ 材料项 CRUD(§7.10)+ 三个内置模板(`TPL_SCHOOL_ROLL`/`TPL_SOCIAL`/`TPL_ZHUANXIANG`)+ 材料目录接口;**`e2e-m1-materials.py` → 68/68** |
| **M1-03 表单 schema 版本化** | ✅ `GET/PUT /tasks/{id}/form-schema`(版本只增不改 + `baseVersion` 乐观锁 40025 + 内置字段不可删 40026)+ 官方 21 项内置字段目录;**`e2e-m1-form.py` → 48/48** |
| **M1-06 填报二维码** | ✅ `GET /tasks/{id}/qrcode`(真调微信生成小程序码)+ 匿名图片接口 `GET /qrcodes/{scene}`;**`e2e-m1-qrcode.py` → 32/32(唯一打外网的 E2E)** |
+| **小程序端骨架 + 扫码落地页** | ✅ `frontend-mp/`(uni-app,appid `wxf01d3fa60f87f0b7`)+ 匿名 `GET /mp/scene-context`;**已在微信开发者工具里跑通**;`e2e-m1-scene.py` → 31/31 |
| PC 前端 | ✅ 已换 Gi Admin Pro + 腾讯云主题;已实现:登录 / 工作台 / 组织架构 / 租户管理 / 账号管理 / **收集任务(含配置班级)** |
-| 待做 | M1 剩余(M1-05 规则模板 + **M1-07~M1-10 前端**——表单设计器 M1-07、材料规则界面 M1-09);小程序(uni-app)未创建;CI/CD |
+| 待做 | M1 剩余(M1-05 规则模板 + **M1-07~M1-10 前端**);**M3 小程序填报主流程**(`/mp/login` 门禁核验 表单);CI/CD;**C1 小程序类目资质(阻塞学生真正开始填报)** |
---
@@ -380,6 +381,77 @@ Flyway 迁移 1~6 全部 success。
---
+## 一·十、小程序端骨架 + 扫码落地页(2026-09-29 上午,未提交)
+
+> 范围:`frontend-mp/`(uni-app 项目,从官方 `uni-preset-vue#vite-ts` 模板建)、
+> `GET /api/v1/mp/scene-context`(匿名,登录前的落地页查询)。
+
+**验收**:`python scripts/e2e-m1-scene.py` → **31/31**;
+八条 E2E 合计 **389 项断言**全通过。
+**已在微信开发者工具里真机模拟跑通**:`scene=t1-k17` → 显示「示范职业学校 /
+2026年9月机电专业认定材料收集 / 尚未发布」。
+
+### ⚠️ 微信版本与「谁能扫」(这是上线计划的关键约束)
+
+| 版本 | 谁能扫开 | 有效性与成本 |
+|---|---|---|
+| `develop` 开发版 | **只有开发者本人** | 上传/预览后短期有效,**会过期**(实测遇到过「开发版小程序已过期」) |
+| `trial` 体验版 | **只有体验成员**(后台「成员管理」加人) | 相对稳定,被新版本顶替前一直有效 |
+| `release` 正式版 | **所有人** | 需**提交审核 + 发布**,涉及小程序类目与资质 |
+
+> ⚠️ **开发版与体验版,学生都扫不开。** 只有正式发布后学生才能扫 ——
+> 所以 **C1「小程序资质法务确认」不是"以后再说"的事**,它直接决定学生能不能开始填报。
+> 建议尽早就"教育类目需要什么资质"问清楚。
+
+### 两个工具链的产物路径(容易搞混)
+
+| 工具 | 命令/操作 | 产物目录 |
+|---|---|---|
+| CLI(pnpm) | `pnpm dev:mp-weixin` / `build:mp-weixin` | `dist/dev/mp-weixin`、`dist/build/mp-weixin` |
+| HBuilderX | 「运行到小程序模拟器」 | **`dist/dev/mp-weixin`**(它把这个项目当 CLI 型项目,**不是** `unpackage/`) |
+
+### 两个必踩的环境坑
+
+| 坑 | 现象与解法 |
+|---|---|
+| **微信开发者工具的「服务端口」默认关闭** | HBuilderX 运行时报 `IDE service port disabled` / `工具的服务端口已关闭`,然后 `[info] 退出` —— **调不起开发者工具**。解法:打开开发者工具 → **设置 → 安全设置 → 服务端口 → 开启**。或绕过:直接「导入项目」`dist/dev/mp-weixin` |
+| **模拟扫码要手动配编译模式** | 默认进入时 `onLoad` 参数为空(页面会提示"请扫描二维码")。要模拟:工具栏「编译模式」→ 添加 → **进入场景=扫描二维码** → **启动参数 `scene=t1-k17`** |
+
+另:`
diff --git a/frontend-mp/src/config/index.ts b/frontend-mp/src/config/index.ts
new file mode 100644
index 0000000..77561eb
--- /dev/null
+++ b/frontend-mp/src/config/index.ts
@@ -0,0 +1,32 @@
+/**
+ * 小程序端配置。
+ *
+ * ⚠️ API 地址在三种场景下不一样,写死会导致"开发者工具里好好的,真机打不开":
+ *
+ * 1. 微信开发者工具:可以用 http://localhost:8080,
+ * 但必须在「详情 → 本地设置」里勾上 **「不校验合法域名、web-view、TLS 版本以及 HTTPS 证书」**。
+ * 不勾的话请求会被拦,报错是「不在以下 request 合法域名列表中」——
+ * 而那句话看起来像"域名没配",会让人跑去小程序后台白改一通。
+ *
+ * 2. 真机预览/体验版:localhost 是**手机自己**,不是你的电脑。
+ * 要把地址换成电脑的局域网 IP(如 http://192.168.1.5:8080),
+ * 并确保手机与电脑在同一网络、电脑防火墙放行 8080。
+ *
+ * 3. 正式发布:必须是 **HTTPS + 已在微信后台配好 request 合法域名**(见待办:域名白名单),
+ * 且域名不能带端口、不能是 IP。
+ *
+ * 所以这里留成一处配置,而不是散在请求代码里。
+ */
+export const API_BASE_URL = 'http://localhost:8080'
+
+/** 主题色(与 PC 管理端同一套腾讯云 TDesign 色板,两端视觉要一致)。 */
+export const THEME = {
+ primary: '#0052D9',
+ success: '#00A870',
+ warning: '#ED7B2F',
+ danger: '#E34D59',
+ pageBg: '#F3F3F3',
+ textPrimary: '#000000E6',
+ textSecondary: '#00000099',
+ textPlaceholder: '#0000004D'
+} as const
diff --git a/frontend-mp/src/env.d.ts b/frontend-mp/src/env.d.ts
new file mode 100644
index 0000000..d27eb5a
--- /dev/null
+++ b/frontend-mp/src/env.d.ts
@@ -0,0 +1,8 @@
+///
+
+declare module '*.vue' {
+ import { DefineComponent } from 'vue'
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
+ const component: DefineComponent<{}, {}, any>
+ export default component
+}
diff --git a/frontend-mp/src/main.ts b/frontend-mp/src/main.ts
new file mode 100644
index 0000000..b12c1ee
--- /dev/null
+++ b/frontend-mp/src/main.ts
@@ -0,0 +1,8 @@
+import { createSSRApp } from "vue";
+import App from "./App.vue";
+export function createApp() {
+ const app = createSSRApp(App);
+ return {
+ app,
+ };
+}
diff --git a/frontend-mp/src/manifest.json b/frontend-mp/src/manifest.json
new file mode 100644
index 0000000..b6c2ca6
--- /dev/null
+++ b/frontend-mp/src/manifest.json
@@ -0,0 +1,72 @@
+{
+ "name" : "填报通",
+ "appid" : "",
+ "description" : "",
+ "versionName" : "1.0.0",
+ "versionCode" : "100",
+ "transformPx" : false,
+ /* 5+App特有相关 */
+ "app-plus" : {
+ "usingComponents" : true,
+ "nvueStyleCompiler" : "uni-app",
+ "compilerVersion" : 3,
+ "splashscreen" : {
+ "alwaysShowBeforeRender" : true,
+ "waiting" : true,
+ "autoclose" : true,
+ "delay" : 0
+ },
+ /* 模块配置 */
+ "modules" : {},
+ /* 应用发布信息 */
+ "distribute" : {
+ /* android打包配置 */
+ "android" : {
+ "permissions" : [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ]
+ },
+ /* ios打包配置 */
+ "ios" : {},
+ /* SDK配置 */
+ "sdkConfigs" : {}
+ }
+ },
+ /* 快应用特有相关 */
+ "quickapp" : {},
+ /* 小程序特有相关 */
+ "mp-weixin" : {
+ "appid" : "wxf01d3fa60f87f0b7",
+ "setting" : {
+ "urlCheck" : false
+ },
+ "usingComponents" : true
+ },
+ "mp-alipay" : {
+ "usingComponents" : true
+ },
+ "mp-baidu" : {
+ "usingComponents" : true
+ },
+ "mp-toutiao" : {
+ "usingComponents" : true
+ },
+ "uniStatistics": {
+ "enable": false
+ },
+ "vueVersion" : "3"
+}
diff --git a/frontend-mp/src/pages.json b/frontend-mp/src/pages.json
new file mode 100644
index 0000000..e5f5701
--- /dev/null
+++ b/frontend-mp/src/pages.json
@@ -0,0 +1,19 @@
+{
+ "pages": [
+ {
+ "path": "pages/index/index",
+ "style": {
+ "navigationBarTitleText": "材料填报",
+ "navigationBarBackgroundColor": "#0052D9",
+ "navigationBarTextStyle": "white",
+ "enablePullDownRefresh": true
+ }
+ }
+ ],
+ "globalStyle": {
+ "navigationBarTextStyle": "white",
+ "navigationBarTitleText": "填报通",
+ "navigationBarBackgroundColor": "#0052D9",
+ "backgroundColor": "#F3F3F3"
+ }
+}
diff --git a/frontend-mp/src/pages/index/index.vue b/frontend-mp/src/pages/index/index.vue
new file mode 100644
index 0000000..16ec0f9
--- /dev/null
+++ b/frontend-mp/src/pages/index/index.vue
@@ -0,0 +1,309 @@
+
+
+
+
+ {{ ctx.tenantName || '填报通' }}
+ {{ ctx.taskName || title }}
+
+ {{ ctx.taskStatusText }}
+
+
+
+
+
+ {{ message }}
+
+
+
+
+ 班级
+ {{ ctx.orgName }}
+
+
+
+
+ 正在读取…
+
+
+
+ scene:{{ scene || '(未获取到)' }}
+
+ 原始值:{{ rawScene }}
+
+
+
+ 职业技能等级认定材料收集中台
+
+
+
+
+
+
diff --git a/frontend-mp/src/shime-uni.d.ts b/frontend-mp/src/shime-uni.d.ts
new file mode 100644
index 0000000..5ecbb26
--- /dev/null
+++ b/frontend-mp/src/shime-uni.d.ts
@@ -0,0 +1,6 @@
+export {}
+
+declare module "vue" {
+ type Hooks = App.AppInstance & Page.PageInstance;
+ interface ComponentCustomOptions extends Hooks {}
+}
\ No newline at end of file
diff --git a/frontend-mp/src/static/logo.png b/frontend-mp/src/static/logo.png
new file mode 100644
index 0000000..b5771e2
Binary files /dev/null and b/frontend-mp/src/static/logo.png differ
diff --git a/frontend-mp/src/uni.scss b/frontend-mp/src/uni.scss
new file mode 100644
index 0000000..288300d
--- /dev/null
+++ b/frontend-mp/src/uni.scss
@@ -0,0 +1,76 @@
+/**
+ * 这里是uni-app内置的常用样式变量
+ *
+ * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量
+ * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App
+ *
+ */
+
+/**
+ * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能
+ *
+ * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件
+ */
+
+/* 颜色变量 */
+
+/* 行为相关颜色 */
+$uni-color-primary: #007aff;
+$uni-color-success: #4cd964;
+$uni-color-warning: #f0ad4e;
+$uni-color-error: #dd524d;
+
+/* 文字基本颜色 */
+$uni-text-color: #333; // 基本色
+$uni-text-color-inverse: #fff; // 反色
+$uni-text-color-grey: #999; // 辅助灰色,如加载更多的提示信息
+$uni-text-color-placeholder: #808080;
+$uni-text-color-disable: #c0c0c0;
+
+/* 背景颜色 */
+$uni-bg-color: #fff;
+$uni-bg-color-grey: #f8f8f8;
+$uni-bg-color-hover: #f1f1f1; // 点击状态颜色
+$uni-bg-color-mask: rgba(0, 0, 0, 0.4); // 遮罩颜色
+
+/* 边框颜色 */
+$uni-border-color: #c8c7cc;
+
+/* 尺寸变量 */
+
+/* 文字尺寸 */
+$uni-font-size-sm: 12px;
+$uni-font-size-base: 14px;
+$uni-font-size-lg: 16;
+
+/* 图片尺寸 */
+$uni-img-size-sm: 20px;
+$uni-img-size-base: 26px;
+$uni-img-size-lg: 40px;
+
+/* Border Radius */
+$uni-border-radius-sm: 2px;
+$uni-border-radius-base: 3px;
+$uni-border-radius-lg: 6px;
+$uni-border-radius-circle: 50%;
+
+/* 水平间距 */
+$uni-spacing-row-sm: 5px;
+$uni-spacing-row-base: 10px;
+$uni-spacing-row-lg: 15px;
+
+/* 垂直间距 */
+$uni-spacing-col-sm: 4px;
+$uni-spacing-col-base: 8px;
+$uni-spacing-col-lg: 12px;
+
+/* 透明度 */
+$uni-opacity-disabled: 0.3; // 组件禁用态的透明度
+
+/* 文章场景相关 */
+$uni-color-title: #2c405a; // 文章标题颜色
+$uni-font-size-title: 20px;
+$uni-color-subtitle: #555; // 二级标题颜色
+$uni-font-size-subtitle: 18px;
+$uni-color-paragraph: #3f536e; // 文章段落颜色
+$uni-font-size-paragraph: 15px;
\ No newline at end of file
diff --git a/frontend-mp/src/utils/request.ts b/frontend-mp/src/utils/request.ts
new file mode 100644
index 0000000..8b31d13
--- /dev/null
+++ b/frontend-mp/src/utils/request.ts
@@ -0,0 +1,57 @@
+import { API_BASE_URL } from '@/config'
+
+/**
+ * 请求封装。
+ *
+ * 后端契约是 `{ code, msg, data }` —— 与 PC 管理端同一套。
+ * ⚠️ 关键差异:**业务错误返回的 HTTP 状态码是 200**,
+ * 真正的错误码在响应体的 `code` 里(只有 401/403/429/5xxxx 才占用真 HTTP 状态码)。
+ * 所以判断成功必须看 `code === 0`,**不能看 HTTP 状态码** ——
+ * 只看状态码会把"业务失败"当成"成功",然后拿着空 data 往下走。
+ */
+export interface ApiResult {
+ code: number
+ msg: string
+ data: T
+}
+
+export function request(options: {
+ url: string
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
+ data?: Record
+ /** 已登录时带上(登录流程见契约 §5.x 的 /mp/login,属 M3) */
+ token?: string
+}): Promise {
+ const { url, method = 'GET', data, token } = options
+ return new Promise((resolve, reject) => {
+ uni.request({
+ url: API_BASE_URL + url,
+ method,
+ data,
+ header: {
+ 'Content-Type': 'application/json; charset=utf-8',
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
+ },
+ success: (res) => {
+ const body = res.data as ApiResult | undefined
+ if (!body || typeof body.code !== 'number') {
+ reject(new Error(`响应格式不对(HTTP ${res.statusCode})`))
+ return
+ }
+ if (body.code !== 0) {
+ // 把后端的 msg 原样带出去:这些 message 是刻意写成人话的
+ // (例如"本次收集已截止,如需补交请联系班主任"),
+ // 前端再包一层"请求失败"只会把有用信息盖掉
+ reject(new Error(body.msg || `请求失败(code=${body.code})`))
+ return
+ }
+ resolve(body.data)
+ },
+ fail: (err) => {
+ // 最常见的失败是域名未放行 / 真机访问了 localhost,
+ // 这两种都不是"网络不好",所以提示要指向配置见 src/config/index.ts
+ reject(new Error(`网络请求失败:${err.errMsg || '未知原因'}(请检查 API 地址配置)`))
+ }
+ })
+ })
+}
diff --git a/frontend-mp/tsconfig.json b/frontend-mp/tsconfig.json
new file mode 100644
index 0000000..11fffd2
--- /dev/null
+++ b/frontend-mp/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "@vue/tsconfig/tsconfig.json",
+ "compilerOptions": {
+ "sourceMap": true,
+ "baseUrl": ".",
+ "paths": {
+ "@/*": ["./src/*"]
+ },
+ "lib": ["esnext", "dom"],
+ "types": ["@dcloudio/types"]
+ },
+ "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
+}
diff --git a/frontend-mp/vite.config.ts b/frontend-mp/vite.config.ts
new file mode 100644
index 0000000..46e36fe
--- /dev/null
+++ b/frontend-mp/vite.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from "vite";
+import uni from "@dcloudio/vite-plugin-uni";
+
+// https://vitejs.dev/config/
+export default defineConfig({
+ plugins: [uni()],
+});
diff --git a/scripts/e2e-m1-scene.py b/scripts/e2e-m1-scene.py
new file mode 100644
index 0000000..ddd78a1
--- /dev/null
+++ b/scripts/e2e-m1-scene.py
@@ -0,0 +1,385 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+扫码落地页(GET /api/v1/mp/scene-context)验收测试。
+
+覆盖 FR-105(统一小程序 + 扫码带参 scene 识别租户):
+ [x] 正常 scene:返回租户名、任务名、状态、能否填报、给学生的话
+ [x] 非法 scene / 不存在的租户 / 不存在的任务:各自给出**不同的**提示
+ [x] 租户级 scene(不带任务):提示去扫任务码
+ [x] 带班级:班级名只在"该班确实在任务覆盖范围里"时才返回
+ [x] 跨租户:A 租户的 scene 拼上 B 租户的任务 id → 必须当作"不存在"
+ [x] 状态文案随任务状态变化(收集中/已暂停/已截止)
+ [x] **限流**:scene 可穷举,必须能挡住批量扫描
+ [x] 这个接口**匿名**就能访问(学生登录前就要用)
+
+为什么这些值得逐条断言:
+ 这是学生扫码后的第一屏,而且它是**匿名**接口、scene 又可穷举(t1-k1、t1-k2…)。
+ 一旦哪个分支写错,后果不是"报错",而是"把不该给的信息给出去了",
+ 或者"扫对了码却告诉他这个码不是本系统的" —— 后者会让学生直接放弃。
+
+用法
+ python scripts/e2e-m1-scene.py
+
+依赖:cryptography;且需要能 `docker exec xt-pg` / `xt-redis`
+退出码:0 = 全部通过
+"""
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import os
+import subprocess
+import sys
+import urllib.error
+import urllib.parse
+import urllib.request
+import uuid
+
+if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8")
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+PUB_KEY = os.path.join(ROOT, "deploy", "rsa-public-key-dev.pem")
+
+PG_CONTAINER = os.environ.get("XT_PG_CONTAINER", "xt-pg")
+PG_USER = os.environ.get("PG_USER", "fill")
+PG_DB = os.environ.get("PG_DB", "filldb")
+PG_PWD = os.environ.get("PG_PASSWORD", "fill_dev_pwd")
+REDIS_CONTAINER = os.environ.get("XT_REDIS_CONTAINER", "xt-redis")
+REDIS_PWD = os.environ.get("REDIS_PASSWORD", "redis_dev_pwd")
+
+PASSED: list[str] = []
+FAILED: list[tuple[str, str]] = []
+
+CREATED_TASK_IDS: list[int] = []
+CREATED_TENANT_IDS: list[int] = []
+
+
+def ok(name: str) -> None:
+ PASSED.append(name)
+ print(f" [OK] {name}")
+
+
+def fail(name: str, detail: str) -> None:
+ FAILED.append((name, detail))
+ print(f" [FAIL] {name}\n {detail}")
+
+
+def check(name: str, cond: bool, detail: str = "") -> bool:
+ if cond:
+ ok(name)
+ else:
+ fail(name, detail or "断言不成立")
+ return cond
+
+
+def sql(stmt: str) -> tuple[bool, str]:
+ try:
+ r = subprocess.run(
+ ["docker", "exec", "-e", f"PGPASSWORD={PG_PWD}", PG_CONTAINER,
+ "psql", "-U", PG_USER, "-d", PG_DB, "-t", "-A", "-c", stmt],
+ capture_output=True, text=True, timeout=40)
+ return r.returncode == 0, (r.stdout or r.stderr).strip()
+ except Exception as e:
+ return False, str(e)
+
+
+def redis(args: list[str]) -> tuple[bool, str]:
+ try:
+ r = subprocess.run(
+ ["docker", "exec", "-e", f"REDISCLI_AUTH={REDIS_PWD}", REDIS_CONTAINER,
+ "redis-cli"] + args, capture_output=True, text=True, timeout=30)
+ return r.returncode == 0, (r.stdout or r.stderr).strip()
+ except Exception as e:
+ return False, str(e)
+
+
+def cleanup_all() -> None:
+ if CREATED_TASK_IDS:
+ ids = ",".join(str(i) for i in CREATED_TASK_IDS)
+ for stmt in [
+ f"DELETE FROM collect_task_org WHERE task_id IN ({ids})",
+ f"DELETE FROM collect_material_def WHERE task_id IN ({ids})",
+ f"DELETE FROM collect_roster WHERE task_id IN ({ids})",
+ f"DELETE FROM collect_task WHERE id IN ({ids})",
+ ]:
+ sql(stmt)
+ for tid in CREATED_TENANT_IDS:
+ for stmt in [
+ f"DELETE FROM sys_user_role WHERE user_id IN (SELECT id FROM sys_user WHERE tenant_id = {tid})",
+ f"DELETE FROM sys_user WHERE tenant_id = {tid}",
+ f"DELETE FROM sys_org WHERE tenant_id = {tid}",
+ f"DELETE FROM sys_role WHERE tenant_id = {tid}",
+ f"DELETE FROM collect_task WHERE tenant_id = {tid}",
+ f"DELETE FROM sys_tenant WHERE id = {tid}",
+ ]:
+ sql(stmt)
+ redis(["DEL", "xt:mp:scene:rate:127.0.0.1"])
+ redis(["DEL", "xt:mp:scene:rate:localhost"])
+
+
+def rsa_encrypt(plain: str) -> str:
+ from cryptography.hazmat.primitives import serialization
+ from cryptography.hazmat.primitives.asymmetric import padding
+ with open(PUB_KEY, "rb") as f:
+ pub = serialization.load_pem_public_key(f.read())
+ return base64.b64encode(pub.encrypt(plain.encode(), padding.PKCS1v15())).decode()
+
+
+def call(method: str, url: str, token: str | None = None,
+ body: dict | None = None, timeout: int = 30) -> tuple[int, dict]:
+ headers = {"Content-Type": "application/json; charset=utf-8"}
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ data = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return resp.status, json.loads(resp.read().decode("utf-8"))
+ except urllib.error.HTTPError as e:
+ raw = e.read().decode("utf-8")
+ try:
+ return e.code, json.loads(raw)
+ except json.JSONDecodeError:
+ return e.code, {"raw": raw}
+
+
+def login(base: str, username: str, password: str, tenant: str | None = None):
+ payload = {"username": username, "password": rsa_encrypt(password)}
+ if tenant:
+ payload["tenantCode"] = tenant
+ return call("POST", f"{base}/api/v1/auth/login", body=payload)
+
+
+def scene(base: str, value: str, token: str | None = None) -> dict:
+ """调 scene-context,返回 data。"""
+ url = f"{base}/api/v1/mp/scene-context?scene={urllib.parse.quote(value)}"
+ _, body = call("GET", url, token)
+ return body.get("data") or {}
+
+
+def scene_raw(base: str, value: str) -> tuple[int, dict]:
+ url = f"{base}/api/v1/mp/scene-context?scene={urllib.parse.quote(value)}"
+ return call("GET", url)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description="扫码落地页 E2E")
+ ap.add_argument("--base", default=os.environ.get("XT_BASE", "http://localhost:8080"))
+ ap.add_argument("--tenant", default=os.environ.get("XT_TENANT", "demo"))
+ ap.add_argument("--password", default="Admin@123")
+ args = ap.parse_args()
+ base = args.base.rstrip("/")
+
+ print("=" * 72)
+ print(f"扫码落地页 E2E base={base}")
+ print(" (本接口是匿名的 —— 学生登录前就要用;测试也刻意不带 token)")
+ print("=" * 72)
+
+ suffix = uuid.uuid4().hex[:6]
+ redis(["DEL", "xt:mp:scene:rate:127.0.0.1"])
+
+ # ── 0. 准备(用管理员造数据,但 scene 查询都不带 token)────
+ print("\n[0] 准备")
+ status, body = login(base, "admin", args.password, args.tenant)
+ if body.get("code") != 0:
+ fail("管理员登录", f"code={body.get('code')} msg={body.get('msg')}")
+ return 1
+ token = body["data"]["token"]
+ tenant_id = (body["data"].get("tenant") or {}).get("id")
+ ok(f"管理员登录(租户 id={tenant_id})")
+
+ # 本次要用的任务
+ status, body = call("POST", f"{base}/api/v1/tasks", token, {
+ "taskName": f"E2E落地页 {suffix}", "collectMode": 1, "batchNo": "2005",
+ "majorName": "数控加工", "certType": 1,
+ "startTime": "2026-09-28", "endTime": "2026-12-31",
+ })
+ if body.get("code") != 0:
+ fail("建任务", f"code={body.get('code')} msg={body.get('msg')}")
+ return 1
+ task_id = body["data"]["id"]
+ CREATED_TASK_IDS.append(task_id)
+ ok(f"建任务(id={task_id},草稿状态)")
+
+ status, body = call("GET", f"{base}/api/v1/orgs/tree", token)
+ classes: list[dict] = []
+
+ def walk(nodes):
+ for n in nodes or []:
+ if n.get("orgType") == 3:
+ classes.append(n)
+ walk(n.get("children"))
+
+ walk(body.get("data"))
+ if not classes:
+ fail("取班级", "demo 租户里没有班级")
+ return 1
+
+ # ── 1. 正常 scene(匿名)─────────────────────────────
+ print("\n[1] 正常 scene(匿名,不带 token)")
+ d = scene(base, f"t{tenant_id}-k{task_id}")
+ check("返回租户名(学生要能确认扫对了学校)", bool(d.get("tenantName")),
+ f"tenantName={d.get('tenantName')}")
+ check("返回任务名", d.get("taskName") == f"E2E落地页 {suffix}", f"taskName={d.get('taskName')}")
+ check("草稿状态 → 尚未发布", d.get("taskStatusText") == "尚未发布", f"{d.get('taskStatusText')}")
+ check("草稿不可填报", d.get("canSubmit") is False, f"canSubmit={d.get('canSubmit')}")
+ check("提示语是「尚未开始」(不是笼统的不可填报)",
+ "尚未开始" in (d.get("message") or ""), f"message={d.get('message')}")
+ check("valid 为 true", d.get("valid") is True, f"valid={d.get('valid')}")
+
+ # ── 2. 各种非法输入要给不同的提示 ─────────────────────
+ print("\n[2] 非法输入:提示要各不相同(否则学生不知道该找谁)")
+ d_garbage = scene(base, "garbage")
+ d_no_tenant = scene(base, "t99999999-k1")
+ d_no_task = scene(base, f"t{tenant_id}-k99999999")
+ check("乱码 → 不是本系统的二维码", "不是本系统生成" in (d_garbage.get("message") or ""),
+ f"{d_garbage.get('message')}")
+ check("不存在的租户 → 单位不存在", "单位不存在" in (d_no_tenant.get("message") or ""),
+ f"{d_no_tenant.get('message')}")
+ check("不存在的任务 → 任务不存在", "任务不存在" in (d_no_task.get("message") or ""),
+ f"{d_no_task.get('message')}")
+ msgs = {d_garbage.get("message"), d_no_tenant.get("message"), d_no_task.get("message")}
+ check("三种失败的提示互不相同(不是同一句话敷衍)", len(msgs) == 3, f"{msgs}")
+
+ # ── 3. 租户级 scene ──────────────────────────────────
+ print("\n[3] 租户级 scene(M0 开通租户时约定的 t{tenantId})")
+ d_tenant = scene(base, f"t{tenant_id}")
+ check("租户级码有效但提示去扫任务码",
+ d_tenant.get("valid") is True and "填报二维码" in (d_tenant.get("message") or ""),
+ f"valid={d_tenant.get('valid')} message={d_tenant.get('message')}")
+ check("租户级码没有任务信息", d_tenant.get("taskId") is None, f"{d_tenant.get('taskId')}")
+
+ # ── 4. 带班级 ────────────────────────────────────────
+ print("\n[4] 带班级的 scene")
+ d_not_covered = scene(base, f"t{tenant_id}-k{task_id}-o{classes[0]['id']}")
+ check("班级不在覆盖范围时不返回 orgName(不能凭空显示一个班)",
+ d_not_covered.get("orgName") is None, f"orgName={d_not_covered.get('orgName')}")
+
+ call("PUT", f"{base}/api/v1/tasks/{task_id}/orgs", token,
+ {"orgs": [{"orgId": classes[0]["id"]}]})
+ d_covered = scene(base, f"t{tenant_id}-k{task_id}-o{classes[0]['id']}")
+ check("班级在覆盖范围时返回班级名",
+ d_covered.get("orgName") == classes[0]["orgName"],
+ f"orgName={d_covered.get('orgName')} 期望={classes[0]['orgName']}")
+ check("带班不影响任务信息", d_covered.get("taskId") == task_id, f"{d_covered.get('taskId')}")
+
+ # ── 5. 跨租户 ────────────────────────────────────────
+ print("\n[5] 跨租户:A 租户的 scene 拼 B 租户的任务 id")
+ status, plat = login(base, "platform", "Platform@123")
+ other_task_id = None
+ if plat.get("code") == 0:
+ plat_token = plat["data"]["token"]
+ other_code = f"scn{suffix}"
+ status, body = call("POST", f"{base}/api/v1/tenants", plat_token, {
+ "tenantName": f"E2E扫码隔离 {suffix}", "tenantCode": other_code, "tenantType": 1,
+ "contactName": "测试", "contactPhone": "13900139601", "expireTime": "2027-12-31",
+ "adminUsername": "admin", "adminRealName": "隔离管理员", "adminPhone": "13900139602",
+ })
+ if body.get("code") == 0:
+ other_tenant_id = body["data"]["id"]
+ other_pwd = body["data"]["adminInitialPassword"]
+ CREATED_TENANT_IDS.append(other_tenant_id)
+ login(base, "admin", other_pwd, other_code)
+ _, ob = login(base, "admin", other_pwd, other_code)
+ if ob.get("code") == 0:
+ ot = ob["data"]["token"]
+ _, tb = call("POST", f"{base}/api/v1/tasks", ot, {
+ "taskName": f"别校的任务 {suffix}", "collectMode": 1, "batchNo": "2011",
+ "majorName": "x", "certType": 1,
+ "startTime": "2026-09-28", "endTime": "2026-12-31",
+ })
+ if tb.get("code") == 0:
+ other_task_id = tb["data"]["id"]
+ sql(f"DELETE FROM collect_task WHERE id = {other_task_id}") # 用 SQL 收尾更省事
+ if other_task_id:
+ d_cross = scene(base, f"t{tenant_id}-k{other_task_id}")
+ check("用 A 租户的租户号 + B 租户的任务 id → 任务不存在(不跨租户泄露)",
+ "任务不存在" in (d_cross.get("message") or ""), f"message={d_cross.get('message')}")
+ d_cross2 = scene(base, f"t{CREATED_TENANT_IDS[0]}-k{task_id}")
+ check("反过来(B 的租户号 + A 的任务 id)也不泄露",
+ "任务不存在" in (d_cross2.get("message") or ""), f"message={d_cross2.get('message')}")
+ else:
+ fail("跨租户用例", "第二个租户没造出来,这条隔离断言没执行")
+
+ # ── 6. 状态文案随状态变化 ────────────────────────────
+ print("\n[6] 状态文案:五种状态给五句不同的话")
+ sql(f"INSERT INTO collect_roster (tenant_id, task_id, real_name, id_card_no, id_card_hash) "
+ f"VALUES ({tenant_id}, {task_id}, 'E2E学生A', 'seed', 'seed')")
+ sql(f"INSERT INTO collect_material_def (tenant_id, task_id, material_code, material_name, required) "
+ f"VALUES ({tenant_id}, {task_id}, 'IDCARD', '身份证', 1)")
+
+ call("POST", f"{base}/api/v1/tasks/{task_id}/publish", token, {"force": True})
+ d_collecting = scene(base, f"t{tenant_id}-k{task_id}")
+ check("收集中 → 可填报", d_collecting.get("canSubmit") is True,
+ f"canSubmit={d_collecting.get('canSubmit')} status={d_collecting.get('taskStatusText')}")
+ check("收集中 → 提示「开始填报」",
+ "开始填报" in (d_collecting.get("message") or ""), f"{d_collecting.get('message')}")
+
+ call("POST", f"{base}/api/v1/tasks/{task_id}/pause", token, {})
+ d_paused = scene(base, f"t{tenant_id}-k{task_id}")
+ check("已暂停 → 不可填报", d_paused.get("canSubmit") is False, f"{d_paused.get('canSubmit')}")
+ check("已暂停 → 提示等恢复通知(不是「已截止」,学生的下一步动作完全不同)",
+ "暂停" in (d_paused.get("message") or ""), f"{d_paused.get('message')}")
+
+ call("POST", f"{base}/api/v1/tasks/{task_id}/resume", token)
+ call("POST", f"{base}/api/v1/tasks/{task_id}/close", token, {})
+ d_closed = scene(base, f"t{tenant_id}-k{task_id}")
+ check("已截止 → 不可填报", d_closed.get("canSubmit") is False, f"{d_closed.get('canSubmit')}")
+ check("已截止 → 提示联系班主任补交(§7.12:码不做失效,靠这句话说明状态)",
+ "截止" in (d_closed.get("message") or "") and "班主任" in (d_closed.get("message") or ""),
+ f"{d_closed.get('message')}")
+ check("截止后仍能查到任务(码永久有效)", d_closed.get("taskName") == f"E2E落地页 {suffix}",
+ f"{d_closed.get('taskName')}")
+
+ # ── 7. 限流 ──────────────────────────────────────────
+ print("\n[7] 限流:scene 可穷举,必须挡得住批量扫描")
+ rate_key = None
+ okk, out = redis(["--scan", "--pattern", "xt:mp:scene:rate:*"])
+ if okk and out.strip():
+ rate_key = out.strip().splitlines()[0]
+ if rate_key:
+ redis(["DEL", rate_key])
+ codes = []
+ for i in range(25):
+ st, b = scene_raw(base, f"t{tenant_id}-k{task_id}")
+ codes.append((st, b.get("code")))
+ # 前 20 次应成功(code=0),第 21 次起应被限流
+ passed_n = sum(1 for st, c in codes if c == 0)
+ limited_n = sum(1 for st, c in codes if c == 40071)
+ check("前 20 次正常通过", passed_n == 20, f"通过 {passed_n} 次")
+ check("第 21 次起被限流(40071)", limited_n == 5, f"被限 {limited_n} 次")
+ check("限流用的是项目的 GATE_RATE_LIMITED(40071),不是自制错误码",
+ any(c == 40071 for _, c in codes), f"{set(c for _, c in codes)}")
+ redis(["DEL", rate_key])
+ _, after = scene_raw(base, f"t{tenant_id}-k{task_id}")
+ check("清掉计数器后立刻恢复(说明是限流不是封禁)", after.get("code") == 0,
+ f"code={after.get('code')}")
+ else:
+ fail("限流用例", "没找到限流键,说明限流可能没生效")
+
+ # ── 8. 清理 ──────────────────────────────────────────
+ print("\n[8] 清理测试数据")
+ cleanup_all()
+ ok(f"已清理 {len(CREATED_TASK_IDS)} 个任务、{len(CREATED_TENANT_IDS)} 个测试租户")
+
+ print("\n" + "=" * 72)
+ print(f"通过 {len(PASSED)} 失败 {len(FAILED)} 共 {len(PASSED) + len(FAILED)}")
+ if FAILED:
+ print("\n失败项:")
+ for name, detail in FAILED:
+ print(f" · {name}\n {detail}")
+ print("=" * 72)
+ return 1 if FAILED else 0
+
+
+if __name__ == "__main__":
+ try:
+ code = main()
+ except BaseException:
+ print("\n ⚠ 脚本异常退出,正在清理…")
+ cleanup_all()
+ raise
+ raise SystemExit(code)