project-loader.component.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import { Component, OnInit } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { Router, ActivatedRoute } from '@angular/router';
  4. import { FormsModule } from '@angular/forms';
  5. import { WxworkSDK, WxworkCorp } from 'fmode-ng/core';
  6. import { FmodeParse, FmodeObject } from 'fmode-ng/parse';
  7. // WxworkCurrentChat 类型定义
  8. interface WxworkCurrentChat {
  9. type?: string;
  10. chatId?: string;
  11. group?: any;
  12. contact?: any;
  13. id?: string;
  14. [key: string]: any;
  15. }
  16. function wxdebug(...params:any[]){
  17. console.log(params)
  18. }
  19. const Parse = FmodeParse.with('nova');
  20. /**
  21. * 项目预加载页面
  22. *
  23. * 功能:
  24. * 1. 从企微会话获取上下文(群聊或联系人)
  25. * 2. 获取当前登录用户(Profile)
  26. * 3. 根据场景跳转到对应页面
  27. * - 群聊 → 项目详情 或 创建项目引导
  28. * - 联系人 → 客户画像
  29. *
  30. * 路由:/wxwork/:cid/project-loader
  31. *
  32. * 参考实现:nova-admin/projects/nova-crm/src/modules/chat/page-chat-context
  33. */
  34. @Component({
  35. selector: 'app-project-loader',
  36. standalone: true,
  37. imports: [CommonModule, FormsModule],
  38. templateUrl: './project-loader.component.html',
  39. styleUrls: ['./project-loader.component.scss']
  40. })
  41. export class ProjectLoaderComponent implements OnInit {
  42. // 基础数据
  43. cid: string = '';
  44. appId: string = 'crm';
  45. // 加载状态
  46. loading: boolean = true;
  47. loadingMessage: string = '正在加载...';
  48. error: string | null = null;
  49. // 企微SDK
  50. wxwork: WxworkSDK | null = null;
  51. wecorp: WxworkCorp | null = null;
  52. // 上下文数据
  53. currentUser: FmodeObject | null = null; // Profile 或 UserSocial
  54. currentChat: WxworkCurrentChat | null = null;
  55. chatType: 'group' | 'contact' | 'none' = 'none';
  56. groupChat: FmodeObject | null = null; // GroupChat
  57. contact: FmodeObject | null = null; // ContactInfo
  58. project: FmodeObject | null = null; // Project
  59. // 创建项目引导
  60. showCreateGuide: boolean = false;
  61. defaultProjectName: string = '';
  62. projectName: string = '';
  63. creating: boolean = false;
  64. // 历史项目(当前群聊无项目时展示)
  65. historyProjects: FmodeObject[] = [];
  66. constructor(
  67. private router: Router,
  68. private route: ActivatedRoute
  69. ) {}
  70. async ngOnInit() {
  71. // 获取路由参数
  72. this.route.paramMap.subscribe(async params => {
  73. this.cid = params.get('cid') || localStorage.getItem("company") || '';
  74. this.appId = params.get('appId') || 'crm';
  75. if (!this.cid) {
  76. this.error = '缺少企业ID参数';
  77. this.loading = false;
  78. return;
  79. }
  80. await this.loadData();
  81. });
  82. }
  83. /**
  84. * 加载数据主流程(参考 page-chat-context 实现)
  85. */
  86. async loadData() {
  87. try {
  88. this.loading = true;
  89. this.loadingMessage = '初始化企微SDK...';
  90. // 1️⃣ 初始化 SDK
  91. // @ts-ignore - fmode-ng type issue
  92. this.wxwork = new WxworkSDK({ cid: this.cid, appId: this.appId });
  93. // @ts-ignore - fmode-ng type issue
  94. this.wecorp = new WxworkCorp(this.cid);
  95. wxdebug('1. SDK初始化完成', { cid: this.cid, appId: this.appId });
  96. // 2️⃣ 加载当前登录员工信息(由 WxworkAuthGuard 自动登录)
  97. this.loadingMessage = '获取用户信息...';
  98. try {
  99. this.currentUser = await this.wxwork.getCurrentUser();
  100. wxdebug('2. 获取当前用户成功', this.currentUser?.toJSON());
  101. } catch (err) {
  102. console.error('获取当前用户失败:', err);
  103. wxdebug('2. 获取当前用户失败', err);
  104. throw new Error('获取用户信息失败,请重试');
  105. }
  106. // 3️⃣ 加载当前聊天上下文
  107. this.loadingMessage = '获取会话信息...';
  108. try {
  109. this.currentChat = await this.wxwork.getCurrentChat();
  110. wxdebug('3. getCurrentChat返回', this.currentChat);
  111. } catch (err) {
  112. console.error('getCurrentChat失败:', err);
  113. wxdebug('3. getCurrentChat失败', err);
  114. }
  115. // 4️⃣ 根据场景同步数据
  116. if (this.currentChat?.type === "chatId" && this.currentChat?.group) {
  117. // 群聊场景
  118. wxdebug('4. 检测到群聊场景', this.currentChat.group);
  119. this.loadingMessage = '同步群聊信息...';
  120. try {
  121. this.chatType = 'group';
  122. this.groupChat = await this.wxwork.syncGroupChat(this.currentChat.group);
  123. wxdebug('5. 群聊同步完成', this.groupChat?.toJSON());
  124. // 处理群聊场景
  125. await this.handleGroupChatScene();
  126. } catch (err) {
  127. console.error('群聊同步失败:', err);
  128. wxdebug('5. 群聊同步失败', err);
  129. throw new Error('群聊信息同步失败');
  130. }
  131. } else if (this.currentChat?.type === "userId" && this.currentChat?.id) {
  132. // 联系人场景
  133. wxdebug('4. 检测到联系人场景', { id: this.currentChat.id });
  134. this.loadingMessage = '同步联系人信息...';
  135. try {
  136. this.chatType = 'contact';
  137. // 获取完整联系人信息
  138. const contactInfo = await this.wecorp!.externalContact.get(this.currentChat.id);
  139. wxdebug('5. 获取完整联系人信息', contactInfo);
  140. this.contact = await this.wxwork.syncContact(contactInfo);
  141. wxdebug('6. 联系人同步完成', this.contact?.toJSON());
  142. // 处理联系人场景
  143. await this.handleContactScene();
  144. } catch (err) {
  145. console.error('联系人同步失败:', err);
  146. wxdebug('联系人同步失败', err);
  147. throw new Error('联系人信息同步失败');
  148. }
  149. } else {
  150. // 未检测到有效场景
  151. wxdebug('4. 未检测到有效场景', {
  152. currentChat: this.currentChat,
  153. type: this.currentChat?.type,
  154. hasGroup: !!this.currentChat?.group,
  155. hasContact: !!this.currentChat?.contact,
  156. hasId: !!this.currentChat?.id
  157. });
  158. throw new Error('无法识别当前会话类型,请在群聊或联系人会话中打开');
  159. }
  160. wxdebug('加载完成', {
  161. chatType: this.chatType,
  162. hasGroupChat: !!this.groupChat,
  163. hasContact: !!this.contact,
  164. hasCurrentUser: !!this.currentUser
  165. });
  166. } catch (err: any) {
  167. console.error('加载失败:', err);
  168. this.error = err.message || '加载失败,请重试';
  169. } finally {
  170. this.loading = false;
  171. }
  172. }
  173. /**
  174. * 处理群聊场景
  175. */
  176. async handleGroupChatScene() {
  177. this.loadingMessage = '查询项目信息...';
  178. // 查询群聊关联的项目
  179. const projectPointer = this.groupChat!.get('project');
  180. if (projectPointer) {
  181. // 有项目,加载项目详情
  182. let pid = projectPointer.id || projectPointer.objectId
  183. try {
  184. const query = new Parse.Query('Project');
  185. query.include('contact', 'assignee');
  186. this.project = await query.get(pid);
  187. wxdebug('找到项目', this.project.toJSON());
  188. // 跳转项目详情
  189. await this.navigateToProjectDetail();
  190. } catch (err) {
  191. console.error('加载项目失败:', err);
  192. wxdebug('加载项目失败', err);
  193. this.error = '项目已删除或无权访问';
  194. }
  195. } else {
  196. // 无项目,查询历史项目并显示创建引导
  197. await this.loadHistoryProjects();
  198. this.showCreateProjectGuide();
  199. }
  200. }
  201. /**
  202. * 处理联系人场景
  203. */
  204. async handleContactScene() {
  205. wxdebug('联系人场景,跳转客户画像', {
  206. contactId: this.contact!.id,
  207. contactName: this.contact!.get('name')
  208. });
  209. // 跳转客户画像页面
  210. await this.router.navigate(['/wxwork', this.cid, 'contact', this.contact!.id], {
  211. queryParams: {
  212. profileId: this.currentUser!.id
  213. }
  214. });
  215. }
  216. /**
  217. * 加载历史项目(当前群聊相关的其他项目)
  218. */
  219. async loadHistoryProjects() {
  220. try {
  221. // 通过 ProjectGroup 查询该群聊的所有项目
  222. const pgQuery = new Parse.Query('ProjectGroup');
  223. pgQuery.equalTo('groupChat', this.groupChat!.toPointer());
  224. pgQuery.include('project');
  225. pgQuery.descending('createdAt');
  226. const projectGroups = await pgQuery.find();
  227. this.historyProjects = projectGroups
  228. .map((pg: any) => pg.get('project'))
  229. .filter((p: any) => p && !p.get('isDeleted'));
  230. wxdebug('找到历史项目', { count: this.historyProjects.length });
  231. } catch (err) {
  232. console.error('加载历史项目失败:', err);
  233. wxdebug('加载历史项目失败', err);
  234. }
  235. }
  236. /**
  237. * 显示创建项目引导
  238. */
  239. showCreateProjectGuide() {
  240. this.showCreateGuide = true;
  241. this.defaultProjectName = this.groupChat!.get('name') || '新项目';
  242. this.projectName = this.defaultProjectName;
  243. wxdebug('显示创建项目引导', {
  244. groupName: this.groupChat!.get('name'),
  245. historyProjectsCount: this.historyProjects.length
  246. });
  247. }
  248. /**
  249. * 创建项目
  250. */
  251. async createProject() {
  252. if (!this.projectName.trim()) {
  253. alert('请输入项目名称');
  254. return;
  255. }
  256. // 权限检查
  257. const role = this.currentUser!.get('roleName');
  258. if (!['客服', '组长', '管理员'].includes(role)) {
  259. alert('您没有权限创建项目');
  260. return;
  261. }
  262. try {
  263. this.creating = true;
  264. wxdebug('开始创建项目', {
  265. projectName: this.projectName,
  266. groupChatId: this.groupChat!.id,
  267. currentUserId: this.currentUser!.id,
  268. role: role
  269. });
  270. // 1. 创建项目
  271. const Project = Parse.Object.extend('Project');
  272. const project = new Project();
  273. project.set('title', this.projectName.trim());
  274. project.set('company', this.currentUser!.get('company'));
  275. project.set('status', '待分配');
  276. project.set('currentStage', '订单分配');
  277. project.set('data', {
  278. createdBy: this.currentUser!.id,
  279. createdFrom: 'wxwork_groupchat',
  280. groupChatId: this.groupChat!.id
  281. });
  282. await project.save();
  283. wxdebug('项目创建成功', { projectId: project.id });
  284. // 2. 关联群聊
  285. this.groupChat!.set('project', project.toPointer());
  286. await this.groupChat!.save();
  287. wxdebug('群聊关联项目成功');
  288. // 3. 创建 ProjectGroup 关联(支持多项目多群)
  289. const ProjectGroup = Parse.Object.extend('ProjectGroup');
  290. const pg = new ProjectGroup();
  291. pg.set('project', project.toPointer());
  292. pg.set('groupChat', this.groupChat!.toPointer());
  293. pg.set('isPrimary', true);
  294. pg.set('company', this.currentUser!.get('company'));
  295. await pg.save();
  296. wxdebug('ProjectGroup关联创建成功');
  297. // 4. 跳转项目详情
  298. this.project = project;
  299. await this.navigateToProjectDetail();
  300. } catch (err: any) {
  301. console.error('创建项目失败:', err);
  302. wxdebug('创建项目失败', err);
  303. alert('创建失败: ' + (err.message || '未知错误'));
  304. } finally {
  305. this.creating = false;
  306. }
  307. }
  308. /**
  309. * 选择历史项目
  310. */
  311. async selectHistoryProject(project: FmodeObject) {
  312. try {
  313. wxdebug('选择历史项目', {
  314. projectId: project.id,
  315. projectTitle: project.get('title')
  316. });
  317. // 更新群聊的当前项目
  318. this.groupChat!.set('project', project.toPointer());
  319. await this.groupChat!.save();
  320. // 跳转项目详情
  321. this.project = project;
  322. await this.navigateToProjectDetail();
  323. } catch (err: any) {
  324. console.error('关联项目失败:', err);
  325. alert('关联失败: ' + (err.message || '未知错误'));
  326. }
  327. }
  328. /**
  329. * 跳转项目详情
  330. */
  331. async navigateToProjectDetail() {
  332. wxdebug('跳转项目详情', {
  333. projectId: this.project!.id,
  334. cid: this.cid,
  335. groupChatId: this.groupChat?.id
  336. });
  337. await this.router.navigate(['/wxwork', this.cid, 'project', this.project!.id], {
  338. queryParams: {
  339. groupId: this.groupChat?.id,
  340. profileId: this.currentUser!.id
  341. }
  342. });
  343. }
  344. /**
  345. * 重新加载
  346. */
  347. async reload() {
  348. this.error = null;
  349. this.showCreateGuide = false;
  350. this.historyProjects = [];
  351. this.chatType = 'none';
  352. await this.loadData();
  353. }
  354. /**
  355. * 获取当前员工姓名
  356. */
  357. getCurrentUserName(): string {
  358. if (!this.currentUser) return '未知';
  359. return this.currentUser.get('name') || this.currentUser.get('userid') || '未知';
  360. }
  361. /**
  362. * 获取当前员工角色
  363. */
  364. getCurrentUserRole(): string {
  365. if (!this.currentUser) return '未知';
  366. return this.currentUser.get('roleName') || '未知';
  367. }
  368. /**
  369. * 获取项目状态的显示样式类
  370. */
  371. getProjectStatusClass(status: string): string {
  372. const classMap: any = {
  373. '待分配': 'status-pending',
  374. '进行中': 'status-active',
  375. '已完成': 'status-completed',
  376. '已暂停': 'status-paused',
  377. '已取消': 'status-cancelled'
  378. };
  379. return classMap[status] || 'status-default';
  380. }
  381. /**
  382. * 格式化日期
  383. */
  384. formatDate(date: Date): string {
  385. if (!date) return '';
  386. const d = new Date(date);
  387. return `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;
  388. }
  389. }