Sfoglia il codice sorgente

feat: enhance project phase management and timeline visualization

- Added new fields for tracking first upload and last submission dates in project phases.
- Improved date handling and validation in the dashboard component for better project timeline accuracy.
- Updated project timeline HTML and CSS to reflect task completion rates and enhance visual representation.
- Refactored logic for calculating project deadlines and phase statuses, ensuring more accurate project tracking.
0235711 4 giorni fa
parent
commit
1ed811c334

+ 4 - 0
src/app/models/project-phase.model.ts

@@ -26,6 +26,10 @@ export interface PhaseInfo {
   startDate?: Date | string;
   /** 阶段截止时间 */
   deadline: Date | string;
+  /** 第一次上传时间 */
+  firstUploadAt?: Date | string;
+  /** 最近一次提交时间 */
+  lastSubmissionAt?: Date | string;
   /** 预计工期(天数) */
   estimatedDays?: number;
   /** 阶段状态 */

+ 77 - 179
src/app/pages/team-leader/dashboard/dashboard.ts

@@ -10,6 +10,9 @@ import { FmodeParse } from 'fmode-ng/parse';
 import { ProjectTimelineComponent } from '../project-timeline';
 import type { ProjectTimeline } from '../project-timeline/project-timeline';
 import { EmployeeDetailPanelComponent } from '../employee-detail-panel';
+import { normalizeDateInput, addDays } from '../../../utils/date-utils';
+import { generatePhaseDeadlines } from '../../../utils/phase-deadline.utils';
+import { PhaseDeadlines, PhaseName } from '../../../models/project-phase.model';
 
 // 项目阶段定义
 interface ProjectStage {
@@ -569,21 +572,6 @@ export class Dashboard implements OnInit, OnDestroy {
    * 将项目数据转换为ProjectTimeline格式(带缓存优化 + 去重)
    */
   private convertToProjectTimeline(): void {
-    // 计算当前数据大小
-    let currentSize = 0;
-    this.designerWorkloadMap.forEach((projects) => {
-      currentSize += projects.length;
-    });
-    
-    console.log(`📊 convertToProjectTimeline: 当前数据大小 = ${currentSize}, 缓存大小 = ${this.lastDesignerWorkloadMapSize}`);
-    
-    // 如果数据没有变化,使用缓存
-    if (currentSize === this.lastDesignerWorkloadMapSize && this.timelineDataCache.length > 0) {
-      console.log(`📊 使用缓存数据,共 ${this.timelineDataCache.length} 个项目`);
-      this.projectTimelineData = this.timelineDataCache;
-      return;
-    }
-    
     // 🔧 不去重,保留所有项目-设计师关联关系(一个项目可能有多个设计师)
     const allDesignerProjects: any[] = [];
     
@@ -626,57 +614,66 @@ export class Dashboard implements OnInit, OnDestroy {
       const projectData = project.data || {};
       
       // 1. 获取真实的项目开始时间
-      // 优先使用 phaseDeadlines.modeling.startDate,其次使用 requirementsConfirmedAt,最后使用 createdAt
-      let realStartDate: Date;
-      if (projectData.phaseDeadlines?.modeling?.startDate) {
-        realStartDate = projectData.phaseDeadlines.modeling.startDate instanceof Date 
-          ? projectData.phaseDeadlines.modeling.startDate
-          : new Date(projectData.phaseDeadlines.modeling.startDate);
-      } else if (projectData.requirementsConfirmedAt) {
-        realStartDate = new Date(projectData.requirementsConfirmedAt);
-      } else if (project.createdAt) {
-        realStartDate = project.createdAt instanceof Date ? project.createdAt : new Date(project.createdAt);
-      } else {
-        // 降级:如果没有开始时间,使用当前时间
-        realStartDate = new Date();
-      }
+      const realStartDate = normalizeDateInput(
+        projectData.phaseDeadlines?.modeling?.startDate ||
+          projectData.requirementsConfirmedAt ||
+          project.createdAt,
+        new Date()
+      );
       
       // 2. 获取真实的交付日期
+      // ✅ 修复:确保 deadline 是未来的日期(不使用过去的初始值或未初始化的值)
+      let proposedEndDate = project.deadline || projectData.phaseDeadlines?.postProcessing?.deadline;
       let realEndDate: Date;
-      if (project.deadline) {
-        realEndDate = project.deadline instanceof Date ? project.deadline : new Date(project.deadline);
-      } else {
-        // ✅ 修复:如果没有交付日期,使用开始时间 + 30天(更合理的默认值)
-        // 避免新项目因为默认7天导致结束日期在过去而被过滤
-        realEndDate = new Date(realStartDate.getTime() + 30 * 24 * 60 * 60 * 1000);
-      }
       
-      // ✅ 调试:检查新项目
-      if (project.id === 'qCV9QHROSH') {
-        console.log(`📊 新项目 qCV9QHROSH 日期计算:`, {
-          projectName: project.name,
-          hasDeadline: !!project.deadline,
-          deadline: project.deadline ? (project.deadline instanceof Date ? project.deadline.toLocaleString('zh-CN') : new Date(project.deadline).toLocaleString('zh-CN')) : '无',
-          realStartDate: realStartDate.toLocaleString('zh-CN'),
-          realEndDate: realEndDate.toLocaleString('zh-CN'),
-          calculatedEndDate: realEndDate.toLocaleString('zh-CN')
-        });
+      // 如果提议的结束日期在过去,或者日期无效,使用默认值
+      if (proposedEndDate) {
+        const proposed = normalizeDateInput(proposedEndDate, realStartDate);
+        // 只有当提议的日期在未来时才使用它
+        if (proposed.getTime() > now.getTime()) {
+          realEndDate = proposed;
+        } else {
+          // 日期在过去,使用默认值(从开始日期起30天)
+          realEndDate = addDays(realStartDate, 30);
+        }
+      } else {
+        // 没有提议的日期,使用默认值
+        realEndDate = addDays(realStartDate, 30);
       }
       
-      // 3. 获取真实的对图时间
-      // 优先使用 demoday,其次使用 phaseDeadlines.softDecor.deadline,最后计算
+      // 3. 获取真实的对图时间(小图对图)
+      // ✅ 逻辑:优先使用 project.demoday,否则在软装截止时间后半天
       let realReviewDate: Date;
+      let reviewDateSource = 'default';
+      
       if (project.demoday) {
-        realReviewDate = project.demoday instanceof Date ? project.demoday : new Date(project.demoday);
+        // 如果有显式设置的小图对图日期,使用它
+        realReviewDate = normalizeDateInput(project.demoday, new Date());
+        reviewDateSource = 'demoday';
       } else if (projectData.phaseDeadlines?.softDecor?.deadline) {
-        const softDecorDeadline = projectData.phaseDeadlines.softDecor.deadline;
-        realReviewDate = softDecorDeadline instanceof Date ? softDecorDeadline : new Date(softDecorDeadline);
+        // 软装截止时间后半天作为小图对图时间
+        const softDecorDeadline = normalizeDateInput(projectData.phaseDeadlines.softDecor.deadline, new Date());
+        realReviewDate = new Date(softDecorDeadline.getTime() + 12 * 60 * 60 * 1000); // 加12小时
+        reviewDateSource = 'softDecor + 12h';
       } else {
-        // 计算:设置在软装和渲染之间(项目周期的 60% 位置)
-        const projectDuration = realEndDate.getTime() - realStartDate.getTime();
-        const projectMidPoint = realStartDate.getTime() + (projectDuration * 0.6);
-        realReviewDate = new Date(projectMidPoint);
-        realReviewDate.setHours(14, 0, 0, 0);
+        // 默认值:项目进度的60%位置,下午2点
+        const defaultReviewPoint = new Date(
+          realStartDate.getTime() + (realEndDate.getTime() - realStartDate.getTime()) * 0.6
+        );
+        defaultReviewPoint.setHours(14, 0, 0, 0);
+        realReviewDate = defaultReviewPoint;
+        reviewDateSource = 'default 60%';
+      }
+      
+      // 调试日志
+      if (project.name?.includes('紫云') || project.name?.includes('自建')) {
+        console.log(`📸 [${project.name}] 小图对图时间计算:`, {
+          source: reviewDateSource,
+          reviewDate: realReviewDate.toLocaleString('zh-CN'),
+          demoday: project.demoday,
+          softDecorDeadline: projectData.phaseDeadlines?.softDecor?.deadline,
+          hasPhaseDeadlines: !!projectData.phaseDeadlines
+        });
       }
       
       // 4. 计算距离交付还有几天(使用真实日期)
@@ -709,59 +706,12 @@ export class Dashboard implements OnInit, OnDestroy {
       const currentStage = stageMap[project.currentStage || '建模阶段'] || 'model';
       const stageName = project.currentStage || '建模阶段';
       
-      // 7. 计算真实的阶段进度(基于 phaseDeadlines)
-      let stageProgress = 50; // 默认值
-      if (projectData.phaseDeadlines) {
-        const phaseDeadlines = projectData.phaseDeadlines;
-        
-        // 根据当前阶段计算进度
-        if (currentStage === 'model' && phaseDeadlines.modeling) {
-          const start = phaseDeadlines.modeling.startDate instanceof Date 
-            ? phaseDeadlines.modeling.startDate 
-            : new Date(phaseDeadlines.modeling.startDate);
-          const end = phaseDeadlines.modeling.deadline instanceof Date 
-            ? phaseDeadlines.modeling.deadline 
-            : new Date(phaseDeadlines.modeling.deadline);
-          const total = end.getTime() - start.getTime();
-          const elapsed = now.getTime() - start.getTime();
-          stageProgress = total > 0 ? Math.min(100, Math.max(0, (elapsed / total) * 100)) : 50;
-        } else if (currentStage === 'decoration' && phaseDeadlines.softDecor) {
-          const start = phaseDeadlines.softDecor.startDate instanceof Date 
-            ? phaseDeadlines.softDecor.startDate 
-            : new Date(phaseDeadlines.softDecor.startDate);
-          const end = phaseDeadlines.softDecor.deadline instanceof Date 
-            ? phaseDeadlines.softDecor.deadline 
-            : new Date(phaseDeadlines.softDecor.deadline);
-          const total = end.getTime() - start.getTime();
-          const elapsed = now.getTime() - start.getTime();
-          stageProgress = total > 0 ? Math.min(100, Math.max(0, (elapsed / total) * 100)) : 50;
-        } else if (currentStage === 'render' && phaseDeadlines.rendering) {
-          const start = phaseDeadlines.rendering.startDate instanceof Date 
-            ? phaseDeadlines.rendering.startDate 
-            : new Date(phaseDeadlines.rendering.startDate);
-          const end = phaseDeadlines.rendering.deadline instanceof Date 
-            ? phaseDeadlines.rendering.deadline 
-            : new Date(phaseDeadlines.rendering.deadline);
-          const total = end.getTime() - start.getTime();
-          const elapsed = now.getTime() - start.getTime();
-          stageProgress = total > 0 ? Math.min(100, Math.max(0, (elapsed / total) * 100)) : 50;
-        } else if (currentStage === 'delivery' && phaseDeadlines.postProcessing) {
-          const start = phaseDeadlines.postProcessing.startDate instanceof Date 
-            ? phaseDeadlines.postProcessing.startDate 
-            : new Date(phaseDeadlines.postProcessing.startDate);
-          const end = phaseDeadlines.postProcessing.deadline instanceof Date 
-            ? phaseDeadlines.postProcessing.deadline 
-            : new Date(phaseDeadlines.postProcessing.deadline);
-          const total = end.getTime() - start.getTime();
-          const elapsed = now.getTime() - start.getTime();
-          stageProgress = total > 0 ? Math.min(100, Math.max(0, (elapsed / total) * 100)) : 50;
-        }
-      } else {
-        // 降级:使用整体项目进度
-        const totalDuration = realEndDate.getTime() - realStartDate.getTime();
-        const elapsed = now.getTime() - realStartDate.getTime();
-        stageProgress = totalDuration > 0 ? Math.min(100, Math.max(0, (elapsed / totalDuration) * 100)) : 50;
-      }
+      // 7. 🆕 阶段任务完成度(由时间轴组件的 getProjectCompletionRate 计算)
+      // ✅ 重要变更:进度条现在表示"任务完成度"而不是"时间百分比"
+      // - 时间轴组件会优先使用交付物完成率(overallCompletionRate)
+      // - 若无交付物数据,则根据 phaseDeadlines.status 推断任务完成度
+      // - stageProgress 保留作为兼容字段,但已弃用
+      let stageProgress = 50; // 默认兼容值(实际进度由时间轴组件计算)
       
       // 8. 检查是否停滞(基于 updatedAt)
       let isStalled = false;
@@ -790,76 +740,24 @@ export class Dashboard implements OnInit, OnDestroy {
       }
       
       // 11. 获取或生成阶段截止时间数据
-      let phaseDeadlines = projectData.phaseDeadlines;
-      
-      // 如果项目没有阶段数据,从交付日期往前推算
-      if (!phaseDeadlines && realEndDate) {
-        const deliveryTime = realEndDate.getTime();
-        const startTime = realStartDate.getTime();
-        const totalDays = Math.ceil((deliveryTime - startTime) / (24 * 60 * 60 * 1000));
-        
-        // 按比例分配:建模30%,软装25%,渲染30%,后期15%
-        const modelingDays = Math.ceil(totalDays * 0.3);
-        const softDecorDays = Math.ceil(totalDays * 0.25);
-        const renderingDays = Math.ceil(totalDays * 0.3);
-        const postProcessDays = totalDays - modelingDays - softDecorDays - renderingDays;
-        
-        let currentDate = new Date(startTime);
-        
-        const modelingDeadline = new Date(currentDate);
-        modelingDeadline.setDate(modelingDeadline.getDate() + modelingDays);
-        
-        currentDate = new Date(modelingDeadline);
-        const softDecorDeadline = new Date(currentDate);
-        softDecorDeadline.setDate(softDecorDeadline.getDate() + softDecorDays);
-        
-        currentDate = new Date(softDecorDeadline);
-        const renderingDeadline = new Date(currentDate);
-        renderingDeadline.setDate(renderingDeadline.getDate() + renderingDays);
-        
-        currentDate = new Date(renderingDeadline);
-        const postProcessingDeadline = new Date(currentDate);
-        postProcessingDeadline.setDate(postProcessingDeadline.getDate() + postProcessDays);
-        
-        // 更新对图时间(软装和渲染之间)
-        const reviewTime = softDecorDeadline.getTime() + (renderingDeadline.getTime() - softDecorDeadline.getTime()) * 0.5;
-        realReviewDate = new Date(reviewTime);
-        realReviewDate.setHours(14, 0, 0, 0);
-        
-        phaseDeadlines = {
-          modeling: {
-            startDate: realStartDate,
-            deadline: modelingDeadline,
-            estimatedDays: modelingDays,
-            status: now.getTime() >= modelingDeadline.getTime() ? 'completed' : 
-                    now.getTime() >= realStartDate.getTime() ? 'in_progress' : 'not_started',
-            priority: 'high'
-          },
-          softDecor: {
-            startDate: modelingDeadline,
-            deadline: softDecorDeadline,
-            estimatedDays: softDecorDays,
-            status: now.getTime() >= softDecorDeadline.getTime() ? 'completed' : 
-                    now.getTime() >= modelingDeadline.getTime() ? 'in_progress' : 'not_started',
-            priority: 'medium'
-          },
-          rendering: {
-            startDate: softDecorDeadline,
-            deadline: renderingDeadline,
-            estimatedDays: renderingDays,
-            status: now.getTime() >= renderingDeadline.getTime() ? 'completed' : 
-                    now.getTime() >= softDecorDeadline.getTime() ? 'in_progress' : 'not_started',
-            priority: 'high'
-          },
-          postProcessing: {
-            startDate: renderingDeadline,
-            deadline: postProcessingDeadline,
-            estimatedDays: postProcessDays,
-            status: now.getTime() >= postProcessingDeadline.getTime() ? 'completed' : 
-                    now.getTime() >= renderingDeadline.getTime() ? 'in_progress' : 'not_started',
-            priority: 'medium'
+      let phaseDeadlines: PhaseDeadlines | undefined = projectData.phaseDeadlines;
+      if (!phaseDeadlines) {
+        phaseDeadlines = generatePhaseDeadlines(realStartDate, realEndDate);
+      }
+      if (phaseDeadlines) {
+        (Object.keys(phaseDeadlines) as PhaseName[]).forEach((phaseKey) => {
+          const info = phaseDeadlines![phaseKey];
+          if (!info) return;
+          const phaseStart = normalizeDateInput(info.startDate, realStartDate);
+          const phaseEnd = normalizeDateInput(info.deadline, realEndDate);
+          if (now >= phaseEnd) {
+            info.status = 'completed';
+          } else if (now >= phaseStart) {
+            info.status = 'in_progress';
+          } else {
+            info.status = info.status || 'not_started';
           }
-        };
+        });
       }
       
       // 12. 获取空间和客户信息
@@ -892,7 +790,7 @@ export class Dashboard implements OnInit, OnDestroy {
     
     // 更新缓存
     this.timelineDataCache = this.projectTimelineData;
-    this.lastDesignerWorkloadMapSize = currentSize;
+    this.lastDesignerWorkloadMapSize = totalProjectsInMap;
     
     console.log(`📊 convertToProjectTimeline 完成: 转换了 ${this.projectTimelineData.length} 个项目`);
     if (this.projectTimelineData.length > 0) {

+ 20 - 7
src/app/pages/team-leader/project-timeline/project-timeline.html

@@ -246,16 +246,29 @@
                      [style.left]="getProjectPosition(project).left"
                      [style.width]="getProjectPosition(project).width"
                      [style.background]="getProjectPosition(project).background"
-                     [title]="project.projectName + ' | ' + project.stageName + ' ' + getProjectCompletionRate(project) + '%'">
-                  <!-- 进度填充 -->
-                  <div class="progress-fill"
-                       [style.width]="getProjectCompletionRate(project) + '%'"
-                       [style.background]="getProjectCompletionColor(project)">
+                     [title]="project.projectName + ' | ' + project.stageName + ' 当前环节进度: ' + getProjectCompletionRate(project) + '%'">
+                  <!-- 🆕 进度条:从现在到最近的一个事件(显示任务完成度) -->
+                  <div class="progress-bar-container"
+                       [style.left]="getProgressBarPosition(project).left"
+                       [style.width]="getProgressBarPosition(project).width"
+                       [title]="'从现在到下一个事件的时间跨度,当前环节任务完成度: ' + getProjectCompletionRate(project) + '%'">
+                    <!-- 任务完成度填充(相对于进度条容器的宽度) -->
+                    <div class="progress-fill"
+                         [style.width.%]="getProjectCompletionRate(project)"
+                         [style.background]="getProjectCompletionColor(project)">
+                      <!-- 任务完成度百分比文本(仅在填充足够宽时显示) -->
+                      @if (getProjectCompletionRate(project) >= 15) {
+                        <span class="progress-text">{{ getProjectCompletionRate(project) }}%</span>
+                      }
+                    </div>
                   </div>
-                  <div class="progress-marker"
+                  
+                  <!-- 任务完成度标记 -->
+                  <div class="completion-marker"
                        [style.left]="getCompletionMarkerLeft(project)">
                     <span class="marker-label"
-                          [style.background]="getProjectCompletionColor(project)">
+                          [style.background]="getProjectCompletionColor(project)"
+                          [title]="'当前环节任务完成度: ' + getProjectCompletionRate(project) + '%'">
                       {{ getProjectCompletionRate(project) }}%
                     </span>
                     <span class="marker-dot"

+ 44 - 6
src/app/pages/team-leader/project-timeline/project-timeline.scss

@@ -692,16 +692,54 @@
   }
 }
 
-// 进度填充
-.progress-fill {
+// 🆕 进度条容器(从现在到下一个事件)
+.progress-bar-container {
   position: absolute;
   top: 0;
-  left: 0;
   bottom: 0;
   border-radius: 8px;
-  transition: width 0.3s ease, background 0.3s ease;
-  box-shadow: inset 0 -8px 12px rgba(0, 0, 0, 0.05);
-  opacity: 0.9;
+  transition: left 0.3s ease, width 0.3s ease;
+  opacity: 0.7;
+  z-index: 5;
+  
+  .progress-fill {
+    position: absolute;
+    top: 0;
+    left: 0;
+    bottom: 0;
+    right: 0;
+    border-radius: 8px;
+    transition: background 0.3s ease;
+    box-shadow: inset 0 -8px 12px rgba(0, 0, 0, 0.05);
+    opacity: 0.9;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    overflow: hidden;
+    
+    .progress-text {
+      font-size: 12px;
+      font-weight: 700;
+      color: #ffffff;
+      text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
+      letter-spacing: 0.3px;
+      white-space: nowrap;
+      pointer-events: none;
+      opacity: 0.95;
+    }
+  }
+}
+
+// 任务完成度标记
+.completion-marker {
+  position: absolute;
+  top: -40px;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  gap: 6px;
+  transform: translateX(-50%);
+  pointer-events: none;
 }
 
 .progress-marker {

+ 125 - 5
src/app/pages/team-leader/project-timeline/project-timeline.ts

@@ -169,6 +169,15 @@ export class ProjectTimelineComponent implements OnInit, OnDestroy {
     const rangeEnd = this.timeRangeEnd.getTime();
     const rangeDuration = rangeEnd - rangeStart;
     
+    if (!this.isValidDate(project.startDate) || !this.isValidDate(project.endDate)) {
+      console.warn('⚠️ 项目缺少有效的起止时间,使用占位条:', project.projectName, project.projectId);
+      return {
+        left: '0%',
+        width: '2px',
+        background: this.getProjectBarBackground(project)
+      };
+    }
+    
     // ✅ 修复:如果项目完全在过去,显示一个最小宽度的条
     if (project.endDate.getTime() < rangeStart) {
       // 项目完全在过去,显示在时间轴最左侧,宽度为最小可见宽度
@@ -212,6 +221,64 @@ export class ProjectTimelineComponent implements OnInit, OnDestroy {
     };
   }
   
+  /**
+   * 🆕 获取进度条的位置和宽度(从现在到最近的一个事件)
+   * ✅ 修改逻辑:进度条表示"从当前时间到下一个事件"的时间跨度
+   */
+  getProgressBarPosition(project: ProjectTimeline): { left: string; width: string } {
+    const rangeStart = this.timeRangeStart.getTime();
+    const rangeEnd = this.timeRangeEnd.getTime();
+    const rangeDuration = rangeEnd - rangeStart;
+    const now = this.currentTime.getTime();
+    
+    // 获取项目的所有事件,找到最近的未来事件
+    const events = this.getProjectEvents(project);
+    let nextEventDate: Date | null = null;
+    
+    // 找到距离现在最近的未来事件
+    for (const event of events) {
+      if (event.date.getTime() > now) {
+        if (!nextEventDate || event.date.getTime() < nextEventDate.getTime()) {
+          nextEventDate = event.date;
+        }
+      }
+    }
+    
+    // 如果没有未来事件,使用项目交付日期作为终点
+    if (!nextEventDate && project.deliveryDate && project.deliveryDate.getTime() > now) {
+      nextEventDate = project.deliveryDate;
+    }
+    
+    // 如果没有找到任何未来事件,返回最小宽度
+    if (!nextEventDate) {
+      return {
+        left: '0%',
+        width: '0%' // 无进度条
+      };
+    }
+    
+    // 计算从现在到下一个事件的时间跨度
+    const progressStart = Math.max(now, rangeStart);
+    const progressEnd = Math.min(nextEventDate.getTime(), rangeEnd);
+    
+    if (progressEnd <= progressStart) {
+      return {
+        left: '0%',
+        width: '0%'
+      };
+    }
+    
+    const left = ((progressStart - rangeStart) / rangeDuration) * 100;
+    const width = ((progressEnd - progressStart) / rangeDuration) * 100;
+    
+    return {
+      left: `${Math.max(0, left)}%`,
+      width: `${Math.max(1, width)}%`
+    };
+  }
+  
+
+  
   /**
    * 获取事件标记在时间轴上的位置
    */
@@ -219,6 +286,10 @@ export class ProjectTimelineComponent implements OnInit, OnDestroy {
     const rangeStart = this.timeRangeStart.getTime();
     const rangeEnd = this.timeRangeEnd.getTime();
     const rangeDuration = rangeEnd - rangeStart;
+
+    if (!this.isValidDate(date)) {
+      return '';
+    }
     
     const eventTime = date.getTime();
     
@@ -261,14 +332,58 @@ export class ProjectTimelineComponent implements OnInit, OnDestroy {
     return `status-${project.status || 'normal'}`;
   }
   
+  /**
+   * 🆕 获取项目当前环节的任务完成度(不是时间进度)
+   * 优先级:1. 交付物完成率 2. 阶段状态推断 3. 默认值
+   */
   getProjectCompletionRate(project: ProjectTimeline): number {
+    // ✅ 首先尝试获取交付物完成率(这是最准确的任务完成度)
     const summary = this.getSpaceDeliverableSummary(project.projectId);
-    if (summary) {
+    if (summary && summary.overallCompletionRate !== undefined) {
       return Math.round(summary.overallCompletionRate);
     }
-    if (typeof project.stageProgress === 'number') {
-      return Math.round(Math.max(0, Math.min(100, project.stageProgress)));
+    
+    // ✅ 降级方案:根据阶段状态推断任务完成度
+    if (project.phaseDeadlines) {
+      const phaseDeadlines = project.phaseDeadlines;
+      
+      // 根据当前阶段的状态推断完成度
+      let currentPhaseInfo: any = null;
+      
+      // 映射当前阶段到对应的 phaseDeadlines 字段
+      const stagePhaseMap: Record<string, string> = {
+        'model': 'modeling',
+        'decoration': 'softDecor',
+        'render': 'rendering',
+        'delivery': 'postProcessing'
+      };
+      
+      // 从阶段名称获取对应的 phaseName
+      let phaseName = stagePhaseMap[project.stageName] || stagePhaseMap['model'];
+      currentPhaseInfo = phaseDeadlines[phaseName as any];
+      
+      if (currentPhaseInfo) {
+        const status = currentPhaseInfo.status;
+        
+        // 根据阶段状态推断任务完成度
+        if (status === 'completed') {
+          return 100; // 完成阶段任务
+        } else if (status === 'in_progress') {
+          // 进行中:根据有无上传文件来判断
+          if (currentPhaseInfo.firstUploadAt) {
+            return 50; // 已有上传,表示有进展
+          } else {
+            return 20; // 刚开始,进度较低
+          }
+        } else if (status === 'not_started') {
+          return 0; // 未开始
+        } else if (status === 'delayed') {
+          return 30; // 延期/驳回
+        }
+      }
     }
+    
+    // ✅ 最后的降级:返回 0
     return 0;
   }
   
@@ -338,6 +453,10 @@ export class ProjectTimelineComponent implements OnInit, OnDestroy {
     // 必须同时满足:在时间范围内 + 在当前时间之后
     return this.isEventInRange(date) && date.getTime() >= this.currentTime.getTime();
   }
+
+  private isValidDate(value: Date): boolean {
+    return value instanceof Date && !isNaN(value.getTime());
+  }
   
   /**
    * 🆕 获取项目的所有时间轴事件(含阶段截止时间)
@@ -386,15 +505,16 @@ export class ProjectTimelineComponent implements OnInit, OnDestroy {
       });
     }
     
-    // 🔥 小图对图事件(始终显示,位于软装和渲染之间,高亮显示)
+    // 🔥 小图对图事件(只要在时间范围内就显示,高亮显示)
     if (project.reviewDate && this.isEventInRange(project.reviewDate)) {
       const isPast = project.reviewDate.getTime() < this.currentTime.getTime();
+      
       events.push({
         date: project.reviewDate,
         label: '小图对图',
         type: 'review',
         projectId: project.projectId,
-        color: isPast ? '#94a3b8' : '#f59e0b', // 🔥 高亮显示:金黄
+        color: isPast ? '#94a3b8' : '#f59e0b', // 🔥 未来显示金黄色,已过去显示灰
         icon: '📸' // 🔥 更醒目的图标
       });
     }

+ 47 - 0
src/app/utils/date-utils.ts

@@ -0,0 +1,47 @@
+export function normalizeDateInput(value: any, fallback?: Date): Date {
+  const parsed = parseDate(value);
+  if (!isNaN(parsed.getTime())) {
+    return parsed;
+  }
+  if (fallback) {
+    const fb = new Date(fallback);
+    return isNaN(fb.getTime()) ? new Date() : fb;
+  }
+  return new Date();
+}
+
+export function addDays(date: Date, days: number): Date {
+  const base = new Date(date);
+  if (isNaN(base.getTime())) {
+    return new Date();
+  }
+  base.setDate(base.getDate() + days);
+  return base;
+}
+
+function parseDate(value: any): Date {
+  if (!value && value !== 0) {
+    return new Date(NaN);
+  }
+
+  if (value instanceof Date) {
+    return new Date(value.getTime());
+  }
+
+  if (typeof value === 'string' || typeof value === 'number') {
+    return new Date(value);
+  }
+
+  if (typeof value === 'object') {
+    if (value.iso) {
+      return new Date(value.iso);
+    }
+
+    if (value.__type === 'Date' && value.iso) {
+      return new Date(value.iso);
+    }
+  }
+
+  return new Date(NaN);
+}
+

+ 200 - 0
src/app/utils/phase-deadline.utils.ts

@@ -0,0 +1,200 @@
+import { PhaseDeadlines, PhaseInfo, PhaseName, PHASE_INFO } from '../models/project-phase.model';
+import { addDays, normalizeDateInput } from './date-utils';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+const DEFAULT_PHASE_RATIOS: Record<PhaseName, number> = {
+  modeling: 0.3,
+  softDecor: 0.25,
+  rendering: 0.3,
+  postProcessing: 0.15
+};
+
+export function generatePhaseDeadlines(
+  startDate: Date,
+  endDate?: Date,
+  ratios: Record<PhaseName, number> = DEFAULT_PHASE_RATIOS
+): PhaseDeadlines {
+  const safeStart = new Date(startDate);
+  const safeEnd = endDate ? new Date(endDate) : addDays(safeStart, 30);
+
+  if (isNaN(safeEnd.getTime()) || safeEnd <= safeStart) {
+    safeEnd.setTime(safeStart.getTime() + 30 * DAY_MS);
+  }
+
+  const totalDays = Math.max(4, Math.ceil((safeEnd.getTime() - safeStart.getTime()) / DAY_MS));
+  const durations = calculatePhaseDurations(totalDays, ratios);
+
+  const deadlines: PhaseDeadlines = {};
+  let cursor = new Date(safeStart);
+
+  (Object.keys(durations) as PhaseName[]).forEach((phase, index) => {
+    const days = Math.max(1, durations[phase]);
+    const deadline = addDays(cursor, days);
+
+    deadlines[phase] = {
+      startDate: cursor.toISOString(),
+      deadline: deadline.toISOString(),
+      estimatedDays: days,
+      status: index === 0 ? 'in_progress' : 'not_started',
+      priority: index === 0 ? 'high' : 'medium'
+    };
+
+    cursor = new Date(deadline.getTime());
+  });
+
+  return deadlines;
+}
+
+export function ensurePhaseDeadlines(
+  existing: PhaseDeadlines | undefined,
+  startDate: Date,
+  endDate?: Date
+): PhaseDeadlines {
+  if (existing) {
+    return existing;
+  }
+  return generatePhaseDeadlines(startDate, endDate);
+}
+
+export function mapDeliveryTypeToPhase(deliveryType: string): PhaseName | null {
+  const map: Record<string, PhaseName> = {
+    white_model: 'modeling',
+    soft_decor: 'softDecor',
+    rendering: 'rendering',
+    post_process: 'postProcessing'
+  };
+  return map[deliveryType] || null;
+}
+
+export function getNextPhaseName(current: PhaseName): PhaseName | null {
+  const order: PhaseName[] = ['modeling', 'softDecor', 'rendering', 'postProcessing'];
+  const index = order.indexOf(current);
+  if (index === -1 || index === order.length - 1) {
+    return null;
+  }
+  return order[index + 1];
+}
+
+export function updatePhaseOnSubmission(
+  deadlines: PhaseDeadlines,
+  phase: PhaseName,
+  submittedAt: Date
+): void {
+  const info = ensurePhaseInfo(deadlines, phase);
+  const iso = submittedAt.toISOString();
+
+  if (!info.startDate) {
+    info.startDate = iso;
+  }
+  if (!(info as any).firstUploadAt) {
+    (info as any).firstUploadAt = iso;
+  }
+  (info as any).lastSubmissionAt = iso;
+
+  if (!info.deadline) {
+    const days = info.estimatedDays || getDefaultPhaseDays(phase);
+    const start = normalizeDateInput(info.startDate, submittedAt);
+    info.deadline = addDays(start, days).toISOString();
+    info.estimatedDays = days;
+  }
+
+  if (info.status !== 'completed') {
+    info.status = 'in_progress';
+  }
+
+  scheduleNextPhase(deadlines, phase, submittedAt);
+}
+
+export function markPhaseStatus(
+  deadlines: PhaseDeadlines,
+  phase: PhaseName,
+  status: 'completed' | 'delayed' | 'in_progress',
+  timestamp: Date
+): void {
+  const info = ensurePhaseInfo(deadlines, phase);
+  info.status = status;
+  if (status === 'completed') {
+    info.completedAt = timestamp.toISOString();
+  } else if (info.completedAt) {
+    delete info.completedAt;
+  }
+}
+
+export function scheduleNextPhase(
+  deadlines: PhaseDeadlines,
+  currentPhase: PhaseName,
+  anchorDate: Date
+): void {
+  const nextPhase = getNextPhaseName(currentPhase);
+  if (!nextPhase) {
+    return;
+  }
+
+  const nextInfo = ensurePhaseInfo(deadlines, nextPhase);
+  if (!nextInfo.startDate) {
+    nextInfo.startDate = anchorDate.toISOString();
+  }
+
+  if (!nextInfo.deadline) {
+    const days = nextInfo.estimatedDays || getDefaultPhaseDays(nextPhase);
+    const start = normalizeDateInput(nextInfo.startDate, anchorDate);
+    nextInfo.deadline = addDays(start, days).toISOString();
+    nextInfo.estimatedDays = days;
+  }
+
+  if (!nextInfo.status || nextInfo.status === 'not_started') {
+    nextInfo.status = 'not_started';
+  }
+}
+
+function ensurePhaseInfo(deadlines: PhaseDeadlines, phase: PhaseName): PhaseInfo {
+  if (!deadlines[phase]) {
+    const start = new Date();
+    const defaultDays = getDefaultPhaseDays(phase);
+    deadlines[phase] = {
+      startDate: start.toISOString(),
+      deadline: addDays(start, defaultDays).toISOString(),
+      estimatedDays: defaultDays,
+      status: 'not_started',
+      priority: 'medium'
+    };
+  }
+  return deadlines[phase]!;
+}
+
+function calculatePhaseDurations(
+  totalDays: number,
+  ratios: Record<PhaseName, number>
+): Record<PhaseName, number> {
+  const result: Record<PhaseName, number> = {
+    modeling: 1,
+    softDecor: 1,
+    rendering: 1,
+    postProcessing: 1
+  };
+
+  let allocated = 0;
+  (Object.keys(result) as PhaseName[]).forEach((phase) => {
+    const ratio = ratios[phase] ?? 0.25;
+    const days = Math.max(1, Math.round(totalDays * ratio));
+    result[phase] = days;
+    allocated += days;
+  });
+
+  const diff = totalDays - allocated;
+  if (diff !== 0) {
+    result.postProcessing = Math.max(1, result.postProcessing + diff);
+  }
+
+  return result;
+}
+
+function getDefaultPhaseDays(phase: PhaseName): number {
+  const meta = PHASE_INFO[phase];
+  if (!meta) {
+    return 3;
+  }
+  return Math.max(1, meta.defaultDays || 3);
+}
+

+ 1 - 1
src/modules/project/pages/project-detail/project-detail.component.ts

@@ -569,7 +569,7 @@ export class ProjectDetailComponent implements OnInit, OnDestroy {
     // 如果是中文名称,转换为英文ID
     if (stageNameToId[workflowCurrent]) {
       workflowCurrent = stageNameToId[workflowCurrent];
-      console.log('🔄 阶段名称映射:', this.project?.get('currentStage'), '->', workflowCurrent);
+      // console.log('🔄 阶段名称映射:', this.project?.get('currentStage'), '->', workflowCurrent);
     }
 
     // 如果没有当前阶段(新创建的项目),默认订单分配为active(红色)

+ 62 - 1
src/modules/project/pages/project-detail/stages/stage-delivery.component.ts

@@ -9,6 +9,9 @@ import { ProductSpaceService, Project } from '../../../services/product-space.se
 import { WxworkAuth } from 'fmode-ng/social';
 import { DragUploadModalComponent, UploadResult } from '../../../components/drag-upload-modal/drag-upload-modal.component';
 import { ImageAnalysisService } from '../../../services/image-analysis.service';
+import { PhaseDeadlines, PhaseName } from '../../../../../app/models/project-phase.model';
+import { ensurePhaseDeadlines, mapDeliveryTypeToPhase, markPhaseStatus, updatePhaseOnSubmission } from '../../../../../app/utils/phase-deadline.utils';
+import { addDays, normalizeDateInput } from '../../../../../app/utils/date-utils';
 
 const Parse = FmodeParse.with('nova');
 
@@ -786,8 +789,11 @@ export class StageDeliveryComponent implements OnInit, OnDestroy {
       this.cdr.markForCheck();
       console.log(`成功上传 ${uploadedFiles} 个交付文件`);
 
-      // ✨ 上传成功后通知组长审批
+      // ✨ 上传成功后通知组长审批,并记录阶段时间线
       if (uploadedFiles > 0) {
+        const projectData = this.project.get('data') || {};
+        this.applyPhaseSubmissionMetadata(projectData, deliveryType, new Date());
+        this.project.set('data', projectData);
         await this.notifyTeamLeaderForApproval(uploadedFiles, deliveryType);
         // 二次校验:从服务器重新查询,确认已写入 ProjectFile 表
         await this.verifyProjectFilesOnServer(targetProjectId, productId, deliveryType);
@@ -1620,6 +1626,8 @@ export class StageDeliveryComponent implements OnInit, OnDestroy {
       data.deliveryStageStatus[stageKey].approvedByName = this.currentUser.get('name');
       data.deliveryStageStatus[stageKey].approvedAt = now;
 
+      this.applyPhaseStatusTransition(data, currentType, 'approved');
+
       // 补充:更新空间交付物汇总
       this.updateSpaceDeliverableSummary(data, currentType, 'approved');
       
@@ -1812,6 +1820,8 @@ export class StageDeliveryComponent implements OnInit, OnDestroy {
         data.deliveryApproval.rejectionReason = reason;
       }
       
+      this.applyPhaseStatusTransition(data, currentType, 'rejected');
+      
       this.project.set('data', data);
       
       console.log('💾 保存驳回结果...');
@@ -1892,6 +1902,8 @@ export class StageDeliveryComponent implements OnInit, OnDestroy {
       data.testMarkedAt = new Date().toISOString();
       data.testMarkedBy = this.currentUser?.get('name') || 'Unknown';
       
+      this.applyPhaseStatusTransition(data, currentType, 'pending');
+      
       this.project.set('data', data);
       await this.project.save();
 
@@ -1911,6 +1923,55 @@ export class StageDeliveryComponent implements OnInit, OnDestroy {
     }
   }
 
+  private getPhaseBaseStartDate(data: any): Date {
+    const source =
+      data?.phaseDeadlines?.modeling?.startDate ||
+      data?.requirementsConfirmedAt ||
+      this.project?.get('createdAt');
+    return normalizeDateInput(source, new Date());
+  }
+
+  private getPhaseEndDate(): Date {
+    const deadline = this.project?.get('deadline');
+    return normalizeDateInput(deadline, addDays(new Date(), 30));
+  }
+
+  private ensureTimelineDeadlines(data: any): PhaseDeadlines {
+    const start = this.getPhaseBaseStartDate(data);
+    const end = this.getPhaseEndDate();
+    data.phaseDeadlines = ensurePhaseDeadlines(data.phaseDeadlines, start, end);
+    return data.phaseDeadlines;
+  }
+
+  private applyPhaseSubmissionMetadata(data: any, deliveryType: string, submittedAt: Date): void {
+    const phase = mapDeliveryTypeToPhase(deliveryType);
+    if (!phase) return;
+    const deadlines = this.ensureTimelineDeadlines(data);
+    updatePhaseOnSubmission(deadlines, phase, submittedAt);
+    data.phaseDeadlines = deadlines;
+  }
+
+  private applyPhaseStatusTransition(
+    data: any,
+    deliveryType: string,
+    status: 'approved' | 'rejected' | 'pending'
+  ): void {
+    const phase = mapDeliveryTypeToPhase(deliveryType);
+    if (!phase) return;
+    const deadlines = this.ensureTimelineDeadlines(data);
+    const timestamp = new Date();
+
+    if (status === 'approved') {
+      markPhaseStatus(deadlines, phase, 'completed', timestamp);
+    } else if (status === 'rejected') {
+      markPhaseStatus(deadlines, phase, 'delayed', timestamp);
+    } else {
+      markPhaseStatus(deadlines, phase, 'in_progress', timestamp);
+    }
+
+    data.phaseDeadlines = deadlines;
+  }
+
   /**
    * 补充:更新空间交付物汇总
    */

+ 17 - 46
src/modules/project/pages/project-detail/stages/stage-requirements.component.ts

@@ -11,6 +11,8 @@ import { ColorGetDialogComponent } from '../../../components/color-get/color-get
 import { completionJSON } from 'fmode-ng/core';
 import { addIcons } from 'ionicons';
 import { add, chevronDown, colorPalette, send, sparkles, trash } from 'ionicons/icons';
+import { generatePhaseDeadlines } from '../../../../../app/utils/phase-deadline.utils';
+import { addDays, normalizeDateInput } from '../../../../../app/utils/date-utils';
 
 addIcons({
   add,sparkles,colorPalette,trash,chevronDown,send
@@ -2358,10 +2360,11 @@ ${context}
       const data = this.project.get('data') || {};
       
       // 保存需求确认数据
+      const confirmedAt = new Date();
       data.requirementsConfirmed = true;
       data.requirementsConfirmedBy = this.currentUser.id;
       data.requirementsConfirmedByName = this.currentUser.get('name');
-      data.requirementsConfirmedAt = new Date().toISOString();
+      data.requirementsConfirmedAt = confirmedAt.toISOString();
 
       // 补充:需求确认详细信息
       data.requirementsDetail = {
@@ -2387,51 +2390,8 @@ ${context}
         confirmedAt: new Date().toISOString()
       };
 
-      // 补充:初始化阶段截止时间 (基于项目交付日期推算)
-      if (!data.phaseDeadlines && this.project.get('deadline')) {
-        const deliveryDate = new Date(this.project.get('deadline'));
-        const startDate = new Date();
-        const totalDays = Math.ceil((deliveryDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
-        
-        // 按比例分配各阶段时间:建模30%,软装25%,渲染30%,后期15%
-        const modelingDays = Math.ceil(totalDays * 0.3);
-        const softDecorDays = Math.ceil(totalDays * 0.25);
-        const renderingDays = Math.ceil(totalDays * 0.3);
-        const postProcessDays = totalDays - modelingDays - softDecorDays - renderingDays;
-
-        let currentDate = new Date(startDate);
-        
-        data.phaseDeadlines = {
-          modeling: {
-            startDate: new Date(currentDate),
-            deadline: new Date(currentDate.setDate(currentDate.getDate() + modelingDays)),
-            estimatedDays: modelingDays,
-            status: 'not_started',
-            priority: 'high'
-          },
-          softDecor: {
-            startDate: new Date(currentDate),
-            deadline: new Date(currentDate.setDate(currentDate.getDate() + softDecorDays)),
-            estimatedDays: softDecorDays,
-            status: 'not_started',
-            priority: 'medium'
-          },
-          rendering: {
-            startDate: new Date(currentDate),
-            deadline: new Date(currentDate.setDate(currentDate.getDate() + renderingDays)),
-            estimatedDays: renderingDays,
-            status: 'not_started',
-            priority: 'high'
-          },
-          postProcessing: {
-            startDate: new Date(currentDate),
-            deadline: new Date(currentDate.setDate(currentDate.getDate() + postProcessDays)),
-            estimatedDays: postProcessDays,
-            status: 'not_started',
-            priority: 'medium'
-          }
-        };
-      }
+      // 重新生成阶段截止时间 (基于当前确认时间与项目交付日期)
+      this.rebuildPhaseDeadlines(data, confirmedAt);
 
       // 补充:初始化空间交付物汇总
       if (!data.spaceDeliverableSummary && this.projectProducts.length > 0) {
@@ -2490,6 +2450,17 @@ ${context}
     }
   }
 
+  private rebuildPhaseDeadlines(data: any, confirmedAt?: Date): void {
+    const start = confirmedAt ? new Date(confirmedAt) : new Date();
+    const projectDeadline = this.project?.get('deadline');
+    const fallbackDelivery = addDays(start, 30);
+    const deliveryDate = projectDeadline
+      ? normalizeDateInput(projectDeadline, fallbackDelivery)
+      : fallbackDelivery;
+
+    data.phaseDeadlines = generatePhaseDeadlines(start, deliveryDate);
+  }
+
   // ===== 工具方法 =====
 
   /**