|
|
@@ -0,0 +1,604 @@
|
|
|
+package com.etotem.cfc.unit;
|
|
|
+
|
|
|
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
|
|
+import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
|
|
|
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
|
|
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
|
|
+import com.etotem.cfc.common.AppCodes;
|
|
|
+import com.etotem.cfc.config.DatabaseInitializer;
|
|
|
+import com.etotem.cfc.controller.HealthPlanController;
|
|
|
+import com.etotem.cfc.entity.UserDataPermission;
|
|
|
+import com.etotem.cfc.entity.WmSubscription;
|
|
|
+import com.etotem.cfc.mapper.UserDataPermissionMapper;
|
|
|
+import com.etotem.cfc.service.DataPermissionService;
|
|
|
+import com.etotem.cfc.service.MembershipService;
|
|
|
+import com.etotem.cfc.service.PurchaseService;
|
|
|
+import com.etotem.cfc.service.wm.WmEntitlementService;
|
|
|
+import com.etotem.cfc.service.wm.WmMemberService;
|
|
|
+import org.apache.ibatis.builder.MapperBuilderAssistant;
|
|
|
+import org.junit.jupiter.api.BeforeEach;
|
|
|
+import org.junit.jupiter.api.DisplayName;
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
+import org.mockito.ArgumentCaptor;
|
|
|
+
|
|
|
+import java.io.File;
|
|
|
+import java.io.InputStream;
|
|
|
+import java.lang.reflect.Field;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.Date;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
|
+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.ArgumentMatchers.eq;
|
|
|
+import static org.mockito.Mockito.atLeastOnce;
|
|
|
+import static org.mockito.Mockito.doAnswer;
|
|
|
+import static org.mockito.Mockito.mock;
|
|
|
+import static org.mockito.Mockito.never;
|
|
|
+import static org.mockito.Mockito.times;
|
|
|
+import static org.mockito.Mockito.verify;
|
|
|
+import static org.mockito.Mockito.when;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 多小程序会员体系区分·阶段1(数据层与会员闭环)契约测试(S-cfc-appscope-stage1)。
|
|
|
+ *
|
|
|
+ * <p>覆盖 6 项完成判据(纯 Mockito + schema.sql / DatabaseInitializer 源契约,无 Spring 上下文 / 无 DB):</p>
|
|
|
+ * <ol>
|
|
|
+ * <li><b>P1 统一权益门</b>({@code WmEntitlementService.canGeneratePlan} 三路放行):
|
|
|
+ * CFC_MAIN 会员 / 健康启航计划放行;同一会员身份在 WEIGHT / AIBAN 一律 4001
|
|
|
+ * (不得以主小程序会员身份白拿方案权益);</li>
|
|
|
+ * <li><b>wm_member_plan 唯一键</b>{@code uk_app_tier(app_code, tier_code)}(WEIGHT:M1 与 AIBAN:M1 共存);
|
|
|
+ * <li><b>13 张存量共享业务表</b>已加 {@code app_code VARCHAR(32) NOT NULL DEFAULT 'CFC_MAIN'}
|
|
|
+ * + 高频联合索引(schema.sql 契约 + DatabaseInitializer 迁移466 镜像);</li>
|
|
|
+ * <li><b>P2 授权分端</b>:同 userId 的 WEIGHT 与 CFC_MAIN 两行授权按 {@code (user_id, app_code)}
|
|
|
+ * 独立读写,互不影响;新端首用复制 CFC_MAIN 开关值;</li>
|
|
|
+ * <li><b>存量回归</b>:{@code AppCodes.currentAppCode()} 阶段1 恒为 CFC_MAIN;
|
|
|
+ * {@code HealthPlanController} 已改为统一权益门调用(不再持有存量双 if 判定字段);</li>
|
|
|
+ * <li><b>wm_member_plan 零档位数据</b>:迁移465 仅建表 + seed app_registry CFC_MAIN 一条,
|
|
|
+ * 无任何 INSERT 进 wm_member_plan(价格未拍板)。</li>
|
|
|
+ * </ol>
|
|
|
+ */
|
|
|
+class WmAppScopeStage1ContractTest {
|
|
|
+
|
|
|
+ // ==================================================================
|
|
|
+ // ① P1 统一权益门(WmEntitlementService.canGeneratePlan 三路放行)
|
|
|
+ // ==================================================================
|
|
|
+
|
|
|
+ private WmEntitlementService entitlementService;
|
|
|
+ private MembershipService membershipService;
|
|
|
+ private PurchaseService purchaseService;
|
|
|
+ private WmMemberService wmMemberService;
|
|
|
+
|
|
|
+ @BeforeEach
|
|
|
+ void setUp() throws Exception {
|
|
|
+ ensureTableInfo(UserDataPermission.class);
|
|
|
+ entitlementService = new WmEntitlementService();
|
|
|
+ membershipService = mock(MembershipService.class);
|
|
|
+ purchaseService = mock(PurchaseService.class);
|
|
|
+ wmMemberService = mock(WmMemberService.class);
|
|
|
+ inject(entitlementService, "membershipService", membershipService);
|
|
|
+ inject(entitlementService, "purchaseService", purchaseService);
|
|
|
+ inject(entitlementService, "wmMemberService", wmMemberService);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static boolean tableInfoReady = false;
|
|
|
+
|
|
|
+ /** MP 3.5.x:LambdaQueryWrapper 的 paramNameValuePairs 在 getSqlSegment() 时才惰性填充,
|
|
|
+ * 且列名解析依赖 TableInfo 的 lambda 缓存 —— 先 init 目标实体。 */
|
|
|
+ private static synchronized void ensureTableInfo(Class<?> entity) {
|
|
|
+ if (tableInfoReady) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), "test"), entity);
|
|
|
+ tableInfoReady = true;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void inject(Object target, String field, Object value) throws Exception {
|
|
|
+ Field f = target.getClass().getDeclaredField(field);
|
|
|
+ f.setAccessible(true);
|
|
|
+ f.set(target, value);
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> purchase(boolean isActive) {
|
|
|
+ Map<String, Object> m = new HashMap<>();
|
|
|
+ m.put("isActive", isActive);
|
|
|
+ return m;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-①:CFC_MAIN 家庭/个人会员 → canGeneratePlan 放行(存量回归)")
|
|
|
+ void canGeneratePlan_cfcMainMember_allowed() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("FAMILY");
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, AppCodes.CFC_MAIN);
|
|
|
+ assertTrue(d.isAllowed(), "CFC_MAIN 家庭会员应放行");
|
|
|
+ assertEquals(AppCodes.CFC_MAIN, d.getAppCode());
|
|
|
+ verify(wmMemberService, never()).hasActiveEntitlement(any(), any(), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-②:CFC_MAIN 免费但已购健康启航计划 → canGeneratePlan 放行(存量回归)")
|
|
|
+ void canGeneratePlan_cfcMainQiHang_allowed() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("FREE");
|
|
|
+ when(purchaseService.checkPurchase(100L)).thenReturn(purchase(true));
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, AppCodes.CFC_MAIN);
|
|
|
+ assertTrue(d.isAllowed(), "CFC_MAIN 已购健康启航计划应放行");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-③:CFC_MAIN 免费且未购启航 → 拒绝(4001 路径)")
|
|
|
+ void canGeneratePlan_cfcMainFreeNotPurchased_denied() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("FREE");
|
|
|
+ when(purchaseService.checkPurchase(100L)).thenReturn(purchase(false));
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, AppCodes.CFC_MAIN);
|
|
|
+ assertFalse(d.isAllowed(), "CFC_MAIN 免费且未购启航应拒绝");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-④:WEIGHT 下 CFC_MAIN 家庭会员不得跨端放行(4001)")
|
|
|
+ void canGeneratePlan_weightMemberOfCfcMain_denied() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("FAMILY");
|
|
|
+ when(wmMemberService.hasActiveEntitlement(eq(100L), eq(AppCodes.WEIGHT), any())).thenReturn(false);
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, AppCodes.WEIGHT);
|
|
|
+ assertFalse(d.isAllowed(), "P1:主小程序会员身份不得放行 WEIGHT");
|
|
|
+ verify(wmMemberService).hasActiveEntitlement(eq(100L), eq(AppCodes.WEIGHT),
|
|
|
+ eq(WmEntitlementService.ENT_PLAN_GENERATE));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-⑤:AIBAN 下已购健康启航计划也不得跨端放行(4001)")
|
|
|
+ void canGeneratePlan_aibanQiHang_denied() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("FREE");
|
|
|
+ when(purchaseService.checkPurchase(100L)).thenReturn(purchase(true));
|
|
|
+ when(wmMemberService.hasActiveEntitlement(eq(100L), eq(AppCodes.AIBAN), any())).thenReturn(false);
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, AppCodes.AIBAN);
|
|
|
+ assertFalse(d.isAllowed(), "P1:AIBAN 不得以主小程序健康启航计划身份放行");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-⑥:WEIGHT 已购 wm 会员(有 PLAN_GENERATE 权益)→ 第三路放行 + tierCode")
|
|
|
+ void canGeneratePlan_weightWmMember_allowed() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("FREE");
|
|
|
+ when(wmMemberService.hasActiveEntitlement(100L, AppCodes.WEIGHT, WmEntitlementService.ENT_PLAN_GENERATE))
|
|
|
+ .thenReturn(true);
|
|
|
+ WmSubscription sub = new WmSubscription();
|
|
|
+ sub.setId(1L);
|
|
|
+ sub.setTierCode("M1");
|
|
|
+ when(wmMemberService.getActiveSubscription(100L, AppCodes.WEIGHT)).thenReturn(sub);
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, AppCodes.WEIGHT);
|
|
|
+ assertTrue(d.isAllowed(), "WEIGHT wm 会员应放行");
|
|
|
+ assertEquals("M1", d.getTierCode());
|
|
|
+ assertFalse(d.isDraftOnly(), "M1 非草稿模式");
|
|
|
+ assertEquals(AppCodes.WEIGHT, d.getAppCode());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-⑦:M0 档位 → 仅 draftOnly 放行(不进正式发布队列)")
|
|
|
+ void canGeneratePlan_m0DraftOnly() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("FREE");
|
|
|
+ when(wmMemberService.hasActiveEntitlement(100L, AppCodes.WEIGHT, WmEntitlementService.ENT_PLAN_GENERATE))
|
|
|
+ .thenReturn(true);
|
|
|
+ WmSubscription sub = new WmSubscription();
|
|
|
+ sub.setId(1L);
|
|
|
+ sub.setTierCode("M0");
|
|
|
+ when(wmMemberService.getActiveSubscription(100L, AppCodes.WEIGHT)).thenReturn(sub);
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, AppCodes.WEIGHT);
|
|
|
+ assertTrue(d.isAllowed());
|
|
|
+ assertTrue(d.isDraftOnly(), "M0 应仅 draft=true 初稿");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("P1-⑧:appCode 为空 → 兜底 CFC_MAIN(存量 token 不回归)")
|
|
|
+ void canGeneratePlan_nullAppCode_fallbackCfcMain() {
|
|
|
+ when(membershipService.getMemberLevel(100L)).thenReturn("PERSONAL");
|
|
|
+ WmEntitlementService.Decision d = entitlementService.canGeneratePlan(100L, null);
|
|
|
+ assertTrue(d.isAllowed());
|
|
|
+ assertEquals(AppCodes.CFC_MAIN, d.getAppCode());
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================================================================
|
|
|
+ // ②/⑥ 表契约:唯一键 + 13 表 app_code + 7 新表 + 零档位数据
|
|
|
+ // ==================================================================
|
|
|
+
|
|
|
+ /** 13 张存量共享业务表(迁移466 加 app_code + 索引) */
|
|
|
+ private static final List<String> SHARED_TABLES = Arrays.asList(
|
|
|
+ "health_reports", "health_report_drafts", "health_plans", "report_summary",
|
|
|
+ "tasks", "task_plan_instances", "diet_records", "exercise_record",
|
|
|
+ "fat_weight_record", "fat_diet_record", "fat_exercise_record",
|
|
|
+ "user_consent_records", "user_data_permissions");
|
|
|
+
|
|
|
+ /** 7 张阶段1 新表(迁移465) */
|
|
|
+ private static final List<String> NEW_TABLES = Arrays.asList(
|
|
|
+ "app_registry", "user_app_identity", "wm_member_plan", "wm_subscription",
|
|
|
+ "wm_order", "wm_addon", "wm_entitlement_usage");
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据②:wm_member_plan 存在唯一键 uk_app_tier(app_code, tier_code)")
|
|
|
+ void wmMemberPlan_hasUkAppTier() {
|
|
|
+ String schema = readSchemaSql();
|
|
|
+ String block = tableBlock(schema, "wm_member_plan");
|
|
|
+ assertTrue(normalize(block).contains("UNIQUEKEYuk_app_tier(app_code,tier_code)"),
|
|
|
+ "wm_member_plan 应定义 UNIQUE KEY uk_app_tier(app_code, tier_code),"
|
|
|
+ + "保证 WEIGHT:M1 与 AIBAN:M1 共存(app_code 隔离唯一)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据③:13 张存量表 schema.sql 均含 app_code VARCHAR(32) NOT NULL DEFAULT 'CFC_MAIN' 列")
|
|
|
+ void sharedTables_haveAppCodeColumn() {
|
|
|
+ String schema = readSchemaSql();
|
|
|
+ StringBuilder missing = new StringBuilder();
|
|
|
+ for (String t : SHARED_TABLES) {
|
|
|
+ String block = tableBlock(schema, t);
|
|
|
+ if (!normalize(block).contains("app_codeVARCHAR(32)NOTNULLDEFAULT'CFC_MAIN'")) {
|
|
|
+ missing.append(t).append(" ");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(missing.length() == 0,
|
|
|
+ "下列表 schema.sql 缺少 app_code VARCHAR(32) NOT NULL DEFAULT 'CFC_MAIN' 列: "
|
|
|
+ + missing.toString().trim());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据③b:迁移466 对 13 张表均有 ensureColumn(app_code) 且高频联合索引齐备")
|
|
|
+ void sharedTables_migration466Mirror() {
|
|
|
+ String dbi = readDatabaseInitializerSource();
|
|
|
+ String normalized = normalize(dbi);
|
|
|
+ assertTrue(normalized.contains("迁移466"), "DatabaseInitializer 应有迁移466 注释锚点");
|
|
|
+ StringBuilder missingCol = new StringBuilder();
|
|
|
+ for (String t : SHARED_TABLES) {
|
|
|
+ if (!normalized.contains("ensureColumn(\"" + t + "\",\"app_code\"")) {
|
|
|
+ missingCol.append(t).append(" ");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(missingCol.length() == 0,
|
|
|
+ "迁移466 应对下列表调用 ensureColumn(\"<table>\", \"app_code\", ...): "
|
|
|
+ + missingCol.toString().trim());
|
|
|
+ // 索引清单(与 schema.sql 高频联合索引一一对应)
|
|
|
+ String[] idx = {
|
|
|
+ "health_reports\",\"idx_appcode_user", "health_reports\",\"idx_appcode_subject",
|
|
|
+ "health_report_drafts\",\"idx_appcode_user", "health_plans\",\"idx_appcode_family",
|
|
|
+ "report_summary\",\"idx_appcode_user", "tasks\",\"idx_appcode_status",
|
|
|
+ "tasks\",\"idx_appcode_executor", "task_plan_instances\",\"idx_appcode_family",
|
|
|
+ "diet_records\",\"idx_appcode_member_date", "exercise_record\",\"idx_appcode_member",
|
|
|
+ "fat_weight_record\",\"idx_appcode_member", "fat_diet_record\",\"idx_appcode_member",
|
|
|
+ "fat_exercise_record\",\"idx_appcode_member", "user_consent_records\",\"idx_appcode_user_type",
|
|
|
+ "user_data_permissions\",\"idx_appcode_user"
|
|
|
+ };
|
|
|
+ StringBuilder missingIdx = new StringBuilder();
|
|
|
+ for (String i : idx) {
|
|
|
+ if (!normalized.contains("ensureIndex(\"" + i)) {
|
|
|
+ missingIdx.append(i).append(" ");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(missingIdx.length() == 0,
|
|
|
+ "迁移466 应对下列索引调用 ensureIndex: " + missingIdx.toString().trim());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据②/⑥:7 张新表 schema.sql 齐备;wm_member_plan 零档位数据;app_registry 仅 seed CFC_MAIN")
|
|
|
+ void newTables_existAndZeroSeeds() {
|
|
|
+ String schema = readSchemaSql();
|
|
|
+ StringBuilder missing = new StringBuilder();
|
|
|
+ for (String t : NEW_TABLES) {
|
|
|
+ if (!schema.contains("CREATE TABLE IF NOT EXISTS " + t)) {
|
|
|
+ missing.append(t).append(" ");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(missing.length() == 0, "schema.sql 缺少以下新表 CREATE TABLE: " + missing.toString().trim());
|
|
|
+
|
|
|
+ String dbi = readDatabaseInitializerSource();
|
|
|
+ String normalized = normalize(dbi);
|
|
|
+ // ① 迁移465 建表(正向:表必须被创建)
|
|
|
+ assertTrue(normalized.contains("CREATETABLEIFNOTEXISTSwm_member_plan"),
|
|
|
+ "迁移465 应创建 wm_member_plan 表");
|
|
|
+ // ② 零档位数据:不得向 wm_member_plan INSERT / insertData / insertSysConfigSeed
|
|
|
+ assertFalse(normalized.contains("INTO wm_member_plan"),
|
|
|
+ "迁移465 不得向 wm_member_plan 写入数据(价格未拍板,本轮零档位)");
|
|
|
+ assertFalse(normalized.contains("insertData(\"wm_member_plan"),
|
|
|
+ "迁移465 不得通过 insertData 写 wm_member_plan");
|
|
|
+ assertFalse(normalized.contains("insertSysConfigSeed(\"wm_member_plan"),
|
|
|
+ "迁移465 不得通过 insertSysConfigSeed 写 wm_member_plan");
|
|
|
+ // ③ app_registry 仅初始化 CFC_MAIN 一条(不 seed WEIGHT/AIBAN)
|
|
|
+ String seedMarker = "INSERTIGNOREINTOapp_registry";
|
|
|
+ int seedStart = normalized.indexOf(seedMarker);
|
|
|
+ assertTrue(seedStart >= 0, "迁移465 应 seed app_registry(INSERT IGNORE)");
|
|
|
+ String seed = normalized.substring(seedStart, Math.min(seedStart + 240, normalized.length()));
|
|
|
+ assertTrue(seed.contains("VALUES('CFC_MAIN'"), "app_registry seed 应写入 CFC_MAIN");
|
|
|
+ assertFalse(seed.contains("WEIGHT"), "app_registry seed 不应包含 WEIGHT(WEIGHT/AIBAN 待阶段2)");
|
|
|
+ assertFalse(seed.contains("AIBAN"), "app_registry seed 不应包含 AIBAN(WEIGHT/AIBAN 待阶段2)");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据②b:user_data_permissions 唯一键 uk_user_app(user_id, app_code)(P2 先决 + 迁移467 先去重)")
|
|
|
+ void userDataPermissions_hasUkUserApp() {
|
|
|
+ String schema = readSchemaSql();
|
|
|
+ String block = tableBlock(schema, "user_data_permissions");
|
|
|
+ assertTrue(normalize(block).contains("UNIQUEKEYuk_user_app(user_id,app_code)"),
|
|
|
+ "user_data_permissions 应定义 UNIQUE KEY uk_user_app(user_id, app_code)(P2 分端授权先决)");
|
|
|
+ String dbi = readDatabaseInitializerSource();
|
|
|
+ String normalized = normalize(dbi);
|
|
|
+ assertTrue(normalized.contains("ADDUNIQUEKEYuk_user_app(user_id,app_code)"),
|
|
|
+ "迁移467 应添加 uk_user_app(user_id, app_code) 唯一键");
|
|
|
+ assertTrue(normalized.contains("user_data_permissions") && normalized.contains("MIN(id)")
|
|
|
+ && normalized.contains("GROUPBYuser_id,app_code"),
|
|
|
+ "迁移467 应先对存量 user_id 多行去重(GROUP BY user_id, app_code 保留 MIN(id))再建唯一键");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================================================================
|
|
|
+ // ⑤ 存量回归:阶段1 appCode 服务端常量 + HealthPlanController 统一权益门
|
|
|
+ // ==================================================================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据⑤:AppCodes.currentAppCode() 阶段1 恒为 CFC_MAIN(服务端常量兜底)")
|
|
|
+ void currentAppCode_isCfcMain() {
|
|
|
+ assertEquals(AppCodes.CFC_MAIN, AppCodes.currentAppCode(),
|
|
|
+ "阶段1 appCode 由服务端常量兜底 CFC_MAIN(JWT claim 属阶段2)");
|
|
|
+ assertEquals("CFC_MAIN", AppCodes.CFC_MAIN);
|
|
|
+ assertEquals("WEIGHT", AppCodes.WEIGHT);
|
|
|
+ assertEquals("AIBAN", AppCodes.AIBAN);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据⑤b:HealthPlanController 付费墙改用统一权益门,不再持有 purchaseService/membershipService")
|
|
|
+ void healthPlanController_paywallUnified() {
|
|
|
+ Class<?> c = HealthPlanController.class;
|
|
|
+ boolean hasUnifiedGate = false;
|
|
|
+ for (Field f : c.getDeclaredFields()) {
|
|
|
+ assertFalse("purchaseService".equals(f.getName()) || "membershipService".equals(f.getName()),
|
|
|
+ "HealthPlanController 不应再持有 " + f.getName()
|
|
|
+ + "(付费墙已改统一权益门 canGeneratePlan)");
|
|
|
+ if (WmEntitlementService.class.isAssignableFrom(f.getType())) {
|
|
|
+ hasUnifiedGate = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(hasUnifiedGate, "HealthPlanController 应注入 WmEntitlementService 作为统一付费墙");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================================================================
|
|
|
+ // ④ P2 授权分端:同 userId 的 WEIGHT 与 CFC_MAIN 独立读写
|
|
|
+ // ==================================================================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据④:WEIGHT 与 CFC_MAIN 两行授权独立读写(按 (user_id, app_code) 查询,互不影响)")
|
|
|
+ void dataPermission_appScopedIsolation() {
|
|
|
+ UserDataPermissionMapper mapper = mock(UserDataPermissionMapper.class);
|
|
|
+ DataPermissionService svc = new DataPermissionService();
|
|
|
+ try {
|
|
|
+ inject(svc, "userDataPermissionMapper", mapper);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new IllegalStateException("注入失败", e);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 两行均已存在:CFC_MAIN AI分析开启;WEIGHT AI分析关闭(分端独立的事实)
|
|
|
+ UserDataPermission cfcRow = permissionRow(1L, AppCodes.CFC_MAIN, true);
|
|
|
+ UserDataPermission weightRow = permissionRow(2L, AppCodes.WEIGHT, false);
|
|
|
+ when(mapper.selectOne(any(Wrapper.class))).thenAnswer(inv -> {
|
|
|
+ AbstractWrapper w = inv.getArgument(0);
|
|
|
+ w.getSqlSegment(); // MP 3.5.x 惰性填充 paramNameValuePairs
|
|
|
+ Map<String, Object> params = w.getParamNameValuePairs();
|
|
|
+ if (params != null && params.containsValue(AppCodes.WEIGHT)) {
|
|
|
+ return weightRow;
|
|
|
+ }
|
|
|
+ if (params != null && params.containsValue(AppCodes.CFC_MAIN)) {
|
|
|
+ return cfcRow;
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ });
|
|
|
+
|
|
|
+ // ① 分端独立读取
|
|
|
+ UserDataPermission cfc = svc.getPermission(100L, AppCodes.CFC_MAIN);
|
|
|
+ UserDataPermission weight = svc.getPermission(100L, AppCodes.WEIGHT);
|
|
|
+ assertNotNull(cfc);
|
|
|
+ assertNotNull(weight);
|
|
|
+ assertTrue(cfc.getAllowAiAnalysis(), "CFC_MAIN 行 AI分析开启");
|
|
|
+ assertFalse(weight.getAllowAiAnalysis(), "WEIGHT 行 AI分析关闭(分端独立)");
|
|
|
+
|
|
|
+ // ② 每次查询都带 (user_id, app_code) 双条件
|
|
|
+ ArgumentCaptor<AbstractWrapper> captor = ArgumentCaptor.forClass(AbstractWrapper.class);
|
|
|
+ verify(mapper, atLeastOnce()).selectOne(captor.capture());
|
|
|
+ boolean sawCfcScoped = false;
|
|
|
+ boolean sawWeightScoped = false;
|
|
|
+ for (AbstractWrapper w : captor.getAllValues()) {
|
|
|
+ if (w == null) continue;
|
|
|
+ String seg = String.valueOf(w.getSqlSegment()); // MP 3.5.x 惰性填充参数值
|
|
|
+ Map<String, Object> params = w.getParamNameValuePairs();
|
|
|
+ if (seg.contains("app_code") && params != null) {
|
|
|
+ if (params.containsValue(AppCodes.CFC_MAIN) && params.containsValue(100L)) {
|
|
|
+ sawCfcScoped = true;
|
|
|
+ }
|
|
|
+ if (params.containsValue(AppCodes.WEIGHT) && params.containsValue(100L)) {
|
|
|
+ sawWeightScoped = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(sawCfcScoped, "CFC_MAIN 查询应带 (user_id, app_code=CFC_MAIN) 条件");
|
|
|
+ assertTrue(sawWeightScoped, "WEIGHT 查询应带 (user_id, app_code=WEIGHT) 条件");
|
|
|
+
|
|
|
+ // ③ WEIGHT 侧关闭 AI 分析只落 WEIGHT 行,CFC_MAIN 行对象不受影响
|
|
|
+ svc.updatePermission(100L, AppCodes.WEIGHT, Collections.singletonMap("allowAiAnalysis", false));
|
|
|
+ verify(mapper, times(1)).updateById(any(UserDataPermission.class));
|
|
|
+ assertEquals(Boolean.TRUE, cfcRow.getAllowAiAnalysis(),
|
|
|
+ "WEIGHT 关闭 AI 分析不得影响 CFC_MAIN 行(P2 分端独立)");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据④b:新端首次使用复制 CFC_MAIN 开关值(createDefault 按端初始化)")
|
|
|
+ void dataPermission_newAppCopiesCfcMainDefaults() {
|
|
|
+ UserDataPermissionMapper mapper = mock(UserDataPermissionMapper.class);
|
|
|
+ DataPermissionService svc = new DataPermissionService();
|
|
|
+ try {
|
|
|
+ inject(svc, "userDataPermissionMapper", mapper);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new IllegalStateException("注入失败", e);
|
|
|
+ }
|
|
|
+ UserDataPermission cfcRow = permissionRow(1L, AppCodes.CFC_MAIN, true);
|
|
|
+ // WEIGHT 尚无行 → selectOne(WEIGHT) 返回 null 触发 createDefault
|
|
|
+ final UserDataPermission[] inserted = new UserDataPermission[1];
|
|
|
+ final boolean[] cfcQueryUsed = {false};
|
|
|
+ when(mapper.selectOne(any(Wrapper.class))).thenAnswer(inv -> {
|
|
|
+ AbstractWrapper w = inv.getArgument(0);
|
|
|
+ w.getSqlSegment(); // MP 3.5.x 惰性填充 paramNameValuePairs
|
|
|
+ Map<String, Object> params = w.getParamNameValuePairs();
|
|
|
+ if (params != null && params.containsValue(AppCodes.WEIGHT) && params.containsValue(100L)) {
|
|
|
+ return inserted[0]; // 初始 null → 触发首次初始化
|
|
|
+ }
|
|
|
+ if (params != null && params.containsValue(AppCodes.CFC_MAIN)) {
|
|
|
+ cfcQueryUsed[0] = true; // createDefault 复制源查询
|
|
|
+ return cfcRow;
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ });
|
|
|
+ doAnswer(inv -> {
|
|
|
+ inserted[0] = inv.getArgument(0);
|
|
|
+ return Integer.valueOf(1);
|
|
|
+ }).when(mapper).insert(any(UserDataPermission.class));
|
|
|
+
|
|
|
+ UserDataPermission weight = svc.getPermission(100L, AppCodes.WEIGHT);
|
|
|
+ assertNotNull(weight);
|
|
|
+ assertEquals(AppCodes.WEIGHT, weight.getAppCode(), "新行应归属 WEIGHT");
|
|
|
+ assertEquals(Boolean.TRUE, weight.getAllowAiAnalysis(), "WEIGHT 首用应复制 CFC_MAIN 的 AI分析开启");
|
|
|
+ assertEquals(Boolean.TRUE, weight.getAllowPersonalizedRecommend(), "个性化推荐开关复制");
|
|
|
+ assertEquals(Boolean.FALSE, weight.getAllowThirdPartyShare(), "第三方共享开关复制");
|
|
|
+ assertTrue(cfcQueryUsed[0], "createDefault 应查询 CFC_MAIN 行作为复制源");
|
|
|
+
|
|
|
+ // 二次访问命中已初始化行(不重复初始化)
|
|
|
+ UserDataPermission again = svc.getPermission(100L, AppCodes.WEIGHT);
|
|
|
+ assertEquals(weight, again);
|
|
|
+ verify(mapper, atLeastOnce()).insert(any(UserDataPermission.class));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("判据④c:存量单参数方法兜底 CFC_MAIN(防回归)")
|
|
|
+ void dataPermission_singleArgFallbackCfcMain() {
|
|
|
+ UserDataPermissionMapper mapper = mock(UserDataPermissionMapper.class);
|
|
|
+ DataPermissionService svc = new DataPermissionService();
|
|
|
+ try {
|
|
|
+ inject(svc, "userDataPermissionMapper", mapper);
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new IllegalStateException("注入失败", e);
|
|
|
+ }
|
|
|
+ UserDataPermission cfcRow = permissionRow(1L, AppCodes.CFC_MAIN, true);
|
|
|
+ when(mapper.selectOne(any(Wrapper.class))).thenReturn(cfcRow);
|
|
|
+
|
|
|
+ assertTrue(svc.canUseAiAnalysis(100L), "存量 canUseAiAnalysis(userId) 应兜底 CFC_MAIN");
|
|
|
+ ArgumentCaptor<AbstractWrapper> captor = ArgumentCaptor.forClass(AbstractWrapper.class);
|
|
|
+ verify(mapper, atLeastOnce()).selectOne(captor.capture());
|
|
|
+ boolean sawCfc = false;
|
|
|
+ for (AbstractWrapper w : captor.getAllValues()) {
|
|
|
+ if (w == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ w.getSqlSegment(); // MP 3.5.x 惰性填充参数值
|
|
|
+ Map<String, Object> params = w.getParamNameValuePairs();
|
|
|
+ if (params != null && params.containsValue(AppCodes.CFC_MAIN)) {
|
|
|
+ sawCfc = true;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(sawCfc, "存量单参数调用应包含 app_code=CFC_MAIN 查询条件");
|
|
|
+ }
|
|
|
+
|
|
|
+ private UserDataPermission permissionRow(Long id, String appCode, boolean aiAnalysis) {
|
|
|
+ UserDataPermission row = new UserDataPermission();
|
|
|
+ row.setId(id);
|
|
|
+ row.setUserId(100L);
|
|
|
+ row.setAppCode(appCode);
|
|
|
+ row.setAllowAiAnalysis(aiAnalysis);
|
|
|
+ row.setAllowPersonalizedRecommend(true);
|
|
|
+ row.setAllowShareTeacher(true);
|
|
|
+ row.setAllowThirdPartyShare(false);
|
|
|
+ row.setCreatedAt(new Date());
|
|
|
+ row.setUpdatedAt(new Date());
|
|
|
+ return row;
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================================================================
|
|
|
+ // 资源/契约辅助(纯 JDK,无 Spring)
|
|
|
+ // ==================================================================
|
|
|
+
|
|
|
+ /** 读取 classpath 下的 schema.sql(测试资源直接挂载) */
|
|
|
+ private String readSchemaSql() {
|
|
|
+ try (InputStream is = getClass().getClassLoader().getResourceAsStream("schema.sql")) {
|
|
|
+ if (is == null) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ java.util.Scanner scanner = new java.util.Scanner(is, StandardCharsets.UTF_8.name());
|
|
|
+ try {
|
|
|
+ scanner.useDelimiter("\\A");
|
|
|
+ return scanner.hasNext() ? scanner.next() : "";
|
|
|
+ } finally {
|
|
|
+ scanner.close();
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 按表名截取 schema.sql 中该表的 CREATE TABLE 块(起点到下一个 CREATE TABLE / 文件尾) */
|
|
|
+ private String tableBlock(String schema, String table) {
|
|
|
+ String marker = "CREATE TABLE IF NOT EXISTS " + table;
|
|
|
+ int start = schema.indexOf(marker);
|
|
|
+ if (start < 0) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ int next = schema.indexOf("CREATE TABLE", start + marker.length());
|
|
|
+ int end = next < 0 ? schema.length() : next;
|
|
|
+ return schema.substring(start, end);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 读取 DatabaseInitializer.java 源文件(优先按编译产物 class 位置反推模块目录,再叠加相对路径兜底) */
|
|
|
+ private String readDatabaseInitializerSource() {
|
|
|
+ String[] relative = {
|
|
|
+ "src/main/java/com/etotem/cfc/config/DatabaseInitializer.java",
|
|
|
+ "cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java",
|
|
|
+ "../cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java"
|
|
|
+ };
|
|
|
+ for (String c : relative) {
|
|
|
+ File f = new File(c);
|
|
|
+ if (f.isFile()) {
|
|
|
+ String s = readUtf8(f);
|
|
|
+ if (!s.isEmpty()) {
|
|
|
+ return s;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 兜底:target/classes → 模块目录 → src/main/java
|
|
|
+ try {
|
|
|
+ java.net.URL loc = DatabaseInitializer.class.getProtectionDomain().getCodeSource().getLocation();
|
|
|
+ if (loc != null) {
|
|
|
+ File classesDir = new File(loc.toURI());
|
|
|
+ File moduleDir = classesDir.getParentFile() != null
|
|
|
+ ? classesDir.getParentFile().getParentFile() : null;
|
|
|
+ if (moduleDir != null) {
|
|
|
+ File f = new File(moduleDir, "src/main/java/com/etotem/cfc/config/DatabaseInitializer.java");
|
|
|
+ String s = readUtf8(f);
|
|
|
+ if (!s.isEmpty()) {
|
|
|
+ return s;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception ignored) {
|
|
|
+ // 反推失败 → 返回空,由断言暴露
|
|
|
+ }
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+
|
|
|
+ private String readUtf8(File f) {
|
|
|
+ try {
|
|
|
+ return new String(java.nio.file.Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8);
|
|
|
+ } catch (Exception e) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 归一化:移除全部空白(表格对齐差异容忍) */
|
|
|
+ private String normalize(String s) {
|
|
|
+ return s == null ? "" : s.replaceAll("\\s+", "");
|
|
|
+ }
|
|
|
+}
|