# 项目日志与人效分析方案

## 概述

基于Product表统一空间管理和ProjectChange表的项目变化日志，设计完整的项目管理行为数据追踪和人效分析系统，为企业提供数据驱动的绩效评估和优化决策支持。

## ProjectChange表设计

### 表结构定义

```typescript
interface ProjectChange {
  objectId: string;                    // 主键ID
  company: Pointer<Company>;          // 所属企业
  project?: Pointer<Project>;         // 关联项目（可选）
  product?: Pointer<Product>;         // 关联空间产品（可选）
  profile: Pointer<Profile>;         // 操作人员
  changeType: string;                // 变化类型
  changeCategory: string;             // 变化分类
  changeAction: string;               // 具体动作
  description: string;                // 变化描述
  oldValue?: any;                     // 变化前值
  newValue?: any;                     // 变化后值
  metadata?: Object;                  // 扩展元数据
  timestamp: Date;                    // 发生时间
  source: string;                     // 数据来源
  clientInfo?: Object;                // 客户端信息
  duration?: Number;                  // 操作耗时（毫秒）
  relatedModule: string;              // 关联模块
  impactLevel: string;                // 影响级别
  tags?: Array<string>;               // 标签
  data?: Object;                      // 扩展数据
  isDeleted: Boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

### 核心字段枚举值

#### changeType（变化类型）
- `project_basic`: 项目基础信息变更
- `project_status`: 项目状态变更
- `product_create`: 产品创建
- `product_update`: 产品更新
- `product_stage`: 产品阶段变更
- `team_assign`: 团队分配
- `file_upload`: 文件上传
- `payment_record`: 付款记录
- `feedback_create`: 反馈创建
- `requirement_update`: 需求更新
- `quotation_change`: 报价变更
- `quality_review`: 质量审核
- `communication`: 沟通记录
- `exception`: 异常事件
- `milestone`: 里程碑达成

#### changeCategory（变化分类）
- `项目管理`: project_management
- `设计执行`: design_execution
- `团队协作`: team_collaboration
- `客户沟通`: client_communication
- `财务管理`: financial_management
- `质量控制`: quality_control
- `文件管理`: file_management
- `交付管理`: delivery_management

#### changeAction（具体动作）
- `create`: 创建
- `update`: 更新
- `delete`: 删除
- `assign`: 分配
- `approve`: 审批
- `reject`: 拒绝
- `complete`: 完成
- `cancel`: 取消
- `upload`: 上传
- `download`: 下载
- `review`: 审核
- `comment`: 评论
- `modify`: 修改

#### impactLevel（影响级别）
- `low`: 低影响 - 常规操作，影响范围小
- `medium`: 中影响 - 重要操作，影响项目进度
- `high`: 高影响 - 关键操作，影响项目交付
- `critical`: 严重 - 风险事件，可能导致项目延期或失败

## 项目管理行为数据分析

### 1. 岗位行为模式识别

#### 客服人员行为数据
```typescript
interface ServiceBehaviorData {
  // 项目接单与分配
  orderAcceptance: {
    totalOrders: number;           // 接单总数
    averageResponseTime: number;   // 平均响应时间
    conversionRate: number;       // 成交转化率
    orderToProjectTime: number;    // 接单转项目平均时间
  };

  // 客户沟通
  clientCommunication: {
    communicationCount: number;    // 沟通次数
    averageResponseTime: number;   // 客户回复响应时间
    satisfactionScore: number;     // 客户满意度
    followupFrequency: number;    // 跟进频次
  };

  // 需求管理
  requirementManagement: {
    requirementCollectionRate: number;  // 需求收集完整率
    requirementClarificationCount: number; // 需求澄清次数
    analysisAccuracy: number;           // 需求分析准确度
  };
}
```

#### 设计师行为数据
```typescript
interface DesignerBehaviorData {
  // 设计执行效率
  designExecution: {
    projectCount: number;          // 负责项目数
    averageDesignTime: number;    // 平均设计时间
    revisionCount: number;         // 修改次数
    firstPassRate: number;        // 一次通过率
  };

