index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. const SHARE_TO = (() => {
  2. const ShareType = {
  3. CREATE: 'create',
  4. UPDATE: 'update',
  5. CANCEL: 'cancel',
  6. };
  7. const PermissionType = commonConstants.SharePermissionChangeType;
  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. emitPermissionChange(permissionType, receiver, curProjectID);
  262. }
  263. } catch (err) {
  264. console.log(err);
  265. alert(`${String(err)} 请重试。`);
  266. initSharedView(curSharedUsers);
  267. } finally {
  268. $.bootstrapLoading.end();
  269. }
  270. }
  271. // 获取权限变更的类型
  272. function getPermissionType(shareType, cache, curShareData) {
  273. if (shareType === ShareType.CANCEL) {
  274. return PermissionType.CANCEL;
  275. }
  276. if (!cache) {
  277. return null;
  278. }
  279. const match = cache.find(item => item._id === curShareData.userID);
  280. if (!match) {
  281. return null;
  282. }
  283. if (match.allowCooperate !== curShareData.allowCooperate) {
  284. return PermissionType.UPDATE_COOPERATE;
  285. }
  286. return null;
  287. }
  288. // 权限变更消息推送
  289. function emitPermissionChange(permissionType, userID, projectID) {
  290. socket.emit('sharePermissionChange', { permissionType, roomID: `${userID}@${projectID}` });
  291. }
  292. // 权限变更处理监听
  293. function permissionChangeListener() {
  294. socket.on('sharePermissionChange', ({ permissionType }) => {
  295. if (permissionType === PermissionType.CANCEL) {
  296. handleCancelPermission();
  297. } else if (permissionType === PermissionType.UPDATE_COOPERATE) {
  298. handleCooperateChange();
  299. }
  300. });
  301. }
  302. function handleCancelPermission() {
  303. // 定位到空白页
  304. window.location.replace(`/blank?type=${commonConstants.BlankType.SHARE_CANCEL}`);
  305. }
  306. function handleCooperateChange() {
  307. setLocalCache(commonConstants.StorageKey.ONCE_MAIN_LOADED, '分享设置已被修改,当前项目已自动刷新。');
  308. window.location.reload();
  309. }
  310. // 刷新项目管理树视图
  311. // 如果是在项目管理页面,需要刷新树(分享图标可能需要清除)
  312. function refreshTreeView() {
  313. if (typeof projTreeObj !== 'undefined' && projTreeObj.tree.selected) {
  314. projTreeObj.tree.selected.data.shareInfo = curSharedUsers;
  315. const sheet = projTreeObj.workBook.getSheet(0);
  316. projTreeObj.renderSheetFuc(sheet, function () {
  317. sheet.invalidateLayout();
  318. sheet.repaint();
  319. });
  320. }
  321. }
  322. // 刷新造价书的分享按钮tooltip提示
  323. function refreshShareTip(sharedUsers) {
  324. const $shareTip = $('#share-tip');
  325. if (!$shareTip) {
  326. return;
  327. }
  328. const limit = 2;
  329. const count = sharedUsers.length;
  330. const users = sharedUsers.slice(0, 2);
  331. const tip = users.reduce((acc, user, index) => {
  332. if (index === 0) {
  333. acc += '已分享给';
  334. acc += user.real_name;
  335. } else {
  336. acc += ` ${user.real_name}`;
  337. }
  338. if (index === users.length - 1 && count > limit) {
  339. acc += `等${count}人`;
  340. }
  341. return acc;
  342. }, '');
  343. $shareTip.attr('data-original-title', tip);
  344. }
  345. // 初始化分享给的页面
  346. async function initModal(projectID) {
  347. try {
  348. curProjectID = projectID;
  349. $.bootstrapLoading.start();
  350. // 恢复
  351. $('#share-phone').val('');
  352. initSearchResultView();
  353. $('#share-hint').text('');
  354. const { isFree, sharedUsers, recentUsers, contacts } = await getInitalData(projectID);
  355. if (isFree) {
  356. hintBox.versionBox('此功能仅在专业版中提供,免费公用版可选择单个分段进行分享。');
  357. } else {
  358. curSharedUsers = sharedUsers;
  359. initSharedView(sharedUsers);
  360. initRecentView(recentUsers);
  361. initContactsView(contacts);
  362. setTimeout(() => $('#share-phone').focus(), 200);
  363. $('#share').modal('show');
  364. }
  365. } catch (err) {
  366. console.log(err);
  367. alert(err);
  368. } finally {
  369. $.bootstrapLoading.end();
  370. }
  371. }
  372. // 退出分享给页面
  373. function exitModal() {
  374. clearCache();
  375. }
  376. // 分享给
  377. async function handleSearch() {
  378. let phone = $('#share-phone').val();
  379. phone = phone && phone.trim() || '';
  380. //$('#share-hint').text('');
  381. initSearchResultView();
  382. if (!phone) {
  383. $('#share-hint').text('请输入手机号码。');
  384. return;
  385. }
  386. // 根据手机号获取用户
  387. const user = await ajaxPost('/user/getUserByMobile', { mobile: phone });
  388. if (!user) {
  389. $('#share-hint').text('账号不存在。');
  390. return;
  391. }
  392. if (user._id === userID) {
  393. $('#share-hint').text('不可分享给自己。');
  394. return;
  395. }
  396. const matched = curSharedUsers.find(item => item._id === user._id);
  397. if (matched) {
  398. $('#share-hint').text('已与该用户分享。');
  399. return;
  400. }
  401. $('#share-hint').text('');
  402. initSearchResultView(user);
  403. }
  404. // 一些事件的监听
  405. function handleEventListener() {
  406. // 界面消失
  407. $('#share').on('hide.bs.modal', function () {
  408. exitModal();
  409. });
  410. // 联系人下拉
  411. $('#contacts-dropdown').click(function () {
  412. const $subMenu = $('#contacts-menue');
  413. const visible = $subMenu.is(':visible');
  414. if (visible) {
  415. $subMenu.removeClass('show');
  416. } else {
  417. $subMenu.addClass('show');
  418. }
  419. });
  420. // 点击body时,联系人菜单的处理
  421. $('body').click(function (e) {
  422. const body = $(this)[0];
  423. const $contactsMenu = $('#contacts-menue');
  424. const contactsMenu = $contactsMenu[0];
  425. const dropdownButton = $('#contacts-dropdown')[0]
  426. if (!$contactsMenu.is(':visible')) {
  427. return;
  428. }
  429. let target = e.target;
  430. while (target !== body) {
  431. if ([contactsMenu, dropdownButton].includes(target)) {
  432. return;
  433. }
  434. target = target.parentElement;
  435. }
  436. $(contactsMenu.parentElement).removeClass('show');
  437. $contactsMenu.removeClass('show');
  438. });
  439. // 输入手机号查找要分享给的用户
  440. let keyupTime = 0;
  441. let delayTime = 500;
  442. function delayKeyup(callback) {
  443. const nowTime = Date.now();
  444. keyupTime = nowTime;
  445. setTimeout(function () {
  446. if (nowTime - keyupTime == 0) {
  447. callback();
  448. }
  449. }, delayTime);
  450. }
  451. $('#share-phone').on('keyup', function () {
  452. delayKeyup(function () {
  453. console.log(curSharedUsers);
  454. handleSearch();
  455. });
  456. });
  457. $('#sharePhone').on('keypress', function (e) {
  458. if (e.keyCode === 13) {
  459. $(this).blur();
  460. }
  461. });
  462. }
  463. return {
  464. initModal,
  465. handleEventListener,
  466. permissionChangeListener,
  467. emitPermissionChange,
  468. getAvatarHTML,
  469. }
  470. })();