index.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. const SHARE_TO = (() => {
  2. const ShareType = {
  3. CREATE: 'create',
  4. UPDATE: 'update',
  5. CANCEL: 'cancel',
  6. };
  7. const { SharePermissionChangeType: PermissionType, PageTarget } = commonConstants;
  8. // 当前分享的项目ID
  9. let curProjectID;
  10. // 当前项目的已分享列表
  11. let curSharedUsers = [];
  12. // 清除缓存
  13. function clearCache() {
  14. curProjectID = null;
  15. curSharedUsers = [];
  16. }
  17. // 最近联系人显示数量
  18. const rencentCount = 5;
  19. // 获取初始数据:1.最近分享人 2.联系人 3.已分享人
  20. async function getInitalData(projectID) {
  21. return await ajaxPost('/pm/api/getInitialShareData', { user_id: userID, count: rencentCount, projectID }, false);
  22. }
  23. // 获取头像视图html
  24. function getAvatarHTML(mobile, realName) {
  25. // 手机最后一位
  26. const lastMobileNumer = mobile.substr(-1);
  27. // 显示名称为真实名称后两位
  28. const nickName = realName.substr(-2);
  29. return `<span class="avatar bg-${lastMobileNumer}">${nickName}</span>`;
  30. }
  31. /**
  32. * 获取用户列表视图html:最近分享和联系人用
  33. * @param {Array} users - 排序过的用户数据
  34. * @param {Boolean} showAlphabet - 是否显示字母表分类
  35. * @return {HTMLString}
  36. * */
  37. function getUserHTML(users, showAlphabet) {
  38. let curLetter = '';
  39. return users.reduce((html, user) => {
  40. const mobile = user.mobile || '';
  41. const realName = user.real_name || '';
  42. const company = user.company || '';
  43. if (showAlphabet) {
  44. // 名字首个字符对应拼音
  45. const letter = pinyinUtil.getFirstLetter(realName).substr(0, 1);
  46. if (letter !== curLetter) {
  47. curLetter = letter;
  48. html += `<li class="letter">${letter}</li>`;
  49. }
  50. }
  51. const avatarHtml = getAvatarHTML(mobile, realName);
  52. return html +
  53. `<li>
  54. ${avatarHtml}
  55. <div class="book-body">
  56. <h5 class="mt-0" title="${company}">${realName}</h5>
  57. <span>${mobile}</span>
  58. </div>
  59. </li>`;
  60. }, '');
  61. }
  62. // 初始化最近分享视图
  63. function initRecentView(recentUsers) {
  64. const recentShareHTML = getUserHTML(recentUsers, false);
  65. $('#recent-share').html(recentShareHTML);
  66. // 点击最近分享列表自动添加该用户添加到搜索框中
  67. $('#recent-share li').click(function () {
  68. const mobile = $(this).find('div span')[0].textContent;
  69. $('#share-phone').val(mobile);
  70. handleSearch()
  71. })
  72. }
  73. // 初始化联系人视图
  74. function initContactsView(contacts) {
  75. // 联系人按拼英首字母降序排序
  76. contacts.sort((a, b) => {
  77. const realNameA = a.real_name || '';
  78. const realNameB = b.real_name || '';
  79. return realNameA.localeCompare(realNameB, 'zh-Hans-CN', { sensitivity: 'accent' })
  80. });
  81. const contactsHTML = getUserHTML(contacts, true);
  82. $('#contacts').html(contactsHTML);
  83. // 点击联系人自动添加该联系人添加到搜索框中
  84. $('#contacts li:not(.letter)').click(function () {
  85. const mobile = $(this).find('div span')[0].textContent;
  86. $('#share-phone').val(mobile);
  87. $('#contacts-menue').removeClass('show');
  88. handleSearch()
  89. });
  90. }
  91. // 初始化已分享视图
  92. function initSharedView(sharedUsers) {
  93. const html = sharedUsers.reduce((html, user, index) => {
  94. const mobile = user.mobile || '';
  95. const realName = user.real_name || '';
  96. const company = user.company || '';
  97. const avatarHTML = getAvatarHTML(mobile, realName);
  98. const copyLabelFor = `allowCopy${index}`;
  99. const editLabelFor = `allowEdit${index}`;
  100. return html +
  101. `<li class="card mb-1">
  102. <div class="card-body p-1 row m-0">
  103. ${avatarHTML}
  104. <div class="book-body col-auto pl-0">
  105. <h5 class="mt-0">${realName}</h5>
  106. ${mobile}
  107. </div>
  108. <div class="col-5">${company}</div>
  109. <div class="col ml-auto p-0">
  110. <div class="d-flex justify-content-end">
  111. <div>
  112. <div class="custom-control custom-checkbox">
  113. <input type="checkbox" class="custom-control-input allow-copy" id="${copyLabelFor}" data-user="${user._id}" ${user.allowCopy ? 'checked' : ''}>
  114. <label class="custom-control-label" for="${copyLabelFor}">允许拷贝</label>
  115. </div>
  116. <div class="custom-control custom-checkbox">
  117. <input type="checkbox" class="custom-control-input allow-edit" id="${editLabelFor}" data-user="${user._id}" ${user.allowCooperate ? 'checked' : ''}>
  118. <label class="custom-control-label" for="${editLabelFor}">允许编辑</label>
  119. </div>
  120. </div>
  121. <div class="ml-3 d-flex align-items-center">
  122. <button class="btn btn-sm btn-outline-danger cancel-share" data-user="${user._id}">取消分享</button>
  123. </div>
  124. </div>
  125. </div>
  126. </div>
  127. </li>`;
  128. }, '');
  129. $('#shared-list').html(html);
  130. // 编辑允许拷贝
  131. $('#shared-list .allow-copy').click(function () {
  132. handleCheckBoxClick.call(this);
  133. handleShareAction.call(this, ShareType.UPDATE);
  134. });
  135. // 编辑允许编辑
  136. $('#shared-list .allow-edit').click(function () {
  137. handleCheckBoxClick.call(this);
  138. handleShareAction.call(this, ShareType.UPDATE);
  139. });
  140. // 取消分享
  141. $('#shared-list .cancel-share').click(function () {
  142. handleShareAction.call(this, ShareType.CANCEL);
  143. });
  144. }
  145. // 初始化搜索结果视图
  146. function initSearchResultView(user) {
  147. if (!user) {
  148. $('#share-search-result').html('')
  149. } else {
  150. const mobile = user.mobile || '';
  151. const realName = user.real_name || '';
  152. const company = user.company || '';
  153. const avatarHTML = getAvatarHTML(mobile, realName);
  154. const html =
  155. `<li class="card mb-1">
  156. <div class="card-body p-1 row m-0">
  157. ${avatarHTML}
  158. <div class="book-body col-auto pl-0">
  159. <h5 class="mt-0">${realName}</h5>
  160. ${mobile}
  161. </div>
  162. <div class="col-5">${company}</div>
  163. <div class="col ml-auto p-0">
  164. <div class="d-flex justify-content-end">
  165. <div>
  166. <div class="custom-control custom-checkbox">
  167. <input type="checkbox" class="custom-control-input" id="allow-copy" checked="">
  168. <label class="custom-control-label" for="allow-copy">允许拷贝</label>
  169. </div>
  170. <div class="custom-control custom-checkbox">
  171. <input type="checkbox" class="custom-control-input" id="allow-edit">
  172. <label class="custom-control-label" for="allow-edit">允许编辑</label>
  173. </div>
  174. </div>
  175. <div class="ml-3 d-flex align-items-center"><button class="btn btn-sm btn-primary" id="share-to" data-user="${user._id}">分享给Ta</button></div>
  176. </div>
  177. </div>
  178. </div>
  179. </li>`;
  180. $('#share-search-result').html(html);
  181. // 允许拷贝
  182. $('#allow-copy').click(function () {
  183. handleCheckBoxClick.call(this);
  184. });
  185. // 允许编辑
  186. $('#allow-edit').click(function () {
  187. handleCheckBoxClick.call(this);
  188. });
  189. // 分享给事件
  190. $('#share-to').click(function () {
  191. handleShareAction.call(this, ShareType.CREATE, user);
  192. });
  193. }
  194. }
  195. // 复选框框的状态随点击更改,不处理的话input的checked并不会自动处理
  196. function handleCheckBoxClick() {
  197. const curChecked = !$(this).attr('checked');
  198. if (curChecked) {
  199. $(this).attr('checked', 'checked');
  200. } else {
  201. $(this).removeAttr('checked');
  202. }
  203. }
  204. // 添加分享、编辑分享、取消分享的动作
  205. async function handleShareAction(shareType, user) {
  206. try {
  207. $.bootstrapLoading.start();
  208. const receiver = $(this).data('user');
  209. let shareData;
  210. let type = ShareType.UPDATE;
  211. if (shareType === ShareType.CREATE) {
  212. const allowCopy = $('#allow-copy').prop('checked');
  213. const allowCooperate = $('#allow-edit').prop('checked');
  214. shareData = [{ userID: receiver, allowCopy, allowCooperate }];
  215. type = ShareType.CREATE; // 上传的服务器的type,删除跟更新是一样的
  216. } else if (shareType === ShareType.UPDATE) {
  217. const allowCopy = $(`[data-user=${receiver}].allow-copy`).prop('checked');
  218. const allowCooperate = $(`[data-user=${receiver}].allow-edit`).prop('checked');
  219. shareData = [{ userID: receiver, allowCopy, allowCooperate }];
  220. } else {
  221. shareData = [{ userID: receiver, isCancel: true }];
  222. }
  223. const postData = {
  224. user_id: userID,
  225. type,
  226. projectID: curProjectID,
  227. count: rencentCount,
  228. shareData
  229. };
  230. const rst = await ajaxPost('/pm/api/share', postData);
  231. // 获取权限变更的类型
  232. const permissionType = getPermissionType(shareType, curSharedUsers, shareData[0]);
  233. // 请求成功后刷新视图
  234. if (shareType === ShareType.CREATE || shareType === ShareType.CANCEL) {
  235. if (shareType === ShareType.CREATE) {
  236. user.allowCopy = shareData[0].allowCopy;
  237. user.allowCooperate = shareData[0].allowCooperate;
  238. curSharedUsers.unshift(user);
  239. $('#share-phone').val('');
  240. initSearchResultView();
  241. } else {
  242. curSharedUsers = curSharedUsers.filter(user => user._id !== receiver);
  243. }
  244. if (Array.isArray(rst.recentUsers)) {
  245. initRecentView(rst.recentUsers);
  246. }
  247. if (Array.isArray(rst.contacts)) {
  248. initContactsView(rst.contacts)
  249. }
  250. initSharedView(curSharedUsers);
  251. refreshShareTip(curSharedUsers);
  252. refreshTreeView();
  253. } else {
  254. const matchItem = curSharedUsers.find(item => item._id === receiver);
  255. if (matchItem) {
  256. matchItem.allowCopy = shareData[0].allowCopy;
  257. matchItem.allowCooperate = shareData[0].allowCooperate;
  258. }
  259. }
  260. if (permissionType !== null) {
  261. console.log(curProjectID);
  262. emitPermissionChange(permissionType, receiver, curProjectID);
  263. }
  264. } catch (err) {
  265. console.log(err);
  266. alert(`${String(err)} 请重试。`);
  267. initSharedView(curSharedUsers);
  268. } finally {
  269. $.bootstrapLoading.end();
  270. }
  271. }
  272. // 获取权限变更的类型
  273. function getPermissionType(shareType, cache, curShareData) {
  274. if (shareType === ShareType.CANCEL) {
  275. return PermissionType.CANCEL;
  276. }
  277. if (shareType === ShareType.CREATE) {
  278. return PermissionType.SHARE;
  279. }
  280. if (!cache) {
  281. return null;
  282. }
  283. const match = cache.find(item => item._id === curShareData.userID);
  284. if (!match) {
  285. return null;
  286. }
  287. if (match.allowCooperate !== curShareData.allowCooperate) {
  288. return PermissionType.UPDATE_COOPERATE;
  289. }
  290. return null;
  291. }
  292. // 权限变更消息推送
  293. function emitPermissionChange(permissionType, userID, projectID) {
  294. const compilationID = typeof projectObj !== 'undefined' ? projectObj.project.projectInfo.compilation : compilationData._id;
  295. socket.emit('sharePermissionChange', { permissionType, userID, compilationID, projectID });
  296. }
  297. // 权限变更处理监听
  298. function permissionChangeListener() {
  299. socket.on('sharePermissionChange', ({ permissionType, target, payload }) => {
  300. const type = `${permissionType}-${target}`;
  301. switch (type) {
  302. case `${PermissionType.UPDATE_COOPERATE}-${PageTarget.PM}`:
  303. handlePMPropChange();
  304. break;
  305. case `${PermissionType.UPDATE_COOPERATE}-${PageTarget.MAIN}`:
  306. handleMainCooperateChange();
  307. break;
  308. case `${PermissionType.CANCEL}-${PageTarget.PM}`:
  309. handlePMCancelPermission(payload);
  310. break;
  311. case `${PermissionType.CANCEL}-${PageTarget.MAIN}`:
  312. handleMainCancelPermission();
  313. break;
  314. case `${PermissionType.SHARE}-${PageTarget.PM}`:
  315. handlePMSharePermission(payload);
  316. break;
  317. }
  318. });
  319. }
  320. // 项目管理页面分享权限变更后相关处理函数
  321. // 分享条数属性变更(是否可拷贝、是否可编辑)
  322. function handlePMPropChange(prop) {
  323. }
  324. // 已读某未读分享项目
  325. function removeUnread(projectID, list) {
  326. const idx = list.indexOf(projectID);
  327. if (idx >= 0) {
  328. list.splice(idx, 1);
  329. refreshUnreadCount(list.length);
  330. }
  331. }
  332. // 取消分享后项目管理页面接收到推送后到操作
  333. function handlePMCancelPermission({ projectID }) {
  334. removeUnread(projectID, unreadShareList);
  335. // 如果当前停留在分享标签界面,清楚分享项目
  336. const isActive = $('#tab_pm_share').hasClass('active');
  337. if (isActive) {
  338. pmShare.handleCancelShare(projectID);
  339. }
  340. }
  341. // 通知信息点击事件
  342. function notify() {
  343. pmShare.initShareTree();
  344. $("#notify").hide();
  345. }
  346. // 新增分享后项目管理页面接收到推送后的操作
  347. function handlePMSharePermission({ projectID }) {
  348. unreadShareList.push(projectID);
  349. unreadShareList = [...new Set(unreadShareList)];
  350. refreshUnreadCount(unreadShareList.length);
  351. // 如果当前停留在分享标签界面,需要弹出提示
  352. const isActive = $('#tab_pm_share').hasClass('active');
  353. if (isActive) {
  354. $("#message").html('您有新的分享项目,<a href="javascript:void(0);" id="load-data" onclick="SHARE_TO.notify()">点击刷新列表</a>');
  355. $("#notify").show();
  356. }
  357. }
  358. // 刷新未读分享标记
  359. function refreshUnreadCount(count) {
  360. if (count) {
  361. $('#unread-share-count').text(count);
  362. $('#unread-share-count').show();
  363. } else {
  364. $('#unread-share-count').hide();
  365. }
  366. }
  367. // 主页面的分享权限变更后相关处理函数
  368. function handleMainCooperateChange() {
  369. setLocalCache(commonConstants.StorageKey.ONCE_MAIN_LOADED, '分享设置已被修改,当前项目已自动刷新。');
  370. window.location.reload();
  371. }
  372. function handleMainCancelPermission() {
  373. // 定位到空白页
  374. window.location.replace(`/blank?type=${commonConstants.BlankType.SHARE_CANCEL}`);
  375. }
  376. function handleShare(params) {
  377. }
  378. // 刷新项目管理树视图
  379. // 如果是在项目管理页面,需要刷新树(分享图标可能需要清除)
  380. function refreshTreeView() {
  381. if (typeof projTreeObj !== 'undefined' && projTreeObj.tree.selected) {
  382. projTreeObj.tree.selected.data.shareInfo = curSharedUsers;
  383. const sheet = projTreeObj.workBook.getSheet(0);
  384. projTreeObj.renderSheetFuc(sheet, function () {
  385. sheet.invalidateLayout();
  386. sheet.repaint();
  387. });
  388. }
  389. }
  390. // 刷新造价书的分享按钮tooltip提示
  391. function refreshShareTip(sharedUsers) {
  392. const $shareTip = $('#share-tip');
  393. if (!$shareTip) {
  394. return;
  395. }
  396. const limit = 2;
  397. const count = sharedUsers.length;
  398. const users = sharedUsers.slice(0, 2);
  399. const tip = users.reduce((acc, user, index) => {
  400. if (index === 0) {
  401. acc += '已分享给';
  402. acc += user.real_name;
  403. } else {
  404. acc += ` ${user.real_name}`;
  405. }
  406. if (index === users.length - 1 && count > limit) {
  407. acc += `等${count}人`;
  408. }
  409. return acc;
  410. }, '');
  411. $shareTip.attr('data-original-title', tip);
  412. }
  413. // 初始化分享给的页面
  414. async function initModal(projectID) {
  415. try {
  416. curProjectID = projectID;
  417. $.bootstrapLoading.start();
  418. // 恢复
  419. $('#share-phone').val('');
  420. initSearchResultView();
  421. $('#share-hint').text('');
  422. const { isFree, sharedUsers, recentUsers, contacts } = await getInitalData(projectID);
  423. if (isFree) {
  424. hintBox.versionBox('此功能仅在专业版中提供,免费公用版可选择单个分段进行分享。');
  425. } else {
  426. curSharedUsers = sharedUsers;
  427. initSharedView(sharedUsers);
  428. initRecentView(recentUsers);
  429. initContactsView(contacts);
  430. setTimeout(() => $('#share-phone').focus(), 200);
  431. $('#share').modal('show');
  432. }
  433. } catch (err) {
  434. console.log(err);
  435. alert(err);
  436. } finally {
  437. $.bootstrapLoading.end();
  438. }
  439. }
  440. // 退出分享给页面
  441. function exitModal() {
  442. clearCache();
  443. }
  444. // 分享给
  445. async function handleSearch() {
  446. let phone = $('#share-phone').val();
  447. phone = phone && phone.trim() || '';
  448. //$('#share-hint').text('');
  449. initSearchResultView();
  450. if (!phone) {
  451. $('#share-hint').text('请输入手机号码。');
  452. return;
  453. }
  454. // 根据手机号获取用户
  455. const user = await ajaxPost('/user/getUserByMobile', { mobile: phone });
  456. if (!user) {
  457. $('#share-hint').text('账号不存在。');
  458. return;
  459. }
  460. if (user._id === userID) {
  461. $('#share-hint').text('不可分享给自己。');
  462. return;
  463. }
  464. const matched = curSharedUsers.find(item => item._id === user._id);
  465. if (matched) {
  466. $('#share-hint').text('已与该用户分享。');
  467. return;
  468. }
  469. $('#share-hint').text('');
  470. initSearchResultView(user);
  471. }
  472. // 一些事件的监听
  473. function handleEventListener() {
  474. // 界面消失
  475. $('#share').on('hide.bs.modal', function () {
  476. exitModal();
  477. });
  478. // 联系人下拉
  479. $('#contacts-dropdown').click(function () {
  480. const $subMenu = $('#contacts-menue');
  481. const visible = $subMenu.is(':visible');
  482. if (visible) {
  483. $subMenu.removeClass('show');
  484. } else {
  485. $subMenu.addClass('show');
  486. }
  487. });
  488. // 点击body时,联系人菜单的处理
  489. $('body').click(function (e) {
  490. const body = $(this)[0];
  491. const $contactsMenu = $('#contacts-menue');
  492. const contactsMenu = $contactsMenu[0];
  493. const dropdownButton = $('#contacts-dropdown')[0]
  494. if (!$contactsMenu.is(':visible')) {
  495. return;
  496. }
  497. let target = e.target;
  498. while (target !== body) {
  499. if ([contactsMenu, dropdownButton].includes(target)) {
  500. return;
  501. }
  502. target = target.parentElement;
  503. }
  504. $(contactsMenu.parentElement).removeClass('show');
  505. $contactsMenu.removeClass('show');
  506. });
  507. // 输入手机号查找要分享给的用户
  508. let keyupTime = 0;
  509. let delayTime = 500;
  510. function delayKeyup(callback) {
  511. const nowTime = Date.now();
  512. keyupTime = nowTime;
  513. setTimeout(function () {
  514. if (nowTime - keyupTime == 0) {
  515. callback();
  516. }
  517. }, delayTime);
  518. }
  519. $('#share-phone').on('keyup', function () {
  520. delayKeyup(function () {
  521. console.log(curSharedUsers);
  522. handleSearch();
  523. });
  524. });
  525. $('#sharePhone').on('keypress', function (e) {
  526. if (e.keyCode === 13) {
  527. $(this).blur();
  528. }
  529. });
  530. }
  531. return {
  532. initModal,
  533. handleEventListener,
  534. permissionChangeListener,
  535. emitPermissionChange,
  536. getAvatarHTML,
  537. notify,
  538. removeUnread,
  539. }
  540. })();