Compare commits

..
2 Commits
Author SHA1 Message Date
chenxing 48cd8884d8 fix(notice): 已读明细空态 receivers 不可变列表修复 + SDK 暴露面测试补齐
build / build-push (push) Successful in 1m2s
- NoticeService.getReadDetailGrouped:receivers 空态(全员通知)返回不可变 emptyList,追加已读者前先拷贝为 ArrayList,避免 UnsupportedOperationException
- 新增 NoticeReadDetailGroupedAllTypeTest、NoticeSdkAdviceExposureTest
2026-10-10 15:17:08 +08:00
chenxing b85f5e16fb feat(notice): 移动端 API 接口面(/mobiapi)——路径常量闭集、访问拦截器与控制器
- Config:API_PATH 由通配 /{platform} 收敛为 /api(PC 管理端,CAS 会话),新增 MOBI_API_PATH=/mobiapi(移动端,平台 Bearer token)
- 新增 MobiAccessInterceptor:移动端访问拦截(token 校验)
- 新增 MobiWebMvcConfig:挂载 /mobiapi 前缀与拦截器
- 新增 BaseMobiController / NoticeMobiController:移动端通知接口
- 随附测试:MobiAccessInterceptorTest / MobiWebMvcConfigTest / NoticeMobiControllerTest
2026-10-10 15:17:06 +08:00
11 changed files with 748 additions and 2 deletions
@@ -0,0 +1,34 @@
package com.yunhai.notice.common.interceptor;
import com.yunhai.platform.auth.BoaUserContext;
import com.yunhai.platform.auth.UserContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 移动端 /mobiapi 访问拦截(口径 = 登录即可访问)。
* <p>不做访问级别判级——移动端主体含学生(旧 SUPER/BUREAU/SCHOOL/NONE 判级照抄会全 403)。
* token 解析、401+40101 信封与 pre-token 豁免由平台 SDK {@code LoginUserInterceptor} 承担
* (tokenSurfaces 缺省 /mobiapi);本拦截器是业务侧兜底:SDK 之后的任何 /mobiapi 业务请求,
* 身份上下文为空即 401,防止依赖链路变化时出现"匿名可达的业务端点"。</p>
*/
public class MobiAccessInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (UserContextHolder.get() == null && BoaUserContext.get() == null) {
try {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(
"{\"code\":40101,\"msg\":\"未登录或登录已过期\",\"data\":null}");
} catch (Exception ignored) {
// 响应已提交等场景:状态码已设置,写体失败不掩盖原始语义
}
return false;
}
return true;
}
}
@@ -1,11 +1,14 @@
package com.yunhai.notice.config; package com.yunhai.notice.config;
/** /**
* 全局路径常量。与 UserBase 一致:API 统一挂在 /{platform}/ 之下(platform = api / manage / mobiapi)。 * 全局路径常量(三层接口面,闭集):/api PC 管理端(CAS)、/mobiapi 移动端(token)、/oapi 开放接口(应用签名)。
* 其余前缀(如旧 /manage、/{platform} 通配)一律 404(方案 §4.1 路径闭集)。
*/ */
public enum Config { public enum Config {
Inst; Inst;
public static final String API_PATH = "/{platform}"; // manage / api / mobiapi,前面有/后面无/,拼接子路径时用"/"分隔 // 末尾不带斜杠:各控制器用 API_PATH + "/xxx/" 拼路径,若这里带尾斜杠会拼出字面双斜杠而 404
public static final String API_PATH = "/api"; // PC 管理端(CAS 会话)
public static final String MOBI_API_PATH = "/mobiapi"; // 移动端(平台 Bearer token)
public static final String OPEN_API_PATH = "/oapi"; public static final String OPEN_API_PATH = "/oapi";
} }
@@ -0,0 +1,27 @@
package com.yunhai.notice.config;
import com.yunhai.notice.common.interceptor.MobiAccessInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 移动端 /mobiapi 拦截装配。
* <p>{@code LOWEST_PRECEDENCE} 保证本配置器在 SDK 的 {@code YhAuthWebMvcConfigurer}
* (无 @Order)之后注册,登录态解析先于本兜底拦截执行。</p>
* <p>排除 {@code /mobiapi/auth/**}:其中 login/bind/exchange 是 SDK 定义的 pre-token 端点
* ({@code LoginUserInterceptor.PRE_TOKEN_ENDPOINTS}),设计上匿名可达——它们是登录链本身,
* 不是"业务免登录端点";logout/jsapiSignature 仍由 SDK 按 token 强制。业务端点无任何白名单。</p>
*/
@Configuration
public class MobiWebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MobiAccessInterceptor())
.addPathPatterns("/mobiapi/**")
.excludePathPatterns("/mobiapi/auth/**")
.order(Ordered.LOWEST_PRECEDENCE);
}
}
@@ -0,0 +1,85 @@
package com.yunhai.notice.controller.mobiapi;
import com.yunhai.notice.config.Config;
import com.yunhai.notice.model.notice.UpFileResultVo;
import com.yunhai.notice.service.IFileService;
import com.yunhai.notice.service.IUserCenterService;
import com.yunhai.platform.utils.model.BoaUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 平台代理域移动端接口(/mobiapi/base/,token 身份)。
* <p>端点从 {@code controller.api.BaseApiController} 按移动端需要迁出,业务逻辑仍在
* {@link IUserCenterService} / {@link IFileService},本控制器仅"取参 → 调 Service → 返回";
* 管理端专用端点留在 api/ 面,本期不删。</p>
* <p>出入参口径与 api 侧一致(路径名沿用旧移动端 base/FilePreview|FileDown 调用形状;
* 文件预览/下载在 api 侧实际位于 FileController 的 file/Down|Preview,此处对齐其
* IFileService 签名)。登出不在此暴露——SDK 已提供 {@code POST /mobiapi/auth/logout}。</p>
*/
@RestController
@RequestMapping(value = Config.MOBI_API_PATH + "/base/")
public class BaseMobiController {
@Autowired
private IUserCenterService userCenterService;
@Autowired
private IFileService fileService;
/** 获取当前登录用户信息(token 链注入)。 */
@GetMapping("GetUserInfo")
public BoaUser getUserInfo(BoaUser authUserWithDept) {
return authUserWithDept;
}
/** 获取当前用户已授权的模块列表(移动端仅用于发布权限判定)。 */
@GetMapping("GetUserMod")
public List<Map<String, Object>> getUserMod(BoaUser authUserWithDept) {
Integer schId = authUserWithDept.getCurrentRole() != null
? authUserWithDept.getCurrentRole().getSchId() : null;
return userCenterService.getUserModuleTree(authUserWithDept.getId(), schId);
}
/** 获取当前用户学校组及用户(树形结构)。 */
@GetMapping("GetSchoolAll")
public List<Map<String, Object>> getSchoolAll(BoaUser authUserWithDept) {
Integer schId = authUserWithDept.getCurrentRole() != null
? authUserWithDept.getCurrentRole().getSchId() : null;
return userCenterService.getSchoolAllTree(schId);
}
/** 获取指定组内用户(教师 + 管理员)。 */
@GetMapping("GetGroupUser")
public List<Map<String, Object>> getGroupUser(
@RequestParam("gid") Integer gid,
@RequestParam(value = "role", defaultValue = "2") Integer role) {
return userCenterService.getGroupUser(gid, role);
}
/** 附件上传(单文件)。返回 { fileid, host, fileurl, name, type, size }。 */
@PostMapping("FileUpload")
public UpFileResultVo fileUpload(@RequestParam("file") MultipartFile file) {
return fileService.uploadToResult(file, "notice");
}
/** 附件在线预览(inline 输出,前端取 Blob 渲染;type 兼容旧调用参数)。 */
@GetMapping("FilePreview")
public void filePreview(@RequestParam("id") Integer id,
@RequestParam(value = "type", required = false) Integer type,
HttpServletResponse response) {
fileService.preview(id, response);
}
/** 附件下载。 */
@GetMapping("FileDown")
public void fileDown(@RequestParam("id") Integer id, HttpServletResponse response) {
fileService.download(id, response);
}
}
@@ -0,0 +1,86 @@
package com.yunhai.notice.controller.mobiapi;
import com.yunhai.notice.config.Config;
import com.yunhai.notice.model.BasePageResult;
import com.yunhai.notice.model.notice.*;
import com.yunhai.notice.service.INoticeService;
import com.yunhai.notice.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortDefault;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 通知公告移动端接口(/mobiapi 面,token 身份)。
* <p>路径前缀:{@code Config.MOBI_API_PATH + "/notice/"};方法名/参数与
* {@code controller.api.NoticeController} 保持一致,注入同一 {@link INoticeService},
* 不改 Service 实现;返回裸对象,由 ApiResponseAdvice 统一包装 {code, msg, data}。</p>
* <p>口径:登录即可访问(移动端主体含学生),不按管理端访问级别判级;
* 拦截与 401 语义见 {@code config.MobiWebMvcConfig} / {@code common.interceptor.MobiAccessInterceptor}。</p>
*/
@RestController
@RequestMapping(value = Config.MOBI_API_PATH + "/notice/")
public class NoticeMobiController {
@Autowired
private INoticeService noticeService;
/** 已收通知列表。 */
@GetMapping("List")
public NoticePageResult<NoticeVo> list(NoticeQuery query,
@SortDefault(sort = {"topmost", "createTime"},
direction = Sort.Direction.DESC) Sort sort) {
return noticeService.userList(query, PageUtils.toPageable(query, sort));
}
/** 已发/全部通知列表(type=user 只看自己)。 */
@GetMapping("SendList")
public BasePageResult<NoticeVo> sendList(NoticeQuery query,
@SortDefault(sort = "createTime",
direction = Sort.Direction.DESC) Sort sort) {
return noticeService.adminList(query, PageUtils.toPageable(query, sort));
}
/** 查看通知详情(type=1 标记已读,type=0 不标记)。 */
@GetMapping("Detail")
public NoticeDetailVo detail(@RequestParam("serid") Integer serid,
@RequestParam(value = "type", defaultValue = "1") Integer type) {
return noticeService.detailMap(serid, type);
}
/** 阅读情况(按学校组分组)。 */
@GetMapping("ReadDetail")
public List<Map<String, Object>> readDetail(@RequestParam("serid") Integer serid) {
return noticeService.getReadDetailGrouped(serid);
}
/** 催收未读。 */
@PostMapping("Expedite")
public void expedite(@RequestParam("serid") Integer serid) {
noticeService.expedite(serid);
}
/** 一键全部已读。 */
@PostMapping("InitializeRed")
public InitializeRedVo initializeRed() {
return noticeService.initializeRedResult();
}
/** 上一篇/下一篇通知ID({prevId, nextId},0=无)。 */
@GetMapping("GetNextPrev")
public Map<String, Object> getNextPrev(@RequestParam("serid") Integer serid,
@RequestParam("type") String type) {
return noticeService.getNextPrev(serid, type);
}
/** 批量下载通知全部附件(打包 zip)。 */
@GetMapping("AllFileDown")
public void allFileDown(@RequestParam("dataid") Integer dataid,
HttpServletResponse response) {
noticeService.downloadAllFiles(dataid, response);
}
}
@@ -707,6 +707,8 @@ public class NoticeService implements INoticeService {
if (receivers.isEmpty()) { if (receivers.isEmpty()) {
receivers = parseReceiveAccounts(notice.getReceiveList()); receivers = parseReceiveAccounts(notice.getReceiveList());
} }
// 空态(ALL 全员通知)返回的是不可变 emptyList,先拷贝再追加
receivers = new ArrayList<>(receivers);
// 已读者不在接收明细中(如追送/数据修补),补充到末尾,保证已读情况完整 // 已读者不在接收明细中(如追送/数据修补),补充到末尾,保证已读情况完整
for (String account : readAccounts) { for (String account : readAccounts) {
if (!receivers.contains(account)) { if (!receivers.contains(account)) {
@@ -0,0 +1,76 @@
package com.yunhai.notice.common.interceptor;
import com.yunhai.platform.auth.BoaUserContext;
import com.yunhai.platform.auth.LoginUser;
import com.yunhai.platform.auth.UserContextHolder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 移动端兜底拦截契约(批次3 T5):<br>
* ① 上下文为空 → 401 + 40101 信封;② 非空 → 放行;<br>
* ③ 断言不存在访问级别判级:最低权限制用户(学生 NONE:无角色/无学校语境)同样放行——
* 移动端主体含学生,照抄管理端 SUPER/BUREAU/SCHOOL/NONE 判级会全 403。
*/
@DisplayName("MobiAccessInterceptor - 登录即可,不判级")
class MobiAccessInterceptorTest {
private final MobiAccessInterceptor interceptor = new MobiAccessInterceptor();
@BeforeEach
void setUp() {
UserContextHolder.clear();
BoaUserContext.clear();
}
@AfterEach
void tearDown() {
UserContextHolder.clear();
BoaUserContext.clear();
}
@Test
@DisplayName("上下文为空 → 401 + 40101 信封")
void anonymousRejected401() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mobiapi/notice/List");
MockHttpServletResponse res = new MockHttpServletResponse();
boolean pass = interceptor.preHandle(req, res, new Object());
assertFalse(pass);
assertEquals(401, res.getStatus());
assertEquals("{\"code\":40101,\"msg\":\"未登录或登录已过期\",\"data\":null}",
res.getContentAsString());
}
@Test
@DisplayName("LoginUser 在位 → 放行")
void loginContextPasses() {
UserContextHolder.set(new LoginUser());
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mobiapi/notice/List");
MockHttpServletResponse res = new MockHttpServletResponse();
assertTrue(interceptor.preHandle(req, res, new Object()));
assertEquals(200, res.getStatus());
}
@Test
@DisplayName("BoaUser 在位(无角色/学校语境的学生形态)→ 放行,无判级")
void studentShapedContextPassesWithoutLevelCheck() {
// 故意不设任何角色/权限字段:若实现引入访问级别判级,本用例将开始失败(回归哨)
BoaUserContext.set(new com.yunhai.platform.utils.model.BoaUser());
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mobiapi/notice/List");
MockHttpServletResponse res = new MockHttpServletResponse();
assertTrue(interceptor.preHandle(req, res, new Object()));
assertEquals(200, res.getStatus());
}
}
@@ -0,0 +1,86 @@
package com.yunhai.notice.config;
import com.yunhai.notice.common.interceptor.MobiAccessInterceptor;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 移动端拦截装配契约(批次3 T5):/mobiapi/** 已注册兜底拦截、/mobiapi/auth/** 豁免
* (SDK pre-token 端点 login/bind/exchange 是登录链本身,设计上匿名可达)。
*/
@DisplayName("MobiWebMvcConfig - 拦截装配")
class MobiWebMvcConfigTest {
@Test
@DisplayName("/mobiapi/** 注册 MobiAccessInterceptor 且豁免 /mobiapi/auth/**")
void registersMobiInterceptorWithAuthExclusion() throws Exception {
MobiWebMvcConfig config = new MobiWebMvcConfig();
InterceptorRegistry registry = new InterceptorRegistry();
config.addInterceptors(registry);
List<InterceptorRegistration> registrations = registrationsOf(registry);
assertEquals(1, registrations.size(), "应恰好注册一个拦截器");
InterceptorRegistration reg = registrations.get(0);
assertTrue(interceptorOf(reg) instanceof MobiAccessInterceptor,
"拦截器类型应为 MobiAccessInterceptor");
assertEquals(Arrays.asList("/mobiapi/**"), pathPatternsOf(reg), "拦截面应为 /mobiapi/**");
assertEquals(Arrays.asList("/mobiapi/auth/**"), excludePatternsOf(reg),
"豁免面应为 /mobiapi/auth/**(pre-token 端点是登录链,非业务白名单)");
}
// ---- InterceptorRegistration 无公开读取器,用反射断言(结构契约测试口径) ----
private static Object interceptorOf(InterceptorRegistration reg) throws Exception {
Field f = InterceptorRegistration.class.getDeclaredField("interceptor");
f.setAccessible(true);
return f.get(reg);
}
private static List<InterceptorRegistration> registrationsOf(InterceptorRegistry registry) throws Exception {
Field f = InterceptorRegistry.class.getDeclaredField("registrations");
f.setAccessible(true);
@SuppressWarnings("unchecked")
List<InterceptorRegistration> list = (List<InterceptorRegistration>) f.get(registry);
return list;
}
private static List<String> pathPatternsOf(InterceptorRegistration reg) throws Exception {
Object include = patternsField(reg, "includePatterns");
return asStringList(include, "/mobiapi/**");
}
private static List<String> excludePatternsOf(InterceptorRegistration reg) throws Exception {
Object exclude = patternsField(reg, "excludePatterns");
return asStringList(exclude, "/mobiapi/auth/**");
}
private static Object patternsField(InterceptorRegistration reg, String name) throws Exception {
Field f = InterceptorRegistration.class.getDeclaredField(name);
f.setAccessible(true);
return f.get(reg);
}
private static List<String> asStringList(Object patterns, String expectedSingle) {
// PatternsRequestCondition 内部持有 List<String>(PathMatcher 语义,Ant 风格)
assertNotNull(patterns, "注册时必须显式声明路径模式(缺 " + expectedSingle + ")");
List<String> out = new ArrayList<>();
if (patterns instanceof Iterable) {
for (Object o : (Iterable<?>) patterns) {
out.add(String.valueOf(o));
}
}
return out;
}
}
@@ -0,0 +1,152 @@
package com.yunhai.notice.controller.mobiapi;
import com.yunhai.notice.model.notice.NoticeDetailVo;
import com.yunhai.notice.model.notice.NoticePageResult;
import com.yunhai.notice.model.notice.NoticeQuery;
import com.yunhai.notice.model.notice.NoticeVo;
import com.yunhai.notice.service.INoticeService;
import com.yunhai.platform.apistd.spring.ApiResponseAdvice;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.data.domain.Sort;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* 移动端通知契约测试(批次3 T5):<br>
* ① 端点齐全性:List/SendList/Detail/ReadDetail/Expedite/InitializeRed/GetNextPrev/AllFileDown 八个映射在位;<br>
* ② 薄透传等价:与 {@code api.NoticeController} 注入同一 INoticeService、同参调用(Mock 入参捕获比对);<br>
* ③ 响应信封 {code,msg,data}(code:0,经 ApiResponseAdvice 包装,standalone MockMvc 注册同款 Advice);<br>
* ④ 401/200:拦截语义属 {@code MobiAccessInterceptorTest},此处验登录上下文在位时 200。
*/
@DisplayName("NoticeMobiController - 契约(端点齐全 / 薄透传 / 信封)")
class NoticeMobiControllerTest {
private INoticeService noticeService;
private NoticeMobiController controller;
@BeforeEach
void setUp() {
noticeService = mock(INoticeService.class);
controller = new NoticeMobiController();
org.springframework.test.util.ReflectionTestUtils.setField(controller, "noticeService", noticeService);
}
/** ① 端点齐全性:八个移动端路径都存在且方法级映射非空 */
@Test
@DisplayName("端点齐全:八路径映射在位")
void allEightEndpointsMapped() {
Set<String> paths = new HashSet<>();
for (Method m : NoticeMobiController.class.getDeclaredMethods()) {
GetMapping gm = m.getAnnotation(GetMapping.class);
PostMapping pm = m.getAnnotation(PostMapping.class);
if (gm != null) {
paths.addAll(Arrays.asList(gm.value()));
}
if (pm != null) {
paths.addAll(Arrays.asList(pm.value()));
}
}
Set<String> expected = new HashSet<>(Arrays.asList(
"List", "SendList", "Detail", "ReadDetail",
"Expedite", "InitializeRed", "GetNextPrev", "AllFileDown"));
Set<String> missing = new HashSet<>(expected);
missing.removeAll(paths);
assertTrue(missing.isEmpty(), "缺少端点: " + missing + ",实际=" + paths);
assertEquals(expected.size(), paths.size(), "出现未预期端点: " + paths);
}
/** ② 薄透传:List 与 api 侧同参(同一 INoticeService.userList(query, pageable)) */
@Test
@DisplayName("薄透传:List 同参透传 INoticeService.userList")
void listDelegatesSameAsApiController() {
NoticeVo vo = new NoticeVo();
vo.setId(82);
vo.setTitle("契约测试");
NoticePageResultStub stub = new NoticePageResultStub(
Collections.singletonList(vo), 1, 1, 10, 1, false, 3);
when(noticeService.userList(any(), any())).thenReturn(stub);
NoticeQuery query = new NoticeQuery();
query.setPageIndex(1);
query.setPageSize(10);
Sort sort = Sort.by(Sort.Direction.DESC, "topmost", "createTime");
NoticePageResult<NoticeVo> out = controller.list(query, sort);
ArgumentCaptor<NoticeQuery> qCap = ArgumentCaptor.forClass(NoticeQuery.class);
ArgumentCaptor<org.springframework.data.domain.Pageable> pCap =
ArgumentCaptor.forClass(org.springframework.data.domain.Pageable.class);
verify(noticeService).userList(qCap.capture(), pCap.capture());
assertEquals(1, qCap.getValue().getPageIndex());
assertEquals(10, qCap.getValue().getPageSize());
assertEquals(10, pCap.getValue().getPageSize());
assertNotNull(pCap.getValue().getSort().getOrderFor("topmost"));
assertEquals(82, out.getContent().get(0).getId());
assertEquals(3, out.getUnreadCount());
}
/** ③ 信封 + ④ 登录态 200:standalone MockMvc + 同款 ApiResponseAdvice(走无 Sort 参数的 Detail) */
@Test
@DisplayName("信封 {code,msg,data} code:0 且登录态 200")
void envelopeShapeAndAuthorized200() throws Exception {
NoticeDetailVo vo = new NoticeDetailVo();
when(noticeService.detailMap(77, 1)).thenReturn(vo);
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new ApiResponseAdvice())
.build();
// 模拟登录上下文(真实链路由 SDK LoginUserInterceptor 写入)
com.yunhai.platform.auth.UserContextHolder.set(new com.yunhai.platform.auth.LoginUser());
try {
mvc.perform(get("/mobiapi/notice/Detail").param("serid", "77").param("type", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.msg").exists())
.andExpect(jsonPath("$.data").exists());
} finally {
com.yunhai.platform.auth.UserContextHolder.clear();
}
}
/** Detail 同参透传(type 默认 1 标读) */
@Test
@DisplayName("薄透传:Detail 同参透传 detailMap(serid,type)")
void detailDelegates() {
NoticeDetailVo vo = new NoticeDetailVo();
when(noticeService.detailMap(77, 1)).thenReturn(vo);
NoticeDetailVo out = controller.detail(77, 1);
assertNotNull(out);
verify(noticeService).detailMap(77, 1);
}
/** 测试桩:避免依赖具体实现类构造(行为等价于 NoticeServiceImpl 返回形状) */
private static class NoticePageResultStub extends com.yunhai.notice.model.notice.NoticePageResult<NoticeVo> {
NoticePageResultStub(List<NoticeVo> content, int total, int pageIndex, int pageSize,
int totalPages, boolean hasNext, long unreadCount) {
super(content, total, pageIndex, pageSize, totalPages, hasNext, unreadCount);
}
}
}
@@ -0,0 +1,112 @@
package com.yunhai.notice.sdk;
import com.yunhai.platform.apistd.ApiResponse;
import com.yunhai.platform.apistd.spring.ApiStdProperties;
import com.yunhai.platform.apistd.spring.GlobalExceptionHandler;
import com.yunhai.platform.openapi.core.OpenApiException;
import com.yunhai.platform.openapi.spring.OpenApiAutoConfiguration;
import com.yunhai.platform.openapi.spring.OpenApiExceptionAdvice;
import com.yunhai.platform.utils.exception.DException;
import com.yunhai.platform.utils.exception.ErrorCode;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* D4 应用级证据(SDK 健壮性自审 2026-09-27):Notice 依赖树上 advice 真的可用的三重证明——
* <ol>
* <li>类可达:Notice classpath(聚合 starter → yh-openapi-spring-boot-starter + yh-api-std)
* 上 OpenApiExceptionAdvice 可加载;</li>
* <li>装配可达:servlet web 应用上下文里仅注册 OpenApiAutoConfiguration(无 YschOpenCall 等
* 其它 bean),嵌套条件装配即产出 advice bean——证明自动注册不依赖应用额外声明;</li>
* <li>行为可达:与 GlobalExceptionHandler 同场,SDK 出向失败落 code=5+档位文案
* (A 档原文 / B 档目标+状态 / C 档通用),非 SDK 异常仍 code=6,401 仍 code=4。</li>
* </ol>
* 本测试在 Notice 工程内运行(对 .m2 中新装 SDK 编译),即"应用上下文里 advice 生效"的
* 发布前等价证明;线上运行时证据另由部署后分档验证补齐。
*/
class NoticeSdkAdviceExposureTest {
@RestController
static class SdkFailureController {
@GetMapping("/sdk/a")
public String addressing() {
// 真实 A 档形态:未配置的调用目标(ServiceDirectory.resolve 的原文)
throw new OpenApiException("unknown call target 'ghost': configure yh.open.services.ghost"
+ " (or yh.call.targets.ghost.base-host) first",
OpenApiException.FailureKind.ADDRESSING, "ghost");
}
@GetMapping("/sdk/b")
public String downstream() {
throw new OpenApiException("OpenAPI request failed: httpStatus=500", 500, "SECRET-DOWN",
OpenApiException.FailureKind.DOWNSTREAM, "usermsg");
}
@GetMapping("/sdk/other")
public String other() {
throw new IllegalStateException("boom");
}
@GetMapping("/sdk/unauthorized")
public String unauthorized() {
throw new DException(ErrorCode.UNAUTHORIZED, "验签失败", null, null, 401);
}
}
@Test
void adviceClass_resolvable_onNoticeClasspath() throws Exception {
assertSame(OpenApiExceptionAdvice.class,
Class.forName("com.yunhai.platform.openapi.spring.OpenApiExceptionAdvice"));
assertSame(OpenApiException.FailureKind.class,
Class.forName("com.yunhai.platform.openapi.core.OpenApiException$FailureKind"));
}
@Test
void adviceBean_autoRegistered_inServletWebContext_withoutAppDeclaration() {
try (AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext()) {
ctx.register(OpenApiAutoConfiguration.class);
ctx.refresh();
assertNotNull(ctx.getBean(OpenApiExceptionAdvice.class),
"仅注册自动装配类(应用零声明)也应产出 advice bean");
}
}
@Test
void sdkFailures_tieredExposure_code5_fallbackIntact() throws Exception {
MockMvc mvc = MockMvcBuilders.standaloneSetup(new SdkFailureController())
.setControllerAdvice(new OpenApiExceptionAdvice(),
new GlobalExceptionHandler(new ApiStdProperties()))
.build();
// A 档:原文透出(可行动配置指引),code≠6
mvc.perform(get("/sdk/a"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(5))
.andExpect(jsonPath("$.msg").value(
"unknown call target 'ghost': configure yh.open.services.ghost"
+ " (or yh.call.targets.ghost.base-host) first"));
// B 档:目标名+HTTP 状态,下游响应体不外露
String body = mvc.perform(get("/sdk/b")).andReturn().getResponse().getContentAsString();
org.junit.jupiter.api.Assertions.assertTrue(body.contains("target=usermsg") && body.contains("HTTP 500"),
body);
org.junit.jupiter.api.Assertions.assertFalse(body.contains("SECRET-DOWN"), body);
// 非 SDK 异常:兜底未被打穿
mvc.perform(get("/sdk/other"))
.andExpect(jsonPath("$.code").value(6))
.andExpect(jsonPath("$.msg").value("内部服务错误"));
// 401 既有语义:code=4
mvc.perform(get("/sdk/unauthorized"))
.andExpect(jsonPath("$.code").value(4))
.andExpect(jsonPath("$.msg").value("验签失败"));
}
}
@@ -0,0 +1,83 @@
package com.yunhai.notice.service.impl;
import com.yunhai.notice.entity.Notice;
import com.yunhai.notice.entity.NoticeRead;
import com.yunhai.notice.repository.NoticeReadRepository;
import com.yunhai.notice.repository.NoticeReceiverRepository;
import com.yunhai.notice.repository.NoticeRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* 回归锁(批次3 T5):ALL 型全员通知的阅读情况分组不得再抛
* {@link UnsupportedOperationException}。<br>
* 根因:receive_list=ALL 时 parseReceiveAccounts 返回不可变空表,
* 历史实现直接在其上追加已读人 → 抛异常(PC api 侧同样命中)。
* 修复 = 追加前 new ArrayList 拷贝;本测试锁死该行为,防回归。
*/
@DisplayName("getReadDetailGrouped - ALL 型通知回归锁")
class NoticeReadDetailGroupedAllTypeTest {
private NoticeRepository noticeRepository;
private NoticeReadRepository noticeReadRepository;
private NoticeReceiverRepository noticeReceiverRepository;
private NoticeService service;
@BeforeEach
void setUp() {
noticeRepository = mock(NoticeRepository.class);
noticeReadRepository = mock(NoticeReadRepository.class);
noticeReceiverRepository = mock(NoticeReceiverRepository.class);
service = new NoticeService();
ReflectionTestUtils.setField(service, "noticeRepository", noticeRepository);
ReflectionTestUtils.setField(service, "noticeReadRepository", noticeReadRepository);
ReflectionTestUtils.setField(service, "noticeReceiverRepository", noticeReceiverRepository);
}
private Notice allTypeNotice() {
Notice n = new Notice();
ReflectionTestUtils.setField(n, "id", 77);
n.setTitle("E2E直发");
n.setReceiveList("ALL");
n.setSchId(990001);
return n;
}
@Test
@DisplayName("ALL 型 + 已读一人:不再抛 UnsupportedOperationException,已读人入组")
void allTypeNotice_appendsReadersWithoutException() {
when(noticeRepository.findById(77)).thenReturn(Optional.of(allTypeNotice()));
NoticeRead read = new NoticeRead();
read.setReaderAccount("flow_liu");
read.setReaderName("刘老师(提交人)");
read.setReadTime(LocalDateTime.of(2026, 9, 27, 15, 14, 25));
when(noticeReadRepository.findByNoticeIdOrderByReadTimeDesc(77))
.thenReturn(Collections.singletonList(read));
// ALL 型不落接收明细
when(noticeReceiverRepository.findByNoticeId(77)).thenReturn(Collections.emptyList());
List<Map<String, Object>> groups = assertDoesNotThrow(() -> service.getReadDetailGrouped(77));
// 用户中心未装配(单测环境)→ 归「其他」组;已读人必须在列且状态 read
assertEquals(1, groups.size());
assertEquals("其他", groups.get(0).get("GroupName"));
@SuppressWarnings("unchecked")
List<Map<String, Object>> teas = (List<Map<String, Object>>) groups.get(0).get("teaslist");
assertEquals(1, teas.size());
assertEquals("flow_liu", teas.get(0).get("account"));
assertEquals("read", teas.get(0).get("states"));
}
}