project-detail.component.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. import { Component, OnInit, Input, Output, EventEmitter, OnDestroy } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { Router, ActivatedRoute, RouterModule } from '@angular/router';
  4. import { IonicModule } from '@ionic/angular';
  5. import { WxworkSDK, WxworkCorp, WxworkAuth } from 'fmode-ng/core';
  6. import { FmodeParse, FmodeObject } from 'fmode-ng/parse';
  7. import { ProfileService } from '../../../../app/services/profile.service';
  8. import { ProjectBottomCardComponent } from '../../components/project-bottom-card/project-bottom-card.component';
  9. import { ProjectFilesModalComponent } from '../../components/project-files-modal/project-files-modal.component';
  10. import { ProjectMembersModalComponent } from '../../components/project-members-modal/project-members-modal.component';
  11. import { ProjectIssuesModalComponent } from '../../components/project-issues-modal/project-issues-modal.component';
  12. import { ProjectIssueService } from '../../services/project-issue.service';
  13. import { FormsModule } from '@angular/forms';
  14. import { CustomerSelectorComponent } from '../../components/contact-selector/contact-selector.component';
  15. import { OrderApprovalPanelComponent } from '../../../../app/shared/components/order-approval-panel/order-approval-panel.component';
  16. import { GroupChatSummaryComponent } from '../../components/group-chat-summary/group-chat-summary.component';
  17. const Parse = FmodeParse.with('nova');
  18. /**
  19. * 项目详情核心组件
  20. *
  21. * 功能:
  22. * 1. 展示四阶段导航(订单分配、确认需求、交付执行、售后归档)
  23. * 2. 根据角色控制权限
  24. * 3. 子路由切换阶段内容
  25. * 4. 支持@Input和路由参数两种数据加载方式
  26. *
  27. * 路由:/wxwork/:cid/project/:projectId
  28. */
  29. @Component({
  30. selector: 'app-project-detail',
  31. standalone: true,
  32. imports: [
  33. CommonModule,
  34. IonicModule,
  35. RouterModule,
  36. ProjectBottomCardComponent,
  37. ProjectFilesModalComponent,
  38. ProjectMembersModalComponent,
  39. ProjectIssuesModalComponent,
  40. CustomerSelectorComponent,
  41. OrderApprovalPanelComponent,
  42. GroupChatSummaryComponent
  43. ],
  44. templateUrl: './project-detail.component.html',
  45. styleUrls: ['./project-detail.component.scss']
  46. })
  47. export class ProjectDetailComponent implements OnInit, OnDestroy {
  48. // 输入参数(支持组件复用)
  49. @Input() project: FmodeObject | null = null;
  50. @Input() groupChat: FmodeObject | null = null;
  51. @Input() currentUser: FmodeObject | null = null;
  52. // 问题统计
  53. issueCount: number = 0;
  54. // 路由参数
  55. cid: string = '';
  56. projectId: string = '';
  57. groupId: string = '';
  58. profileId: string = '';
  59. chatId: string = ''; // 从企微进入时的 chat_id
  60. // 企微SDK
  61. wxwork: WxworkSDK | null = null;
  62. wecorp: WxworkCorp | null = null;
  63. wxAuth: WxworkAuth | null = null; // WxworkAuth 实例
  64. // 加载状态
  65. loading: boolean = true;
  66. error: string | null = null;
  67. // 项目数据
  68. contact: FmodeObject | null = null;
  69. assignee: FmodeObject | null = null;
  70. // 当前阶段
  71. currentStage: string = 'order'; // order | requirements | delivery | aftercare
  72. stages = [
  73. { id: 'order', name: '订单分配', icon: 'document-text-outline', number: 1 },
  74. { id: 'requirements', name: '确认需求', icon: 'checkmark-circle-outline', number: 2 },
  75. { id: 'delivery', name: '交付执行', icon: 'rocket-outline', number: 3 },
  76. { id: 'aftercare', name: '售后归档', icon: 'archive-outline', number: 4 }
  77. ];
  78. // 权限
  79. canEdit: boolean = false;
  80. canViewCustomerPhone: boolean = false;
  81. role: string = '';
  82. // 模态框状态
  83. showFilesModal: boolean = false;
  84. showMembersModal: boolean = false;
  85. showIssuesModal: boolean = false;
  86. // 新增:客户详情侧栏面板状态
  87. showContactPanel: boolean = false;
  88. // 问卷状态
  89. surveyStatus: {
  90. filled: boolean;
  91. text: string;
  92. icon: string;
  93. surveyLog?: FmodeObject;
  94. contact?: FmodeObject;
  95. } = {
  96. filled: false,
  97. text: '发送问卷',
  98. icon: 'document-text-outline'
  99. };
  100. // 折叠:项目基本信息
  101. showProjectInfoCollapsed: boolean = true;
  102. // 事件监听器引用
  103. private stageCompletedListener: any = null;
  104. constructor(
  105. private router: Router,
  106. private route: ActivatedRoute,
  107. private profileService: ProfileService,
  108. private issueService: ProjectIssueService
  109. ) {}
  110. async ngOnInit() {
  111. // 获取路由参数
  112. this.cid = this.route.snapshot.paramMap.get('cid') || '';
  113. // 兼容:cid 在父级路由上
  114. if (!this.cid) {
  115. this.cid = this.route.parent?.snapshot.paramMap.get('cid') || '';
  116. }
  117. // 降级:从 localStorage 读取
  118. if (!this.cid) {
  119. this.cid = localStorage.getItem('company') || '';
  120. }
  121. this.projectId = this.route.snapshot.paramMap.get('projectId') || '';
  122. this.groupId = this.route.snapshot.queryParamMap.get('groupId') || '';
  123. this.profileId = this.route.snapshot.queryParamMap.get('profileId') || '';
  124. this.chatId = this.route.snapshot.queryParamMap.get('chatId') || '';
  125. console.log('📌 路由参数:', {
  126. cid: this.cid,
  127. projectId: this.projectId
  128. });
  129. // 监听路由变化
  130. this.route.firstChild?.url.subscribe((segments) => {
  131. if (segments.length > 0) {
  132. this.currentStage = segments[0].path;
  133. console.log('🔄 当前阶段已更新:', this.currentStage);
  134. }
  135. });
  136. // 初始化企微授权(不阻塞页面加载)
  137. await this.initWxworkAuth();
  138. await this.loadData();
  139. // 初始化工作流阶段(若缺失则根据已完成记录推断)
  140. this.ensureWorkflowStage();
  141. // 监听各阶段完成事件,自动推进到下一环节
  142. this.stageCompletedListener = async (e: any) => {
  143. console.log('🎯 [监听器] 事件触发', e?.detail);
  144. const stageId = e?.detail?.stage as string;
  145. if (!stageId) {
  146. console.error('❌ [监听器] 事件缺少 stage 参数');
  147. return;
  148. }
  149. console.log('✅ [监听器] 接收到阶段完成事件:', stageId);
  150. await this.advanceToNextStage(stageId);
  151. };
  152. console.log('📡 [初始化] 注册事件监听器: stage:completed');
  153. document.addEventListener('stage:completed', this.stageCompletedListener);
  154. console.log('✅ [初始化] 事件监听器注册成功');
  155. }
  156. /**
  157. * 组件销毁时清理事件监听器
  158. */
  159. ngOnDestroy() {
  160. if (this.stageCompletedListener) {
  161. document.removeEventListener('stage:completed', this.stageCompletedListener);
  162. console.log('🧹 已清理阶段完成事件监听器');
  163. }
  164. }
  165. /**
  166. * 初始化企微授权(不阻塞页面)
  167. */
  168. async initWxworkAuth() {
  169. try {
  170. let cid = this.cid || localStorage.getItem("company") || "";
  171. // 如果没有cid,记录警告但不抛出错误
  172. if (!cid) {
  173. console.warn('⚠️ 未找到company ID (cid),企微功能将不可用');
  174. return;
  175. }
  176. this.wxAuth = new WxworkAuth({ cid: cid });
  177. this.wxwork = new WxworkSDK({ cid: cid, appId: 'crm' });
  178. this.wecorp = new WxworkCorp(cid);
  179. console.log('✅ 企微SDK初始化成功,cid:', cid);
  180. } catch (error) {
  181. console.error('❌ 企微SDK初始化失败:', error);
  182. // 不阻塞页面加载
  183. }
  184. }
  185. /**
  186. * 折叠/展开 项目基本信息
  187. */
  188. toggleProjectInfo(): void {
  189. this.showProjectInfoCollapsed = !this.showProjectInfoCollapsed;
  190. }
  191. /**
  192. * 跳转到指定阶段(程序化跳转,用于阶段推进)
  193. */
  194. goToStage(stageId: 'order'|'requirements'|'delivery'|'aftercare') {
  195. console.log('🚀 [goToStage] 开始导航', {
  196. 目标阶段: stageId,
  197. 当前路由: this.router.url,
  198. cid: this.cid,
  199. projectId: this.projectId
  200. });
  201. // 更新本地状态
  202. this.currentStage = stageId;
  203. // 优先使用绝对路径导航(更可靠)
  204. if (this.cid && this.projectId) {
  205. console.log('🚀 [goToStage] 使用绝对路径导航');
  206. this.router.navigate(['/wxwork', this.cid, 'project', this.projectId, stageId])
  207. .then(success => {
  208. if (success) {
  209. console.log('✅ [goToStage] 导航成功:', stageId);
  210. }
  211. })
  212. .catch(err => {
  213. console.error('❌ [goToStage] 导航出错:', err);
  214. });
  215. } else {
  216. console.warn('⚠️ [goToStage] 缺少参数,使用相对路径', {
  217. cid: this.cid,
  218. projectId: this.projectId
  219. });
  220. // 降级:使用相对路径(直接切换子路由)
  221. this.router.navigate([stageId], { relativeTo: this.route })
  222. .then(success => {
  223. if (success) {
  224. console.log('✅ [goToStage] 相对路径导航成功');
  225. } else {
  226. console.error('❌ [goToStage] 相对路径导航失败');
  227. }
  228. })
  229. .catch(err => {
  230. console.error('❌ [goToStage] 相对路径导航出错:', err);
  231. });
  232. }
  233. }
  234. /**
  235. * 从给定阶段推进到下一个阶段
  236. */
  237. async advanceToNextStage(current: string) {
  238. console.log('🚀 [推进阶段] 开始', { current });
  239. const order = ['order','requirements','delivery','aftercare'];
  240. const idx = order.indexOf(current);
  241. console.log('🚀 [推进阶段] 阶段索引:', { current, idx });
  242. if (idx === -1) {
  243. console.error('❌ [推进阶段] 未找到当前阶段:', current);
  244. return;
  245. }
  246. if (idx >= order.length - 1) {
  247. console.log('✅ [推进阶段] 已到达最后阶段');
  248. window?.fmode?.alert('所有阶段已完成!');
  249. return;
  250. }
  251. const next = order[idx + 1];
  252. console.log('➡️ [推进阶段] 下一阶段:', next);
  253. // 持久化:标记当前阶段完成并设置下一阶段为当前
  254. console.log('💾 [推进阶段] 开始持久化');
  255. await this.persistStageProgress(current, next);
  256. console.log('✅ [推进阶段] 持久化完成');
  257. // 导航到下一阶段
  258. console.log('🚀 [推进阶段] 开始导航到:', next);
  259. this.goToStage(next as any);
  260. const nextStageName = this.stages.find(s => s.id === next)?.name || next;
  261. window?.fmode?.alert(`已自动跳转到下一阶段: ${nextStageName}`);
  262. console.log('✅ [推进阶段] 完成');
  263. }
  264. /**
  265. * 确保存在工作流当前阶段。如缺失则根据完成记录计算
  266. */
  267. ensureWorkflowStage() {
  268. if (!this.project) return;
  269. const order = ['order','requirements','delivery','aftercare'];
  270. const data = this.project.get('data') || {};
  271. const statuses = data.stageStatuses || {};
  272. let current = this.project.get('currentStage');
  273. if (!current) {
  274. // 找到第一个未完成的阶段
  275. current = order.find(s => statuses[s] !== 'completed') || 'aftercare';
  276. this.project.set('currentStage', current);
  277. }
  278. }
  279. /**
  280. * 持久化阶段推进(标记当前完成、设置下一阶段)
  281. */
  282. private async persistStageProgress(current: string, next: string) {
  283. if (!this.project) {
  284. console.warn('⚠️ 项目对象不存在,无法持久化');
  285. return;
  286. }
  287. console.log('💾 开始持久化阶段:', { current, next });
  288. const data = this.project.get('data') || {};
  289. data.stageStatuses = data.stageStatuses || {};
  290. data.stageStatuses[current] = 'completed';
  291. this.project.set('data', data);
  292. this.project.set('currentStage', next);
  293. console.log('💾 设置阶段状态:', {
  294. currentStage: next,
  295. stageStatuses: data.stageStatuses
  296. });
  297. try {
  298. await this.project.save();
  299. console.log('✅ 阶段状态持久化成功');
  300. } catch (e) {
  301. console.warn('⚠️ 阶段状态持久化失败(忽略以保证流程可继续):', e);
  302. }
  303. }
  304. /**
  305. * 加载数据
  306. */
  307. async loadData() {
  308. try {
  309. this.loading = true;
  310. // 2. 获取当前用户(优先从全局服务获取)
  311. if (!this.currentUser?.id && this.wxAuth) {
  312. try {
  313. this.currentUser = await this.wxAuth.currentProfile();
  314. } catch (error) {
  315. console.warn('⚠️ 获取当前用户Profile失败:', error);
  316. }
  317. }
  318. // 设置权限
  319. this.role = this.currentUser?.get('roleName') || '';
  320. this.canEdit = ['客服', '组员', '组长', '管理员', '设计师', '客服主管'].includes(this.role);
  321. this.canViewCustomerPhone = ['客服', '组长', '管理员'].includes(this.role);
  322. const companyId = this.currentUser?.get('company')?.id || localStorage?.getItem("company");
  323. // 3. 加载项目
  324. if (!this.project) {
  325. if (this.projectId) {
  326. // 通过 projectId 加载(从后台进入)
  327. const query = new Parse.Query('Project');
  328. query.include('contact', 'assignee','department','department.leader');
  329. this.project = await query.get(this.projectId);
  330. } else if (this.chatId) {
  331. // 通过 chat_id 查找项目(从企微群聊进入)
  332. if (companyId) {
  333. // 先查找 GroupChat
  334. const gcQuery = new Parse.Query('GroupChat');
  335. gcQuery.equalTo('chat_id', this.chatId);
  336. gcQuery.equalTo('company', companyId);
  337. let groupChat = await gcQuery.first();
  338. if (groupChat) {
  339. this.groupChat = groupChat;
  340. const projectPointer = groupChat.get('project');
  341. if (projectPointer) {
  342. const pQuery = new Parse.Query('Project');
  343. pQuery.include('contact', 'assignee','department','department.leader');
  344. this.project = await pQuery.get(projectPointer.id);
  345. }
  346. }
  347. if (!this.project) {
  348. throw new Error('该群聊尚未关联项目,请先在后台创建项目');
  349. }
  350. }
  351. }
  352. }
  353. if(!this.groupChat?.id){
  354. const gcQuery2 = new Parse.Query('GroupChat');
  355. gcQuery2.equalTo('project', this.projectId);
  356. gcQuery2.equalTo('company', companyId);
  357. this.groupChat = await gcQuery2.first();
  358. }
  359. this.wxwork?.syncGroupChat(this.groupChat?.toJSON())
  360. if (!this.project) {
  361. throw new Error('无法加载项目信息');
  362. }
  363. this.contact = this.project.get('contact');
  364. this.assignee = this.project.get('assignee');
  365. // 加载问卷状态
  366. await this.loadSurveyStatus();
  367. // 更新问题计数
  368. try {
  369. if (this.project?.id) {
  370. this.issueService.seed(this.project.id!);
  371. const counts = this.issueService.getCounts(this.project.id!);
  372. this.issueCount = counts.total;
  373. }
  374. } catch (e) {
  375. console.warn('统计问题数量失败:', e);
  376. }
  377. // 4. 加载群聊(如果没有传入且有groupId)
  378. if (!this.groupChat && this.groupId) {
  379. try {
  380. const gcQuery = new Parse.Query('GroupChat');
  381. this.groupChat = await gcQuery.get(this.groupId);
  382. } catch (err) {
  383. console.warn('加载群聊失败:', err);
  384. }
  385. }
  386. // 5. 根据项目当前阶段设置默认路由
  387. const projectStage = this.project.get('currentStage');
  388. const stageMap: any = {
  389. '订单分配': 'order',
  390. '确认需求': 'requirements',
  391. '方案确认': 'requirements',
  392. '方案深化': 'requirements',
  393. '交付执行': 'delivery',
  394. '建模': 'delivery',
  395. '软装': 'delivery',
  396. '渲染': 'delivery',
  397. '后期': 'delivery',
  398. '尾款结算': 'aftercare',
  399. '客户评价': 'aftercare',
  400. '投诉处理': 'aftercare'
  401. };
  402. const targetStage = stageMap[projectStage] || 'order';
  403. // 如果当前没有子路由,跳转到对应阶段
  404. if (!this.route.firstChild) {
  405. this.router.navigate([targetStage], { relativeTo: this.route, replaceUrl: true });
  406. }
  407. } catch (err: any) {
  408. console.error('加载失败:', err);
  409. this.error = err.message || '加载失败';
  410. } finally {
  411. this.loading = false;
  412. }
  413. }
  414. /**
  415. * 切换阶段(点击顶部导航栏,无权限限制)
  416. * 允许自由访问所有阶段,无论状态如何
  417. */
  418. switchStage(stageId: string) {
  419. console.log('🔄 用户点击切换阶段:', stageId, {
  420. currentRoute: this.router.url,
  421. currentStage: this.currentStage,
  422. workflowStage: this.project?.get('currentStage')
  423. });
  424. // 获取点击阶段的状态(仅用于日志)
  425. const status = this.getStageStatus(stageId);
  426. // ✅ 取消权限限制,允许访问所有阶段
  427. console.log(`✅ 允许访问阶段: ${stageId} (状态: ${status})`);
  428. // 更新本地显示状态(仅影响路由,不影响工作流)
  429. this.currentStage = stageId;
  430. // 使用相对路径导航到指定阶段
  431. this.router.navigate([stageId], { relativeTo: this.route })
  432. .then(success => {
  433. if (success) {
  434. console.log('✅ 导航成功:', stageId);
  435. } else {
  436. console.warn('⚠️ 导航失败:', stageId);
  437. }
  438. })
  439. .catch(err => {
  440. console.error('❌ 导航出错:', err);
  441. });
  442. }
  443. /**
  444. * 获取阶段状态(参考设计师端 getSectionStatus 实现)
  445. * @returns 'completed' - 已完成(绿色)| 'active' - 当前进行中(红色)| 'pending' - 待开始(灰色)
  446. */
  447. getStageStatus(stageId: string): 'completed' | 'active' | 'pending' {
  448. // 颜色显示仅依据"工作流状态",不受临时浏览路由影响
  449. const data = this.project?.get('data') || {};
  450. const statuses = data.stageStatuses || {};
  451. const workflowCurrent = this.project?.get('currentStage') || 'order';
  452. // 如果没有当前阶段(新创建的项目),默认订单分配为active(红色)
  453. if (!workflowCurrent || workflowCurrent === 'order') {
  454. return stageId === 'order' ? 'active' : 'pending';
  455. }
  456. // 计算阶段索引
  457. const stageOrder = ['order', 'requirements', 'delivery', 'aftercare'];
  458. const currentIdx = stageOrder.indexOf(workflowCurrent);
  459. const idx = stageOrder.indexOf(stageId);
  460. if (idx === -1 || currentIdx === -1) return 'pending';
  461. // 已完成的阶段:当前阶段之前的所有阶段(绿色)
  462. if (idx < currentIdx) return 'completed';
  463. // 当前进行中的阶段:等于当前阶段(红色)
  464. if (idx === currentIdx) return 'active';
  465. // 未开始的阶段:当前阶段之后的所有阶段(灰色)
  466. return 'pending';
  467. }
  468. /**
  469. * 返回
  470. */
  471. goBack() {
  472. let ua = navigator.userAgent.toLowerCase();
  473. let isWeixin = ua.indexOf("micromessenger") != -1;
  474. if(isWeixin){
  475. this.router.navigate(['/wxwork', this.cid, 'project-loader']);
  476. }else{
  477. history.back();
  478. }
  479. }
  480. /**
  481. * 更新项目阶段
  482. */
  483. async updateProjectStage(stage: string) {
  484. if (!this.project || !this.canEdit) return;
  485. try {
  486. this.project.set('currentStage', stage);
  487. await this.project.save();
  488. // 添加阶段历史
  489. const data = this.project.get('data') || {};
  490. const stageHistory = data.stageHistory || [];
  491. stageHistory.push({
  492. stage,
  493. startTime: new Date(),
  494. status: 'current',
  495. operator: {
  496. id: this.currentUser!.id,
  497. name: this.currentUser!.get('name'),
  498. role: this.role
  499. }
  500. });
  501. this.project.set('data', { ...data, stageHistory });
  502. await this.project.save();
  503. } catch (err) {
  504. console.error('更新阶段失败:', err);
  505. window?.fmode?.alert('更新失败');
  506. }
  507. }
  508. /**
  509. * 发送企微消息
  510. */
  511. async sendWxMessage(message: string) {
  512. if (!this.groupChat || !this.wecorp) return;
  513. try {
  514. const chatId = this.groupChat.get('chat_id');
  515. await this.wecorp.appchat.sendText(chatId, message);
  516. } catch (err) {
  517. console.error('发送消息失败:', err);
  518. }
  519. }
  520. /**
  521. * 选择客户(从群聊成员中选择外部联系人)
  522. */
  523. async selectCustomer() {
  524. console.log(this.canEdit, this.groupChat)
  525. if (!this.groupChat) return;
  526. try {
  527. const memberList = this.groupChat.get('member_list') || [];
  528. const externalMembers = memberList.filter((m: any) => m.type === 2);
  529. if (externalMembers.length === 0) {
  530. window?.fmode?.alert('当前群聊中没有外部联系人');
  531. return;
  532. }
  533. console.log(externalMembers)
  534. // 简单实现:选择第一个外部联系人
  535. // TODO: 实现选择器UI
  536. const selectedMember = externalMembers[0];
  537. await this.setCustomerFromMember(selectedMember);
  538. } catch (err) {
  539. console.error('选择客户失败:', err);
  540. window?.fmode?.alert('选择客户失败');
  541. }
  542. }
  543. /**
  544. * 从群成员设置客户
  545. */
  546. async setCustomerFromMember(member: any) {
  547. if (!this.wecorp) return;
  548. try {
  549. const companyId = this.currentUser?.get('company')?.id || localStorage.getItem("company");
  550. if (!companyId) throw new Error('无法获取企业信息');
  551. // 1. 查询是否已存在 ContactInfo
  552. const query = new Parse.Query('ContactInfo');
  553. query.equalTo('external_userid', member.userid);
  554. query.equalTo('company', companyId);
  555. let contactInfo = await query.first();
  556. // 2. 如果不存在,通过企微API获取并创建
  557. if (!contactInfo) {
  558. contactInfo = new Parse.Object("ContactInfo");
  559. }
  560. const externalContactData = await this.wecorp.externalContact.get(member.userid);
  561. console.log("externalContactData",externalContactData)
  562. const ContactInfo = Parse.Object.extend('ContactInfo');
  563. contactInfo.set('name', externalContactData.name);
  564. contactInfo.set('external_userid', member.userid);
  565. const company = new Parse.Object('Company');
  566. company.id = companyId;
  567. const companyPointer = company.toPointer();
  568. contactInfo.set('company', companyPointer);
  569. contactInfo.set('data', externalContactData);
  570. await contactInfo.save();
  571. // 3. 设置为项目客户
  572. if (this.project) {
  573. this.project.set('contact', contactInfo.toPointer());
  574. await this.project.save();
  575. this.contact = contactInfo;
  576. window?.fmode?.alert('客户设置成功');
  577. }
  578. } catch (err) {
  579. console.error('设置客户失败:', err);
  580. throw err;
  581. }
  582. }
  583. /**
  584. * 显示文件模态框
  585. */
  586. showFiles() {
  587. this.showFilesModal = true;
  588. }
  589. /**
  590. * 显示成员模态框
  591. */
  592. showMembers() {
  593. this.showMembersModal = true;
  594. }
  595. /** 显示问题模态框 */
  596. showIssues() {
  597. this.showIssuesModal = true;
  598. }
  599. /**
  600. * 关闭文件模态框
  601. */
  602. closeFilesModal() {
  603. this.showFilesModal = false;
  604. }
  605. /**
  606. * 关闭成员模态框
  607. */
  608. closeMembersModal() {
  609. this.showMembersModal = false;
  610. }
  611. /** 显示客户详情面板 */
  612. openContactPanel() {
  613. if (this.contact) {
  614. this.showContactPanel = true;
  615. }
  616. }
  617. /** 关闭客户详情面板 */
  618. closeContactPanel() {
  619. this.showContactPanel = false;
  620. }
  621. /** 关闭问题模态框 */
  622. closeIssuesModal() {
  623. this.showIssuesModal = false;
  624. if (this.project?.id) {
  625. const counts = this.issueService.getCounts(this.project.id!);
  626. this.issueCount = counts.total;
  627. }
  628. }
  629. /** 客户选择事件回调(接收子组件输出) */
  630. onContactSelected(evt: { contact: FmodeObject; isNewCustomer: boolean; action: 'selected' | 'created' | 'updated' }) {
  631. this.contact = evt.contact;
  632. // 重新加载问卷状态
  633. this.loadSurveyStatus();
  634. }
  635. /**
  636. * 加载问卷状态
  637. */
  638. async loadSurveyStatus() {
  639. if (!this.project?.id) return;
  640. try {
  641. const query = new Parse.Query('SurveyLog');
  642. query.equalTo('project', this.project.toPointer());
  643. query.equalTo('type', 'survey-project');
  644. query.equalTo('isCompleted', true);
  645. query.include("contact")
  646. const surveyLog = await query.first();
  647. if (surveyLog) {
  648. this.surveyStatus = {
  649. filled: true,
  650. text: '查看问卷',
  651. icon: 'checkmark-circle',
  652. surveyLog,
  653. contact:surveyLog?.get("contact")
  654. };
  655. console.log('✅ 问卷已填写');
  656. } else {
  657. this.surveyStatus = {
  658. filled: false,
  659. text: '发送问卷',
  660. icon: 'document-text-outline'
  661. };
  662. console.log('✅ 问卷未填写');
  663. }
  664. } catch (err) {
  665. console.error('❌ 查询问卷状态失败:', err);
  666. }
  667. }
  668. /**
  669. * 发送问卷
  670. */
  671. async sendSurvey() {
  672. if (!this.groupChat || !this.wxwork) {
  673. window?.fmode?.alert('无法发送问卷:未找到群聊或企微SDK未初始化');
  674. return;
  675. }
  676. try {
  677. const chatId = this.groupChat.get('chat_id');
  678. const surveyUrl = `${document.baseURI}/wxwork/${this.cid}/survey/project/${this.project?.id}`;
  679. await this.wxwork.ww.openExistedChatWithMsg({
  680. chatId: chatId,
  681. msg: {
  682. msgtype: 'link',
  683. link: {
  684. title: '《家装效果图服务需求调查表》',
  685. desc: '为让本次服务更贴合您的需求,请花3-5分钟填写简短问卷,感谢支持!',
  686. url: surveyUrl,
  687. imgUrl: `${document.baseURI}/assets/logo.jpg`
  688. }
  689. }
  690. });
  691. window?.fmode?.alert('问卷已发送到群聊!');
  692. } catch (err) {
  693. console.error('❌ 发送问卷失败:', err);
  694. window?.fmode?.alert('发送失败,请重试');
  695. }
  696. }
  697. /**
  698. * 查看问卷结果
  699. */
  700. async viewSurvey() {
  701. if (!this.surveyStatus.surveyLog) return;
  702. // 跳转到问卷页面查看结果
  703. this.router.navigate(['/wxwork', this.cid, 'survey', 'project', this.project?.id]);
  704. }
  705. /**
  706. * 处理问卷点击
  707. */
  708. async handleSurveyClick(event: Event) {
  709. event.stopPropagation();
  710. if (this.surveyStatus.filled) {
  711. // 已填写,查看结果
  712. await this.viewSurvey();
  713. } else {
  714. // 未填写,发送问卷
  715. await this.sendSurvey();
  716. }
  717. }
  718. /**
  719. * 是否显示审批面板
  720. * 条件:当前用户是组长 + 项目处于订单分配阶段 + 审批状态为待审批
  721. */
  722. get showApprovalPanel(): boolean {
  723. if (!this.project || !this.currentUser) {
  724. console.log('🔍 审批面板检查: 缺少项目或用户数据');
  725. return false;
  726. }
  727. const userRole = this.currentUser.get('roleName') || '';
  728. // ✅ 恢复正确的角色检查:只有组长才能看到审批面板
  729. const isTeamLeader = userRole === '设计组长' || userRole === 'team-leader' || userRole === '组长';
  730. const currentStage = this.project.get('currentStage') || '';
  731. const isOrderStage = currentStage === '订单分配' || currentStage === 'order';
  732. const data = this.project.get('data') || {};
  733. const approvalStatus = data.approvalStatus;
  734. const isPending = approvalStatus === 'pending';
  735. // console.log('🔍 审批面板检查:', {
  736. // userRole,
  737. // isTeamLeader,
  738. // currentStage,
  739. // isOrderStage,
  740. // approvalStatus,
  741. // isPending,
  742. // result: isTeamLeader && isOrderStage && isPending
  743. // });
  744. return isTeamLeader && isOrderStage && isPending;
  745. }
  746. /**
  747. * 处理审批完成事件
  748. */
  749. async onApprovalCompleted(event: { action: 'approved' | 'rejected'; reason?: string; comment?: string }) {
  750. if (!this.project) return;
  751. try {
  752. const data = this.project.get('data') || {};
  753. const approvalHistory = data.approvalHistory || [];
  754. const latestRecord = approvalHistory[approvalHistory.length - 1];
  755. if (latestRecord) {
  756. latestRecord.status = event.action;
  757. latestRecord.approver = {
  758. id: this.currentUser?.id,
  759. name: this.currentUser?.get('name'),
  760. role: this.currentUser?.get('roleName')
  761. };
  762. latestRecord.approvalTime = new Date();
  763. latestRecord.comment = event.comment;
  764. latestRecord.reason = event.reason;
  765. }
  766. if (event.action === 'approved') {
  767. // 通过审批:推进到确认需求阶段
  768. data.approvalStatus = 'approved';
  769. this.project.set('currentStage', '确认需求');
  770. this.project.set('data', data);
  771. await this.project.save();
  772. alert('✅ 审批通过,项目已进入确认需求阶段');
  773. // 刷新页面数据
  774. await this.loadData();
  775. } else {
  776. // 驳回:保持在订单分配阶段,记录驳回原因
  777. data.approvalStatus = 'rejected';
  778. data.lastRejectionReason = event.reason || '未提供原因';
  779. this.project.set('data', data);
  780. await this.project.save();
  781. alert('✅ 已驳回订单,客服将收到通知');
  782. // 刷新页面数据
  783. await this.loadData();
  784. }
  785. } catch (err) {
  786. console.error('处理审批失败:', err);
  787. alert('审批操作失败,请重试');
  788. }
  789. }
  790. }
  791. // duplicate inline CustomerSelectorComponent removed (we keep single declaration above)