  // 质量表现
  qualityMetrics: {
    clientRating: number;          // 客户评分
    qualityIssueCount: number;     // 质量问题数
    reworkRate: number;           // 返工率
    innovationScore: number;       // 创新评分
  };

  // 协作表现
  collaboration: {
    teamCommunication: number;     // 团队沟通频次
    knowledgeSharing: number;     // 知识分享次数
    mentorshipActivity: number;  // 指导新人次数
  };
}
```

#### 组长行为数据
```typescript
interface LeaderBehaviorData {
  // 项目管理
  projectManagement: {
    teamProjectCount: number;     // 团队项目数
    onTimeDeliveryRate: number;   // 按时交付率
    budgetUtilization: number;    // 预算使用率
    resourceAllocation: number;   // 资源分配效率
  };

  // 团队管理
  teamManagement: {
    teamSize: number;             // 团队规模
    teamSatisfaction: number;     // 团队满意度
    teamPerformanceScore: number; // 团队绩效
    conflictResolution: number;   // 冲突解决次数
  };

  // 质量控制
  qualityControl: {
    reviewCount: number;          // 审核次数
    qualityImprovement: number;   // 质量改进建议数
    errorPrevention: number;      // 错误预防次数
  };
}
```

### 2. 项目生命周期行为数据

#### 项目启动阶段
```typescript
interface ProjectInitiationData {
  // 需求收集
  requirementCollection: {
    collectionTime: number;       // 需求收集耗时
    completenessScore: number;   // 需求完整度
    clarificationRound: number;  // 需求澄清轮次
    stakeholderEngagement: number; // 相关方参与度
  };

  // 项目规划
  projectPlanning: {
    planningTime: number;         // 规划时间
    scopeDefinitionQuality: number; // 范围定义质量
    timelineAccuracy: number;     // 时间预估准确性
    resourcePlanningAccuracy: number; // 资源规划准确性
  };
}
```

#### 设计执行阶段
```typescript
interface DesignExecutionData {
  // 产品创建
  productCreation: {
    productCount: number;          // 产品数量
    creationTime: number;         // 创建时间
    qualityScore: number;          // 质量评分
    clientApprovalRate: number;   // 客户通过率
  };

  // 阶段管理
  stageManagement: {
    stageTransitionTime: number;  // 阶段转换时间
    blockageFrequency: number;    // 阻塞频率
    stageQualityScore: number;   // 各阶段质量评分
    coordinationEfficiency: number; // 协调效率
  };
}
```

#### 交付完成阶段
```typescript
interface DeliveryCompletionData {
  // 交付管理
  deliveryManagement: {
    deliveryTime: number;         // 交付时间
    qualityCompliance: number;   // 质量合规性
    clientAcceptanceRate: number; // 客户验收率
    defectRate: number;          // 缺陷率
  };

