Procházet zdrojové kódy

Merge branch 'task/S-cfc-274' into cfclub

Sisyphus před 5 dny
rodič
revize
b0a212a183

+ 303 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/AssessmentPlannerSelectContractTest.java

@@ -0,0 +1,303 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.assessment.AssessmentAppointmentController;
+import com.etotem.cfc.controller.family.BindController;
+import com.etotem.cfc.entity.AssessmentAppointment;
+import com.etotem.cfc.entity.AssessmentQuota;
+import com.etotem.cfc.entity.DanAssessmentExecution;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.AssessmentAppointmentService;
+import com.etotem.cfc.service.AssessmentQuotaService;
+import com.etotem.cfc.service.DanAssessmentExecutionService;
+import com.etotem.cfc.service.GuideFamilyAccessGuard;
+import com.etotem.cfc.service.GuideFamilyService;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 契约级单测 · 能力键 {@code assessment.planner.select}(S-cfc-274,TDD-RED)。
+ *
+ * <p><b>契约溯源</b></p>
+ * <ul>
+ *   <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-P-32(选择规划师)——
+ *       <blockquote>目标:指定服务规划师。流程:测评选规划师 → 绑定的 T 列表。
+ *       边界:未绑定规划师提示先绑定。模块:测评订单。</blockquote></li>
+ *   <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.10 测评
+ *       {@code POST /api/assessment/appointment/create}(预约前需规划师绑定)。</li>
+ * </ul>
+ *
+ * <p><b>能力边界/方向</b>:家长侧选规划师 = 测评预约时,所选规划师(guideId)必须属于
+ * 该家庭<b>已绑定</b>的 T(指导师/规划师)列表;未绑定规划师 → 提示先绑定。
+ * 与 {@code teacher.family.bind}(S-cfc-190,规划师侧接家庭,走
+ * {@link GuideFamilyAccessGuard#checkBinding})方向相反,本能力以家庭维度(familyId)
+ * 反查绑定列表,不引入规划师侧守卫。</p>
+ *
+ * <p><b>实现现状(RED 依据,cfclub 核实)</b>:
+ * <ul>
+ *   <li>{@link AssessmentAppointmentController#createAppointment} 仅参数级校验
+ *       (assessorId/guideId 至少其一),未校验所选规划师 ∈ 家庭绑定列表;家庭未绑定
+ *       规划师时返回泛参数错误「assessorId或guideId必须提供一个」,而非「请先绑定规划师」。</li>
+ *   <li>Controller 未注入 {@link GuideFamilyService}(绑定 T 列表数据源);
+ *       {@link AssessmentAppointmentService} 无「规划师绑定校验」方法。</li>
+ * </ul>
+ * 因此本节测以「反射结构契约 + 源码文本契约 + Mockito 行为契约」探测缺失,编译通过、能运行、
+ * 断言失败(红),失败原文清晰可贴(仿同批 TeamProfitHookContractTest / FamilyJoinValidationRulesContractTest)。
+ * </p>
+ *
+ * <p><b>GREEN 升级指引</b>:创建预约前以家庭维度校验所选规划师:
+ * 复用已有 {@link GuideFamilyService#getGuidesByFamily(Long)} /
+ * {@link GuideFamilyService#isBound(Long, Long)}(家长侧绑定 T 列表数据源,
+ * {@code POST /api/bind/guides} 已提供);未绑定 → 返回含「请先绑定规划师」的业务错误;
+ * guideId 不在绑定列表 → 同口径拒绝。上述结构/文本/行为断言即可转绿。</p>
+ */
+class AssessmentPlannerSelectContractTest extends AssessmentPlanContractTestBase {
+
+    /** §4.10 预约创建端点源码(文本契约锚点) */
+    private static final String APPOINTMENT_CONTROLLER_SOURCE =
+            "src/main/java/com/etotem/cfc/controller/assessment/AssessmentAppointmentController.java";
+
+    /** SC-P-32 / TC-P-32-E 边界提示:未绑定规划师提示先绑定 */
+    private static final String MSG_UNBOUND_PLANNER_PROMPT = "请先绑定规划师";
+
+    // ==================== 正常流:家长侧选规划师 → 绑定的 T 列表 ====================
+
+    @Test
+    @DisplayName("正常流-1:预约 Controller 应注入家庭绑定源 GuideFamilyService(预约前需规划师绑定)")
+    void appointmentController_shouldWireBoundPlannerValidation() {
+        boolean wired = false;
+        for (Field f : AssessmentAppointmentController.class.getDeclaredFields()) {
+            if (GuideFamilyService.class.equals(f.getType())) {
+                wired = true;
+                break;
+            }
+        }
+        assertTrue(wired,
+                "[assessment.planner.select] AssessmentAppointmentController 未注入 GuideFamilyService(家庭绑定 T 列表数据源):"
+                        + "契约要求创建预约前校验所选规划师 ∈ 家庭已绑定列表(API_REFERENCE §4.10『预约前需规划师绑定』,"
+                        + "SC-P-32『测评选规划师 → 绑定的 T 列表』)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-2:预约 Service 应提供规划师绑定校验方法(仅绑定规划师可选)")
+    void appointmentService_shouldProvidePlannerBindingValidationMethod() {
+        boolean hasPlannerMethod = false;
+        for (Method m : AssessmentAppointmentService.class.getDeclaredMethods()) {
+            if (m.getName().toLowerCase().contains("planner")) {
+                hasPlannerMethod = true;
+                break;
+            }
+        }
+        assertTrue(hasPlannerMethod,
+                "[assessment.planner.select] AssessmentAppointmentService 缺少规划师绑定校验方法(如 requireBoundPlanner/isPlannerBound):"
+                        + "测评预约只能指定家庭已绑定的规划师(SC-P-32;TC-P-32-E:已解绑 T 不在可选列表,选则拒绝)。实现未落地。");
+    }
+
+    @Test
+    @DisplayName("正常流-3:绑定 T 列表数据源已存在(/api/bind/guides,家长侧;GREEN 复用锚点)")
+    void boundPlannerListSource_bindGuidesEndpointExists() {
+        Class<?> bindController = loadClass(BindController.class.getName());
+        assertNotNull(bindController, "[assessment.planner.select] BindController 应存在(绑定 T 列表入口,SC-P-32)。");
+        boolean hasGetBoundGuides = false;
+        boolean mapsToGuidesPath = false;
+        for (Method m : bindController.getDeclaredMethods()) {
+            if (m.getName().equals("getBoundGuides")) {
+                hasGetBoundGuides = true;
+                PostMapping pm = m.getAnnotation(PostMapping.class);
+                if (pm != null && pm.value().length > 0 && "/guides".equals(pm.value()[0])) {
+                    mapsToGuidesPath = true;
+                }
+            }
+        }
+        assertTrue(hasGetBoundGuides,
+                "[assessment.planner.select] /api/bind/guides 端点(getBoundGuides)应返回家庭已绑定指导师列表,"
+                        + "作为测评选规划师的『绑定的 T 列表』数据源(SC-P-32)。");
+        assertTrue(mapsToGuidesPath,
+                "[assessment.planner.select] getBoundGuides 应映射到 POST /api/bind/guides(家长侧绑定 T 列表)。");
+    }
+
+    // ==================== 异常流:未绑定规划师提示先绑定 ====================
+
+    @Test
+    @DisplayName("异常流-1:预约创建端点源码应包含「请先绑定规划师」提示(SC-P-32 边界)")
+    void createAppointment_shouldContainUnboundPlannerPromptMessage() {
+        String source = readSource(APPOINTMENT_CONTROLLER_SOURCE);
+        assertTrue(source.contains(MSG_UNBOUND_PLANNER_PROMPT),
+                "[assessment.planner.select] AssessmentAppointmentController.createAppointment 缺少「"
+                        + MSG_UNBOUND_PLANNER_PROMPT + "」文案:SC-P-32 边界『未绑定规划师提示先绑定』"
+                        + "(TC-P-32-E:未绑定提示『请先绑定规划师』),当前仅返回泛参数错误"
+                        + "『assessorId或guideId必须提供一个』。实现未落地。(源码路径: " + sourcePathUsed() + ")");
+    }
+
+    @Test
+    @DisplayName("异常流-2:未绑定规划师创建预约 → 应提示先绑定(而非泛参数错误)且不消耗额度")
+    void createAppointment_unboundPlanner_shouldPromptBindFirst_notSilentlyCreate() throws Exception {
+        UserMapper userMapper = mock(UserMapper.class);
+        AssessmentQuotaService quotaSvc = mock(AssessmentQuotaService.class);
+        AssessmentAppointmentService apptSvc = mock(AssessmentAppointmentService.class);
+        DanAssessmentExecutionService execSvc = mock(DanAssessmentExecutionService.class);
+        AssessmentAppointmentController c = new AssessmentAppointmentController();
+        inject(c, "appointmentService", apptSvc);
+        inject(c, "quotaService", quotaSvc);
+        inject(c, "danAssessmentExecutionService", execSvc);
+        inject(c, "userMapper", userMapper);
+
+        User user = new User();
+        user.setId(1L);
+        when(userMapper.selectById(1L)).thenReturn(user);
+
+        // 家庭无绑定规划师:body 未携带 guideId/assessorId
+        Map<String, Object> body = new HashMap<>();
+        body.put("memberId", 10L);
+        body.put("quotaId", 5L);
+
+        Result<Map<String, Object>> r = c.createAppointment(1L, body, null);
+
+        // 契约:未绑定规划师 → 提示先绑定(SC-P-32 边界),不静默创建空预约(TC-B-09-E)
+        assertTrue(r.getMessage() != null && r.getMessage().contains("绑定"),
+                "[assessment.planner.select] 未绑定规划师时 createAppointment 应提示『请先绑定规划师』,"
+                        + "实际返回: " + r.getMessage() + "(当前为泛参数错误『assessorId或guideId必须提供一个』)。实现未落地。");
+        verify(quotaSvc, never()).consumeQuota(anyLong(), anyLong());
+        verify(apptSvc, never()).createAppointment(anyLong(), anyLong(), anyLong(), any(), any(), any(), any(), any());
+    }
+
+    @Test
+    @DisplayName("异常流-3:指定未绑定规划师创建预约 → 应拒绝(预约前需规划师绑定),当前会成功创建(红)")
+    void createAppointment_unboundGuide_shouldRejectInsteadOfSuccess() throws Exception {
+        UserMapper userMapper = mock(UserMapper.class);
+        AssessmentQuotaService quotaSvc = mock(AssessmentQuotaService.class);
+        AssessmentAppointmentService apptSvc = mock(AssessmentAppointmentService.class);
+        DanAssessmentExecutionService execSvc = mock(DanAssessmentExecutionService.class);
+        AssessmentAppointmentController c = new AssessmentAppointmentController();
+        inject(c, "appointmentService", apptSvc);
+        inject(c, "quotaService", quotaSvc);
+        inject(c, "danAssessmentExecutionService", execSvc);
+        inject(c, "userMapper", userMapper);
+
+        User user = new User();
+        user.setId(1L);
+        when(userMapper.selectById(1L)).thenReturn(user);
+        // 模拟当前实现路径:可消耗额度、可创建预约 → 成功响应
+        when(quotaSvc.consumeQuota(5L, 10L)).thenReturn(2);
+        AssessmentQuota quota = new AssessmentQuota();
+        quota.setId(5L);
+        quota.setFamilyId(7L);
+        quota.setProductOrderId(11L);
+        when(quotaSvc.getById(5L)).thenReturn(quota);
+        AssessmentAppointment appt = new AssessmentAppointment();
+        appt.setId(101L);
+        when(apptSvc.createAppointment(anyLong(), anyLong(), anyLong(), any(), any(), any(), any(), any()))
+                .thenReturn(appt);
+        DanAssessmentExecution exec = new DanAssessmentExecution();
+        exec.setId(201L);
+        when(execSvc.createExecution(anyLong(), anyLong(), anyLong(), anyLong(), anyLong(), any(), anyLong()))
+                .thenReturn(exec);
+
+        // 家长指定 guideId=7,但该规划师并未绑定到家庭(家庭维度绑定校验缺失)
+        Map<String, Object> body = new HashMap<>();
+        body.put("memberId", 10L);
+        body.put("guideId", 7L);
+        body.put("quotaId", 5L);
+
+        Result<Map<String, Object>> r = c.createAppointment(1L, body, null);
+
+        // 契约:预约前需规划师绑定(§4.10)→ 未绑定规划师应拒绝,不得成功创建
+        assertTrue(r.getCode() != 200,
+                "[assessment.planner.select] 指定未绑定规划师(guideId=7 不在家庭绑定列表)创建预约竟返回成功(code=200),"
+                        + "违反 API_REFERENCE §4.10『预约前需规划师绑定』(SC-P-32)。"
+                        + "应提示『请先绑定规划师』并拒绝,不消耗额度、不创建预约。实现未落地。");
+        verify(apptSvc, never()).createAppointment(anyLong(), anyLong(), anyLong(), any(), any(), any(), any(), any());
+        verify(quotaSvc, never()).consumeQuota(anyLong(), anyLong());
+    }
+
+    // ==================== 权限流:家长侧 vs 规划师侧(S-cfc-190 区分) ====================
+
+    @Test
+    @DisplayName("权限流-1:家长侧走家庭维度绑定校验,与规划师侧守卫(S-cfc-190)方向区分(锚点)")
+    void permissionFlow_parentSideFamilyDirection_notTeacherSideGuard() {
+        // 规划师侧接家庭守卫已落地(S-cfc-190 teacher.family.bind 方向:guide 维度)
+        assertNotNull(loadClass(GuideFamilyAccessGuard.class.getName()),
+                "[assessment.planner.select] GuideFamilyAccessGuard 应存在(S-cfc-190 规划师侧守卫,作为方向区分的既存物)。");
+        // 家长侧绑定数据源:GuideFamilyService 提供按家庭反查绑定 T 的能力(GREEN 阶段复用)
+        boolean hasFamilyDirection = false;
+        for (Method m : GuideFamilyService.class.getDeclaredMethods()) {
+            if (m.getName().equals("getGuidesByFamily") || m.getName().equals("isBound")) {
+                hasFamilyDirection = true;
+                break;
+            }
+        }
+        assertTrue(hasFamilyDirection,
+                "[assessment.planner.select] GuideFamilyService 应提供家庭维度绑定查询(getGuidesByFamily/isBound),"
+                        + "供家长侧选规划师校验使用(SC-P-32),以区别于规划师侧 checkBinding 方向。");
+        // Controller 注入使用 @Resource(项目 DI 规范),且不依赖规划师侧守卫类型
+        boolean usesResource = false;
+        for (Field f : AssessmentAppointmentController.class.getDeclaredFields()) {
+            if (f.isAnnotationPresent(Resource.class)) {
+                usesResource = true;
+                break;
+            }
+        }
+        assertTrue(usesResource,
+                "[assessment.planner.select] AssessmentAppointmentController 应遵循项目 DI 规范(@Resource 注入字段)。");
+    }
+
+    // ==================== 辅助 ====================
+
+    private Class<?> loadClass(String name) {
+        try {
+            return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private String sourcePathUsed = "";
+
+    private String readSource(String relPath) {
+        String[] candidates = {
+                relPath,
+                "cfc-backend/" + relPath,
+                "../" + relPath,
+                "../cfc-backend/" + relPath
+        };
+        for (String p : candidates) {
+            File f = new File(p);
+            if (f.exists()) {
+                try {
+                    sourcePathUsed = f.getCanonicalPath();
+                    byte[] bytes = Files.readAllBytes(f.toPath());
+                    return new String(bytes, StandardCharsets.UTF_8);
+                } catch (Exception e) {
+                    // 忽略读取异常,尝试下一个候选
+                }
+            }
+        }
+        return "";
+    }
+
+    private String sourcePathUsed() {
+        return sourcePathUsed.isEmpty() ? "未找到" : sourcePathUsed;
+    }
+}