file_controller.js 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2021/10/27
  7. * @version
  8. */
  9. const auditConst = require('../const/audit');
  10. const sendToWormhole = require('stream-wormhole');
  11. const path = require('path');
  12. const advanceConst = require('../const/advance');
  13. const FILE_MANAGEMENT_EXTRA_EXTENSIONS = [
  14. '.sbp', '.jygs', '.gkgs', '.sjgs', '.sgys', '.qdys', '.gcjs', '.sjys',
  15. ];
  16. module.exports = app => {
  17. class FileController extends app.BaseController {
  18. checkUnlock(ctx) {
  19. if (ctx.subProject.lock_file) throw '管理员锁定中,暂无法编辑分类&文件,仅可查看';
  20. }
  21. checkLock(ctx) {
  22. if (!ctx.subProject.lock_file) throw '请先锁定,再管理分类数据';
  23. }
  24. isAdmin(ctx) {
  25. return Number(ctx.session.sessionUser.is_admin) === 1;
  26. }
  27. getFileUploadWhitelist(ctx) {
  28. const defaultWhitelist = ctx.app.config.multipart.whitelist || [];
  29. return Array.from(new Set(defaultWhitelist.concat(FILE_MANAGEMENT_EXTRA_EXTENSIONS).map(ext => ext.toLowerCase())));
  30. }
  31. isFileUploadExtensionAllowed(ctx, filename) {
  32. const ext = path.extname(filename || '').toLowerCase();
  33. return this.getFileUploadWhitelist(ctx).indexOf(ext) >= 0;
  34. }
  35. getFileUploadCheck(ctx) {
  36. const whitelist = this.getFileUploadWhitelist(ctx);
  37. return (fieldname, fileStream, filename) => {
  38. if (!fileStream || !filename) return null;
  39. const ext = path.extname(filename).toLowerCase();
  40. if (whitelist.indexOf(ext) >= 0) return null;
  41. const error = new Error(`资料管理不支持${ext || '无扩展名'}格式文件`);
  42. error.status = 400;
  43. return error;
  44. };
  45. }
  46. hasFilePermission(ctx, permissionKey) {
  47. if (this.isAdmin(ctx)) return true;
  48. const permission = ctx.service.subProjPermission.PermissionConst.file[permissionKey];
  49. const filePermission = ctx.subProject.permission.file_permission || [];
  50. return permission && filePermission.indexOf(permission.value) >= 0;
  51. }
  52. hasFileConfigPermission(ctx) {
  53. return this.hasFilePermission(ctx, 'manage_dir') || this.hasFilePermission(ctx, 'auth_user');
  54. }
  55. applyFileConfigViewPermission(ctx, permissionMap) {
  56. if (!this.hasFileConfigPermission(ctx)) return permissionMap;
  57. Object.keys(permissionMap || {}).forEach(filingId => {
  58. permissionMap[filingId].can_view = 1;
  59. });
  60. return permissionMap;
  61. }
  62. checkFilePermission(ctx, permissionKey) {
  63. if (!this.hasFilePermission(ctx, permissionKey)) throw '您无权进行该操作';
  64. }
  65. hasLegacyFilePermission(ctx, value) {
  66. if (this.isAdmin(ctx)) return true;
  67. return (ctx.subProject.permission.file_permission || []).indexOf(value) >= 0;
  68. }
  69. async getProjectFiling(ctx, filingId) {
  70. const filing = await ctx.service.filing.getDataById(filingId);
  71. if (!filing || filing.is_deleted || filing.spid !== ctx.subProject.id) throw '分类不存在';
  72. return filing;
  73. }
  74. async fillFilingAddUserNames(ctx, filingList) {
  75. const rows = filingList || [];
  76. const userIds = this.app._.uniq(rows.map(x => Number(x.create_uid)).filter(x => x > 0));
  77. const users = userIds.length > 0 ? await ctx.service.projectAccount.getAllDataByCondition({
  78. columns: ['id', 'name'],
  79. where: { id: userIds },
  80. }) : [];
  81. const userNameMap = {};
  82. users.forEach(user => { userNameMap[Number(user.id)] = user.name || ''; });
  83. rows.forEach(filing => {
  84. filing.add_user = userNameMap[Number(filing.create_uid)] || '';
  85. });
  86. return rows;
  87. }
  88. async fillFilingPermissionCreatorNames(ctx, filingList, permissionRows) {
  89. const rows = filingList || [];
  90. const exactPermissionRows = (permissionRows || []).filter(permission => {
  91. return permission.filing_id && Number(permission.create_uid) > 0;
  92. });
  93. const creatorIds = this.app._.uniq(exactPermissionRows
  94. .map(permission => Number(permission.create_uid)).filter(uid => uid > 0));
  95. const creators = creatorIds.length > 0 ? await ctx.service.projectAccount.getAllDataByCondition({
  96. columns: ['id', 'name'],
  97. where: { id: creatorIds },
  98. }) : [];
  99. const creatorNameMap = {};
  100. creators.forEach(creator => { creatorNameMap[Number(creator.id)] = creator.name || ''; });
  101. rows.forEach(filing => {
  102. const creatorNames = this.app._.uniq(exactPermissionRows.filter(permission => {
  103. return String(permission.filing_id) === String(filing.id);
  104. }).map(permission => creatorNameMap[Number(permission.create_uid)]).filter(Boolean));
  105. if (creatorNames.length > 0) filing.add_user = creatorNames.join('、');
  106. });
  107. return rows;
  108. }
  109. async checkFilingView(ctx, filing) {
  110. const permission = await ctx.service.subProjectFilingPermission.getResolvedPermission(
  111. ctx.subProject.id,
  112. ctx.session.sessionUser.accountId,
  113. filing.id,
  114. filing.filing_type,
  115. ctx.subProject.permission.file_permission,
  116. ctx.subProject.permission.filing_type,
  117. this.isAdmin(ctx)
  118. );
  119. if (this.hasFileConfigPermission(ctx)) permission.can_view = 1;
  120. if (!permission.can_view) throw '您无权查看该资料目录';
  121. return permission;
  122. }
  123. async getFilingOperationPermission(ctx, filing) {
  124. return await this.checkFilingView(ctx, filing);
  125. }
  126. async checkFilingOperation(ctx, filing, permissionField) {
  127. const permission = await this.getFilingOperationPermission(ctx, filing);
  128. if (!permission[permissionField]) throw '您无权进行该操作';
  129. return permission;
  130. }
  131. async getFilingFromDirectoryData(ctx, data) {
  132. const filingId = data.id || data.tree_pre_id || (data.tree_pid && data.tree_pid !== '-1' ? data.tree_pid : '');
  133. if (!filingId) throw '请先选择资料类别';
  134. return await this.getProjectFiling(ctx, filingId);
  135. }
  136. filterVisibleFiling(filingList, permissionMap) {
  137. const filingMap = {};
  138. (filingList || []).forEach(filing => { filingMap[String(filing.id)] = filing; });
  139. const visibleIds = new Set();
  140. (filingList || []).forEach(filing => {
  141. const permission = permissionMap[filing.id];
  142. if (!permission || !permission.can_view) return;
  143. let current = filing;
  144. while (current) {
  145. const currentId = String(current.id);
  146. if (visibleIds.has(currentId)) break;
  147. visibleIds.add(currentId);
  148. if (current.tree_pid === '-1' || current.tree_pid === -1) break;
  149. current = filingMap[String(current.tree_pid)];
  150. }
  151. });
  152. return (filingList || []).filter(filing => visibleIds.has(String(filing.id)));
  153. }
  154. /**
  155. * 概算投资
  156. *
  157. * @param ctx
  158. * @returns {Promise<void>}
  159. */
  160. async index(ctx) {
  161. try {
  162. if (!ctx.subProject.page_show.openFile) {
  163. throw '该功能已关闭或无法查看';
  164. }
  165. const renderData = {
  166. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.index),
  167. auditConst,
  168. };
  169. renderData.projectList = await ctx.service.subProject.getFileProject(ctx.session.sessionProject.id, ctx.session.sessionUser.accountId, ctx.session.sessionUser.is_admin);
  170. for (const p of renderData.projectList) {
  171. if (!p.is_folder) p.file_count = await this.service.filing.sumFileCount(p.id);
  172. }
  173. renderData.tenderList = await ctx.service.tender.getList4Select('stage');
  174. renderData.categoryData = await this.ctx.service.category.getAllCategory(ctx.subProject);
  175. await this.layout('file/index.ejs', renderData, 'file/modal.ejs');
  176. } catch (err) {
  177. ctx.log(err);
  178. ctx.session.postError = err.toString();
  179. ctx.redirect(this.menu.menu.dashboard.url);
  180. }
  181. }
  182. async file(ctx) {
  183. try {
  184. if (!this.hasLegacyFilePermission(ctx, 1)) throw '您无权查看旧版资料管理';
  185. const renderData = {
  186. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.file),
  187. };
  188. renderData.filing = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type);
  189. renderData.categoryData = await ctx.service.category.getAllCategory(ctx.subProject);
  190. renderData.canFiling = !ctx.subProject.lock_file && this.hasLegacyFilePermission(ctx, 3);
  191. renderData.canUpload = !ctx.subProject.lock_file && this.hasLegacyFilePermission(ctx, 2);
  192. renderData.canEdit = !ctx.subProject.lock_file && this.hasLegacyFilePermission(ctx, 4);
  193. renderData.fileReferenceList = await ctx.service.subProject.getFileReference(ctx.subProject, ctx.service.subProject.FileReferenceType.file);
  194. await this.layout('file/file.ejs', renderData, 'file/file_modal.ejs');
  195. } catch (err) {
  196. ctx.log(err);
  197. }
  198. }
  199. /**
  200. * SpreadJS 替代 zTree 展示资料分类树 Demo
  201. *
  202. * @param {Object} ctx - egg context
  203. */
  204. async fileSjsDemo(ctx) {
  205. try {
  206. const renderData = {
  207. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.sjs_demo),
  208. };
  209. renderData.filing = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type);
  210. renderData.categoryData = await ctx.service.category.getAllCategory(ctx.subProject);
  211. // 根据 lock_file 判断是否可编辑
  212. const canEdit = !ctx.subProject.lock_file;
  213. renderData.canFiling = canEdit;
  214. renderData.canUpload = canEdit;
  215. renderData.canEdit = canEdit;
  216. renderData.fileReferenceList = await ctx.service.subProject.getFileReference(ctx.subProject, ctx.service.subProject.FileReferenceType.file);
  217. await this.layout('file/file_sjs_demo.ejs', renderData);
  218. } catch (err) {
  219. ctx.log(err);
  220. }
  221. }
  222. /**
  223. * 资料管理 SpreadJS 版本
  224. * 使用 SpreadJS 替代 zTree 展示文件分类树
  225. *
  226. * @param {Object} ctx - egg context
  227. */
  228. async filesjs(ctx) {
  229. try {
  230. const renderData = {
  231. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.filesjs),
  232. fileUploadWhitelist: this.getFileUploadWhitelist(ctx),
  233. };
  234. const allFiling = await ctx.service.filing.getValidFiling(ctx.params.id, 'all');
  235. const canManageDir = this.hasFilePermission(ctx, 'manage_dir');
  236. renderData.categoryData = await ctx.service.category.getAllCategory(ctx.subProject);
  237. renderData.filingPermissionMap = await ctx.service.subProjectFilingPermission.getPermissionMap(
  238. ctx.subProject.id,
  239. ctx.session.sessionUser.accountId,
  240. allFiling,
  241. ctx.subProject.permission.filing_type,
  242. ctx.subProject.permission.file_permission,
  243. this.isAdmin(ctx)
  244. );
  245. this.applyFileConfigViewPermission(ctx, renderData.filingPermissionMap);
  246. renderData.filing = this.filterVisibleFiling(allFiling, renderData.filingPermissionMap);
  247. // 共用 file_modal.ejs 需要渲染全部弹窗,实际显示与操作由 filingPermissionMap 控制。
  248. renderData.canFiling = true;
  249. renderData.canUpload = true;
  250. renderData.canEdit = false;
  251. renderData.canManageDir = this.hasFileConfigPermission(ctx);
  252. renderData.needFilingInitialization = canManageDir && allFiling.length === 0;
  253. renderData.filingInitializationTemplates = [];
  254. renderData.filingInitializationProjects = [];
  255. if (renderData.needFilingInitialization) {
  256. renderData.filingInitializationTemplates = await ctx.service.filingTemplateList.getAllDataByCondition({
  257. columns: ['id', 'name'],
  258. where: { ft_type: ctx.service.filingTemplateList.FtType.org },
  259. orders: [['create_time', 'asc']],
  260. });
  261. renderData.filingInitializationProjects = await ctx.service.subProject.getManageDirProjects(
  262. ctx.session.sessionProject.id,
  263. ctx.session.sessionUser.accountId,
  264. this.isAdmin(ctx),
  265. ctx.subProject.id
  266. );
  267. }
  268. renderData.fileReferenceList = await ctx.service.subProject.getFileReference(ctx.subProject, ctx.service.subProject.FileReferenceType.file);
  269. await this.layout('file/filesjs.ejs', renderData, 'file/file_modal.ejs');
  270. } catch (err) {
  271. ctx.log(err);
  272. }
  273. }
  274. async initializeFiling(ctx) {
  275. try {
  276. this.checkFilePermission(ctx, 'manage_dir');
  277. const data = JSON.parse(ctx.request.body.data);
  278. if (!data || !data.init_type) throw '请选择初始化方式';
  279. let sourceData = [];
  280. let templateData = null;
  281. if (data.init_type === 'template') {
  282. if (!data.template_id) throw '请选择系统模板库';
  283. templateData = await ctx.service.filingTemplateList.getDataByCondition({
  284. id: data.template_id,
  285. ft_type: ctx.service.filingTemplateList.FtType.org,
  286. });
  287. if (!templateData) throw '选择的系统模板不存在';
  288. sourceData = await ctx.service.filingTemplate.getAllDataByCondition({
  289. where: { temp_id: templateData.id },
  290. orders: [['tree_level', 'asc'], ['tree_order', 'asc']],
  291. });
  292. if (sourceData.length === 0) throw '选择的系统模板没有目录数据';
  293. } else if (data.init_type === 'project') {
  294. if (!data.source_spid) throw '请选择来源项目';
  295. const sourceProjects = await ctx.service.subProject.getManageDirProjects(
  296. ctx.session.sessionProject.id,
  297. ctx.session.sessionUser.accountId,
  298. this.isAdmin(ctx),
  299. ctx.subProject.id
  300. );
  301. const sourceProject = sourceProjects.find(project => {
  302. return String(project.id) === String(data.source_spid);
  303. });
  304. if (!sourceProject) throw '来源项目不存在或您没有管理目录权限';
  305. sourceData = await ctx.service.filing.getValidFiling(sourceProject.id, 'all');
  306. }
  307. const result = await ctx.service.filing.initializeDirectory(
  308. ctx.subProject.id,
  309. data.init_type,
  310. sourceData,
  311. ctx.session.sessionUser.accountId,
  312. templateData
  313. );
  314. ctx.body = { err: 0, msg: '', data: result };
  315. } catch (err) {
  316. ctx.log(err);
  317. ctx.ajaxErrorBody(err, '初始化资料目录失败');
  318. }
  319. }
  320. async configDir(ctx) {
  321. try {
  322. const canManageDir = this.hasFilePermission(ctx, 'manage_dir');
  323. const canAuthUser = this.hasFilePermission(ctx, 'auth_user');
  324. if (!canManageDir && !canAuthUser) throw '您无权查看配置目录';
  325. const renderData = {
  326. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.config_dir),
  327. };
  328. renderData.canManageDir = canManageDir;
  329. renderData.canAuthUser = canAuthUser;
  330. renderData.filing = await ctx.service.filing.getValidFiling(ctx.params.id, 'all');
  331. await this.fillFilingAddUserNames(ctx, renderData.filing);
  332. renderData.permissionData = renderData.canAuthUser ? await ctx.service.subProjPermission.getPermission(ctx.params.id) : [];
  333. renderData.filingPermissionData = renderData.canAuthUser
  334. ? await ctx.service.subProjectFilingPermission.getConfigPermissionRows(ctx.params.id, renderData.filing) : [];
  335. if (renderData.canAuthUser) {
  336. await this.fillFilingPermissionCreatorNames(
  337. ctx, renderData.filing, renderData.filingPermissionData
  338. );
  339. }
  340. renderData.accountList = renderData.canAuthUser
  341. ? await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file') : [];
  342. await this.layout('file/config_dir.ejs', renderData);
  343. } catch (err) {
  344. ctx.log(err);
  345. ctx.session.postError = err.toString();
  346. ctx.redirect(this.menu.menu.dashboard.url);
  347. }
  348. }
  349. async configDirLock(ctx) {
  350. const redirectUrl = `/sp/${ctx.subProject.id}/config-dir`;
  351. try {
  352. this.checkFilePermission(ctx, 'manage_dir');
  353. const lock = Number(ctx.request.body.lock);
  354. if (lock !== 0 && lock !== 1) throw '锁定状态参数错误';
  355. await ctx.service.subProject.save({ id: ctx.subProject.id, lock_file: lock });
  356. ctx.redirect(redirectUrl);
  357. } catch (err) {
  358. ctx.log(err);
  359. ctx.postError(err, '资料管理锁定状态修改失败');
  360. ctx.redirect(redirectUrl);
  361. }
  362. }
  363. async configDirUpdate(ctx) {
  364. try {
  365. this.checkFilePermission(ctx, 'manage_dir');
  366. this.checkLock(ctx);
  367. const data = JSON.parse(ctx.request.body.data);
  368. const result = await this.updateFiling(ctx, data);
  369. if (result && result.create) await this.fillFilingAddUserNames(ctx, result.create);
  370. ctx.body = { err: 0, msg: '', data: result };
  371. } catch (err) {
  372. ctx.log(err);
  373. ctx.ajaxErrorBody(err, '修改失败');
  374. }
  375. }
  376. async getFilingNodePermission(ctx) {
  377. try {
  378. this.checkFilePermission(ctx, 'auth_user');
  379. const filingId = ctx.request.body.filing_id;
  380. const filing = await this.getProjectFiling(ctx, filingId);
  381. const selectableAccounts = await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file');
  382. const projectAccounts = await ctx.service.subProjPermission.getPermission(ctx.subProject.id);
  383. const permissionRows = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  384. ctx.subProject.id, [filing]
  385. );
  386. const authorizedIds = permissionRows.filter(row => {
  387. return String(row.filing_id || '') === String(filing.id);
  388. }).map(row => Number(row.uid));
  389. const accountMap = {};
  390. projectAccounts.forEach(permission => {
  391. const userId = Number(permission.uid);
  392. accountMap[userId] = {
  393. id: userId,
  394. name: permission.name,
  395. company: permission.company,
  396. role: permission.role,
  397. };
  398. });
  399. selectableAccounts.forEach(account => {
  400. accountMap[Number(account.id)] = account;
  401. });
  402. const authorizedUsers = authorizedIds.map(uid => accountMap[uid]).filter(Boolean).map(account => {
  403. return {
  404. id: Number(account.id),
  405. name: account.name,
  406. company: account.company,
  407. role: account.role,
  408. };
  409. }).filter((account, index, list) => {
  410. return list.findIndex(item => Number(item.id) === Number(account.id)) === index;
  411. });
  412. /*
  413. * 下拉选择仍只使用数据范围内账号;这里额外合并项目账号,
  414. * 是为了让已经存在的旧授权不会因数据范围调整而从弹窗消失。
  415. */
  416. const selectableIds = selectableAccounts.map(account => Number(account.id));
  417. authorizedUsers.forEach(account => {
  418. account.selectable = selectableIds.indexOf(Number(account.id)) >= 0;
  419. });
  420. ctx.body = { err: 0, msg: '', data: authorizedUsers };
  421. } catch (err) {
  422. ctx.log(err);
  423. ctx.ajaxErrorBody(err, '获取授权用户失败');
  424. }
  425. }
  426. async saveFilingNodePermission(ctx) {
  427. try {
  428. this.checkFilePermission(ctx, 'auth_user');
  429. this.checkLock(ctx);
  430. const data = JSON.parse(ctx.request.body.data);
  431. if (!data || !data.filing_id) throw '请选择需要授权的资料目录';
  432. if (!(data.user_permissions instanceof Array)) throw '授权用户权限格式错误';
  433. if (data.user_permissions.find(x => !x || typeof x !== 'object')) throw '授权用户权限格式错误';
  434. const filing = await this.getProjectFiling(ctx, data.filing_id);
  435. const allFiling = await ctx.service.filing.getValidFiling(ctx.subProject.id, 'all');
  436. const filingMap = {};
  437. allFiling.forEach(item => { filingMap[String(item.id)] = item; });
  438. const ancestorIds = [];
  439. let parentId = String(filing.tree_pid);
  440. while (parentId !== '-1') {
  441. const parent = filingMap[parentId];
  442. if (!parent) break;
  443. ancestorIds.push(String(parent.id));
  444. parentId = String(parent.tree_pid);
  445. }
  446. if (ancestorIds.length > 0) {
  447. const ancestorPermissionRows = await ctx.service.subProjectFilingPermission.getAllDataByCondition({
  448. columns: ['filing_id'],
  449. where: { spid: ctx.subProject.id, filing_id: ancestorIds },
  450. limit: 1,
  451. });
  452. if (ancestorPermissionRows.length > 0) throw '父级目录已授权,当前目录不能单独授权';
  453. }
  454. const userPermissions = data.user_permissions;
  455. const requestedUserIds = userPermissions.map(x => Number(x.uid !== undefined ? x.uid : x.id));
  456. if (requestedUserIds.find(uid => !Number.isInteger(uid) || uid <= 0)) throw '授权用户数据错误';
  457. if (new Set(requestedUserIds).size !== requestedUserIds.length) throw '授权用户数据重复';
  458. const selectableAccounts = await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file');
  459. const selectableIds = selectableAccounts.map(account => Number(account.id));
  460. const currentPermissionRows = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  461. ctx.subProject.id, [filing]
  462. );
  463. const currentUserIds = currentPermissionRows.filter(row => {
  464. return String(row.filing_id || '') === String(filing.id);
  465. }).map(row => Number(row.uid));
  466. const invalidUserId = requestedUserIds.find(uid => {
  467. return selectableIds.indexOf(uid) < 0 && currentUserIds.indexOf(uid) < 0;
  468. });
  469. if (invalidUserId) throw '选择的用户超出资料管理数据范围';
  470. const result = await ctx.service.subProjectFilingPermission.savePermissionsToSubtree(
  471. ctx.subProject,
  472. filing,
  473. allFiling,
  474. userPermissions,
  475. ctx.session.sessionUser.accountId
  476. );
  477. const savedPermissionRows = await ctx.service.subProjectFilingPermission.getRows(ctx.subProject.id);
  478. await this.fillFilingAddUserNames(ctx, result.filings);
  479. await this.fillFilingPermissionCreatorNames(ctx, result.filings, savedPermissionRows);
  480. ctx.body = {
  481. err: 0,
  482. msg: '',
  483. data: {
  484. permissions: result.permissions,
  485. filings: result.filings.map(item => ({
  486. id: item.id,
  487. add_user: item.add_user || '',
  488. })),
  489. },
  490. };
  491. } catch (err) {
  492. ctx.log(err);
  493. ctx.ajaxErrorBody(err, '保存授权用户失败');
  494. }
  495. }
  496. async addFilingNodePermissions(ctx) {
  497. await this._saveFilingNodePermissionsToOther(ctx, false);
  498. }
  499. async coverFilingNodePermissions(ctx) {
  500. await this._saveFilingNodePermissionsToOther(ctx, true);
  501. }
  502. async _saveFilingNodePermissionsToOther(ctx, replaceExisting) {
  503. try {
  504. this.checkFilePermission(ctx, 'auth_user');
  505. this.checkLock(ctx);
  506. const data = JSON.parse(ctx.request.body.data);
  507. if (!data || !data.source_filing_id) throw '请选择来源资料目录';
  508. if (!(data.target_filing_ids instanceof Array) || data.target_filing_ids.length === 0) {
  509. throw '请选择目标资料目录';
  510. }
  511. if (data.target_filing_ids.length > 500) throw '一次最多选择500个目标资料目录';
  512. if (!(data.user_permissions instanceof Array) || data.user_permissions.length === 0) {
  513. throw '请选择需要添加的授权用户';
  514. }
  515. if (data.user_permissions.find(x => !x || typeof x !== 'object')) {
  516. throw '授权用户权限格式错误';
  517. }
  518. const sourceFiling = await this.getProjectFiling(ctx, data.source_filing_id);
  519. const targetFilingIds = data.target_filing_ids.map(id => String(id || '').trim());
  520. if (targetFilingIds.find(id => !id)) throw '目标资料目录数据错误';
  521. if (new Set(targetFilingIds).size !== targetFilingIds.length) throw '目标资料目录重复';
  522. if (targetFilingIds.indexOf(String(sourceFiling.id)) >= 0) throw '当前目录不能作为目标目录';
  523. const targetFilingRows = await ctx.service.filing.getAllDataByCondition({
  524. where: {
  525. id: targetFilingIds,
  526. spid: ctx.subProject.id,
  527. is_deleted: 0,
  528. },
  529. });
  530. const targetFilingMap = {};
  531. targetFilingRows.forEach(filing => { targetFilingMap[String(filing.id)] = filing; });
  532. if (targetFilingIds.find(filingId => !targetFilingMap[filingId])) throw '目标资料目录不存在';
  533. const targetFilings = targetFilingIds.map(filingId => targetFilingMap[filingId]);
  534. const userPermissions = data.user_permissions;
  535. const requestedUserIds = userPermissions.map(x => Number(x.uid !== undefined ? x.uid : x.id));
  536. if (requestedUserIds.find(uid => !Number.isInteger(uid) || uid <= 0)) throw '授权用户数据错误';
  537. if (new Set(requestedUserIds).size !== requestedUserIds.length) throw '授权用户数据重复';
  538. const selectableAccounts = await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file');
  539. const selectableIds = selectableAccounts.map(account => Number(account.id));
  540. const sourcePermissionRows = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  541. ctx.subProject.id, [sourceFiling]
  542. );
  543. const sourceUserIds = sourcePermissionRows.filter(row => {
  544. return String(row.filing_id || '') === String(sourceFiling.id);
  545. }).map(row => Number(row.uid));
  546. const invalidUserId = requestedUserIds.find(uid => {
  547. return selectableIds.indexOf(uid) < 0 && sourceUserIds.indexOf(uid) < 0;
  548. });
  549. if (invalidUserId) throw '选择的用户超出资料管理数据范围';
  550. const permissionService = ctx.service.subProjectFilingPermission;
  551. if (replaceExisting) {
  552. await permissionService.coverPermissionsToFilings(
  553. ctx.subProject,
  554. targetFilings,
  555. userPermissions,
  556. ctx.session.sessionUser.accountId
  557. );
  558. } else {
  559. await permissionService.addPermissionsToFilings(
  560. ctx.subProject,
  561. targetFilings,
  562. userPermissions,
  563. ctx.session.sessionUser.accountId
  564. );
  565. }
  566. const savedPermissionRows = await ctx.service.subProjectFilingPermission.getRows(ctx.subProject.id);
  567. const targetPermissionRows = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  568. ctx.subProject.id, targetFilings
  569. );
  570. await this.fillFilingAddUserNames(ctx, targetFilings);
  571. await this.fillFilingPermissionCreatorNames(ctx, targetFilings, savedPermissionRows);
  572. ctx.body = {
  573. err: 0,
  574. msg: '',
  575. data: {
  576. permissions: targetPermissionRows,
  577. filings: targetFilings.map(filing => ({
  578. id: filing.id,
  579. add_user: filing.add_user || '',
  580. })),
  581. },
  582. };
  583. } catch (err) {
  584. ctx.log(err);
  585. ctx.ajaxErrorBody(err, replaceExisting ? '覆盖授权用户至其他目录失败' : '添加授权用户至其他目录失败');
  586. }
  587. }
  588. async getFilingTypePermission(ctx) {
  589. try {
  590. if (ctx.subProject.project_id !== this.ctx.session.sessionProject.id) throw '您无权操作该数据';
  591. const filingType = await ctx.service.subProjPermission.getFilingType(ctx.subProject.id);
  592. ctx.body = { err: 0, msg: '', data: filingType };
  593. } catch(err) {
  594. ctx.log(err);
  595. ctx.ajaxErrorBody(err, '获取授权用户数据错误');
  596. }
  597. }
  598. async saveFilingTypePermission(ctx) {
  599. try {
  600. const data = JSON.parse(ctx.request.body.data);
  601. await ctx.service.subProjPermission.saveFilingType(data);
  602. ctx.body = { err: 0, msg: '', data: '' };
  603. } catch(err) {
  604. ctx.log(err);
  605. ctx.ajaxErrorBody(err, '保存授权用户信息错误');
  606. }
  607. }
  608. async addFiling(ctx) {
  609. try {
  610. this.checkUnlock(ctx);
  611. const data = JSON.parse(ctx.request.body.data);
  612. const filing = await this.getFilingFromDirectoryData(ctx, data);
  613. await this.checkFilingOperation(ctx, filing, 'can_edit_dir');
  614. const result = await ctx.service.filing.add(data);
  615. ctx.body = { err: 0, msg: '', data: result };
  616. } catch (err) {
  617. ctx.log(err);
  618. ctx.ajaxErrorBody(err, '新增分类失败');
  619. }
  620. }
  621. async delFiling(ctx) {
  622. try {
  623. this.checkUnlock(ctx);
  624. const data = JSON.parse(ctx.request.body.data);
  625. const filing = await this.getFilingFromDirectoryData(ctx, data);
  626. await this.checkFilingOperation(ctx, filing, 'can_edit_dir');
  627. const result = await ctx.service.filing.del(data);
  628. ctx.body = { err: 0, msg: '', data: result };
  629. } catch (err) {
  630. ctx.log(err);
  631. ctx.ajaxErrorBody(err, '删除分类失败');
  632. }
  633. }
  634. async saveFiling(ctx) {
  635. try {
  636. this.checkUnlock(ctx);
  637. const data = JSON.parse(ctx.request.body.data);
  638. const filing = await this.getFilingFromDirectoryData(ctx, data);
  639. await this.checkFilingOperation(ctx, filing, 'can_edit_dir');
  640. const result = await ctx.service.filing.save(data);
  641. ctx.body = { err: 0, msg: '', data: result };
  642. } catch (err) {
  643. ctx.log(err);
  644. ctx.ajaxErrorBody(err, '保存分类数据失败');
  645. }
  646. }
  647. async moveFiling(ctx) {
  648. try {
  649. this.checkUnlock(ctx);
  650. const data = JSON.parse(ctx.request.body.data);
  651. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  652. const filing = await this.getFilingFromDirectoryData(ctx, data);
  653. await this.checkFilingOperation(ctx, filing, 'can_edit_dir');
  654. const result = await ctx.service.filing.move(data);
  655. ctx.body = { err: 0, msg: '', data: result };
  656. } catch (err) {
  657. ctx.log(err);
  658. ctx.ajaxErrorBody(err, '移动分类失败');
  659. }
  660. }
  661. async loadFile(ctx) {
  662. try {
  663. const data = JSON.parse(ctx.request.body.data);
  664. const filing = await this.getProjectFiling(ctx, data.filing_id);
  665. await this.checkFilingView(ctx, filing);
  666. const order = data.order.split('|');
  667. if (order.length !== 2) throw '加载文件错误';
  668. if (order[0] !== 'filename' && order[0] !== 'create_time') throw '加载文件错误';
  669. if (order[1] !== 'asc' && order[1] !== 'desc') throw '加载文件错误';
  670. const result = await ctx.service.file.getFiles({
  671. where: { filing_id: data.filing_id, is_deleted: 0 },
  672. orders: [order],
  673. limit: data.count,
  674. offset: (data.page-1)*data.count,
  675. }, order);
  676. ctx.body = { err: 0, msg: '', data: result };
  677. } catch (err) {
  678. ctx.log(err);
  679. ctx.ajaxErrorBody(err, '加载文件失败');
  680. }
  681. }
  682. async checkCanUpload(ctx, filing) {
  683. this.checkUnlock(ctx);
  684. await this.checkFilingOperation(ctx, filing, 'can_upload');
  685. }
  686. async checkFiling(filing) {
  687. const child = await this.ctx.service.filing.getDataByCondition({ tree_pid: filing.id, is_deleted: 0 });
  688. if (child) throw '该分类下存在子分类,请在子分类下上传、导入文件';
  689. }
  690. async checkFiles(ctx) {
  691. try{
  692. const data = JSON.parse(ctx.request.body.data);
  693. if (!data.filing_id || !data.files) throw '缺少参数';
  694. const filing = await this.getProjectFiling(ctx, data.filing_id);
  695. await this.checkCanUpload(ctx, filing);
  696. const result = await ctx.service.file.checkFiles(data.filing_id, data.files);
  697. ctx.body = { err: 0, msg: '', data: result };
  698. } catch(error) {
  699. this.log(error);
  700. ctx.ajaxErrorBody(error, '检查附件错误');
  701. }
  702. }
  703. async uploadFile(ctx){
  704. let stream;
  705. try {
  706. const parts = ctx.multipart({
  707. autoFields: true,
  708. checkFile: this.getFileUploadCheck(ctx),
  709. });
  710. let index = 0;
  711. const create_time = Date.parse(new Date()) / 1000;
  712. stream = await parts();
  713. const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  714. const filing = await this.getProjectFiling(ctx, parts.field.filing_id);
  715. await this.checkCanUpload(ctx, filing);
  716. await this.checkFiling(filing);
  717. const uploadfiles = [];
  718. while (stream !== undefined) {
  719. if (!stream.filename) throw '未发现上传文件!';
  720. const fileInfo = path.parse(stream.filename);
  721. const filepath = `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
  722. // 保存文件
  723. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  724. await sendToWormhole(stream);
  725. // 插入到stage_pay对应的附件列表中
  726. uploadfiles.push({
  727. filename: fileInfo.name,
  728. fileext: fileInfo.ext,
  729. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  730. filepath,
  731. });
  732. ++index;
  733. if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
  734. stream = await parts();
  735. } else {
  736. stream = undefined;
  737. }
  738. }
  739. const result = await ctx.service.file.addFiles(filing, uploadfiles, user);
  740. ctx.body = {err: 0, msg: '', data: result };
  741. } catch (error) {
  742. ctx.helper.log(error);
  743. // 失败需要消耗掉stream 以防卡死
  744. if (stream) await sendToWormhole(stream);
  745. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  746. }
  747. }
  748. async delFile(ctx) {
  749. try{
  750. this.checkUnlock(ctx);
  751. const data = JSON.parse(ctx.request.body.data);
  752. if (!data.del) throw '缺少参数';
  753. const result = await ctx.service.file.delFiles(data.del);
  754. ctx.body = { err: 0, msg: '', data: result };
  755. } catch(error) {
  756. this.log(error);
  757. ctx.ajaxErrorBody(error, '删除附件失败');
  758. }
  759. }
  760. async saveFile(ctx) {
  761. try {
  762. this.checkUnlock(ctx);
  763. const data = JSON.parse(ctx.request.body.data);
  764. if (!data.id) throw '缺少参数';
  765. const result = await ctx.service.file.saveFile(data.id, data.filename);
  766. ctx.body = { err: 0, msg: '', data: result };
  767. } catch (error) {
  768. this.log(error);
  769. ctx.ajaxErrorBody(error, '编辑附件失败');
  770. }
  771. }
  772. async lockFile(ctx) {
  773. try {
  774. this.checkUnlock(ctx);
  775. const data = JSON.parse(ctx.request.body.data);
  776. if (!data || !data.id) throw '缺少参数';
  777. const result = await ctx.service.file.setLocked(data.id, data.is_locked);
  778. ctx.body = { err: 0, msg: '', data: result };
  779. } catch (error) {
  780. this.log(error);
  781. ctx.ajaxErrorBody(error, '修改文件锁定状态失败');
  782. }
  783. }
  784. async moveFile(ctx) {
  785. try {
  786. this.checkUnlock(ctx);
  787. const data = JSON.parse(ctx.request.body.data);
  788. if (!data.id || !data.filingId) throw '缺少参数';
  789. const targetFiling = await this.getProjectFiling(ctx, data.filingId);
  790. await this.checkFilingOperation(ctx, targetFiling, 'can_upload');
  791. const result = await ctx.service.file.moveFile(data.id, data.filingId);
  792. ctx.body = { err: 0, msg: '', data: result };
  793. } catch (error) {
  794. this.log(error);
  795. ctx.ajaxErrorBody(error, '编辑附件失败');
  796. }
  797. }
  798. async uploadBigFile(ctx) {
  799. try {
  800. const data = JSON.parse(ctx.request.body.data);
  801. if (!data.type || !data.filing_id || !data.fileInfo) throw '缺少参数';
  802. const filing = await this.getProjectFiling(ctx, data.filing_id);
  803. await this.checkCanUpload(ctx, filing);
  804. let result;
  805. const fileInfo = path.parse(data.fileInfo.filename);
  806. if (!this.isFileUploadExtensionAllowed(ctx, data.fileInfo.filename)) {
  807. throw `资料管理不支持${fileInfo.ext || '无扩展名'}格式文件`;
  808. }
  809. switch(data.type) {
  810. case 'begin':
  811. const create_time = Date.parse(new Date()) / 1000;
  812. result = {
  813. filename: `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + fileInfo.ext}`,
  814. };
  815. result.filepath = ctx.app.config.fujianOssFolder + result.filename;
  816. // todo 写入ossToken
  817. result.oss = await ctx.helper.getOssToken(ctx.app.fujianOss);
  818. break;
  819. case 'end':
  820. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  821. const uploadFiles = [{
  822. filepath: data.filepath,
  823. filename: fileInfo.name, fileext: fileInfo.ext, filesize: data.fileInfo.filesize,
  824. }];
  825. result = await ctx.service.file.addFiles(filing, uploadFiles, user);
  826. break;
  827. }
  828. ctx.body = {err: 0, msg: '', data: result };
  829. } catch (error) {
  830. ctx.log(error);
  831. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  832. }
  833. }
  834. async loadValidRelaTender(ctx) {
  835. try {
  836. const data = JSON.parse(ctx.request.body.data);
  837. if (data.type) throw '参数错误';
  838. const accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  839. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  840. ? JSON.parse(accountInfo.permission) : null;
  841. const tenders = await ctx.service.tender.getList('', userPermission, ctx.session.sessionUser.is_admin);
  842. for (const r of tenders) {
  843. r.advance = await ctx.service.advance.getAllDataByCondition({ columns: ['id', 'order', 'type'], where: { tid: r.id }});
  844. r.advance.forEach(a => {
  845. const type = advanceConst.typeCol.find(x => { return x.type === a.type });
  846. if (type) a.type_str = type.name;
  847. });
  848. r.stage = await ctx.service.stage.getAllDataByCondition({ columns: ['id', 'order'], where: { tid: r.id, status: auditConst.stage.status.checked } });
  849. r.change = await ctx.service.change.getAllDataByCondition({ columns: ['cid', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked }, orders: [['in_time', 'asc']] });
  850. r.change_apply = await ctx.service.changeApply.getAllDataByCondition({ columns: ['id', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked } });
  851. r.change_plan = await ctx.service.changePlan.getAllDataByCondition({ columns: ['id', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked } });
  852. r.change_project = await ctx.service.changeProject.getAllDataByCondition({ columns: ['id', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked } });
  853. }
  854. const category = await this.ctx.service.category.getAllCategory(ctx.subProject);
  855. ctx.body = {err: 0, msg: '', data: { category, tenders, selfCategoryLevel: this.ctx.subProject.permission.self_category_level} };
  856. } catch (error) {
  857. ctx.helper.log(error);
  858. ctx.body = this.ajaxErrorBody(error, '加载标段信息失败');
  859. }
  860. }
  861. async _loadLedgerAtt(data) {
  862. if (!data.tender_id) throw '参数错误';
  863. return await this.ctx.service.ledgerAtt.getAllDataByCondition({ where: { tid: data.tender_id }, order: [['id', 'desc']]});
  864. }
  865. async _loadStageAtt(data) {
  866. if (!data.tender_id || !data.stage || !data.sub_type) throw '参数错误';
  867. const stage = await this.ctx.service.stage.getDataById(data.stage);
  868. switch (data.sub_type) {
  869. case 'att':
  870. return await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: data.tender_id, sid: stage.order }, orders: [['id', 'desc']]});
  871. case 'dealPay':
  872. const payAtt = await this.ctx.service.payAtt.getAllDataByCondition({ where: { sid: stage.id}, orders: [['id', 'desc']] });
  873. return payAtt;
  874. case 'stageIm':
  875. const imFiles = [];
  876. const stageIm = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: stage.id} });
  877. stageIm.forEach(x => {
  878. x.attachment = x.attachment ? JSON.parse(x.attachment) : [];
  879. if (x.attachment.length > 0) imFiles.push(...x.attachment);
  880. });
  881. return imFiles;
  882. }
  883. }
  884. async _loadAdvanceAtt(data) {
  885. if (!data.stage) throw '参数错误';
  886. const self = this;
  887. const result = await this.ctx.service.advanceFile.getAllDataByCondition({ where: { vid: data.stage }, order: [['id', 'desc']]});
  888. result.forEach(x => {
  889. const info = path.parse(x.filename);
  890. x.filename = info.name;
  891. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  892. });
  893. return result;
  894. }
  895. async _loadChangeAtt(data) {
  896. if (!data.selectId) throw '参数错误';
  897. const result = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid: data.selectId }, order: [['id', 'desc']]});
  898. return result;
  899. }
  900. async _loadChangePlanAtt(data) {
  901. if (!data.selectId) throw '参数错误';
  902. const self = this;
  903. const result = await this.ctx.service.changePlanAtt.getAllDataByCondition({ where: { cpid: data.selectId }, order: [['id', 'desc']]});
  904. result.forEach(x => {
  905. const info = path.parse(x.filename);
  906. x.filename = info.name;
  907. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  908. });
  909. return result;
  910. }
  911. async _loadChangeProjectAtt(data) {
  912. if (!data.selectId) throw '参数错误';
  913. const self = this;
  914. const result = await this.ctx.service.changeProjectAtt.getAllDataByCondition({ where: { cpid: data.selectId }, order: [['id', 'desc']]});
  915. result.forEach(x => {
  916. const info = path.parse(x.filename);
  917. x.filename = info.name;
  918. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  919. });
  920. return result;
  921. }
  922. async _loadChangeApplyAtt(data) {
  923. if (!data.selectId) throw '参数错误';
  924. const self = this;
  925. const result = await this.ctx.service.changeApplyAtt.getAllDataByCondition({ where: { caid: data.selectId }, order: [['id', 'desc']]});
  926. result.forEach(x => {
  927. const info = path.parse(x.filename);
  928. x.filename = info.name;
  929. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  930. });
  931. return result;
  932. }
  933. async loadRelaFiles(ctx) {
  934. try {
  935. const data = JSON.parse(ctx.request.body.data);
  936. if (!data.type) throw '参数错误';
  937. let files;
  938. switch(data.type) {
  939. case 'ledger':
  940. files = await this._loadLedgerAtt(data);
  941. break;
  942. case 'stage':
  943. files = await this._loadStageAtt(data);
  944. break;
  945. case 'advance':
  946. files = await this._loadAdvanceAtt(data);
  947. break;
  948. case 'change':
  949. files = await this._loadChangeAtt(data);
  950. break;
  951. case 'change_plan':
  952. files = await this._loadChangePlanAtt(data);
  953. break;
  954. case 'change_project':
  955. files = await this._loadChangeProjectAtt(data);
  956. break;
  957. case 'change_apply':
  958. files = await this._loadChangeApplyAtt(data);
  959. break;
  960. default: throw '未知文件类型';
  961. }
  962. ctx.body = {err: 0, msg: '', data: files };
  963. } catch (error) {
  964. ctx.helper.log(error);
  965. ctx.body = this.ajaxErrorBody(error, '加载附件失败,请重试');
  966. }
  967. }
  968. async relaFile(ctx) {
  969. try {
  970. const data = JSON.parse(ctx.request.body.data);
  971. if (!data.filing_id || !data.files) throw '缺少参数';
  972. const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  973. const filing = await this.getProjectFiling(ctx, data.filing_id);
  974. await this.checkCanUpload(ctx, filing);
  975. await this.checkFiling(filing);
  976. const result = await ctx.service.file.relaFiles(filing, data.files, user);
  977. ctx.body = {err: 0, msg: '', data: result };
  978. } catch (error) {
  979. ctx.helper.log(error);
  980. ctx.body = this.ajaxErrorBody(error, '导入附件失败,请重试');
  981. }
  982. }
  983. async template(ctx) {
  984. const defaultTemplate = await ctx.service.filingTemplateList.getOriginTemplate();
  985. ctx.redirect('/file/template/' + defaultTemplate.id);
  986. }
  987. async templateDetail(ctx) {
  988. try {
  989. const renderData = {
  990. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.template),
  991. };
  992. renderData.templateList = await ctx.service.filingTemplateList.getAllTemplate(ctx.session.sessionProject.id);
  993. renderData.shareTemplate = await ctx.service.filingTemplateList.getShareTemplate(ctx.session.sessionProject.id);
  994. renderData.FtType = ctx.service.filingTemplateList.FtType;
  995. renderData.template = renderData.templateList.find(x => { return x.id === ctx.params.id });
  996. if (!renderData.template) throw '查看的资料模板不存在';
  997. renderData.templateData = await ctx.service.filingTemplate.getData(renderData.template.id);
  998. await this.layout('file/template.ejs', renderData, 'file/template_modal.ejs');
  999. } catch (err) {
  1000. ctx.log(err);
  1001. ctx.session.postError = err.toString();
  1002. ctx.redirect(this.menu.menu.dashboard.url);
  1003. }
  1004. }
  1005. async saveTemplate(ctx) {
  1006. try {
  1007. const id = ctx.query.id;
  1008. const name = ctx.request.body.name;
  1009. const is_share = ctx.request.body.is_share ? parseInt(ctx.request.body.is_share) : undefined;
  1010. const share_id = ctx.request.body.share_id;
  1011. const [save, templateId] = share_id ? await ctx.service.filingTemplateList.copy(share_id) : await ctx.service.filingTemplateList.save(name, is_share, id);
  1012. if (!save) throw '保存数据失败';
  1013. ctx.redirect('/file/template/' + templateId);
  1014. } catch(err) {
  1015. ctx.log(err);
  1016. ctx.session.postError = err.toString();
  1017. ctx.redirect('/file/template');
  1018. }
  1019. }
  1020. async resetTemplate(ctx) {
  1021. try {
  1022. const id = ctx.query.id;
  1023. await ctx.service.filingTemplateList.reset(id);
  1024. ctx.redirect('/file/template/' + id);
  1025. } catch (err) {
  1026. ctx.log(err);
  1027. ctx.postError(err, '重置模板失败');
  1028. ctx.redirect('/file/template');
  1029. }
  1030. }
  1031. async delTemplate(ctx) {
  1032. try {
  1033. const id = ctx.query.id;
  1034. await ctx.service.filingTemplateList.delete(id);
  1035. if (ctx.request.headers.referer.indexOf(id) > 0) {
  1036. ctx.redirect('/file/template');
  1037. } else {
  1038. ctx.redirect(ctx.request.headers.referer);
  1039. }
  1040. } catch (err) {
  1041. ctx.log(err);
  1042. ctx.postError(err, '删除模板失败');
  1043. ctx.redirect('/file/template');
  1044. }
  1045. }
  1046. async updateTemplate(ctx) {
  1047. try {
  1048. const data = JSON.parse(ctx.request.body.data);
  1049. if (!data.updateType) throw '数据错误';
  1050. let result;
  1051. if (data.updateType === 'add') {
  1052. result = await ctx.service.filingTemplate.add(ctx.params.id, data);
  1053. } else if (data.updateType === 'del') {
  1054. result = await ctx.service.filingTemplate.del(ctx.params.id, data);
  1055. } else if (data.updateType === 'save') {
  1056. result = await ctx.service.filingTemplate.save(data);
  1057. } else if (data.updateType === 'move') {
  1058. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  1059. result = await ctx.service.filingTemplate.move(ctx.params.id, data);
  1060. } else if (data.updateType === 'import') {
  1061. result = await ctx.service.filingTemplate.import(ctx.params.id, data.data);
  1062. } else if (data.updateType === 'multi' ) {
  1063. result = await ctx.service.filingTemplate.multiUpdate(ctx.params.id, data.data);
  1064. }
  1065. ctx.body = { err: 0, msg: '', data: result };
  1066. } catch (err) {
  1067. ctx.log(err);
  1068. ctx.ajaxErrorBody(err, '修改失败');
  1069. }
  1070. }
  1071. async search(ctx) {
  1072. try {
  1073. const limit = 1000;
  1074. const data = JSON.parse(ctx.request.body.data);
  1075. if (!data.keyword) throw '数据错误';
  1076. if (data.filing_id instanceof Array) {
  1077. const filingIds = this.app._.uniq(data.filing_id.map(id => String(id || '')).filter(Boolean));
  1078. if (filingIds.length === 0) throw '数据错误';
  1079. const filings = await ctx.service.filing.getAllDataByCondition({
  1080. where: { id: filingIds, spid: ctx.subProject.id, is_deleted: 0 },
  1081. });
  1082. const permissionMap = await ctx.service.subProjectFilingPermission.getPermissionMap(
  1083. ctx.subProject.id,
  1084. ctx.session.sessionUser.accountId,
  1085. filings,
  1086. ctx.subProject.permission.filing_type,
  1087. ctx.subProject.permission.file_permission,
  1088. this.isAdmin(ctx)
  1089. );
  1090. this.applyFileConfigViewPermission(ctx, permissionMap);
  1091. const validFilingIds = filings.filter(filing => {
  1092. return permissionMap[filing.id] && permissionMap[filing.id].can_view;
  1093. }).map(filing => filing.id);
  1094. const result = await ctx.service.file.searchByFilingIds(validFilingIds, data.keyword, limit);
  1095. ctx.body = { err: 0, msg: '', data: { list: result, limit } };
  1096. return;
  1097. }
  1098. if (!data.filing_type) throw '数据错误';
  1099. const validFilingType = [];
  1100. for (const f of data.filing_type) {
  1101. const filingType = Number(f);
  1102. if (!Number.isInteger(filingType) || filingType <= 0) continue;
  1103. if (ctx.subProject.permission.filing_type === 'all' ||
  1104. ctx.subProject.permission.filing_type.indexOf(filingType) >= 0) validFilingType.push(filingType);
  1105. }
  1106. const result = await ctx.service.file.search(validFilingType, data.keyword, limit);
  1107. ctx.body = { err: 0, msg: '', data: { list: result, limit } };
  1108. } catch(err) {
  1109. ctx.log(err);
  1110. ctx.ajaxErrorBody(err, '搜索文件失败');
  1111. }
  1112. }
  1113. async manage(ctx) {
  1114. try {
  1115. const renderData = {
  1116. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.manage),
  1117. };
  1118. renderData.filingData = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type);
  1119. const permissionData = await ctx.service.subProjPermission.getFilingType(ctx.subProject.id);
  1120. permissionData.forEach(x => { x.filing_type = x.filing_type.split(','); });
  1121. renderData.filingData.forEach(x => {
  1122. if (!x.is_fixed) {
  1123. x.permission_count = 0;
  1124. } else {
  1125. const rela = permissionData.filter(y => { return y.filing_type.indexOf(x.filing_type + '') >= 0; });
  1126. x.permission_count = rela.length;
  1127. }
  1128. });
  1129. await this.layout('file/manage.ejs', renderData, 'file/manage_modal.ejs');
  1130. } catch (err) {
  1131. ctx.log(err);
  1132. ctx.session.postError = err.toString();
  1133. ctx.redirect(this.menu.menu.dashboard.url);
  1134. }
  1135. }
  1136. async lockFiling(ctx) {
  1137. try {
  1138. await ctx.service.subProject.save({ id: ctx.subProject.id, lock_file: ctx.query.lock });
  1139. ctx.redirect(`/sp/${ctx.subProject.id}/fm`);
  1140. } catch(err) {
  1141. ctx.log(err);
  1142. ctx.postError(err, '资料归集分类锁定错误');
  1143. ctx.redirect(`/sp/${ctx.subProject.id}/fm`);
  1144. }
  1145. }
  1146. async manageUpdate(ctx) {
  1147. try {
  1148. this.checkLock(ctx);
  1149. const data = JSON.parse(ctx.request.body.data);
  1150. const result = await this.updateFiling(ctx, data);
  1151. ctx.body = { err: 0, msg: '', data: result };
  1152. } catch (err) {
  1153. ctx.log(err);
  1154. ctx.ajaxErrorBody(err, '修改失败');
  1155. }
  1156. }
  1157. async updateFiling(ctx, data) {
  1158. if (!data.updateType) throw '数据错误';
  1159. const updateData = JSON.parse(JSON.stringify(data));
  1160. delete updateData.updateType;
  1161. if (data.updateType === 'add') {
  1162. return await ctx.service.filing.add(updateData);
  1163. } else if (data.updateType === 'del') {
  1164. return await ctx.service.filing.del(updateData);
  1165. } else if (data.updateType === 'save') {
  1166. return await ctx.service.filing.save(updateData);
  1167. } else if (data.updateType === 'edit') {
  1168. return await ctx.service.filing.editDirectory(updateData);
  1169. } else if (data.updateType === 'move') {
  1170. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  1171. return await ctx.service.filing.move(updateData);
  1172. } else if (data.updateType === 'multi') {
  1173. return await ctx.service.filing.multiUpdate(ctx.subProject.id, data.data);
  1174. }
  1175. throw '未知的修改类型';
  1176. }
  1177. }
  1178. return FileController;
  1179. };