  // 客户满意度
  clientSatisfaction: {
    satisfactionScore: number;    // 满意度评分
    feedbackCount: number;        // 反馈数量
    complaintCount: number;      // 投诉数量
    recommendationRate: number;   // 推荐率
  };
}
```

## ProjectChange记录场景设计

### 1. 项目管理场景

#### 项目创建与分配
```typescript
// 场景：客服接收新项目并分配给设计师
const projectAssignmentChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: serviceProfilePointer,
  changeType: "project_basic",
  changeCategory: "项目管理",
  changeAction: "assign",
  description: "客服张三将项目'李总现代简约全案'分配给设计师李四",
  oldValue: { assignee: null },
  newValue: { assignee: "李四", assignedAt: timestamp },
  metadata: {
    customerResponseTime: 1200,    // 客户响应时间（毫秒）
    orderValue: 85000,              // 订单金额
    projectComplexity: "medium"    // 项目复杂度
  },
  duration: 3500,
  impactLevel: "medium",
  tags: ["项目分配", "新项目", "客户转化"],
  relatedModule: "项目管理"
};
```

#### 项目状态变更
```typescript
// 场景：项目阶段推进
const projectStageChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: designerProfilePointer,
  changeType: "project_status",
  changeCategory: "项目管理",
  changeAction: "update",
  description: "设计师李四将项目'李总现代简约全案'从'建模'阶段推进到'渲染'阶段",
  oldValue: { stage: "建模", progress: 45 },
  newValue: { stage: "rendering", progress: 60 },
  metadata: {
    stageCompletionTime: 864000000,  // 阶段完成时间（毫秒）
    qualityScore: 4.2,                // 阶段质量评分
    clientFeedbackCount: 2            // 客户反馈次数
  },
  duration: 1200,
  impactLevel: "high",
  tags: ["阶段推进", "质量把控", "客户反馈"],
  relatedModule: "设计执行"
};
```

### 2. 产品管理场景

#### 空间产品创建
```typescript
// 场景：设计师创建新的空间设计产品
const productCreationChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  product: productPointer,
  profile: designerProfilePointer,
  changeType: "product_create",
  changeCategory: "设计执行",
  changeAction: "create",
  description: "设计师李四创建空间产品'李总主卧设计'",
  newValue: {
    productName: "李总主卧设计",
    productType: "bedroom",
    estimatedBudget: 35000,
    estimatedDuration: 7
  },
  metadata: {
    spaceArea: 18.5,                 // 空间面积
    designComplexity: "medium",       // 设计复杂度
    templateUsed: "modern_minimal",   // 使用模板
    innovationScore: 3.8             // 创新评分
  },
  duration: 5400,
  impactLevel: "medium",
  tags: ["产品设计", "空间规划", "创新设计"],
  relatedModule: "产品设计"
};
```

#### 产品报价更新
```typescript
// 场景：组长审核并批准产品报价
const quotationApprovalChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  product: productPointer,
  profile: leaderProfilePointer,
  changeType: "quotation_change",
  changeCategory: "财务管理",
  changeAction: "approve",
  description: "组长王五审核通过'李总主卧设计'产品报价，金额35000元",
  oldValue: {
    quotation: {
      price: 32000,
      status: "pending"
    }
  },
  newValue: {
    quotation: {
      price: 35000,
      status: "approved",
      approvedBy: "王五",
      approvedAt: timestamp
    }
  },
  metadata: {
    priceAdjustment: 3000,           // 价格调整
    negotiationRound: 1,            // 商议轮次
    profitMargin: 0.28,              // 利润率
    marketCompetitiveness: "high"   // 市场竞争力
  },
  duration: 2800,
  impactLevel: "high",
  tags: ["报价审核", "财务决策", "利润管理"],
  relatedModule: "财务管理"
};
```

### 3. 团队协作场景

#### 团队成员分配
```typescript
// 场景：组长为项目分配团队成员
const teamAssignmentChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: leaderProfilePointer,
  changeType: "team_assign",
  changeCategory: "团队协作",
  changeAction: "assign",
  description: "组长王五为项目'李总现代简约全案'分配渲染师赵六",
  newValue: {
    teamMember: "赵六",
    role: "渲染师",
    workload: 0.6,
    startDate: timestamp,
    responsibilities: ["主卧渲染", "客厅渲染"]
  },
  metadata: {
    workloadBalance: 0.75,          // 工作负载平衡度
    skillMatchScore: 4.5,           // 技能匹配评分
    teamMemberAvailability: "high",  // 成员可用性
    coordinationComplexity: "low"    // 协调复杂度
  },
  duration: 1800,
  impactLevel: "medium",
  tags: ["团队协作", "技能匹配", "资源分配"],
  relatedModule: "团队管理"
};
```

#### 工作负载调整
```typescript
// 场景：项目经理调整团队成员工作负载
const workloadAdjustmentChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: leaderProfilePointer,
  changeType: "team_assign",
  changeCategory: "团队协作",
  changeAction: "modify",
  description: "组长王五调整设计师李四的工作负载从0.8降至0.6，避免过载",
  oldValue: { workload: 0.8, status: "高负载" },
  newValue: { workload: 0.6, status: "正常负载" },
  metadata: {
    overloadRiskLevel: "medium",    // 过载风险级别
    adjustmentReason: "质量保障",   // 调整原因
    impactOnTimeline: "minimal",    // 对时间线影响
    teamMemberConsent: true         // 成员同意
  },
  duration: 900,
  impactLevel: "medium",
  tags: ["负载调整", "资源优化", "团队管理"],
  relatedModule: "团队管理"
};
```

### 4. 文件管理场景

#### 设计文件上传
```typescript
// 场景：设计师上传设计效果图
const fileUploadChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  product: productPointer,
  profile: designerProfilePointer,
  changeType: "file_upload",
  changeCategory: "文件管理",
  changeAction: "upload",
  description: "设计师李四上传'李总主卧设计'效果图3张",
  newValue: {
    files: [
      {
        fileName: "主卧效果图1.jpg",
        fileSize: 2458176,
        fileType: "rendering",
        category: "delivery"
      },
      {
        fileName: "主卧效果图2.jpg",
        fileSize: 3152418,
        fileType: "rendering",
        category: "delivery"
      }
    ],
    uploadCount: 3,
    totalSize: 8452792
  },
  metadata: {
    uploadDuration: 45000,          // 上传耗时（毫秒）
    fileQualityScore: 4.7,          // 文件质量评分
    revisionNumber: 1,              // 修改版本
    clientApprovalRequired: true   // 需要客户审批
  },
  duration: 45000,
  impactLevel: "medium",
  tags: ["文件上传", "设计交付", "质量检查"],
  relatedModule: "文件管理"
};
```

#### 客户反馈文件
```typescript
// 场景：客户上传参考图片
const customerFileUploadChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: customerProfilePointer,
  changeType: "file_upload",
  changeCategory: "客户沟通",
  changeAction: "upload",
  description: "客户李总上传参考图片5张，用于明确设计风格偏好",
  newValue: {
    files: [
      { fileName: "参考风格1.jpg", category: "reference" },
      { fileName: "参考风格2.jpg", category: "reference" }
    ],
    uploadCount: 5,
    purpose: "设计参考"
  },
  metadata: {
    source: "客户上传",
    referenceClarity: "high",       // 参考清晰度
    designAlignment: 0.85,          // 设计契合度
    designerFeedbackRequired: true  // 需要设计师反馈
  },
  duration: 32000,
  impactLevel: "low",
  tags: ["客户参与", "需求明确", "设计参考"],
  relatedModule: "客户沟通"
};
```

### 5. 财务管理场景

#### 付款记录
```typescript
// 场景：财务人员记录客户付款
const paymentRecordChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: financeProfilePointer,
  changeType: "payment_record",
  changeCategory: "财务管理",
  changeAction: "create",
  description: "财务人员钱七记录客户李总支付项目首期款35000元",
  newValue: {
    payment: {
      type: "advance",
      amount: 35000,
      currency: "CNY",
      method: "bank_transfer",
      status: "paid",
      percentage: 30
    }
  },
  metadata: {
    paymentDelayDays: 2,            // 付款延迟天数
    paymentMethod: "bank_transfer", // 付款方式
    cashFlowImpact: "positive",     // 现金流影响
    followUpRequired: false        // 需要跟进
  },
  duration: 2400,
  impactLevel: "high",
  tags: ["付款记录", "现金管理", "项目收款"],
  relatedModule: "财务管理"
};
```

#### 付款提醒
```typescript
// 场景：系统自动发送付款提醒
const paymentReminderChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: systemProfilePointer,
  changeType: "payment_record",
  changeCategory: "财务管理",
  changeAction: "comment",
  description: "系统自动发送付款提醒给客户李总，提醒第二笔款35000元将于3天后到期",
  newValue: {
    reminder: {
      type: "payment_due",
      amount: 35000,
      dueDate: dueDate,
      reminderSent: true,
      reminderCount: 1
    }
  },
  metadata: {
    reminderChannel: "wechat",      // 提醒渠道
    automationEnabled: true,        // 自动化启用
    responseRequired: true,         // 需要响应
    urgencyLevel: "medium"          // 紧急程度
  },
  duration: 500,
  impactLevel: "medium",
  tags: ["自动提醒", "付款管理", "客户沟通"],
  relatedModule: "财务管理",
  source: "system"
};
```

### 6. 质量控制场景

#### 设计质量审核
```typescript
// 场景：组长审核设计方案
const qualityReviewChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  product: productPointer,
  profile: leaderProfilePointer,
  changeType: "quality_review",
  changeCategory: "质量控制",
  changeAction: "review",
  description: "组长王五审核'李总主卧设计'方案，提出3点改进建议",
  newValue: {
    review: {
      status: "approved_with_modifications",
      qualityScore: 4.2,
      issueCount: 3,
      improvementSuggestions: [
        "灯光布局需要优化",
        "储物空间设计可以更充分利用",
        "色彩搭配建议调整"
      ]
    }
  },
  metadata: {
    reviewDuration: 3600,           // 审核耗时（秒）
    checklistScore: 0.88,          // 检查表得分
    standardCompliance: "high",     // 标准合规性
    revisionImpact: "low"          // 修改影响程度
  },
  duration: 3600,
  impactLevel: "high",
  tags: ["质量审核", "设计把关", "改进建议"],
  relatedModule: "质量控制"
};
```

#### 客户反馈处理
```typescript
// 场景：客服处理客户反馈
const feedbackHandlingChange: ProjectChange = {
  company: companyPointer,
  project: projectPointer,
  profile: serviceProfilePointer,
  changeType: "feedback_create",
  changeCategory: "客户沟通",
  changeAction: "update",
  description: "客服张三处理客户李总关于客厅设计的反馈，协调设计师进行修改",
  newValue: {
    feedback: {
      status: "in_progress",
      priority: "medium",
      assignedTo: "李四",
      expectedResolution: timestamp + 86400000
    }
  },
  metadata: {
    responseTime: 1800,            // 响应时间（秒）
    feedbackType: "design_modification", // 反馈类型
    clientEmotion: "neutral",       // 客户情绪
    resolutionComplexity: "medium"  // 解决复杂度
  },
  duration: 1500,
  impactLevel: "medium",
  tags: ["客户反馈", "问题处理", "协调沟通"],
  relatedModule: "客户沟通"
};
```

## 人效分析计算方案

### 1. 个人绩效分析

#### 基础效率指标
```typescript
interface IndividualEfficiencyMetrics {
  // 工作量指标
  workload: {
    projectCount: number;          // 负责项目数量
    productCount: number;          // 完成产品数量
    taskCompletionRate: number;    // 任务完成率
    averageTaskDuration: number;   // 平均任务时长
  };

