Răsfoiți Sursa

feat(workbench): 任务新增/编辑(归属校验防越权)

Xiaogang Liao 5 zile în urmă
părinte
comite
7af0d0a157

+ 49 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminFamilyTaskController.java

@@ -0,0 +1,49 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.FamilyTaskCreateDTO;
+import com.etotem.cfc.service.TaskService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.Map;
+
+@Tag(name = "管理端-单家庭工作台-任务", description = "家庭维度任务新增/编辑(familyId 来自 URL,强制 admin)")
+@RestController
+@RequestMapping("/api/admin")
+public class AdminFamilyTaskController {
+
+    @Resource
+    private TaskService taskService;
+
+    @Operation(summary = "任务新增")
+    @PostMapping("/families/{id}/tasks/create")
+    @PreAuthorize("hasRole('admin')")
+    public Result<Long> createTask(@PathVariable Long id,
+                                   @RequestAttribute(value = "userId", required = false) Long userId,
+                                   @RequestBody FamilyTaskCreateDTO dto) {
+        try {
+            return Result.success(taskService.createAdminFamilyTask(id, userId, dto));
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+
+    @Operation(summary = "任务编辑")
+    @PostMapping("/families/{id}/tasks/update")
+    @PreAuthorize("hasRole('admin')")
+    public Result<Boolean> updateTask(@PathVariable Long id,
+                                      @RequestBody FamilyTaskCreateDTO dto) {
+        if (dto.getTaskId() == null) {
+            return Result.error("taskId不能为空");
+        }
+        try {
+            return Result.success(taskService.updateAdminFamilyTask(dto.getTaskId(), id, dto));
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
+}

+ 28 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyTaskCreateDTO.java

@@ -0,0 +1,28 @@
+package com.etotem.cfc.dto;
+
+import lombok.Data;
+
+import java.util.Date;
+import java.util.List;
+
+/** 单家庭工作台-任务新增/编辑入参(family_id/creator_id 由服务端固定,不取自请求体) */
+@Data
+public class FamilyTaskCreateDTO {
+    private Long taskId;          // update 必填(create 忽略)
+    private String title;
+    private String description;
+    private String category;
+    private Integer points;
+    private Integer duration;
+    private String taskType;        // once / recurring
+    private String frequency;
+    private Integer maxFrequency;
+    private Integer needReview;
+    private String reviewType;
+    private List<String> completeTypes;
+    private String executorType;
+    private Long executorId;
+    private Long memberId;
+    private String repeatType;
+    private Date deadline;
+}

+ 58 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java

@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.etotem.cfc.common.Result;
 import com.etotem.cfc.dto.CreateProductOrderDTO;
 import com.etotem.cfc.dto.CreateTaskDTO;
+import com.etotem.cfc.dto.FamilyTaskCreateDTO;
 import com.etotem.cfc.dto.ProductOrderDTO;
 import com.etotem.cfc.dto.TaskReviewDTO;
 import com.etotem.cfc.entity.*;
@@ -2274,4 +2275,61 @@ return points; // 达到每日扣分上限:不扣分,任务完成仍发放
         }
         return taskMapper.selectList(wrapper);
     }
+
+    /** 工作台-admin 任务新增:family_id/creator_id 固定来自服务端,status 默认 pending */
+    public Long createAdminFamilyTask(Long familyId, Long adminUserId, FamilyTaskCreateDTO dto) {
+        Task t = new Task();
+        t.setFamilyId(familyId);
+        t.setCreatorId(adminUserId);
+        t.setTitle(dto.getTitle());
+        t.setDescription(dto.getDescription());
+        t.setCategory(dto.getCategory());
+        t.setPoints(dto.getPoints());
+        t.setDuration(dto.getDuration());
+        t.setTaskType(dto.getTaskType());
+        t.setFrequency(dto.getFrequency());
+        t.setMaxFrequency(dto.getMaxFrequency());
+        t.setNeedReview(dto.getNeedReview());
+        t.setReviewType(dto.getReviewType());
+        t.setCompleteTypes(dto.getCompleteTypes() == null ? null : String.join(",", dto.getCompleteTypes()));
+        t.setExecutorType(dto.getExecutorType());
+        t.setExecutorId(dto.getExecutorId());
+        t.setMemberId(dto.getMemberId());
+        t.setRepeatType(dto.getRepeatType());
+        t.setDeadline(dto.getDeadline());
+        t.setStatus("pending");
+        t.setSourceType("admin");
+        t.setCreatedAt(new Date());
+        t.setUpdatedAt(new Date());
+        taskMapper.insert(t);
+        return t.getId();
+    }
+
+    /** 工作台-admin 任务编辑:任务存在且 family_id 与 URL 一致,否则拒绝(防跨家庭越权) */
+    public boolean updateAdminFamilyTask(Long taskId, Long familyId, FamilyTaskCreateDTO dto) {
+        Task t = taskMapper.selectById(taskId);
+        if (t == null) throw new RuntimeException("任务不存在");
+        if (t.getFamilyId() == null || !t.getFamilyId().equals(familyId)) {
+            throw new RuntimeException("任务不属于该家庭");
+        }
+        t.setTitle(dto.getTitle());
+        t.setDescription(dto.getDescription());
+        t.setCategory(dto.getCategory());
+        t.setPoints(dto.getPoints());
+        t.setDuration(dto.getDuration());
+        t.setTaskType(dto.getTaskType());
+        t.setFrequency(dto.getFrequency());
+        t.setMaxFrequency(dto.getMaxFrequency());
+        t.setNeedReview(dto.getNeedReview());
+        t.setReviewType(dto.getReviewType());
+        if (dto.getCompleteTypes() != null) t.setCompleteTypes(String.join(",", dto.getCompleteTypes()));
+        t.setExecutorType(dto.getExecutorType());
+        t.setExecutorId(dto.getExecutorId());
+        t.setMemberId(dto.getMemberId());
+        t.setRepeatType(dto.getRepeatType());
+        t.setDeadline(dto.getDeadline());
+        t.setUpdatedAt(new Date());
+        return taskMapper.updateById(t) > 0;
+    }
+
 }

+ 27 - 14
cfc-backend/src/test/java/com/etotem/cfc/controller/admin/AdminWorkbenchAuthContractTest.java

@@ -5,32 +5,45 @@ import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.PostMapping;
 
 import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
 
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
- * 单家庭工作台-鉴权契约:AdminFamilyWorkbenchController 的每个 POST 端点必须
- * @PreAuthorize("hasRole(admin)") 且路径挂在 /api/admin/families/ 下。
+ * 单家庭工作台-鉴权契约:家庭维度(路径以 /families/{id}/ 开头)POST 端点必须
+ * @PreAuthorize("hasRole(admin)"),familyId 一律来自 URL。
+ * 覆盖:AdminFamilyWorkbenchController(聚合/消息/报告)、AdminFamilyTaskController(任务写)、
+ * AdminHealthPlanController 中新增的 family 写方法(其遗留 list/detail/delete 保持多角色行为,不在本契约内)。
  * 无 token 由 JwtInterceptor(LOGIN_REQUIRED_PATHS 含 /api/admin/**) 回 401;
  * 非 admin 由 @PreAuthorize → GlobalExceptionHandler 回 200+{code:403}。
  * 纯反射(无 Spring/DB),任何环境可跑。
  */
 class AdminWorkbenchAuthContractTest {
 
+    private static final List<Class<?>> CONTROLLERS = Arrays.asList(
+            AdminFamilyWorkbenchController.class,
+            AdminFamilyTaskController.class,
+            AdminHealthPlanController.class);
+
     @Test
-    void 工作台控制器每个POST端点必须admin鉴权且路径在apiAdminFamilies下() {
-        int found = 0;
-        for (Method m : AdminFamilyWorkbenchController.class.getDeclaredMethods()) {
-            PostMapping pm = m.getAnnotation(PostMapping.class);
-            if (pm == null) continue;
-            found++;
-            PreAuthorize pa = m.getAnnotation(PreAuthorize.class);
-            assertNotNull(pa, m.getName() + " 必须带 @PreAuthorize");
-            assertTrue(pa.value().contains("admin"), m.getName() + " 必须要求 admin 角色");
-            assertTrue(pm.value()[0].startsWith("/families/"),
-                    m.getName() + " 路径必须以 /families/ 开头(familyId 来自 URL): " + pm.value()[0]);
+    void 家庭维度POST端点必须admin鉴权且familyId来自URL() {
+        int checked = 0;
+        for (Class<?> clazz : CONTROLLERS) {
+            for (Method m : clazz.getDeclaredMethods()) {
+                PostMapping pm = m.getAnnotation(PostMapping.class);
+                if (pm == null || pm.value().length == 0) continue;
+                String path = pm.value()[0];
+                if (!path.startsWith("/families/")) continue;
+                checked++;
+                PreAuthorize pa = m.getAnnotation(PreAuthorize.class);
+                assertNotNull(pa, clazz.getSimpleName() + "." + m.getName() + " 必须带 @PreAuthorize");
+                assertTrue(pa.value().contains("admin"),
+                        clazz.getSimpleName() + "." + m.getName() + " 必须要求 admin 角色");
+                assertTrue(path.matches("/families/\\{.*\\}/.*"), m.getName() + " 路径必须含 {id} 变量: " + path);
+            }
         }
-        assertTrue(found > 0, "控制器必须至少有一个 POST 端点");
+        assertTrue(checked >= 6, "应至少覆盖 7 个家庭维度端点,实际 " + checked);
     }
 }

+ 92 - 0
cfc-backend/src/test/java/com/etotem/cfc/service/FamilyWorkbenchTaskWriteTest.java

@@ -0,0 +1,92 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.dto.FamilyTaskCreateDTO;
+import com.etotem.cfc.entity.Task;
+import com.etotem.cfc.mapper.TaskMapper;
+import com.etotem.cfc.service.TaskService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.Date;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * 任务新增/编辑契约:create 固定 family_id/creator_id 来自服务端、update 校验归属(防跨家庭越权)。
+ */
+class FamilyWorkbenchTaskWriteTest {
+
+    @Mock private TaskMapper taskMapper;
+    @InjectMocks private TaskService service;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    private FamilyTaskCreateDTO dto() {
+        FamilyTaskCreateDTO d = new FamilyTaskCreateDTO();
+        d.setTitle("完成数学作业");
+        d.setCategory("学习类");
+        d.setPoints(10);
+        d.setTaskType("once");
+        d.setExecutorType("child");
+        d.setDeadline(new Date());
+        return d;
+    }
+
+    @Test
+    void 创建任务_familyId和creatorId固定_返回id() {
+        when(taskMapper.insert(any(Task.class))).thenAnswer(inv -> {
+            Task t = inv.getArgument(0);
+            t.setId(123L);
+            return 1;
+        });
+        Long id = service.createAdminFamilyTask(5L, 88L, dto());
+        ArgumentCaptor<Task> cap = ArgumentCaptor.forClass(Task.class);
+        verify(taskMapper).insert(cap.capture());
+        Task t = cap.getValue();
+        assertEquals(5L, t.getFamilyId());
+        assertEquals(88L, t.getCreatorId());
+        assertEquals(123L, id);
+        assertNotNull(t.getStatus());
+        assertEquals("完成数学作业", t.getTitle());
+        assertEquals(Integer.valueOf(10), t.getPoints());
+    }
+
+    @Test
+    void 更新任务_跨家庭_拒绝() {
+        Task other = new Task();
+        other.setId(77L);
+        other.setFamilyId(9L);
+        when(taskMapper.selectById(77L)).thenReturn(other);
+        RuntimeException e = assertThrows(RuntimeException.class,
+                () -> service.updateAdminFamilyTask(77L, 5L, dto()));
+        assertTrue(e.getMessage().contains("任务不属于该家庭"));
+    }
+
+    @Test
+    void 更新任务_同家庭_字段更新() {
+        Task t = new Task();
+        t.setId(77L);
+        t.setFamilyId(5L);
+        t.setTitle("旧标题");
+        when(taskMapper.selectById(77L)).thenReturn(t);
+        when(taskMapper.updateById(any(Task.class))).thenReturn(1);
+        boolean ok = service.updateAdminFamilyTask(77L, 5L, dto());
+        verify(taskMapper).updateById(t);
+        assertTrue(ok);
+        assertEquals("完成数学作业", t.getTitle());
+        assertEquals(Integer.valueOf(10), t.getPoints());
+    }
+}