| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181 |
- import { Component, OnInit, Input, Output, EventEmitter, OnDestroy } from '@angular/core';
- import { CommonModule } from '@angular/common';
- import { Router, ActivatedRoute, RouterModule } from '@angular/router';
- import { IonicModule } from '@ionic/angular';
- import { WxworkSDK, WxworkCorp, WxworkAuth } from 'fmode-ng/core';
- import { FmodeParse, FmodeObject } from 'fmode-ng/parse';
- import { ProfileService } from '../../../../app/services/profile.service';
- import { ProjectBottomCardComponent } from '../../components/project-bottom-card/project-bottom-card.component';
- import { ProjectFilesModalComponent } from '../../components/project-files-modal/project-files-modal.component';
- import { ProjectMembersModalComponent } from '../../components/project-members-modal/project-members-modal.component';
- import { ProjectIssuesModalComponent } from '../../components/project-issues-modal/project-issues-modal.component';
- import { ProjectIssueService } from '../../services/project-issue.service';
- import { FormsModule } from '@angular/forms';
- import { CustomerSelectorComponent } from '../../components/contact-selector/contact-selector.component';
- import { OrderApprovalPanelComponent } from '../../../../app/shared/components/order-approval-panel/order-approval-panel.component';
- const Parse = FmodeParse.with('nova');
- /**
- * 项目详情核心组件
- *
- * 功能:
- * 1. 展示四阶段导航(订单分配、确认需求、交付执行、售后归档)
- * 2. 根据角色控制权限
- * 3. 子路由切换阶段内容
- * 4. 支持@Input和路由参数两种数据加载方式
- *
- * 路由:/wxwork/:cid/project/:projectId
- */
- @Component({
- selector: 'app-project-detail',
- standalone: true,
- imports: [
- CommonModule,
- IonicModule,
- RouterModule,
- ProjectBottomCardComponent,
- ProjectFilesModalComponent,
- ProjectMembersModalComponent,
- ProjectIssuesModalComponent,
- CustomerSelectorComponent,
- OrderApprovalPanelComponent
- ],
- templateUrl: './project-detail.component.html',
- styleUrls: ['./project-detail.component.scss']
- })
- export class ProjectDetailComponent implements OnInit, OnDestroy {
- // 输入参数(支持组件复用)
- @Input() project: FmodeObject | null = null;
- @Input() groupChat: FmodeObject | null = null;
- @Input() currentUser: FmodeObject | null = null;
- // 问题统计
- issueCount: number = 0;
- // 路由参数
- cid: string = '';
- projectId: string = '';
- groupId: string = '';
- profileId: string = '';
- chatId: string = ''; // 从企微进入时的 chat_id
- // 企微SDK
- wxwork: WxworkSDK | null = null;
- wecorp: WxworkCorp | null = null;
- wxAuth: WxworkAuth | null = null; // WxworkAuth 实例
- // 加载状态
- loading: boolean = true;
- error: string | null = null;
- // 项目数据
- contact: FmodeObject | null = null;
- assignee: FmodeObject | null = null;
- // 当前阶段
- currentStage: string = 'order'; // order | requirements | delivery | aftercare
- stages = [
- { id: 'order', name: '订单分配', icon: 'document-text-outline', number: 1 },
- { id: 'requirements', name: '确认需求', icon: 'checkmark-circle-outline', number: 2 },
- { id: 'delivery', name: '交付执行', icon: 'rocket-outline', number: 3 },
- { id: 'aftercare', name: '售后归档', icon: 'archive-outline', number: 4 }
- ];
- // 权限
- canEdit: boolean = false;
- canViewCustomerPhone: boolean = false;
- role: string = '';
- // 模态框状态
- showFilesModal: boolean = false;
- showMembersModal: boolean = false;
- showIssuesModal: boolean = false;
- // 新增:客户详情侧栏面板状态
- showContactPanel: boolean = false;
- // 问卷状态
- surveyStatus: {
- filled: boolean;
- text: string;
- icon: string;
- surveyLog?: FmodeObject;
- contact?: FmodeObject;
- } = {
- filled: false,
- text: '发送问卷',
- icon: 'document-text-outline'
- };
- // 折叠:项目基本信息
- showProjectInfoCollapsed: boolean = true;
- // 事件监听器引用
- private stageCompletedListener: any = null;
- // 🆕 停滞期和改图期状态
- get isStalled(): boolean {
- const data = this.project?.get('data') || {};
- return data.isStalled === true;
- }
- get isModification(): boolean {
- const data = this.project?.get('data') || {};
- return data.isModification === true;
- }
- get stagnationInfo() {
- const data = this.project?.get('data') || {};
- return {
- reasonType: data.stagnationReasonType,
- customReason: data.stagnationCustomReason,
- estimatedResumeDate: data.estimatedResumeDate,
- notes: data.reasonNotes,
- markedAt: data.markedAt,
- markedBy: data.markedBy
- };
- }
- get modificationInfo() {
- const data = this.project?.get('data') || {};
- return {
- reasonType: data.modificationReasonType,
- customReason: data.modificationCustomReason,
- notes: data.reasonNotes,
- markedAt: data.markedAt,
- markedBy: data.markedBy
- };
- }
- constructor(
- private router: Router,
- private route: ActivatedRoute,
- private profileService: ProfileService,
- private issueService: ProjectIssueService
- ) {}
- async ngOnInit() {
- // 获取路由参数
- this.cid = this.route.snapshot.paramMap.get('cid') || '';
- // 兼容:cid 在父级路由上
- if (!this.cid) {
- this.cid = this.route.parent?.snapshot.paramMap.get('cid') || '';
- }
- // 降级:从 localStorage 读取
- if (!this.cid) {
- this.cid = localStorage.getItem('company') || '';
- }
- this.projectId = this.route.snapshot.paramMap.get('projectId') || '';
- this.groupId = this.route.snapshot.queryParamMap.get('groupId') || '';
- this.profileId = this.route.snapshot.queryParamMap.get('profileId') || '';
- this.chatId = this.route.snapshot.queryParamMap.get('chatId') || '';
-
- console.log('📌 路由参数:', {
- cid: this.cid,
- projectId: this.projectId
- });
- // 监听路由变化
- this.route.firstChild?.url.subscribe((segments) => {
- if (segments.length > 0) {
- this.currentStage = segments[0].path;
- console.log('🔄 当前阶段已更新:', this.currentStage);
- }
- });
- // 初始化企微授权(不阻塞页面加载)
- await this.initWxworkAuth();
- await this.loadData();
- // 初始化工作流阶段(若缺失则根据已完成记录推断)
- this.ensureWorkflowStage();
- // 监听各阶段完成事件,自动推进到下一环节
- this.stageCompletedListener = async (e: any) => {
- console.log('🎯 [监听器] 事件触发', e?.detail);
-
- const stageId = e?.detail?.stage as string;
- if (!stageId) {
- console.error('❌ [监听器] 事件缺少 stage 参数');
- return;
- }
-
- console.log('✅ [监听器] 接收到阶段完成事件:', stageId);
- await this.advanceToNextStage(stageId);
- };
-
- console.log('📡 [初始化] 注册事件监听器: stage:completed');
- document.addEventListener('stage:completed', this.stageCompletedListener);
- console.log('✅ [初始化] 事件监听器注册成功');
- }
- /**
- * 组件销毁时清理事件监听器
- */
- ngOnDestroy() {
- if (this.stageCompletedListener) {
- document.removeEventListener('stage:completed', this.stageCompletedListener);
- console.log('🧹 已清理阶段完成事件监听器');
- }
- }
- /**
- * 初始化企微授权(不阻塞页面)
- */
- async initWxworkAuth() {
- try {
- let cid = this.cid || localStorage.getItem("company") || "";
-
- // 如果没有cid,记录警告但不抛出错误
- if (!cid) {
- console.warn('⚠️ 未找到company ID (cid),企微功能将不可用');
- return;
- }
-
- this.wxAuth = new WxworkAuth({ cid: cid });
- this.wxwork = new WxworkSDK({ cid: cid, appId: 'crm' });
- this.wecorp = new WxworkCorp(cid);
-
- console.log('✅ 企微SDK初始化成功,cid:', cid);
- } catch (error) {
- console.error('❌ 企微SDK初始化失败:', error);
- // 不阻塞页面加载
- }
- }
- /**
- * 折叠/展开 项目基本信息
- */
- toggleProjectInfo(): void {
- this.showProjectInfoCollapsed = !this.showProjectInfoCollapsed;
- }
- /**
- * 跳转到指定阶段(程序化跳转,用于阶段推进)
- */
- goToStage(stageId: 'order'|'requirements'|'delivery'|'aftercare') {
- console.log('🚀 [goToStage] 开始导航', {
- 目标阶段: stageId,
- 当前路由: this.router.url,
- cid: this.cid,
- projectId: this.projectId
- });
-
- // 更新本地状态
- this.currentStage = stageId;
-
- // 优先使用绝对路径导航(更可靠)
- if (this.cid && this.projectId) {
- console.log('🚀 [goToStage] 使用绝对路径导航');
- this.router.navigate(['/wxwork', this.cid, 'project', this.projectId, stageId])
- .then(success => {
- if (success) {
- console.log('✅ [goToStage] 导航成功:', stageId);
- }
- })
- .catch(err => {
- console.error('❌ [goToStage] 导航出错:', err);
- });
- } else {
- console.warn('⚠️ [goToStage] 缺少参数,使用相对路径', {
- cid: this.cid,
- projectId: this.projectId
- });
-
- // 降级:使用相对路径(直接切换子路由)
- this.router.navigate([stageId], { relativeTo: this.route })
- .then(success => {
- if (success) {
- console.log('✅ [goToStage] 相对路径导航成功');
- } else {
- console.error('❌ [goToStage] 相对路径导航失败');
- }
- })
- .catch(err => {
- console.error('❌ [goToStage] 相对路径导航出错:', err);
- });
- }
- }
- /**
- * 从给定阶段推进到下一个阶段
- */
- async advanceToNextStage(current: string) {
- console.log('🚀 [推进阶段] 开始', { current });
-
- const order = ['order','requirements','delivery','aftercare'];
- const idx = order.indexOf(current);
-
- console.log('🚀 [推进阶段] 阶段索引:', { current, idx });
-
- if (idx === -1) {
- console.error('❌ [推进阶段] 未找到当前阶段:', current);
- return;
- }
-
- if (idx >= order.length - 1) {
- console.log('✅ [推进阶段] 已到达最后阶段');
- window?.fmode?.alert('所有阶段已完成!');
- return;
- }
-
- const next = order[idx + 1];
- console.log('➡️ [推进阶段] 下一阶段:', next);
- // 持久化:标记当前阶段完成并设置下一阶段为当前
- console.log('💾 [推进阶段] 开始持久化');
- await this.persistStageProgress(current, next);
- console.log('✅ [推进阶段] 持久化完成');
- // 导航到下一阶段
- console.log('🚀 [推进阶段] 开始导航到:', next);
- this.goToStage(next as any);
-
- const nextStageName = this.stages.find(s => s.id === next)?.name || next;
- window?.fmode?.alert(`已自动跳转到下一阶段: ${nextStageName}`);
- console.log('✅ [推进阶段] 完成');
- }
- /**
- * 确保存在工作流当前阶段。如缺失则根据完成记录计算
- */
- ensureWorkflowStage() {
- if (!this.project) return;
- const order = ['order','requirements','delivery','aftercare'];
- const data = this.project.get('data') || {};
- const statuses = data.stageStatuses || {};
- let current = this.project.get('currentStage');
- if (!current) {
- // 找到第一个未完成的阶段
- current = order.find(s => statuses[s] !== 'completed') || 'aftercare';
- this.project.set('currentStage', current);
- }
- }
- /**
- * 持久化阶段推进(标记当前完成、设置下一阶段)
- */
- private async persistStageProgress(current: string, next: string) {
- if (!this.project) {
- console.warn('⚠️ 项目对象不存在,无法持久化');
- return;
- }
-
- console.log('💾 开始持久化阶段:', { current, next });
-
- const data = this.project.get('data') || {};
- data.stageStatuses = data.stageStatuses || {};
- data.stageStatuses[current] = 'completed';
- this.project.set('data', data);
-
- // 🔥 关键修复:将英文阶段ID映射为中文阶段名称
- const stageNameMap: Record<string, string> = {
- 'order': '订单分配',
- 'requirements': '确认需求',
- 'delivery': '白模', // 交付执行的第一个子阶段
- 'aftercare': '尾款结算'
- };
-
- const chineseStageName = stageNameMap[next] || next;
- this.project.set('currentStage', chineseStageName);
-
- console.log('💾 设置阶段状态:', {
- currentStage: chineseStageName,
- stageStatuses: data.stageStatuses
- });
-
- try {
- await this.project.save();
- console.log('✅ 阶段状态持久化成功');
- } catch (e) {
- console.warn('⚠️ 阶段状态持久化失败(忽略以保证流程可继续):', e);
- }
- }
- /**
- * 加载数据
- */
- async loadData() {
- try {
- this.loading = true;
- // 2. 获取当前用户(优先从全局服务获取)
- if (!this.currentUser?.id && this.wxAuth) {
- try {
- this.currentUser = await this.wxAuth.currentProfile();
- } catch (error) {
- console.warn('⚠️ 获取当前用户Profile失败:', error);
- }
- }
- // 设置权限
- this.role = this.currentUser?.get('roleName') || '';
- this.canEdit = ['客服', '组员', '组长', '管理员', '设计师', '客服主管'].includes(this.role);
- this.canViewCustomerPhone = ['客服', '组长', '管理员'].includes(this.role);
- const companyId = this.currentUser?.get('company')?.id || localStorage?.getItem("company");
-
- // 3. 加载项目
- // 🔥 关键修改:每次都重新加载项目数据,确保获取最新的停滞期/改图期状态
- if (this.projectId) {
- // 通过 projectId 加载(从后台进入)
- const query = new Parse.Query('Project');
- query.include('contact', 'assignee','department','department.leader');
- this.project = await query.get(this.projectId);
- console.log('🔄 [项目数据] 已从服务器重新加载,停滞期状态:', this.project?.get('data')?.isStalled, '改图期状态:', this.project?.get('data')?.isModification);
- } else if (this.chatId) {
- // 通过 chat_id 查找项目(从企微群聊进入)
- if (companyId) {
- // 先查找 GroupChat
- const gcQuery = new Parse.Query('GroupChat');
- gcQuery.equalTo('chat_id', this.chatId);
- gcQuery.equalTo('company', companyId);
- let groupChat = await gcQuery.first();
- if (groupChat) {
- this.groupChat = groupChat;
- const projectPointer = groupChat.get('project');
- if (projectPointer) {
- const pQuery = new Parse.Query('Project');
- pQuery.include('contact', 'assignee','department','department.leader');
- // 🔥 强制从服务器获取最新数据(确保停滞期/改图期状态实时更新)
- this.project = await pQuery.get(projectPointer.id);
- }
- }
- if (!this.project) {
- throw new Error('该群聊尚未关联项目,请先在后台创建项目');
- }
- }
- }
-
- if(!this.groupChat?.id){
- const gcQuery2 = new Parse.Query('GroupChat');
- gcQuery2.equalTo('project', this.projectId);
- gcQuery2.equalTo('company', companyId);
- this.groupChat = await gcQuery2.first();
- }
- this.wxwork?.syncGroupChat(this.groupChat?.toJSON())
- if (!this.project) {
- throw new Error('无法加载项目信息');
- }
- this.contact = this.project.get('contact');
- this.assignee = this.project.get('assignee');
- // 加载问卷状态
- await this.loadSurveyStatus();
- // 更新问题计数
- try {
- if (this.project?.id) {
- this.issueService.seed(this.project.id!);
- const counts = this.issueService.getCounts(this.project.id!);
- this.issueCount = counts.total;
- }
- } catch (e) {
- console.warn('统计问题数量失败:', e);
- }
- // 4. 加载群聊(如果没有传入且有groupId)
- if (!this.groupChat && this.groupId) {
- try {
- const gcQuery = new Parse.Query('GroupChat');
- this.groupChat = await gcQuery.get(this.groupId);
- } catch (err) {
- console.warn('加载群聊失败:', err);
- }
- }
- // 5. 【已禁用】验证项目阶段 - 只显示警告,不自动回退
- // ⚠️ 原因:自动回退会覆盖组长审批通过后的阶段推进,导致反复回退
- let projectStage = this.project.get('currentStage');
- const data = this.project.get('data') || {};
-
- console.log('🔍 [项目详情] 当前项目阶段:', projectStage);
- console.log('🔍 [项目详情] 项目数据:', {
- title: this.project.get('title'),
- projectType: this.project.get('projectType'),
- demoday: this.project.get('demoday'),
- quotationTotal: data.quotation?.total,
- approvalStatus: data.approvalStatus,
- approvalHistory: data.approvalHistory,
- requirementsAnalysis: !!data.requirementsAnalysis,
- spaceRequirements: !!data.spaceRequirements
- });
-
- // ⚠️ 【已禁用】自动回退检查 - 改为只记录警告
- let needRollback = false;
- let correctStage = projectStage;
- let rollbackReason = '';
-
- // 【已禁用】检查1:订单分配阶段完成情况 - 只记录警告,不回退
- if (projectStage && ['确认需求', '方案确认', '方案深化', '交付执行', '白模', '软装', '渲染', '后期', '建模', '尾款结算', '客户评价', '投诉处理', '售后归档'].includes(projectStage)) {
- const title = this.project.get('title');
- const projectType = this.project.get('projectType');
- const demoday = this.project.get('demoday');
- const quotationTotal = data.quotation?.total || 0;
- const approvalStatus = data.approvalStatus;
-
- // 检查订单分配阶段是否完成
- const orderStageIncomplete = !title || !projectType || !demoday || quotationTotal <= 0;
-
- // ✅ 智能判断审批状态:检查审批历史
- const hasApprovedHistory = data.approvalHistory?.some((h: any) =>
- h.stage === '订单分配' && h.status === 'approved'
- );
-
- const notApproved = approvalStatus !== 'approved' && !hasApprovedHistory;
-
- // ⚠️ 【已禁用回退】只记录警告,不执行回退
- if (orderStageIncomplete || notApproved) {
- const reasons = [];
- if (!title) reasons.push('缺少项目名称');
- if (!projectType) reasons.push('缺少项目类型');
- if (!demoday) reasons.push('缺少小图日期');
- if (quotationTotal <= 0) reasons.push('缺少报价数据');
- if (notApproved) reasons.push('待组长审批');
-
- console.warn('⚠️ [数据警告] 订单分配阶段数据不完整,但不执行回退:', {
- currentStage: projectStage,
- 缺失项: reasons,
- approvalStatus,
- hasApprovedHistory
- });
- } else {
- console.log('✅ [数据验证] 订单分配阶段数据完整');
- }
- }
-
- // 【已禁用】检查2:确认需求阶段完成情况 - 只记录警告,不回退
- if (projectStage && ['交付执行', '白模', '软装', '渲染', '后期', '建模', '尾款结算', '客户评价', '投诉处理', '售后归档'].includes(projectStage)) {
- const hasRequirements = data.requirementsAnalysis || data.spaceRequirements;
-
- if (!hasRequirements) {
- console.warn('⚠️ [数据警告] 确认需求阶段数据不完整,但不执行回退:', {
- currentStage: projectStage,
- hasRequirementsAnalysis: !!data.requirementsAnalysis,
- hasSpaceRequirements: !!data.spaceRequirements
- });
- } else {
- console.log('✅ [数据验证] 确认需求阶段数据完整');
- }
- }
-
- // 【已禁用】自动回退功能 - 避免覆盖审批通过后的阶段推进
- console.log('ℹ️ [阶段验证] 自动回退功能已禁用,当前阶段:', projectStage);
-
- // 映射到路由ID
- const stageMap: any = {
- '订单分配': 'order',
- '确认需求': 'requirements',
- '方案确认': 'requirements',
- '方案深化': 'requirements',
- '交付执行': 'delivery',
- '白模': 'delivery', // 🔥 交付执行子阶段
- '软装': 'delivery',
- '渲染': 'delivery',
- '后期': 'delivery',
- '建模': 'delivery',
- '尾款结算': 'aftercare',
- '客户评价': 'aftercare',
- '投诉处理': 'aftercare'
- };
- const targetStage = stageMap[projectStage] || 'order';
- console.log('🎯 [项目详情] 目标路由阶段:', targetStage);
- // 🔥 修复:始终导航到正确的阶段,即使已有子路由
- const currentChildRoute = this.route.firstChild?.snapshot.url[0]?.path;
- console.log('📍 [项目详情] 当前子路由:', currentChildRoute);
-
- if (!currentChildRoute || currentChildRoute !== targetStage) {
- console.log('🚀 [项目详情] 导航到正确阶段:', targetStage);
- this.router.navigate([targetStage], { relativeTo: this.route, replaceUrl: true });
- } else {
- console.log('✅ [项目详情] 已在正确阶段,无需导航');
- }
- } catch (err: any) {
- console.error('加载失败:', err);
- this.error = err.message || '加载失败';
- } finally {
- this.loading = false;
- }
- }
- /**
- * 切换阶段(查看模式)
- * 允许查看所有阶段,但不改变项目的实际阶段(currentStage)
- * 只有通过各阶段的提交按钮(如"确认订单")才能推进项目阶段
- */
- switchStage(stageId: string) {
- console.log('🔄 用户点击切换阶段(查看模式):', stageId, {
- currentRoute: this.router.url,
- currentViewStage: this.currentStage,
- projectActualStage: this.project?.get('currentStage')
- });
-
- // ✅ 允许查看所有阶段(包括未开始的)
- const status = this.getStageStatus(stageId);
- console.log(`✅ 切换到阶段视图: ${stageId} (项目实际状态: ${status})`);
-
- // ⚠️ 如果查看未开始的阶段,给予友好提示
- if (status === 'pending') {
- const stageName = this.stages.find(s => s.id === stageId)?.name || stageId;
- console.warn(`⚠️ 正在查看未开始的阶段: ${stageName}`);
- console.warn(`💡 提示: 这是查看模式,项目实际阶段不会改变`);
- console.warn(`💡 需要完成当前阶段的必填项才能推进到 ${stageName}`);
- }
-
- // 更新本地视图状态(仅影响显示,不影响项目实际阶段)
- this.currentStage = stageId;
-
- // 导航到指定阶段(查看模式)
- this.router.navigate([stageId], { relativeTo: this.route })
- .then(success => {
- if (success) {
- console.log('✅ 导航成功(查看模式):', stageId);
- } else {
- console.warn('⚠️ 导航失败:', stageId);
- }
- })
- .catch(err => {
- console.error('❌ 导航出错:', err);
- });
- }
- /**
- * 获取阶段状态(参考设计师端 getSectionStatus 实现)
- * @returns 'completed' - 已完成(绿色)| 'active' - 当前进行中(红色)| 'pending' - 待开始(灰色)
- */
- getStageStatus(stageId: string): 'completed' | 'active' | 'pending' {
- // 颜色显示仅依据“工作流状态”,不受临时浏览路由影响
- const data = this.project?.get('data') || {};
- const statuses = data.stageStatuses || {};
- let workflowCurrent = this.project?.get('currentStage') || 'order';
-
- // 🔥 关键修复:将中文阶段名称映射为英文ID
- const stageNameToId: Record<string, string> = {
- '订单分配': 'order',
- '确认需求': 'requirements',
- // 设计师阶段(需求阶段)
- '方案深化': 'requirements',
- // 交付执行子阶段统一归为 delivery
- '交付执行': 'delivery',
- '交付': 'delivery',
- '白模': 'delivery',
- '建模': 'delivery',
- '软装': 'delivery',
- '渲染': 'delivery',
- '后期': 'delivery',
- // 售后归档
- '售后归档': 'aftercare',
- '尾款结算': 'aftercare',
- '已完成': 'aftercare'
- };
-
- // 如果是中文名称,转换为英文ID
- if (stageNameToId[workflowCurrent]) {
- workflowCurrent = stageNameToId[workflowCurrent];
- }
- // 如果没有当前阶段(新创建的项目),默认订单分配为active(红色)
- if (!workflowCurrent || workflowCurrent === 'order') {
- return stageId === 'order' ? 'active' : 'pending';
- }
- // 计算阶段索引
- const stageOrder = ['order', 'requirements', 'delivery', 'aftercare'];
- const currentIdx = stageOrder.indexOf(workflowCurrent);
- const idx = stageOrder.indexOf(stageId);
- if (idx === -1 || currentIdx === -1) return 'pending';
- // 已完成的阶段:当前阶段之前的所有阶段(绿色)
- if (idx < currentIdx) return 'completed';
- // 当前进行中的阶段:等于当前阶段(红色)
- if (idx === currentIdx) return 'active';
- // 未开始的阶段:当前阶段之后的所有阶段(灰色)
- return 'pending';
- }
- /**
- * 返回
- */
- goBack() {
- let ua = navigator.userAgent.toLowerCase();
- let isWeixin = ua.indexOf("micromessenger") != -1;
- if(isWeixin){
- this.router.navigate(['/wxwork', this.cid, 'project-loader']);
- }else{
- history.back();
- }
- }
- /**
- * 更新项目阶段
- */
- async updateProjectStage(stage: string) {
- if (!this.project || !this.canEdit) return;
- try {
- this.project.set('currentStage', stage);
- await this.project.save();
- // 添加阶段历史
- const data = this.project.get('data') || {};
- const stageHistory = data.stageHistory || [];
- stageHistory.push({
- stage,
- startTime: new Date(),
- status: 'current',
- operator: {
- id: this.currentUser!.id,
- name: this.currentUser!.get('name'),
- role: this.role
- }
- });
- this.project.set('data', { ...data, stageHistory });
- await this.project.save();
- } catch (err) {
- console.error('更新阶段失败:', err);
- window?.fmode?.alert('更新失败');
- }
- }
- /**
- * 发送企微消息
- */
- async sendWxMessage(message: string) {
- if (!this.groupChat || !this.wecorp) return;
- try {
- const chatId = this.groupChat.get('chat_id');
- await this.wecorp.appchat.sendText(chatId, message);
- } catch (err) {
- console.error('发送消息失败:', err);
- }
- }
- /**
- * 选择客户(从群聊成员中选择外部联系人)
- */
- async selectCustomer() {
- console.log(this.canEdit, this.groupChat)
- if (!this.groupChat) return;
- try {
- const memberList = this.groupChat.get('member_list') || [];
- const externalMembers = memberList.filter((m: any) => m.type === 2);
- if (externalMembers.length === 0) {
- window?.fmode?.alert('当前群聊中没有外部联系人');
- return;
- }
- console.log(externalMembers)
- // 简单实现:选择第一个外部联系人
- // TODO: 实现选择器UI
- const selectedMember = externalMembers[0];
- await this.setCustomerFromMember(selectedMember);
- } catch (err) {
- console.error('选择客户失败:', err);
- window?.fmode?.alert('选择客户失败');
- }
- }
- /**
- * 从群成员设置客户
- */
- async setCustomerFromMember(member: any) {
- if (!this.wecorp) return;
- try {
- const companyId = this.currentUser?.get('company')?.id || localStorage.getItem("company");
- if (!companyId) throw new Error('无法获取企业信息');
- // 1. 查询是否已存在 ContactInfo
- const query = new Parse.Query('ContactInfo');
- query.equalTo('external_userid', member.userid);
- query.equalTo('company', companyId);
- let contactInfo = await query.first();
- // 2. 如果不存在,通过企微API获取并创建
- if (!contactInfo) {
- contactInfo = new Parse.Object("ContactInfo");
- }
- const externalContactData = await this.wecorp.externalContact.get(member.userid);
- console.log("externalContactData",externalContactData)
- const ContactInfo = Parse.Object.extend('ContactInfo');
- contactInfo.set('name', externalContactData.name);
- contactInfo.set('external_userid', member.userid);
- const company = new Parse.Object('Company');
- company.id = companyId;
- const companyPointer = company.toPointer();
- contactInfo.set('company', companyPointer);
- contactInfo.set('data', externalContactData);
- await contactInfo.save();
- // 3. 设置为项目客户
- if (this.project) {
- this.project.set('contact', contactInfo.toPointer());
- await this.project.save();
- this.contact = contactInfo;
- window?.fmode?.alert('客户设置成功');
- }
- } catch (err) {
- console.error('设置客户失败:', err);
- throw err;
- }
- }
- /**
- * 显示文件模态框
- */
- showFiles() {
- this.showFilesModal = true;
- }
- /**
- * 显示成员模态框
- */
- showMembers() {
- this.showMembersModal = true;
- }
- /** 显示问题模态框 */
- showIssues() {
- this.showIssuesModal = true;
- }
- /**
- * 关闭文件模态框
- */
- closeFilesModal() {
- this.showFilesModal = false;
- }
- /**
- * 关闭成员模态框
- */
- closeMembersModal() {
- this.showMembersModal = false;
- }
- /** 显示客户详情面板 */
- openContactPanel() {
- if (this.contact) {
- this.showContactPanel = true;
- }
- }
- /** 关闭客户详情面板 */
- closeContactPanel() {
- this.showContactPanel = false;
- }
- /** 关闭问题模态框 */
- closeIssuesModal() {
- this.showIssuesModal = false;
- if (this.project?.id) {
- const counts = this.issueService.getCounts(this.project.id!);
- this.issueCount = counts.total;
- }
- }
- /** 客户选择事件回调(接收子组件输出) */
- onContactSelected(evt: { contact: FmodeObject; isNewCustomer: boolean; action: 'selected' | 'created' | 'updated' }) {
- this.contact = evt.contact;
- // 重新加载问卷状态
- this.loadSurveyStatus();
- }
- /**
- * 加载问卷状态
- */
- async loadSurveyStatus() {
- if (!this.project?.id) return;
- try {
- const query = new Parse.Query('SurveyLog');
- query.equalTo('project', this.project.toPointer());
- query.equalTo('type', 'survey-project');
- query.equalTo('isCompleted', true);
- query.include("contact")
- const surveyLog = await query.first();
- if (surveyLog) {
- this.surveyStatus = {
- filled: true,
- text: '查看问卷',
- icon: 'checkmark-circle',
- surveyLog,
- contact:surveyLog?.get("contact")
- };
- console.log('✅ 问卷已填写');
- } else {
- this.surveyStatus = {
- filled: false,
- text: '发送问卷',
- icon: 'document-text-outline'
- };
- console.log('✅ 问卷未填写');
- }
- } catch (err) {
- console.error('❌ 查询问卷状态失败:', err);
- }
- }
- /**
- * 发送问卷
- */
- async sendSurvey() {
- if (!this.groupChat || !this.wxwork) {
- window?.fmode?.alert('无法发送问卷:未找到群聊或企微SDK未初始化');
- return;
- }
- try {
- const chatId = this.groupChat.get('chat_id');
- const surveyUrl = `${document.baseURI}/wxwork/${this.cid}/survey/project/${this.project?.id}`;
- await this.wxwork.ww.openExistedChatWithMsg({
- chatId: chatId,
- msg: {
- msgtype: 'link',
- link: {
- title: '《家装效果图服务需求调查表》',
- desc: '为让本次服务更贴合您的需求,请花3-5分钟填写简短问卷,感谢支持!',
- url: surveyUrl,
- imgUrl: `${document.baseURI}/assets/logo.jpg`
- }
- }
- });
- window?.fmode?.alert('问卷已发送到群聊!');
- } catch (err) {
- console.error('❌ 发送问卷失败:', err);
- window?.fmode?.alert('发送失败,请重试');
- }
- }
- /**
- * 查看问卷结果
- */
- async viewSurvey() {
- if (!this.surveyStatus.surveyLog) return;
- // 跳转到问卷页面查看结果
- this.router.navigate(['/wxwork', this.cid, 'survey', 'project', this.project?.id]);
- }
- /**
- * 处理问卷点击
- */
- async handleSurveyClick(event: Event) {
- event.stopPropagation();
- if (this.surveyStatus.filled) {
- // 已填写,查看结果
- await this.viewSurvey();
- } else {
- // 未填写,发送问卷
- await this.sendSurvey();
- }
- }
- /**
- * 是否显示审批面板
- * 条件:当前用户是组长 + 项目处于订单分配阶段 + 审批状态为待审批
- */
- get showApprovalPanel(): boolean {
- if (!this.project || !this.currentUser) {
- console.log('🔍 审批面板检查: 缺少项目或用户数据');
- return false;
- }
-
- const userRole = this.currentUser.get('roleName') || '';
- // ✅ 恢复正确的角色检查:只有组长才能看到审批面板
- const isTeamLeader = userRole === '设计组长' || userRole === 'team-leader' || userRole === '组长';
-
- const currentStage = this.project.get('currentStage') || '';
- const isOrderStage = currentStage === '订单分配' || currentStage === 'order';
-
- const data = this.project.get('data') || {};
- const approvalStatus = data.approvalStatus;
- const isPending = approvalStatus === 'pending';
-
- // console.log('🔍 审批面板检查:', {
- // userRole,
- // isTeamLeader,
- // currentStage,
- // isOrderStage,
- // approvalStatus,
- // isPending,
- // result: isTeamLeader && isOrderStage && isPending
- // });
-
- return isTeamLeader && isOrderStage && isPending;
- }
- /**
- * 处理审批完成事件
- */
- async onApprovalCompleted(event: any) {
- if (!this.project) return;
- try {
- const data = this.project.get('data') || {};
- const approvalHistory = data.approvalHistory || [];
- const latestRecord = approvalHistory[approvalHistory.length - 1];
- if (latestRecord) {
- latestRecord.status = event.action;
- latestRecord.approver = {
- id: this.currentUser?.id,
- name: this.currentUser?.get('name'),
- role: this.currentUser?.get('roleName')
- };
- latestRecord.approvalTime = new Date();
- latestRecord.comment = event.comment;
- latestRecord.reason = event.reason;
- }
- if (event.action === 'approved') {
- // 通过审批:推进到确认需求阶段
- data.approvalStatus = 'approved';
- this.project.set('currentStage', '确认需求');
- this.project.set('data', data);
- await this.project.save();
-
- alert('✅ 审批通过,项目已进入确认需求阶段');
-
- // 刷新页面数据
- await this.loadData();
- } else {
- // 驳回:保持在订单分配阶段,记录驳回原因
- data.approvalStatus = 'rejected';
- data.lastRejectionReason = event.reason || '未提供原因';
- this.project.set('data', data);
- await this.project.save();
-
- alert('✅ 已驳回订单,客服将收到通知');
-
- // 刷新页面数据
- await this.loadData();
- }
- } catch (err) {
- console.error('处理审批失败:', err);
- alert('审批操作失败,请重试');
- }
- }
- /**
- * 取消停滞期标记
- */
- async cancelStagnation(event?: Event) {
- // 阻止事件冒泡
- if (event) {
- event.stopPropagation();
- event.preventDefault();
- }
-
- if (!this.project) {
- console.warn('❌ 项目数据不存在');
- return;
- }
- // 确认对话框
- const confirmed = confirm('确定要取消该项目的停滞期状态吗?');
- if (!confirmed) return;
- try {
- console.log('🔄 [取消停滞期] 开始取消...');
-
- const data = this.project.get('data') || {};
-
- // 清除停滞期相关字段
- data.isStalled = false;
- delete data.stagnationReasonType;
- delete data.stagnationCustomReason;
- delete data.estimatedResumeDate;
- delete data.reasonNotes;
- delete data.markedAt;
- delete data.markedBy;
-
- this.project.set('data', data);
- await this.project.save();
-
- console.log('✅ 停滞期标记已取消');
- window?.fmode?.alert('停滞期标记已取消');
-
- // 刷新页面数据
- await this.loadData();
- } catch (err) {
- console.error('❌ 取消停滞期失败:', err);
- window?.fmode?.alert('操作失败,请重试');
- }
- }
- /**
- * 取消改图期标记(由上传文件后自动触发)
- */
- async cancelModification() {
- if (!this.project) return;
- try {
- const data = this.project.get('data') || {};
-
- // 清除改图期相关字段
- data.isModification = false;
- data.modificationReasonType = undefined;
- data.modificationCustomReason = undefined;
- data.reasonNotes = undefined;
- data.markedAt = undefined;
- data.markedBy = undefined;
-
- this.project.set('data', data);
- await this.project.save();
-
- console.log('✅ 改图期标记已自动取消');
-
- // 刷新页面数据
- await this.loadData();
- } catch (err) {
- console.error('❌ 取消改图期失败:', err);
- }
- }
- /**
- * 获取停滞/改图原因的显示文本
- */
- getReasonText(type: 'stagnation' | 'modification'): string {
- const info = type === 'stagnation' ? this.stagnationInfo : this.modificationInfo;
-
- if (!info.reasonType) return '';
-
- const reasonMap: Record<string, string> = {
- 'designer': '设计师原因',
- 'customer': '客户原因',
- 'custom': info.customReason || '其他原因'
- };
-
- return reasonMap[info.reasonType] || '';
- }
- }
- // duplicate inline CustomerSelectorComponent removed (we keep single declaration above)
|