  // 质量指标
  quality: {
    clientSatisfactionScore: number; // 客户满意度评分
    revisionRate: number;           // 修改率
    firstPassYield: number;         // 一次通过率
    errorCount: number;             // 错误数量
  };

  // 效率指标
  efficiency: {
    outputPerHour: number;          // 每小时产出
    resourceUtilization: number;    // 资源利用率
    deadlineAdherence: number;      // 截止时间遵守率
    reworkPercentage: number;       // 返工比例
  };
}
```

#### 协作表现指标
```typescript
interface CollaborationMetrics {
  // 团队协作
  teamwork: {
    collaborationScore: number;     // 协作评分
    knowledgeSharingCount: number;  // 知识分享次数
    mentorshipScore: number;        // 指导评分
    conflictResolutionSuccess: number; // 冲突解决成功率
  };

  // 沟通效率
  communication: {
    responseTime: number;           // 平均响应时间
    communicationClarity: number;   // 沟通清晰度
    stakeholderSatisfaction: number; // 相关方满意度
    meetingEffectiveness: number;   // 会议有效性
  };
}
```

### 2. 团队效能分析

#### 团队综合指标
```typescript
interface TeamEffectivenessMetrics {
  // 交付能力
  delivery: {
    onTimeDeliveryRate: number;     // 按时交付率
    qualityCompliance: number;     // 质量合规性
    clientSatisfactionAverage: number; // 平均客户满意度
    throughputPerPeriod: number;   // 周期产出量
  };

