Browse Source

fix(task): 修复任务编辑日期格式——DTO加@JsonFormat + 前端回显时间戳转字符串

Xiaogang Liao 25 minutes ago
parent
commit
08eb3d2ed2

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

@@ -3,6 +3,7 @@ package com.etotem.cfc.dto;
 import lombok.Data;
 
 import java.util.Date;
+import com.fasterxml.jackson.annotation.JsonFormat;
 import java.util.List;
 
 /** 单家庭工作台-任务新增/编辑入参(family_id/creator_id 由服务端固定,不取自请求体) */
@@ -24,16 +25,21 @@ public class FamilyTaskCreateDTO {
     private Long executorId;
     private Long memberId;
     private String repeatType;
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
     private Date deadline;
 
     // ---- 全量可编辑字段(2026-11-30 扩展)----
     private Integer reviewByCategory;
     private String frequencyUnit;
     private Integer frequencyInterval;
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
     private Date cycleAnchor;
     private Integer isPaused;
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
     private Date earliestStart;
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
     private Date latestEnd;
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
     private Date acceptDeadline;
     private String minigameCode;
     private String bonusRule;

+ 18 - 2
cfc-backend/src/test/java/com/etotem/cfc/service/FamilyWorkbenchTaskWriteTest.java

@@ -12,6 +12,7 @@ import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
 import java.util.Date;
+import com.fasterxml.jackson.databind.ObjectMapper;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -32,6 +33,10 @@ class FamilyWorkbenchTaskWriteTest {
     @BeforeEach
     void setUp() {
         MockitoAnnotations.openMocks(this);
+        // updateAdminFamilyTask 用 LambdaUpdateWrapper,需初始化 Task 实体元数据(否则 can not find lambda cache)
+        com.baomidou.mybatisplus.core.MybatisConfiguration config = new com.baomidou.mybatisplus.core.MybatisConfiguration();
+        com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(
+                new org.apache.ibatis.builder.MapperBuilderAssistant(config, ""), Task.class);
     }
 
     private FamilyTaskCreateDTO dto() {
@@ -45,6 +50,17 @@ class FamilyWorkbenchTaskWriteTest {
         return d;
     }
 
+    @Test
+    void dtoDateField_spaceFormatDeserializable() throws Exception {
+        // 前端 el-date-picker value-format="yyyy-MM-dd HH:mm:ss" 产生的格式,后端必须能解析(否则400)
+        String json = "{\"taskId\":1,\"title\":\"t\",\"deadline\":\"2026-12-01 18:30:00\","
+                + "\"cycleAnchor\":\"2026-12-01 08:00:00\",\"earliestStart\":\"2026-12-01 09:00:00\","
+                + "\"latestEnd\":\"2026-12-01 20:00:00\",\"acceptDeadline\":\"2026-12-01 21:00:00\"}";
+        FamilyTaskCreateDTO d = new ObjectMapper().readValue(json, FamilyTaskCreateDTO.class);
+        assertNotNull(d.getDeadline(), "deadline 应被解析,不能因格式不匹配返回 null/抛错");
+        assertEquals(2026, d.getDeadline().getYear() + 1900);
+    }
+
     @Test
     void 创建任务_familyId和creatorId固定_返回id() {
         when(taskMapper.insert(any(Task.class))).thenAnswer(inv -> {
@@ -82,9 +98,9 @@ class FamilyWorkbenchTaskWriteTest {
         t.setFamilyId(5L);
         t.setTitle("旧标题");
         when(taskMapper.selectById(77L)).thenReturn(t);
-        when(taskMapper.updateById(any(Task.class))).thenReturn(1);
+        when(taskMapper.update(any(Task.class), any())).thenReturn(1);
         boolean ok = service.updateAdminFamilyTask(77L, 5L, dto());
-        verify(taskMapper).updateById(t);
+        verify(taskMapper).update(any(Task.class), any());
         assertTrue(ok);
         assertEquals("完成数学作业", t.getTitle());
         assertEquals(Integer.valueOf(10), t.getPoints());

+ 24 - 0
cfc-web/src/__tests__/views/FamilyWorkbench.taskDateFormat.contract.spec.js

@@ -0,0 +1,24 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+// 契约:任务编辑回显时,详情接口返回的时间戳数字必须转成 el-date-picker 的 value-format 字符串,
+// 否则 getFullYear is not a function;提交时时间字段须为后端可解析的 "yyyy-MM-dd HH:mm:ss"。
+describe('任务编辑日期格式契约', () => {
+  const src = readFileSync(resolve(__dirname, '../../../src/views/FamilyWorkbench.vue'), 'utf8')
+
+  it('openTaskForm 回显时对日期字段做时间戳→字符串转换(toTaskFormDate)', () => {
+    expect(src).toMatch(/toTaskFormDate/)
+    const idx = src.indexOf('async openTaskForm')
+    const block = src.slice(idx, idx + 900)
+    expect(block).toMatch(/deadline/)
+    expect(block).toMatch(/toTaskFormDate/)
+  })
+
+  it('存在 toTaskFormDate 方法,兼容 number/string/Date/null', () => {
+    const idx = src.indexOf('toTaskFormDate(')
+    expect(idx).toBeGreaterThan(-1)
+    const block = src.slice(idx, idx + 700)
+    expect(block).toMatch(/typeof/)
+    expect(block).toMatch(/null/)
+  })
+})

+ 18 - 1
cfc-web/src/views/FamilyWorkbench.vue

@@ -819,14 +819,31 @@ export default {
       this.taskList = (res.data && res.data.records) || []
       this.taskTotal = (res.data && res.data.total) || 0
     },
+    /** 详情日期(时间戳数字 / ISO字符串 / Date)→ "yyyy-MM-dd HH:mm:ss" 字符串;null/空 → null */
+    toTaskFormDate(v) {
+      if (v === null || v === undefined || v === '') return null
+      let d
+      if (typeof v === 'number') d = new Date(v)
+      else if (v instanceof Date) d = v
+      else d = new Date(v)
+      if (isNaN(d.getTime())) return null
+      const p = n => String(n).padStart(2, '0')
+      return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds())
+    },
+
     async openTaskForm(row) {
       this.taskFormErrors = {}
       if (row && row.id) {
         try {
           const detail = await getFamilyTaskDetail(this.familyId, row.id)
           const d = (detail && detail.data) || {}
+          // 详情接口日期是时间戳数字(Jackson默认),el-date-picker 的 value-format 期望 "yyyy-MM-dd HH:mm:ss" 字符串,
+          // 直接塞数字会报 getFullYear is not a function → 统一转换
+          const dateFields = ['deadline', 'cycleAnchor', 'earliestStart', 'latestEnd', 'acceptDeadline']
+          const fixed = { ...d }
+          dateFields.forEach(k => { fixed[k] = this.toTaskFormDate(d[k]) })
           // completeTypes 存库是逗号字符串,编辑框用数组
-          this.taskForm = { ...d, completeTypes: d.completeTypes ? String(d.completeTypes).split(',').filter(Boolean) : [] }
+          this.taskForm = { ...fixed, completeTypes: d.completeTypes ? String(d.completeTypes).split(',').filter(Boolean) : [] }
         } catch (e) {
           // 详情失败时退回列表行数据,避免完全打不开
           this.taskForm = { ...row }