  // 资源利用
  resource: {
    teamUtilizationRate: number;    // 团队资源利用率
    workloadBalance: number;       // 工作负载平衡度
    skillUtilization: number;       // 技能利用率
    overtimePercentage: number;     // 加班比例
  };

  // 财务表现
  financial: {
    revenuePerTeamMember: number;   // 人均收入
    projectProfitability: number;   // 项目盈利性
    costEfficiency: number;        // 成本效率
    budgetAdherence: number;        // 预算遵守率
  };
}
```

### 3. 计算方法与公式

#### 个人效率计算
```typescript
// 效率综合评分计算
function calculateEfficiencyScore(changeLogs: ProjectChange[], timeRange: DateRange): number {
  const workloadScore = calculateWorkloadScore(changeLogs, timeRange);
  const qualityScore = calculateQualityScore(changeLogs, timeRange);
  const speedScore = calculateSpeedScore(changeLogs, timeRange);

  // 加权平均
  const weights = { workload: 0.4, quality: 0.4, speed: 0.2 };
  return workloadScore * weights.workload +
         qualityScore * weights.quality +
         speedScore * weights.speed;
}

// 工作量评分计算
function calculateWorkloadScore(changeLogs: ProjectChange[], timeRange: DateRange): number {
  const completedTasks = changeLogs.filter(log =>
    log.changeAction === 'complete' &&
    isDateInRange(log.timestamp, timeRange)
  ).length;

  const totalWorkingHours = calculateWorkingHours(timeRange);
  const tasksPerHour = completedTasks / totalWorkingHours;

  // 基准对比评分（假设基准为2 tasks/hour）
  const baseline = 2.0;
  return Math.min(tasksPerHour / baseline, 2.0) * 100;
}

// 质量评分计算
function calculateQualityScore(changeLogs: ProjectChange[], timeRange: DateRange): number {
  const feedbackLogs = changeLogs.filter(log =>
    log.changeType === 'feedback_create' &&
    isDateInRange(log.timestamp, timeRange)
  );

  if (feedbackLogs.length === 0) return 80; // 默认质量分

  const averageRating = feedbackLogs.reduce((sum, log) => {
    return sum + (log.metadata?.rating || 3);
  }, 0) / feedbackLogs.length;

  const revisionLogs = changeLogs.filter(log =>
    log.changeAction === 'modify' &&
    log.changeCategory === '设计执行'
  ).length;

  const revisionPenalty = Math.min(revisionLogs * 5, 30);
  return Math.max((averageRating / 5) * 100 - revisionPenalty, 0);
}

// 速度评分计算
function calculateSpeedScore(changeLogs: ProjectChange[], timeRange: DateRange): number {
  const completedTasks = changeLogs.filter(log =>
    log.changeAction === 'complete' &&
    log.duration &&
    isDateInRange(log.timestamp, timeRange)
  );

  if (completedTasks.length === 0) return 80;

  const averageDuration = completedTasks.reduce((sum, log) =>
    sum + log.duration!, 0) / completedTasks.length;

  const expectedDuration = 3600000; // 1小时基准
  const speedRatio = expectedDuration / averageDuration;

  return Math.min(speedRatio * 100, 150); // 最高150分
}
```

#### 团队效能计算
```typescript
// 团队效能综合评分
function calculateTeamEffectivenessScore(teamChanges: ProjectChange[], timeRange: DateRange): TeamEffectivenessMetrics {
  const teamMembers = getUniqueProfiles(teamChanges);

  return {
    delivery: {
      onTimeDeliveryRate: calculateOnTimeDeliveryRate(teamChanges, timeRange),
      qualityCompliance: calculateQualityComplianceRate(teamChanges, timeRange),
      clientSatisfactionAverage: calculateAverageClientSatisfaction(teamChanges, timeRange),
      throughputPerPeriod: calculateThroughput(teamChanges, timeRange)
    },
    resource: {
      teamUtilizationRate: calculateTeamUtilization(teamChanges, teamMembers, timeRange),
      workloadBalance: calculateWorkloadBalance(teamChanges, teamMembers, timeRange),
      skillUtilization: calculateSkillUtilization(teamChanges, timeRange),
      overtimePercentage: calculateOvertimePercentage(teamChanges, teamMembers, timeRange)
    },
    financial: {
      revenuePerTeamMember: calculateRevenuePerMember(teamChanges, teamMembers, timeRange),
      projectProfitability: calculateProjectProfitability(teamChanges, timeRange),
      costEfficiency: calculateCostEfficiency(teamChanges, timeRange),
      budgetAdherence: calculateBudgetAdherence(teamChanges, timeRange)
    }
  };
}

// 按时交付率计算
function calculateOnTimeDeliveryRate(changes: ProjectChange[], timeRange: DateRange): number {
  const deliveries = changes.filter(log =>
    log.changeType === 'milestone' &&
    log.changeAction === 'complete' &&
    isDateInRange(log.timestamp, timeRange)
  );

  if (deliveries.length === 0) return 100;

  const onTimeDeliveries = deliveries.filter(log =>
    !log.metadata?.delay || log.metadata.delay <= 0
  ).length;

  return (onTimeDeliveries / deliveries.length) * 100;
}

// 工作负载平衡度计算
function calculateWorkloadBalance(changes: ProjectChange[], members: Profile[], timeRange: DateRange): number {
  const workloadByMember = members.map(member => {
    const memberChanges = changes.filter(log =>
      log.profile.objectId === member.objectId &&
      isDateInRange(log.timestamp, timeRange)
    );

    return memberChanges.reduce((total, log) => {
      if (log.changeAction === 'complete' || log.changeAction === 'create') {
        return total + (log.metadata?.workload || 1);
      }
      return total;
    }, 0);
  });

  const averageWorkload = workloadByMember.reduce((sum, w) => sum + w, 0) / workloadByMember.length;
  const variance = workloadByMember.reduce((sum, w) => sum + Math.pow(w - averageWorkload, 2), 0) / workloadByMember.length;
  const standardDeviation = Math.sqrt(variance);

  // 平衡度 = 1 - (标准差/平均值)，越接近1表示越平衡
  return Math.max(0, Math.min(100, (1 - standardDeviation / averageWorkload) * 100));
}
```

### 4. 预测分析模型

#### 个人绩效预测
```typescript
interface PerformancePrediction {
  predictedEfficiency: number;     // 预测效率评分
  confidenceLevel: number;         // 预测置信度
  riskFactors: string[];          // 风险因素
  improvementSuggestions: string[]; // 改进建议
}

function predictIndividualPerformance(
  profile: Profile,
  historicalData: ProjectChange[],
  timeHorizon: number // 预测天数
): PerformancePrediction {
  const recentPerformance = calculateRecentPerformance(historicalData, 30);
  const trend = calculatePerformanceTrend(historicalData, 90);
  const workloadPattern = analyzeWorkloadPattern(historicalData, 60);

  // 线性回归预测
  const predictedScore = recentPerformance.efficiencyScore + (trend * timeHorizon / 30);

  // 识别风险因素
  const riskFactors = identifyRiskFactors(historicalData);

  // 生成改进建议
  const suggestions = generateImprovementSuggestions(recentPerformance, riskFactors);

  return {
    predictedEfficiency: Math.max(0, Math.min(100, predictedScore)),
    confidenceLevel: calculateConfidenceLevel(historicalData.length),
    riskFactors,
    improvementSuggestions: suggestions
  };
}
```

#### 项目风险预警
```typescript
interface ProjectRiskAlert {
  riskLevel: 'low' | 'medium' | 'high' | 'critical';
  riskFactors: Array<{
    type: string;
    probability: number;
    impact: number;
    description: string;
  }>;
  mitigationSuggestions: string[];
}

function predictProjectRisks(projectChanges: ProjectChange[]): ProjectRiskAlert {
  const riskFactors = [];

  // 进度风险分析
  const scheduleRisk = analyzeScheduleRisk(projectChanges);
  if (scheduleRisk.probability > 0.3) {
    riskFactors.push(scheduleRisk);
  }

  // 质量风险分析
  const qualityRisk = analyzeQualityRisk(projectChanges);
  if (qualityRisk.probability > 0.2) {
    riskFactors.push(qualityRisk);
  }

  // 资源风险分析
  const resourceRisk = analyzeResourceRisk(projectChanges);
  if (resourceRisk.probability > 0.25) {
    riskFactors.push(resourceRisk);
  }

  // 综合风险评级
  const overallRisk = calculateOverallRisk(riskFactors);

  return {
    riskLevel: overallRisk.level,
    riskFactors,
    mitigationSuggestions: generateMitigationStrategies(riskFactors)
  };
}
```

### 5. 数据可视化方案

#### 个人绩效仪表板
```typescript
interface PersonalPerformanceDashboard {
  profile: Profile;
  timeRange: DateRange;
  metrics: {
    efficiencyScore: number;
    qualityScore: number;
    workloadBalance: number;
    collaborationScore: number;
  };
  trends: {
    efficiencyTrend: Array<{date: Date, value: number}>;
    qualityTrend: Array<{date: Date, value: number}>;
    workloadTrend: Array<{date: Date, value: number}>;
  };
  comparisons: {
    teamAverage: number;
    departmentRank: number;
    personalBest: number;
  };
}
```

#### 团队效能雷达图
```typescript
interface TeamPerformanceRadar {
  teamName: string;
  dimensions: {
    delivery: number;              // 交付能力
    quality: number;               // 质量水平
    efficiency: number;            // 效率指标
    collaboration: number;         // 协作能力
    innovation: number;            // 创新能力
    clientSatisfaction: number;    // 客户满意度
  };
  benchmarks: {
    departmentAverage: number;
    companyAverage: number;
    industryStandard: number;
  };
}
```

## 实施建议

### 1. 数据收集策略
- **实时记录**: 关键业务操作实时记录到ProjectChange表
- **批量处理**: 高频操作可考虑批量写入，提高性能
- **数据清洗**: 定期清理重复、无效的日志数据
- **隐私保护**: 敏感信息进行脱敏处理

### 2. 分析频率设置
- **实时监控**: 关键指标异常实时告警
- **日报**: 个人工作量和完成情况日报
- **周报**: 团队效能和项目进度周报
- **月报**: 综合绩效分析和趋势预测月报
- **季报**: 人才发展和团队建设季报

### 3. 激励机制设计
- **绩效挂钩**: 将分析结果与薪酬激励挂钩
- **发展导向**: 关注个人成长和技能提升
- **团队奖励**: 鼓励团队协作和知识分享
- **持续改进**: 基于数据持续优化工作流程

### 4. 技术实施要点
- **数据一致性**: 确保日志数据的完整性和一致性
- **计算性能**: 优化大数据量下的计算性能
- **存储优化**: 合理设计索引和分区策略
- **安全防护**: 防止数据泄露和恶意访问

---

该方案通过完整的项目变化日志记录和科学的人效分析模型，为企业提供了数据驱动的人才管理和项目优化决策支持系统。